问:
Accessing dynamically generated elements
When adding a dynamically added element, how can I get attributes for that element (when clicking on it, for example)?  I figured out that I need to delegate an event, but I still can't access any of the attributes of that event.

This JSFiddle shows the issue problem: https://jsfiddle.net/wgc499n9/

$(this).data('index') comes up as 'undefined' - I think $(this) is referencing 'document' instead of .remove_link; even the event data doesn't seem to have any useful information in it.  $(this).attr('id') also comes up as 'undefined'.

In the end, I just need to be able to click that remove link to remove the row it's on.  How can I accomplish that?  I even tried inline JS, but that caused even stranger behavior.

P.S. I also learned that my dynamically added data-index attribute is not stored in the DOM; jQuery stores it separately, so its containing element has to be accessed by using .find()...but I can't figure out how to use .find() to access the specific individual elements I need.

答:
Use element event(e) parameter instead this:

let i = 0;
$('#add').on('click', () => {
  $('#container').append(`<div>row #${(i+1)} remove</div>`);
  i++;
})

$(document).on('click', '.remove_link', (e) => {
  //alert(JSON.stringify(e));
  alert($(e.target).data('index'));
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.remove_link {
  color: red;
  font-size: 0.8em;
  cursor: pointer;
}</code>```

<button id="add">Add row</button>

```

For more detail read difference b/w $(this) ans event.target.

Body:
Use element event(e) parameter instead this:

let i = 0;
$('#add').on('click', () => {
  $('#container').append(`<div>row #${(i+1)} <a "href="#" data-index="${i}" class="remove_link">remove</a></div>`);
  i++;
})

$(document).on('click', '.remove_link', (e) => {
  //alert(JSON.stringify(e));
  alert($(e.target).data('index'));
})

.remove_link {
  color: red;
  font-size: 0.8em;
  cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="add">Add row</button>
<div id="container"></div>

For more detail read difference b/w $(this) ans event.target.


来源: stackexchange

问:
Positioning a div just before the footer of my page
Attaching a page layout to explain my requirements better.

Place the the text just before the footer section.

Some time the footer may not be visible (may need scroll), in that case bring the text to the bottom of visible area.

I have tried many ways to achieve this.
Any pointers to solve this issue would be helpful.

Thanks,
Santhosh

答:
You can use flexbox to achieve this

body {
  margin: 0;

  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.content {
  /* occupy all height */
  flex: 1 0 auto;
  /* nested flex container */
  display: flex;
  flex-direction: column;
}

.bottom-text {
  /* Move to the bottom */
  /* This works because this is flex item */
  margin-top: auto;
}

/* styles just for demo */
body {
  text-align: center;
}

header {
  background-color: tomato;
}

.content {
  background-color: lightsteelblue;
}

.bottom-text {
  background-color: moccasin;
}

footer {
  background-color: lime;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>Page header</header>
<section class="content">
  Page content
  <div class="bottom-text">Place a text just before footer</div>
</section>
<footer>Page footer</footer></code>```

For showing bottom-text when footer is not visible we'll use Javascript:

// Checks if element is visible on screen
function checkVisible(element) {
  var rect = element.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

var footer = document.querySelector("footer");
var bottomText = document.querySelector(".bottom-text");
var bottomTextFixedClassName = "bottom-text--fixed";

// Sets element position as fixed
// when footer is not visible on screen
function setFixedButtonText() {
  if (checkVisible(footer))
    bottomText.classList.remove(bottomTextFixedClassName);
  else
    bottomText.classList.add(bottomTextFixedClassName);
}

window.addEventListener("scroll", setFixedButtonText);

setFixedButtonText();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.content {
  /* occupy all height by flex-grow: 1 */
  /* Don't shrink using flex-shrink: 0 */
  /* Setting flex-basis to 1500px to emulate long content */
  /* Replace 1500px with auto in production code */
  flex: 1 0 1500px;
  /* nested flex container */
  display: flex;
  flex-direction: column;
}

.bottom-text {
  /* Move to the bottom */
  /* This works because this is flex item */
  margin-top: auto;
}

.bottom-text--fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
}

/* styles just for demo */
body {
  text-align: center;
}

header {
  background-color: tomato;
}

.content {
  background-color: lightsteelblue;
}

.bottom-text {
  background-color: moccasin;
}

footer {
  background-color: lime;
}</code>```

Page header

  Page content

Place a text just before footer

Page footer```

If you need IE suppost you can use change min-height: 100vh; to height: 100vh;. This is workaround for IE's min-height bug for flex with flex-direction: column;.

ContentLicense: CC BY-SA 3.0

Body:
You can use flexbox to achieve this

body {
  margin: 0;

  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.content {
  /* occupy all height */
  flex: 1 0 auto;
  /* nested flex container */
  display: flex;
  flex-direction: column;
}

.bottom-text {
  /* Move to the bottom */
  /* This works because this is flex item */
  margin-top: auto;
}

/* styles just for demo */
body {
  text-align: center;
}

header {
  background-color: tomato;
}

.content {
  background-color: lightsteelblue;
}

.bottom-text {
  background-color: moccasin;
}

footer {
  background-color: lime;
}

<header>Page header</header>
<section class="content">
  Page content
  <div class="bottom-text">Place a text just before footer</div>
</section>
<footer>Page footer</footer>

For showing bottom-text when footer is not visible we'll use Javascript:

// Checks if element is visible on screen
function checkVisible(element) {
  var rect = element.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

var footer = document.querySelector("footer");
var bottomText = document.querySelector(".bottom-text");
var bottomTextFixedClassName = "bottom-text--fixed";

// Sets element position as fixed
// when footer is not visible on screen
function setFixedButtonText() {
  if (checkVisible(footer))
    bottomText.classList.remove(bottomTextFixedClassName);
  else
    bottomText.classList.add(bottomTextFixedClassName);
}

window.addEventListener("scroll", setFixedButtonText);

setFixedButtonText();

body {
  margin: 0;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.content {
  /* occupy all height by flex-grow: 1 */
  /* Don't shrink using flex-shrink: 0 */
  /* Setting flex-basis to 1500px to emulate long content */
  /* Replace 1500px with auto in production code */
  flex: 1 0 1500px;
  /* nested flex container */
  display: flex;
  flex-direction: column;
}

.bottom-text {
  /* Move to the bottom */
  /* This works because this is flex item */
  margin-top: auto;
}

.bottom-text--fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
}

/* styles just for demo */
body {
  text-align: center;
}

header {
  background-color: tomato;
}

.content {
  background-color: lightsteelblue;
}

.bottom-text {
  background-color: moccasin;
}

footer {
  background-color: lime;
}

<header>Page header</header>
<section class="content">
  Page content
  <div class="bottom-text">Place a text just before footer</div>
</section>
<footer>Page footer</footer>

If you need IE suppost you can use change min-height: 100vh; to height: 100vh;. This is workaround for IE's min-height bug for flex with flex-direction: column;.


答:
In your event handler, this represent window. You have access to e.target to get the clicked element.

This should works:

```<code>$('#container').on('click', '.remove_link', (e) => {
    alert($(e.target).data('index'));
})
</code>```

Title: Accessing dynamically generated elements

Body:
When adding a dynamically added element, how can I get attributes for that element (when clicking on it, for example)?  I figured out that I need to delegate an event, but I still can't access any of the attributes of that event.

This JSFiddle shows the issue problem: https://jsfiddle.net/wgc499n9/

$(this).data('index') comes up as 'undefined' - I think $(this) is referencing 'document' instead of .remove_link; even the event data doesn't seem to have any useful information in it.  $(this).attr('id') also comes up as 'undefined'.

In the end, I just need to be able to click that remove link to remove the row it's on.  How can I accomplish that?  I even tried inline JS, but that caused even stranger behavior.

P.S. I also learned that my dynamically added data-index attribute is not stored in the DOM; jQuery stores it separately, so its containing element has to be accessed by using .find()...but I can't figure out how to use .find() to access the specific individual elements I need.

Body:
In your event handler, this represent window. You have access to e.target to get the clicked element.

This should works:

$('#container').on('click', '.remove_link', (e) => {
    alert($(e.target).data('index'));
})


问:
Dealing with polymorphic association: is there such a thing as "too many" LEFT JOIN?
I have ten tables (Product_A, Product_B, Product_C, etc.), each of them having a primary key pointing to a row in a the parent table Product.

Basically, I have applied the recommendations coming from the SQL antipattern book from Bill Karwin (this antipattern solution described here:
https://fr.slideshare.net/billkarwin/practical-object-oriented-models-in-sql/34-Polymorphic_Assocations_Exclusive_Arcs_Referential )

In order to load a child product, I use something like this:

```<code>SELECT * FROM Product
LEFT JOIN Product_A USING (product_id)
LEFT JOIN Product_B USING (product_id)
LEFT JOIN Product_C USING (product_id)
LEFT JOIN Product_D USING (product_id)
WHERE product_id = 1337
etc.
</code>```

I fear that the more types of child table products I get, the more JOIN clause I will have to add, causing the query to end up incredibly slow.

Is using LEFT JOIN in order to prevent polymorphic associations antipattern still a solution if we work on tens of sub child tables?

Should I start thinking of up using a query on parent table Product in order to grab a "product_type" and then execute another query on the appropriate child table depending on the value stored in the "product_type" column in the parent table?

Update: first replies on this topic state that this is bad design and that I should create a single table combining the colums from the child tables. But each product type has its own attributes. To say it otherwise: "A TV might have a pixel count, but that wouldn't make much sense for a blender." @TomH

Thank you

答:
Maybe change your design? One product can have many attributes (and many of the same attributes), and those attributes have values.

I suggest three tables:

```<code>Products        ProductsAttributes      Attributes
-Product_Id     -Product_Id             -Attribute_Id
-...            -Attribute_Id           -Attribute_Name
                -Value                  -...
                -...
</code>```

Using as such:

```<code>SELECT p.Product_Id, a.Attribute_Name, pa.Value FROM Products p
JOIN ProductsAttributes pa ON pa.Product_Id = p.ProductId
JOIN Attributes a ON a.Attribute_Id = pa.Attribute_Id
</code>```

Then you can reuse attributes, tie them to products, and store their values. Each product only has the attributes that it needs.

Body:
I have ten tables (Product_A, Product_B, Product_C, etc.), each of them having a primary key pointing to a row in a the parent table Product.

Basically, I have applied the recommendations coming from the SQL antipattern book from Bill Karwin (this antipattern solution described here:
https://fr.slideshare.net/billkarwin/practical-object-oriented-models-in-sql/34-Polymorphic_Assocations_Exclusive_Arcs_Referential )

In order to load a child product, I use something like this:

SELECT * FROM Product
LEFT JOIN Product_A USING (product_id)
LEFT JOIN Product_B USING (product_id)
LEFT JOIN Product_C USING (product_id)
LEFT JOIN Product_D USING (product_id)
WHERE product_id = 1337
etc.

I fear that the more types of child table products I get, the more JOIN clause I will have to add, causing the query to end up incredibly slow.

Is using LEFT JOIN in order to prevent polymorphic associations antipattern still a solution if we work on tens of sub child tables?

Should I start thinking of up using a query on parent table Product in order to grab a "product_type" and then execute another query on the appropriate child table depending on the value stored in the "product_type" column in the parent table?

Update: first replies on this topic state that this is bad design and that I should create a single table combining the colums from the child tables. But each product type has its own attributes. To say it otherwise: "A TV might have a pixel count, but that wouldn't make much sense for a blender." @TomH

Thank you

Body:
Maybe change your design? One product can have many attributes (and many of the same attributes), and those attributes have values.

I suggest three tables:

Products        ProductsAttributes      Attributes
-Product_Id     -Product_Id             -Attribute_Id
-...            -Attribute_Id           -Attribute_Name
                -Value                  -...
                -...

Using as such:

SELECT p.Product_Id, a.Attribute_Name, pa.Value FROM Products p
JOIN ProductsAttributes pa ON pa.Product_Id = p.ProductId
JOIN Attributes a ON a.Attribute_Id = pa.Attribute_Id

Then you can reuse attributes, tie them to products, and store their values. Each product only has the attributes that it needs.


问:
How can I pass my user entered information to my database using php?
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.

```<code><!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

//<!-- post added information to database -->
if ($_POST['name']) {
 if ($_POST['number']) {

 $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  }
 }
} ?>
</code>```

From looking at my code I believe the issue is with this line.

```<code>   $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
</code>```

There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:

```<code>$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
</code>```

These hard coded entries are put into the database but i can't get the user entered data to go in.

答:
You're about to go down a slippery slope using mysqli. I'd recommend trying to learn to use PDO for making queries. Right now, someone could easily put SQL into the name POST data and actually do damage to your database.

Anyways, your problem at hand, you have a missing bracket and one issue:

VALUES ('', '$_POST['name']', '$_POST['number'')";

It won't work as intended with nested single quotes.

VALUES ('', '$_POST[name]', '$_POST[number]')";

Body:
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

//
if ($_POST['name']) {
 if ($_POST['number']) {

 $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  }
 }
} ?>

From looking at my code I believe the issue is with this line.

   $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";

There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:

$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";

These hard coded entries are put into the database but i can't get the user entered data to go in.


问:
When the user do not want to purchase in-app product and cancels Google store pop-up dialog, app crashes. Why?
My in-app purchase works very well, however, when my users do not want to buy it, and cancels or exit "Google Store pop-up dialog", my app crashes (exits). I have this following code:</p>

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent data) {
    if (!mHelper.handleActivityResult(requestCode,
            resultCode, data)) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

        if (purchase.getSku().equals(ITEM_SKU)) {
            Log.d(TAG, "Purchase is fast mode");
            try {
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            } catch (Exception e) {
                Log.d(TAG, "error");
            }
        }

    }
};

IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
    public void onConsumeFinished(Purchase purchase, IabResult result) {

        Log.d(TAG, "Consumption finished. JSON: " + purchase.getOriginalJson() + ", signature: " + purchase.getSignature());

        if (mHelper == null) return;

        if (result.isSuccess()) {
            Log.i(TAG, "BOUGHT THE ITEM :-)");
            clickButton.setEnabled(true);
            buyButton.setEnabled(false);
        } else {
            Log.e(TAG, "Error while consuming: " + result);
        }
        Log.d(TAG, "End consumption flow.");
    }
};
</code>```

答:
The problem lies in your OnIabPurchaseFinishedListener interface since this is what's invoked when the purchase dialog opens, and you have to make sure to exit out of the method immediately when the process is cancelled since there's no SKU to check for purchases which most likely leads to a NullPointerException. That said, I'd add validation methods (just like you did in your consume finished listener) in the interface as follows:

```<code>IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

        // If we were disposed of in the meantime, exits out of the method.
        if (mHelper == null) return;

        // If purchase was cancelled, exits out of the method.
        if (result.isFailure()) {
            Log.d(TAG, "Error purchasing: " + result);
            return;
        }

        // If user authentication is invalid, exits out of the method.
        if (!verifyDeveloperPayload(purchase)) {
            Log.d(TAG, "Error purchasing. Authenticity verification failed.");
            return;
        }

        // Only then if all of the validation conditions are met will the following be executed.
        if (purchase.getSku().equals(ITEM_SKU)) {
            Log.d(TAG, "Purchase is fast mode");
            try {
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            } catch (Exception e) {
                Log.d(TAG, "error");
            }
        }

    }
};
</code>```

Body:
My in-app purchase works very well, however, when my users do not want to buy it, and cancels or exit "Google Store pop-up dialog", my app crashes (exits). I have this following code:

@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent data) {
    if (!mHelper.handleActivityResult(requestCode,
            resultCode, data)) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

        if (purchase.getSku().equals(ITEM_SKU)) {
            Log.d(TAG, "Purchase is fast mode");
            try {
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            } catch (Exception e) {
                Log.d(TAG, "error");
            }
        }

    }
};

IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
    public void onConsumeFinished(Purchase purchase, IabResult result) {

        Log.d(TAG, "Consumption finished. JSON: " + purchase.getOriginalJson() + ", signature: " + purchase.getSignature());

        if (mHelper == null) return;

        if (result.isSuccess()) {
            Log.i(TAG, "BOUGHT THE ITEM :-)");
            clickButton.setEnabled(true);
            buyButton.setEnabled(false);
        } else {
            Log.e(TAG, "Error while consuming: " + result);
        }
        Log.d(TAG, "End consumption flow.");
    }
};

Body:
The problem lies in your OnIabPurchaseFinishedListener interface since this is what's invoked when the purchase dialog opens, and you have to make sure to exit out of the method immediately when the process is cancelled since there's no SKU to check for purchases which most likely leads to a NullPointerException. That said, I'd add validation methods (just like you did in your consume finished listener) in the interface as follows:

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

        // If we were disposed of in the meantime, exits out of the method.
        if (mHelper == null) return;

        // If purchase was cancelled, exits out of the method.
        if (result.isFailure()) {
            Log.d(TAG, "Error purchasing: " + result);
            return;
        }

        // If user authentication is invalid, exits out of the method.
        if (!verifyDeveloperPayload(purchase)) {
            Log.d(TAG, "Error purchasing. Authenticity verification failed.");
            return;
        }

        // Only then if all of the validation conditions are met will the following be executed.
        if (purchase.getSku().equals(ITEM_SKU)) {
            Log.d(TAG, "Purchase is fast mode");
            try {
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            } catch (Exception e) {
                Log.d(TAG, "error");
            }
        }

    }
};


