问:
SetInterval to do carousel. Two similar snippet, one is right, the other is wrong. Why?
I am doing a carousel sample using JavaScript. Is there any difference between

```<code>        index++;
        index == imgList.length && (index = 0);
        show(index);
</code>```

and

```<code>    index++;
    show(index);
    index == imgList.length - 1 && (index = -1);
</code>```

Because the code above can work,code below cannot.
Here is all the code:

window.onload = function() {
  var numList = document.getElementById("numbers").getElementsByTagName("li");
  var imgList = document.getElementById("imgs").getElementsByTagName("li");
  var containBox = document.getElementById("box");
  var index = 0;
  var timer = play = null;

  for (var i = 0; i < numList.length; i++) {
    numList[i].index = i;
    numList[i].onmouseover = function() {
      clearInterval(timer);
      show(this.index);
    };
  }

  function show(a) {
    index = a;
    var opacity = 0;
    for (var i = 0; i < imgList.length; i++) {
      imgList[i].style.opacity = 0;
    }
    for (var i = 0; i < numList.length; i++) numList[i].className = "";
    numList[index].className = "current";
    timer = setInterval(function() {
      opacity += 2;
      imgList[index].style.opacity = opacity / 100;
      opacity == 100 && clearTimeout(timer);
    }, 20);
  }

  function autoPlay() {
    play = setInterval(function() {
      index++;
      show(index);
      index == imgList.length - 1 && (index = -1);
      //                index++;
      //                index == imgList.length && (index = 0);
      //                show(index);
    }, 2000);
  }
  autoPlay();

  containBox.onmouseover = function() {
    clearInterval(play);
  }

  containBox.onmouseout = function() {
    autoPlay();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
  width: 445px;
  margin: 0 auto;
  position: relative;
}

ul,
li {
  padding: 0;
  margin: 0;
}

li {
  list-style-type: none;
}

#imgs {
  position: relative;
}

#imgs li {
  position: absolute;
  top: 0;
  left: 0;
}

#imgs img {
  width: 440px;
  height: 220px;
}

#numbers {
  position: absolute;
  right: 15px;
  top: 190px;
}

#numbers li {
  display: inline-block;
  background-color: #F90;
  width: 20px;
  height: 20px;
  border-radius: 20px;
  color: rgb(232, 227, 227);
  text-align: center;
  font-size: 12px;
  line-height: 20px;
}

#numbers .current {
  color: white;
  background-color: #f60;
}

#imgs li {
  opacity: 0;
}

#imgs .current {
  opacity: 1;
}</code>```

1

2

3

4

5

1

2

3

4

5

```

When I code below, I debug in chrome devtools finding that when the index first became 4 in line index = a, then got error. I have been working on it for three hours. Help！

答:
You need to set your index back to 0 so that it can loop back

```<code>function autoPlay() {
    play = setInterval(function() {
        index = index > 4 ? index +1 : 0;
        show(index);
    }, 2000);
}
autoPlay();
</code>```

window.onload = function() {
  var numList = document.getElementById("numbers").getElementsByTagName("li");
  var imgList = document.getElementById("imgs").getElementsByTagName("li");
  var containBox = document.getElementById("box");
  var index = 0;
  var timer = play = null;

  for (var i = 0; i < numList.length; i++) {
    numList[i].index = i;
    numList[i].onmouseover = function() {
      clearInterval(timer);
      show(this.index);
    };
  }

  function show(a) {
    index = a;
    var opacity = 0;
    for (var i = 0; i < imgList.length; i++) {
      imgList[i].style.opacity = 0;
    }
    for (var i = 0; i < numList.length; i++) numList[i].className = "";
    numList[index].className = "current";
    timer = setInterval(function() {
      opacity += 2;
      imgList[index].style.opacity = opacity / 100;
      opacity == 100 && clearTimeout(timer);
    }, 20);
  }

  function autoPlay() {

    play = setInterval(function() {
      index = index < 4? index+1 : 0;
      show(index);
    }, 2000);
  }
  autoPlay();

  containBox.onmouseover = function() {
    clearInterval(play);
  }

  containBox.onmouseout = function() {
    autoPlay();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
  width: 445px;
  margin: 0 auto;
  position: relative;
}

ul,
li {
  padding: 0;
  margin: 0;
}

li {
  list-style-type: none;
}

#imgs {
  position: relative;
}

#imgs li {
  position: absolute;
  top: 0;
  left: 0;
}

#imgs img {
  width: 440px;
  height: 220px;
}

#numbers {
  position: absolute;
  right: 15px;
  top: 190px;
}

#numbers li {
  display: inline-block;
  background-color: #F90;
  width: 20px;
  height: 20px;
  border-radius: 20px;
  color: rgb(232, 227, 227);
  text-align: center;
  font-size: 12px;
  line-height: 20px;
}

#numbers .current {
  color: white;
  background-color: #f60;
}

#imgs li {
  opacity: 0;
}

#imgs .current {
  opacity: 1;
}</code>```

1

2

3

4

5

1

2

3

4

5

```

Body:
I am doing a carousel sample using JavaScript. Is there any difference between

        index++;
        index == imgList.length && (index = 0);
        show(index);

and

    index++;
    show(index);
    index == imgList.length - 1 && (index = -1);

Because the code above can work,code below cannot.
Here is all the code:

window.onload = function() {
  var numList = document.getElementById("numbers").getElementsByTagName("li");
  var imgList = document.getElementById("imgs").getElementsByTagName("li");
  var containBox = document.getElementById("box");
  var index = 0;
  var timer = play = null;

  for (var i = 0; i < numList.length; i++) {
    numList[i].index = i;
    numList[i].onmouseover = function() {
      clearInterval(timer);
      show(this.index);
    };
  }

  function show(a) {
    index = a;
    var opacity = 0;
    for (var i = 0; i < imgList.length; i++) {
      imgList[i].style.opacity = 0;
    }
    for (var i = 0; i < numList.length; i++) numList[i].className = "";
    numList[index].className = "current";
    timer = setInterval(function() {
      opacity += 2;
      imgList[index].style.opacity = opacity / 100;
      opacity == 100 && clearTimeout(timer);
    }, 20);
  }

  function autoPlay() {
    play = setInterval(function() {
      index++;
      show(index);
      index == imgList.length - 1 && (index = -1);
      //                index++;
      //                index == imgList.length && (index = 0);
      //                show(index);
    }, 2000);
  }
  autoPlay();

  containBox.onmouseover = function() {
    clearInterval(play);
  }

  containBox.onmouseout = function() {
    autoPlay();
  }
}

#box {
  width: 445px;
  margin: 0 auto;
  position: relative;
}

ul,
li {
  padding: 0;
  margin: 0;
}

li {
  list-style-type: none;
}

#imgs {
  position: relative;
}

#imgs li {
  position: absolute;
  top: 0;
  left: 0;
}

#imgs img {
  width: 440px;
  height: 220px;
}

#numbers {
  position: absolute;
  right: 15px;
  top: 190px;
}

#numbers li {
  display: inline-block;
  background-color: #F90;
  width: 20px;
  height: 20px;
  border-radius: 20px;
  color: rgb(232, 227, 227);
  text-align: center;
  font-size: 12px;
  line-height: 20px;
}

#numbers .current {
  color: white;
  background-color: #f60;
}

#imgs li {
  opacity: 0;
}

#imgs .current {
  opacity: 1;
}

1

2

3

4

5

1

2

3

4

5

When I code below, I debug in chrome devtools finding that when the index first became 4 in line index = a, then got error. I have been working on it for three hours. Help！

Body:
You need to set your index back to 0 so that it can loop back

function autoPlay() {
    play = setInterval(function() {
        index = index > 4 ? index +1 : 0;
        show(index);
    }, 2000);
}
autoPlay();

window.onload = function() {
  var numList = document.getElementById("numbers").getElementsByTagName("li");
  var imgList = document.getElementById("imgs").getElementsByTagName("li");
  var containBox = document.getElementById("box");
  var index = 0;
  var timer = play = null;

  for (var i = 0; i < numList.length; i++) {
    numList[i].index = i;
    numList[i].onmouseover = function() {
      clearInterval(timer);
      show(this.index);
    };
  }

  function show(a) {
    index = a;
    var opacity = 0;
    for (var i = 0; i < imgList.length; i++) {
      imgList[i].style.opacity = 0;
    }
    for (var i = 0; i < numList.length; i++) numList[i].className = "";
    numList[index].className = "current";
    timer = setInterval(function() {
      opacity += 2;
      imgList[index].style.opacity = opacity / 100;
      opacity == 100 && clearTimeout(timer);
    }, 20);
  }

  function autoPlay() {

    play = setInterval(function() {
      index = index < 4? index+1 : 0;
      show(index);
    }, 2000);
  }
  autoPlay();

  containBox.onmouseover = function() {
    clearInterval(play);
  }

  containBox.onmouseout = function() {
    autoPlay();
  }
}

#box {
  width: 445px;
  margin: 0 auto;
  position: relative;
}

ul,
li {
  padding: 0;
  margin: 0;
}

li {
  list-style-type: none;
}

#imgs {
  position: relative;
}

#imgs li {
  position: absolute;
  top: 0;
  left: 0;
}

#imgs img {
  width: 440px;
  height: 220px;
}

#numbers {
  position: absolute;
  right: 15px;
  top: 190px;
}

#numbers li {
  display: inline-block;
  background-color: #F90;
  width: 20px;
  height: 20px;
  border-radius: 20px;
  color: rgb(232, 227, 227);
  text-align: center;
  font-size: 12px;
  line-height: 20px;
}

#numbers .current {
  color: white;
  background-color: #f60;
}

#imgs li {
  opacity: 0;
}

#imgs .current {
  opacity: 1;
}

<div id="box">
  <ul id="imgs">
    <li class="current"><img src="01.jpg" alt="01.jpg">1</li>
    <li><img src="02.jpg" alt="02.jpg">2</li>
    <li><img src="03.jpg" alt="03.jpg">3</li>
    <li><img src="04.jpg" alt="04.jpg">4</li>
    <li><img src="05.jpg" alt="05.jpg">5</li>
  </ul>
  <ul id="numbers">
    <li class="current">1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
</div>


来源: stackexchange

问:
SIPP basic message exchange between server and client
I am trying to learn sipp, and hence to get started I was looking for the below example:

SIPP Acting as Server at one end.
   SIPP Acting as Client at the other end.

How can we achieve this? and perform Simple message exchange between server and client both simulated by SIPP.

