问:
Web Audio API - Get correct frequency
I am using the Web Audio API to get the frequency of the sound, which is coming from the microphone. For this I found some useful code on this github repo: https://gist.github.com/giraj/250decbbc50ce091f79e .

Now my problem is, that I am getting a lot of different frequencies, for only one little sound. This sound might be from my voice, or from an instrument.

These frequencies are like between 90 and 4000Hz. But as I know, one note of a human voice or from an instrument, only can have one single frequency amount in Hz. And I am pretty sure, that I am only playing one single tone.

So how can I know, which frequency of the 3 or 4 frequencies per tone is the one I am searching. I need this value, to recognize musical notes like C, D, E from their frequencies. I hope this question isn't off-topic, because I really tried hard to find a solution and I don't know if this is a solveable issue from the API itself, or if I have to eliminate some frequencies somehow. I would appreciate any kind of help.

Edit: And I want to add, that I never reach the same values of the notes as listed in this frequency list: http://www.phy.mtu.edu/~suits/notefreqs.html . I am using a piano app, which is giving always the correct frequencies on frequency apps on the play store. So I even doubt the results I am receiving.

答:
I'm a professional singer, pianist, and voice teacher transitioning into code, so I think I can speak to some of the confusing results you're getting here.

Bottom line: you are actually producing many different frequencies at the same time when you sing or play a note on an instrument, so chances are the results you're seeing are accurate. What you're aiming for, however, is almost certainly the fundamental pitch, which is the lowest one.

Longer, more complex answer with physics: Unless you're looking at a sine wave (sounds like a mechanical beep, and won't come out of a decent musical instrument), the sound you're hearing probably contains many different frequencies. The sound is made up of a fundamental pitch (the lowest frequency, and usually the one we're talking about when we name a pitch in music), and a whole lot of overtones (other, higher frequencies that make up the characteristic sound of an instrument, or for singers, even a vowel).

Let's pick a number that's easy to work with: imagine your fundamental pitch is 100hz. We'll call that C1 for convenience in discussing musical implications (though it's not actually a C), and the numbers represent octave leaps with octaves ranging from C up to B. You could potentially have overtones at any of the following pitches: 200hz (C2), 300hz (G2), 400hz (C3), 500hz (E3), 600hz (G3), 700hz (Bb3), 800hz (C4), 900 hz (D4), 1000hz (E4), etc. Different instruments might make some overtones pop out more than others, or skip some of these entirely (many will skip every other overtone), but all the overtones will be within this pattern.

Notice that all the overtones are multiples of the fundamental. That means you can use the pattern in all those other pitches you see to figure out the fundamental pitch underneath. From a musical standpoint, you might also notice that the pitches you see first in this overtone series are the ones we consider most consonant — octaves, perfect 5ths, major 3rds, major triads. This is not a coincidence, and the way the overtones line up with these other pitches is almost certainly why we find them pretty to listen to.

Boiling all this down to how you'd determine the fundamental pitch given a series of overtones presumably resulting from the same fundamental: you're essentially looking for the greatest common factor of the various frequencies you'll see. It is probably also the lowest frequency you detected, but be careful with this heuristic, because you may have unrelated noise in your signal. Anything that doesn't fall into your nice list of multiples is probably noise.

All this gets much more complicated, of course, when you play more than one (fundamental) pitch at once. I'm pondering chord detection myself, and found your question while looking for what people have already done in this area and how I can build on it.

Title: Web Audio API - Get correct frequency


来源: stackexchange

问:
Regex-How to prevent repeated special characters?
I don't have an experience on Regular Expressions. I need to a regular expression which doesn't allow to repeat of special characters (+-*/& etc.)
The string can contain digits, alphanumerics, and special characters.

This should be valid : abc,df

This should be invalid : abc-,df

i will be really appreciated if you can help me ! Thanks for advance.

答:
Use the following regex to match the invalid string.</p>

```<code>[^A-Za-z0-9]{2,}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use the following regex to match the invalid string.

[^A-Za-z0-9]{2,}


问:
MSBuild project vs PowerShell build procedure
I have to complete the following tasks:

Prebuild setup (download dependencies etc.)

Build .net solution

Run Tests (unit tests and functional tests)

Generate documentation

Generate nuget packages

Sign output

I'm able to complete the task by creating PS build procedure(that uses msbuild just to compile the solution) or MSBuild project with targets(that uses some helper PS scripts). PowerShell is more flexible but MSBuild is a build framework an has some integrated build related features. I'm wondering what will be the best approach. Please share thoughts.

答:
Out of the box, MSBuild is specialized in handling tasks and its dependencies. So when you want to do custom stuff that MSBuild can't do by default, you need to call scripts/tools through targets or you can add more types of tasks by including community/custom extensions to your project.

On the other hand, Powershell is free of form, so you have to work your way without built-in structure, but you have the liberty to do whatever you want right out of the box and without having to use another tool/language to fill up the gaps. For multiple projects, you'll have to create some sort of framework if you want to keep your build system maintainable.

If you want both worlds, PSAKE is a tasks handling Powershell module that acts similarly to MSBuild and has syntax based on RAKE, which is pretty neat. In short, PSAKE have a lighter syntax than MSBuild and has most of its features available through Powershell, so you benefit from both worlds.

Generally, it's a matter of taste and needs. I favor short and sweet syntax that tells clearly what part of code do what. MSBuild is based on XML, so there is a lot of redundancy, it has no IDE shipped with it and needs an external tool like Visual Studio to debug it. PSAKE is a Powershell module, so you can spawn Powershell ISE, load the module and enjoy IntelliSense while creating your build scripts.

But understand that there is a lot of possibilities as of what to choose, so pick your poison and don't narrow your choices to only MSBuild and Powershell. See some alternatives here.


问:
Join two queries mysql
I would like to join two queries :

This first query get "pgm_posts.post_title" and "pgm_post_views.count" (WHERE  pgm_post_views.type="4")

```<code>SELECT pgm_posts.post_title, pgm_post_views.count
FROM pgm_posts, pgm_post_views
WHERE  pgm_post_views.type="4" AND pgm_post_views.id = pgm_posts.id
</code>```

This second query get all the ids from "pgm_post_views" with condition.

pgm_post_views.type="0" : its the condition for get "period". (look img)

```<code>SELECT pgm_posts.id
FROM pgm_posts
INNER JOIN pgm_post_views
ON pgm_posts.id = pgm_post_views.id AND pgm_post_views.type="0" AND DATE_FORMAT(pgm_post_views.period, "%Y-%m-%d") <= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d') AND DATE_FORMAT(pgm_posts.post_date, "%Y-%m-%d") <= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d')
</code>```

Resume : First query get post_title and total count based on all ids of second query.

How i can do this ?

答:
A simple way is a pure join based on selected table</p>

```<code>SELECT p
        gm_posts.post_title
      , pgm_post_views.count
FROM pgm_posts
INNER JOIN  pgm_post_views ON  pgm_post_views.id = pgm_posts.id
                  AND pgm_post_views.type="4"
INNER JOIN (
 SELECT
        pgm_posts.id
 FROM pgm_posts
 INNER JOIN pgm_post_views ON pgm_posts.id = pgm_post_views.id AND pgm_post_views.type="0"
          AND DATE_FORMAT(pgm_post_views.period, "%Y-%m-%d") <=
                        DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d')
          AND DATE_FORMAT(pgm_posts.post_date, "%Y-%m-%d") <=
                        DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d')
) T on T.id = pgm_posts
</code>```

Title: Join two queries mysql

Body:
I would like to join two queries :

This first query get "pgm_posts.post_title" and "pgm_post_views.count" (WHERE  pgm_post_views.type="4")

SELECT pgm_posts.post_title, pgm_post_views.count
FROM pgm_posts, pgm_post_views
WHERE  pgm_post_views.type="4" AND pgm_post_views.id = pgm_posts.id

This second query get all the ids from "pgm_post_views" with condition.

pgm_post_views.type="0" : its the condition for get "period". (look img)

SELECT pgm_posts.id
FROM pgm_posts
INNER JOIN pgm_post_views
ON pgm_posts.id = pgm_post_views.id AND pgm_post_views.type="0" AND DATE_FORMAT(pgm_post_views.period, "%Y-%m-%d") <= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d') AND DATE_FORMAT(pgm_posts.post_date, "%Y-%m-%d") <= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d')

Resume : First query get post_title and total count based on all ids of second query.

How i can do this ?

Body:
A simple way is a pure join based on selected table

SELECT p
        gm_posts.post_title
      , pgm_post_views.count
FROM pgm_posts
INNER JOIN  pgm_post_views ON  pgm_post_views.id = pgm_posts.id
                  AND pgm_post_views.type="4"
INNER JOIN (
 SELECT
        pgm_posts.id
 FROM pgm_posts
 INNER JOIN pgm_post_views ON pgm_posts.id = pgm_post_views.id AND pgm_post_views.type="0"
          AND DATE_FORMAT(pgm_post_views.period, "%Y-%m-%d") <=
                        DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d')
          AND DATE_FORMAT(pgm_posts.post_date, "%Y-%m-%d") <=
                        DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d')
) T on T.id = pgm_posts


问:
Try to hide mailchimp inputfields after successfull submitting?
I couldn't find an answer on mailchimp and i thought i would be simple. Just checkin if the succes-response div has any value and hide the div's.

```<code>    jQuery(document).ready(function($){

        $("#mc-embedded-subscribe").click(function (e) {
            if ($('#mce-success-response').text().length > 0) {
                $('#mc_embed_signup .mc-field-group').hide();
                alert('hide hide the fields');
            }
        });
    });
</code>```

But this doesn't work, the response happens after the click event. So how can i make it to work??

答:
You could hide the fields first in the click function, and then redisplay them if the length of the success response does not indicate success.

Hiding might be a little harsh visually...maybe fade out their opacity or use a slide toggle to make the form go away to a swirling 'please wait' image.  The sky is the limit.

Body:
I couldn't find an answer on mailchimp and i thought i would be simple. Just checkin if the succes-response div has any value and hide the div's.

    jQuery(document).ready(function($){

        $("#mc-embedded-subscribe").click(function (e) {
            if ($('#mce-success-response').text().length > 0) {
                $('#mc_embed_signup .mc-field-group').hide();
                alert('hide hide the fields');
            }
        });
    });

But this doesn't work, the response happens after the click event. So how can i make it to work??


问:
how do i make a loop to display the next 3 even number?
hello all i'm trying to make javascript to display an evens numbers by using a form with start number and number of evens to display. user will enter starting number and enter the number of even to display.
say start at 7 number of evens is 3 should display 8 10 12.  just need some direction. thanks

my code:

```<code><html>
<head>
<title>evens</title>
<div class="container">
           <h1>Enter Number</h1>
           <form name="number" class="form-inline">
           <div class="form-group">
            <label for="starting">Starting Number</label>
            <input type="text" id="starting" class="form-control">
           </div> <div class="form-group">
               <label for="step">numbers of evens</label>
               <input type="text" id="step" class="form-control">
           </div>