问:
Django queries with complex filter
I have the following model:

```<code>...
from django.contrib.auth.models import User

class TaxonomyNode(models.Model):
    node_id = models.CharField(max_length=20)
    name = models.CharField(max_length=100)
    ...

class Annotation(models.Model):
    ...
    taxonomy_node = models.ForeignKey(TaxonomyNode, blank=True, null=True)

class Vote(models.Model):
    created_by = models.ForeignKey(User, related_name='votes', null=True, on_delete=models.SET_NULL)
    vote = models.FloatField()
    annotation = models.ForeignKey(Annotation, related_name='votes')
    ...
</code>```

In the app, a User can produce Vote for an Annotation instance.
A User can vote only once for an Annotation instance.
I want to get a query set with the TaxonomyNode which a User can still annotate a least one of its Annotation. For now, I do it that way:

```<code>def user_can_annotate(node_id, user):
    if Annotation.objects.filter(node_id=node_id).exclude(votes__created_by=user).count() == 0:
        return False
    else:
        return True

def get_categories_to_validate(user):
    """
    Returns a query set with the TaxonomyNode which have Annotation that can be validated by a user
    """
    nodes = TaxonomyNode.objects.all()
    nodes_to_keep = [node.node_id for node in nodes if self.user_can_annotate(node.node_id, user)]
    return nodes.filter(node_id__in=nodes_to_keep)

categories_to_validate = get_category_to_validate(<user instance>)
</code>```