Thanks In Advance!

答:
EXAMPLE:

Run sipp with embedded server (uas) scenario:

```<code>./sipp -sn uas
</code>```

On the same host, run sipp with embedded client (uac) scenario

```<code>./sipp -sn uac 127.0.0.1
</code>```

You can do the same if you have 2 computers/devices on the same network.
With -ifconfig (assuming you are in linux) you can find out the adress your device running the UAS (Server) scenario
The UAC needs to know IP adress of server it tries to send mesages to.
So lets say you run -ifconfig, and you get the adress 192.168.0.101 for your device that you will run UAS on, then your device that runs UAC will need to be run using

./sipp -sn uac 192.168.0.101

I would advise reading the official documentation. It is a bit confusing at first but it is the best source for learning SIPp
http://sipp.sourceforge.net/doc/reference.html

ContentLicense: CC BY-SA 3.0

Body:
EXAMPLE:

Run sipp with embedded server (uas) scenario:

./sipp -sn uas

On the same host, run sipp with embedded client (uac) scenario

./sipp -sn uac 127.0.0.1

You can do the same if you have 2 computers/devices on the same network.
With -ifconfig (assuming you are in linux) you can find out the adress your device running the UAS (Server) scenario
The UAC needs to know IP adress of server it tries to send mesages to.
So lets say you run -ifconfig, and you get the adress 192.168.0.101 for your device that you will run UAS on, then your device that runs UAC will need to be run using

./sipp -sn uac 192.168.0.101

I would advise reading the official documentation. It is a bit confusing at first but it is the best source for learning SIPp
http://sipp.sourceforge.net/doc/reference.html


问:
How to fetch all the child nodes of an XML using python?
This is my XML file

```<code><?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>
</code>```

How to pull all the child nodes of country?

For Example, I need the output as ['rank','year','gdp','neighbor']

答:
The solution using xml.etree.ElementTree module:

```<code>import xml.etree.ElementTree as ET

tree = ET.parse("yourxml.xml")
root = tree.getroot()
tag_names = {t.tag for t in root.findall('.//country/*')}

print(tag_names)  # print a set of unique tag names
</code>```

The output:

```<code>{'gdp', 'rank', 'neighbor', 'year'}
</code>```

'.//country/*' - xpath expression to extract all child elements of node country

Body:
This is my XML file

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>

How to pull all the child nodes of country?

For Example, I need the output as ['rank','year','gdp','neighbor']

Body:
The solution using xml.etree.ElementTree module:

import xml.etree.ElementTree as ET

tree = ET.parse("yourxml.xml")
root = tree.getroot()
tag_names = {t.tag for t in root.findall('.//country/*')}

print(tag_names)  # print a set of unique tag names

The output:

{'gdp', 'rank', 'neighbor', 'year'}

'.//country/*' - xpath expression to extract all child elements of node country


问:
Rails 5 fields_for nesting under a collection
So I have a model with this structure:

```<code>document {
  structure {
    id,
    ...
  },
  fields {
    field {
      id,
      ...
    },
    value {
      ...
    }
  }
}
</code>```

And I'm trying to put together a form for the fields, where the fields would look like:

```<code><input type="hidden" name="document[fields][0][field][id]" />
<input type="text" name="document[fields][0][value]" />

<input type="hidden" name="document[fields][1][field][id]" />
<input type="text" name="document[fields][1][value]" />

...
</code>```

This is what I'm currently doing:

```<code>  <%= document.fields.each_with_index do |df, i| %>
    <%= f.fields_for "fields[]", df do |builder| %>
      <p>
        <%= builder.label df.field.name %>
        <%= builder.fields_for :field do |field_builder| %>
          <%= field_builder.hidden_field :id, value: df.field.id %>
        <% end %>

        <%= builder.fields_for :value do |value_builder| %>
          <%= render df.field.edit_view, field: df.field, builder: value_builder %>
        <% end %>
      </p>
    <% end %>
  <% end %>
</code>```

But the resulting field names are:

```<code>document[fields][field][id]
document[fields][value][value]
</code>```

In other words, the indices are missing.

Using <%= builder.hidden_field :id, value: df.field.id %> results in the correct format but no index (because the field object has no id yet): document[fields][][id] but that is not an option for value, as there could be multiple fields involved.

Is there a way to do this using the form helpers, or is what I'm doing just too wonky?

Edit: Here are the models involved:

The idea is to have a configurable set of fields for document. The structure determines fields available, and a document_field is a relation between a document and a field with a value contained.

```<code>class Field < ApplicationRecord
    belongs_to :structure
end

class Document < ApplicationRecord
    belongs_to :structure
    has_many :document_fields

class DocumentField < ApplicationRecord
  belongs_to :document
  belongs_to :field

class Structure < ApplicationRecord
    has_many :fields
</code>```

答: You should configure a nested attributes setup on your models, build those nested relations on the controller, and instantiate an object in you form_for block instead of passing a referencing symbol.

Body:
So I have a model with this structure:

document {
  structure {
    id,
    ...
  },
  fields {
    field {
      id,
      ...
    },
    value {
      ...
    }
  }
}

And I'm trying to put together a form for the fields, where the fields would look like:

<input type="hidden" name="document[fields][0][field][id]" />
<input type="text" name="document[fields][0][value]" />

<input type="hidden" name="document[fields][1][field][id]" />
<input type="text" name="document[fields][1][value]" />

...

This is what I'm currently doing:

  <%= document.fields.each_with_index do |df, i| %>
    <%= f.fields_for "fields[]", df do |builder| %>

        <%= builder.label df.field.name %>
        <%= builder.fields_for :field do |field_builder| %>
          <%= field_builder.hidden_field :id, value: df.field.id %>
        <% end %>

        <%= builder.fields_for :value do |value_builder| %>
          <%= render df.field.edit_view, field: df.field, builder: value_builder %>
        <% end %>

    <% end %>
  <% end %>

But the resulting field names are:

document[fields][field][id]
document[fields][value][value]

In other words, the indices are missing.

Using <%= builder.hidden_field :id, value: df.field.id %> results in the correct format but no index (because the field object has no id yet): document[fields][][id] but that is not an option for value, as there could be multiple fields involved.

Is there a way to do this using the form helpers, or is what I'm doing just too wonky?

Edit: Here are the models involved:

The idea is to have a configurable set of fields for document. The structure determines fields available, and a document_field is a relation between a document and a field with a value contained.

class Field < ApplicationRecord
    belongs_to :structure
end

class Document < ApplicationRecord
    belongs_to :structure
    has_many :document_fields

class DocumentField < ApplicationRecord
  belongs_to :document
  belongs_to :field

class Structure < ApplicationRecord
    has_many :fields


问:
Load emacs elisp library only if it is present
I have a standard .emacs file that I want to use on multiple machines. One some of the machines I am not able to load all of my elisp libraries.

Right now, I get this error on machines where, for example, wc-mode-0.2.el is not present:

```<code>Cannot open load file: wc-mode-0.2.el
</code>```

Is there a way that I can make the .emacs file not error out at this point? Either by:

Checking to see if the library exists before I try to load it.

Catching the error condition.

答:
Both load and require have a way of no signaling an error if a file is not found.

```<code>(load FILE &optional NOERROR NOMESSAGE NOSUFFIX MUST-SUFFIX)
(require FEATURE &optional FILENAME NOERROR)
</code>```

So you can do this:

```<code>;; using load
(when (load "myfile.el" t)
       (do-my-thing))
;;using require
(when (require "myfeature" nil t)
       (do-my-thing))
</code>```

Body:
I have a standard .emacs file that I want to use on multiple machines. One some of the machines I am not able to load all of my elisp libraries.

Right now, I get this error on machines where, for example, wc-mode-0.2.el is not present:

Cannot open load file: wc-mode-0.2.el

Is there a way that I can make the .emacs file not error out at this point? Either by:

Checking to see if the library exists before I try to load it.

Catching the error condition.

Body:
Both load and require have a way of no signaling an error if a file is not found.

(load FILE &optional NOERROR NOMESSAGE NOSUFFIX MUST-SUFFIX)
(require FEATURE &optional FILENAME NOERROR)

So you can do this:

;; using load
(when (load "myfile.el" t)
       (do-my-thing))
;;using require
(when (require "myfeature" nil t)
       (do-my-thing))


问:
LINQ decimal value in query
I use:

Asp.net core

MongoDB Driver 2.4.2

I'm building a Mongo DB Linq query like hereunder:

This returns records as expected:

```<code>int.TryParse("1", out intVal);
query = query.Where(x => x.MyIntField == intVal);
</code>```

This doesn't return any records while there are records that have MyDecimalField equal to 1.0:

```<code>decimal.TryParse("1.0", out decVal);
query = query.Where(x => x.MyDecimalField == decVal);
</code>```

Does anybody have a clue why?

答:
There can be two problems

First problem can be in your culture. Decimal separator in your culture is not . (maybe it is ,).

You can use decimal separator which your culture uses.

```<code>var parsed = decimal.TryParse("1,0", out decVal); // instead of "," use your culture decimal separator

if (parsed)
{
    query = query.Where(x => x.MyDecimalField == decVal);
}
</code>```

Or try to use InvariantCulture:

```<code>var parsed = decimal.TryParse("1.0", NumberStyles.Any, CultureInfo.InvariantCulture, out decVal);

if (parsed)
{
    query = query.Where(x => x.MyDecimalField == decVal);
}
</code>```

The second problem can be in parsing some text that cannot be parsed to decimal. If this text cannot be parsed then default value of decVal is 0 and filter by Where doesn't return values with MyDecimalField == 0.

You need to check if value is parsed and if it is then you can query some data.

Title: LINQ decimal value in query

Body:
I use:

Asp.net core

MongoDB Driver 2.4.2

I'm building a Mongo DB Linq query like hereunder:

This returns records as expected:

int.TryParse("1", out intVal);
query = query.Where(x => x.MyIntField == intVal);

This doesn't return any records while there are records that have MyDecimalField equal to 1.0:

decimal.TryParse("1.0", out decVal);
query = query.Where(x => x.MyDecimalField == decVal);

Does anybody have a clue why?

Body:
There can be two problems

First problem can be in your culture. Decimal separator in your culture is not . (maybe it is ,).

You can use decimal separator which your culture uses.

var parsed = decimal.TryParse("1,0", out decVal); // instead of "," use your culture decimal separator

if (parsed)
{
    query = query.Where(x => x.MyDecimalField == decVal);
}