</code>```

```<code>           <button type="button" onclick="evenDisplay()" class="btn" >submit</button>

<script>

function evenDisplay() {

    var starting = document.getElementById("starting").value;
    var step = document.getElementById("step").value;
    var evens = [];

    for (i = starting;  i <=12; i++) { /* this loop would show as much as evens number as long value of i<= set to  and doesn't care if the user enter the number of evens */
        i % 2 || evens.push(i);
    }
   console.log(evens)

}
   </body>
 </html>
</code>```

答:
You are using comas in your javascript where you should be using semi colons and you are missing numerous tags. Please see below for corrected code. I've included comments where you were missing things:</p>

```<code><!DOCTYPE html >
<head>
<title>evens</title>

<script>

function evenDisplay() {

var starting = document.getElementById("starting").value;  //SEMI-COLON HERE
var step = document.getElementById("step").value; //SEMI-COLON HERE
var evens = [];

for (i = starting;  i <=12; i++) {
    i % 2 || evens.push(i);
}
  console.log(evens); //SEMI-COLON HERE
}
</script> <!--you had no closing script tag-->
</head> <!--you had no closing head tag-->
 <body> <!--you had no opening body tag-->
 <div class="container">
       <h1>Enter Number</h1>
       <form name="number" class="form-inline">
       <div class="form-group">
        <label for="starting">Starting Number</label>
        <input type="text" id="starting" class="form-control">
       </div> <div class="form-group">
           <label for="step">numbers of evens</label>
           <input type="text" id="step" class="form-control">
       </div>

       <button type="button" onclick="evenDisplay()" class="btn" >submit</button>
</form> <!--CLOSING FORM TAG HERE-->
</div>

</body>
</html>
</code>```

Body:
hello all i'm trying to make javascript to display an evens numbers by using a form with start number and number of evens to display. user will enter starting number and enter the number of even to display.
say start at 7 number of evens is 3 should display 8 10 12.  just need some direction. thanks

my code:

<title>evens</title>

Enter Number

           <form name="number" class="form-inline">

            Starting Number
            <input type="text" id="starting" class="form-control">

               numbers of evens
               <input type="text" id="step" class="form-control">

           <button type="button" onclick="evenDisplay()" class="btn" >submit</button>

Body:
You are using comas in your javascript where you should be using semi colons and you are missing numerous tags. Please see below for corrected code. I've included comments where you were missing things:

<!DOCTYPE html >
<head>
<title>evens</title>

<script>

function evenDisplay() {

var starting = document.getElementById("starting").value;  //SEMI-COLON HERE
var step = document.getElementById("step").value; //SEMI-COLON HERE
var evens = [];

for (i = starting;  i <=12; i++) {
    i % 2 || evens.push(i);
}
  console.log(evens); //SEMI-COLON HERE
}
</script> <!--you had no closing script tag-->
</head> <!--you had no closing head tag-->
 <body> <!--you had no opening body tag-->
 <div class="container">
       <h1>Enter Number</h1>
       <form name="number" class="form-inline">
       <div class="form-group">
        <label for="starting">Starting Number</label>
        <input type="text" id="starting" class="form-control">
       </div> <div class="form-group">
           <label for="step">numbers of evens</label>
           <input type="text" id="step" class="form-control">
       </div>

       <button type="button" onclick="evenDisplay()" class="btn" >submit</button>
</form> <!--CLOSING FORM TAG HERE-->
</div>

</body>
</html>


问:
FileIO, writing to document, var = 1.0 becomes 1
When I have the user input a section number (such as 1.1, 3.4, 4.23 etc), I need to be able to write section numbers to a .txt document that are inclusive of 1.0, where currently 1.0 is written as just an integer 1 (or 1.10 which is written as 1.1).

Doing this as a bunch of 'if' statements is messy, is there a better way?

Edit:

```<code>#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main()
{
  cout << "Enter a float here" << endl;
  float f;
  cin >> f;

  ofstream fine;
  fine.open("fine.txt", ios::out);
  fine << f << "\n";
}
</code>```

If you enter 1.0 as your float, it saves 1 to the .txt. What I need to be able to do is have the user enter in a number like 1.0, or 1.10, and have those be writable to the .txt as they are, not with the zero truncated.

答:
float is a terrible choice to represent a "section number". If you use  float then §1.1 == §1.10 and §1.3.2 can't exist. Try std::string instead:

```<code>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
  cout << "Enter a section number here" << endl;
  string f;
  cin >> f;

  ofstream fine;
  fine.open("fine.txt", ios::out);
  fine << f << "\n";
}
</code>```

Body:
When I have the user input a section number (such as 1.1, 3.4, 4.23 etc), I need to be able to write section numbers to a .txt document that are inclusive of 1.0, where currently 1.0 is written as just an integer 1 (or 1.10 which is written as 1.1).

Doing this as a bunch of 'if' statements is messy, is there a better way?

Edit:

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main()
{
  cout << "Enter a float here" << endl;
  float f;
  cin >> f;

  ofstream fine;
  fine.open("fine.txt", ios::out);
  fine << f << "\n";
}

If you enter 1.0 as your float, it saves 1 to the .txt. What I need to be able to do is have the user enter in a number like 1.0, or 1.10, and have those be writable to the .txt as they are, not with the zero truncated.

Body:
float is a terrible choice to represent a "section number". If you use  float then §1.1 == §1.10 and §1.3.2 can't exist. Try std::string instead:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
  cout << "Enter a section number here" << endl;
  string f;
  cin >> f;

  ofstream fine;
  fine.open("fine.txt", ios::out);
  fine << f << "\n";
}


问:
C# - using List<T>.Find() with custom objects
I'm trying to use a List<T> with a custom class of mine, and being able to use methods like Contains(), Find(), etc., on the list. I thought I'd just have to overload the operator == but apparently, one way of doing that is to use a delegate method with the Find()...

Note: Right now, I've overloaded the Equals() method to get the Contains() method to work, but I still couldn't get the Find() function to work.

What would be the best way of getting both to work?

I'm using the latest C# /.NET framework version with mono, on linux.

edit: Here's my code

```<code>using System;
namespace GuerreDesClans
{
public class Reponse : IEquatable<Reponse>
{
    public Reponse ()
    {
        m_statement = string.Empty;
        m_pointage = 0;
    }

    public Reponse (string statement, int pointage)
    {
        m_pointage = pointage;
        m_statement = statement;
    }

    /*
     * attributs privés
     */

    private string m_statement;
    private int m_pointage;

    /*
     * properties
     */

    public string Statement {
        get { return m_statement; }
        set { m_statement = value; }
    }

    public int Pointage {
        get { return m_pointage; }
        set { m_pointage = value; }
    }

    /*
     * Equatable
     */

    public bool Equals (Reponse other)
    {
        if (this.m_statement == other.m_statement)
            return true;
        else
            return false;
    }
}
</code>```

}

and how I would like to search my Reponse objects using the find() function...

```<code>list.find("statement1"); // would return a Reponse object
</code>```

答:
Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.

```<code>var element = myList.Find(e => [some condition on e]);
</code>```

In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.

In your case, that would be:

```<code>var reponse = list.Find(r => r.Statement == "statement1")
</code>```

And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:

```<code>var response = list.Find(delegate (Response r) {
    return r.Statement == "statement1";
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use a List<T> with a custom class of mine, and being able to use methods like Contains(), Find(), etc., on the list. I thought I'd just have to overload the operator == but apparently, one way of doing that is to use a delegate method with the Find()...

Note: Right now, I've overloaded the Equals() method to get the Contains() method to work, but I still couldn't get the Find() function to work.

What would be the best way of getting both to work?

I'm using the latest C# /.NET framework version with mono, on linux.

edit: Here's my code

using System;
namespace GuerreDesClans
{
public class Reponse : IEquatable<Reponse>
{
    public Reponse ()
    {
        m_statement = string.Empty;
        m_pointage = 0;
    }

    public Reponse (string statement, int pointage)
    {
        m_pointage = pointage;
        m_statement = statement;
    }

    /*
     * attributs privés
     */

    private string m_statement;
    private int m_pointage;

    /*
     * properties
     */

    public string Statement {
        get { return m_statement; }
        set { m_statement = value; }
    }

    public int Pointage {
        get { return m_pointage; }
        set { m_pointage = value; }
    }

    /*
     * Equatable
     */

    public bool Equals (Reponse other)
    {
        if (this.m_statement == other.m_statement)
            return true;
        else
            return false;
    }
}

}

and how I would like to search my Reponse objects using the find() function...

list.find("statement1"); // would return a Reponse object

Body:
Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.

var element = myList.Find(e => [some condition on e]);

In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.

In your case, that would be:

var reponse = list.Find(r => r.Statement == "statement1")

And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:

var response = list.Find(delegate (Response r) {
    return r.Statement == "statement1";
});


问:
Does JavaScript have a method like "range()" to generate a range within the supplied bounds?
In PHP, you can do...

```<code>range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
</code>```

That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.

Is there anything built-in to JavaScript natively for this? If not, how would I implement it?

答:
My new favorite form (ES2015)

```<code>Array(10).fill(1).map((x, y) => x + y)
</code>```

And if you need a function with a step param:

```<code>const range = (start, stop, step = 1) =>
  Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)
</code>```

Another possible implementation suggested by the MDN docs:

```<code>// Sequence generator function
// (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) =>
  Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step))
</code>```

Body:
In PHP, you can do...

range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")

That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.

Is there anything built-in to JavaScript natively for this? If not, how would I implement it?

Body:
My new favorite form (ES2015)

Array(10).fill(1).map((x, y) => x + y)

And if you need a function with a step param:

const range = (start, stop, step = 1) =>
  Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)

Another possible implementation suggested by the MDN docs:

// Sequence generator function
// (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) =>
  Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step))

ContentLicense: CC BY-SA 4.0


问:
Docker: How to curl local server xyz.example.com running on host machine from within a docker container
On my host machine, I have a server xyz.example.com running on nginx. It is not dockerized and not accessible to the outside world, it is simply used for local dev environment.

I would like to be able to access it from within a docker container.

For example, I'd like to be able to do the following from within my docker container:

```<code>curl xyz.example.com
</code>```

and to see the same output I see when I run the command on my host machine.

Also, I am using docker-compose.