I guess there is a way to do it in one query, that would speed up the process quite a lot. In brief, I want to exclude from the TaxonomyNode set, all the nodes that have all their annotations already voted once by the user.

Any idea of how I could do it? With django ORM or in SQL?
I have Django version 1.10.6

答:
What I have done so far:

```<code>taxonomy_node_pk = [a[0] for a in Annotation.objects.exclude(votes__created_by=user)
    .select_related('taxonomy_node').values_list('taxonomy_node').distinct()]

nodes = TaxonomyNode.objects.filter(pk__in=taxonomy_node_pk)
</code>```

I am doing two queries but the second one is not very costly.
It is quite faster than my original version.
Still what I do is not really beatifull. There is no way to get a query set of TaxonomyNode from the Annotation set directly? And then applying disctinct() in it?

Title: Django queries with complex filter

Body:
I have the following model:

...
from django.contrib.auth.models import User

class TaxonomyNode(models.Model):
    node_id = models.CharField(max_length=20)
    name = models.CharField(max_length=100)
    ...

class Annotation(models.Model):
    ...
    taxonomy_node = models.ForeignKey(TaxonomyNode, blank=True, null=True)

class Vote(models.Model):
    created_by = models.ForeignKey(User, related_name='votes', null=True, on_delete=models.SET_NULL)
    vote = models.FloatField()
    annotation = models.ForeignKey(Annotation, related_name='votes')
    ...

In the app, a User can produce Vote for an Annotation instance.
A User can vote only once for an Annotation instance.
I want to get a query set with the TaxonomyNode which a User can still annotate a least one of its Annotation. For now, I do it that way:

def user_can_annotate(node_id, user):
    if Annotation.objects.filter(node_id=node_id).exclude(votes__created_by=user).count() == 0:
        return False
    else:
        return True

def get_categories_to_validate(user):
    """
    Returns a query set with the TaxonomyNode which have Annotation that can be validated by a user
    """
    nodes = TaxonomyNode.objects.all()
    nodes_to_keep = [node.node_id for node in nodes if self.user_can_annotate(node.node_id, user)]
    return nodes.filter(node_id__in=nodes_to_keep)

categories_to_validate = get_category_to_validate(<user instance>)

I guess there is a way to do it in one query, that would speed up the process quite a lot. In brief, I want to exclude from the TaxonomyNode set, all the nodes that have all their annotations already voted once by the user.

Any idea of how I could do it? With django ORM or in SQL?
I have Django version 1.10.6

Body:
What I have done so far:

taxonomy_node_pk = [a[0] for a in Annotation.objects.exclude(votes__created_by=user)
    .select_related('taxonomy_node').values_list('taxonomy_node').distinct()]

nodes = TaxonomyNode.objects.filter(pk__in=taxonomy_node_pk)

I am doing two queries but the second one is not very costly.
It is quite faster than my original version.
Still what I do is not really beatifull. There is no way to get a query set of TaxonomyNode from the Annotation set directly? And then applying disctinct() in it?


问:
How to stop Amazon EBS charge
I created some EBS volumes on some Linux instances. Then I terminated the instances but the volumes were still there (I forgot to check the Delete on Termination setting).

When I went to billing I saw that I was charged for the IOPS of those EBS volumes -- approximately US$8. So then I removed them, even though they were no longer attached to the instances (they were just there but with an available state).

Today after almost a day without EBS volumes in my AWS account I see that the billing is US$13!!! I checked the billing details and it all charged to IOPS of the EBS volumes even though I already removed them yesterday! I need to stop this right away.

I opened a case yesterday in AWS and the case is still unassigned. Anybody knows how EBS volumes are being charged? HELP! Thank you!

答:
Sometimes AWS support takes some time to get back to you, this depends on your support level. If you have the free tier it may take 48 hours.

EBS is charged monthly and the charges do not instantly show up. So more than likely the $8-$13 charge was already there when you terminated the volumes.

You can view the EBS pricing here: https://aws.amazon.com/ebs/pricing/

Title: How to stop Amazon EBS charge


问:
SAPUI5 Fragment Value setValue not working
We have set the value of input on click of button on a Fragment Dialog.

sap.ui.getCore().byId("idFragment--txtLatitude").setValue(position.coords.latitude);
```

But the Value is not displaying on UI. If we close and open the dialog again, the value is appearing. Even the console getValue showing the value.

答:
In the UI control and hierarchy. Generally when have a control as a dependent of another control.

Once we made control as part of the content of the parent control and it worked.

ContentLicense: CC BY-SA 4.0

Body:
We have set the value of input on click of button on a Fragment Dialog.

sap.ui.getCore().byId("idFragment--txtLatitude").setValue(position.coords.latitude);

But the Value is not displaying on UI. If we close and open the dialog again, the value is appearing. Even the console getValue showing the value.


问:
PHP: "Broadcast message" between two functions
I am currently trying to create "extensions" for a project I made.
I want to create "broadcasts" so that extensions can get triggered when something happens. Here is an example of what I want to do:

```<code>class mainproject {
 public static function dosomething() {
  runsomething();
  self::save();
 }
 public static function save() {
  savesomething();
  broadcast("saved it");
 }
}

class extension extends mainproject {
 onBroadcast("saved it", function() {
  dosomething();
 });
}
</code>```

Is is possible? Or are there other ways of achieving this?

Wordpress has something similar withadd_action( 'admin_menu', 'function_name' );

答: I have found a solution that works for me: https://gist.github.com/im4aLL/548c11c56dbc7267a2fe96bda6ed348b</p>

Body:
I am currently trying to create "extensions" for a project I made.
I want to create "broadcasts" so that extensions can get triggered when something happens. Here is an example of what I want to do:

class mainproject {
 public static function dosomething() {
  runsomething();
  self::save();
 }
 public static function save() {
  savesomething();
  broadcast("saved it");
 }
}

class extension extends mainproject {
 onBroadcast("saved it", function() {
  dosomething();
 });
}

Is is possible? Or are there other ways of achieving this?

Wordpress has something similar withadd_action( 'admin_menu', 'function_name' );


问:
AngularJS - Validate a part of a form
I'm using Angular 1.5.9

I have a big form, which I scattered through different Bootstrap Accordion.

When there is an error in the form, I want to be able to change the class of my accordions to show in which accordions the error is located.

To check for errors in a whole form, I can check

```<code>myFormName.$error
</code>```

And to check errors for an element, I can simply do

```<code>myFormName.myInputName.$error
</code>```

But I don't know if there is a way to do this for multiple element at once, without having to check each element individually.

My first thought was to change the name of my inputs like so:

```<code><input name="accordion1.fieldName">
</code>```

But this didn't give me the expected result: I don't have myFormName.accordion1.$error, actually, I don't even have myFormName.accordion1.fieldName, since my data is actually stored in myFormName['accordion1.fieldName'] which is pretty much useless.

Has anyone found an answer to this problem? I think I'll have to check each field, which is kinda ugly, and a mess to maintain whenever we add / remove fields...

Maybe there is a directive out there that could do that for me, but as a non-native English speaker, I can't find which key words to use for my search in this situation.

答:
One approach is to nest with the ng-form directive:</p>

```<code><form name=form1>
    <div ng-form=set1>
       <input name=input1 />
       <input name=input2 />
    </div>
</form>

