问:
Pure CSS Collapse Accordion
I have a CSS collapse accordion with just pure CSS, it is working perfect.

I have just 1 issue:
right now if the user click in any label: Label One, Label Two, Label Three, he can't close it clicking in Label  again, each label can just close if the user clicks in the next one

I would like make it possible,

example: the user click in Label One to open, if him click again this label will close and the same will all for all labels.

js fiddle: https://jsfiddle.net/11wunqqz/4/

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.blue .tab-content {
  background: #3498db;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked ~ .tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox] + label::after {
  content: "+";
}

input[type=radio] + label::after {
  content: "\25BC";
}

input[type=checkbox]:checked + label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked + label::after {
  transform: rotateX(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="wrapper">
  <div class="tab blue">
    <input id="tab-four" type="radio" name="tabs2">
    <label for="tab-four">Label One</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-five" type="radio" name="tabs2">
    <label for="tab-five">Label Two</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-six" type="radio" name="tabs2">
    <label for="tab-six">Label Three</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
</div></code>```

答:
if you want to use Jquery this code may help you

this is html

```<code><div class="accordion">
    <div class="group">
        <a href="#" class="title">title 1</a>
        <div class="content">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
    <div class="group">
        <a href="#" class="title">title 2</a>
        <div class="content">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
    <div class="group">
        <a href="#" class="title">title 3</a>
        <div class="content">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
</div>
</code>```

this is css

```<code>.title{
            text-decoration: none;
            font-size: 17px;
            display: block;
            padding: 10px;
            background: #ccc;
            color: #fff;
            border-bottom:1px solid #fff;
        }
        .group .content{
            display: none;
            padding: 10px;
            background: #43ad43;
            color: #fff;
        }
        .open .title{
            background: green !important;
            border-bottom:none;
        }
        .open .content{
            display: block;
        }
</code>```

and this is jquery

```<code>$(document).ready(function () {
        $('.title').on('click',function (e) {
            e.preventDefault();
            var parent=$(this).parent();

            if (parent.hasClass('open')) {
               parent.removeClass('open')
            }
            else{
                $(".group").removeClass("open");
                parent.addClass("open");
            }

        })
    });
</code>```

Title: Pure CSS Collapse Accordion

Body:
I have a CSS collapse accordion with just pure CSS, it is working perfect.

I have just 1 issue:
right now if the user click in any label: Label One, Label Two, Label Three, he can't close it clicking in Label  again, each label can just close if the user clicks in the next one

I would like make it possible,

example: the user click in Label One to open, if him click again this label will close and the same will all for all labels.

js fiddle: https://jsfiddle.net/11wunqqz/4/

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.blue .tab-content {
  background: #3498db;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked ~ .tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox] + label::after {
  content: "+";
}

input[type=radio] + label::after {
  content: "\25BC";
}

input[type=checkbox]:checked + label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked + label::after {
  transform: rotateX(180deg);
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <input id="tab-four" type="radio" name="tabs2">
    Label One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

    <input id="tab-five" type="radio" name="tabs2">
    Label Two

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

    <input id="tab-six" type="radio" name="tabs2">
    Label Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

Body:
if you want to use Jquery this code may help you

this is html

<div class="accordion">
    <div class="group">
        <a href="#" class="title">title 1</a>
        <div class="content">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
    <div class="group">
        <a href="#" class="title">title 2</a>
        <div class="content">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
    <div class="group">
        <a href="#" class="title">title 3</a>
        <div class="content">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
</div>

this is css

.title{
            text-decoration: none;
            font-size: 17px;
            display: block;
            padding: 10px;
            background: #ccc;
            color: #fff;
            border-bottom:1px solid #fff;
        }
        .group .content{
            display: none;
            padding: 10px;
            background: #43ad43;
            color: #fff;
        }
        .open .title{
            background: green !important;
            border-bottom:none;
        }
        .open .content{
            display: block;
        }

and this is jquery

$(document).ready(function () {
        $('.title').on('click',function (e) {
            e.preventDefault();
            var parent=$(this).parent();

            if (parent.hasClass('open')) {
               parent.removeClass('open')
            }
            else{
                $(".group").removeClass("open");
                parent.addClass("open");
            }

        })
    });


来源: stackexchange

问:
join contains a syntaxis error
I want to get the services that are filled and all the other services that are empty, but on excecute I get an message saying that

join contains a syntaxis error

```<code>SELECT OverzichtID, ServiceID, Service.Beschrijving, [Service Aantal]
FROM Service.Overzicht
LEFT JOIN Service
ON Service_Overzicht.ServiceID = Service.ServiceID
</code>```

答: First, I think your table name in the FROM clause is wrong - it probably should be Service_Overzicht and not Service.Overzicht. Second, Access really likes parentheses - try ON (Service_Overzicht.ServiceID = Service.ServiceID) – Zohar Peled 6 mins ago

ContentLicense: CC BY-SA 3.0

Title: join contains a syntaxis error

Body:
I want to get the services that are filled and all the other services that are empty, but on excecute I get an message saying that

join contains a syntaxis error

SELECT OverzichtID, ServiceID, Service.Beschrijving, [Service Aantal]
FROM Service.Overzicht
LEFT JOIN Service
ON Service_Overzicht.ServiceID = Service.ServiceID


问:
Change UITextField width dynamically depends of content
I have the same issue as here: Resize a UITextField while typing (by using Autolayout)

But It was resolved with UITextView and not with UITextField.

This code doesn't help:

```<code>func textFieldDidChange(sender: UITextField) {
    sender.invalidateIntrinsicContentSize()
}
</code>```

I have UITextField(red background) and use AutoLayout with StackView:

and constraints:

but UITextField change it width only when it is resignFirstResponder.
Could you give me please any advice about the issue?
I'm new in Swift and iOS Development.

答:
This works for UITextField.
In my case I wanted the font to be of the same size. I set textField width constraint to >= 10 and it just works fine on iOS 9, 10, 11.

For iOS 11 this even works while editing text.

To make this work while editing text on iOS 9 and 10, I handled one more method by registering for a textDidChange event.

```<code>//Swift 3 Sample

//In viewDidLoad
adjustableTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

 @objc func textFieldDidChange(_ textField: UITextField) {
    adjustableTextField.resignFirstResponder()
    adjustableTextField.becomeFirstResponder()
}
</code>```

Body:
I have the same issue as here: Resize a UITextField while typing (by using Autolayout)

But It was resolved with UITextView and not with UITextField.

This code doesn't help:

func textFieldDidChange(sender: UITextField) {
    sender.invalidateIntrinsicContentSize()
}

I have UITextField(red background) and use AutoLayout with StackView:

and constraints:

but UITextField change it width only when it is resignFirstResponder.
Could you give me please any advice about the issue?
I'm new in Swift and iOS Development.

Body:
This works for UITextField.
In my case I wanted the font to be of the same size. I set textField width constraint to >= 10 and it just works fine on iOS 9, 10, 11.

For iOS 11 this even works while editing text.

To make this work while editing text on iOS 9 and 10, I handled one more method by registering for a textDidChange event.

//Swift 3 Sample

//In viewDidLoad
adjustableTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

 @objc func textFieldDidChange(_ textField: UITextField) {
    adjustableTextField.resignFirstResponder()
    adjustableTextField.becomeFirstResponder()
}


问:
parsing commands into tree python : multiple key dictionary?
I have a list of commands looking like this :

set_string equipment_type 3 Pump

All commands almost follow this template:

cmd_type propertyname equipment_id value

What I am trying to do is to go through a txt document full of this kind of commands and store all possible combinations of command statements. I am only interested in cmd, type, dimension of equipment_id and property name.

What I already did was using a dictionary with tuples (cmd,type,dimension) as keys and a set of property names as a value.

But I would like to add a notion of priority into this data structure : cmd then type then dimension. Is there a tree-like data structure in python that can permit me to store this kind of data? First layer would be : cmd, Second layer : type, Third layer would be : dimension and the leaves are the set of property names that can be used following the corresponding path in the tree.

Thank you for your help!

答:
You could use nested dicts, nested defaultdicts or a Trie.

With standard dicts, you'd use setdefault:

```<code>tree = {}
tree.setdefault(cmd, {}).setdefault(cmd_type, {}).setdefault(dimension, []).append(prop)
</code>```

It would give you a dict of dicts of dicts of lists.
If you want sets at the leaves, you could use:

```<code>tree.setdefault(cmd, {}).setdefault(cmd_type, {}).setdefault(dimension, set()).add(prop)
</code>```

As an example:

```<code>data = [
  ('cmd1', 'typeA', 3, 'propertyX'),
  ('cmd1', 'typeA', 3, 'propertyZ'),
  ('cmd1', 'typeB', 2, 'propertyY'),
  ('cmd2', 'typeA', 3, 'propertyX'),
  ('cmd2', 'typeB', 1, 'propertyZ'),
  ('cmd2', 'typeA', 1, 'propertyX'),
  ('cmd1', 'typeB', 2, 'propertyZ')
]

tree = {}
for cmd, cmd_type, dimension, prop in data:
    tree.setdefault(cmd, {}).setdefault(cmd_type, {}).setdefault(dimension, []).append(prop)

from pprint import pprint
pprint(tree)
</code>```

It outputs:

```<code>{'cmd1': {'typeA': {3: ['propertyX', 'propertyZ']},
          'typeB': {2: ['propertyY', 'propertyZ']}},
 'cmd2': {'typeA': {1: ['propertyX'], 3: ['propertyX']},
          'typeB': {1: ['propertyZ']}}}
</code>```

With defaultdicts, your code would look like:

```<code>tree = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
for cmd, cmd_type, dimension, prop in data:
    tree[cmd][cmd_type][dimension].append(prop)
</code>```

Body:
You could use nested dicts, nested defaultdicts or a Trie.

With standard dicts, you'd use setdefault:

tree = {}
tree.setdefault(cmd, {}).setdefault(cmd_type, {}).setdefault(dimension, []).append(prop)

It would give you a dict of dicts of dicts of lists.
If you want sets at the leaves, you could use:

tree.setdefault(cmd, {}).setdefault(cmd_type, {}).setdefault(dimension, set()).add(prop)

As an example:

data = [
  ('cmd1', 'typeA', 3, 'propertyX'),
  ('cmd1', 'typeA', 3, 'propertyZ'),
  ('cmd1', 'typeB', 2, 'propertyY'),
  ('cmd2', 'typeA', 3, 'propertyX'),
  ('cmd2', 'typeB', 1, 'propertyZ'),
  ('cmd2', 'typeA', 1, 'propertyX'),
  ('cmd1', 'typeB', 2, 'propertyZ')
]

tree = {}
for cmd, cmd_type, dimension, prop in data:
    tree.setdefault(cmd, {}).setdefault(cmd_type, {}).setdefault(dimension, []).append(prop)

from pprint import pprint
pprint(tree)

It outputs:

{'cmd1': {'typeA': {3: ['propertyX', 'propertyZ']},
          'typeB': {2: ['propertyY', 'propertyZ']}},
 'cmd2': {'typeA': {1: ['propertyX'], 3: ['propertyX']},
          'typeB': {1: ['propertyZ']}}}

With defaultdicts, your code would look like:

tree = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
for cmd, cmd_type, dimension, prop in data:
    tree[cmd][cmd_type][dimension].append(prop)


问:
How can I extract certain strings with Xpath
```<code><span>1 Bedroom, 1 Bath</span>
</code>```

Hi
I am new in Xpath. And my English is not very well, but I'll try. I need to extract with Xpath only '1 Bedroom' and '1 Bath'. How can I do this?
Thank you a lot

答:
You can use substring-after() and substring-before():

```<code>substring-before(span, ',')

substring-after(span, ', ')
</code>```

Body:
1 Bedroom, 1 Bath

Hi
I am new in Xpath. And my English is not very well, but I'll try. I need to extract with Xpath only '1 Bedroom' and '1 Bath'. How can I do this?
Thank you a lot

Body:
You can use substring-after() and substring-before():

substring-before(span, ',')

substring-after(span, ', ')


问:
How to remove characters in String Swift 3?
Code to get the string before a certain character:

```<code>let string = "Hello World"
if let range = string.range(of: "World") {
    let firstPart = string[string.startIndex..<range.lowerBound]
    print(firstPart) // print Hello
}
</code>```

To begin with, I have a program that converts Hex float to a Binary float and I want to remove all "0" from Binary string answer until first "1". Example:

Any ideas?

答:
You can use Regular Expression:

```<code>var str = "001110111001"
str = str.replacingOccurrences(of: "0", with: "", options: [.anchored], range: nil)
</code>```

The anchored option means search for 0s at the start of the string only.

Body:
Code to get the string before a certain character:

let string = "Hello World"
if let range = string.range(of: "World") {
    let firstPart = string[string.startIndex..<range.lowerBound]
    print(firstPart) // print Hello
}

To begin with, I have a program that converts Hex float to a Binary float and I want to remove all "0" from Binary string answer until first "1". Example:

Any ideas?

Body:
You can use Regular Expression:

var str = "001110111001"
str = str.replacingOccurrences(of: "0", with: "", options: [.anchored], range: nil)

The anchored option means search for 0s at the start of the string only.


问:
How to create a non-persistent Field in an JPA Entity?
I have an Entity called Users that have login, name and department as fields that are stored in Users table.

My Spring-Boot configuration defines the departments that gives the system manager role for users in this application.

The key problem is that I want the login end-point to return the User data with the additional information that he/she is or is not a system manager.

I think that this information should be in the User class, but I do not want this information to be stored in the database along with other fields as the management departments may change or the user my change from one department to another that does not manage the system.

(Edit) I will define this IsManager field when user request login(): I will get user's department field and check against managerDepartment's list to set it to true ou false.

So the question is if it is right to put that information in a non-persistent field in the entity class (and how to do that) or if I may change the ResponseEntity in the rest method to add the additional information (and how) ?

答:
Short answer is to use @Transient annotation.
Correct answer is to separate UserEntity and UserDto to two different classes and use MapStruct for example for transformation.


问:
Creating objects during runtime in Python
I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person()

What I have trouble understanding now is how I would design a model that creates a new object during runtime? I'm aware that my phrasing is probably faulty since all objects are generated during runtime but what I mean is that if I were to start my application in a terminal or UI how would I create new objects and manage them. I can't really define new variable names on the fly right?

An example application where I run into this design issue would be a database storing people. The user gets a terminal menu which allows him to create a new user and assign a name, salary, position. How would you instantiate that object and later call it if you want to manage it, call functions, etc.? What's the design pattern here?

Please excuse my poor understanding of the OPP model. I'm currently reading up on classes and OOP but I feel like I need to understand what my error is here before moving on. Please let me know if there is anything I should clarify.

答:
For your example, you want to use a model abstraction.

If Person is a model class, you could simply do:

```<code>person = new Person()
person.name = "Bob"
person.email = "bob@aol.com"
person.save()  # this line will write to the persistent datastore (database, flat files, etc)
</code>```

and then in another session, you could:

```<code>person = Person.get_by_email("bob@aol.com") # assuming you had a classmethod called 'get_by_email'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For your example, you want to use a model abstraction.

If Person is a model class, you could simply do:

person = new Person()
person.name = "Bob"
person.email = "bob@aol.com"
person.save()  # this line will write to the persistent datastore (database, flat files, etc)

and then in another session, you could:

person = Person.get_by_email("bob@aol.com") # assuming you had a classmethod called 'get_by_email'


问:
MySQL DB, send a multiple data through Python-PHP to the server
I have a Virtual Machine/Web Server with MySQL up and running, and want to receive the data from client hardware that is saved in a .csv file, how can i do a python script to send it? i was recommended requests library from Python to send it and receive it through PHP POST. Problem is ive NEVER used PHP and HTML and so im a bit stuck with the interaction between the 2. Thanks a lot!

sample code is:

```<code>import csv
import requests

session = requests.Session()
with open('r01a2.csv','rb') as f:
    reader = csv.reader(f)
    for row in reader:
        r = session.post('MyURL', data = {'date: row[0],'value': row[1]})
        print r.text
</code>```

Code on Server side is:

```<code>    <?php
$formato = "INSERT INTO `datos_pruebas`.`Datos_Edison` (`id`, `date`, `pulse`) VALUES (NULL, '%s', '%f')";
$sql=sprintf($formato,$date,$pulse);
$enlace = mysql_connect('localhost','root','clinichub');
$resultado = mysql_query($sql,$enlace);
$id=NULL;
if(!empty($_POST))
{
        echo htmlspecialchars($_POST["date"]);
} else {
echo "gg";
}
</code>```

EDIT2: It finally worked after solutions gave by community and feedback, thanks a lot for your recommendations!

答: Make sure the post in python uses the correct content-type and verify on the serverside php if $_FILES has an entry.  (i.e. print_r($_FILES) ) should return your file, you won't find it in $_POST.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a Virtual Machine/Web Server with MySQL up and running, and want to receive the data from client hardware that is saved in a .csv file, how can i do a python script to send it? i was recommended requests library from Python to send it and receive it through PHP POST. Problem is ive NEVER used PHP and HTML and so im a bit stuck with the interaction between the 2. Thanks a lot!

sample code is:

import csv
import requests

session = requests.Session()
with open('r01a2.csv','rb') as f:
    reader = csv.reader(f)
    for row in reader:
        r = session.post('MyURL', data = {'date: row[0],'value': row[1]})
        print r.text

Code on Server side is:

    <?php
$formato = "INSERT INTO `datos_pruebas`.`Datos_Edison` (`id`, `date`, `pulse`) VALUES (NULL, '%s', '%f')";
$sql=sprintf($formato,$date,$pulse);
$enlace = mysql_connect('localhost','root','clinichub');
$resultado = mysql_query($sql,$enlace);
$id=NULL;
if(!empty($_POST))
{
        echo htmlspecialchars($_POST["date"]);
} else {
echo "gg";
}

EDIT2: It finally worked after solutions gave by community and feedback, thanks a lot for your recommendations!


问:
Equivalent function to stringr::word in stringi package
I went through the stringi package manual to find an equivalent to the function word() in the package stringr, but I could not find it. The reason I am looking for it is because I want to set collation options for my locale  and stringr doesn't give me all the options that stringi does. Is there a function in the stringi package that does the same as the word() function in the stringr package? See the example below, where I want the next three words after the word "José", that is written in different ways. In the stringi package, the function stri_opts_collatorallows to set the argument strength=1 for a permissive collation strength, so all forms of "José" would have been taken into consideration.

```<code>sentencas<-c("josé é um trabalhador responsável","José é um trabalhador
responsável","jose é um trabalhador responsável","Jose é um trabalhador
responsável")

sentencas %>% word(2,sep=coll("jose ",ignore_case=T)) %>% word(1,3)
</code>```

With stringi, I can extract all forms of "José":

```<code>stri_extract_first_coll(sentencas,"jose",strength=1).
</code>```

I would like to do something like this:

```<code>sentencas %>% word(2,sep=coll("jose ",strength=1)) %>% word(1,3)
</code>```

答:
Not exactly the same as stringr::word(), but this would seem to do the trick:

```<code>sentencas %>%
  stri_split_coll("jose ", strength=1, simplify = TRUE) %>%
  .[,2] %>%
  word(1,3)
</code>```

Body:
I went through the stringi package manual to find an equivalent to the function word() in the package stringr, but I could not find it. The reason I am looking for it is because I want to set collation options for my locale  and stringr doesn't give me all the options that stringi does. Is there a function in the stringi package that does the same as the word() function in the stringr package? See the example below, where I want the next three words after the word "José", that is written in different ways. In the stringi package, the function stri_opts_collatorallows to set the argument strength=1 for a permissive collation strength, so all forms of "José" would have been taken into consideration.

sentencas<-c("josé é um trabalhador responsável","José é um trabalhador
responsável","jose é um trabalhador responsável","Jose é um trabalhador
responsável")

sentencas %>% word(2,sep=coll("jose ",ignore_case=T)) %>% word(1,3)

With stringi, I can extract all forms of "José":

stri_extract_first_coll(sentencas,"jose",strength=1).

I would like to do something like this:

sentencas %>% word(2,sep=coll("jose ",strength=1)) %>% word(1,3)

Body:
Not exactly the same as stringr::word(), but this would seem to do the trick:

sentencas %>%
  stri_split_coll("jose ", strength=1, simplify = TRUE) %>%
  .[,2] %>%
  word(1,3)


问:
Python: List merging method
I have a question:

I have 2 lists:

```<code>list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
</code>```

And I want to merge them in order to have the following result:

```<code>mergedlist = [1, 4, 2, 5, 3, 6]
</code>```

How can I do that?

答:
You can use chain from iter tools:

```<code>list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

from itertools import chain

res = list(chain.from_iterable((list_1[x], list_2[x]) for x in range(len(list_1))))
</code>```

=> [1, 4, 2, 5, 3, 6]

Title: Python: List merging method

Body:
I have a question:

I have 2 lists:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

And I want to merge them in order to have the following result:

mergedlist = [1, 4, 2, 5, 3, 6]

How can I do that?

Body:
You can use chain from iter tools:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

from itertools import chain

res = list(chain.from_iterable((list_1[x], list_2[x]) for x in range(len(list_1))))

=> [1, 4, 2, 5, 3, 6]


问:
How to conditionally add attributes to react DOM element
I have a scenario where I'm using React.js to create a div using the following code :

```<code>React.createElement('div', {}, "div content")
</code>```

Some additional javascript processing will allow me afterwards to deduce if this div needs to have the className attribute set to" ClassA" or "ClassB" or if it shouldn't have className at all.

Is there a way in javascript to access the div that was created from the React DOM and to add to it the className attribute?

Note : I couldn't achieve this is JSX so I resorted to the createElement method.

Edit: it is worth to mention that i might need to conditionally add attributes other than className. For example, I might need to add to an anchor tag an "alt" attribute or not based on conditional logic.
Thank you in advance.

答:
You can use ES6 syntax to achieve the desired functionality</p>

```<code>const yourComponentProps = {
  [ifThisIsTrue ? 'useThisName' : 'useAnotherName']: 'yourDesiredValue',
};

return <YourComponent {...yourComponentProps} />
</code>```

Body:
I have a scenario where I'm using React.js to create a div using the following code :

React.createElement('div', {}, "div content")

Some additional javascript processing will allow me afterwards to deduce if this div needs to have the className attribute set to" ClassA" or "ClassB" or if it shouldn't have className at all.

Is there a way in javascript to access the div that was created from the React DOM and to add to it the className attribute?

Note : I couldn't achieve this is JSX so I resorted to the createElement method.

Edit: it is worth to mention that i might need to conditionally add attributes other than className. For example, I might need to add to an anchor tag an "alt" attribute or not based on conditional logic.
Thank you in advance.

Body:
You can use ES6 syntax to achieve the desired functionality

const yourComponentProps = {
  [ifThisIsTrue ? 'useThisName' : 'useAnotherName']: 'yourDesiredValue',
};

return <YourComponent {...yourComponentProps} />


问:
serial port communication accumulate big number of running threads
We have the follow C# code for our serial port communication:

```<code>               ProcCntrlSSPort = new SerialPort(portNumber, 115200, Parity.None, 8, StopBits.One);

                ProcCntrlSSPort.Handshake = Handshake.None;
                ProcCntrlSSPort.ReadTimeout = 10;
                ProcCntrlSSPort.ReadBufferSize = 32768;
                ProcCntrlSSPort.DataReceived += ProcCntrlSSPortDataReceived;
                //ProcCntrlSSPort.DataReceived += new SerialDataReceivedEventHandler(ProcCntrlSSPortDataReceived);
                ProcCntrlSSPort.ReceivedBytesThreshold = 1;
                try
                {
                    ProcCntrlSSPort.Open();
                    ProcCntrlSSPort.DiscardInBuffer();
                }
</code>```

Every 100 msec, there is a status message received by our application. I understand when the SerialPort received ReceivedBytesThreshold number of bytes, an event will be fired by the SerialPort. We have to use 1 for the ReceivedBytesThreshold because one of our important data is sent 1 byte each time whenever that byte is available.

When an event is fired by SerialPort and is processed by the receiver, that event should be disposed and the thread associated that event should be available for next use. so there should not be a big number of running thread accumulation.

But I found the running threads will continuously increase from 20 threads up to more than 400 threads after overnight. Just status message is sent to our application, no other activities then. I have disabled all process code so I am sure the accumulated threads are NOT from our code. That means we do nothing on the received data for the testing purpose.

I have increased the ReceivedBytesThreshold, saying 128, for testing purpose. It will slow down the accumulation but the thread count still goes up slowly. why .net framework cannot handle their threads properly? Or I didn't use it correctly?

答:
How does SerialPort handle DataReceived explains what might be happening.

Looks like the DataReceived calls will use the ThreadPool and calls to QueueUserWorkItem.  This means that if you dont process the data fast enough, the calls could be queuing up like you are seeing.

If you wish to keep the count down (as a test), you could try and read out all the bytes once you receive the event using BytesToRead and then 'process' each character read.  Another option that is suggested in the post is to create a "processing" thread of your own to do the processing when you receive the data.

It also looks like you can set the maximum number of threads created in the ThreadPool using ThreadPool.SetMaxThreads

Sets the number of requests to the thread pool that can be active concurrently. All requests above that number remain queued until thread pool threads become available.

But this all this would do is change where the queuing is taking place.  Ultimately you have to fix why its getting behind.

Body:
We have the follow C# code for our serial port communication:

               ProcCntrlSSPort = new SerialPort(portNumber, 115200, Parity.None, 8, StopBits.One);

                ProcCntrlSSPort.Handshake = Handshake.None;
                ProcCntrlSSPort.ReadTimeout = 10;
                ProcCntrlSSPort.ReadBufferSize = 32768;
                ProcCntrlSSPort.DataReceived += ProcCntrlSSPortDataReceived;
                //ProcCntrlSSPort.DataReceived += new SerialDataReceivedEventHandler(ProcCntrlSSPortDataReceived);
                ProcCntrlSSPort.ReceivedBytesThreshold = 1;
                try
                {
                    ProcCntrlSSPort.Open();
                    ProcCntrlSSPort.DiscardInBuffer();
                }

Every 100 msec, there is a status message received by our application. I understand when the SerialPort received ReceivedBytesThreshold number of bytes, an event will be fired by the SerialPort. We have to use 1 for the ReceivedBytesThreshold because one of our important data is sent 1 byte each time whenever that byte is available.

When an event is fired by SerialPort and is processed by the receiver, that event should be disposed and the thread associated that event should be available for next use. so there should not be a big number of running thread accumulation.

But I found the running threads will continuously increase from 20 threads up to more than 400 threads after overnight. Just status message is sent to our application, no other activities then. I have disabled all process code so I am sure the accumulated threads are NOT from our code. That means we do nothing on the received data for the testing purpose.

I have increased the ReceivedBytesThreshold, saying 128, for testing purpose. It will slow down the accumulation but the thread count still goes up slowly. why .net framework cannot handle their threads properly? Or I didn't use it correctly?


问:
Issues with installed plugins like cordova-sqlite-storage
Every time I try to run my Ionic app, it is unable to load native plugins like the Cordova SQLite plugin and the Splash Screen plugin.

This happens at this line of code:

```<code>this.dbLocal.executeSql('CREATE TABLE IF NOT EXISTS contacts(id INTEGER
PRIMARY KEY AUTOINCREMENT, nickname TEXT, firstName TEXT, lastName TEXT,
description TEXT)', {}).then(console.log('Contacts loaded'));
</code>```

I get the following error:

```<code>Error: Uncaught (in promise): plugin_not_installed
</code>```

I also notice in the console logs that it is unable to find the native SQLITE plugin despite it being installed in the Ionic project. I tried uninstalling and reinstalling it, as well as doing:

```<code>ionic cordova prepare
</code>```

But it still does not work. I am not sure how to resolve this issue. Currently we are using:

答:
Looks like you are testing on a browser and sql native plugin is not available at a browser, thats why you get this reason.

You need to test on a real mobile, there it'll work without any problems.

Body:
Every time I try to run my Ionic app, it is unable to load native plugins like the Cordova SQLite plugin and the Splash Screen plugin.

This happens at this line of code:

this.dbLocal.executeSql('CREATE TABLE IF NOT EXISTS contacts(id INTEGER
PRIMARY KEY AUTOINCREMENT, nickname TEXT, firstName TEXT, lastName TEXT,
description TEXT)', {}).then(console.log('Contacts loaded'));

I get the following error:

Error: Uncaught (in promise): plugin_not_installed

I also notice in the console logs that it is unable to find the native SQLITE plugin despite it being installed in the Ionic project. I tried uninstalling and reinstalling it, as well as doing:

ionic cordova prepare

But it still does not work. I am not sure how to resolve this issue. Currently we are using:


问:
How to display error message when extra fields are not filled on registration in WordPress?
I would like to custamize the default user registration in Wordpress by adding first and last name and checkox with terms and coditions. The user is not able to register till all fields are filled and the checkbox is checked. I solved the checkbox with JavaScript. But now I want to add extra error messages when first and last name are not field. On the picture you see a massage for empty username and email. How could I add those kind of messages for first name and last name?

Error message for empty and email

答:
I did it the way you suggested. I created a plugin that validates the extra fields(first and last name). Now the user is not able to register if all fields are not filled.
User validation

Now the question is how could I change the error messages for user name and email address, so they can match mine? In other words where is the code that displays a message whena  user does not fill in any required field?

Thank you for the help!


问:
clang: initialising a lock reference from a mutex
This program is compiled by clang:

```<code>#include <mutex>

int main() {
    std::mutex mtx;
    const std::lock_guard<std::mutex>& lock(mtx);
    return 0;
}
</code>```

Other major compilers refuse it (I have tried gcc, msvc, and icc). This is an error message from gcc:

```<code>error: invalid initialization of reference of type ‘const
       std::lock_guard<std::mutex>&’ from expression of type ‘std::mutex’
</code>```

Others give similar errors.

Is clang right or wrong? Can this be reproduced with a simpler example not involving library classes? I have tried but to no avail.

Edit this seems to be the minimal reproduction:

```<code>struct A {};

struct X
{
    explicit X(A&) {};
};

int main()
{
    A a;
    const X& x(a);
}
</code>```

Interestingly, an int in place of A does trigger the error message in clang (which is why I could not reproduce this initially).

答:
I don't have the relevant chapter and verse of the C++ standard; I can only refer to CppReference on Converting Constructors right now (emphasis mine):

A constructor that is not declared with the specifier explicit and which can be called with a single parameter (until C++11) is called a converting constructor.

Unlike explicit constructors, which are only considered during direct initialization (which includes explicit conversions such as static_cast), converting constructors are also considered during copy initialization, as part of user-defined conversion sequence.

So:

```<code>struct A {};

struct X
{
    explicit X(A const &) {};
};

int main()
{
    A a;
    const X& x1(A());                 // OK, direct init (no A object after init)
    const X& x3(a);                   // NOK, copy init
}
</code>```

Body:
This program is compiled by clang:

#include <mutex>

int main() {
    std::mutex mtx;
    const std::lock_guard<std::mutex>& lock(mtx);
    return 0;
}

Other major compilers refuse it (I have tried gcc, msvc, and icc). This is an error message from gcc:

error: invalid initialization of reference of type ‘const
       std::lock_guard<std::mutex>&’ from expression of type ‘std::mutex’

Others give similar errors.

Is clang right or wrong? Can this be reproduced with a simpler example not involving library classes? I have tried but to no avail.

Edit this seems to be the minimal reproduction:

struct A {};

struct X
{
    explicit X(A&) {};
};

int main()
{
    A a;
    const X& x(a);
}

Interestingly, an int in place of A does trigger the error message in clang (which is why I could not reproduce this initially).

Body:
I don't have the relevant chapter and verse of the C++ standard; I can only refer to CppReference on Converting Constructors right now (emphasis mine):

A constructor that is not declared with the specifier explicit and which can be called with a single parameter (until C++11) is called a converting constructor.

Unlike explicit constructors, which are only considered during direct initialization (which includes explicit conversions such as static_cast), converting constructors are also considered during copy initialization, as part of user-defined conversion sequence.

So:

struct A {};

struct X
{
    explicit X(A const &) {};
};

int main()
{
    A a;
    const X& x1(A());                 // OK, direct init (no A object after init)
    const X& x3(a);                   // NOK, copy init
}


问:
How to combine 2 different dataframes together?
I have 2 DataFrames:

Users (~29.000.000 entries)

```<code>|-- userId: string (nullable = true)
</code>```

Impressions (~1000 entries)

```<code>|-- modules: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- content: array (nullable = true)
|    |    |    |-- element: string (containsNull = true)
|    |    |-- id: string (nullable = true)
</code>```

I want to walk through all the Users and attach to each User 1 Impression from these ~1000 entries. So actually at each ~1000th User the Impression would be the same, then the loop on the Impressions would start from the beginning and assign the same ~1000 impressions for the next ~1000 users.
At the end I want to have a DataFrame with the combined data. Also the Users dataframe could be reused by adding the columns of the Impressions or a newly created one would work also as a result.

You have any ideas, which would be a good solution here?

答:
What I would do is use the old trick of adding a monotically increasing ID to both dataframes, then create a new column on your LARGER dataframe (Users) which contains the modulo of each row's ID and the size of smaller dataframe.

This new column then provides a rolling matching key against the items in the Impressions dataframe.

This is a minimal example (tested) to give you the idea. Obviously this will work if you have 1000 impressions to join against:

```<code>var users = Seq("user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9").toDF("users")
var impressions = Seq("a", "b", "c").toDF("impressions").withColumn("id", monotonically_increasing_id())

var cnt = impressions.count

users=users.withColumn("id", monotonically_increasing_id())
       .withColumn("mod", $"id" mod cnt)
       .join(impressions, $"mod"===impressions("id"))
       .drop("mod")

users.show

+-----+---+-----------+---+
|users| id|impressions| id|
+-----+---+-----------+---+
|user1|  0|          a| 0|
|user2|  1|          b| 1|
|user3|  2|          c| 2|
|user4|  3|          a| 0|
|user5|  4|          b| 1|
|user6|  5|          c| 2|
|user7|  6|          a| 0|
|user8|  7|          b| 1|
|user9|  8|          c| 2|
+-----+---+-----------+---+
</code>```

Body:
I have 2 DataFrames:

Users (~29.000.000 entries)

|-- userId: string (nullable = true)

Impressions (~1000 entries)

|-- modules: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- content: array (nullable = true)
|    |    |    |-- element: string (containsNull = true)
|    |    |-- id: string (nullable = true)

I want to walk through all the Users and attach to each User 1 Impression from these ~1000 entries. So actually at each ~1000th User the Impression would be the same, then the loop on the Impressions would start from the beginning and assign the same ~1000 impressions for the next ~1000 users.
At the end I want to have a DataFrame with the combined data. Also the Users dataframe could be reused by adding the columns of the Impressions or a newly created one would work also as a result.

You have any ideas, which would be a good solution here?

Body:
What I would do is use the old trick of adding a monotically increasing ID to both dataframes, then create a new column on your LARGER dataframe (Users) which contains the modulo of each row's ID and the size of smaller dataframe.

This new column then provides a rolling matching key against the items in the Impressions dataframe.

This is a minimal example (tested) to give you the idea. Obviously this will work if you have 1000 impressions to join against:

var users = Seq("user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9").toDF("users")
var impressions = Seq("a", "b", "c").toDF("impressions").withColumn("id", monotonically_increasing_id())

var cnt = impressions.count

users=users.withColumn("id", monotonically_increasing_id())
       .withColumn("mod", $"id" mod cnt)
       .join(impressions, $"mod"===impressions("id"))
       .drop("mod")

users.show

+-----+---+-----------+---+
|users| id|impressions| id|
+-----+---+-----------+---+
|user1|  0|          a| 0|
|user2|  1|          b| 1|
|user3|  2|          c| 2|
|user4|  3|          a| 0|
|user5|  4|          b| 1|
|user6|  5|          c| 2|
|user7|  6|          a| 0|
|user8|  7|          b| 1|
|user9|  8|          c| 2|
+-----+---+-----------+---+


问:
How do I adjust subplots from a .fig file in Matlab
I have a .fig file with 9 subplots, arranged 3 by 3. Now I want to add labels with I have written in plotlabels(i) to subplot i, on point (xcoordinates(i),0.01). I try this

```<code>plotlabels = ['A','B','C','D','E','F','G','H','I'];
xcoordinates = [30,1000,1000,1000,1000,1000,1000,1000,1000];
fig = openfig('degreedistribution.fig');

for i = drange(1,9)
     subplot(3,3,i);
     text(xcoordinates(i),0.01,plotlabels(i),'FontWeight','bold'); hold on
end
</code>```

The figure is returned with subplot 1, 4 and 7 (the left column) blanc. In the other subplots, the proper label is added in the right location. I have checked that the locations of the labels in subplot 1, 4 and 7 are compatible with the plots. So what is happening?

答:
Its the axis, I assume.

as I don't have your figure, I tried without that line:

```<code>plotlabels = ['A','B','C','D','E','F','G','H','I'];
xcoordinates = [30,1000,1000,1000,1000,1000,1000,1000,1000];
for i = drange(1,9)
   subplot(3,3,i);
   text(xcoordinates(i),0.01,plotlabels(i),'FontWeight','bold'); hold on;
end
</code>```

You can see that no labels are shown, however, all x axis are [0-1]. If I add the line axis([0 2000 0 0.02]) after text(... then I can see all labels:

Body:
I have a .fig file with 9 subplots, arranged 3 by 3. Now I want to add labels with I have written in plotlabels(i) to subplot i, on point (xcoordinates(i),0.01). I try this

plotlabels = ['A','B','C','D','E','F','G','H','I'];
xcoordinates = [30,1000,1000,1000,1000,1000,1000,1000,1000];
fig = openfig('degreedistribution.fig');

for i = drange(1,9)
     subplot(3,3,i);
     text(xcoordinates(i),0.01,plotlabels(i),'FontWeight','bold'); hold on
end

The figure is returned with subplot 1, 4 and 7 (the left column) blanc. In the other subplots, the proper label is added in the right location. I have checked that the locations of the labels in subplot 1, 4 and 7 are compatible with the plots. So what is happening?

Body:
Its the axis, I assume.

as I don't have your figure, I tried without that line:

plotlabels = ['A','B','C','D','E','F','G','H','I'];
xcoordinates = [30,1000,1000,1000,1000,1000,1000,1000,1000];
for i = drange(1,9)
   subplot(3,3,i);
   text(xcoordinates(i),0.01,plotlabels(i),'FontWeight','bold'); hold on;
end

You can see that no labels are shown, however, all x axis are [0-1]. If I add the line axis([0 2000 0 0.02]) after text(... then I can see all labels:


问:
jxBrowser and Google maps in Java Swing
I'm developing a map with jxBrowser in Java Swing, The problem is that I need to return the lat / long variable from javaScript (executeJavaScriptAndReturnValue) to java Swing.

```<code>  browser.executeJavaScriptAndReturnValue(
                "map.addListener('click', function(e) {\n" +
                "placeMarker(e.latLng, map);\n" +
                "});\n" +
                "\n" +
                "function placeMarker(position, map) {\n" +
                "        var marker = new google.maps.Marker({\n" +
                "        position: position,\n" +
                "        map: map,\n" +
                "        title:'test point',\n " +
                "    });\n" +
                "    map.panTo(position);\n" +
                "}");
</code>```

答:
According to the code that you have posted, the executeJavaScriptAndReturnValue() configures a listener to the map events. In this case, you need to call back to the Java side and pass the latLng value as soon as the map event is received.

Here is a complete sample demonstrating the approach:

```<code>public class GoogleMapsSample {

    public static void main(String[] args) {
        final Browser browser = new Browser();
        browser.addScriptContextListener(new ScriptContextAdapter() {
            @Override
            public void onScriptContextCreated(ScriptContextEvent event) {
                browser.executeJavaScriptAndReturnValue("window").asObject().setProperty("java", new JavaCallback());
            }
        });
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(900, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // Provide the correct full path to the map.html file, e.g. D:\\map.html
        Browser.invokeAndWaitFinishLoadingMainFrame(browser, new Callback<Browser>() {
            @Override
            public void invoke(Browser value) {
                browser.loadURL("map.html");
            }
        });
        browser.executeJavaScriptAndReturnValue(
                "map.addListener('click', function(e) {\n" +
                        "placeMarker(e.latLng, map);\n" +
                        "});\n" +
                        "\n" +
                        "function placeMarker(position, map) {\n" +
                        "        var marker = new google.maps.Marker({\n" +
                        "        position: position,\n" +
                        "        map: map,\n" +
                        "        title:'test point',\n " +
                        "    });\n" +
                        "    map.panTo(position);\n" +
                        "    window.java.onMarkerAdded(position);" +
                        "}");
    }

    public static class JavaCallback {
        public void onMarkerAdded(JSObject position){
            double lat = position.getProperty("lat").asFunction().invoke(position).asNumber().getDouble();
            double lng = position.getProperty("lng").asFunction().invoke(position).asNumber().getDouble();
            System.out.println("lat = " + lat + ", lng = " + lng);
        }
    }
}
</code>```

The HTML code of the map.html that can be used with this sample:

```<code>The code of our map.html file is the following:
HTML

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
   <style type="text/css">
       html { height: 100% }
       body { height: 100%; margin: 0; padding: 0 }
       #map-canvas { height: 100% }
   </style>
   <script type="text/javascript"
           src="https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false"></script>
   <script type="text/javascript">
     var map;
     function initialize() {
       var mapOptions = {
         center: new google.maps.LatLng(48.209331, 16.381302),
         zoom: 4
       };
       map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
     }
     google.maps.event.addDomListener(window, 'load', initialize);

   </script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
</code>```

To use this file replace API_KEY with your Google API key. See the instruction about how to obtain API key.

You can find the general description of calling back from JavaScript to Java in the following article:
https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013062-calling-java-from-javascript

Title: jxBrowser and Google maps in Java Swing

Body:
I'm developing a map with jxBrowser in Java Swing, The problem is that I need to return the lat / long variable from javaScript (executeJavaScriptAndReturnValue) to java Swing.

  browser.executeJavaScriptAndReturnValue(
                "map.addListener('click', function(e) {\n" +
                "placeMarker(e.latLng, map);\n" +
                "});\n" +
                "\n" +
                "function placeMarker(position, map) {\n" +
                "        var marker = new google.maps.Marker({\n" +
                "        position: position,\n" +
                "        map: map,\n" +
                "        title:'test point',\n " +
                "    });\n" +
                "    map.panTo(position);\n" +
                "}");

Body:
According to the code that you have posted, the executeJavaScriptAndReturnValue() configures a listener to the map events. In this case, you need to call back to the Java side and pass the latLng value as soon as the map event is received.

Here is a complete sample demonstrating the approach:

public class GoogleMapsSample {

    public static void main(String[] args) {
        final Browser browser = new Browser();
        browser.addScriptContextListener(new ScriptContextAdapter() {
            @Override
            public void onScriptContextCreated(ScriptContextEvent event) {
                browser.executeJavaScriptAndReturnValue("window").asObject().setProperty("java", new JavaCallback());
            }
        });
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(900, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // Provide the correct full path to the map.html file, e.g. D:\\map.html
        Browser.invokeAndWaitFinishLoadingMainFrame(browser, new Callback<Browser>() {
            @Override
            public void invoke(Browser value) {
                browser.loadURL("map.html");
            }
        });
        browser.executeJavaScriptAndReturnValue(
                "map.addListener('click', function(e) {\n" +
                        "placeMarker(e.latLng, map);\n" +
                        "});\n" +
                        "\n" +
                        "function placeMarker(position, map) {\n" +
                        "        var marker = new google.maps.Marker({\n" +
                        "        position: position,\n" +
                        "        map: map,\n" +
                        "        title:'test point',\n " +
                        "    });\n" +
                        "    map.panTo(position);\n" +
                        "    window.java.onMarkerAdded(position);" +
                        "}");
    }

    public static class JavaCallback {
        public void onMarkerAdded(JSObject position){
            double lat = position.getProperty("lat").asFunction().invoke(position).asNumber().getDouble();
            double lng = position.getProperty("lng").asFunction().invoke(position).asNumber().getDouble();
            System.out.println("lat = " + lat + ", lng = " + lng);
        }
    }
}

The HTML code of the map.html that can be used with this sample:

The code of our map.html file is the following:
HTML

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
   <style type="text/css">
       html { height: 100% }
       body { height: 100%; margin: 0; padding: 0 }
       #map-canvas { height: 100% }
   </style>
   <script type="text/javascript"
           src="https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false"></script>
   <script type="text/javascript">
     var map;
     function initialize() {
       var mapOptions = {
         center: new google.maps.LatLng(48.209331, 16.381302),
         zoom: 4
       };
       map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
     }
     google.maps.event.addDomListener(window, 'load', initialize);

   </script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

To use this file replace API_KEY with your Google API key. See the instruction about how to obtain API key.

You can find the general description of calling back from JavaScript to Java in the following article:
https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013062-calling-java-from-javascript


问:
Get absolute coordinates of view inside popup window
I have a draggable popup window fragment. I need to get the x and y coordinates of that fragment in onSaveInstanceState(). I got the width and height of the fragment by using getView().getWidth() and getView().getHeight(). But if i use getView().getX() or getView().getY() giving 0.0. Is there any chance to get the coordinates?

答:
Use View#getLocationOnScreen(int[]) API:

Computes the coordinates of this view on the screen. The argument must be an array of two integers. After the method returns, the array contains the x and y location in that order.

```
<code>
    int[] location = new int[2];
    getView().getLocationOnScreen(location);
    // now location[0] contains x position
    // and location[1] contains y position
</code>
```

Body:
Use View#getLocationOnScreen(int[]) API:

Computes the coordinates of this view on the screen. The argument must be an array of two integers. After the method returns, the array contains the x and y location in that order.

    int[] location = new int[2];
    getView().getLocationOnScreen(location);
    // now location[0] contains x position
    // and location[1] contains y position


问:
Sorting a parquet dataset using Spark and storing the sorted result as multiple files in S3
In s3://my-bucket/events/date=X/ I have a parquet dataset stored in multiple part files:

part000.snappy.parquet

part001.snappy.parquet

part002.snappy.parquet

...

Events in the dataset have a timestamp column, a string in ISO 8601. The events in the dataset are completely unsorted.

Using spark, I would like to sort the dataset and store it back in S3, such that:

within each partXXX.snappy.parquet, events are ordered by timestamp

part files with lower XXX have lower timestamps, i.e. timestamps of
events in part000 are <= timestamps of events in part 001 <=
timestamps of events in part 002, ...

Details:
 - Each part file has 200MB - 1GB
 - The final saved files can contain any number of events, as long as I can control their size somehow. I would like to keep part files with a size smaller than 1GB.

Is it easy to do this in Spark? How could one implement this?/

答:
The following worked:</p>

```<code>target_path = "s3://..."
events = spark.read.parquet("s3://my-bucket/events/date=X/")
events = events.sort("timestamp", ascending=True)
num_files = ceil(float(events.count()) / EVENTS_PER_FILE)
events.coalesce(num_files).write.parquet(
            target_path,
            mode="overwrite")  # note: overwrite deletes old files
</code>```

Body:
The following worked:

target_path = "s3://..."
events = spark.read.parquet("s3://my-bucket/events/date=X/")
events = events.sort("timestamp", ascending=True)
num_files = ceil(float(events.count()) / EVENTS_PER_FILE)
events.coalesce(num_files).write.parquet(
            target_path,
            mode="overwrite")  # note: overwrite deletes old files


答:
You don't store each object with a variable name. Variable names are for the convenience of a programmer.

If you want a collection of objects, you use just that - a collection. Use either a list or a dictionary containing object instances, referenced by index or key respectively.

So for example, if each employee has an employee number, you might keep them in a dictionary with the employee number as a key.

Title: Creating objects during runtime in Python

Body:
I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person()

What I have trouble understanding now is how I would design a model that creates a new object during runtime? I'm aware that my phrasing is probably faulty since all objects are generated during runtime but what I mean is that if I were to start my application in a terminal or UI how would I create new objects and manage them. I can't really define new variable names on the fly right?

An example application where I run into this design issue would be a database storing people. The user gets a terminal menu which allows him to create a new user and assign a name, salary, position. How would you instantiate that object and later call it if you want to manage it, call functions, etc.? What's the design pattern here?

Please excuse my poor understanding of the OPP model. I'm currently reading up on classes and OOP but I feel like I need to understand what my error is here before moving on. Please let me know if there is anything I should clarify.


问:
Return Code on failure. Positive or negative?
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;
</code>```

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;
</code>```

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.

答:
5.1.2.2.3  Program termination

If the return type of the main function is a type compatible with int,
  a return from the initial call to the main function is equivalent to
  calling the exit function with the value returned  by  the main
  function  as  its  argument; 11) reaching  the } that  terminates  the
  main function returns a value of 0. If the return type is not
  compatible with int, the termination status returned to the host
  environment is unspeciﬁed.

7.22.4.4  The exit function:

Finally, control is returned to the host environment.  If the value of
  status is zero or EXIT_SUCCESS, an implementation-deﬁned form of the
  status successful termination is returned.  If the value of status is
  EXIT_FAILURE, an implementation-deﬁned form of  the  status
  unsuccessful  termination is returned. Otherwise  the  status
  returned  is implementation-deﬁned.

I found this to be self-descriptive.

Body:
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.


问:
How can I add multiple tables via LEFT JOIN and count the rows of each table?
I am counting the results of a table I LEFT JOINED:

```<code>SELECT p.*,COUNT(po.name) AS posts
    FROM projects p
    left join posts po on p.name = po.name
    group by p.id
</code>```

http://sqlfiddle.com/#!9/3e9d4b/4

But now I want to add another table via LEFT JOIN and count it also:

```<code>SELECT p.*,COUNT(po.name) AS posts,
    COUNT(ta.name) AS tasks
    FROM projects p
    left join posts po on p.name = po.name
    left join tasks ta on p.name = ta.name
    group by p.id
</code>```

http://sqlfiddle.com/#!9/ee068/2

But now the counting is wrong. For cat I have only 2 posts and 3 tasks. Where is the number 6 coming from?

答:
Left joins are not the right tool for this. You should use subselects:</p>

```<code>SELECT p.*,
  (SELECT COUNT(*) FROM posts po WHERE p.name = po.name) AS posts,
  (SELECT COUNT(*) FROM tasks ta WHERE p.name = ta.name) AS tasks
FROM projects p
</code>```

Body:
I am counting the results of a table I LEFT JOINED:

SELECT p.*,COUNT(po.name) AS posts
    FROM projects p
    left join posts po on p.name = po.name
    group by p.id

http://sqlfiddle.com/#!9/3e9d4b/4

But now I want to add another table via LEFT JOIN and count it also:

SELECT p.*,COUNT(po.name) AS posts,
    COUNT(ta.name) AS tasks
    FROM projects p
    left join posts po on p.name = po.name
    left join tasks ta on p.name = ta.name
    group by p.id

http://sqlfiddle.com/#!9/ee068/2

But now the counting is wrong. For cat I have only 2 posts and 3 tasks. Where is the number 6 coming from?

Body:
Left joins are not the right tool for this. You should use subselects:

SELECT p.*,
  (SELECT COUNT(*) FROM posts po WHERE p.name = po.name) AS posts,
  (SELECT COUNT(*) FROM tasks ta WHERE p.name = ta.name) AS tasks
FROM projects p


问:
Printing from array with button
I´m trying to print from an array with a button. The users are supposed to press the button and a text box is showing up. But nothing happens when I press the button. Does anyone see the problem?

The button is made in html.

```<code>(function () {
  "use strict";

  //HTML objects
  let lenkerBtn;
  let mainContent;

  //bildeliste
  let tekst = ["Her kan du lese om lenker. Bare vent et øyeblikk :)"];

  let init = function () {

    let setHTMLObjects = function () {
      lenkerBtn = document.getElementById("lenkerBtn");
      mainContent = document.getElementById("main-content");
    }(); //end setEvents

    let setEvents = function(){
      lenkerBtn.onclick = vislenker;
    }(); //end setEvents

  }(); //end init

  function visLenker () {
    let antallTekst = tekst.length;
    for (var i = 0; i < tekst; i++) {
      document.getElementById("tekstOmLenker").innerHTML += ("<li>" + tekst[i] + "</li>");
    }
  }
}());
</code>```

答:
The problem might be in

```<code> function visLenker(){
       let antallTekst = tekst.length;
       for(var i = 0; i < tekst; i++){
        document.getElementById("tekstOmLenker").innerHTML += ("<li>" + tekst[i] + "</li>");
   }
</code>```

where you declare

```<code>i < tekst
</code>```

instead of

```<code>i < antallTekst
</code>```

It is usually best to avoid declaring one-time use variables, so ( i < tekst.length ) would probably be a cleaner form.

If that does not solve the problem you might want to post some of the relevant Html too.

Title: Printing from array with button

Body:
I´m trying to print from an array with a button. The users are supposed to press the button and a text box is showing up. But nothing happens when I press the button. Does anyone see the problem?

The button is made in html.

(function () {
  "use strict";

  //HTML objects
  let lenkerBtn;
  let mainContent;

  //bildeliste
  let tekst = ["Her kan du lese om lenker. Bare vent et øyeblikk :)"];

  let init = function () {

    let setHTMLObjects = function () {
      lenkerBtn = document.getElementById("lenkerBtn");
      mainContent = document.getElementById("main-content");
    }(); //end setEvents

    let setEvents = function(){
      lenkerBtn.onclick = vislenker;
    }(); //end setEvents

  }(); //end init

  function visLenker () {
    let antallTekst = tekst.length;
    for (var i = 0; i < tekst; i++) {
      document.getElementById("tekstOmLenker").innerHTML += ("
" + tekst[i] + "
");
    }
  }
}());

Body:
The problem might be in

 function visLenker(){
       let antallTekst = tekst.length;
       for(var i = 0; i < tekst; i++){
        document.getElementById("tekstOmLenker").innerHTML += ("<li>" + tekst[i] + "</li>");
   }

where you declare

i < tekst

instead of

i < antallTekst

It is usually best to avoid declaring one-time use variables, so ( i < tekst.length ) would probably be a cleaner form.

If that does not solve the problem you might want to post some of the relevant Html too.


问:
How return json in django for bootstrap table
How return json from queryset - A.objects.all() to bootstrap table (http://wenzhixin.net.cn/p/bootstrap-table/docs/examples.html):

```<code><table data-toggle="table" data-url="data" data-cache="false" data-height="299">
    <thead>
        <tr>
            <th data-field="id">Item ID</th>
            <th data-field="name">Name</th>
        </tr>
    </thead>
</table>
</code>```

in views:

```<code>data = serializers.serialize("json", A.objects.all())
return render(request, 'a.html', {'data': data})
</code>```

答:
There is 2 modes : server or client

For server mode:

in utils.py :

```<code>from django.core.serializers import serialize
import json
def serialize_bootstraptable(queryset):
    json_data = serialize('json', queryset)
    json_final = {"total": queryset.count(), "rows": []}
    data = json.loads(json_data)
    for item in data:
        del item["model"]
        item["fields"].update({"id": item["pk"]})
        item = item["fields"]
        json_final['rows'].append(item)
    return json_final
</code>```

in views.py :

```<code>from django.http import JsonResponse
json_send = serialize_bootstraptable(Model.objects.all())
return JsonResponse(json_send, safe=False)
</code>```

Body:
How return json from queryset - A.objects.all() to bootstrap table (http://wenzhixin.net.cn/p/bootstrap-table/docs/examples.html):

            Item ID
            Name

in views:

data = serializers.serialize("json", A.objects.all())
return render(request, 'a.html', {'data': data})

Body:
There is 2 modes : server or client

For server mode:

in utils.py :

from django.core.serializers import serialize
import json
def serialize_bootstraptable(queryset):
    json_data = serialize('json', queryset)
    json_final = {"total": queryset.count(), "rows": []}
    data = json.loads(json_data)
    for item in data:
        del item["model"]
        item["fields"].update({"id": item["pk"]})
        item = item["fields"]
        json_final['rows'].append(item)
    return json_final

in views.py :

from django.http import JsonResponse
json_send = serialize_bootstraptable(Model.objects.all())
return JsonResponse(json_send, safe=False)


问:
Help needed to decide type of service account at SQL Server reporting services
My problem has to do with the kind of service account i need to setup in order to make reporting services on a sql server 2008 db work.The OS is windows server 2003.We need the reports to be viewed from users on the company intranet.this intranet is not on a domain, it is controlled from linux servers. The users will view the reports at the browser typing the url.
 My problem is that if i set the windows account as the service account,then every user will be prompted for the credential of the windows account and we don't want to give that kind of information to everyone.
 What is the best way to handle that?</p>

答:
not sure if i'm understanding your question correctly, but if users are being prompted for credentials when they type the url, it is them that cant authenticate on the reports web server. Have your users got access into the virtual directory on the iis server?

Also in your reports, under the Data Sources option how are you authenticating on the database, if the users have direct access onto the database server Windows integrated security should work, otherwise you will need to save the connection authentication details into the report


问:
exporting to lambda function from a zip does not pick up the sleep module
I have a nodeJs script and want to put some sleep during the execution.

I have created a local npm package and a project. Project directory are given below.

```<code>[ec2-user@ip-local lambdaTestFunction]$ ls -ltr
total 888
drwx------. 8 ec2-user ec2-user     98 Nov 13 11:22 node_modules
-rwxr-xr-x. 1 ec2-user ec2-user    510 Nov 13 13:51 index.js
-rw-------. 1 ec2-user ec2-user 899230 Nov 13 13:51 index.zip
[ec2-user@ip-local lambdaTestFunction]$
</code>```

I have zipped node_modules and index.js and have zipped them as index.zip

node_modules contains the following

```<code>[ec2-user@ip-local lambdaTestFunction]$ cd node_modules/
[ec2-user@ip-local node_modules]$ ls -ltr
total 12
drwx------. 2 ec2-user ec2-user   73 Nov 13 11:22 deasync-promise
drwx------. 2 ec2-user ec2-user   59 Nov 13 11:22 bindings
drwx------. 2 ec2-user ec2-user   71 Nov 13 11:22 system-sleep
drwx------. 4 ec2-user ec2-user 4096 Nov 13 11:22 nan
drwx------. 4 ec2-user ec2-user 4096 Nov 13 11:22 deasync
drwx------. 3 ec2-user ec2-user 4096 Nov 13 11:22 sleep
[ec2-user@ip-local node_modules]$
</code>```

When I execute the script index.js locally, it works well as given below.

```<code>[ec2-user@ip-local lambdaTestFunction]$ node index.js
starting the function
start before wait
after 5 mins
[ec2-user@ip-local lambdaTestFunction]$
</code>```

But when I export the zip to lambda function, execution fails with the message

```<code>{
  "errorMessage": "Cannot find module 'index/node_modules/sleep'",
  "errorType": "Error",
  "stackTrace": [
    "Module.require (module.js:497:17)",
    "require (internal/module.js:20:19)",
    "Object.<anonymous> (/var/task/index/index.js:2:13)",
    "Module._compile (module.js:570:32)",
    "Object.Module._extensions..js (module.js:579:10)",
    "Module.load (module.js:487:32)",
    "tryModuleLoad (module.js:446:12)",
    "Function.Module._load (module.js:438:3)"
  ]
}
</code>```

Contents of index.js is below

```<code>console.log("starting the function");
var sleep = require('sleep');
console.log("start before wait");
sleep.sleep(5); // 5 seconds
console.log("after 5 mins");

exports.handler = (event, context, callback) => {
    // TODO implement
    //callback(null, 'Hello from Lambda');
    console.log("start before wait");
    //sleep.sleep(5); // 5 seconds
    //             //setTimeout(function(){ alert("Hello"); }, 3000);
    console.log("after 5 mins");
    callback(null, 'Hello from Lambda after 5 sec');

};
</code>```

I am not sure what am I still missing.

答:
Mostly it is because of the way zipping the files making the problem. Instead of zipping the folder you have to select all files and zip it like below,

Please upload all files and folders including your node_modules folder

Body:
I have a nodeJs script and want to put some sleep during the execution.

I have created a local npm package and a project. Project directory are given below.

[ec2-user@ip-local lambdaTestFunction]$ ls -ltr
total 888
drwx------. 8 ec2-user ec2-user     98 Nov 13 11:22 node_modules
-rwxr-xr-x. 1 ec2-user ec2-user    510 Nov 13 13:51 index.js
-rw-------. 1 ec2-user ec2-user 899230 Nov 13 13:51 index.zip
[ec2-user@ip-local lambdaTestFunction]$

I have zipped node_modules and index.js and have zipped them as index.zip

node_modules contains the following

[ec2-user@ip-local lambdaTestFunction]$ cd node_modules/
[ec2-user@ip-local node_modules]$ ls -ltr
total 12
drwx------. 2 ec2-user ec2-user   73 Nov 13 11:22 deasync-promise
drwx------. 2 ec2-user ec2-user   59 Nov 13 11:22 bindings
drwx------. 2 ec2-user ec2-user   71 Nov 13 11:22 system-sleep
drwx------. 4 ec2-user ec2-user 4096 Nov 13 11:22 nan
drwx------. 4 ec2-user ec2-user 4096 Nov 13 11:22 deasync
drwx------. 3 ec2-user ec2-user 4096 Nov 13 11:22 sleep
[ec2-user@ip-local node_modules]$

When I execute the script index.js locally, it works well as given below.

[ec2-user@ip-local lambdaTestFunction]$ node index.js
starting the function
start before wait
after 5 mins
[ec2-user@ip-local lambdaTestFunction]$

But when I export the zip to lambda function, execution fails with the message

{
  "errorMessage": "Cannot find module 'index/node_modules/sleep'",
  "errorType": "Error",
  "stackTrace": [
    "Module.require (module.js:497:17)",
    "require (internal/module.js:20:19)",
    "Object.<anonymous> (/var/task/index/index.js:2:13)",
    "Module._compile (module.js:570:32)",
    "Object.Module._extensions..js (module.js:579:10)",
    "Module.load (module.js:487:32)",
    "tryModuleLoad (module.js:446:12)",
    "Function.Module._load (module.js:438:3)"
  ]
}

Contents of index.js is below

console.log("starting the function");
var sleep = require('sleep');
console.log("start before wait");
sleep.sleep(5); // 5 seconds
console.log("after 5 mins");

exports.handler = (event, context, callback) => {
    // TODO implement
    //callback(null, 'Hello from Lambda');
    console.log("start before wait");
    //sleep.sleep(5); // 5 seconds
    //             //setTimeout(function(){ alert("Hello"); }, 3000);
    console.log("after 5 mins");
    callback(null, 'Hello from Lambda after 5 sec');

};

I am not sure what am I still missing.


问:
Open MPI Waitall() Segmentation Fault
I'm new with MPI and I'm trying to develop a non-blocking programm (with Isend and Irecv). The functionality is very basic (it's educational):

There is one process (rank 0) who is the master and receives messages from the slaves (rank 1-P). The master only receives results.

The slaves generates an array of N random numbers between 0 and R and then they do some operations with those numbers (again, it's just for educational purpose, the operations don't make any sense)

This whole process (operations + send data) is done M times (this is just for comparing different implementations; blocking and non-blocking)

I get a Segmentation Fault in the Master process when I'm calling the MPI_waitall() funcion

```<code>#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#include <math.h>
#include <time.h>
#define M 1000      //Number of times
#define N 2000      //Quantity of random numbers
#define R 1000      //Max value of random numbers

double SumaDeRaices (double*);

int main(int argc, char* argv[]) {
    int         yo;            /* rank of process      */
    int         p;             /* number of processes  */
    int         dest;          /* rank of receiver     */

    /* Start up MPI */
    MPI_Init(&argc, &argv);

    /* Find out process rank  */
    MPI_Comm_rank(MPI_COMM_WORLD, &yo);

    /* Find out number of processes */
    MPI_Comm_size(MPI_COMM_WORLD, &p);

    MPI_Request  reqs[p-1];
    MPI_Status   stats[p-1];

    if (yo == 0) {
        int i,j;
        double result;
        clock_t inicio,fin;

        inicio = clock();

        for(i = 0; i<M; i++){ //M times
            for(j = 1; j<p; j++){ //for every slave
                MPI_Irecv(&result, sizeof(double), MPI_DOUBLE, j, i, MPI_COMM_WORLD, &reqs[j-1]);
            }
            MPI_Waitall(p-1,reqs,stats); //wait all slaves (SEG_FAULT)
        }
        fin = clock()-inicio;

        printf("Tiempo total de ejecucion %f segundos \n", ((double)fin)/CLOCKS_PER_SEC);
    }
    else {
        double* numAleatorios = (double*) malloc( sizeof(double) * ((double) N) ); //array with numbers
        int i,j;
        double resultado;
        dest=0;

        for(i=0; i<M; i++){ //again, M times
            for(j=0; j<N; j++){
                numAleatorios[j] = rand() % R ;
            }
            resultado = SumaDeRaices(numAleatorios);
            MPI_Isend(&resultado,sizeof(double), MPI_DOUBLE, dest, i, MPI_COMM_WORLD,&reqs[p-1]); //send result to master
        }
    }

    /* Shut down MPI */
    MPI_Finalize();

    exit(0);
} /* main */

double SumaDeRaices (double* valores){
    int i;
    double sumaTotal = 0.0;

    //Raices cuadradas de los valores y suma de estos
    for(i=0; i<N; i++){
        sumaTotal = sqrt(valores[i]) + sumaTotal;
    }

    return sumaTotal;
}
</code>```

答:
There are several issues with your code. First and foremost in your Isend you pass &resultado several times without waiting until previous non-blocking operation finishes. You are not allowed to reuse the buffer you pass to Isend before you make sure the operation finishes.

Instead I recommend you using normal Send, because in contrast to synchronous send (SSend) normal blocking send returns as soon as you can reuse the buffer.

Second, there is no need to use message tags. I recommend you to just set tag to 0. In terms of performance it is simply faster.

Third, the result shouldn't be a simple variable, but an array of size at least (p-1)

Fourth, I do not recommend you to allocate arrays on stack, like MPI_Request and MPI_Status if the size is not a known small number. In this case the size of array is (p-1), so you better use malloc for this data structure.

Fifth, if you do not check status, use MPI_STATUSES_IGNORE.

Also instead of sizeof(double) you should specify number of items (1).

But of course the absolutely best version is just to use MPI_Gather.

Moreover, generally there is no reason not to run computations on the root node.

Here is slightly rewritten example:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#include <math.h>
#include <time.h>
#define M 1000      //Number of times
#define N 2000      //Quantity of random numbers
#define R 1000      //Max value of random numbers

double SumaDeRaices (double* valores)
{

  int i;
  double sumaTotal = 0.0;

  //Raices cuadradas de los valores y suma de estos
  for(i=0; i<N; i++) {
    sumaTotal = sqrt(valores[i]) + sumaTotal;
  }

  return sumaTotal;
}

int main(int argc, char* argv[]) {
  int         yo;            /* rank of process      */
  int         p;             /* number of processes  */

  /* Start up MPI */
  MPI_Init(&argc, &argv);

  /* Find out process rank  */
  MPI_Comm_rank(MPI_COMM_WORLD, &yo);

  /* Find out number of processes */
  MPI_Comm_size(MPI_COMM_WORLD, &p);

  double *result;
  clock_t inicio, fin;
  double *numAleatorios;
  if (yo == 0) {
    inicio = clock();
  }

  numAleatorios = (double*) malloc( sizeof(double) * ((double) N) ); //array with numbers
  result = (double *) malloc(sizeof(double) * p);

  for(int i = 0; i<M; i++){ //M times
    for(int j=0; j<N; j++) {
      numAleatorios[j] = rand() % R ;
    }
    double local_result = SumaDeRaices(numAleatorios);
    MPI_Gather(&local_result, 1, MPI_DOUBLE, result, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); //send result to master
  }

  if (yo == 0) {
    fin = clock()-inicio;

    printf("Tiempo total de ejecucion %f segundos \n", ((double)fin)/CLOCKS_PER_SEC);
  }

  free(numAleatorios);

  /* Shut down MPI */
  MPI_Finalize();
} /* main */
</code>```

Title: Open MPI Waitall() Segmentation Fault

Body:
I'm new with MPI and I'm trying to develop a non-blocking programm (with Isend and Irecv). The functionality is very basic (it's educational):

There is one process (rank 0) who is the master and receives messages from the slaves (rank 1-P). The master only receives results.

The slaves generates an array of N random numbers between 0 and R and then they do some operations with those numbers (again, it's just for educational purpose, the operations don't make any sense)

This whole process (operations + send data) is done M times (this is just for comparing different implementations; blocking and non-blocking)

I get a Segmentation Fault in the Master process when I'm calling the MPI_waitall() funcion

#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#include <math.h>
#include <time.h>
#define M 1000      //Number of times
#define N 2000      //Quantity of random numbers
#define R 1000      //Max value of random numbers

double SumaDeRaices (double*);

int main(int argc, char* argv[]) {
    int         yo;            /* rank of process      */
    int         p;             /* number of processes  */
    int         dest;          /* rank of receiver     */

    /* Start up MPI */
    MPI_Init(&argc, &argv);

    /* Find out process rank  */
    MPI_Comm_rank(MPI_COMM_WORLD, &yo);

    /* Find out number of processes */
    MPI_Comm_size(MPI_COMM_WORLD, &p);

    MPI_Request  reqs[p-1];
    MPI_Status   stats[p-1];

    if (yo == 0) {
        int i,j;
        double result;
        clock_t inicio,fin;

        inicio = clock();

        for(i = 0; i<M; i++){ //M times
            for(j = 1; j<p; j++){ //for every slave
                MPI_Irecv(&result, sizeof(double), MPI_DOUBLE, j, i, MPI_COMM_WORLD, &reqs[j-1]);
            }
            MPI_Waitall(p-1,reqs,stats); //wait all slaves (SEG_FAULT)
        }
        fin = clock()-inicio;

        printf("Tiempo total de ejecucion %f segundos \n", ((double)fin)/CLOCKS_PER_SEC);
    }
    else {
        double* numAleatorios = (double*) malloc( sizeof(double) * ((double) N) ); //array with numbers
        int i,j;
        double resultado;
        dest=0;

        for(i=0; i<M; i++){ //again, M times
            for(j=0; j<N; j++){
                numAleatorios[j] = rand() % R ;
            }
            resultado = SumaDeRaices(numAleatorios);
            MPI_Isend(&resultado,sizeof(double), MPI_DOUBLE, dest, i, MPI_COMM_WORLD,&reqs[p-1]); //send result to master
        }
    }

    /* Shut down MPI */
    MPI_Finalize();

    exit(0);
} /* main */

double SumaDeRaices (double* valores){
    int i;
    double sumaTotal = 0.0;

    //Raices cuadradas de los valores y suma de estos
    for(i=0; i<N; i++){
        sumaTotal = sqrt(valores[i]) + sumaTotal;
    }

    return sumaTotal;
}

Body:
There are several issues with your code. First and foremost in your Isend you pass &resultado several times without waiting until previous non-blocking operation finishes. You are not allowed to reuse the buffer you pass to Isend before you make sure the operation finishes.

Instead I recommend you using normal Send, because in contrast to synchronous send (SSend) normal blocking send returns as soon as you can reuse the buffer.

Second, there is no need to use message tags. I recommend you to just set tag to 0. In terms of performance it is simply faster.

Third, the result shouldn't be a simple variable, but an array of size at least (p-1)

Fourth, I do not recommend you to allocate arrays on stack, like MPI_Request and MPI_Status if the size is not a known small number. In this case the size of array is (p-1), so you better use malloc for this data structure.

Fifth, if you do not check status, use MPI_STATUSES_IGNORE.

Also instead of sizeof(double) you should specify number of items (1).

But of course the absolutely best version is just to use MPI_Gather.

Moreover, generally there is no reason not to run computations on the root node.

Here is slightly rewritten example:

#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#include <math.h>
#include <time.h>
#define M 1000      //Number of times
#define N 2000      //Quantity of random numbers
#define R 1000      //Max value of random numbers

double SumaDeRaices (double* valores)
{

  int i;
  double sumaTotal = 0.0;

  //Raices cuadradas de los valores y suma de estos
  for(i=0; i<N; i++) {
    sumaTotal = sqrt(valores[i]) + sumaTotal;
  }

  return sumaTotal;
}

int main(int argc, char* argv[]) {
  int         yo;            /* rank of process      */
  int         p;             /* number of processes  */

  /* Start up MPI */
  MPI_Init(&argc, &argv);

  /* Find out process rank  */
  MPI_Comm_rank(MPI_COMM_WORLD, &yo);

  /* Find out number of processes */
  MPI_Comm_size(MPI_COMM_WORLD, &p);

  double *result;
  clock_t inicio, fin;
  double *numAleatorios;
  if (yo == 0) {
    inicio = clock();
  }

  numAleatorios = (double*) malloc( sizeof(double) * ((double) N) ); //array with numbers
  result = (double *) malloc(sizeof(double) * p);

  for(int i = 0; i<M; i++){ //M times
    for(int j=0; j<N; j++) {
      numAleatorios[j] = rand() % R ;
    }
    double local_result = SumaDeRaices(numAleatorios);
    MPI_Gather(&local_result, 1, MPI_DOUBLE, result, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); //send result to master
  }

  if (yo == 0) {
    fin = clock()-inicio;

    printf("Tiempo total de ejecucion %f segundos \n", ((double)fin)/CLOCKS_PER_SEC);
  }

  free(numAleatorios);

  /* Shut down MPI */
  MPI_Finalize();
} /* main */


问:
Python: List merging method
I have a question:

I have 2 lists:

```<code>list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
</code>```

And I want to merge them in order to have the following result:

```<code>mergedlist = [1, 4, 2, 5, 3, 6]
</code>```

How can I do that?

答:
In my opinion, the most Pythonic way would be:

merged_list = [item for pair in zip(list_1, list_2) for item in pair]

Alternatively, you can use collections.chain as well:

merged_list = list(chain.from_iterable(zip(list_1, list_2)))

Title: Python: List merging method

Body:
I have a question:

I have 2 lists:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

And I want to merge them in order to have the following result:

mergedlist = [1, 4, 2, 5, 3, 6]

How can I do that?


问:
Django: Filtering the Distinct Data
I'm trying to build a messaging app. Here's my model,

```<code>class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

This is what I tried in view,

```<code>data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))
</code>```

In the template,

```<code>{% for abc in data %}
    {{ abc.receiver }} <br/>
{% endfor %}
</code>```

How to get distinct users and re-order them based upon new messages as we see on social media platforms?

答:
here thing you need to do,

fetch sender request.user rec - somename

fetch receivedMsg for above sender, receiver request.user serder - somename

message_queue = Message.objects.filter(Q(receiver=rec_name, sender=request.user), Q(receiver=request.user, sender=rec_name).order_by('-created_at')

order by created_at will shuffle like chain

Title: Django: Filtering the Distinct Data

Body:
I'm trying to build a messaging app. Here's my model,

class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

This is what I tried in view,

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))

In the template,

{% for abc in data %}
    {{ abc.receiver }}

{% endfor %}

How to get distinct users and re-order them based upon new messages as we see on social media platforms?