答:
I guess your container doesn't know about your xyz.example.com because It is declared in your host's /etc/host (you said it is a private server)?

Then you could add the host as extra_host:

```<code>services:
  some-service:
    extra_hosts:
      - "xyz.example.com:HOST_BRIDGE_IP"
</code>```

The extra_host will add hostname mappings in container's /etc/host.

And run your docker-compose.yml replacing HOST_BRIDGE_IP with it's ip in docker bridge:

```<code>HOST_BRIDGE_IP=$(docker network inspect bridge \
  --format '{{range .IPAM.Config}}{{.Gateway}}{{end}}') \
&& sed -e "s/HOST_BRIDGE_IP/${HOST_BRIDGE_IP}/g" \
docker-compose.yml | docker-compose --file - up
</code>```

This would allow virtual host resolution based on DNS in your server.

Edit: This seems a bit overkill to me, anyone has a better suggestion?

Body:
On my host machine, I have a server xyz.example.com running on nginx. It is not dockerized and not accessible to the outside world, it is simply used for local dev environment.

I would like to be able to access it from within a docker container.

For example, I'd like to be able to do the following from within my docker container:

curl xyz.example.com

and to see the same output I see when I run the command on my host machine.

Also, I am using docker-compose.

Body:
I guess your container doesn't know about your xyz.example.com because It is declared in your host's /etc/host (you said it is a private server)?

Then you could add the host as extra_host:

services:
  some-service:
    extra_hosts:
      - "xyz.example.com:HOST_BRIDGE_IP"

The extra_host will add hostname mappings in container's /etc/host.

And run your docker-compose.yml replacing HOST_BRIDGE_IP with it's ip in docker bridge:

HOST_BRIDGE_IP=$(docker network inspect bridge \
  --format '{{range .IPAM.Config}}{{.Gateway}}{{end}}') \
&& sed -e "s/HOST_BRIDGE_IP/${HOST_BRIDGE_IP}/g" \
docker-compose.yml | docker-compose --file - up

This would allow virtual host resolution based on DNS in your server.

Edit: This seems a bit overkill to me, anyone has a better suggestion?


问:
Is there a way to read an input string with "ifstream"
Currently my programme takes a string as an input which I access using argc and argv

then I use

```<code>FILE *fp, *input = stdin;
fp = fopen("input.xml","w+b");
    while(fgets(mystring,100,input) != NULL)
    {
        fputs(mystring,fp);
    }
    fclose(fp);
</code>```

I did this part only to create a file input.xml which I then supply to

```<code>ifstream in("input.xml");
    string s((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
</code>```

to get s as a string(basic string).
Is there a way to feed my input directly to ifstream? (i.e feeding a string to ifstream).

答:
If I get it right then you want to read all the text provided through standard input into a string.

An easy way to achieve this could be the use of std::getline, which reads all the bytes up to a specific delimiter into a string. If you may assume that it is text content (which does not contain any \0-character), you could write the following:

```<code>std::string s;
std::getline(cin,s,'\0');
</code>```

Body:
Currently my programme takes a string as an input which I access using argc and argv

then I use

FILE *fp, *input = stdin;
fp = fopen("input.xml","w+b");
    while(fgets(mystring,100,input) != NULL)
    {
        fputs(mystring,fp);
    }
    fclose(fp);

I did this part only to create a file input.xml which I then supply to

ifstream in("input.xml");
    string s((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());

to get s as a string(basic string).
Is there a way to feed my input directly to ifstream? (i.e feeding a string to ifstream).

Body:
If I get it right then you want to read all the text provided through standard input into a string.

An easy way to achieve this could be the use of std::getline, which reads all the bytes up to a specific delimiter into a string. If you may assume that it is text content (which does not contain any \0-character), you could write the following:

std::string s;
std::getline(cin,s,'\0');


答:
You had several bugs in your code. I think i fixed it:

```<code>function evenDisplay() {

    var starting = parseInt(document.getElementById("starting").value);
    var step = parseInt(document.getElementById("step").value);
    var evens = [];

    for (i = starting+(starting%2), j=0;  j <step; i+=2, j++) {
        evens.push(i);
    }
    console.log(evens);
}

window.onload = function(){
  document.getElementById("btn").onclick = evenDisplay;
}
</code>```

CodePen

You need to add id="btn" to your button for this to work.

Btw definind event handlers in HTML is highly discouraged.

Title: how do i make a loop to display the next 3 even number?

Body:
You had several bugs in your code. I think i fixed it:

function evenDisplay() {

    var starting = parseInt(document.getElementById("starting").value);
    var step = parseInt(document.getElementById("step").value);
    var evens = [];

    for (i = starting+(starting%2), j=0;  j <step; i+=2, j++) {
        evens.push(i);
    }
    console.log(evens);
}

window.onload = function(){
  document.getElementById("btn").onclick = evenDisplay;
}

CodePen

You need to add id="btn" to your button for this to work.

Btw definind event handlers in HTML is highly discouraged.


问:
How to output a sequence of images in a loop with ffmpeg from rtsp stream
I am reading an RTSP stream from a surveillance camera and want to use ffmpeg to create a snapshot of the camera as jpeg. Principally it works to create a snapshot.jpg using the -update 1 option, but if it happens (what it does very often) that the client application reads the file while ffmpeg writes to it, the image is displayed only partially.

Hence I want to use ffmpeg to capture more than 1 images in a kind of ring buffer, so I can access the image captured just before the current one and have also the last n images as short history.

Though ffmpeg allows to create a series of jpgs, this seems infinite. Is it possible to tell ffmpeg to create images in a file pattern like this:

pic1.jpg, pic2.jpg, pic3.jpg, pic4.jpg, pic5.jpg and after pic5.jpg to start over again using pic1.jpg etc. This way it could consume a stream continuously without filling up my drive. Unfortunately something like -update 5 seems not to work (ffmpeg simply exits).

Principally I can also let it run infinitely and clean up all files older than n seconds, but that would introduce additional overhead and is IMHO not really clean programming compared to ffmpeg using this kind of ring buffer approach.

Any help would be appreciated.

答:
You have to use the segment muxer.</p>

```<code>ffmpeg -i input -f segment -segment_time 0.0001 -segment_format singlejpeg -segment_wrap 5 pic%d.jpg
</code>```

Body:
You have to use the segment muxer.

ffmpeg -i input -f segment -segment_time 0.0001 -segment_format singlejpeg -segment_wrap 5 pic%d.jpg


问:
Convert list of dictionaries to a pandas DataFrame
How can I convert a list of dictionaries into a DataFrame? Given:

```<code>[{'points': 50, 'time': '5:00', 'year': 2010},
 {'points': 25, 'time': '6:00', 'month': "february"},
 {'points':90, 'time': '9:00', 'month': 'january'},
 {'points_h1':20, 'month': 'june'}]
</code>```

I want to turn the above into a DataFrame:

```<code>      month  points  points_h1  time  year
0       NaN      50        NaN  5:00  2010
1  february      25        NaN  6:00   NaN
2   january      90        NaN  9:00   NaN
3      june     NaN         20   NaN   NaN
</code>```

Note: Order of the columns does not matter.

答:
You can also use pd.DataFrame.from_dict(d) as :

```<code>In [8]: d = [{'points': 50, 'time': '5:00', 'year': 2010},
   ...: {'points': 25, 'time': '6:00', 'month': "february"},
   ...: {'points':90, 'time': '9:00', 'month': 'january'},
   ...: {'points_h1':20, 'month': 'june'}]

In [12]: pd.DataFrame.from_dict(d)
Out[12]:
      month  points  points_h1  time    year
0       NaN    50.0        NaN  5:00  2010.0
1  february    25.0        NaN  6:00     NaN
2   january    90.0        NaN  9:00     NaN
3      june     NaN       20.0   NaN     NaN
</code>```

Body:
How can I convert a list of dictionaries into a DataFrame? Given:

[{'points': 50, 'time': '5:00', 'year': 2010},
 {'points': 25, 'time': '6:00', 'month': "february"},
 {'points':90, 'time': '9:00', 'month': 'january'},
 {'points_h1':20, 'month': 'june'}]

I want to turn the above into a DataFrame:

      month  points  points_h1  time  year
0       NaN      50        NaN  5:00  2010
1  february      25        NaN  6:00   NaN
2   january      90        NaN  9:00   NaN
3      june     NaN         20   NaN   NaN

Note: Order of the columns does not matter.

Body:
You can also use pd.DataFrame.from_dict(d) as :

In [8]: d = [{'points': 50, 'time': '5:00', 'year': 2010},
   ...: {'points': 25, 'time': '6:00', 'month': "february"},
   ...: {'points':90, 'time': '9:00', 'month': 'january'},
   ...: {'points_h1':20, 'month': 'june'}]

In [12]: pd.DataFrame.from_dict(d)
Out[12]:
      month  points  points_h1  time    year
0       NaN    50.0        NaN  5:00  2010.0
1  february    25.0        NaN  6:00     NaN
2   january    90.0        NaN  9:00     NaN
3      june     NaN       20.0   NaN     NaN


问:
AVD Emulator stuck on loading screen in Android Studio
I decided to try Android Studio 2.0 having used Eclipse in the past but I'm having considerable difficulty getting the AVD to load correctly. I've done quite a bit of googling and research into the problem, both here on SO and Google.So far nothing has worked.

The emulator simply hangs on the android load-up screen ever time I try to run it. I've seen it advised to use Genymotion but I would first prefer to resolve the issue natively in Android Studio to feel confident going forward using the IDE for building projects.

Here's what I've tried:

Complete reinstall of Android, SDK and SDK Tools

Install and configure of Intel x86 accelerator

Lowered the RAM amount to 512 in AVD settings

Multiple attempts at deleting and recreating AVD's

Tried creating different AVD phone models(Nexus One,Nexus 5x etc.)

Resetting ADB in AVD Monitor Tool

Starting ADB server from terminal

Restarting Android Studio multiple times after changes

Running SDK/SDK Tools updates several times

Made sure the SDK path is correct

These are the majority of the "solutions" I found either on other similar SO questions or by googling none of which has resolved the problem.

When I run the emulator currently it displays the following in the run window:

```<code>/Users/<username>/Library/Android/sdk/tools/emulator -netdelay none -netspeed full -avd Nexus_5X_API_23
Warning: requested ram_size 1024M too big, reduced to 512M
emulator: WARNING: Increasing RAM size to 1024MB
emulator: WARNING: VM heap size set below hardware specified minimum of 228MB
emulator: WARNING: Setting VM heap size to 256MB
Hax is enabled
Hax ram_size 0x20000000
HAX is working and emulator runs in fast virt mode.
console on port 5554, ADB on port 5555
</code>```

The emulator shows up fine in the Android AVD Monitor devices pane and even appears to go through the entire booting process on the emulator screen itself but never gets to the Android home screen.
Also, Logcat seems to be looping continuously through dozens of errors and warnings, which don't offer any clear indication of what the issue might be or direction of how to resolve it.

I feel like I've exhausted every idea and not sure how to move forward.Just for the record, I am running El Capitan 10.9.2 with a 2.4gh Intel Core 2 Duo and 4gb ram.It's not the fastest machine for sure but should be capable of running Android Studio and the emulator.

Any help or guidance resolving this problem is gratefully appreciated!

答:
I had the same problem. I'm running El Capitan 10.11.5 with a 2.0GHz Intel Core 2 Duo and 8GB RAM, Android Studio 1.5.1.

After upgrading to Intel x86 Emulator Accelerator (HAXM Installer), rev 6.1.1 and deleting my API 14 SDK and related files, the newly installed API 23's Google APIs Intel x86 Atom System Image would not get past the Android logo screen.

After much trial & error, the Intel x86 Atom System Image (not Google APIs Intel x86 Atom System Image) for API 15 finally loaded the home screen on the emulator after ~ 8 min and one android system crash.

Will try the Intel x86 Atom System Image for API 23 later. Hope that helps.

Body:
I decided to try Android Studio 2.0 having used Eclipse in the past but I'm having considerable difficulty getting the AVD to load correctly. I've done quite a bit of googling and research into the problem, both here on SO and Google.So far nothing has worked.

The emulator simply hangs on the android load-up screen ever time I try to run it. I've seen it advised to use Genymotion but I would first prefer to resolve the issue natively in Android Studio to feel confident going forward using the IDE for building projects.

Here's what I've tried:

Complete reinstall of Android, SDK and SDK Tools

Install and configure of Intel x86 accelerator

Lowered the RAM amount to 512 in AVD settings

Multiple attempts at deleting and recreating AVD's

Tried creating different AVD phone models(Nexus One,Nexus 5x etc.)

Resetting ADB in AVD Monitor Tool

Starting ADB server from terminal

Restarting Android Studio multiple times after changes

Running SDK/SDK Tools updates several times

Made sure the SDK path is correct

These are the majority of the "solutions" I found either on other similar SO questions or by googling none of which has resolved the problem.

When I run the emulator currently it displays the following in the run window:

/Users/<username>/Library/Android/sdk/tools/emulator -netdelay none -netspeed full -avd Nexus_5X_API_23
Warning: requested ram_size 1024M too big, reduced to 512M
emulator: WARNING: Increasing RAM size to 1024MB
emulator: WARNING: VM heap size set below hardware specified minimum of 228MB
emulator: WARNING: Setting VM heap size to 256MB
Hax is enabled
Hax ram_size 0x20000000
HAX is working and emulator runs in fast virt mode.
console on port 5554, ADB on port 5555

The emulator shows up fine in the Android AVD Monitor devices pane and even appears to go through the entire booting process on the emulator screen itself but never gets to the Android home screen.
Also, Logcat seems to be looping continuously through dozens of errors and warnings, which don't offer any clear indication of what the issue might be or direction of how to resolve it.

I feel like I've exhausted every idea and not sure how to move forward.Just for the record, I am running El Capitan 10.9.2 with a 2.4gh Intel Core 2 Duo and 4gb ram.It's not the fastest machine for sure but should be capable of running Android Studio and the emulator.

Any help or guidance resolving this problem is gratefully appreciated!


问:
MVC application Viewengine not looking in Areas/{name}/Views instead looking in default Views folder
I am using 2017 VC for mac, the xamarian version of vs does not have the auto Areas Mapper. I manually added Areas folder and configured the routing properly, when I add an actionLink to my main csHTML page it is throwing an 500 error and stating.

```<code>System.InvalidOperationException
The view 'Billing' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/BillingMain/Billing.cshtml
~/Views/BillingMain/Billing.vbhtml
~/Views/Shared/Billing.cshtml
~/Views/Shared/Billing.vbhtml
~/Views/BillingMain/Billing.aspx
~/Views/BillingMain/Billing.ascx
~/Views/Shared/Billing.aspx
~/Views/Shared/Billing.ascx
</code>```

Instead it should be searching in ~/Areas/Billing/Views/BillingMainController.cshtml

I have tried everything to get this to work, but only keep on getting stuck.

Here is my directory hierarchy

```<code>Project-
    AppStart-
    Areas-
        Billing-
        Invoice-
    Controllers-
    Scripts-
    Views-
    Global.asax
</code>```

I am only testing Billing area for now, below is the rest of my code.

RouteConfig

```<code>using System.Web.Mvc;
using System.Web.Routing;

namespace WORK_GODDAMN
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //AreaRegistration.RegisterAllAreas();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                //,namespaces: new string[] { "WORK_GODDAMN.Areas.Controllers" }
            );

        }
    }
</code>```

}