{{form1.set1.$error}}
</code>```

Title: AngularJS - Validate a part of a form

Body:
I'm using Angular 1.5.9

I have a big form, which I scattered through different Bootstrap Accordion.

When there is an error in the form, I want to be able to change the class of my accordions to show in which accordions the error is located.

To check for errors in a whole form, I can check

myFormName.$error

And to check errors for an element, I can simply do

myFormName.myInputName.$error

But I don't know if there is a way to do this for multiple element at once, without having to check each element individually.

My first thought was to change the name of my inputs like so:

<input name="accordion1.fieldName">

But this didn't give me the expected result: I don't have myFormName.accordion1.$error, actually, I don't even have myFormName.accordion1.fieldName, since my data is actually stored in myFormName['accordion1.fieldName'] which is pretty much useless.

Has anyone found an answer to this problem? I think I'll have to check each field, which is kinda ugly, and a mess to maintain whenever we add / remove fields...

Maybe there is a directive out there that could do that for me, but as a non-native English speaker, I can't find which key words to use for my search in this situation.

Body:
One approach is to nest with the ng-form directive:

<form name=form1>
    <div ng-form=set1>
       <input name=input1 />
       <input name=input2 />
    </div>
</form>

{{form1.set1.$error}}


问:
Transfer files between users of the same app with "cloud" storage
I am building an WPF app that need to exchange some very small xml files with other users. I'm currently looking into peer2peer networking, but I need the sender of the files to be able to send without the receiver being online also. I do not want to host a service myself, and I want the users to store the other users they interact with locally on their machine, for example just a name together with a GUID or email adress to identify them.

Do you guys have any suggestions on how to solve this? My wishful thinking would be if there was a free or cheap service where users could connect via my program to a public API and upload their files. And when the receiver user logs on, it would check the service and authenticate somehow, and download the XML files so it could be imported by the program.

I have made a solution with a IMAP library where the XML files are attached in the email and sent to the receivers email account. The program on the receiver checks the email and read the attachment. This works ok, but is not very slick and also filling up the users inbox and sent items with garbage..

Any suggestions is greatly appreciated.

Best regards
Ola

答:
This is one idea:

Normally, Block Storage volumes are seen as extra 'Drives' that you attach to a Virtual Machine.  You could then use this but as if it was a metaphorical 'USB flashkey' that you would share with the other person.

Create the storage volume

Attach it to your VM and copy your
data-to-be-shared on it

Detach the volume from your VM

Your Buddy, attaches it to his VM

He then copies the files and voila!

All this could be done through a web interface and you wouldn't have to do any networking steps.

All you need now is a capable Cloud Geek, a pot of coffee and some convincing.

ContentLicense: CC BY-SA 2.5


问:
grade sync failed when i want to import a project
i want to import a project in to android studio but i have an error gradle sync failed .

this is my build.gradle file:

```<code>buildscript {
    repositories {
        jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Gradle sync failed: Cause: com.android.build.gradle.tasks.factory.AndroidJavaCompile.setDependencyCacheDir(Ljava/io/File;)V
            Consult IDE log for more details (Help | Show Log)

i changed the distributionUrl but doesn't solve the problem .

my gradle-wrapper propertice:

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
</code>```

i searched the net for 3-4 hours but there was no solution for my problem that can solve my problem .

答:
Hope it works
File → Settings → Build, Execution, Deployment → Instant Run and uncheck Enable Instant Run.</p>

Body:
i want to import a project in to android studio but i have an error gradle sync failed .

this is my build.gradle file:

buildscript {
    repositories {
        jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Gradle sync failed: Cause: com.android.build.gradle.tasks.factory.AndroidJavaCompile.setDependencyCacheDir(Ljava/io/File;)V
            Consult IDE log for more details (Help | Show Log)

i changed the distributionUrl but doesn't solve the problem .

my gradle-wrapper propertice:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

i searched the net for 3-4 hours but there was no solution for my problem that can solve my problem .


问:
Void function is throwing a "no return statement" warning
So I have the following function, evidently a void:

```<code>static void *CpuStatsTestLoop (void *arg){
    UNUSED (arg);

    rtems_object_set_name(rtems_task_self(), "CPU Usage Thread");

    while (1)
    {
        sleep (CPU_USAGE_REPORT_INTERVAL_SECS);
        rtems_cpu_usage_report();
        rtems_cpu_usage_reset();
    }
}
</code>```

and it throws

"cpu_stats.c:98:1: warning: no return statement in function returning non-void [-Wreturn-type]".

I've tried adding a blank return and return 0 with no luck.

Any idea about why it's throwing this error, and how to fix?

答:
This is not a void function, this is a void* (void pointer) function. It must return a value, which must be a pointer to data of any type, or NULL.

In your case, a return is not necessary, because the function never returns: it has a while(1) loop, which runs forever. A better approach is to make it a void function, rather than a void* function, unless it must conform to some predefined function pointer type.

If changing return type is not an option, for example, because you must pass this function as a start_routine parameter of pthread_create you can silence the warning by adding return NULL at the end of the function's body.

Body:
So I have the following function, evidently a void:

static void *CpuStatsTestLoop (void *arg){
    UNUSED (arg);

    rtems_object_set_name(rtems_task_self(), "CPU Usage Thread");

    while (1)
    {
        sleep (CPU_USAGE_REPORT_INTERVAL_SECS);
        rtems_cpu_usage_report();
        rtems_cpu_usage_reset();
    }
}

and it throws

"cpu_stats.c:98:1: warning: no return statement in function returning non-void [-Wreturn-type]".

I've tried adding a blank return and return 0 with no luck.

Any idea about why it's throwing this error, and how to fix?


问:
A default DbContext context must exist, or a context factory must be provided
I'm getting the following error while performing "Bulk Insert" using EntityFramework extensions.

```<code>_indnCon.BulkInsert(_DataToTrans, operation => operation.IncludeGraph = true);
</code>```

Exception occurs in the above line and here is the exception.

A default DbContext context must exist,
      or a context factory must be provided (EntityFrameworkManager.ContextFactory).
      This setting is required for some features like IncludeGraph.

Here I'm passing the Connection String to the DBContext manually.

```<code>using (InsightDataContext _indnCon = new InsightDataContext(_connectionString))
</code>```

Can anyone help?

答:
It seems that IncludeGraph feature needs to be able to create a new instance of your context, even if you already instantiated the context yourself in this scope. So, as the message says, you can try setting a default constructor for your context:

```<code>EntityFrameworkManager.ContextFactory = context => new CurrentContext(yourConnectionString);
</code>```

The info comes from this post.

Body:
I'm getting the following error while performing "Bulk Insert" using EntityFramework extensions.

_indnCon.BulkInsert(_DataToTrans, operation => operation.IncludeGraph = true);

Exception occurs in the above line and here is the exception.

A default DbContext context must exist,
      or a context factory must be provided (EntityFrameworkManager.ContextFactory).
      This setting is required for some features like IncludeGraph.

Here I'm passing the Connection String to the DBContext manually.

using (InsightDataContext _indnCon = new InsightDataContext(_connectionString))

Can anyone help?

Body:
It seems that IncludeGraph feature needs to be able to create a new instance of your context, even if you already instantiated the context yourself in this scope. So, as the message says, you can try setting a default constructor for your context:

EntityFrameworkManager.ContextFactory = context => new CurrentContext(yourConnectionString);

The info comes from this post.


问:
sum by group including intermediate groups
I have:

```<code>df <- data.frame(group=c(1,1,2,4,4,5), value=c(3,1,5,2,3,6))
aggregate(value ~ group, data = df, FUN = 'sum')

  group value
1  1     4
2  2     5
3  4     5
4  5     6
</code>```

is there a way to include intermediate groups to return the below? I realise this could be done by creating a dataframe with all the desired groups and matching in the results from aggregate() but I am hoping there is a cleaner way to do this. it would need to be as fast as using aggregate and only use base r packages - this is due to restrictions in my workplace.

```<code>  group value
1  1     4
2  2     5
3  3     0
4  4     5
5  5     6
</code>```

答:
You can try this . </p>

```<code>library(tidyr)
library(dplyr)
df %>%
    mutate(group=factor(group, 1:5)) %>%
    complete(group) %>%group_by(group)%>%
    dplyr::summarise(value=sum(value,na.rm = T))

   group value
  <fctr> <dbl>
1      1     4
2      2     5
3      3     0
4      4     5
5      5     6
</code>```

Body:
I have:

df <- data.frame(group=c(1,1,2,4,4,5), value=c(3,1,5,2,3,6))
aggregate(value ~ group, data = df, FUN = 'sum')

  group value
1  1     4
2  2     5
3  4     5
4  5     6

is there a way to include intermediate groups to return the below? I realise this could be done by creating a dataframe with all the desired groups and matching in the results from aggregate() but I am hoping there is a cleaner way to do this. it would need to be as fast as using aggregate and only use base r packages - this is due to restrictions in my workplace.

  group value
1  1     4
2  2     5
3  3     0
4  4     5
5  5     6

Body:
You can try this .

library(tidyr)
library(dplyr)
df %>%
    mutate(group=factor(group, 1:5)) %>%
    complete(group) %>%group_by(group)%>%
    dplyr::summarise(value=sum(value,na.rm = T))

   group value
  <fctr> <dbl>
1      1     4
2      2     5
3      3     0
4      4     5
5      5     6


问:
aws cognito angular example: URIError: URI malformed
I was trying out the aws cognito example app based on angular 2, and noticed the following error.

The app is https://github.com/awslabs/aws-cognito-angular2-quickstart

When I try to browse to this app deployed at http://cognito.budilov.com/ from Chrome browser on my Android, I get the following error. Any ideas on what could be going on?

```<code>vendor.f06d8c6….bundle.js:148 ERROR Error: Uncaught (in promise): URIError:
URI malformed
URIError: URI malformed
at decodeURIComponent (<anonymous>)
at Object.fromBits (sjcl.js:11)
at e.value (amazon-cognito-identity.min.js:19)
at e.value (amazon-cognito-identity.min.js:19)
at e.value (amazon-cognito-identity.min.js:19)
at l.O7AO.l.isAuthenticated (main.fd38a9f….bundle.js:1)
at new l (main.fd38a9f….bundle.js:1)
at Ze (vendor.f06d8c6….bundle.js:225)
at ze (vendor.f06d8c6….bundle.js:225)
at On (vendor.f06d8c6….bundle.js:239)
at _n (vendor.f06d8c6….bundle.js:239)
at Object.Hn [as createRootView] (vendor.f06d8c6….bundle.js:239)
at e.create (vendor.f06d8c6….bundle.js:302)
at e.create (vendor.f06d8c6….bundle.js:281)
at t.createComponent (vendor.f06d8c6….bundle.js:302)
at decodeURIComponent (<anonymous>)
at Object.fromBits (sjcl.js:11)
at e.value (amazon-cognito-identity.min.js:19)
at e.value (amazon-cognito-identity.min.js:19)
at e.value (amazon-cognito-identity.min.js:19)
at l.O7AO.l.isAuthenticated (main.fd38a9f….bundle.js:1)
at new l (main.fd38a9f….bundle.js:1)
at Ze (vendor.f06d8c6….bundle.js:225)
at ze (vendor.f06d8c6….bundle.js:225)
at On (vendor.f06d8c6….bundle.js:239)
at _n (vendor.f06d8c6….bundle.js:239)
at Object.Hn [as createRootView] (vendor.f06d8c6….bundle.js:239)
at e.create (vendor.f06d8c6….bundle.js:302)
at e.create (vendor.f06d8c6….bundle.js:281)
at t.createComponent (vendor.f06d8c6….bundle.js:302)
at v (vendor.f06d8c6….bundle.js:697)
at p (vendor.f06d8c6….bundle.js:697)
at p (vendor.f06d8c6….bundle.js:697)
at vendor.f06d8c6….bundle.js:697
at t.invokeTask (vendor.f06d8c6….bundle.js:697)
at Object.onInvokeTask (vendor.f06d8c6….bundle.js:281)
at t.invokeTask (vendor.f06d8c6….bundle.js:697)
at e.runTask (vendor.f06d8c6….bundle.js:697)
at a (vendor.f06d8c6….bundle.js:697)
at HTMLAnchorElement.invoke (vendor.f06d8c6….bundle.js:697)
</code>```

UPDATE:

This works fine with the non minified version of aws cognito identity js file, but is still a problem with the minified version.

答:
Updating to the latest version of aws-cognito-sdk.js and amazon-cognito-identity.js solves the problem.

You can fetch them from this repository https://github.com/aws/amazon-cognito-identity-js

Body:
I was trying out the aws cognito example app based on angular 2, and noticed the following error.

The app is https://github.com/awslabs/aws-cognito-angular2-quickstart

When I try to browse to this app deployed at http://cognito.budilov.com/ from Chrome browser on my Android, I get the following error. Any ideas on what could be going on?

vendor.f06d8c6….bundle.js:148 ERROR Error: Uncaught (in promise): URIError:
URI malformed
URIError: URI malformed
at decodeURIComponent (<anonymous>)
at Object.fromBits (sjcl.js:11)
at e.value (amazon-cognito-identity.min.js:19)
at e.value (amazon-cognito-identity.min.js:19)
at e.value (amazon-cognito-identity.min.js:19)
at l.O7AO.l.isAuthenticated (main.fd38a9f….bundle.js:1)
at new l (main.fd38a9f….bundle.js:1)
at Ze (vendor.f06d8c6….bundle.js:225)
at ze (vendor.f06d8c6….bundle.js:225)
at On (vendor.f06d8c6….bundle.js:239)
at _n (vendor.f06d8c6….bundle.js:239)
at Object.Hn [as createRootView] (vendor.f06d8c6….bundle.js:239)
at e.create (vendor.f06d8c6….bundle.js:302)
at e.create (vendor.f06d8c6….bundle.js:281)
at t.createComponent (vendor.f06d8c6….bundle.js:302)
at decodeURIComponent (<anonymous>)
at Object.fromBits (sjcl.js:11)
at e.value (amazon-cognito-identity.min.js:19)
at e.value (amazon-cognito-identity.min.js:19)
at e.value (amazon-cognito-identity.min.js:19)
at l.O7AO.l.isAuthenticated (main.fd38a9f….bundle.js:1)
at new l (main.fd38a9f….bundle.js:1)
at Ze (vendor.f06d8c6….bundle.js:225)
at ze (vendor.f06d8c6….bundle.js:225)
at On (vendor.f06d8c6….bundle.js:239)
at _n (vendor.f06d8c6….bundle.js:239)
at Object.Hn [as createRootView] (vendor.f06d8c6….bundle.js:239)
at e.create (vendor.f06d8c6….bundle.js:302)
at e.create (vendor.f06d8c6….bundle.js:281)
at t.createComponent (vendor.f06d8c6….bundle.js:302)
at v (vendor.f06d8c6….bundle.js:697)
at p (vendor.f06d8c6….bundle.js:697)
at p (vendor.f06d8c6….bundle.js:697)
at vendor.f06d8c6….bundle.js:697
at t.invokeTask (vendor.f06d8c6….bundle.js:697)
at Object.onInvokeTask (vendor.f06d8c6….bundle.js:281)
at t.invokeTask (vendor.f06d8c6….bundle.js:697)
at e.runTask (vendor.f06d8c6….bundle.js:697)
at a (vendor.f06d8c6….bundle.js:697)
at HTMLAnchorElement.invoke (vendor.f06d8c6….bundle.js:697)

UPDATE:

This works fine with the non minified version of aws cognito identity js file, but is still a problem with the minified version.


问:
C# How to prevent ListBox to select first item when you unselect the last one
C# How to prevent ListBox in MultiSimple selection mode to select first item automatically, when you unselect the last one selected item in the box - it happens only if listbox represented by my own class objects, and everything is ok when it represented by string objects. Thnx!</p>

答:
It seems like keeping track of the order of the list is the most important part.  I would suggest maybe making an array of a struct.  You can make this struct contain whatever you want for example:

```<code>struct itemList
{
    public string itemName;
    public int itemIndex;
    //include whatever other variables that you need included in here.

}
</code>```

Also, make sure you place your struct before the namespace.  Then, making the array of the struct would look like this:

```<code>itemList[] items1 = new itemList[listBoxName.SelectedItems.Count];
</code>```

All you would have to do then is to add the items to the array before you reorder the listBox

```<code>for (int i = 0; i < listBoxName.SelectedItems.Count; i++)
   {
        items1[i].itemName = listBoxName.SelectedItems[i].ToString();
        items1[i].itemIndex = listBoxName.SelectedIndices[i];
   }
</code>```

Body:
It seems like keeping track of the order of the list is the most important part.  I would suggest maybe making an array of a struct.  You can make this struct contain whatever you want for example:

struct itemList
{
    public string itemName;
    public int itemIndex;
    //include whatever other variables that you need included in here.

}

Also, make sure you place your struct before the namespace.  Then, making the array of the struct would look like this:

itemList[] items1 = new itemList[listBoxName.SelectedItems.Count];

All you would have to do then is to add the items to the array before you reorder the listBox

for (int i = 0; i < listBoxName.SelectedItems.Count; i++)
   {
        items1[i].itemName = listBoxName.SelectedItems[i].ToString();
        items1[i].itemIndex = listBoxName.SelectedIndices[i];
   }


问:
How to normalize input in Mongo - Ruby
I am dealing with some very large third party CSV files which I import in Mongo. The issue is that the headers on these files are very inconsistent. Some files contain all lowercase, some mixed case and some all uppercase headers. After the file is imported, is there a way to query a collection case insensitively?

In short can I do:

```<code> @collection.find('AB' => value) so that it's true for fields 'ab' or aB' as well?
</code>```

Is there a way to normalize these headers at the time of import? or may be there's another way?

The question suggested as a duplicate is for regex searches on values and not the field itself

答: You should use the built-in Ruby methods for the String class documentation. For example, .strip!, would be a good one to use to remove excess whitespace. .downcase! could be used to normalize the case. There are others you may find useful to use in the documentation. This is one of the best resources for beginner to intermediate level Ruby programming. Once you master the methods of each class, you can leverage the full power of Ruby.

Title: How to normalize input in Mongo - Ruby

Body:
I am dealing with some very large third party CSV files which I import in Mongo. The issue is that the headers on these files are very inconsistent. Some files contain all lowercase, some mixed case and some all uppercase headers. After the file is imported, is there a way to query a collection case insensitively?

In short can I do:

 @collection.find('AB' => value) so that it's true for fields 'ab' or aB' as well?

Is there a way to normalize these headers at the time of import? or may be there's another way?

The question suggested as a duplicate is for regex searches on values and not the field itself


问:
jQuery Fadein Not Working on Wordpress Localhost
I'll start by saying this site is not on a live server at all, it is being built locally by me to be deployed later. I'm not a jQuery person and am learning as I go, and was using an online solution for this.

The goal is to have an element fade in when a button is clicked. I followed a tutorial and it didn't work.

Some things to consider:
1. The parent theme is Divi
2. This is using a child theme (not sure how much that matters)
3. The button and the element to fade in are not in the same section

Here is the jQuery code:

```<code><script>
var j = jQuery.noConflict();
j(document).ready(function($){
$("#goals-button").click(function(){
$("#goals-content").fadein(1000,"linear");
});
});
</script>
</code>```

I have checked and double checked that the button and the section have the correct id tags, so I know that's not the problem.

I have put this code in the correct section as well. I just don't understand why it's not working. I even tried using the original tutorial code and that didn't work at all. Could this be an issue with jQuery running on local environments?

Thanks for your help.

答: I had fadein and not fadeIn, silly mistake.

Body:
I'll start by saying this site is not on a live server at all, it is being built locally by me to be deployed later. I'm not a jQuery person and am learning as I go, and was using an online solution for this.

The goal is to have an element fade in when a button is clicked. I followed a tutorial and it didn't work.

Some things to consider:
1. The parent theme is Divi
2. This is using a child theme (not sure how much that matters)
3. The button and the element to fade in are not in the same section

Here is the jQuery code:

I have checked and double checked that the button and the section have the correct id tags, so I know that's not the problem.

I have put this code in the correct section as well. I just don't understand why it's not working. I even tried using the original tutorial code and that didn't work at all. Could this be an issue with jQuery running on local environments?

Thanks for your help.


问:
Javascript: How to spy on superagent with Jasmine?
I'm using the superagent ajax library for an app, and I'm trying to write some unit tests for it.  I've got a class which looks like this:

```<code>someClass = {
  getData: function(){
    _this = this;
    superagent.get('/some_url').end(function(res){
      if(res.body){
        _this.data = res.body
      }
     });
   });
 }
</code>```

How do I write a Jasmine test to spy on the _this.data = res.body call? Setting up a spy with and.callThrough() on getData isn't working.  I don't want to actually call the URL in question; I'm just trying to test that if it gets data, it does something with it.

Thanks

答:
Say it's a patch, first make a mock patch return value:

```<code>this.mockPatchObject = {
      set: () => {
        return {
          end: (cb: any) => {
            cb(null, {body: 'etc'});
          },
        };
      },
    };
</code>```

then return it as the value of patch:

```<code>this.superagentSpy = spyOn(request,'patch').and.returnValue(this.mockPatchObject);
</code>```

then spy on the set function of the "mock" patch object:

```<code>this.superagentSetSpy = spyOn(this.mockPatchObject, 'set');
</code>```

Body:
I'm using the superagent ajax library for an app, and I'm trying to write some unit tests for it.  I've got a class which looks like this:

someClass = {
  getData: function(){
    _this = this;
    superagent.get('/some_url').end(function(res){
      if(res.body){
        _this.data = res.body
      }
     });
   });
 }

How do I write a Jasmine test to spy on the _this.data = res.body call? Setting up a spy with and.callThrough() on getData isn't working.  I don't want to actually call the URL in question; I'm just trying to test that if it gets data, it does something with it.

Thanks

Body:
Say it's a patch, first make a mock patch return value:

this.mockPatchObject = {
      set: () => {
        return {
          end: (cb: any) => {
            cb(null, {body: 'etc'});
          },
        };
      },
    };

then return it as the value of patch:

this.superagentSpy = spyOn(request,'patch').and.returnValue(this.mockPatchObject);

then spy on the set function of the "mock" patch object:

this.superagentSetSpy = spyOn(this.mockPatchObject, 'set');


问:
Is it possible to detect the time difference between the moment an epoll is generated by the kernel and the moment the Sun JVM reads it?
i.e. Time A = voltage hits the NIC; Time B = Selector from Java NIO package is able to select socket channel for I/O.</p>

答: you'll need to use something like tcpdump and then correlate timestamps between your application logs and the "sniffer" logs to determine this, it's not possible from the jvm alone.</p>


问:
How to pass a result from a function that requires GUI input (python)?
I'm writing a python script that takes user input through a GUI and then passes that along to a function that basically reads through text files and checks that what the user requested is there.  This function returns an array with True or False for each check.

I want to use this array in a different function (def markup()), but if I call it without giving the function the user input, I get an error.

Is there a way for me to store the results of this function and pass it without needing the user input each time?

Pseudo code:

```<code>def clickButton():

    userInput = [A,B,C,D,E]
    textCheck(userInput)

def textCheck(userInput):

    *code for checking text creates an array named allResults*
    return allResults

def markup():

    results = textCheck()
    print(results)
</code>```

答:
You need to manage allResults as a persistent object.  One way is to pass the results everywhere as a parameter, such that whatever thread is executing always has a handle to the list.  Another way is to (shudder) make it a global variable -- this is somewhat dangerous as a habit, but may be the easiest for you to implement and maintain.  You can also create a Results class and instantiate an object that persists as long as you need it.

I can't recommend one over another without having the flow of the main program.

Body:
I'm writing a python script that takes user input through a GUI and then passes that along to a function that basically reads through text files and checks that what the user requested is there.  This function returns an array with True or False for each check.

I want to use this array in a different function (def markup()), but if I call it without giving the function the user input, I get an error.

Is there a way for me to store the results of this function and pass it without needing the user input each time?

Pseudo code:

def clickButton():

    userInput = [A,B,C,D,E]
    textCheck(userInput)

def textCheck(userInput):

    *code for checking text creates an array named allResults*
    return allResults

def markup():

    results = textCheck()
    print(results)


问:
File reading & counting & sorting by hours in Python
I'm new to Python & here is my question

Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.

Link of the file:

http://www.pythonlearn.com/code/mbox-short.txt

This is my code:

```<code>name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

counts = dict()
for line in handle:
    if not line.startswith ("From "):continue
    #words = line.split()

    col = line.find(':')
    coll = col - 2
    print coll

    #zero = line.find('0')
    #one = line.find('1')
    #b = line[ zero or one : col ]
    #print b
    #hour = words[5:6]
    #print hour

    #for line in hour:
     #   hr = line.split(':')
      #  x = hr[1]

    for x in coll:
        counts[x] = counts.get(x,0) + 1

        for key, value in sorted(counts.items()):
            print key, value
</code>```

My first try was with list splitting(Comments) and it didn't work as it considered the 0 & the 1 as the first & the second letter not the numbers
second one was with line find (:) which is partially worked with minutes not with hours as required!!

First question

Why when I write line.find(:), it takes automatically the 2 numbers after?

Second question

Why when I run the program now, it gives an error
TypeError: 'int' object is not iterable on line 26 ??

Third question

Why it considered 0 & 1 as first & second letters of the line not  0 & 1 numbers

Finally
If possible please solve me this problem with a little of explanation please (with the same codes to keep my learning sequence)

Thank you...

答:
That's because str.find() returns an index of the found substring, not the string itself. Consequently, when you subtract 2 from it and then try to loop through it it will complain that you're trying to loop through an integer and raise a TypeError.

You can grab the whole time string as:

```<code>time_start = line.find(":")
if time_start == -1:  # not found
    continue
time_string = line[time_start-2:time_start+6]  # slice out the whole time string
</code>```

You can then further split the time_string by : to get hours, minutes and seconds (e.g. hours, minutes, seconds = time_string.split(":", 2) just keep in mind that those will be strings, not integers), or if you just want the hour:

```<code>hour = int(line[time_start-2:time_start])
</code>```

You can take it from there - just increase your dict value and when you're done with parsing the file sort everything out.

Body:
I'm new to Python & here is my question

Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.

Link of the file:

http://www.pythonlearn.com/code/mbox-short.txt

This is my code:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

counts = dict()
for line in handle:
    if not line.startswith ("From "):continue
    #words = line.split()

    col = line.find(':')
    coll = col - 2
    print coll

    #zero = line.find('0')
    #one = line.find('1')
    #b = line[ zero or one : col ]
    #print b
    #hour = words[5:6]
    #print hour

    #for line in hour:
     #   hr = line.split(':')
      #  x = hr[1]

    for x in coll:
        counts[x] = counts.get(x,0) + 1

        for key, value in sorted(counts.items()):
            print key, value

My first try was with list splitting(Comments) and it didn't work as it considered the 0 & the 1 as the first & the second letter not the numbers
second one was with line find (:) which is partially worked with minutes not with hours as required!!

First question

Why when I write line.find(:), it takes automatically the 2 numbers after?

Second question

Why when I run the program now, it gives an error
TypeError: 'int' object is not iterable on line 26 ??

Third question

Why it considered 0 & 1 as first & second letters of the line not  0 & 1 numbers

Finally
If possible please solve me this problem with a little of explanation please (with the same codes to keep my learning sequence)

Thank you...

Body:
That's because str.find() returns an index of the found substring, not the string itself. Consequently, when you subtract 2 from it and then try to loop through it it will complain that you're trying to loop through an integer and raise a TypeError.

You can grab the whole time string as:

time_start = line.find(":")
if time_start == -1:  # not found
    continue
time_string = line[time_start-2:time_start+6]  # slice out the whole time string

You can then further split the time_string by : to get hours, minutes and seconds (e.g. hours, minutes, seconds = time_string.split(":", 2) just keep in mind that those will be strings, not integers), or if you just want the hour:

hour = int(line[time_start-2:time_start])

You can take it from there - just increase your dict value and when you're done with parsing the file sort everything out.


问:
Dynamically populating google column charts
I want to populate a dynamic column chart such that the rows as well the columns are dynamic.

Here is a sample json array that I want to transform:
{"location":"Chain","item_category":"A","delay":"681"},
{"location":"Chennai ","item_category":"A","delay":"286"},{"location":"Bawal","item_category":"A","delay":"339"},{"location":"Haridwar","item_category":"A","delay":"1256"},{"location":"Ludhiana","item_category":"A","delay":"1048"},{"location":"Bawal","item_category":"B","delay":"1"}

There are 3 parameters namely location, item_category and delay where:

Location represents columns. (Varies dynamically)

Delay range should be on Y-axis. (Varies dynamically)

On x-axis they are mapped with items.

So far, I'm able to fetch all the required data but unable to create a graph out of it. I have referred to various libraries such as Google-visualization, Pchart, JPGraph and many more.

Each time I freeze on populating the graph dynamically.

Here is a sample code for populating Google Column Chart:

```<code><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Item Category', 'Location 1', 'Location 2', 'Location 3,...'],
          ['item1', 1000, 400, 200,...delay value of location 'n'],
          ['item2', 1170, 460, 250,...],
          ['item3', 660, 1120, 300]...],
          ['item4', 1030, 540, 350]
          .
          .
        ]);