Or try to use InvariantCulture:

var parsed = decimal.TryParse("1.0", NumberStyles.Any, CultureInfo.InvariantCulture, out decVal);

if (parsed)
{
    query = query.Where(x => x.MyDecimalField == decVal);
}

The second problem can be in parsing some text that cannot be parsed to decimal. If this text cannot be parsed then default value of decVal is 0 and filter by Where doesn't return values with MyDecimalField == 0.

You need to check if value is parsed and if it is then you can query some data.


问:
Round to Highest Factor with Variable Scale?
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.

But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number?  For example:

```<code>num_to_scale(538.9)           // 500
num_to_scale(543123654.01234) // 5000000
</code>```

答:
My answer uses logarithm :</p>

```<code>function num_to_scale($var) {
    $nbDigits = (int)log($var,10);
    return (int)($var/10**$nbDigits)*10**$nbDigits;
}
</code>```

Body:
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.

But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number?  For example:

num_to_scale(538.9)           // 500
num_to_scale(543123654.01234) // 5000000

Body:
My answer uses logarithm :

function num_to_scale($var) {
    $nbDigits = (int)log($var,10);
    return (int)($var/10**$nbDigits)*10**$nbDigits;
}


问:
How to check if connection pools are cleared
I want to rename database file and even I use using with connection every time I have to call:

```<code>FirebirdSql.Data.FirebirdClient.FbConnection.ClearAllPools();
</code>```

The problem is that this method doesn't block the thread and I don't know how to check if all connections are cleared, because if I get value from:

```<code>FirebirdSql.Data.FirebirdClient.FbConnection.ConnectionPoolsCount
</code>```

It is zero immediately after the method, but I am still not able to rename the database file. If I set some timeout after the method (I tried 1s) then the file is not locked and I can rename it. The problem is that this timeout could be certainly different on different machines.

FWIK the only other method how to check if the file is not locked is to try the renaming in the loop with some timeout, but I can not be sure if the lock is made by connections from my application or from somewhere else.

So is there a better way, how I can wait until this method clears the connections?

答:
If I was responsible for maintaining the firebird provider, I wouldn't want users to rely on such functionality.

Other applications could have the file open (you're only in control of connection pools in the current AppDomain), and the server might be running some kind of maintenance on the database.

So even if you can wait for the pools to be cleared, I'd argue that if you really really have to mess with these files, a more robust solution is to stop the firebird service instead (and wait for it to have fully stopped).

Body:
I want to rename database file and even I use using with connection every time I have to call:

FirebirdSql.Data.FirebirdClient.FbConnection.ClearAllPools();

The problem is that this method doesn't block the thread and I don't know how to check if all connections are cleared, because if I get value from:

FirebirdSql.Data.FirebirdClient.FbConnection.ConnectionPoolsCount

It is zero immediately after the method, but I am still not able to rename the database file. If I set some timeout after the method (I tried 1s) then the file is not locked and I can rename it. The problem is that this timeout could be certainly different on different machines.

FWIK the only other method how to check if the file is not locked is to try the renaming in the loop with some timeout, but I can not be sure if the lock is made by connections from my application or from somewhere else.

So is there a better way, how I can wait until this method clears the connections?


问:
Retrieving JSON array with $.get but can't set retrieved array value outside function
If I do the following it gives me, in console.log, the values I want.

```<code>        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
                console.log(q);
            });
</code>```

But if I do this

```<code>        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
            });

        console.log(q);
</code>```

q has no value and is an undefined value? Why can't I set returnedData as public?

答:
$.get is asynchronous. You are logging before the ajax is able to finish. In other words, the var q will only have the value once the $.get receive the response from the service.

You should handle the returnedData inside the callback function. Or delegate to another function if it's too complex, like:

```<code>        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
        function(returnedData){
            doStuffWithReturnedData(returnedData);
        });
</code>```

Body:
If I do the following it gives me, in console.log, the values I want.

        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
                console.log(q);
            });

But if I do this

        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
            });

        console.log(q);

q has no value and is an undefined value? Why can't I set returnedData as public?

Body:
$.get is asynchronous. You are logging before the ajax is able to finish. In other words, the var q will only have the value once the $.get receive the response from the service.

You should handle the returnedData inside the callback function. Or delegate to another function if it's too complex, like:

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
        function(returnedData){
            doStuffWithReturnedData(returnedData);
        });


问:
Python - capture ALL tables from an HTML page
I have emails with embedded HTML tables and I have code that uses BeautifulSoup to extract the tables and the data within them, my problem is that sometimes it only succeeds in capturing one table when there are more.

The code I normally run on these table is:

```<code>with open(file_path) as in_f:
    msg = email.message_from_file(in_f)

html_msg = msg.get_payload(1)

body = html_msg.get_payload(decode=True)

html = body.decode()

table = bs4.BeautifulSoup(html).find("table")
data = [[cell.text.strip() for cell in row.find_all("td")] for row in table.find_all("tr")]
</code>```

But for this email, and some others like it, I only successfully extract the first Package. I've tried changing one line to table = bs4.BeautifulSoup(html).find_all("table") but find_all doesn't work there.

I'm a novice when it comes to BeautifulSoup so any help would be appreciated, thanks.

答:
I think I see what you are doing wrong;

if you do

```<code>table = bs4.BeautifulSoup(html).find("table")
</code>```

it returns a Tag (ie one element). If instead you do

```<code>tables = bs4.BeautifulSoup(html).find_all("table")
</code>```

it returns a ResultSet (basically a list of tables). So far so good! The problem comes in the next line, when you try to treat the ResultSet as if it were a single Tag:

```<code>... for row in tables.find_all("tr")   # Can't do this!
</code>```