BillingAreaRegistration.cs

```<code>using System;
using System.Web.Mvc;

namespace WORK_GODDAMN.Areas.Billing
{

    public class BillingAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Billing";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Billing_Default",
                "Billing/{controller}/{action}/{id}",
                new {controller = "BillingMain", action = "Index", id = UrlParameter.Optional }
                , namespaces: new string[] { "WORK_GODDAMN.Areas.Billing.Controllers" }
            );

        }
    }

}
</code>```

Global.asax

```<code>using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Http;

namespace WORK_GODDAMN
{
    public class Global : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
}
</code>```

main _Layout.cshtml this is where the Action Link redirects and believe I might be doing something wrong here, but at this point I have no clue what could be causing the problem.

```<code><!DOCTYPE html>

<html>
    @using System.Web.Optimization
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Scripts.Render("~/Scripts/modernizr.js")
</head>
<body>
    <div>
        <div>
            <h2>{Demo}- Pluggable Modules</h2>
        </div>
        <div id="nav">
            @Html.ActionLink("Home","Index","Home", new {Area=""}, null)
            @Html.ActionLink("Invoice","Index","InvoiceMain", new {Area=""}, null)
            @Html.ActionLink("Billing","Index","BillingMain", new {Area=""}, null)
        </div>
        <hr />
        <div>
                @RenderBody()
        </div>
    </div>
    @Scripts.Render("~/Scripts/jquery.js")
    @RenderSection("Scripts", required: false)
</body>
</html>
</code>```

答:
Figured it out, it was in my controller that the error was happening. Instead of returing return View("Index") I just gave the absolute path return View("~/Areas/Billing/Views/Index.cshtml") which is sort of a work-around, which is the only thing I found would work.

Also in the future if anyone wants to use html action link and model tags, you will need to manually add Web.Config file in both Areas/{area}/Views and Areas folder so you can use MVC framework in your cshtml View file. THIS IS FOR ANYONE WHO HAD TO MANUALLY CREATE AREAS if you use VS tool to add->Areas VS will automatically generate required files if you have VS do it, since Im using Mac Xamarin VS I don't have that convenient option.

This is what I had to change.

In {Project/Areas/Billing/Views/Index.cshtml} Change

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace WORK_GODDAMN.Controllers
{

    public class BillingMainController : Controller
    {
        // GET: Billing/BillingMain

        public ActionResult Index()
        {
            return View("Index");
        }
    }
}
</code>```

TO

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace WORK_GODDAMN.Controllers
{

    public class BillingMainController : Controller
    {
        // GET: Billing/BillingMain

        public ActionResult Index()
        {
            return View("~/Areas/Billing/Views/BillingMain/Index.cshtml");
        }
    }
}
</code>```

Body:
I am using 2017 VC for mac, the xamarian version of vs does not have the auto Areas Mapper. I manually added Areas folder and configured the routing properly, when I add an actionLink to my main csHTML page it is throwing an 500 error and stating.

System.InvalidOperationException
The view 'Billing' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/BillingMain/Billing.cshtml
~/Views/BillingMain/Billing.vbhtml
~/Views/Shared/Billing.cshtml
~/Views/Shared/Billing.vbhtml
~/Views/BillingMain/Billing.aspx
~/Views/BillingMain/Billing.ascx
~/Views/Shared/Billing.aspx
~/Views/Shared/Billing.ascx

Instead it should be searching in ~/Areas/Billing/Views/BillingMainController.cshtml

I have tried everything to get this to work, but only keep on getting stuck.

Here is my directory hierarchy

Project-
    AppStart-
    Areas-
        Billing-
        Invoice-
    Controllers-
    Scripts-
    Views-
    Global.asax

I am only testing Billing area for now, below is the rest of my code.

RouteConfig

using System.Web.Mvc;
using System.Web.Routing;

namespace WORK_GODDAMN
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //AreaRegistration.RegisterAllAreas();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                //,namespaces: new string[] { "WORK_GODDAMN.Areas.Controllers" }
            );

        }
    }

}

BillingAreaRegistration.cs

using System;
using System.Web.Mvc;

namespace WORK_GODDAMN.Areas.Billing
{

    public class BillingAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Billing";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Billing_Default",
                "Billing/{controller}/{action}/{id}",
                new {controller = "BillingMain", action = "Index", id = UrlParameter.Optional }
                , namespaces: new string[] { "WORK_GODDAMN.Areas.Billing.Controllers" }
            );

        }
    }

}

Global.asax

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Http;

namespace WORK_GODDAMN
{
    public class Global : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
}

main _Layout.cshtml this is where the Action Link redirects and believe I might be doing something wrong here, but at this point I have no clue what could be causing the problem.

<!DOCTYPE html>

    @using System.Web.Optimization

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Scripts.Render("~/Scripts/modernizr.js")

{Demo}- Pluggable Modules

            @Html.ActionLink("Home","Index","Home", new {Area=""}, null)
            @Html.ActionLink("Invoice","Index","InvoiceMain", new {Area=""}, null)
            @Html.ActionLink("Billing","Index","BillingMain", new {Area=""}, null)

                @RenderBody()

    @Scripts.Render("~/Scripts/jquery.js")
    @RenderSection("Scripts", required: false)

Body:
Figured it out, it was in my controller that the error was happening. Instead of returing return View("Index") I just gave the absolute path return View("~/Areas/Billing/Views/Index.cshtml") which is sort of a work-around, which is the only thing I found would work.

Also in the future if anyone wants to use html action link and model tags, you will need to manually add Web.Config file in both Areas/{area}/Views and Areas folder so you can use MVC framework in your cshtml View file. THIS IS FOR ANYONE WHO HAD TO MANUALLY CREATE AREAS if you use VS tool to add->Areas VS will automatically generate required files if you have VS do it, since Im using Mac Xamarin VS I don't have that convenient option.