</code>```

//I want to populate this data variable using PHP

```<code>        var chart = new google.charts.Bar(document.getElementById('my_Chartid'));

        chart.draw(data, google.charts.Bar.convertOptions(options));
      }
</code>```

These are the links I have referred. I want to populate this data variable in javascript dynamically.

Google column chart dashboard

https://developers.google.com/chart/interactive/docs/gallery/columnchart

答:
first, need to convert json data to normal array

then use a data view to create a column for each category

then aggregate the data and draw the chart

google.charts.load('current', {
  callback: function () {
    var jsonData = [
      {"location":"Chain","item_category":"A","delay":"681"},
      {"location":"Chennai ","item_category":"A","delay":"286"},
      {"location":"Bawal","item_category":"A","delay":"339"},
      {"location":"Haridwar","item_category":"A","delay":"1256"},
      {"location":"Ludhiana","item_category":"A","delay":"1048"},
      {"location":"Bawal","item_category":"B","delay":"100"}
    ];

    // load chart data
    var chartData = [];
    jsonData.forEach(function (row, rowIndex) {
      // column headings
      var columns = Object.keys(row);
      if (rowIndex === 0) {
        chartData.push(columns);
      }

      // row values
      var chartRow = [];
      columns.forEach(function (column, colIndex) {
        var chartCell = row[column];
        if (colIndex > 1) {
          chartCell = parseFloat(chartCell);
        }
        chartRow.push(chartCell);
      });
      chartData.push(chartRow);
    });
    var data = google.visualization.arrayToDataTable(chartData);

    // create data view
    var view = new google.visualization.DataView(data);

    // init column arrays
    var aggColumns = [];
    var viewColumns = [0];

    // build view & agg column for each category
    data.getDistinctValues(1).forEach(function (category, index) {
      // add view column
      viewColumns.push({
        calc: function (dt, row) {
          if (dt.getValue(row, 1) === category) {
            return dt.getValue(row, 2);
          }
          return null;
        },
        label: category,
        type: 'number'
      });

      // add agg column
      aggColumns.push({
        aggregation: google.visualization.data.sum,
        column: index + 1,
        label: category,
        type: 'number'
      });
    });

    // set view columns
    view.setColumns(viewColumns);

    // agg view
    var group = google.visualization.data.group(
      view,
      [0],
      aggColumns
    );

    var chart = new google.charts.Bar(document.getElementById('chart_div'));

    // use group data to draw chart
    chart.draw(group);
  },
  packages:['bar']
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div></code>```