tables is not a single element (which has a .find_all method), it is a list of elements (which doesn't) - hence the AttributeError. Instead, you have to iterate over each table, like so:

```<code>tables = bs4.BeautifulSoup(html).find_all("table")
data = []
for table in tables:     # <-- extra level of iteration!
    for row in table.find_all("tr"):
        data.append([cell.text.strip() for cell in row.find_all("td")])
</code>```

Hope that helps!

Body:
I have emails with embedded HTML tables and I have code that uses BeautifulSoup to extract the tables and the data within them, my problem is that sometimes it only succeeds in capturing one table when there are more.

The code I normally run on these table is:

with open(file_path) as in_f:
    msg = email.message_from_file(in_f)

html_msg = msg.get_payload(1)

body = html_msg.get_payload(decode=True)

html = body.decode()

table = bs4.BeautifulSoup(html).find("table")
data = [[cell.text.strip() for cell in row.find_all("td")] for row in table.find_all("tr")]

But for this email, and some others like it, I only successfully extract the first Package. I've tried changing one line to table = bs4.BeautifulSoup(html).find_all("table") but find_all doesn't work there.

I'm a novice when it comes to BeautifulSoup so any help would be appreciated, thanks.

Body:
I think I see what you are doing wrong;

if you do

table = bs4.BeautifulSoup(html).find("table")

it returns a Tag (ie one element). If instead you do

tables = bs4.BeautifulSoup(html).find_all("table")

it returns a ResultSet (basically a list of tables). So far so good! The problem comes in the next line, when you try to treat the ResultSet as if it were a single Tag:

... for row in tables.find_all("tr")   # Can't do this!

tables is not a single element (which has a .find_all method), it is a list of elements (which doesn't) - hence the AttributeError. Instead, you have to iterate over each table, like so:

tables = bs4.BeautifulSoup(html).find_all("table")
data = []
for table in tables:     # <-- extra level of iteration!
    for row in table.find_all("tr"):
        data.append([cell.text.strip() for cell in row.find_all("td")])

Hope that helps!


问:
Changing css dynamically without reloading page in Angular2
I have a side navigation bar, wherein there is progress bar in each nav.
This is modular structure-

```<code>MainFile
   -Children1
       -children1.html
       -children1.component.ts
  -Children2
       -children2.html
       -children2.component.ts
  -Children3
       -children3.html
       -children3.component.ts
  -ProgressIndicator
       -progressIndicator.html
       -progressIndicator.component.ts
  -main.html
  -main.component.ts
</code>```

Inside progressIndicator.html, I have this code,

```<code> <div class="progress">
    <div [ngStyle]="{'width':getProgress()}" class="progress-bar" role="progressbar" aria-
       valuenow="70" aria-valuemin="0" aria-valuemax="100">
       <span class="sr-only">70% Complete</span>
   </div>
</code>```

And my progressIndicator.component.ts

```<code>currentPage = '';
progressBar = '';
//getting current route name using 'this.route.url' and updating 'currentPage' property in
constructor.
getProgress(){
   if(currentPage  === 'children1'){
         return progressBar = '25%';
     }
   if(currentPage  === 'children2'){
        return progressBar = '50%';
    }
}
</code>```

I am successfully getting the current page, as 'children1.html' or 'children2.html', based on the current page I want to change the width of div with class 'progress-bar', I used

```<code>[ngStyle]="{width:getProgress()}"
</code>```

but it takes effect ONLY if page reloads, which angular2 being SPA doesn't happen.
Do help me in finding a better way that when I move from 'children1' to 'children2', the 'getProgress()' takes effect and changes the style.

答:
You should return the whole style object from a method:

Component

```<code>getStyle():any{
    return { width: getProgress() };
}
</code>```

Template:

```<code>[ngStyle]="getStyle()";
</code>```

This way, the whole getStyle method will be called upon change detection, which should update your style even if you don't reload (because, as you said, you should never have to reload).

Body:
I have a side navigation bar, wherein there is progress bar in each nav.
This is modular structure-

MainFile
   -Children1
       -children1.html
       -children1.component.ts
  -Children2
       -children2.html
       -children2.component.ts
  -Children3
       -children3.html
       -children3.component.ts
  -ProgressIndicator
       -progressIndicator.html
       -progressIndicator.component.ts
  -main.html
  -main.component.ts

Inside progressIndicator.html, I have this code,

       70% Complete

And my progressIndicator.component.ts

currentPage = '';
progressBar = '';
//getting current route name using 'this.route.url' and updating 'currentPage' property in
constructor.
getProgress(){
   if(currentPage  === 'children1'){
         return progressBar = '25%';
     }
   if(currentPage  === 'children2'){
        return progressBar = '50%';
    }
}

I am successfully getting the current page, as 'children1.html' or 'children2.html', based on the current page I want to change the width of div with class 'progress-bar', I used

[ngStyle]="{width:getProgress()}"

but it takes effect ONLY if page reloads, which angular2 being SPA doesn't happen.
Do help me in finding a better way that when I move from 'children1' to 'children2', the 'getProgress()' takes effect and changes the style.

Body:
You should return the whole style object from a method:

Component

getStyle():any{
    return { width: getProgress() };
}

Template:

[ngStyle]="getStyle()";

This way, the whole getStyle method will be called upon change detection, which should update your style even if you don't reload (because, as you said, you should never have to reload).


问:
c++ algorithm to select two random numbers from a range, with minimal distance
I have an std::vector initialized with numbers from 1 to 100

```<code>std::vector<int> vec;
for(int i = 1; i < 101; i++)
  vec.push_back(i);
</code>```

I want to select two random integers that have a minimal distance (for example minimal distance can be 10).

If num1, num2 are the numbers:

num2 - num1 > distance

I am using the following method to select a random integer between ranges:

```<code>int getRandomValue(int from, int to)
        {
                std::random_device seeder;
                std::mt19937 engine(seeder());
                std::uniform_int_distribution<int> dist(from, to);
                return dist(engine);
        }
</code>```

How can I generate num2 and num1?

答:
You may use something like the following:

```<code>num1 = getRandomValue(minRange, maxRange - distance - 1);
num2 = getRandomValue(num1 + distance + 1, maxRange);
</code>```

Note though that it would not be an uniform distribution for the pair result.

Body:
I have an std::vector initialized with numbers from 1 to 100

std::vector<int> vec;
for(int i = 1; i < 101; i++)
  vec.push_back(i);

I want to select two random integers that have a minimal distance (for example minimal distance can be 10).

If num1, num2 are the numbers:

num2 - num1 > distance

I am using the following method to select a random integer between ranges:

int getRandomValue(int from, int to)
        {
                std::random_device seeder;
                std::mt19937 engine(seeder());
                std::uniform_int_distribution<int> dist(from, to);
                return dist(engine);
        }

How can I generate num2 and num1?

Body:
You may use something like the following:

num1 = getRandomValue(minRange, maxRange - distance - 1);
num2 = getRandomValue(num1 + distance + 1, maxRange);

Note though that it would not be an uniform distribution for the pair result.


问:
Powershell - parsing through JSON to create CSV
I am extracting a JSON from Facebook, this is what it looks like:

```<code>pressions_by_paid_non_paid_unique/day
{
  "data": [
    {
      "name": "page_impressions_by_paid_non_paid_unique",
  "period": "day",
  "values": [
    {
      "value": {
        "total": 549215,
        "unpaid": 549215,
        "paid": 0
      },
      "end_time": "2017-06-02T07:00:00+0000"
    },
</code>```

What I would like is to create a CSV that would either looks like this:

total,unpaid,paid,endtime

  549215,549215,0,2017-06-02T07:00:00+0000

or

value,num,end_time

total,549215,2017-06-02T07:00:00+0000

unpaid,549215,2017-06-02T07:00:00+0000

paid,0,2017-06-02T07:00:00+0000

What I came up with is:

```<code>$file = "D:\BI_LP\001-Solutions_Sources\script\Powershell\curl\facebook21.json"
Get-Content $file -Raw |
ConvertFrom-Json |
Select -Expand data |
Select -Expand values | % {
$end_time = $_.end_time
$value = $_.value
$_.value | select @{n='end_time';e={$end_time}}, @{n='value';e={$value}}
}
</code>```

Which gives me:

```<code>end_time                 value

--------                 -----

2017-05-21T07:00:00+0000 @{total=608837; unpaid=608837; paid=0}

2017-05-22T07:00:00+0000 @{total=682090; unpaid=682090; paid=0}

2017-05-23T07:00:00+0000 @{total=885274; unpaid=885274; paid=0}

2017-05-24T07:00:00+0000 @{total=810845; unpaid=810845; paid=0}

2017-05-25T07:00:00+0000 @{total=755453; unpaid=755453; paid=0}

2017-05-26T07:00:00+0000 @{total=629096; unpaid=629096; paid=0}
</code>```

Does anyone have any suggestions?

答:
Based on your code:

```<code>@"
{
    "data": [
    {
        "name": "page_impressions_by_paid_non_paid_unique",
        "period": "day",
        "values": [
        {
            "value": {
            "total": 549215,
            "unpaid": 549215,
            "paid": 0
        },
        "end_time": "2017-06-02T07:00:00+0000"
        }
        ]
    }
    ]
}
"@ | ConvertFrom-Json | Select -Expand data | Select -Expand values | % {
    $end_time = $_.end_time
    $value = $_.value
    $_.value | select @{n='endtime'; e={$value.total}}, @{n='unpaid'; e={$value.unpaid}}, @{n='paid'; e={$value.paid}}, @{n='end_time';e={$end_time}}
} | ft -autosize
</code>```

Gives the following output:

```<code>endtime unpaid paid end_time
------- ------ ---- --------
 549215 549215    0 2017-06-02T07:00:00+0000
</code>```

And to export to csv, change the ft -autosize to Export-Csv -Path c:\...

FYI: Your json sample is missing a lot of closing brackets.

Body:
I am extracting a JSON from Facebook, this is what it looks like:

pressions_by_paid_non_paid_unique/day
{
  "data": [
    {
      "name": "page_impressions_by_paid_non_paid_unique",
  "period": "day",
  "values": [
    {
      "value": {
        "total": 549215,
        "unpaid": 549215,
        "paid": 0
      },
      "end_time": "2017-06-02T07:00:00+0000"
    },

What I would like is to create a CSV that would either looks like this:

total,unpaid,paid,endtime

  549215,549215,0,2017-06-02T07:00:00+0000

or

value,num,end_time

total,549215,2017-06-02T07:00:00+0000

unpaid,549215,2017-06-02T07:00:00+0000

paid,0,2017-06-02T07:00:00+0000

What I came up with is:

$file = "D:\BI_LP\001-Solutions_Sources\script\Powershell\curl\facebook21.json"
Get-Content $file -Raw |
ConvertFrom-Json |
Select -Expand data |
Select -Expand values | % {
$end_time = $_.end_time
$value = $_.value
$_.value | select @{n='end_time';e={$end_time}}, @{n='value';e={$value}}
}

Which gives me:

end_time                 value

--------                 -----

2017-05-21T07:00:00+0000 @{total=608837; unpaid=608837; paid=0}

2017-05-22T07:00:00+0000 @{total=682090; unpaid=682090; paid=0}

2017-05-23T07:00:00+0000 @{total=885274; unpaid=885274; paid=0}

2017-05-24T07:00:00+0000 @{total=810845; unpaid=810845; paid=0}

2017-05-25T07:00:00+0000 @{total=755453; unpaid=755453; paid=0}

2017-05-26T07:00:00+0000 @{total=629096; unpaid=629096; paid=0}

Does anyone have any suggestions?

Body:
Based on your code:

@"
{
    "data": [
    {
        "name": "page_impressions_by_paid_non_paid_unique",
        "period": "day",
        "values": [
        {
            "value": {
            "total": 549215,
            "unpaid": 549215,
            "paid": 0
        },
        "end_time": "2017-06-02T07:00:00+0000"
        }
        ]
    }
    ]
}
"@ | ConvertFrom-Json | Select -Expand data | Select -Expand values | % {
    $end_time = $_.end_time
    $value = $_.value
    $_.value | select @{n='endtime'; e={$value.total}}, @{n='unpaid'; e={$value.unpaid}}, @{n='paid'; e={$value.paid}}, @{n='end_time';e={$end_time}}
} | ft -autosize

Gives the following output:

endtime unpaid paid end_time
------- ------ ---- --------
 549215 549215    0 2017-06-02T07:00:00+0000

And to export to csv, change the ft -autosize to Export-Csv -Path c:\...

FYI: Your json sample is missing a lot of closing brackets.


问:
how to check vbs script in windows is running or not?
I have created a VBS script in Windows. I will run this script to get size of a file.

I made this to run for ever. (even this is my requirement).

How should I know if it is running or stopped?

```<code>------ Exact Script starts here -----
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO_check=CreateObject("Scripting.FileSystemObject")
do while infiniteLoop=0
----- This code is lasting for ever ----
Loop
</code>```

Am i clear in my ques?

答:
@nimizen answer is not correct. If you have another wscript running, it will return that your script is already running.

@h pic answer is correct, but I get an error with the "a" array in my windows. So I changed it a little and cleaned to work.

```<code>Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("select * from win32_process where name = 'wscript.exe'")

i = 0
For Each objProcess in colProcesses
    if not (IsNull(objProcess.CommandLine )) then
            strScriptName = Trim(Right(objProcess.CommandLine,Len(objProcess.CommandLine) - InstrRev(objProcess.CommandLine,"\")))
            strScriptName = Left(strScriptName, Len(strScriptName) - 1)
            if strScriptName = Wscript.ScriptName then
                i=i+1
            end if
            if i > 1 then 'if > 1 wscript instance
                    'Wscript.Echo "Duplicate :"&strScriptName&" ."
                    Wscript.Quit
            end if
    end if
Next

'Wscript.Echo "Pause 2 have 2 scripts running ."
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a VBS script in Windows. I will run this script to get size of a file.

I made this to run for ever. (even this is my requirement).

How should I know if it is running or stopped?

------ Exact Script starts here -----
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO_check=CreateObject("Scripting.FileSystemObject")
do while infiniteLoop=0
----- This code is lasting for ever ----
Loop

Am i clear in my ques?

Body:
@nimizen answer is not correct. If you have another wscript running, it will return that your script is already running.

@h pic answer is correct, but I get an error with the "a" array in my windows. So I changed it a little and cleaned to work.

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("select * from win32_process where name = 'wscript.exe'")

i = 0
For Each objProcess in colProcesses
    if not (IsNull(objProcess.CommandLine )) then
            strScriptName = Trim(Right(objProcess.CommandLine,Len(objProcess.CommandLine) - InstrRev(objProcess.CommandLine,"\")))
            strScriptName = Left(strScriptName, Len(strScriptName) - 1)
            if strScriptName = Wscript.ScriptName then
                i=i+1
            end if
            if i > 1 then 'if > 1 wscript instance
                    'Wscript.Echo "Duplicate :"&strScriptName&" ."
                    Wscript.Quit
            end if
    end if
Next

'Wscript.Echo "Pause 2 have 2 scripts running ."


问:
Make return type of parent class to be covariant
I have following class hierarchy:

public class Node<T extends Comparable>
{
  private T element;
  private Node<T> rightChild;
  private Node<T> leftChild;

  public Node(T element)
  {
    this.element = element;
  }

  public Node()
  {
  }

  public T getElement()
  {
    return element;
  }

  public void setElement(T element)
  {
    this.element = element;
  }

  public Node<T> getRightChild()
  {
    return rightChild;
  }

  public void setRightChild(Node<T> rightChild)
  {
    this.rightChild = rightChild;
  }

  public Node<T> getLeftChild()
  {
    return leftChild;
  }

  public void setLeftChild(Node<T> leftChild)
  {
    this.leftChild = leftChild;
  }
}

public class RedBlackNode<T extends Comparable> extends Node<T>
{
  public RedBlackNode(T element)
  {
    super(element);
    this.isRed = true;
  }

  private boolean isRed;

  public boolean isRed()
  {
    return isRed;
  }

  public void setRed(boolean red)
  {
    isRed = red;
  }

  @Override
  public RedBlackNode<T> getRightChild()
  {
    return (RedBlackNode<T>) super.getRightChild();
  }

  @Override
  public RedBlackNode<T> getLeftChild()
  {
    return (RedBlackNode<T>) super.getLeftChild();
  }
}
```

Is it possible in child class RedBlackNode use method getRightChild so it will return RedBlackNode and not the parent Node? One possible solution for me is to override this method in RedBlackNode but are there any more elegant ways to do that?

Update
I added code how it will look with overriding but not sure if there are any scope for improvements:)

答:
My opinion common interface for all the tree node type and specialize will implement the common interface.If required the client api can call to specialized method by typecast</p>

```<code>public interface TreeNode<V> {

    public V getValue();

    public TreeNode<V> getLeftChield();

    public TreeNode<V> getRightChield();
   public void setLeftChield(TreeNode<V> treeNode);

public void setRightChield(TreeNode<V> treeNode);
}
class Node<V> implements TreeNode<V> {

        V value;
        int count;
        TreeNode<V> left;
        TreeNode<V> right;
        TreeNode<V> parent;

        public Node(V value, TreeNode<V> parent) {
            this.value = value;
            this.parent = parent;
        }

        public V getValue() {
            return value;
        }

        public TreeNode<V> getLeftChield() {
            return left;
        }

        public TreeNode<V> getRightChield() {
            return right;
        }

        public void setLeftChield(TreeNode<V> leftNode) {
            left = leftNode;
        }

        public void setRightChield(TreeNode<V> rightNode) {
            right = rightNode;
        }

    }
</code>```

Body:
I have following class hierarchy:

public class Node<T extends Comparable>
{
  private T element;
  private Node<T> rightChild;
  private Node<T> leftChild;

  public Node(T element)
  {
    this.element = element;
  }

  public Node()
  {
  }

  public T getElement()
  {
    return element;
  }

  public void setElement(T element)
  {
    this.element = element;
  }

  public Node<T> getRightChild()
  {
    return rightChild;
  }

  public void setRightChild(Node<T> rightChild)
  {
    this.rightChild = rightChild;
  }

  public Node<T> getLeftChild()
  {
    return leftChild;
  }

  public void setLeftChild(Node<T> leftChild)
  {
    this.leftChild = leftChild;
  }
}

public class RedBlackNode<T extends Comparable> extends Node<T>
{
  public RedBlackNode(T element)
  {
    super(element);
    this.isRed = true;
  }

  private boolean isRed;

  public boolean isRed()
  {
    return isRed;
  }

  public void setRed(boolean red)
  {
    isRed = red;
  }

  @Override
  public RedBlackNode<T> getRightChild()
  {
    return (RedBlackNode<T>) super.getRightChild();
  }

  @Override
  public RedBlackNode<T> getLeftChild()
  {
    return (RedBlackNode<T>) super.getLeftChild();
  }
}

Is it possible in child class RedBlackNode use method getRightChild so it will return RedBlackNode and not the parent Node? One possible solution for me is to override this method in RedBlackNode but are there any more elegant ways to do that?

Update
I added code how it will look with overriding but not sure if there are any scope for improvements:)

Body:
My opinion common interface for all the tree node type and specialize will implement the common interface.If required the client api can call to specialized method by typecast

public interface TreeNode<V> {

    public V getValue();

    public TreeNode<V> getLeftChield();

    public TreeNode<V> getRightChield();
   public void setLeftChield(TreeNode<V> treeNode);

public void setRightChield(TreeNode<V> treeNode);
}
class Node<V> implements TreeNode<V> {

        V value;
        int count;
        TreeNode<V> left;
        TreeNode<V> right;
        TreeNode<V> parent;

        public Node(V value, TreeNode<V> parent) {
            this.value = value;
            this.parent = parent;
        }

        public V getValue() {
            return value;
        }

        public TreeNode<V> getLeftChield() {
            return left;
        }

        public TreeNode<V> getRightChield() {
            return right;
        }

        public void setLeftChield(TreeNode<V> leftNode) {
            left = leftNode;
        }

        public void setRightChield(TreeNode<V> rightNode) {
            right = rightNode;
        }

    }


问:
Is there any value in including SQLite in VCS's
Having an argument with my team. We are developing an application using SQLite and some want to add it to the repo (GIT) and some don't. Previously with RDBMS system there has been no perceived benefit of using VCS on the DB. However SQLite is a self contained file with no external dependencies so i assume, even though it is binary, that a commit of the project code + the SQLite  file will give an accurate snapshot of the state of play at that point.

I also assume that a branch and merge would work as well.

Has anyone actually done this and if so does it work?

答: You'd get more benefit from GIT's versioning facilities if you stored a dump of the SQLite database (i.e. commands required to create it) rather than the database file itself. That way you could look at the history of the dump file and see tables or data being added etc.</p>

ContentLicense: CC BY-SA 2.5


问:
indexing table rows js/jquery
I've been tryin to index my table rows but unsuccessfully. The best I could do was come up with the code the could maybe reindex every row in the table everytime i add new table row, but it doesnt work. I think something is wrong with syntax, but I'm not sure what. JS part:

```<code>$("#pridet").click(function(){
  $("table tbody tr").first().clone().prependTo("table tbody");
  var x = document.getElementsByTagName("tr");
  document.getElementsByName("tabelis").innerHTML = x.rowIndex;
});
</code>```

I realise something is fatally wrong with the second part (like directing where to write what index maybe?)

code on html file:

```<code><button id = "pridet">pridet</button>
  <table id="myTable" class="table table-inverse">
    <thead id = "headings" class = "thead-default">
      <tr>
        <th>Tabelio Nr.</th>
        <th>Vardas</th>
        <th>Pavardė</th>
        <th>Pareigos</th>
        <th>Bazinė alga, €</th>
        <th>Valandinis atlyginimas, €</th>
        <th>Veiksmai</th>
      </tr>
    </thead>
    <tfoot class = "thead-default">
      <tr>
        <td>Vidurkis</td>
        <td></td>
        <td></td>
        <td></td>
        <td>10000</td>
        <td>17.3</td>
        <td></td>
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <td class = "tabelis">1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td>bla</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        <td>
          <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p>
          <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr>
        <td class = "tabelis">2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td>bla</td>
        <td>blum</td>
        <td>
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
      </tr>
      <tr>
        <td class = "tabelis">3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
        <td>bla</td>
        <td>blum</td>
        <td>
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
      </tr>
    </tbody>
  </table>
  <script src="script.js" charset="utf-8"></script>
  <script>
    function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("myTable").deleteRow(i);
  };
  </script>
</code>```

I could probably count the total number of rows with something like this

```<code>$("#counter").text( $("table tbody tr").length );
</code>```

and use the value to insert numbers into table cells somehow

EDIT: didnt mention this before, but table rows have to eb added at the top of the table (below thead)

答:
Because you have the row index in the first column of body row you can select each one with:

```<code>$('#myTable tbody tr td:nth-child(1)')
</code>```

and you can cycle using .each() to iterate on every index in order to update it.

function updateRowIndex() {
    $('#myTable tbody tr td:nth-child(1)').each(function(idx, ele) {
        ele.textContent = idx + 1;
    });
}

function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("myTable").deleteRow(i);
    updateRowIndex();
};

$("#pridet").on('click', function(e) {
    $("table tbody tr").first().clone().prependTo("table tbody");
    var x = document.getElementsByTagName("tr");
    document.getElementsByName("tabelis").innerHTML = x.rowIndex;
    updateRowIndex();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id = "pridet">pridet</button>
<table id="myTable" class="table table-inverse">
    <thead id = "headings" class = "thead-default">
    <tr>
        <th>Tabelio Nr.</th>
        <th>Vardas</th>
        <th>Pavardė</th>
        <th>Pareigos</th>
        <th>Bazinė alga, €</th>
        <th>Valandinis atlyginimas, €</th>
        <th>Veiksmai</th>
    </tr>
    </thead>
    <tfoot class = "thead-default">
    <tr>
        <td>Vidurkis</td>
        <td></td>
        <td></td>
        <td></td>
        <td>10000</td>
        <td>17.3</td>
        <td></td>
    </tr>
    </tfoot>
    <tbody>
    <tr>
        <td class = "tabelis">1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td>bla</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        <td>
            <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p>
            <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
    </tr>
    <tr>
        <td class = "tabelis">2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td>bla</td>
        <td>blum</td>
        <td>
            <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
            <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
    </tr>
    <tr>
        <td class = "tabelis">3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
        <td>bla</td>
        <td>blum</td>
        <td>
            <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
            <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
    </tr>
    </tbody>
</table></code>```

Title: indexing table rows js/jquery

Body:
I've been tryin to index my table rows but unsuccessfully. The best I could do was come up with the code the could maybe reindex every row in the table everytime i add new table row, but it doesnt work. I think something is wrong with syntax, but I'm not sure what. JS part:

$("#pridet").click(function(){
  $("table tbody tr").first().clone().prependTo("table tbody");
  var x = document.getElementsByTagName("tr");
  document.getElementsByName("tabelis").innerHTML = x.rowIndex;
});

I realise something is fatally wrong with the second part (like directing where to write what index maybe?)

code on html file:

<button id = "pridet">pridet</button>

        Tabelio Nr.
        Vardas
        Pavardė
        Pareigos
        Bazinė alga, €
        Valandinis atlyginimas, €
        Veiksmai

        Vidurkis

        10000
        17.3

        1
        Mark
        Otto
        @mdo
        bla
        <input type="button" value="Delete" onclick="deleteRow(this)">

        2
        Jacob
        Thornton
        @fat
        bla
        blum

        3
        Larry
        the Bird
        @twitter
        bla
        blum

I could probably count the total number of rows with something like this

$("#counter").text( $("table tbody tr").length );

and use the value to insert numbers into table cells somehow

EDIT: didnt mention this before, but table rows have to eb added at the top of the table (below thead)

Body:
Because you have the row index in the first column of body row you can select each one with:

$('#myTable tbody tr td:nth-child(1)')

and you can cycle using .each() to iterate on every index in order to update it.

function updateRowIndex() {
    $('#myTable tbody tr td:nth-child(1)').each(function(idx, ele) {
        ele.textContent = idx + 1;
    });
}

function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("myTable").deleteRow(i);
    updateRowIndex();
};

$("#pridet").on('click', function(e) {
    $("table tbody tr").first().clone().prependTo("table tbody");
    var x = document.getElementsByTagName("tr");
    document.getElementsByName("tabelis").innerHTML = x.rowIndex;
    updateRowIndex();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id = "pridet">pridet</button>
<table id="myTable" class="table table-inverse">
    <thead id = "headings" class = "thead-default">
    <tr>
        <th>Tabelio Nr.</th>
        <th>Vardas</th>
        <th>Pavardė</th>
        <th>Pareigos</th>
        <th>Bazinė alga, €</th>
        <th>Valandinis atlyginimas, €</th>
        <th>Veiksmai</th>
    </tr>
    </thead>
    <tfoot class = "thead-default">
    <tr>
        <td>Vidurkis</td>
        <td></td>
        <td></td>
        <td></td>
        <td>10000</td>
        <td>17.3</td>
        <td></td>
    </tr>
    </tfoot>
    <tbody>
    <tr>
        <td class = "tabelis">1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td>bla</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        <td>
            <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p>
            <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
    </tr>
    <tr>
        <td class = "tabelis">2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td>bla</td>
        <td>blum</td>
        <td>
            <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
            <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
    </tr>
    <tr>
        <td class = "tabelis">3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
        <td>bla</td>
        <td>blum</td>
        <td>
            <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
            <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
    </tr>
    </tbody>
</table>


问:
Modifying Tomcat Connector settings on Heroku
The Heroku's webapp-runner.jar runs on Tomcat and the default Tomcat maxPostSize is 2MB. I need to increase this value but have no idea how can I do that.

I see no parameter for this setting in https://github.com/jsimone/webapp-runner#options (this is the runner to which official Heroku documentation points to). There is a maxPostSize connector option in the Tomcat documentation (https://tomcat.apache.org/tomcat-8.5-doc/config/http.html ) but I have no idea how can I pass it to webapp-runner.

In act of desperation I tried setting --maxPostSize in WEBAPP_RUNNER_OPTS but when I start the app I am getting:

```<code>  Exception in thread "main" com.beust.jcommander.ParameterException:
  Unknown option: --maxPostSize=8388608
</code>```

Although I am trying to increase max post size, this question is relevant to any other Tomcat Connector parameter.

答:
The solution is:

```<code> heroku config:set WEBAPP_RUNNER_OPTS="-AmaxPostSize=12582912"
</code>```

You must have a relatively recent version of webrunner referenced, though .

Body:
The Heroku's webapp-runner.jar runs on Tomcat and the default Tomcat maxPostSize is 2MB. I need to increase this value but have no idea how can I do that.

I see no parameter for this setting in https://github.com/jsimone/webapp-runner#options (this is the runner to which official Heroku documentation points to). There is a maxPostSize connector option in the Tomcat documentation (https://tomcat.apache.org/tomcat-8.5-doc/config/http.html ) but I have no idea how can I pass it to webapp-runner.

In act of desperation I tried setting --maxPostSize in WEBAPP_RUNNER_OPTS but when I start the app I am getting:

  Exception in thread "main" com.beust.jcommander.ParameterException:
  Unknown option: --maxPostSize=8388608

Although I am trying to increase max post size, this question is relevant to any other Tomcat Connector parameter.

Body:
The solution is:

 heroku config:set WEBAPP_RUNNER_OPTS="-AmaxPostSize=12582912"

You must have a relatively recent version of webrunner referenced, though .


问:
How can I disable lazy loading of active record queries?
I want to query some objects from the database using a WHERE clause similar to the following:

```<code>@monuments =  Monument.where("... lots of SQL ...").limit(6)
</code>```

Later on, in my view I use methods like @monuments.first, then I loop through @monuments, then I display @monuments.count.

When I look at the Rails console, I see that Rails queries the database multiple times, first with a limit of 1 (for @monuments.first), then with a limit of 6 (for looping through all of them), and finally it issues a count() query.

How can I tell ActiveRecord to only execute the query once? Just executing the query once with a limit of 6 should be enough to get all the data I need. Since the query is slow (80ms), repeating it costs a lot of time.

答:
In your situation you'll want to trigger the query before you your call to first because while first is a method on Array, it's also a “finder method” on ActiveRecord objects that'll fetch the first record.

You can prompt this with any method that requires data to work with. I prefer using to_a since it's clear that we'll be dealing with an array after:

```<code>@moments = Moment.where(foo: true).to_a
# SQL Query Executed
@moments.first #=> (Array#first) <Moment @foo=true>
@moments.count #=> (Array#count) 42
</code>```

In this case, you can also use first(6) in place of limit(6), which will also trigger the query. It may be less obvious to another developer on your team that this is intentional, however.

Body:
I want to query some objects from the database using a WHERE clause similar to the following:

@monuments =  Monument.where("... lots of SQL ...").limit(6)

Later on, in my view I use methods like @monuments.first, then I loop through @monuments, then I display @monuments.count.

When I look at the Rails console, I see that Rails queries the database multiple times, first with a limit of 1 (for @monuments.first), then with a limit of 6 (for looping through all of them), and finally it issues a count() query.

How can I tell ActiveRecord to only execute the query once? Just executing the query once with a limit of 6 should be enough to get all the data I need. Since the query is slow (80ms), repeating it costs a lot of time.

Body:
In your situation you'll want to trigger the query before you your call to first because while first is a method on Array, it's also a “finder method” on ActiveRecord objects that'll fetch the first record.

You can prompt this with any method that requires data to work with. I prefer using to_a since it's clear that we'll be dealing with an array after:

@moments = Moment.where(foo: true).to_a
# SQL Query Executed
@moments.first #=> (Array#first) <Moment @foo=true>
@moments.count #=> (Array#count) 42

In this case, you can also use first(6) in place of limit(6), which will also trigger the query. It may be less obvious to another developer on your team that this is intentional, however.


问:
Django OneToMany Field with predefined Models
I'd like to make a OneToMany-relationship between one of my models and the builtin Permission model of django.contrib.auth.models.

My plan is to create at least one new permission when my model is created and delete this/these permissions when the model is deleted.

When it comes to Many-to-one relations the documentation recommends using a ForeignKey (https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_one/). But if I get this right, I would need (theoretically) to add a ForeignKey to the Permission model.

Am I on the wrong way? What would be the best practice to implement this?

答:
Django provides ManytoOne relationship through ForeignKey, which specifies a dual way relationship, however it needs to be specified in on of the models only.
Intuitively if your model should be related to various Permission models, in the latter your need to specify rel = models.ForeignKey(YourModelClassName).

In this case you tell django that many instances of Permission can be related to a single YourModel instance.

Hope this helps.


问:
how send a json request to api server by angular4?
How do I send a request to an API service by using formBuilder in Angular 4 that sends (POST) a JSON file like below to the server ?:

```<code>{
  "Password": "sample string 1",
  "Identity": {
    "LastName": "sample string 1",
    "FirstName": "sample string 2",
    "NationalCode": "sample string 3",

  }
}
</code>```

I've written the code below but, it doesn't work and the error is : asyncValidator":null

```<code>registerForm: FormGroup = this.builder.group({
    Password : this.Password ,
    Identity : {
      LastName : this.LastName,
      FirstName : this.FirstName,

    },
  },
</code>```

答:
You should use httpClient for this purpose.

Please check docs: Use an HTTP Client to talk to a remote server

Body:
How do I send a request to an API service by using formBuilder in Angular 4 that sends (POST) a JSON file like below to the server ?:

{
  "Password": "sample string 1",
  "Identity": {
    "LastName": "sample string 1",
    "FirstName": "sample string 2",
    "NationalCode": "sample string 3",

  }
}

I've written the code below but, it doesn't work and the error is : asyncValidator":null

registerForm: FormGroup = this.builder.group({
    Password : this.Password ,
    Identity : {
      LastName : this.LastName,
      FirstName : this.FirstName,

    },
  },


问:
hadoop jar error while copying data from mongoDB to hdfs
I am trying to copy collection from mongodb to hadoop using HadoopMongodb connector
using the code below :
package hdfs;

```<code>import java.io.*;
import org.apache.commons.logging.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.lib.output.*;
import org.apache.hadoop.mapreduce.*;
import org.bson.*;
import com.mongodb.hadoop.*;
import com.mongodb.hadoop.util.*;

public class ImportWeblogsFromMongo {
    private static final Log log = LogFactory.getLog(ImportWeblogsFromMongo.class);

    public static class ReadWeblogsFromMongo extends Mapper<Object, BSONObject, Text, Text> {
        public void map(Object key, BSONObject value, Context context) throws IOException, InterruptedException {
            System.out.println("Key: " + key);
            System.out.println("Value: " + value);
            String md5 = value.get("md5").toString();
            String url = value.get("url").toString();
            String date = value.get("date").toString();
            String time = value.get("time").toString();
            String ip = value.get("ip").toString();
            String output = "\t" + url + "\t" + date + "\t" + time + "\t" + ip;
            context.write(new Text(md5), new Text(output));
        }
    }

    public static void main(String[] args) throws Exception {
        final Configuration conf = new Configuration();
        MongoConfigUtil.setInputURI(conf,"mongodb://localhost:27017/clusterdb.fish");
        MongoConfigUtil.setCreateInputSplits(conf, false);
        System.out.println("Configuration: " + conf);
        @SuppressWarnings("deprecation")
        final Job job = new Job(conf, "Mongo Import");
        Path out = new Path("/home/mongo_import");
        FileOutputFormat.setOutputPath(job, out);
        job.setJarByClass(ImportWeblogsFromMongo.class);
        job.setMapperClass(ReadWeblogsFromMongo.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setInputFormatClass(MongoInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        job.setNumReduceTasks(0);
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
    }
</code>```

1. After exporting the Jar file named importmongo.jar
 2. I tried to execute this command hadoop jar /home/yass/importmongo.jar hdfs.ImportWeblogsFromMongo but i got the following error:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/hadoop/util/MongoConfigUtil
    at hdfs.ImportWeblogsFromMongo.main(ImportWeblogsFromMongo.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by: java.lang.ClassNotFoundException: com.mongodb.hadoop.util.MongoConfigUtil
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more
</code>```

NB:clustedb is the database name and fish its collection
and hdfs.ImportWeblogsFromMongo  is package.class

Any suggestions please

答:
I didn't resolve the issue this way but i found solution using Mongodump by copying the file to Hdfs ,the lines below it may help someone to get the job done

```<code>   mongodump  --db clusterdb --collection CollectionName

   bsondump file.bson > file.json

   hadoop dfs -copyFromLocal /path/to/file/fish.json mongo
</code>```

Body:
I am trying to copy collection from mongodb to hadoop using HadoopMongodb connector
using the code below :
package hdfs;

import java.io.*;
import org.apache.commons.logging.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.lib.output.*;
import org.apache.hadoop.mapreduce.*;
import org.bson.*;
import com.mongodb.hadoop.*;
import com.mongodb.hadoop.util.*;

public class ImportWeblogsFromMongo {
    private static final Log log = LogFactory.getLog(ImportWeblogsFromMongo.class);

    public static class ReadWeblogsFromMongo extends Mapper<Object, BSONObject, Text, Text> {
        public void map(Object key, BSONObject value, Context context) throws IOException, InterruptedException {
            System.out.println("Key: " + key);
            System.out.println("Value: " + value);
            String md5 = value.get("md5").toString();
            String url = value.get("url").toString();
            String date = value.get("date").toString();
            String time = value.get("time").toString();
            String ip = value.get("ip").toString();
            String output = "\t" + url + "\t" + date + "\t" + time + "\t" + ip;
            context.write(new Text(md5), new Text(output));
        }
    }

    public static void main(String[] args) throws Exception {
        final Configuration conf = new Configuration();
        MongoConfigUtil.setInputURI(conf,"mongodb://localhost:27017/clusterdb.fish");
        MongoConfigUtil.setCreateInputSplits(conf, false);
        System.out.println("Configuration: " + conf);
        @SuppressWarnings("deprecation")
        final Job job = new Job(conf, "Mongo Import");
        Path out = new Path("/home/mongo_import");
        FileOutputFormat.setOutputPath(job, out);
        job.setJarByClass(ImportWeblogsFromMongo.class);
        job.setMapperClass(ReadWeblogsFromMongo.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setInputFormatClass(MongoInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        job.setNumReduceTasks(0);
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
    }

1. After exporting the Jar file named importmongo.jar
 2. I tried to execute this command hadoop jar /home/yass/importmongo.jar hdfs.ImportWeblogsFromMongo but i got the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/hadoop/util/MongoConfigUtil
    at hdfs.ImportWeblogsFromMongo.main(ImportWeblogsFromMongo.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by: java.lang.ClassNotFoundException: com.mongodb.hadoop.util.MongoConfigUtil
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more

NB:clustedb is the database name and fish its collection
and hdfs.ImportWeblogsFromMongo  is package.class

Any suggestions please

Body:
I didn't resolve the issue this way but i found solution using Mongodump by copying the file to Hdfs ,the lines below it may help someone to get the job done

   mongodump  --db clusterdb --collection CollectionName

   bsondump file.bson > file.json

   hadoop dfs -copyFromLocal /path/to/file/fish.json mongo


问:
Difficulty importing SearchBox from 'react-google-maps'
The documentation for react-google-maps says that you can import SearchBox via import { SearchBox } from 'react-google-maps' but it seems to break my page when I try giving me an error of Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). when I attempt to import it in.  Everything else with react-google-maps seems to work, however.

my code is below:

```<code>/* global google */
import _ from "lodash";

import {
  default as React,
  Component,
} from "react";

import Helmet from "react-helmet";

import {
  GoogleMapLoader,
  withGoogleMap,
  GoogleMap,
  Marker,
  SearchBox,
  InfoWindow,
} from "react-google-maps";

// mobx
import {observer} from 'mobx-react'
import {observable} from 'mobx'

const INPUT_STYLE = {
  boxSizing: `border-box`,
  MozBoxSizing: `border-box`,
  border: `1px solid transparent`,
  width: `240px`,
  height: `32px`,
  marginTop: `27px`,
  padding: `0 12px`,
  borderRadius: `1px`,
  boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
  fontSize: `14px`,
  outline: `none`,
  textOverflow: `ellipses`,
};

/*
 * This is the modify version of:
 * https://developers.google.com/maps/documentation/javascript/examples/event-arguments
 */
const GettingStartedGoogleMap = withGoogleMap(props => (
  <GoogleMap
    ref={props.onMapMounted}
    defaultZoom={3}
    center={props.center}
    onBoundsChanged={props.onBoundsChanged}
    onClick={props.onMapClick}
  >
    <SearchBox
      ref={props.onSearchBoxMounted}
      bounds={props.bounds}
      controlPosition={google.maps.ControlPosition.TOP_LEFT}
      onPlacesChanged={props.onPlacesChanged}
      inputPlaceholder="Customized your placeholder"
      inputStyle={INPUT_STYLE}
    />
    ...
  </GoogleMap>
));

const Browse = observer(class Browse extends Component {

  constructor(props) {
    super(props)

    this.populateMap(this.props.properties);

    // this.state ONLY FOR vars, not for functions.
    // if i need to change state, use this.setState({})
    this.state = observable({
      bounds: null,
      center: {
        lat: 25.363882,
        lng: -80.044922,
      },
      properties: this.props.properties,
      markers: [],
    });

    this.handleMapMounted = this.handleMapMounted.bind(this);
    this.handleMapClick = this.handleMapClick.bind(this);
    this.handleMarkerClick = this.handleMarkerClick.bind(this);
    this.handleBoundsChanged = this.handleBoundsChanged.bind(this);
    this.handleSearchBoxMounted = this.handleSearchBoxMounted.bind(this);
    this.handlePlacesChanged = this.handlePlacesChanged.bind(this);
  }

  didFinishLoadingMarkers(markers) {
    this.setState({markers: markers});
  }

  //... removed this code to make it all easier to read...

  // test

  handleBoundsChanged() {
    this.setState({
      bounds: this._map.getBounds(),
      center: this._map.getCenter(),
    });
    console.log('handleBoundsChanged')
  }

  handleSearchBoxMounted(searchBox) {
    this._searchBox = searchBox;
    console.log('handleSearchBoxMounted')
  }

  handlePlacesChanged() {
    const places = this._searchBox.getPlaces();

    // Add a marker for each place returned from search bar
    const markers = places.map(place => ({
      position: place.geometry.location,
    }));

    // Set markers; set map center to first search result
    const mapCenter = markers.length > 0 ? markers[0].position : this.state.center;
    console.log('handlePlacesChanged')
    this.setState({
      center: mapCenter,
      markers,
    });
  }
  // end test

  render() {
    return (
      <div className='container-fluid full-height'>
        <div className='row full-height'>
          <div className='col-xs-6 full-height map-position'>
            <GettingStartedGoogleMap
              containerElement={
                <div style={{ height: `100%` }} />
              }
              mapElement={
                <div style={{ height: `100%`, position: `static` }} />
              }
              center={this.state.center}
              onMapMounted={this.handleMapMounted}
              onMapClick={this.handleMapClick}
              markers={this.state.markers}
              onMarkerClick={this.handleMarkerClick}
              onBoundsChanged={this.handleBoundsChanged}
              onSearchBoxMounted={this.handleSearchBoxMounted}
              bounds={this.state.bounds}
              onPlacesChanged={this.handlePlacesChanged}
            />
          </div>
          <div className='col-xs-6 full-height pull-right'>
            <h1>Browse All Properties</h1>
            {this.props.properties.map(function(property, i) {
              return (
                <div key={i}>
                  <a href={'housing_applications/' + property.id}>{property.name}</a>
                </div>
              )
            }, this)}
          </div>
        </div>
      </div>
    );
  }
})

export default Browse

ReactOnRails.register({ Browse });
</code>```

Thanks!

答:
These days SearchBox is not a root export by default so:

```<code>import SearchBox from 'react-google-maps/lib/places/SearchBox'
</code>```

Also note this SO - you need to add ?libraries=places to your script import

Body:
The documentation for react-google-maps says that you can import SearchBox via import { SearchBox } from 'react-google-maps' but it seems to break my page when I try giving me an error of Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). when I attempt to import it in.  Everything else with react-google-maps seems to work, however.

my code is below:

/* global google */
import _ from "lodash";

import {
  default as React,
  Component,
} from "react";

import Helmet from "react-helmet";

import {
  GoogleMapLoader,
  withGoogleMap,
  GoogleMap,
  Marker,
  SearchBox,
  InfoWindow,
} from "react-google-maps";

// mobx
import {observer} from 'mobx-react'
import {observable} from 'mobx'

const INPUT_STYLE = {
  boxSizing: `border-box`,
  MozBoxSizing: `border-box`,
  border: `1px solid transparent`,
  width: `240px`,
  height: `32px`,
  marginTop: `27px`,
  padding: `0 12px`,
  borderRadius: `1px`,
  boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
  fontSize: `14px`,
  outline: `none`,
  textOverflow: `ellipses`,
};

/*
 * This is the modify version of:
 * https://developers.google.com/maps/documentation/javascript/examples/event-arguments
 */
const GettingStartedGoogleMap = withGoogleMap(props => (
  <GoogleMap
    ref={props.onMapMounted}
    defaultZoom={3}
    center={props.center}
    onBoundsChanged={props.onBoundsChanged}
    onClick={props.onMapClick}
  >
    <SearchBox
      ref={props.onSearchBoxMounted}
      bounds={props.bounds}
      controlPosition={google.maps.ControlPosition.TOP_LEFT}
      onPlacesChanged={props.onPlacesChanged}
      inputPlaceholder="Customized your placeholder"
      inputStyle={INPUT_STYLE}
    />
    ...
  </GoogleMap>
));

const Browse = observer(class Browse extends Component {

  constructor(props) {
    super(props)

    this.populateMap(this.props.properties);

    // this.state ONLY FOR vars, not for functions.
    // if i need to change state, use this.setState({})
    this.state = observable({
      bounds: null,
      center: {
        lat: 25.363882,
        lng: -80.044922,
      },
      properties: this.props.properties,
      markers: [],
    });

    this.handleMapMounted = this.handleMapMounted.bind(this);
    this.handleMapClick = this.handleMapClick.bind(this);
    this.handleMarkerClick = this.handleMarkerClick.bind(this);
    this.handleBoundsChanged = this.handleBoundsChanged.bind(this);
    this.handleSearchBoxMounted = this.handleSearchBoxMounted.bind(this);
    this.handlePlacesChanged = this.handlePlacesChanged.bind(this);
  }

  didFinishLoadingMarkers(markers) {
    this.setState({markers: markers});
  }

  //... removed this code to make it all easier to read...

  // test

  handleBoundsChanged() {
    this.setState({
      bounds: this._map.getBounds(),
      center: this._map.getCenter(),
    });
    console.log('handleBoundsChanged')
  }

  handleSearchBoxMounted(searchBox) {
    this._searchBox = searchBox;
    console.log('handleSearchBoxMounted')
  }

  handlePlacesChanged() {
    const places = this._searchBox.getPlaces();

    // Add a marker for each place returned from search bar
    const markers = places.map(place => ({
      position: place.geometry.location,
    }));

    // Set markers; set map center to first search result
    const mapCenter = markers.length > 0 ? markers[0].position : this.state.center;
    console.log('handlePlacesChanged')
    this.setState({
      center: mapCenter,
      markers,
    });
  }
  // end test

  render() {
    return (

            <GettingStartedGoogleMap
              containerElement={
                <div style={{ height: `100%` }} />
              }
              mapElement={
                <div style={{ height: `100%`, position: `static` }} />
              }
              center={this.state.center}
              onMapMounted={this.handleMapMounted}
              onMapClick={this.handleMapClick}
              markers={this.state.markers}
              onMarkerClick={this.handleMarkerClick}
              onBoundsChanged={this.handleBoundsChanged}
              onSearchBoxMounted={this.handleSearchBoxMounted}
              bounds={this.state.bounds}
              onPlacesChanged={this.handlePlacesChanged}
            />

Browse All Properties

            {this.props.properties.map(function(property, i) {
              return (

                  {property.name}

              )
            }, this)}

    );
  }
})

export default Browse

ReactOnRails.register({ Browse });

Thanks!

Body:
These days SearchBox is not a root export by default so:

import SearchBox from 'react-google-maps/lib/places/SearchBox'

Also note this SO - you need to add ?libraries=places to your script import


问:
Twitter4j Getting Tweets Too Long
Hello i have tweet id's and i saved them to database before. But i saw that i could not save created time efficiently (it is saved like 00:00:00). Therefore i wished to update my tweets with tweet id by using following code.

```<code>   MyConnectionBuilder myConnection = new MyConnectionBuilder();
   Twitter twitter = new TwitterFactory(myConnection.configuration.build()).getInstance();
    Status status = twitter.showStatus(Long.parseLong(tweetId));
</code>```

But it takes too much time to get tweets, is there any rate limit for this ? If there is a rate limit how can i make it faster ?

答:
Updating every single tweet via showStatus wastes your "credits" for a given timeframe (rate-limit).

For updating multiple tweets, you should use lookup with a maximum of 100 ids per request. This call will use the /statuses/lookup endpoint.

Rate-Limit and endpoint documentation can be found here

Code-Snipped for it:

```<code>Twitter twitter =  twitterFactory.getInstance();
ResponseList<Status> responseList  = twitter.lookup(ArrayUtils.toPrimitive(ids));

    if(responseList != null) {
        for (Status status : responseList) {
            // do what you need to do here

        }
    }
</code>```

Title: Twitter4j Getting Tweets Too Long

Body:
Hello i have tweet id's and i saved them to database before. But i saw that i could not save created time efficiently (it is saved like 00:00:00). Therefore i wished to update my tweets with tweet id by using following code.

   MyConnectionBuilder myConnection = new MyConnectionBuilder();
   Twitter twitter = new TwitterFactory(myConnection.configuration.build()).getInstance();
    Status status = twitter.showStatus(Long.parseLong(tweetId));

But it takes too much time to get tweets, is there any rate limit for this ? If there is a rate limit how can i make it faster ?

Body:
Updating every single tweet via showStatus wastes your "credits" for a given timeframe (rate-limit).

For updating multiple tweets, you should use lookup with a maximum of 100 ids per request. This call will use the /statuses/lookup endpoint.

Rate-Limit and endpoint documentation can be found here

Code-Snipped for it:

Twitter twitter =  twitterFactory.getInstance();
ResponseList<Status> responseList  = twitter.lookup(ArrayUtils.toPrimitive(ids));

    if(responseList != null) {
        for (Status status : responseList) {
            // do what you need to do here

        }
    }


答:
The below snippet should work</p>

```<code>>>> from pyspark.sql import Row
>>>
>>> data = [{'foo': 'bar', 'hello': 'world'}]
>>> rdd = spark.sparkContext.parallelize(data)
>>> df = rdd.map(lambda x: Row(**x)).toDF()

>>> df.show()
+---+-----+
|foo|hello|
+---+-----+
|bar|world|
+---+-----+
</code>```

Title: convert an rdd of dictionary to df

Body:
How can i make an pipelined rdd of dict into a dataframe in pyspark

[{'ACARS 20170507/20170506085012209001.rcv': 'QU SOUTA8X\r\n.BJSXCXA 060849\r\nM12\r\nFI CX731/AN B-LAN\r\nDT BJS HKG 060849 M63A\r\n-  OFF,V01,CX 731 20170506 1,VHHH,OMDB,0833,0849,----,  600', 'ACARS 20170507/20170502020906017001.rcv': 'QU SOUTA8X\r\n.BJSXCXA 020209\r\nM12\r\nFI KA876/AN B-LAB\r\nDT BJS HKG 020209 M11A\r\n-  OFF,V01,KA 876 20170502 1,VHHH,ZSPD,0149,0208,----,  294', 'ACARS 20170507/20170505050124358002.rcv': 'QU SOUTA8X\r\n.BKKXCXA 050501\r\nCFD\r\nFI CX690/AN B-LAJ\r\nDT BKK XSP 050501 C10A\r\n-  .1/WRN/DBN17D/WN1705050500  261707002SMOKE LAVATORY DET FAULT'}]

Body:
The below snippet should work

>>> from pyspark.sql import Row
>>>
>>> data = [{'foo': 'bar', 'hello': 'world'}]
>>> rdd = spark.sparkContext.parallelize(data)
>>> df = rdd.map(lambda x: Row(**x)).toDF()

>>> df.show()
+---+-----+
|foo|hello|
+---+-----+
|bar|world|
+---+-----+


问:
How can i lookup values from another table in Entity Framework
very new to this. Building a Tourettes pattern tracker for a friend.

I have two related tables in EF. How can I create an entry in the TicEntry table that has a foreign key requirment from the other table? I will populate TicType as it will remain pretty static.

A user needs to be able to create an TicEntry ideally with just Frequency, Severity, TicType selections. TicType should lookup from the TicType Table. Date will hopefully be auto, as well as TicEntryID which is an IDENTITY. But how do I deal with the TicTypeID when giving a model to my View?

Many thanks.

```<code>public enum Frequency { Low, Medium, High }
public enum Severity { Low, Medium, High }
public class TicEntry {
    public int TicEntryID { get; set; }
    public int TicTypeID { get; set; }
    public DateTime DateTime { get; set; }
    public Frequency? Frequency { get; set; }
    public Severity? Severity { get; set; }
    public virtual TicType TicType { get; set; }
}

    public enum Type { Motor, Vocal, ComMotor, ComVocal }
public class TicType
{
    public int TicTypeID { get; set; }
    public Type? Type { get; set; }
    public virtual ICollection<TicEntry> TicEntry { get; set; }
}
</code>```

答:
Let the user select the tic type from the Type enum. Then use the selected enum value to look up the TicType entry from the DB.

In the View.cshtml:

```<code>var availableTicTypes = new List<SelectListItem>(
    new SelectListItem{ Value = Type.Motor, Text = "Motor", Selected = true },
    new SelectListItem{ Value = Type.Vocal, Text = "Vocal", Selected = false }
    // ...
);
@Html.DropDownListFor(m => m.TickType, availableTicTypes)
</code>```

In your Controller:

```<code>var ticType = _dbContext.TicTypes.SingleOrDefault(t => t.Type == viewModel.TickType);

var tickEntry = new TicEntry {
    TicType = ticType
    // set other properties ...
};
_dbContext.TickEntries.Add(tickEntry);
_dbContext.SaveChanges();
</code>```

Body:
very new to this. Building a Tourettes pattern tracker for a friend.

I have two related tables in EF. How can I create an entry in the TicEntry table that has a foreign key requirment from the other table? I will populate TicType as it will remain pretty static.

A user needs to be able to create an TicEntry ideally with just Frequency, Severity, TicType selections. TicType should lookup from the TicType Table. Date will hopefully be auto, as well as TicEntryID which is an IDENTITY. But how do I deal with the TicTypeID when giving a model to my View?

Many thanks.

public enum Frequency { Low, Medium, High }
public enum Severity { Low, Medium, High }
public class TicEntry {
    public int TicEntryID { get; set; }
    public int TicTypeID { get; set; }
    public DateTime DateTime { get; set; }
    public Frequency? Frequency { get; set; }
    public Severity? Severity { get; set; }
    public virtual TicType TicType { get; set; }
}

    public enum Type { Motor, Vocal, ComMotor, ComVocal }
public class TicType
{
    public int TicTypeID { get; set; }
    public Type? Type { get; set; }
    public virtual ICollection<TicEntry> TicEntry { get; set; }
}

Body:
Let the user select the tic type from the Type enum. Then use the selected enum value to look up the TicType entry from the DB.

In the View.cshtml:

var availableTicTypes = new List<SelectListItem>(
    new SelectListItem{ Value = Type.Motor, Text = "Motor", Selected = true },
    new SelectListItem{ Value = Type.Vocal, Text = "Vocal", Selected = false }
    // ...
);
@Html.DropDownListFor(m => m.TickType, availableTicTypes)

In your Controller:

var ticType = _dbContext.TicTypes.SingleOrDefault(t => t.Type == viewModel.TickType);

var tickEntry = new TicEntry {
    TicType = ticType
    // set other properties ...
};
_dbContext.TickEntries.Add(tickEntry);
_dbContext.SaveChanges();