This is what I had to change.

In {Project/Areas/Billing/Views/Index.cshtml} Change

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace WORK_GODDAMN.Controllers
{

    public class BillingMainController : Controller
    {
        // GET: Billing/BillingMain

        public ActionResult Index()
        {
            return View("Index");
        }
    }
}

TO

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace WORK_GODDAMN.Controllers
{

    public class BillingMainController : Controller
    {
        // GET: Billing/BillingMain

        public ActionResult Index()
        {
            return View("~/Areas/Billing/Views/BillingMain/Index.cshtml");
        }
    }
}


问:
How can I dynamically resize my iframe, avoiding the browser security crossdomain restrictions?
We have an embeddable badge that creates an iframe. It needs to be a dynamic size; it changes size based on data loaded from a 3rd party API or our database. So it's not known what height it will be before it loads.

It's invoked with a  tag that loads a script from our server, which creates an iframe set to a specific src.

On my own machine, within the iframe I can do

```<code>window.parent.document.getElementById('my_frame').style.height=new_calculated_height+'px';
</code>```

but of course when it's embedded in a page different than the iframe src, that fails due to crossdomain restrictions ('unsafe access attempt' error in FF, etc.).

As we're already loading a script into the host page with full access, this is kind of silly.

Basically, I need to get a variable, the new height, from the iframe into the host page.

Could I do it in reverse maybe? Have a function on the host page ask the iframe for it's an element's offsetHeight?

答: Although i have no particular experience with this situation referencing the following wouldn't hurt: Cross Domain Iframe Resize</p>

Body:
We have an embeddable badge that creates an iframe. It needs to be a dynamic size; it changes size based on data loaded from a 3rd party API or our database. So it's not known what height it will be before it loads.

It's invoked with a  tag that loads a script from our server, which creates an iframe set to a specific src.

On my own machine, within the iframe I can do

window.parent.document.getElementById('my_frame').style.height=new_calculated_height+'px';

but of course when it's embedded in a page different than the iframe src, that fails due to crossdomain restrictions ('unsafe access attempt' error in FF, etc.).

As we're already loading a script into the host page with full access, this is kind of silly.

Basically, I need to get a variable, the new height, from the iframe into the host page.

Could I do it in reverse maybe? Have a function on the host page ask the iframe for it's an element's offsetHeight?


问:
how to grab only first few commits with Git bundle create
I have a git repo and I want to use the git bundle command to only grab a portion of the repo.

Lets say there are 10 commits in this repo, but I only want to grab the first 3? And maybe at a later time grab the next 3? and so on

How can I leverage the git bundle command in order to do this?

Feel free to fill in the blanks on other details I may have not provided, that could be useful to you.

答:
UPDATE - incorporating info about a limitation of bundles.  tl;dr - you have to have a ref at the bundle's head

The commits to include in the bundle are specified using the same syntax you would use to specify what you want to see in a log command (among others), with the exception that you must use named refs (branches or tags) to indicate what should be included.  So for your example (bundle the 1st 3 commits, then later the next 3, from a repo with 10 commits):

You have a repo with

```<code>A -- B -- C -- D -- E -- F -- G -- H -- I -- J <--(master)
</code>```

Then you say

```<code>git bundle create a_to_c.bundle C
</code>```

where C a ref (branch or tag) pointing to C.  Later

```<code>git bundle create d_to_f.bundle C..F
</code>```

In this case C may be the SHA ID for commit C (or an unambiguous prefix of that ID), or it may still be a re; but F must be a ref (tag or branch) pointing to commit F.

This syntax works any time you want to include what's reachable from one commit (F in this example) except for what's reachable from another (C).  An equivalent command is

```<code>git bundle create d_to_f.bundle ^C F
</code>```

which shows a more general syntax wherein you can easily add multiple commits to  be included or excluded.

You note in comments that you could make this work with tags, but not SHA ID's.  What I had forgotten - but someone pointed out to me in the form of an unfortunately-unclear edit - is that a bundle cannot contain dangling commits.  Every commit in the bundle must be reachable from a ref in the bundle.  I suppose this prevents creation of dangling objects that would be difficult to access - and that would be immediately eligible for gc in any case - when applying the bundle to another repo.

Body:
UPDATE - incorporating info about a limitation of bundles.  tl;dr - you have to have a ref at the bundle's head

The commits to include in the bundle are specified using the same syntax you would use to specify what you want to see in a log command (among others), with the exception that you must use named refs (branches or tags) to indicate what should be included.  So for your example (bundle the 1st 3 commits, then later the next 3, from a repo with 10 commits):

You have a repo with

A -- B -- C -- D -- E -- F -- G -- H -- I -- J <--(master)

Then you say

git bundle create a_to_c.bundle C

where C a ref (branch or tag) pointing to C.  Later

git bundle create d_to_f.bundle C..F

In this case C may be the SHA ID for commit C (or an unambiguous prefix of that ID), or it may still be a re; but F must be a ref (tag or branch) pointing to commit F.

This syntax works any time you want to include what's reachable from one commit (F in this example) except for what's reachable from another (C).  An equivalent command is

git bundle create d_to_f.bundle ^C F

which shows a more general syntax wherein you can easily add multiple commits to  be included or excluded.

You note in comments that you could make this work with tags, but not SHA ID's.  What I had forgotten - but someone pointed out to me in the form of an unfortunately-unclear edit - is that a bundle cannot contain dangling commits.  Every commit in the bundle must be reachable from a ref in the bundle.  I suppose this prevents creation of dangling objects that would be difficult to access - and that would be immediately eligible for gc in any case - when applying the bundle to another repo.


问:
How to cross-compile a Qt Quick application for the Raspberry Pi?
I successfully cross-compiled "standard" Qt applications (QT += core gui) for a Raspberry Pi, but I'm having trouble to do the same with Qt Quick (QT += quick).

I installed a cross-compiling tool-chain and successfully compiled Qt with it, and my Qt GUI applications can now run on the Raspberry Pi.

Now I tried to run one of the Qt Quick examples on the Raspberry Pi, without success. I open the example from Welcome/Examples, I can successfully build and run them on my PC with Debian, but if I try to build it for the Raspberry Pi (by adding the same kit I used for the regular Qt applications), it doesn't even compile. It gives the following error:

```<code>:-1: error: Unknown module(s) in QT: quick
</code>```

This seems to indicate that Qt Quick is not part of my Qt build.

I checked again how the cross-compiler is configured:

```<code>Building on:   linux-g++ (x86_64, CPU features: mmx sse sse2)
Building for:  devices/linux-rasp-pi-g++ (arm, CPU features: none detected)
Platform notes:

            - Also available for Linux: linux-clang linux-kcc linux-icc linux-cxx

Build options:
  Configuration .......... accessibility audio-backend c++11 clock-gettime clock-monotonic compile_examples concurrent cross_compile dbus egl eglfs eglfs_brcm enable_new_dtags evdev eventfd freetype full-config getaddrinfo getifaddrs harfbuzz iconv inotify ipv6ifname large-config largefile linuxfb medium-config minimal-config mremap nis no-pkg-config opengl opengles2 pcre png posix_fallocate precompile_header qpa qpa reduce_exports release rpath shared small-config system-zlib threadsafe-cloexec
  Build parts ............  libs
  Mode ................... release
  Using sanitizer(s)...... none
  Using C++ standard ..... c++11
  Using gold linker....... no
  Using new DTAGS ........ yes
  Using PCH .............. yes
  Target compiler supports:
    Neon ................. no

Qt modules and options:
  Qt D-Bus ............... yes (loading dbus-1 at runtime)
  Qt Concurrent .......... yes
  Qt GUI ................. yes
  Qt Widgets ............. yes
  Large File ............. yes
  QML debugging .......... yes
  Use system proxies ..... no

Support enabled for:
  Accessibility .......... yes
  ALSA ................... no
  CUPS ................... no
  Evdev .................. yes
  FontConfig ............. no
  FreeType ............... yes (bundled copy)
  Glib ................... no
  GStreamer .............. no
  GTK theme .............. no
  HarfBuzz ............... yes (bundled copy)
  Iconv .................. yes
  ICU .................... no
  Image formats:
    GIF .................. yes (plugin, using bundled copy)
    JPEG ................. yes (plugin, using bundled copy)
    PNG .................. yes (in QtGui, using bundled copy)
  libinput................ no
  Logging backends:
    journald ............... no
    syslog   ............... no
  mtdev .................. no
  Networking:
    getaddrinfo .......... yes
    getifaddrs ........... yes
    IPv6 ifname .......... yes
    libproxy.............. no
    OpenSSL .............. no
  NIS .................... yes
  OpenGL / OpenVG:
    EGL .................. yes
    OpenGL ............... yes (OpenGL ES 2.0+)
    OpenVG ............... no
  PCRE ................... yes (bundled copy)
  pkg-config ............. no
  PulseAudio ............. no
  QPA backends:
    DirectFB ............. no
    EGLFS ................ yes
      EGLFS i.MX6....... . no
      EGLFS KMS .......... no
      EGLFS Mali ......... no
      EGLFS Raspberry Pi . yes
      EGLFS X11 .......... no
    LinuxFB .............. yes
    Mir client............ no
    XCB .................. no
  Session management ..... yes
  SQL drivers:
    DB2 .................. no
    InterBase ............ no
    MySQL ................ no
    OCI .................. no
    ODBC ................. no
    PostgreSQL ........... no
    SQLite 2 ............. no
    SQLite ............... yes (plugin, using bundled copy)
    TDS .................. no
  tslib .................. no
  udev ................... no
  xkbcommon-x11........... no
  xkbcommon-evdev......... no
  zlib ................... yes (system library)
</code>```

Qt Quick doesn't even appear in the list of options. Does this mean that the cross-compiler doesn't support it? The option "QML debugging" makes me think that it should be, because what else should be using QML if not Qt Quick.

OpenGL 2.0 is active, so that shouldn't be the problem.

答:
I used QtRpi script successfully with a Raspberry 3. You can download it at http://www.qtrpi.com, it's a ready to use tools to install a cross compiler toolchain on your Linux host pc and a complete deployment environment on Rpi.

I use it with Qt Quick for my applications, it runs without any problem.

Body:
I successfully cross-compiled "standard" Qt applications (QT += core gui) for a Raspberry Pi, but I'm having trouble to do the same with Qt Quick (QT += quick).

I installed a cross-compiling tool-chain and successfully compiled Qt with it, and my Qt GUI applications can now run on the Raspberry Pi.