Body:
first, need to convert json data to normal array

then use a data view to create a column for each category

then aggregate the data and draw the chart

google.charts.load('current', {
  callback: function () {
    var jsonData = [
      {"location":"Chain","item_category":"A","delay":"681"},
      {"location":"Chennai ","item_category":"A","delay":"286"},
      {"location":"Bawal","item_category":"A","delay":"339"},
      {"location":"Haridwar","item_category":"A","delay":"1256"},
      {"location":"Ludhiana","item_category":"A","delay":"1048"},
      {"location":"Bawal","item_category":"B","delay":"100"}
    ];

    // load chart data
    var chartData = [];
    jsonData.forEach(function (row, rowIndex) {
      // column headings
      var columns = Object.keys(row);
      if (rowIndex === 0) {
        chartData.push(columns);
      }

      // row values
      var chartRow = [];
      columns.forEach(function (column, colIndex) {
        var chartCell = row[column];
        if (colIndex > 1) {
          chartCell = parseFloat(chartCell);
        }
        chartRow.push(chartCell);
      });
      chartData.push(chartRow);
    });
    var data = google.visualization.arrayToDataTable(chartData);

    // create data view
    var view = new google.visualization.DataView(data);

    // init column arrays
    var aggColumns = [];
    var viewColumns = [0];

    // build view & agg column for each category
    data.getDistinctValues(1).forEach(function (category, index) {
      // add view column
      viewColumns.push({
        calc: function (dt, row) {
          if (dt.getValue(row, 1) === category) {
            return dt.getValue(row, 2);
          }
          return null;
        },
        label: category,
        type: 'number'
      });

      // add agg column
      aggColumns.push({
        aggregation: google.visualization.data.sum,
        column: index + 1,
        label: category,
        type: 'number'
      });
    });

    // set view columns
    view.setColumns(viewColumns);

    // agg view
    var group = google.visualization.data.group(
      view,
      [0],
      aggColumns
    );

    var chart = new google.charts.Bar(document.getElementById('chart_div'));

    // use group data to draw chart
    chart.draw(group);
  },
  packages:['bar']
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


问:
How can I get the bokeh hover tool to snap to the data?
I would like the bokeh hover tool to snap to the data points instead of interpolating the mouse position on the line. Here's the code that I thought would do it, but I'm still getting interpolated data in the display.</p>

```<code>from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool

# prepare some data
x = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
y0 = [i**2 for i in x]
y1 = [10**i for i in x]
y2 = [10**(i**2) for i in x]

# output to static HTML file
output_file("log_lines.html")

hover = HoverTool(tooltips=[
    ("index", "$index"),
    ("(x,y)", "(@x, @y)"),
    ("desc", "@desc"),
])
hover.point_policy='snap_to_data'
hover.line_policy='none'

# create a new plot
p = figure(
   tools="pan,box_zoom,reset,save,hover",
   y_axis_type="log", y_range=[0.001, 10**11], title="log axis example",
   x_axis_label='sections', y_axis_label='particles'
)

# add some renderers
p.line(x, x, legend="y=x")
p.circle(x, x, legend="y=x", fill_color="white", size=8)
p.line(x, y0, legend="y=x^2", line_width=3)
p.line(x, y1, legend="y=10^x", line_color="red")
p.circle(x, y1, legend="y=10^x", fill_color="red", line_color="red", size=6)
p.line(x, y2, legend="y=10^x^2", line_color="orange", line_dash="4 4")

# show the results
show(p)
</code>```

答:
You're not passing your custom HoverTool instance to the plot. You need to do:</p>

```<code>...
p = figure(tools="pan,box_zoom,reset,save",
           y_axis_type="log", y_range=[0.001, 10**11], title="log axis example",
           x_axis_label='sections', y_axis_label='particles')
p.add_tools(hover) # this is your custom HoverTool
...
</code>```

Body:
I would like the bokeh hover tool to snap to the data points instead of interpolating the mouse position on the line. Here's the code that I thought would do it, but I'm still getting interpolated data in the display.

from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool

# prepare some data
x = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
y0 = [i**2 for i in x]
y1 = [10**i for i in x]
y2 = [10**(i**2) for i in x]

# output to static HTML file
output_file("log_lines.html")

hover = HoverTool(tooltips=[
    ("index", "$index"),
    ("(x,y)", "(@x, @y)"),
    ("desc", "@desc"),
])
hover.point_policy='snap_to_data'
hover.line_policy='none'

# create a new plot
p = figure(
   tools="pan,box_zoom,reset,save,hover",
   y_axis_type="log", y_range=[0.001, 10**11], title="log axis example",
   x_axis_label='sections', y_axis_label='particles'
)

# add some renderers
p.line(x, x, legend="y=x")
p.circle(x, x, legend="y=x", fill_color="white", size=8)
p.line(x, y0, legend="y=x^2", line_width=3)
p.line(x, y1, legend="y=10^x", line_color="red")
p.circle(x, y1, legend="y=10^x", fill_color="red", line_color="red", size=6)
p.line(x, y2, legend="y=10^x^2", line_color="orange", line_dash="4 4")

# show the results
show(p)

Body:
You're not passing your custom HoverTool instance to the plot. You need to do:

...
p = figure(tools="pan,box_zoom,reset,save",
           y_axis_type="log", y_range=[0.001, 10**11], title="log axis example",
           x_axis_label='sections', y_axis_label='particles')
p.add_tools(hover) # this is your custom HoverTool
...


问:
WebPack: require a javascript file into global scope
How can I require() a vendor library into global scope (using the WebPack bundler)? Independently of the fact if it actually has any exports definitions or not.
I just need to require a library so that some other scripts on a page could also be able to use it.

I have found a possible solution by using script-loader like:

```<code>require('script-loader!./some-vendor-library.js');
</code>```

And everything works perfectly, but the key disadvantage of that solution is that included script is actually evaluated via eval() function: the vendor-library code is added to end bundle.js as a string (not as an actual code). Is there any similar solution the library to be included to the end-bundle as a code, but not as a string?

P.S. Sometimes I need to do it dynamically, so, I can not add this to a webpack's config.

答:
Script-loader wraps included scripts into a string sadly, so you could evalutate it out using Blob or something similar. But I think you might want to try something else.

First: Make sure your require("./path/to/a-neat-module.js") is actually pulling in the file. Go to your outputted bundle and sift through the code to confirm. If possible, use npm to install any libraries, so you can simply, and portably, just call require("a-neat-module")

So how can I make my non-exported variables and functions exposed?

You can't directly.

In your entry files, calling this will make all exported variables, available dynamically in the ./js folder and subdirectories, exposed:

```<code>function requireAll(requireContext) {
    return requireContext.keys().map(requireContext);
}
var jsModules = requireAll(require.context("./js", true, /\.js$/));
</code>```

Or if you have a specific module and global in mind:

```<code>window["silly"] = require("./js/silly.js");
window["$"] = window["jQuery"] = require("jquery");
</code>```

But if your files aren't exporting it's just adding size to your bundle. Just think about how the code is exported into your final bundle. It's all wrapped up, so any variables defined in the global scope become local to the wrapping function.

So, that's where loaders and plugins like script-loader and globals-loader come in. They help preprocess your files to be available to you later.

Besides those, I do not know of any plugins that'll help dynamically convert your non-exported code by translation. It may be worthwhile attempting to re-write some of them to support the modular format. I know this isn't great news, but it might be worthwhile to think about how long it'll take to make your javascript modular. Nearly every js library worth its salt functions with this design flow to avoid importation problems.

Ps: Have you checked out the effects of ouput.libraryTarget: "this" in your config? Some people have had success with that.

PPs: Have you checked out webpack-raw-bundler? It will paste your code into another file with the global scope preserved, but it will be in another file so you could run a post build to concat the two together at the end. I run this on a few frontend files so that their non-exported functions are available as if each of the files were included in their own

Body:
How can I require() a vendor library into global scope (using the WebPack bundler)? Independently of the fact if it actually has any exports definitions or not.
I just need to require a library so that some other scripts on a page could also be able to use it.

I have found a possible solution by using script-loader like:

require('script-loader!./some-vendor-library.js');

And everything works perfectly, but the key disadvantage of that solution is that included script is actually evaluated via eval() function: the vendor-library code is added to end bundle.js as a string (not as an actual code). Is there any similar solution the library to be included to the end-bundle as a code, but not as a string?

P.S. Sometimes I need to do it dynamically, so, I can not add this to a webpack's config.

Body:
Script-loader wraps included scripts into a string sadly, so you could evalutate it out using Blob or something similar. But I think you might want to try something else.

First: Make sure your require("./path/to/a-neat-module.js") is actually pulling in the file. Go to your outputted bundle and sift through the code to confirm. If possible, use npm to install any libraries, so you can simply, and portably, just call require("a-neat-module")

So how can I make my non-exported variables and functions exposed?

You can't directly.

In your entry files, calling this will make all exported variables, available dynamically in the ./js folder and subdirectories, exposed:

function requireAll(requireContext) {
    return requireContext.keys().map(requireContext);
}
var jsModules = requireAll(require.context("./js", true, /\.js$/));

Or if you have a specific module and global in mind:

window["silly"] = require("./js/silly.js");
window["$"] = window["jQuery"] = require("jquery");

But if your files aren't exporting it's just adding size to your bundle. Just think about how the code is exported into your final bundle. It's all wrapped up, so any variables defined in the global scope become local to the wrapping function.

So, that's where loaders and plugins like script-loader and globals-loader come in. They help preprocess your files to be available to you later.

Besides those, I do not know of any plugins that'll help dynamically convert your non-exported code by translation. It may be worthwhile attempting to re-write some of them to support the modular format. I know this isn't great news, but it might be worthwhile to think about how long it'll take to make your javascript modular. Nearly every js library worth its salt functions with this design flow to avoid importation problems.

Ps: Have you checked out the effects of ouput.libraryTarget: "this" in your config? Some people have had success with that.

PPs: Have you checked out webpack-raw-bundler? It will paste your code into another file with the global scope preserved, but it will be in another file so you could run a post build to concat the two together at the end. I run this on a few frontend files so that their non-exported functions are available as if each of the files were included in their own <script> tags. You do have to be cautious about load times and method overloading, however.


问:
sequence item 0: expected str instance, bytes found
This question has been asked before but I am not getting where I went wrong. basically I have one many to many table. and am executing complex query on that so I have written views.pay like this

```<code>def flightBooking(request):
    if request.method=='POST':
        form= SearchForm(request.POST)
        if not form.is_valid():
          return render(request, 'booking/search.html',{'form':form})
        else:
                form.is_valid()
                data=(form.cleaned_data['fromLocation'],form.cleaned_data['toLocation'])
                cursor=connection.cursor()
                cursor.execute("""select flight.name,scheduleDepart.depart_time,scheduleArrive.arrival_time.ai.name from
                flight flight,airline ai,flight_schedule scheduleDepart inner join
                flight_schedule scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d,
                 and scheduleArrive.flight_id=flight.id and flight.airline_code_id=ai.id """,[data])
                results=dictFetchAll(cursor)
                return render(results,'booking/searchResult.html')
                #return HttpResponse(results,'booking/searchResult.html')

def dictFetchAll(cursor):
    "return all rows with column name"
    columns=[col[0] for col in cursor.description]
    return [
            dict(zip(columns,row))
            for row in cursor.fetchall()
        ]
</code>```

here my from and to location is integer field
and I got stack trace like this

```<code>  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\kepsla-workspace\WS\demoWS\flightBooking\booking\views.py", line 29, in flightBooking
    and scheduleArrive.flight_id=flight.id and flight.airline_code_id=ai.id """,[data])
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute
    return self.cursor.execute(query, args)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 234, in execute
    args = tuple(map(db.literal, args))
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\connections.py", line 316, in literal
    s = self.escape(o, self.encoders)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\converters.py", line 90, in quote_tuple
    return "(%s)" % (','.join(escape_sequence(t, d)))
TypeError: sequence item 0: expected str instance, bytes found
[06/Jul/2017 22:45:52] "POST /booking HTTP/1.1" 500 97454
</code>```

so can anyone please tell me where I went wrong? or is there any other way to write this query??

答:
I have got solution from like this</p>

```<code>select flight.name,scheduleDepart.depart_time,scheduleArrive.arrival_time.ai.name from
                flight flight,airline ai,flight_schedule scheduleDepart inner join
                flight_schedule scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d,
                 and scheduleArrive.flight_id=flight.id and flight.airline_code_id=ai.id """.join(''.join(elems) for elems in data
</code>```

Body:
This question has been asked before but I am not getting where I went wrong. basically I have one many to many table. and am executing complex query on that so I have written views.pay like this

def flightBooking(request):
    if request.method=='POST':
        form= SearchForm(request.POST)
        if not form.is_valid():
          return render(request, 'booking/search.html',{'form':form})
        else:
                form.is_valid()
                data=(form.cleaned_data['fromLocation'],form.cleaned_data['toLocation'])
                cursor=connection.cursor()
                cursor.execute("""select flight.name,scheduleDepart.depart_time,scheduleArrive.arrival_time.ai.name from
                flight flight,airline ai,flight_schedule scheduleDepart inner join
                flight_schedule scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d,
                 and scheduleArrive.flight_id=flight.id and flight.airline_code_id=ai.id """,[data])
                results=dictFetchAll(cursor)
                return render(results,'booking/searchResult.html')
                #return HttpResponse(results,'booking/searchResult.html')

def dictFetchAll(cursor):
    "return all rows with column name"
    columns=[col[0] for col in cursor.description]
    return [
            dict(zip(columns,row))
            for row in cursor.fetchall()
        ]

here my from and to location is integer field
and I got stack trace like this

  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\kepsla-workspace\WS\demoWS\flightBooking\booking\views.py", line 29, in flightBooking
    and scheduleArrive.flight_id=flight.id and flight.airline_code_id=ai.id """,[data])
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute
    return self.cursor.execute(query, args)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 234, in execute
    args = tuple(map(db.literal, args))
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\connections.py", line 316, in literal
    s = self.escape(o, self.encoders)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\converters.py", line 90, in quote_tuple
    return "(%s)" % (','.join(escape_sequence(t, d)))
TypeError: sequence item 0: expected str instance, bytes found
[06/Jul/2017 22:45:52] "POST /booking HTTP/1.1" 500 97454

so can anyone please tell me where I went wrong? or is there any other way to write this query??

Body:
I have got solution from like this

select flight.name,scheduleDepart.depart_time,scheduleArrive.arrival_time.ai.name from
                flight flight,airline ai,flight_schedule scheduleDepart inner join
                flight_schedule scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d,
                 and scheduleArrive.flight_id=flight.id and flight.airline_code_id=ai.id """.join(''.join(elems) for elems in data


答:
You can do this easily with the tidyverse:

```<code>library(dplyr)
library(tidyr)

df %>%
  group_by(group) %>%
  summarise(valuesum = sum(value)) %>%
  full_join(., expand(df, group = 1:5)) %>%
  complete(group, fill = list(valuesum = 0))
</code>```

The result:

```<code># A tibble: 5 x 2
  group valuesum
  <dbl>    <dbl>
1     1        4
2     2        5
3     3        0
4     4        5
5     5        6
</code>```

Or a bit more difficult to understand with data.table:

```<code>library(data.table)
setDT(df)[.(group = 1:5), on = 'group', sum(value, na.rm = TRUE), by = .EACHI]
</code>```

Title: sum by group including intermediate groups

Body:
I have:

df <- data.frame(group=c(1,1,2,4,4,5), value=c(3,1,5,2,3,6))
aggregate(value ~ group, data = df, FUN = 'sum')

  group value
1  1     4
2  2     5
3  4     5
4  5     6

is there a way to include intermediate groups to return the below? I realise this could be done by creating a dataframe with all the desired groups and matching in the results from aggregate() but I am hoping there is a cleaner way to do this. it would need to be as fast as using aggregate and only use base r packages - this is due to restrictions in my workplace.

  group value
1  1     4
2  2     5
3  3     0
4  4     5
5  5     6

Body:
You can do this easily with the tidyverse:

library(dplyr)
library(tidyr)

df %>%
  group_by(group) %>%
  summarise(valuesum = sum(value)) %>%
  full_join(., expand(df, group = 1:5)) %>%
  complete(group, fill = list(valuesum = 0))

The result:

# A tibble: 5 x 2
  group valuesum
  <dbl>    <dbl>
1     1        4
2     2        5
3     3        0
4     4        5
5     5        6

Or a bit more difficult to understand with data.table:

library(data.table)
setDT(df)[.(group = 1:5), on = 'group', sum(value, na.rm = TRUE), by = .EACHI]