Now I tried to run one of the Qt Quick examples on the Raspberry Pi, without success. I open the example from Welcome/Examples, I can successfully build and run them on my PC with Debian, but if I try to build it for the Raspberry Pi (by adding the same kit I used for the regular Qt applications), it doesn't even compile. It gives the following error:

:-1: error: Unknown module(s) in QT: quick

This seems to indicate that Qt Quick is not part of my Qt build.

I checked again how the cross-compiler is configured:

Building on:   linux-g++ (x86_64, CPU features: mmx sse sse2)
Building for:  devices/linux-rasp-pi-g++ (arm, CPU features: none detected)
Platform notes:

            - Also available for Linux: linux-clang linux-kcc linux-icc linux-cxx

Build options:
  Configuration .......... accessibility audio-backend c++11 clock-gettime clock-monotonic compile_examples concurrent cross_compile dbus egl eglfs eglfs_brcm enable_new_dtags evdev eventfd freetype full-config getaddrinfo getifaddrs harfbuzz iconv inotify ipv6ifname large-config largefile linuxfb medium-config minimal-config mremap nis no-pkg-config opengl opengles2 pcre png posix_fallocate precompile_header qpa qpa reduce_exports release rpath shared small-config system-zlib threadsafe-cloexec
  Build parts ............  libs
  Mode ................... release
  Using sanitizer(s)...... none
  Using C++ standard ..... c++11
  Using gold linker....... no
  Using new DTAGS ........ yes
  Using PCH .............. yes
  Target compiler supports:
    Neon ................. no

Qt modules and options:
  Qt D-Bus ............... yes (loading dbus-1 at runtime)
  Qt Concurrent .......... yes
  Qt GUI ................. yes
  Qt Widgets ............. yes
  Large File ............. yes
  QML debugging .......... yes
  Use system proxies ..... no

Support enabled for:
  Accessibility .......... yes
  ALSA ................... no
  CUPS ................... no
  Evdev .................. yes
  FontConfig ............. no
  FreeType ............... yes (bundled copy)
  Glib ................... no
  GStreamer .............. no
  GTK theme .............. no
  HarfBuzz ............... yes (bundled copy)
  Iconv .................. yes
  ICU .................... no
  Image formats:
    GIF .................. yes (plugin, using bundled copy)
    JPEG ................. yes (plugin, using bundled copy)
    PNG .................. yes (in QtGui, using bundled copy)
  libinput................ no
  Logging backends:
    journald ............... no
    syslog   ............... no
  mtdev .................. no
  Networking:
    getaddrinfo .......... yes
    getifaddrs ........... yes
    IPv6 ifname .......... yes
    libproxy.............. no
    OpenSSL .............. no
  NIS .................... yes
  OpenGL / OpenVG:
    EGL .................. yes
    OpenGL ............... yes (OpenGL ES 2.0+)
    OpenVG ............... no
  PCRE ................... yes (bundled copy)
  pkg-config ............. no
  PulseAudio ............. no
  QPA backends:
    DirectFB ............. no
    EGLFS ................ yes
      EGLFS i.MX6....... . no
      EGLFS KMS .......... no
      EGLFS Mali ......... no
      EGLFS Raspberry Pi . yes
      EGLFS X11 .......... no
    LinuxFB .............. yes
    Mir client............ no
    XCB .................. no
  Session management ..... yes
  SQL drivers:
    DB2 .................. no
    InterBase ............ no
    MySQL ................ no
    OCI .................. no
    ODBC ................. no
    PostgreSQL ........... no
    SQLite 2 ............. no
    SQLite ............... yes (plugin, using bundled copy)
    TDS .................. no
  tslib .................. no
  udev ................... no
  xkbcommon-x11........... no
  xkbcommon-evdev......... no
  zlib ................... yes (system library)

Qt Quick doesn't even appear in the list of options. Does this mean that the cross-compiler doesn't support it? The option "QML debugging" makes me think that it should be, because what else should be using QML if not Qt Quick.

OpenGL 2.0 is active, so that shouldn't be the problem.


问:
Softlayer API: How to get the static subnet belongs to which VSI?

background

I can get a vlan's subnet info by the flowing python script:

```<code># Declare an Object Mask to get additional information
    object_mask = 'mask[primaryRouter,subnets[id,billingItem,cidr,version,addressSpace,subnetType,networkIdentifier,totalIpAddresses,usableIpAddressCount,ipAddresses[ipAddress, isReserved, virtualGuest, hardware]]]'
    # Declare an Object Filter to get information from specific vlan
    filter = {'networkVlans': {'id': {'operation': vlan_id}}}
    return self.sl_account.getNetworkVlans(mask=object_mask, filter=filter)[0]
</code>```

And the result contains:

```<code>[... 'subnets': [{'cidr': 28,
              'id': 986245,
              'billingItem': {'allowCancellationFlag': 1,}
              orderItemId': 223126909,
              'ipAddresses': [{'ipAddress': '169.38.73.xxx', ...
               'subnetType': 'STATIC_IP_ROUTED',
             'totalIpAddresses': '8',
             'usableIpAddressCount': '5',
             'version': 4},
             ...]
            }
            ...
            ]]
</code>```

question

The result of STATIC_IP_ROUTED subnet do not contain the  virtualGuest item.

Now I want to know which VSI has bind this subnet?  Does any other mask can helps?

Or, How can I get the secondary ip info of a vsi?

答:
You may add the subnets relational property to go deeper and display the VSI on  which the subnet is binded through the property endpointIpAddress.

Please try your code with the mask previously mentioned:

```<code># Declare an Object Mask to get additional information
object_mask = 'mask[primaryRouter,subnets[id,billingItem,cidr,version,addressSpace,subnetType,networkIdentifier,totalIpAddresses,usableIpAddressCount,ipAddresses[id, ipAddress, virtualGuest[id], hardware[id]]], subnets[endPointIpAddress[id,ipAddress,subnet[id, datacenter[longName,name]],hardware[id,fullyQualifiedDomainName],virtualGuest[id,fullyQualifiedDomainName]]]]'

# Declare an Object Filter to get information from specific vlan
filter = {'networkVlans': {'id': {'operation': vlan_id}}}

return self.sl_account.getNetworkVlans(mask=object_mask, filter=filter)[0]
</code>```

Or you may use the SoftLayer_Account::getSubnets method.

```<code># Declare an Object Mask to get additional subnet information
object_mask = 'mask[id, networkIdentifier, subnetType, totalIpAddresses, datacenter[longName, name], networkVlan[id, vlanNumber], endPointIpAddress[id,ipAddress,subnet[id, datacenter[longName,name]],hardware[id,fullyQualifiedDomainName],virtualGuest[id,fullyQualifiedDomainName]]]'

# Declare an Object Filter to get information from specific Subnet.
filter = {"subnets":{"id":{"operation":subnet_id}}}

subnetsResult = client ['Account'].getSubnets(filter = filter, mask = object_mask)

print(subnetsResult)
</code>```

On both solutions you will see the VirtualGuest item information.

In order to retrieve the secondary ip Addresses of a VSI please refer to this post How to get secondary ip addresses.

Body:
background

I can get a vlan's subnet info by the flowing python script:

# Declare an Object Mask to get additional information
    object_mask = 'mask[primaryRouter,subnets[id,billingItem,cidr,version,addressSpace,subnetType,networkIdentifier,totalIpAddresses,usableIpAddressCount,ipAddresses[ipAddress, isReserved, virtualGuest, hardware]]]'
    # Declare an Object Filter to get information from specific vlan
    filter = {'networkVlans': {'id': {'operation': vlan_id}}}
    return self.sl_account.getNetworkVlans(mask=object_mask, filter=filter)[0]

And the result contains:

[... 'subnets': [{'cidr': 28,
              'id': 986245,
              'billingItem': {'allowCancellationFlag': 1,}
              orderItemId': 223126909,
              'ipAddresses': [{'ipAddress': '169.38.73.xxx', ...
               'subnetType': 'STATIC_IP_ROUTED',
             'totalIpAddresses': '8',
             'usableIpAddressCount': '5',
             'version': 4},
             ...]
            }
            ...
            ]]

question

The result of STATIC_IP_ROUTED subnet do not contain the  virtualGuest item.

Now I want to know which VSI has bind this subnet?  Does any other mask can helps?

Or, How can I get the secondary ip info of a vsi?

Body:
You may add the subnets relational property to go deeper and display the VSI on  which the subnet is binded through the property endpointIpAddress.

Please try your code with the mask previously mentioned:

# Declare an Object Mask to get additional information
object_mask = 'mask[primaryRouter,subnets[id,billingItem,cidr,version,addressSpace,subnetType,networkIdentifier,totalIpAddresses,usableIpAddressCount,ipAddresses[id, ipAddress, virtualGuest[id], hardware[id]]], subnets[endPointIpAddress[id,ipAddress,subnet[id, datacenter[longName,name]],hardware[id,fullyQualifiedDomainName],virtualGuest[id,fullyQualifiedDomainName]]]]'

# Declare an Object Filter to get information from specific vlan
filter = {'networkVlans': {'id': {'operation': vlan_id}}}

return self.sl_account.getNetworkVlans(mask=object_mask, filter=filter)[0]

Or you may use the SoftLayer_Account::getSubnets method.

# Declare an Object Mask to get additional subnet information
object_mask = 'mask[id, networkIdentifier, subnetType, totalIpAddresses, datacenter[longName, name], networkVlan[id, vlanNumber], endPointIpAddress[id,ipAddress,subnet[id, datacenter[longName,name]],hardware[id,fullyQualifiedDomainName],virtualGuest[id,fullyQualifiedDomainName]]]'

# Declare an Object Filter to get information from specific Subnet.
filter = {"subnets":{"id":{"operation":subnet_id}}}

subnetsResult = client ['Account'].getSubnets(filter = filter, mask = object_mask)

print(subnetsResult)

On both solutions you will see the VirtualGuest item information.

In order to retrieve the secondary ip Addresses of a VSI please refer to this post How to get secondary ip addresses.


问:
Portable SQL upsert (insert+update) solution needed
I need to perform a very simple operation on the database - put some values into the table by key, if the row exists - update it, if not - create a new one. The problem is that I need to do it in a portable way - i.e. the same query must work on MySQL, SQL Server, Oracle and preferably also DB2, Postgres, etc. So while I could use REPLACE or INSERT ... ON DUPLICATE KEY UPDATE in MySQL, I'm not sure that these would support such syntax. And I really want to avoid if's by database type, because this would be unmaintainable. I also don't want to actually query the value before updating, because I suspect it would slow down the process significantly (I need to do it multiple times).

So far the best I came up with is just doing:

```<code>  UPDATE table SET data='data' WHERE key='key';
  INSERT INTO table(key, data) VALUES ('key', 'data');
</code>```

one of those would always succeed and another fail, but I don't care that one of the queries fails. It looks kind of inelegant though. Any suggestions how to make it better?

答:
The only completely database-agnostic solution, using somewhat modern databases, is to call the Update then the Insert in two operations. Some databases do not allow for multiple statements sent in a single operation and some databases might not return the number of rows affected by the Update so I would not rely upon that.

```<code>Update MyTable
Set Data = 'Data'
Where KeyCol = 'key';
</code>```

(separate call)

```<code>Insert Into MyTable(KeyCol, Data)
Select 'key', 'Data'
From ( Select 1 As Value ) As Z
Where Not Exists    (
                    Select 1
                    From MyTable As T1
                    Where T1.KeyCol = 'key'
                    );
</code>```

Body:
I need to perform a very simple operation on the database - put some values into the table by key, if the row exists - update it, if not - create a new one. The problem is that I need to do it in a portable way - i.e. the same query must work on MySQL, SQL Server, Oracle and preferably also DB2, Postgres, etc. So while I could use REPLACE or INSERT ... ON DUPLICATE KEY UPDATE in MySQL, I'm not sure that these would support such syntax. And I really want to avoid if's by database type, because this would be unmaintainable. I also don't want to actually query the value before updating, because I suspect it would slow down the process significantly (I need to do it multiple times).

So far the best I came up with is just doing:

  UPDATE table SET data='data' WHERE key='key';
  INSERT INTO table(key, data) VALUES ('key', 'data');

one of those would always succeed and another fail, but I don't care that one of the queries fails. It looks kind of inelegant though. Any suggestions how to make it better?

Body:
The only completely database-agnostic solution, using somewhat modern databases, is to call the Update then the Insert in two operations. Some databases do not allow for multiple statements sent in a single operation and some databases might not return the number of rows affected by the Update so I would not rely upon that.

Update MyTable
Set Data = 'Data'
Where KeyCol = 'key';

(separate call)

Insert Into MyTable(KeyCol, Data)
Select 'key', 'Data'
From ( Select 1 As Value ) As Z
Where Not Exists    (
                    Select 1
                    From MyTable As T1
                    Where T1.KeyCol = 'key'
                    );


问:
Why is my pandas dataframe not updating its values as I change them?
I am trying to make changes to each string in my Series object 'tweet_text', but for some reason when I print the series object after making changes to the tweets in my for loop, I get the same strings as I had before the for loop. How can I fix this?  </p>

```<code>import pandas as pd
import re
import string

df = pd.read_csv('sample-tweets.csv',
                 names=['Tweet_Date', 'User_ID', 'Tweet_Text', 'Favorites', 'Retweets', 'Tweet_ID'])

sum_df = df[['User_ID', 'Tweet_ID', 'Tweet_Text']].copy()
sum_df.set_index(['User_ID'])
# print sum_df

tweet_text = df.ix[:, 2]
print type(tweet_text)

# efficiency could be im proved by using translate method
# regex = re.compile('[%s]' % re.escape(string.punctuation))

for tweet in tweet_text:
    tweet = re.sub('https://t.co/[a-zA-Z0-9]*', "", tweet)
    tweet = re.sub('@[a-zA-Z0-9]*', '', tweet)
    tweet = re.sub('#[a-zA-Z0-9]*', '', tweet)
    tweet = re.sub('$[a-zA-Z0-9]*', '', tweet)
    tweet = ''.join(i for i in tweet if not i.isdigit())
    tweet = tweet.replace('"', '')
    tweet = re.sub(r'[\(\[].*?[\)\]]', '', tweet)  # takes out everything between parentheses also, fix this

    # gets rid of all punctuation and emoji's
    tweet = "".join(l for l in tweet if l not in string.punctuation)
    tweet = re.sub(r'[^\x00-\x7F]+',' ', tweet)

    # gets ride of all extra spacing
    tweet = tweet.lower()
    tweet = tweet.strip()
    tweet = " ".join(tweet.split())

    count = count + 1
    # print tweet

print tweet_text
</code>```

答:
Python strings are immutable. You are just changing the value attributed to variable tweet, but never actually updating the dataframe.

You just have to reinsert the updated value back to your dataframe. Example of a simple fix:

```<code>for i, tweet in enumerate(tweet_text):
    tweet = re.sub('https://t.co/[a-zA-Z0-9]*', "", tweet)
    tweet = re.sub('@[a-zA-Z0-9]*', '', tweet)

    # ...

    # update dataframe
    df.ix[i, 2] = tweet
</code>```

Body:
I am trying to make changes to each string in my Series object 'tweet_text', but for some reason when I print the series object after making changes to the tweets in my for loop, I get the same strings as I had before the for loop. How can I fix this?

import pandas as pd
import re
import string

df = pd.read_csv('sample-tweets.csv',
                 names=['Tweet_Date', 'User_ID', 'Tweet_Text', 'Favorites', 'Retweets', 'Tweet_ID'])

sum_df = df[['User_ID', 'Tweet_ID', 'Tweet_Text']].copy()
sum_df.set_index(['User_ID'])
# print sum_df

tweet_text = df.ix[:, 2]
print type(tweet_text)

# efficiency could be im proved by using translate method
# regex = re.compile('[%s]' % re.escape(string.punctuation))

for tweet in tweet_text:
    tweet = re.sub('https://t.co/[a-zA-Z0-9]*', "", tweet)
    tweet = re.sub('@[a-zA-Z0-9]*', '', tweet)
    tweet = re.sub('#[a-zA-Z0-9]*', '', tweet)
    tweet = re.sub('$[a-zA-Z0-9]*', '', tweet)
    tweet = ''.join(i for i in tweet if not i.isdigit())
    tweet = tweet.replace('"', '')
    tweet = re.sub(r'[\(\[].*?[\)\]]', '', tweet)  # takes out everything between parentheses also, fix this

    # gets rid of all punctuation and emoji's
    tweet = "".join(l for l in tweet if l not in string.punctuation)
    tweet = re.sub(r'[^\x00-\x7F]+',' ', tweet)

    # gets ride of all extra spacing
    tweet = tweet.lower()
    tweet = tweet.strip()
    tweet = " ".join(tweet.split())

    count = count + 1
    # print tweet

print tweet_text

Body:
Python strings are immutable. You are just changing the value attributed to variable tweet, but never actually updating the dataframe.

You just have to reinsert the updated value back to your dataframe. Example of a simple fix:

for i, tweet in enumerate(tweet_text):
    tweet = re.sub('https://t.co/[a-zA-Z0-9]*', "", tweet)
    tweet = re.sub('@[a-zA-Z0-9]*', '', tweet)

    # ...

    # update dataframe
    df.ix[i, 2] = tweet


答:
function evenDisplay() {

    var starting = parseInt(document.getElementById("starting").value);
    var step = parseInt(document.getElementById("step").value);
    if(!isNaN(starting)&&!isNaN(step)){
    var evens = [];
    var x=(step*2)+starting;
    for (i = starting+1;  i <=x; i++) { /* this loop would show as much as evens number as long value of i<= set to  and doesn't care if the user enter the number of evens */
        i % 2 || evens.push(i);
    }
   console.log(evens);
}

else{console.log("Nan");}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
           <h1>Enter Number</h1>
           <form name="number" class="form-inline">
           <div class="form-group">
            <label for="starting">Starting Number</label>
            <input type="text" id="starting" class="form-control">
           </div> <div class="form-group">
               <label for="step">numbers of evens</label>
               <input type="text" id="step" class="form-control">
           </div>

           <button type="button" onclick="javascript:evenDisplay();" class="btn" >submit</button></code>```

Here I use the equation =(step*2)+starting to loop with in the required range also I check if isNaN for the input values

Body:
hello all i'm trying to make javascript to display an evens numbers by using a form with start number and number of evens to display. user will enter starting number and enter the number of even to display.
say start at 7 number of evens is 3 should display 8 10 12.  just need some direction. thanks

my code:

<title>evens</title>

Enter Number

           <form name="number" class="form-inline">

            Starting Number
            <input type="text" id="starting" class="form-control">

               numbers of evens
               <input type="text" id="step" class="form-control">

           <button type="button" onclick="evenDisplay()" class="btn" >submit</button>

Body:
function evenDisplay() {

    var starting = parseInt(document.getElementById("starting").value);
    var step = parseInt(document.getElementById("step").value);
    if(!isNaN(starting)&&!isNaN(step)){
    var evens = [];
    var x=(step*2)+starting;
    for (i = starting+1;  i <=x; i++) { /* this loop would show as much as evens number as long value of i<= set to  and doesn't care if the user enter the number of evens */
        i % 2 || evens.push(i);
    }
   console.log(evens);
}

else{console.log("Nan");}
}

<div class="container">
           <h1>Enter Number</h1>
           <form name="number" class="form-inline">
           <div class="form-group">
            <label for="starting">Starting Number</label>
            <input type="text" id="starting" class="form-control">
           </div> <div class="form-group">
               <label for="step">numbers of evens</label>
               <input type="text" id="step" class="form-control">
           </div>

           <button type="button" onclick="javascript:evenDisplay();" class="btn" >submit</button>

Here I use the equation =(step*2)+starting to loop with in the required range also I check if isNaN for the input values


问:
Tcl Tk double click binding is blocked by another binding
I work with tcl 8.6

I've got two tablelists (by Nehmeti):

```<code>set pfd(frMain) [frame $fr.frMain]
set pfd(bottomFr) [frame $pfd(frMain).bfr]
set pfd(panWin) [panedwindow $pfd(bottomFr).pw -showhandle 1 -orient vertical -sashpad 0 -sashrelief raised -sashwidth 2]
set pfd(frKlaffNeupkt) [frame $pfd(panWin).frKlaffNeupkt]
pack $pfd(frMesswerte)   -anchor nw -expand 0 -fill both
pack $pfd(frKlaffNeupkt) -anchor nw -expand 0 -fill both
pack $pfd(panWin) -anchor nw -expand 1 -fill both
$pfd(panWin) add $pfd(frMesswerte) $pfd(frKlaffNeupkt)
set pfd(tali_mw) [tablelist::tablelist $pfd(frMesswerte).li.tali_mw \
                  -columns {0 "oid" l \
                            0 "status" l \
                            0 "art" l \
                            0 "sollTyp" l \
                            0 "Nr" l \
                            0 "Typ" l \
                            0 "Gst" l \
                            0 "Hz" r \
                            0 "V" r \
                            0 "S" r \
                            0 "Q" r \
                            0 "L" r \
                            0 "AK" l\
                            0 "LSEX" l \
                            0 "lfdNrGes" l}\
                  -exportselection 0 \
                  -labelbackground #EEEEEE \
                  -background white \
                  -labelfont $tableheadfont\
                  -font $tableinhfont\
                  -stretch 12\
                  -selectbackground $vmVConfig::setVar(activeBG) \
                  -selectforeground $vmVConfig::setVar(activeFG) \
                  -selectmode single\
                  -borderwidth 1 \
                  -labelborderwidth 1 \
                  -selectborderwidth 0 \
                  -tooltipaddcommand [::itcl::code $this tooltipAddCmd] \
                  -tooltipdelcommand [::itcl::code $this tooltipDelCmd] \
                  -xscrollcommand [list vmTkTools::configSB "h" $pfd(mw_scrx)]\
                  -yscrollcommand [list vmTkTools::configSB "v" $pfd(mw_scry)]]

set pfd(noteb) [iwidgets::notebook $pfd(frKlaffNeupkt).noteb]
pack $pfd(noteb) -anchor nw -expand 1 -fill both
set pfd(frKlaffungen) [$pfd(noteb) add -label Klaffungen]

set pfd(tali_klaff) [tablelist::tablelist $pfd(frKlaffungen).li.tali_klaff \
                      -columns {0 "oid" l 0 "Nr" l 0 "dX" r 0 "dY" r 0 "GwX" r 0 "GwY" r 0 "Rdz" r 0 "lfdNrGes" r}\
                      -exportselection 0 \
                      -labelbackground #EEEEEE \
                      -background white \
                      -labelfont $tableheadfont\
                      -font $tableinhfont\
                      -stretch 7\
                      -selectbackground $vmVConfig::setVar(activeBG) \
                      -selectforeground $vmVConfig::setVar(activeFG) \
                      -selectmode single\
                      -labelrelief groove \
                      -borderwidth 1 \
                      -labelborderwidth 1 \
                      -selectborderwidth 0 \
                      -xscrollcommand [list vmTkTools::configSB "h" $pfd(klaff_scrx)]\
                      -yscrollcommand [list vmTkTools::configSB "v" $pfd(klaff_scry)]]
</code>```

Both tablelist have Bindings:

```<code>set body [$pfd(tali_mw) bodypath]
bind $body <Button-1> +[::itcl::code $this klickZeile %x %y %W]
bind $body <Double-1> +[::itcl::code $this doubleKlickMesswerte %x %y %W]

set body [$pfd(tali_klaff) bodypath]
bind $body <Button-1> [::itcl::code $this klickZeile %x %y %W]
</code>```

The method klickZeile looks like this

```<code>itcl::body vmMaskHelmert::klickZeile {x y W} {
   puts "klickZeile"

   delCommonKreuz

   foreach {pfad xC yC} [tablelist::convEventFields $W $x $y] {}
   set row    [$pfad containing $yC]
   if {$row == -1} {
      set row end
   }

   if {[string first "tali_mw" $W] != -1} {
      # select the row
      $pfd(tali_mw) activate $row
      $pfd(tali_mw) selection clear 0 end
      $pfd(tali_mw) selection set $row $row
      anzeigePpMp
   } else {
      $pfd(tali_klaff) activate $row
      $pfd(tali_klaff) selection clear 0 end
      $pfd(tali_klaff) selection set $row $row
      anzeigePpMp4Klaff
   }
   return
}
</code>```

It seems, that the method klickZeile blocks my double click binding, the method doubleKlickMesswerte is not being called.

In klickZeile two corresponding rows in both tablelists are selected.

I tried to comment out the two blocks with "activate $row, selection clear 0 end and selection set $row $row". In that case, doubleKlickMesswerte is being called but unfortunately the method klickZeile doesn't work correctly. It seems that in that case the method selects the corresponding row for the row selected before.

So I've got two questions:

How can I prevent the method klickZeile from blocking the double click binding?
Or, if there is no way for this, what can I do, to make the method "klickZeile" work correctly without extra selection and activation?

Thanks for your help!

答:
Mouse click events (at least single/double/triple) without modifiers (like Control) will all trigger when a bind to triple is set up and the user triple-clicks on the target element. The GUI cannot predict that another click is coming. It has to dispatch the single-click event first, followed by the double, then the triple.

Your best alternative is to use a modifier, such as a , because this is unique and does not depend on sequence, as long as the Control button is pressed first ;)

```<code>proc doClick { widget } {
    puts "You clicked [$widget cget -text]"
}

proc doControlClick { widget } {
    puts "You control-clicked [$widget cget -text]"
}

set label_1 [label .l1 -text "This is label 1"]
pack $label_1 -side top -fill both

bind $label_1 <Control-Button-1> { doControlClick %W }
bind $label_1 <Button-1> { doClick %W }
</code>```

Body:
I work with tcl 8.6

I've got two tablelists (by Nehmeti):

set pfd(frMain) [frame $fr.frMain]
set pfd(bottomFr) [frame $pfd(frMain).bfr]
set pfd(panWin) [panedwindow $pfd(bottomFr).pw -showhandle 1 -orient vertical -sashpad 0 -sashrelief raised -sashwidth 2]
set pfd(frKlaffNeupkt) [frame $pfd(panWin).frKlaffNeupkt]
pack $pfd(frMesswerte)   -anchor nw -expand 0 -fill both
pack $pfd(frKlaffNeupkt) -anchor nw -expand 0 -fill both
pack $pfd(panWin) -anchor nw -expand 1 -fill both
$pfd(panWin) add $pfd(frMesswerte) $pfd(frKlaffNeupkt)
set pfd(tali_mw) [tablelist::tablelist $pfd(frMesswerte).li.tali_mw \
                  -columns {0 "oid" l \
                            0 "status" l \
                            0 "art" l \
                            0 "sollTyp" l \
                            0 "Nr" l \
                            0 "Typ" l \
                            0 "Gst" l \
                            0 "Hz" r \
                            0 "V" r \
                            0 "S" r \
                            0 "Q" r \
                            0 "L" r \
                            0 "AK" l\
                            0 "LSEX" l \
                            0 "lfdNrGes" l}\
                  -exportselection 0 \
                  -labelbackground #EEEEEE \
                  -background white \
                  -labelfont $tableheadfont\
                  -font $tableinhfont\
                  -stretch 12\
                  -selectbackground $vmVConfig::setVar(activeBG) \
                  -selectforeground $vmVConfig::setVar(activeFG) \
                  -selectmode single\
                  -borderwidth 1 \
                  -labelborderwidth 1 \
                  -selectborderwidth 0 \
                  -tooltipaddcommand [::itcl::code $this tooltipAddCmd] \
                  -tooltipdelcommand [::itcl::code $this tooltipDelCmd] \
                  -xscrollcommand [list vmTkTools::configSB "h" $pfd(mw_scrx)]\
                  -yscrollcommand [list vmTkTools::configSB "v" $pfd(mw_scry)]]

set pfd(noteb) [iwidgets::notebook $pfd(frKlaffNeupkt).noteb]
pack $pfd(noteb) -anchor nw -expand 1 -fill both
set pfd(frKlaffungen) [$pfd(noteb) add -label Klaffungen]

set pfd(tali_klaff) [tablelist::tablelist $pfd(frKlaffungen).li.tali_klaff \
                      -columns {0 "oid" l 0 "Nr" l 0 "dX" r 0 "dY" r 0 "GwX" r 0 "GwY" r 0 "Rdz" r 0 "lfdNrGes" r}\
                      -exportselection 0 \
                      -labelbackground #EEEEEE \
                      -background white \
                      -labelfont $tableheadfont\
                      -font $tableinhfont\
                      -stretch 7\
                      -selectbackground $vmVConfig::setVar(activeBG) \
                      -selectforeground $vmVConfig::setVar(activeFG) \
                      -selectmode single\
                      -labelrelief groove \
                      -borderwidth 1 \
                      -labelborderwidth 1 \
                      -selectborderwidth 0 \
                      -xscrollcommand [list vmTkTools::configSB "h" $pfd(klaff_scrx)]\
                      -yscrollcommand [list vmTkTools::configSB "v" $pfd(klaff_scry)]]

Both tablelist have Bindings:

set body [$pfd(tali_mw) bodypath]
bind $body <Button-1> +[::itcl::code $this klickZeile %x %y %W]
bind $body <Double-1> +[::itcl::code $this doubleKlickMesswerte %x %y %W]

set body [$pfd(tali_klaff) bodypath]
bind $body <Button-1> [::itcl::code $this klickZeile %x %y %W]

The method klickZeile looks like this

itcl::body vmMaskHelmert::klickZeile {x y W} {
   puts "klickZeile"

   delCommonKreuz

   foreach {pfad xC yC} [tablelist::convEventFields $W $x $y] {}
   set row    [$pfad containing $yC]
   if {$row == -1} {
      set row end
   }

   if {[string first "tali_mw" $W] != -1} {
      # select the row
      $pfd(tali_mw) activate $row
      $pfd(tali_mw) selection clear 0 end
      $pfd(tali_mw) selection set $row $row
      anzeigePpMp
   } else {
      $pfd(tali_klaff) activate $row
      $pfd(tali_klaff) selection clear 0 end
      $pfd(tali_klaff) selection set $row $row
      anzeigePpMp4Klaff
   }
   return
}

It seems, that the method klickZeile blocks my double click binding, the method doubleKlickMesswerte is not being called.

In klickZeile two corresponding rows in both tablelists are selected.

I tried to comment out the two blocks with "activate $row, selection clear 0 end and selection set $row $row". In that case, doubleKlickMesswerte is being called but unfortunately the method klickZeile doesn't work correctly. It seems that in that case the method selects the corresponding row for the row selected before.

So I've got two questions:

How can I prevent the method klickZeile from blocking the double click binding?
Or, if there is no way for this, what can I do, to make the method "klickZeile" work correctly without extra selection and activation?

Thanks for your help!

Body:
Mouse click events (at least single/double/triple) without modifiers (like Control) will all trigger when a bind to triple is set up and the user triple-clicks on the target element. The GUI cannot predict that another click is coming. It has to dispatch the single-click event first, followed by the double, then the triple.

Your best alternative is to use a modifier, such as a , because this is unique and does not depend on sequence, as long as the Control button is pressed first ;)

proc doClick { widget } {
    puts "You clicked [$widget cget -text]"
}

proc doControlClick { widget } {
    puts "You control-clicked [$widget cget -text]"
}

set label_1 [label .l1 -text "This is label 1"]
pack $label_1 -side top -fill both

bind $label_1 <Control-Button-1> { doControlClick %W }
bind $label_1 <Button-1> { doClick %W }