问:
ggplot2: Divide Legend into Two Columns, Each with Its Own Title
I have these factors

```<code>require(ggplot2)
names(table(diamonds$cut))
# [1] "Fair"      "Good"      "Very Good" "Premium"   "Ideal"
</code>```

which I want to visually divide into two groups in the legend (indicating also the group name):

```<code>"First group" -> "Fair", "Good"
</code>```

and

```<code>"Second group" -> "Very Good", "Premium", "Ideal"
</code>```

Starting with this plot

```<code>ggplot(diamonds, aes(color, fill=cut)) + geom_bar() +
  guides(fill=guide_legend(ncol=2)) +
  theme(legend.position="bottom")
</code>```

I want to get

(note that "Very Good" slipped in the second column/group)

答:
This question is a few years old but there are new packages that appeared since this question was asked that can help here.

1) ggnewscale This CRAN package supplies new_scale_fill such that any fill geom after it appears gets a separate scale.

```<code>library(ggplot2)
library(dplyr)
library(ggnewscale)

cut.levs <- levels(diamonds$cut)
cut.values <- setNames(rainbow(length(cut.levs)), cut.levs)

ggplot(diamonds, aes(color)) +
  geom_bar(aes(fill = cut)) +
  scale_fill_manual(aesthetics = "fill", values = cut.values,
                    breaks = cut.levs[1:2], name = "First Grouop:") +
  new_scale_fill() +
  geom_bar(aes(fill2 = cut)) %>% rename_geom_aes(new_aes = c(fill = "fill2")) +
  scale_fill_manual(aesthetics = "fill2", values = cut.values,
                    breaks = cut.levs[-(1:2)], name = "Second Group:") +
  guides(fill=guide_legend(order = 1)) +
  theme(legend.position="bottom")
</code>```

2) relayer The relayer (on github) package allows one to define new aesthetics so here we draw the bars twice, once with a fill aesthetic and once with a fill2 aesthetic, generating a separate legend for each using scale_fill_manual.

```<code>library(ggplot2)
library(dplyr)
library(relayer)

cut.levs <- levels(diamonds$cut)
cut.values <- setNames(rainbow(length(cut.levs)), cut.levs)

ggplot(diamonds, aes(color)) +
  geom_bar(aes(fill = cut)) +
  geom_bar(aes(fill2 = cut)) %>% rename_geom_aes(new_aes = c(fill = "fill2")) +
  guides(fill=guide_legend(order = 1)) +  ##
  theme(legend.position="bottom") +
  scale_fill_manual(aesthetics = "fill", values = cut.values,
                    breaks = cut.levs[1:2], name = "First Grouop:") +
  scale_fill_manual(aesthetics = "fill2", values = cut.values,
                    breaks = cut.levs[-(1:2)], name = "Second Group:")
</code>```

I think the horizontal legend looks a bit better here as it does not take up so much space but if you want two side by side vertical legends use this line in place of the guides line marked ## :

```<code>guides(fill = guide_legend(order = 1, ncol = 1),
  fill2 = guide_legend(ncol = 1)) +
</code>```

Body:
I have these factors

require(ggplot2)
names(table(diamonds$cut))
# [1] "Fair"      "Good"      "Very Good" "Premium"   "Ideal"

which I want to visually divide into two groups in the legend (indicating also the group name):

"First group" -> "Fair", "Good"

and

"Second group" -> "Very Good", "Premium", "Ideal"

Starting with this plot

ggplot(diamonds, aes(color, fill=cut)) + geom_bar() +
  guides(fill=guide_legend(ncol=2)) +
  theme(legend.position="bottom")

I want to get

(note that "Very Good" slipped in the second column/group)

Body:
This question is a few years old but there are new packages that appeared since this question was asked that can help here.

1) ggnewscale This CRAN package supplies new_scale_fill such that any fill geom after it appears gets a separate scale.

library(ggplot2)
library(dplyr)
library(ggnewscale)

cut.levs <- levels(diamonds$cut)
cut.values <- setNames(rainbow(length(cut.levs)), cut.levs)

ggplot(diamonds, aes(color)) +
  geom_bar(aes(fill = cut)) +
  scale_fill_manual(aesthetics = "fill", values = cut.values,
                    breaks = cut.levs[1:2], name = "First Grouop:") +
  new_scale_fill() +
  geom_bar(aes(fill2 = cut)) %>% rename_geom_aes(new_aes = c(fill = "fill2")) +
  scale_fill_manual(aesthetics = "fill2", values = cut.values,
                    breaks = cut.levs[-(1:2)], name = "Second Group:") +
  guides(fill=guide_legend(order = 1)) +
  theme(legend.position="bottom")

2) relayer The relayer (on github) package allows one to define new aesthetics so here we draw the bars twice, once with a fill aesthetic and once with a fill2 aesthetic, generating a separate legend for each using scale_fill_manual.

library(ggplot2)
library(dplyr)
library(relayer)

cut.levs <- levels(diamonds$cut)
cut.values <- setNames(rainbow(length(cut.levs)), cut.levs)

ggplot(diamonds, aes(color)) +
  geom_bar(aes(fill = cut)) +
  geom_bar(aes(fill2 = cut)) %>% rename_geom_aes(new_aes = c(fill = "fill2")) +
  guides(fill=guide_legend(order = 1)) +  ##
  theme(legend.position="bottom") +
  scale_fill_manual(aesthetics = "fill", values = cut.values,
                    breaks = cut.levs[1:2], name = "First Grouop:") +
  scale_fill_manual(aesthetics = "fill2", values = cut.values,
                    breaks = cut.levs[-(1:2)], name = "Second Group:")

I think the horizontal legend looks a bit better here as it does not take up so much space but if you want two side by side vertical legends use this line in place of the guides line marked ## :

guides(fill = guide_legend(order = 1, ncol = 1),
  fill2 = guide_legend(ncol = 1)) +


来源: stackexchange

问:
How would I use javascript to make an image "jiggle" or "shiver"?
So my question is simple, I'm building a webpage in HTML and I want to incorporate a little JavaScript into it so as to make an image "vibrate" or "jiggle" Basically move back and forth in a relatively tight space/pattern.

I did some research and I found this:

```<code>Copy the below code and paste it into the <HEAD> section of your page
Example:<head>Code Here</head>
<style>
.jc{
position:relative;
}
</style>

<script language="JavaScript1.2">

var ns6=document.getElementById&&!document.all
var ie=document.all

var customcollect=new Array()
var i=0

function jiggleit(num){
if ((!document.all&&!document.getElementById)) return;
customcollect[num].style.left=(parseInt(customcollect[num].style.left)==-1)? customcollect[num].style.left=1 : customcollect[num].style.left=-1
}

function init(){
if (ie){
while (eval("document.all.jiggle"+i)!=null){
customcollect[i]= eval("document.all.jiggle"+i)
i++
}
}
else if (ns6){
while (document.getElementById("jiggle"+i)!=null){
customcollect[i]= document.getElementById("jiggle"+i)
i++
}
}

if (customcollect.length==1)
setInterval("jiggleit(0)",80)
else if (customcollect.length>1)
for (y=0;y<customcollect.length;y++){
var tempvariable='setInterval("jiggleit('+y+')",'+'100 )'
eval(tempvariable)
}
}

window.onload=init

</script>

NOW PASTE THIS ANYWHERE YOU WISH YOUR IMAGE TO APPEAR

<span id="jiggle0" class="jc"><b>YOUR IMAGE URL HERE</b></span>
</code>```

They called it a "shivering pic" and gave an example... its exactly what I want. I did it exactly as they described it. I added the code where they said it was needed, I copied all the right parts (none of the directions), and I made sure everything is in the right place.

I tested it out an there was no image! There was nothing! I realized that this was because I was using a black background, and if there was any text, it would also be black, so what actually was happening was that it was merely showing the URL of the image I want to add in (I could see it once I highlighted it). Regardless, still no image (just the text), and still no vibrating/jittering/shivering/jiggling. I did note that there were bold tags right where it suggests to add the image URL... so to me that would make it seem like I would be putting in text.

PLEASE HELP! How do I make this code work, or how do I make an image "shiver"?

答:
I am not sure what is wrong with the above code, sorry. </p>

<p>I hate to toot my own horn, but I recently released a plugin that might work for you, if you are willing to use jQuery. It is called jRumble. You can customize the X range, Y range, rotation range, rumble speed, and event type. It can be used on any element, so you could apply it directly to the image or to the div that the image is in, if you want. </p>

ContentLicense: CC BY-SA 3.0

Body:
So my question is simple, I'm building a webpage in HTML and I want to incorporate a little JavaScript into it so as to make an image "vibrate" or "jiggle" Basically move back and forth in a relatively tight space/pattern.

I did some research and I found this:

Copy the below code and paste it into the  section of your page
Example:Code Here

NOW PASTE THIS ANYWHERE YOU WISH YOUR IMAGE TO APPEAR

YOUR IMAGE URL HERE

They called it a "shivering pic" and gave an example... its exactly what I want. I did it exactly as they described it. I added the code where they said it was needed, I copied all the right parts (none of the directions), and I made sure everything is in the right place.

I tested it out an there was no image! There was nothing! I realized that this was because I was using a black background, and if there was any text, it would also be black, so what actually was happening was that it was merely showing the URL of the image I want to add in (I could see it once I highlighted it). Regardless, still no image (just the text), and still no vibrating/jittering/shivering/jiggling. I did note that there were bold tags right where it suggests to add the image URL... so to me that would make it seem like I would be putting in text.

PLEASE HELP! How do I make this code work, or how do I make an image "shiver"?

Body:
I am not sure what is wrong with the above code, sorry.

I hate to toot my own horn, but I recently released a plugin that might work for you, if you are willing to use jQuery. It is called jRumble. You can customize the X range, Y range, rotation range, rumble speed, and event type. It can be used on any element, so you could apply it directly to the image or to the div that the image is in, if you want.


问:
LINQ Concat nested queries sorting
I have the following code:

```<code>var comp = db.Companies.Select(x => new
        {

            topid = x.ID_comp,
            hill = ((from company in db.Companies
                    where x.ID_comp > company.ID_comp
                    orderby company.ID_comp
                    select new { h = company.ID_comp.ToString() })
                    .Concat((
                    from company in db.Companies
                    where x.ID_comp > company.ID_comp
                    orderby company.ID_comp descending
                    select new { h = company.ID_comp.ToString() })))
                    .Select(y => y.h)
        });
</code>```

The task is to build "pyramids" of ids for each company's id: 121 for 3, 12321 for 4 and so on (if there are companies with id's like 1, 2, 3 4). The idea of the given query is to take all ids that are less than current in 2 sets and then concatenate them, ordering the second set in descending order (the top of the pyramid duplicates, but I'll return to it later).

The problem is that the order by clause is not performed for each set separately, and at the end I get something like 1 2 3 1 2 3 for a company with id 4. How can I order the nested queries in different orders?

UPD1: The data I work with:

Table db.Companies

```<code>ID_comp | name
--------------------
   1    |Don_avia
   2    |Aeroflot
   3    |Dale_avia
   4    |air_France
   5    |British_AW
</code>```

Output:

```<code>1:
2: 1 1
3: 1 2 1 2
4: 1 2 3 1 2 3
5: 1 2 3 4 1 2 3 4
</code>```

UPD2: Resulting query:

```<code>SELECT
[Extent1].[ID_comp] AS [ID_comp],
[Project3].[C2] AS [C1],
[Project3].[C1] AS [C2]
FROM  [dbo].[Company] AS [Extent1]
OUTER APPLY  (SELECT
    [UnionAll1].[C1] AS [C1],
    1 AS [C2]
    FROM  (SELECT
         CAST( [Extent2].[ID_comp] AS nvarchar(max)) AS [C1]
        FROM [dbo].[Company] AS [Extent2]
        WHERE [Extent1].[ID_comp] > [Extent2].[ID_comp]
    UNION ALL
        SELECT
         CAST( [Extent3].[ID_comp] AS nvarchar(max)) AS [C1]
        FROM [dbo].[Company] AS [Extent3]
        WHERE [Extent1].[ID_comp] > [Extent3].[ID_comp]) AS [UnionAll1] ) AS [Project3]
ORDER BY [Extent1].[ID_comp] ASC, [Project3].[C2] ASC
</code>```

答:
```<code>var comp = db.Companies.Select(x => new
{
    topid = x.ID_comp,
    hill = ((from company in db.Companies.OrderBy(y => y.ID_comp)
        where x.ID_comp > company.ID_comp
        select new { h = company.ID_comp.ToString() })
        .Concat((
        from company in db.Companies.OrderByDescending(y => y.ID_comp)
        where x.ID_comp > company.ID_comp
        select new { h = company.ID_comp.ToString() })))
        .Select(y => y.h)
    });
</code>```

ContentLicense: CC BY-SA 4.0

Title: LINQ Concat nested queries sorting

Body:
I have the following code:

var comp = db.Companies.Select(x => new
        {

            topid = x.ID_comp,
            hill = ((from company in db.Companies
                    where x.ID_comp > company.ID_comp
                    orderby company.ID_comp
                    select new { h = company.ID_comp.ToString() })
                    .Concat((
                    from company in db.Companies
                    where x.ID_comp > company.ID_comp
                    orderby company.ID_comp descending
                    select new { h = company.ID_comp.ToString() })))
                    .Select(y => y.h)
        });

The task is to build "pyramids" of ids for each company's id: 121 for 3, 12321 for 4 and so on (if there are companies with id's like 1, 2, 3 4). The idea of the given query is to take all ids that are less than current in 2 sets and then concatenate them, ordering the second set in descending order (the top of the pyramid duplicates, but I'll return to it later).

The problem is that the order by clause is not performed for each set separately, and at the end I get something like 1 2 3 1 2 3 for a company with id 4. How can I order the nested queries in different orders?

UPD1: The data I work with:

Table db.Companies

ID_comp | name
--------------------
   1    |Don_avia
   2    |Aeroflot
   3    |Dale_avia
   4    |air_France
   5    |British_AW

Output:

1:
2: 1 1
3: 1 2 1 2
4: 1 2 3 1 2 3
5: 1 2 3 4 1 2 3 4

UPD2: Resulting query:

SELECT
[Extent1].[ID_comp] AS [ID_comp],
[Project3].[C2] AS [C1],
[Project3].[C1] AS [C2]
FROM  [dbo].[Company] AS [Extent1]
OUTER APPLY  (SELECT
    [UnionAll1].[C1] AS [C1],
    1 AS [C2]
    FROM  (SELECT
         CAST( [Extent2].[ID_comp] AS nvarchar(max)) AS [C1]
        FROM [dbo].[Company] AS [Extent2]
        WHERE [Extent1].[ID_comp] > [Extent2].[ID_comp]
    UNION ALL
        SELECT
         CAST( [Extent3].[ID_comp] AS nvarchar(max)) AS [C1]
        FROM [dbo].[Company] AS [Extent3]
        WHERE [Extent1].[ID_comp] > [Extent3].[ID_comp]) AS [UnionAll1] ) AS [Project3]
ORDER BY [Extent1].[ID_comp] ASC, [Project3].[C2] ASC


问:
Get many values with 1 query
```<code>+----+-----------+-----+
| ID | name      |price|
+----+-----------+-----+
|  1 |dest_tahiti|  10 |
|  2 |dest_bora  |  20 |
| ...|   ...     | ... |
+----+-----------+-----+
</code>```

```<code>$price="SELECT price FROM rates WHERE name IN('dest_tahiti','dest_bora', ...) ";
$price_prep= mysqli_query($connect,$price);
$price_result=  mysqli_fetch_array($price_prep);

echo $prix_result["price"] //Just display price for dest_tahiti with WHERE = 'dest_tahiti';
echo $prix_result["price"] //Just display price for dest_bora  with WHERE = 'dest_bora';
</code>```

I would like to custom values WHERE name = ... for same query with mysqli_fetch_array ?
You can help me ?

答:
You could include the name as an output in your query. And after that iterate over the returned rows and build an array where the index is the name and the value is the price.

$price = "SELECT name, price FROM rates WHERE name IN('dest_tahiti','dest_bora', ...) ";
$price_result = mysqli_query($connect, $price);
$prix_result = [];
while($row = mysqli_fetch_array($price_result, MYSQLI_ASSOC)) {
  $prix_result[ $row['name'] ] = $row['price'];
}

echo $prix_result['dest_tahiti'];
echo $prix_result['dest_bora'];
```

Title: Get many values with 1 query

Body:
+----+-----------+-----+
| ID | name      |price|
+----+-----------+-----+
|  1 |dest_tahiti|  10 |
|  2 |dest_bora  |  20 |
| ...|   ...     | ... |
+----+-----------+-----+

$price="SELECT price FROM rates WHERE name IN('dest_tahiti','dest_bora', ...) ";
$price_prep= mysqli_query($connect,$price);
$price_result=  mysqli_fetch_array($price_prep);

echo $prix_result["price"] //Just display price for dest_tahiti with WHERE = 'dest_tahiti';
echo $prix_result["price"] //Just display price for dest_bora  with WHERE = 'dest_bora';

I would like to custom values WHERE name = ... for same query with mysqli_fetch_array ?
You can help me ?


问:
c#.net function
```<code>namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}
</code>```

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

答:
Do like that:

```<code>   namespace csfunction
    {
        class Program
        {
            static void Main(string[] args)
            {
              AddNumbers(8,5);
            }
            public int AddNumbers(int number1, int number2)
            {
              int result = AddNumbers(10, 5);
              Console.WriteLine(result);
            }
        }
    }
</code>```

Dont try inside function..

Title: c#.net function

Body:
namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

Body:
Do like that:

   namespace csfunction
    {
        class Program
        {
            static void Main(string[] args)
            {
              AddNumbers(8,5);
            }
            public int AddNumbers(int number1, int number2)
            {
              int result = AddNumbers(10, 5);
              Console.WriteLine(result);
            }
        }
    }

Dont try inside function..


问:
Nix mkDerivation can't recognize local filesystem zip file as src
According to https://nixos.org/nixpkgs/manual/#ssec-unpack-phase I can use a zip file as a 'source'.

```<code>with import <nixpkgs> {};

stdenv.mkDerivation {
  name = "test-environment";
  nativeBuildInputs = [ unzip ];
  buildInputs = [ unzip ];
  src = "./x.zip";
}
</code>```

```<code>nix-build
these derivations will be built:
  /nix/store/431i1riasgh2hjs5rd9azfh0ssjlg7qj-test-environment.drv
building '/nix/store/431i1riasgh2hjs5rd9azfh0ssjlg7qj-test-environment.drv'...
unpacking sources
unpacking source archive ./x.zip
unzip:  cannot find or open ./x.zip, ./x.zip.zip or ./x.zip.ZIP.
unzip:  cannot find or open ./x.zip, ./x.zip.zip or ./x.zip.ZIP.
do not know how to unpack source archive ./x.zip
builder for '/nix/store/431i1riasgh2hjs5rd9azfh0ssjlg7qj-test-environment.drv' failed with exit code 1
error: build of '/nix/store/431i1riasgh2hjs5rd9azfh0ssjlg7qj-test-environment.drv' failed
</code>```

There is a x.zip file in my working directory. Why is it failing?

Update:

If I set unpackCmd = "ls -altr"; I see the following output:

```<code>total 16
drwxr-x--- 9 nobody nixbld 4096 May 26 12:39 ..
drwx------ 2 nixbld nixbld 4096 May 26 12:39 .
-rw-r--r-- 1 nixbld nixbld 5806 May 26 12:39 env-vars
</code>```

Why isn't my zip file appearing in that context?

答:
You don't want your Nix derivation to reference local filesystem elements! If anything hasn't been hashed and put into the store, your build is impure, and won't work in sandboxed mode.

Change it to src = ./x.zip, and the file will be hashed and added to the store, and src will be set to a /nix/store/.....-x.zip path.

```<code>with import <nixpkgs> {};

stdenv.mkDerivation {
  name = "test-environment";
  nativeBuildInputs = [ unzip ];
  buildInputs = [ unzip ];
  src = ./x.zip;  ## NO QUOTES!
}
</code>```

Body:
According to https://nixos.org/nixpkgs/manual/#ssec-unpack-phase I can use a zip file as a 'source'.

with import <nixpkgs> {};

stdenv.mkDerivation {
  name = "test-environment";
  nativeBuildInputs = [ unzip ];
  buildInputs = [ unzip ];
  src = "./x.zip";
}

nix-build
these derivations will be built:
  /nix/store/431i1riasgh2hjs5rd9azfh0ssjlg7qj-test-environment.drv
building '/nix/store/431i1riasgh2hjs5rd9azfh0ssjlg7qj-test-environment.drv'...
unpacking sources
unpacking source archive ./x.zip
unzip:  cannot find or open ./x.zip, ./x.zip.zip or ./x.zip.ZIP.
unzip:  cannot find or open ./x.zip, ./x.zip.zip or ./x.zip.ZIP.
do not know how to unpack source archive ./x.zip
builder for '/nix/store/431i1riasgh2hjs5rd9azfh0ssjlg7qj-test-environment.drv' failed with exit code 1
error: build of '/nix/store/431i1riasgh2hjs5rd9azfh0ssjlg7qj-test-environment.drv' failed

There is a x.zip file in my working directory. Why is it failing?

Update:

If I set unpackCmd = "ls -altr"; I see the following output:

total 16
drwxr-x--- 9 nobody nixbld 4096 May 26 12:39 ..
drwx------ 2 nixbld nixbld 4096 May 26 12:39 .
-rw-r--r-- 1 nixbld nixbld 5806 May 26 12:39 env-vars

Why isn't my zip file appearing in that context?

Body:
You don't want your Nix derivation to reference local filesystem elements! If anything hasn't been hashed and put into the store, your build is impure, and won't work in sandboxed mode.

Change it to src = ./x.zip, and the file will be hashed and added to the store, and src will be set to a /nix/store/.....-x.zip path.

with import <nixpkgs> {};

stdenv.mkDerivation {
  name = "test-environment";
  nativeBuildInputs = [ unzip ];
  buildInputs = [ unzip ];
  src = ./x.zip;  ## NO QUOTES!
}


问:
Django/ How get sum of order - 'int' object is not iterable
I'm trying to withdraw the order amount using the method from the model, but I can't. Have error - 'int' object is not iterable

models.py

```<code>class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.PROTECT)
    product = models.ForeignKey(Product, on_delete=models.PROTECT)
    price = models.IntegerField()
    quantity = models.PositiveIntegerField(default=1)

    def get_total_price(self):
        return sum(self.get_price())

    def get_price(self):
        return self.price * self.quantity

    def __str__(self):
        return str(self.order)
</code>```

get_price method it's work, but in get_total_price have error, what I'am doing wrong?

order_success.html

```<code>{% for item in order_item %}
    <tr>
        <td>{{item.quantity}}</td>
        <td>{{item.price}}</td>
        <td>{{item.get_price}}</td>
    </tr>
{% endfor %}

<h2>To pay - {{order_item.get_total_price}}</h2> # doesn't work
</code>```

can you help me write right the sum method, please. I think my method is wrong.

答:
Can you help me write right the sum method, please. I think my method is wrong.

I think your modeling is wrong. An OrderItem has no total_price, it has a certain price that is the quantity times the unit price, but the total price is an attribute of the entire queryset.

We can however calculate such aggregates, by using a queryset in the view for that, like:

```<code>from django.db.models import F, Sum

def some_view(request):
    order_items = OrderItems.object.all()  # might be a different query
    aggrs = order_items.aggregate(
        <b>total_price=Sum(F('quantity') * F('price'))</b>
    )
    context = {
        'order_items': order_items,
        'aggrs': aggrs
    }
    return render(request, 'some_template.html', context)</code>```

In the template, we can then render it like:

```<code>{% for item in <b>order_items</b> %}
    <tr>
        <td>{{item.quantity}}</td>
        <td>{{item.price}}</td>
        <td>{{item.get_price}}</td>
    </tr>
{% endfor %}

<h2>To pay - {{ <b>aggr.total_price</b> }}</h2></code>```

Note: since your order_item is a collection, it makes more sense to use a plular (like order_items here in this sample view).

Note: it makes sense to define this on the Order model, for example:

```<code>class Order(models.Model):

    # ...

    @property
    def total_price():
        return self.order_item_set.aggregate(
            total_price=Sum(F('quantity') * F('price'))
        )['total_price']</code>```

then we can thus write some_order.total_price to obtain the total price of that Order object.

Note: it is a bit confusing that you have a price field and a get_price method, perhaps you should consider renaming price to
  unit_price, and then make get_price a @property named price.

Body:
I'm trying to withdraw the order amount using the method from the model, but I can't. Have error - 'int' object is not iterable

models.py

class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.PROTECT)
    product = models.ForeignKey(Product, on_delete=models.PROTECT)
    price = models.IntegerField()
    quantity = models.PositiveIntegerField(default=1)

    def get_total_price(self):
        return sum(self.get_price())

    def get_price(self):
        return self.price * self.quantity

    def __str__(self):
        return str(self.order)

get_price method it's work, but in get_total_price have error, what I'am doing wrong?

order_success.html

{% for item in order_item %}

        {{item.quantity}}
        {{item.price}}
        {{item.get_price}}

{% endfor %}

To pay - {{order_item.get_total_price}}
 # doesn't work

can you help me write right the sum method, please. I think my method is wrong.

Body:
Can you help me write right the sum method, please. I think my method is wrong.

I think your modeling is wrong. An OrderItem has no total_price, it has a certain price that is the quantity times the unit price, but the total price is an attribute of the entire queryset.

We can however calculate such aggregates, by using a queryset in the view for that, like:

from django.db.models import F, Sum

def some_view(request):
    order_items = OrderItems.object.all()  # might be a different query
    aggrs = order_items.aggregate(
        total_price=Sum(F('quantity') * F('price'))
    )
    context = {
        'order_items': order_items,
        'aggrs': aggrs
    }
    return render(request, 'some_template.html', context)

In the template, we can then render it like:

{% for item in order_items %}
    <tr>
        <td>{{item.quantity}}</td>
        <td>{{item.price}}</td>
        <td>{{item.get_price}}</td>
    </tr>
{% endfor %}

<h2>To pay - {{ aggr.total_price }}</h2>

Note: since your order_item is a collection, it makes more sense to use a plular (like order_items here in this sample view).

Note: it makes sense to define this on the Order model, for example:

class Order(models.Model):

    # ...

    @property
    def total_price():
        return self.order_item_set.aggregate(
            total_price=Sum(F('quantity') * F('price'))
        )['total_price']

then we can thus write some_order.total_price to obtain the total price of that Order object.

Note: it is a bit confusing that you have a price field and a get_price method, perhaps you should consider renaming price to
  unit_price, and then make get_price a @property named price.


问:
Fast loading and querying data in Python
I am doing some data analysis in Python. I have ~15k financial products identified by ISIN code and ~15 columns of daily data for each of them. I would like to easily and quickly access the data given an ISIN code.

The data is in a MySQL DB. On the Python side so far I have been working with Pandas DataFrame.

First thing I did was to use pd.read_sql to load the DF directly from the database. However, this is relatively slow. Then I tried loading the full database in a single DF and serializing it to a pickle file. The loading of the pickle file is fast, a few seconds. However, when querying for an individual product, the perfomance is the same as if I am querying the SQL DB. Here is some code:

import pandas as pd
from sqlalchemy import create_engine, engine
from src.Database import Database
import time
import src.bonds.database.BondDynamicDataETL as BondsETL

database_instance = Database(Database.get_db_instance_risk_analytics_prod())

engine = create_engine(
    "mysql+pymysql://"
    + database_instance.get_db_user()
    + ":"
    + database_instance.get_db_pass()
    + "@"
    + database_instance.get_db_host()
    + "/"
    + database_instance.get_db_name()
)
con = engine.connect()

class DataBase:
    def __init__(self):
        print("made a DatBase instance")

    def get_individual_bond_dynamic_data(self, isin):
        return self.get_individual_bond_dynamic_data_from_db(isin, con)

    @staticmethod
    def get_individual_bond_dynamic_data_from_db(isin, connection):
        df = pd.read_sql(
            "SELECT * FROM BondDynamicDataClean WHERE isin = '"
            + isin
            + "' ORDER BY date ASC",
            con=connection,
        )
        df.set_index("date", inplace=True)
        return df

class PickleFile:
    def __init__(self):
        print("made a PickleFile instance")
        df = pd.read_pickle("bonds_pickle.pickle")
        # df.set_index(['isin', 'date'], inplace=True)
        self.data = df
        print("loaded file")

    def get_individual_bond_dynamic_data(self, isin):
        result = self.data.query("isin == '@isin'")
        return result

fromPickle = PickleFile()
fromDB = DataBase()

isins = BondsETL.get_all_isins_with_dynamic_data_from_db(
    connection=con,
    table_name=database_instance.get_bonds_dynamic_data_clean_table_name(),
)

isins = isins[0:50]

start_pickle = time.time()

for i, isin in enumerate(isins):
    x = fromPickle.get_individual_bond_dynamic_data(isin)
    print("pickle: " + str(i))

stop_pickle = time.time()

for i, isin in enumerate(isins):
    x = fromDB.get_individual_bond_dynamic_data(isin)
    print("db: " + str(i))

stop_db = time.time()

pickle_t = stop_pickle - start_pickle
db_t = stop_db - stop_pickle
print("pickle: " + str(pickle_t))
print("db: " + str(db_t))
print("ratio: " + str(pickle_t / db_t))
```

This results in:
    pickle: 7.636280059814453
    db: 6.167926073074341
    ratio: 1.23806283819615

Also, curiously enough setting the index on the DF (uncommenting the line in the constructor) slows down everything!

I thought of trying https://www.pytables.org/index.html as an alternative to Pandas. Any other ideas or comments?

Greetings,
Georgi

答: It helped a lot to transform the large data frame into a dictionary {isin -> DF} of smaller data frames indexed by ISIN code. Data retrieval is much more efficient from a dictionary compared to from a DF. Also, it is very natural to be able to request a single DF given an ISIN code. Hope this helps someone else.</p>

Body:
I am doing some data analysis in Python. I have ~15k financial products identified by ISIN code and ~15 columns of daily data for each of them. I would like to easily and quickly access the data given an ISIN code.

The data is in a MySQL DB. On the Python side so far I have been working with Pandas DataFrame.

First thing I did was to use pd.read_sql to load the DF directly from the database. However, this is relatively slow. Then I tried loading the full database in a single DF and serializing it to a pickle file. The loading of the pickle file is fast, a few seconds. However, when querying for an individual product, the perfomance is the same as if I am querying the SQL DB. Here is some code:

import pandas as pd
from sqlalchemy import create_engine, engine
from src.Database import Database
import time
import src.bonds.database.BondDynamicDataETL as BondsETL

database_instance = Database(Database.get_db_instance_risk_analytics_prod())

engine = create_engine(
    "mysql+pymysql://"
    + database_instance.get_db_user()
    + ":"
    + database_instance.get_db_pass()
    + "@"
    + database_instance.get_db_host()
    + "/"
    + database_instance.get_db_name()
)
con = engine.connect()

class DataBase:
    def __init__(self):
        print("made a DatBase instance")

    def get_individual_bond_dynamic_data(self, isin):
        return self.get_individual_bond_dynamic_data_from_db(isin, con)

    @staticmethod
    def get_individual_bond_dynamic_data_from_db(isin, connection):
        df = pd.read_sql(
            "SELECT * FROM BondDynamicDataClean WHERE isin = '"
            + isin
            + "' ORDER BY date ASC",
            con=connection,
        )
        df.set_index("date", inplace=True)
        return df

class PickleFile:
    def __init__(self):
        print("made a PickleFile instance")
        df = pd.read_pickle("bonds_pickle.pickle")
        # df.set_index(['isin', 'date'], inplace=True)
        self.data = df
        print("loaded file")

    def get_individual_bond_dynamic_data(self, isin):
        result = self.data.query("isin == '@isin'")
        return result

fromPickle = PickleFile()
fromDB = DataBase()

isins = BondsETL.get_all_isins_with_dynamic_data_from_db(
    connection=con,
    table_name=database_instance.get_bonds_dynamic_data_clean_table_name(),
)

isins = isins[0:50]

start_pickle = time.time()

for i, isin in enumerate(isins):
    x = fromPickle.get_individual_bond_dynamic_data(isin)
    print("pickle: " + str(i))

stop_pickle = time.time()

for i, isin in enumerate(isins):
    x = fromDB.get_individual_bond_dynamic_data(isin)
    print("db: " + str(i))

stop_db = time.time()

pickle_t = stop_pickle - start_pickle
db_t = stop_db - stop_pickle
print("pickle: " + str(pickle_t))
print("db: " + str(db_t))
print("ratio: " + str(pickle_t / db_t))

This results in:
    pickle: 7.636280059814453
    db: 6.167926073074341
    ratio: 1.23806283819615

Also, curiously enough setting the index on the DF (uncommenting the line in the constructor) slows down everything!

I thought of trying https://www.pytables.org/index.html as an alternative to Pandas. Any other ideas or comments?

Greetings,
Georgi


问:
Any utility which can print out map quickly
I am wondering any utility to print out map quickly for debugging purpose.</p>

答:
I think that System.out.println works very well with a map, as this:

```<code>Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key1", 1);
map.put("key2", 2);
System.out.println(map);
</code>```

prints:

```<code>{key1=1, key2=2}
</code>```

Or you can define an utility method like this:

```<code>public void printMap(Map<?, ?> map)
{
    for (Entry<?, ?> e : map.entrySet())
    {
        System.out.println("Key: " + e.getKey() + ", Value: " + e.getValue());
    }
}
</code>```

Body:
I think that System.out.println works very well with a map, as this:

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key1", 1);
map.put("key2", 2);
System.out.println(map);

prints:

{key1=1, key2=2}

Or you can define an utility method like this:

public void printMap(Map<?, ?> map)
{
    for (Entry<?, ?> e : map.entrySet())
    {
        System.out.println("Key: " + e.getKey() + ", Value: " + e.getValue());
    }
}


问:
Accessing values from one-to-many relationship in PonyORM
For a database of games, where one game is called different names by different users, I have two tables, set up as one-to-many:

```<code>class Game(db.Entity):
    name = Set('Name')
    ...

class Name(db.Entity):
    game = Required(Game)
    name = Required(str)
    ...
</code>```

How can I access the names for a specific game? They come back as "Multiset", which (I think) is a special Counter object, when I do this:

```<code>games = Game.select()
for g in games:
    names = g.name.name
    print(names)

>>> Multiset({'Sticks And Stones': 1, 'May Break Your Bones': 1 })
</code>```

This also seems pretty ugly to me, I suppose there must be a better way?

答:
It turns out the to_dict() method, well documented in PonyORM's API Reference, helps greatly with to-many relationships.

```<code> for g in games:
      this_game = g.to_dict(
          with_collections=True,
          related_objects=True,
          exclude=['game_meta', 'statistics']
      )
</code>```

And then access the dict() entries like this: this_game['name']

Body:
For a database of games, where one game is called different names by different users, I have two tables, set up as one-to-many:

class Game(db.Entity):
    name = Set('Name')
    ...

class Name(db.Entity):
    game = Required(Game)
    name = Required(str)
    ...

How can I access the names for a specific game? They come back as "Multiset", which (I think) is a special Counter object, when I do this:

games = Game.select()
for g in games:
    names = g.name.name
    print(names)

>>> Multiset({'Sticks And Stones': 1, 'May Break Your Bones': 1 })

This also seems pretty ugly to me, I suppose there must be a better way?

Body:
It turns out the to_dict() method, well documented in PonyORM's API Reference, helps greatly with to-many relationships.

 for g in games:
      this_game = g.to_dict(
          with_collections=True,
          related_objects=True,
          exclude=['game_meta', 'statistics']
      )

And then access the dict() entries like this: this_game['name']


问:
css - shrink a parent div to fit one child's width and constrain the width of the other child
Say, a parent div has two child divs, one containing text, the other containing an image of known (but variable) width & height.

I would like

the width of the first child (image-containing) div to shrink to fit the width of the image (this i can do)

the parent div (of unspecified width) to shrink to fit the width of the image-containing div (this is ok too)

the text-containing second child div (also of unspecified width) to match the parent div's width irrespective of the quantity of text it contains (this is where it gets tricky).

I have a working version that does what I want until the quantity of text in the second child pushes the parent div's width wider than that of the image.

Here's my code:

css:

```<code>#container{border:1px solid #f00;display:inline-block;}
#child1{border:1px solid #0f0;}
#child2{border:1px solid #00f;}
img {border:1px solid #000;}
</code>```

html:

```<code><div id="container">
<div id="child1"><img src="//www.google.com/logos/2012/Teachers_Day_Alt-2012-hp.jpg" width="300" height="116"></div>
<div id="child2">Lorem ipsum dolor sit amet.</div>
</div>
</code>```

and here's a jsfiddle:
http://jsfiddle.net/BmbAS/1/

you can see where it's going wrong by clicking the 'lengthen/shorten text' link to increase the quantity of text

tldr - i want all the divs to be the same width which is equal to the width of the image

ps. modern browser solution only necessary

答:
The answer provided by @Chris leads me to the following, great solution of my case, where I need to fit the container div only to the first child element (and leave the rest child elements to auto fit to the container's width):

div.container {
    width: fit-content;
    max-width: 100%;
    margin: 16px auto;
    display: table;
}

div.inner-primary {
    display: block;
}

div.inner-rest {
    margin-top: 8px;
    display: table-caption;
    caption-side: bottom;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="inner-primary"><div style="width:200px; border:1px dotted #ccc; border-radius:4px; padding: 4px;">This is the main element that drives the width of the container.</div></div>
  <div class="inner-rest">This is the first of the rest divs that fit automatically to the container...</div>
  <div class="inner-rest">This is the second element...</div>
</div></code>```

Body:
Say, a parent div has two child divs, one containing text, the other containing an image of known (but variable) width & height.

I would like

the width of the first child (image-containing) div to shrink to fit the width of the image (this i can do)

the parent div (of unspecified width) to shrink to fit the width of the image-containing div (this is ok too)

the text-containing second child div (also of unspecified width) to match the parent div's width irrespective of the quantity of text it contains (this is where it gets tricky).

I have a working version that does what I want until the quantity of text in the second child pushes the parent div's width wider than that of the image.

Here's my code:

css:

#container{border:1px solid #f00;display:inline-block;}
#child1{border:1px solid #0f0;}
#child2{border:1px solid #00f;}
img {border:1px solid #000;}

html:

Lorem ipsum dolor sit amet.

and here's a jsfiddle:
http://jsfiddle.net/BmbAS/1/

you can see where it's going wrong by clicking the 'lengthen/shorten text' link to increase the quantity of text

tldr - i want all the divs to be the same width which is equal to the width of the image

ps. modern browser solution only necessary

Body:
The answer provided by @Chris leads me to the following, great solution of my case, where I need to fit the container div only to the first child element (and leave the rest child elements to auto fit to the container's width):

div.container {
    width: fit-content;
    max-width: 100%;
    margin: 16px auto;
    display: table;
}

div.inner-primary {
    display: block;
}

div.inner-rest {
    margin-top: 8px;
    display: table-caption;
    caption-side: bottom;
}

<div class="container">
  <div class="inner-primary"><div style="width:200px; border:1px dotted #ccc; border-radius:4px; padding: 4px;">This is the main element that drives the width of the container.</div></div>
  <div class="inner-rest">This is the first of the rest divs that fit automatically to the container...</div>
  <div class="inner-rest">This is the second element...</div>
</div>


问:
how can i convert this sql to sequelize funciton
i wanna to convert sql to sequelize function

i tried code

```<code>const result = await models.chapter.findOne({
    logging: log.trace,
    where: {
      seq: db.fn('max', db.col('seq'))
    }
  });
</code>```

success code in sql
select * from page_chapter where seq = (select max(seq) from page_chapter)

i expect the result like

```<code>  const result = await model.chapter.findOne({
    where: {
      seq: sequelize.fn('max', sequelize.col('seq'))
    }
  })
</code>```

答:
You can get your query by using sequelize.literal :

```<code>const result = await model.chapter.findOne({
    where: sequelize.literal('"seq" = (SELECT MAX("page_chapter"."seq") FROM "page_chapter")')
})
</code>```

Body:
i wanna to convert sql to sequelize function

i tried code

const result = await models.chapter.findOne({
    logging: log.trace,
    where: {
      seq: db.fn('max', db.col('seq'))
    }
  });

success code in sql
select * from page_chapter where seq = (select max(seq) from page_chapter)

i expect the result like

  const result = await model.chapter.findOne({
    where: {
      seq: sequelize.fn('max', sequelize.col('seq'))
    }
  })

Body:
You can get your query by using sequelize.literal :

const result = await model.chapter.findOne({
    where: sequelize.literal('"seq" = (SELECT MAX("page_chapter"."seq") FROM "page_chapter")')
})


问:
how to convert return type to void using Redux types?
I would like to derive the types for props a react component based on the action types. Since action types always return action object and dispatched props wouldn't have a return type, how can we get the correct type for dispatched props as in the expected type?

```<code>export type Action =
  ({ type: 'PING', arg: number })

const ping = (arg: number): Action => ({
  type: 'PING', arg
})

interface Props {
  ping: typeof ping;
}

const PingTestComponent: React.SFC<Props> = ({ping}) => {
  return (
    <Button onPress={() => ping(123)} title="ping"/>
  );
};

export const PingTest = connect(
  null,
  ({ ping: ping })
)(PingTestComponent);
</code>```

I was expecting the dispatched props resolved types to be

Expected

```<code> interface Props {
   ping: (arg: number) => void
}
</code>```

答:
Actually props connected to action creators will have the same return type and not void.

Anyway, this is how you can change return type of a function:

```<code>declare function foo(bar: string, baz: boolean): { type: 'A' };

type WithReturnVoid<T extends (...arg) => any> = (...args: Parameters<T>) => void;

type VoidFoo = WithReturnVoid<typeof foo>; // (bar: string, baz: boolean) => void
</code>```

Playground

Parameters is builtin utility that allows to get the type of function arguments.

So in your example it will be:

```<code>interface Props {
  ping: WithReturnVoid<typeof ping>;
}
</code>```

Body:
I would like to derive the types for props a react component based on the action types. Since action types always return action object and dispatched props wouldn't have a return type, how can we get the correct type for dispatched props as in the expected type?

export type Action =
  ({ type: 'PING', arg: number })

const ping = (arg: number): Action => ({
  type: 'PING', arg
})

interface Props {
  ping: typeof ping;
}

const PingTestComponent: React.SFC<Props> = ({ping}) => {
  return (
    <Button onPress={() => ping(123)} title="ping"/>
  );
};

export const PingTest = connect(
  null,
  ({ ping: ping })
)(PingTestComponent);

I was expecting the dispatched props resolved types to be

Expected

 interface Props {
   ping: (arg: number) => void
}

Body:
Actually props connected to action creators will have the same return type and not void.

Anyway, this is how you can change return type of a function:

declare function foo(bar: string, baz: boolean): { type: 'A' };

type WithReturnVoid<T extends (...arg) => any> = (...args: Parameters<T>) => void;

type VoidFoo = WithReturnVoid<typeof foo>; // (bar: string, baz: boolean) => void

Playground

Parameters is builtin utility that allows to get the type of function arguments.

So in your example it will be:

interface Props {
  ping: WithReturnVoid<typeof ping>;
}


问:
What is equivalent of SAS (shared access signature) feature of Azure Storage on S3?
Azure provides shared access signatures ([1], [2], [3]) that can delegate access (read/write) to specific blobs/containers/tables/queues in an Azure Storage account using an access key generated through the REST API. Does AWS offer a similar feature?</p>

答:
Presigned URL in S3 is the equivalent:
https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURL.html

There are also ways to generate them with SDKs not mentioned in this documentation, you can google it.

Python for example:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html


问:
jS code is not working, not showing total
I am trying to calculate three values using JS, but the total is not being calculated. it gets values from the form elements and then function calculateTotal() is called onchange. But the total is not being displayed.
*I am new on stackoverflow, please be kind!

I was trying to use method Post on the form, removed it.
Also removed any styling.

function getpkgPriceA() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyA"
  var QuantityA = theForm.elements["qtyA"];
  if (QuantityA == null || QuantityA === false) {
    var totalpkgPriceA = 0;
    return totalpkgPriceA;
  } else {
    var totalpkgPriceA = 5.99 * QuantityA.value;
    return totalpkgPriceA;
  }
}

function getpkgPriceB() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyB"
  var QuantityB = theForm.elements["qtyB"];
  if (QuantityB == null || QuantityB === false) {
    var totalpkgPriceB = 0;
    return totalpkgPriceB;
  } else {
    var totalpkgPriceB = 12.99 * QuantityB.value;
    return totalpkgPriceB;
  }
}

function getpkgPriceC() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyC"
  var QuantityC = theForm.elements["qtyC"];
  if (QuantityC == null || QuantityC === false) {
    var totalpkgPriceC = 0;
    return totapkgPriceC;
  } else {
    var totalpkgPriceC = 17.99 * QuantityC.value;
    return totalpkgPriceC;
  }
}

function calculateTotal() {

  var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
  //display the result
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'block';
  divobj.innerHTML = "Your Total: £"
  TotalpkgPrice.toFixed(2);
}

function hideTotal() {
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'none';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" id="Mangoform">
  <div>
    <div>
      <div>
        <span>Small: 1.3kg</span>
        <input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
      </div>
      </br>
      <div>
        <span>Large: 3.3kg</span>
        <input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
      </div>
      </br>
      <div>
        <span>Small: 5.0kg</span>
        <input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
      </div>
    </div>
  </div>
  <span id="totalprice" name='totalprice'>Your Total:</span>
  <div>
    <input name="submit" type="submit" value="submit" onclick="calculateTotal()">
  </div>
</form></code>```

if value in qtyA=1, qtyB=1 and qtyC=1 and adding 2 then total should be displayed

as 38.97

(5.99*1)+(12.99*1)+(17.99*1)+2=38.97

if qtyA=2, qtyB=2 and qtyC=3 adding 2
(5.99*2)+(12.99*2)+(17.99*3)+2=93.93

Please point out the mistake. Thanks.

答:
There is one extra closing curly bracket in getpkgPriceA function. You just need to remove it and also you need to add + sign while adding strings:

```<code>"Your Total: £" + TotalpkgPrice.toFixed(2);
</code>```

Try this:

function getpkgPriceA(){
    //Get a reference to the form id="Mangoform"
    var theForm = document.forms["Mangoform"];
    //Get a reference to the select id="qtyA"
    var QuantityA=theForm.elements["qtyA"];
    if(QuantityA==null || QuantityA===false){
        var totalpkgPriceA = 0;
        return totalpkgPriceA;
    }
        var totalpkgPriceA = 5.99 * QuantityA.value;
        return totalpkgPriceA;
}

function getpkgPriceB(){
    //Get a reference to the form id="Mangoform"
    var theForm = document.forms["Mangoform"];
    //Get a reference to the select id="qtyB"
    var QuantityB=theForm.elements["qtyB"];
    if(QuantityB==null || QuantityB===false){
        var totalpkgPriceB = 0;
        return totalpkgPriceB;
    }
    else{
        var totalpkgPriceB = 12.99 * QuantityB.value;
        return totalpkgPriceB;
    }
}

function getpkgPriceC(){
    //Get a reference to the form id="Mangoform"
    var theForm = document.forms["Mangoform"];
    //Get a reference to the select id="qtyC"

    var QuantityC=theForm.elements["qtyC"];
    if(QuantityC==null || QuantityC===false){
        var totalpkgPriceC = 0;
        return totapkgPriceC;
    }
    else{
        var totalpkgPriceC = 17.99 * QuantityC.value;
        return totalpkgPriceC;
    }
}

function calculateTotal(){
    var TotalpkgPrice =  getpkgPriceA() + getpkgPriceB() + getpkgPriceC() +2;
    //display the result
    var divobj = document.getElementById('totalprice');
    divobj.style.display='block';
    divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2)  ;
   }

function hideTotal(){
  var divobj = document.getElementById('totalprice');
    divobj.style.display='none';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form  action="#" id="Mangoform">
    <div >
    <div>
    <div>
            <span>
                Small: 1.3kg
            </span>
            <input  type="number" id="qtyA" name="qtyA"  placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
        </div>
        </br>
        <div>
        <span>
            Large: 3.3kg
        </span>
        <input type="number" id="qtyB" name="qtyB"  placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
        </div>
        </br>
        <div>
            <span>
                Small: 5.0kg
            </span>
            <input type="number" id="qtyC" name="qtyC"  placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
        </div>
        </div>
        </div>
        <span id="totalprice" name='totalprice'>
            Your Total:
        </span>
        <div>
            <input name="submit" type="submit" value="submit" onclick="calculateTotal()" >
        </div>

</form></code>```

Body:
I am trying to calculate three values using JS, but the total is not being calculated. it gets values from the form elements and then function calculateTotal() is called onchange. But the total is not being displayed.
*I am new on stackoverflow, please be kind!

I was trying to use method Post on the form, removed it.
Also removed any styling.

function getpkgPriceA() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyA"
  var QuantityA = theForm.elements["qtyA"];
  if (QuantityA == null || QuantityA === false) {
    var totalpkgPriceA = 0;
    return totalpkgPriceA;
  } else {
    var totalpkgPriceA = 5.99 * QuantityA.value;
    return totalpkgPriceA;
  }
}

function getpkgPriceB() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyB"
  var QuantityB = theForm.elements["qtyB"];
  if (QuantityB == null || QuantityB === false) {
    var totalpkgPriceB = 0;
    return totalpkgPriceB;
  } else {
    var totalpkgPriceB = 12.99 * QuantityB.value;
    return totalpkgPriceB;
  }
}

function getpkgPriceC() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyC"
  var QuantityC = theForm.elements["qtyC"];
  if (QuantityC == null || QuantityC === false) {
    var totalpkgPriceC = 0;
    return totapkgPriceC;
  } else {
    var totalpkgPriceC = 17.99 * QuantityC.value;
    return totalpkgPriceC;
  }
}

function calculateTotal() {

  var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
  //display the result
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'block';
  divobj.innerHTML = "Your Total: £"
  TotalpkgPrice.toFixed(2);
}

function hideTotal() {
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'none';
}

<form action="#" id="Mangoform">

        Small: 1.3kg
        <input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">

        Large: 3.3kg
        <input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">

        Small: 5.0kg
        <input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">

  Your Total:

    <input name="submit" type="submit" value="submit" onclick="calculateTotal()">

</form>

if value in qtyA=1, qtyB=1 and qtyC=1 and adding 2 then total should be displayed

as 38.97

(5.99*1)+(12.99*1)+(17.99*1)+2=38.97

if qtyA=2, qtyB=2 and qtyC=3 adding 2
(5.99*2)+(12.99*2)+(17.99*3)+2=93.93

Please point out the mistake. Thanks.

Body:
There is one extra closing curly bracket in getpkgPriceA function. You just need to remove it and also you need to add + sign while adding strings:

"Your Total: £" + TotalpkgPrice.toFixed(2);

Try this:

function getpkgPriceA(){
    //Get a reference to the form id="Mangoform"
    var theForm = document.forms["Mangoform"];
    //Get a reference to the select id="qtyA"
    var QuantityA=theForm.elements["qtyA"];
    if(QuantityA==null || QuantityA===false){
        var totalpkgPriceA = 0;
        return totalpkgPriceA;
    }
        var totalpkgPriceA = 5.99 * QuantityA.value;
        return totalpkgPriceA;
}

function getpkgPriceB(){
    //Get a reference to the form id="Mangoform"
    var theForm = document.forms["Mangoform"];
    //Get a reference to the select id="qtyB"
    var QuantityB=theForm.elements["qtyB"];
    if(QuantityB==null || QuantityB===false){
        var totalpkgPriceB = 0;
        return totalpkgPriceB;
    }
    else{
        var totalpkgPriceB = 12.99 * QuantityB.value;
        return totalpkgPriceB;
    }
}

function getpkgPriceC(){
    //Get a reference to the form id="Mangoform"
    var theForm = document.forms["Mangoform"];
    //Get a reference to the select id="qtyC"

    var QuantityC=theForm.elements["qtyC"];
    if(QuantityC==null || QuantityC===false){
        var totalpkgPriceC = 0;
        return totapkgPriceC;
    }
    else{
        var totalpkgPriceC = 17.99 * QuantityC.value;
        return totalpkgPriceC;
    }
}

function calculateTotal(){
    var TotalpkgPrice =  getpkgPriceA() + getpkgPriceB() + getpkgPriceC() +2;
    //display the result
    var divobj = document.getElementById('totalprice');
    divobj.style.display='block';
    divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2)  ;
   }

function hideTotal(){
  var divobj = document.getElementById('totalprice');
    divobj.style.display='none';
}

<form  action="#" id="Mangoform">
    <div >
    <div>
    <div>
            <span>
                Small: 1.3kg
            </span>
            <input  type="number" id="qtyA" name="qtyA"  placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
        </div>
        </br>
        <div>
        <span>
            Large: 3.3kg
        </span>
        <input type="number" id="qtyB" name="qtyB"  placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
        </div>
        </br>
        <div>
            <span>
                Small: 5.0kg
            </span>
            <input type="number" id="qtyC" name="qtyC"  placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
        </div>
        </div>
        </div>
        <span id="totalprice" name='totalprice'>
            Your Total:
        </span>
        <div>
            <input name="submit" type="submit" value="submit" onclick="calculateTotal()" >
        </div>

</form>


问:
How to fix 'ValueError: math domain error' in python?
I am trying to write a program which calculates formula y=√x*x + 3*x - 500,
Interval is [x1;x2] and f.e x1=15, x2=25.

I tried to use Exception Handling but it didn't help.
And the code I try to use now gives me: ValueError: math domain error

```<code>import math

x1 = int(input("Enter first number:"))
x2 = int(input("Enter second number:"))
print(" x", "   y")
for x in range(x1, x2):
    formula = math.sqrt(x * x + 3 * x - 500)
    if formula < 0:
        print("square root cant be negative")
    print(x, round(formula, 2))
</code>```

The output should look like this:

```<code>x   y
15 ***
16 ***
17 ***
18 ***
19 ***
20 ***
21 2.00
22 7.07
23 9.90
24 12.17
25 14.14
</code>```

答:
You should try to modify your code as shown below. Compute the expression value before performing sqrt

```<code>print(" x", " y")
for x in range(x1, x2):
    expres = x * x + 3 * x - 500
    if expres >= 0:
        formula = math.sqrt(expres)
        print(x, round(formula, 2))
    else:
        print(x, "***")

#  x  y
# 15 ***
# 16 ***
# 17 ***
# 18 ***
# 19 ***
# 20 ***
# 21 2.0
# 22 7.07
# 23 9.9
# 24 12.17
# 25 14.14
</code>```

Body:
I am trying to write a program which calculates formula y=√x*x + 3*x - 500,
Interval is [x1;x2] and f.e x1=15, x2=25.

I tried to use Exception Handling but it didn't help.
And the code I try to use now gives me: ValueError: math domain error

import math

x1 = int(input("Enter first number:"))
x2 = int(input("Enter second number:"))
print(" x", "   y")
for x in range(x1, x2):
    formula = math.sqrt(x * x + 3 * x - 500)
    if formula < 0:
        print("square root cant be negative")
    print(x, round(formula, 2))

The output should look like this:

x   y
15 ***
16 ***
17 ***
18 ***
19 ***
20 ***
21 2.00
22 7.07
23 9.90
24 12.17
25 14.14

Body:
You should try to modify your code as shown below. Compute the expression value before performing sqrt

print(" x", " y")
for x in range(x1, x2):
    expres = x * x + 3 * x - 500
    if expres >= 0:
        formula = math.sqrt(expres)
        print(x, round(formula, 2))
    else:
        print(x, "***")

#  x  y
# 15 ***
# 16 ***
# 17 ***
# 18 ***
# 19 ***
# 20 ***
# 21 2.0
# 22 7.07
# 23 9.9
# 24 12.17
# 25 14.14


问:
What is the type of apomorphism specific to list and how is it implemented?
I am learning recursion schemes and it has proven very helpful to me to implement them specific to the list type. However, I got stuck on apomorphisms.

Here is an implementation of tails in terms of apo I recently found:

import Data.Functor.Foldable

tailsApo :: [a] -> [[a]]
tailsApo = apo coalgTails
    where
    coalgTails = \case
        [] -> Cons [] (Left [])
        li@(_:xs) -> Cons li (Right xs)
```

<p>Unfortunately, I couldn't import <code>Data.Functor.Foldable</code> with GHCi, because I get a package not found error. Another search revealed this implemenation of apo specific to lists:</p>

<pre class="lang-hs prettyprint-override"><code>apoList :: ([b] -> Maybe (a, Either [b] [a])) -> [b] -> [a]
apoList f b = case f b of
    Nothing -> []
    Just (x, Left c)  -> x : apoL f c
    Just (x, Right e) -> x : e
</code>```

Obviously, apoList's first argument doesn't match with tailsApo. I'd expext the type to be something like apoList :: ([b] -> Either (a, b) [a])) -> [b] -> [a].

There seems to be no more beginner friendly information on this subject. I appreciate any help.

答:
The type is

```<code>apo :: (a ->           Base t   (Either t  a  ))      -- g :: a -> Base t r
    ->  a -> t

apo  g  a =  rec a  where                             -- rec = apo g :: a -> t
             rec = embed . fmap (either id rec) . g
{-
type family                           Base t :: * -> *
embed                ::               Base t    t -> t
fmap (either id rec) :: Base t   r -> Base t    t
      either id rec  ::          r ->           t            r ~ Either t a
          g :: a ->     Base t   r                           r ~ Either t a
rec = apo g :: a ->                                  t
-}
</code>```

Here a is the seed. For t ~ [b] we'll have

```<code>type instance Base [b] = ListF b
data                     ListF b r = Nil | Cons b r

Base t (Either t a) ~    ListF b (Either [b] a)
                    ~                Maybe     (b, Either [b] a)
</code>```

so overall it'll be

```<code>apoList :: (a -> Maybe (b, Either [b] a)) -> a -> [b]
apoList coalg a = case coalg a of
   Nothing           -> []  -- (embed  Nil       )                       -- either
   Just (b, Left bs) -> b : bs   -- no more seed, no more steps to do!   --   id    $ bs
   Just (b, Right a) -> b : apoList coalg a  -- new seed, go on!         --   apo g $ a
                     -- ^^^^^  (embed (Cons b bs))
</code>```

so

```<code>apoTails :: [a] -> [[a]]      -- [[a]] ~ [b], b ~ [a]
apoTails = apoList tailsCoalg
  where
  -- tailsCoalg :: [a] -> Maybe ([a], Either [[a]] [a])
  tailsCoalg []       = Just ([], Left [])
  tailsCoalg s@(_:xs) = Just (s, Right xs)
</code>```

edit: a simpler apoList with a simpler typed coalgebra,

```<code>apoListE :: (a -> Either [b] (b, a)) -> a -> [b]
apoListE coalg a = case coalg a of
   Left bs      -> bs             -- final tail, whether empty or non-empty
   Right (b, a) -> b : apoListE coalg a     -- new element and seed, go on!
</code>```

seems to be easier to use:

```<code>apoTailsE :: [a] -> [[a]]
apoTailsE = apoListE tailsCoalgE
  where
  -- tailsCoalgE :: [a] -> Either [[a]] ([a], [a])
  tailsCoalgE []       = Left [[]]
  tailsCoalgE s@(_:xs) = Right (s, xs)
</code>```

Looks like the two types are equivalent:

```<code>type instance Base [b] = ListF b
data                     ListF b r = Nil | Cons b r

Base t (Either t a) ~    ListF b (Either [b] a)
                    ~                Maybe     (b, Either [b] a)
                    ~                              Either [b] (b, a)
--------------------------------------------------------------------
Maybe (b, Either [b] a)  ~  Either [b] (b, a)

{ Nothing,               ~  { Left [],
  Just (b, Left bs),          Left (b:bs),
  Just (b, Right a)           Right (b, a)
}                           }
</code>```

Body:
I am learning recursion schemes and it has proven very helpful to me to implement them specific to the list type. However, I got stuck on apomorphisms.

Here is an implementation of tails in terms of apo I recently found:

import Data.Functor.Foldable

tailsApo :: [a] -> [[a]]
tailsApo = apo coalgTails
    where
    coalgTails = \case
        [] -> Cons [] (Left [])
        li@(_:xs) -> Cons li (Right xs)

Unfortunately, I couldn't import Data.Functor.Foldable with GHCi, because I get a package not found error. Another search revealed this implemenation of apo specific to lists:

apoList :: ([b] -> Maybe (a, Either [b] [a])) -> [b] -> [a]
apoList f b = case f b of
    Nothing -> []
    Just (x, Left c)  -> x : apoL f c
    Just (x, Right e) -> x : e

Obviously, apoList's first argument doesn't match with tailsApo. I'd expext the type to be something like apoList :: ([b] -> Either (a, b) [a])) -> [b] -> [a].

There seems to be no more beginner friendly information on this subject. I appreciate any help.

Body:
The type is

apo :: (a ->           Base t   (Either t  a  ))      -- g :: a -> Base t r
    ->  a -> t

apo  g  a =  rec a  where                             -- rec = apo g :: a -> t
             rec = embed . fmap (either id rec) . g
{-
type family                           Base t :: * -> *
embed                ::               Base t    t -> t
fmap (either id rec) :: Base t   r -> Base t    t
      either id rec  ::          r ->           t            r ~ Either t a
          g :: a ->     Base t   r                           r ~ Either t a
rec = apo g :: a ->                                  t
-}

Here a is the seed. For t ~ [b] we'll have

type instance Base [b] = ListF b
data                     ListF b r = Nil | Cons b r

Base t (Either t a) ~    ListF b (Either [b] a)
                    ~                Maybe     (b, Either [b] a)

so overall it'll be

apoList :: (a -> Maybe (b, Either [b] a)) -> a -> [b]
apoList coalg a = case coalg a of
   Nothing           -> []  -- (embed  Nil       )                       -- either
   Just (b, Left bs) -> b : bs   -- no more seed, no more steps to do!   --   id    $ bs
   Just (b, Right a) -> b : apoList coalg a  -- new seed, go on!         --   apo g $ a
                     -- ^^^^^  (embed (Cons b bs))

so

apoTails :: [a] -> [[a]]      -- [[a]] ~ [b], b ~ [a]
apoTails = apoList tailsCoalg
  where
  -- tailsCoalg :: [a] -> Maybe ([a], Either [[a]] [a])
  tailsCoalg []       = Just ([], Left [])
  tailsCoalg s@(_:xs) = Just (s, Right xs)

edit: a simpler apoList with a simpler typed coalgebra,

apoListE :: (a -> Either [b] (b, a)) -> a -> [b]
apoListE coalg a = case coalg a of
   Left bs      -> bs             -- final tail, whether empty or non-empty
   Right (b, a) -> b : apoListE coalg a     -- new element and seed, go on!

seems to be easier to use:

apoTailsE :: [a] -> [[a]]
apoTailsE = apoListE tailsCoalgE
  where
  -- tailsCoalgE :: [a] -> Either [[a]] ([a], [a])
  tailsCoalgE []       = Left [[]]
  tailsCoalgE s@(_:xs) = Right (s, xs)

Looks like the two types are equivalent:

type instance Base [b] = ListF b
data                     ListF b r = Nil | Cons b r

Base t (Either t a) ~    ListF b (Either [b] a)
                    ~                Maybe     (b, Either [b] a)
                    ~                              Either [b] (b, a)
--------------------------------------------------------------------
Maybe (b, Either [b] a)  ~  Either [b] (b, a)

{ Nothing,               ~  { Left [],
  Just (b, Left bs),          Left (b:bs),
  Just (b, Right a)           Right (b, a)
}                           }


问:
Dart How to get the name of an enum as a String
Before enums were available in Dart I wrote some cumbersome and hard to maintain code to simulate enums and now want to simplify it.  I need to get the name of the enum as a string such as can be done with Java but cannot.

For instance little test code snippet returns 'day.MONDAY' in each case when what I want is 'MONDAY"

```<code>enum day {MONDAY, TUESDAY}
print( 'Today is $day.MONDAY');
print( 'Today is $day.MONDAY.toString()');
</code>```

Am I correct that to get just 'MONDAY' I will need to parse the string?

答:
Simplest way to get the name of an enum is a standard method from the flutter/foundation.dart</p>

```<code>describeEnum(enumObject)

enum Day {
  monday, tuesday, wednesday, thursday, friday, saturday, sunday
}

void validateDescribeEnum() {
  assert(Day.monday.toString() == 'Day.monday');
  assert(describeEnum(Day.monday) == 'monday');
}
</code>```

Body:
Before enums were available in Dart I wrote some cumbersome and hard to maintain code to simulate enums and now want to simplify it.  I need to get the name of the enum as a string such as can be done with Java but cannot.

For instance little test code snippet returns 'day.MONDAY' in each case when what I want is 'MONDAY"

enum day {MONDAY, TUESDAY}
print( 'Today is $day.MONDAY');
print( 'Today is $day.MONDAY.toString()');

Am I correct that to get just 'MONDAY' I will need to parse the string?

Body:
Simplest way to get the name of an enum is a standard method from the flutter/foundation.dart

describeEnum(enumObject)

enum Day {
  monday, tuesday, wednesday, thursday, friday, saturday, sunday
}

void validateDescribeEnum() {
  assert(Day.monday.toString() == 'Day.monday');
  assert(describeEnum(Day.monday) == 'monday');
}


答:
Data.Functor.Foldable is provided by the recursion-schemes package. The type of apo there is:

```<code>apo :: Corecursive t => (a -> Base t (Either t a)) -> a -> t
</code>```

Here, t is the structure being generated by the unfold, and Base t is its base functor. Broadly speaking, the base functor represents one level of the recursive structure, the idea being that if we indefinitely nest it within itself we get a type equivalent to that of the whole structure -- in fact, that is precisely what Fix from Data.Functor.Foldable does. (On a meta note, there doesn't seem to be a Q&A here specifically about Base in recursion-schemes; it could be useful to have one.)

Base for lists is:

```<code>data ListF a b = Nil | Cons a b
</code>```

So apo specialises to:

```<code>apo @[_] :: (b -> ListF a (Either [a] b)) -> b -> [a]
</code>```

If we want to write it without using the recursion-scheme infrastructure, we can use the fact that ListF a b is isomorphic to Maybe (a, b):

```<code>Nil     | Cons  a  b
Nothing | Just (a, b)
</code>```

In terms of Maybe (a, b), the signature would then become:

```<code>apoList :: (b -> Maybe (a, Either [a] b)) -> b -> [a]
</code>```

In the coalgebra (that is, the function argument to apo), Nothing (or Nil, in the recursion-schemes version) signal the generation of the list should be stopped by capping it with an empty tail. That is why you still need Maybe, even if you are also using Either to short-circuit the unfold in other ways.

The implementation of this apoList is pretty much like the one in your question, except that this signature doesn't restrict the seed (of b type) to a list, and flips the roles of Left and Right (so that Left signals short-circuiting):

```<code>apoList :: (b -> Maybe (a, Either [a] b)) -> b -> [a]
apoList f b = case f b of
    Nothing -> []
    Just (x, Left e) -> x : e
    Just (x, Right c) -> x : apoList f c
</code>```

Title: What is the type of apomorphism specific to list and how is it implemented?

Body:
Data.Functor.Foldable is provided by the recursion-schemes package. The type of apo there is:

apo :: Corecursive t => (a -> Base t (Either t a)) -> a -> t

Here, t is the structure being generated by the unfold, and Base t is its base functor. Broadly speaking, the base functor represents one level of the recursive structure, the idea being that if we indefinitely nest it within itself we get a type equivalent to that of the whole structure -- in fact, that is precisely what Fix from Data.Functor.Foldable does. (On a meta note, there doesn't seem to be a Q&A here specifically about Base in recursion-schemes; it could be useful to have one.)

Base for lists is:

data ListF a b = Nil | Cons a b

So apo specialises to:

apo @[_] :: (b -> ListF a (Either [a] b)) -> b -> [a]

If we want to write it without using the recursion-scheme infrastructure, we can use the fact that ListF a b is isomorphic to Maybe (a, b):

Nil     | Cons  a  b
Nothing | Just (a, b)

In terms of Maybe (a, b), the signature would then become:

apoList :: (b -> Maybe (a, Either [a] b)) -> b -> [a]

In the coalgebra (that is, the function argument to apo), Nothing (or Nil, in the recursion-schemes version) signal the generation of the list should be stopped by capping it with an empty tail. That is why you still need Maybe, even if you are also using Either to short-circuit the unfold in other ways.

The implementation of this apoList is pretty much like the one in your question, except that this signature doesn't restrict the seed (of b type) to a list, and flips the roles of Left and Right (so that Left signals short-circuiting):

apoList :: (b -> Maybe (a, Either [a] b)) -> b -> [a]
apoList f b = case f b of
    Nothing -> []
    Just (x, Left e) -> x : e
    Just (x, Right c) -> x : apoList f c


问:
How to test directory reading and addressing method in ruby?
I have a ruby class to read directory and do something for each file. But I am not sure how to test it.

```<code>class Scanner
  def scan(dir)
    Dir.glob(File.join(dir, '**', '*')).each do |path|
       verify(path)
    end
  end

  private

  def verify(path)
    do something for the file...
  end
end
</code>```

I want to have a unit-testing for scan method.

Should I mock something?

Should I provide a test directory in spec/fixtures?

What's the expectation?

Cheers

答:
There are few ways to approach that. One (proposed in the comments) is to separate the concerns, e.g.

```<code>class Scanner
  def scan(dir)
    Dir.glob(File.join(dir, '**', '*')).each do |path|
       verify(path)
    end
  end

  private

  def verify(path)
    Veryfier.new.verify(File.read(path))
    # you can test veryfier easily by passing different strings into `verify` method
  end
end
</code>```

And go on with your life, as Scanner#scan is not that complicated anymore, and one would not expect many bugs in there.

But, if for whatever reason, you want it tested as well, you can do one of the following:

set up a dir structure under test/features and tread different directories like different cases. This has one drawback: you have to inspect directories plus read the tests to understand the tests. But it's simple to do.

use Dir.tmpdir and File.tmpfile to set up the dir structure inside your tests. This is a bit more involved, but on the plus side you have the structure and the tests for behavior of the Scanner in a single test file.

Body:
I have a ruby class to read directory and do something for each file. But I am not sure how to test it.

class Scanner
  def scan(dir)
    Dir.glob(File.join(dir, '**', '*')).each do |path|
       verify(path)
    end
  end

  private

  def verify(path)
    do something for the file...
  end
end

I want to have a unit-testing for scan method.

Should I mock something?

Should I provide a test directory in spec/fixtures?

What's the expectation?

Cheers

Body:
There are few ways to approach that. One (proposed in the comments) is to separate the concerns, e.g.

class Scanner
  def scan(dir)
    Dir.glob(File.join(dir, '**', '*')).each do |path|
       verify(path)
    end
  end

  private

  def verify(path)
    Veryfier.new.verify(File.read(path))
    # you can test veryfier easily by passing different strings into `verify` method
  end
end

And go on with your life, as Scanner#scan is not that complicated anymore, and one would not expect many bugs in there.

But, if for whatever reason, you want it tested as well, you can do one of the following:

set up a dir structure under test/features and tread different directories like different cases. This has one drawback: you have to inspect directories plus read the tests to understand the tests. But it's simple to do.

use Dir.tmpdir and File.tmpfile to set up the dir structure inside your tests. This is a bit more involved, but on the plus side you have the structure and the tests for behavior of the Scanner in a single test file.


问:
Unity3d - How to show model edges in game?
I want the same effect as the Unity editor when an object clicked, same as the top on the picture.

The camera view at bottom show that no any edges on model.

I google a bit, there are many topic about wireframe and edge detection, but i cant find anything useful about showing the inner edges.

答:
Since I had same, I wrote custom shader.
Code Listing :</p>

```<code>Shader "DESS/WireframeShader"
{
    Properties
    {
        _WireColor("Edges Color", Color) = (0,0,0,1)
        _WireThickness("Edge Thickness", RANGE(0, 800)) = 100
        _WireSmoothness("Edge Smoothness", RANGE(0, 20)) = 3
        _AlbedoColor("Albedo Color", Color) = (1,1,1,1)
        _MainTex("Albedo (RGB)", 2D) = "white" {}
    }

    SubShader
    {
        Tags { "RenderType" = "Opaque" }
        LOD 200

        Pass
        {
        CGPROGRAM
            // Use shader model 3.0 target, to get nicer looking lighting
            #pragma target 3.0

            #include "UnityCG.cginc"

            #pragma vertex vert
            #pragma fragment frag
            #pragma geometry geom

            uniform sampler2D _MainTex;
            uniform float4 _MainTex_ST;

            struct Input
            {
                float2 uv_MainTex;
            };

            fixed4 _WireColor;
            fixed4 _AlbedoColor;

            uniform float _WireThickness;
            uniform float _WireSmoothness;

            struct appdata
            {
                float4 vertex : POSITION;
                float2 texcoord0 : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct v2g
            {
                float4 projSpaceVertex : SV_POSITION;
                float2 uv0 : TEXCOORD0;
                float4 worldSpacePosition : TEXCOORD1;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            struct g2f
            {
                float4 projSpaceVertex : SV_POSITION;
                float2 uv0 : TEXCOORD0;
                float4 worldSpacePosition : TEXCOORD1;
                float4 dist : TEXCOORD2;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            v2g vert(appdata v)
            {
                v2g o;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
                o.projSpaceVertex = UnityObjectToClipPos(v.vertex);
                o.worldSpacePosition = mul(unity_ObjectToWorld, v.vertex);
                o.uv0 = TRANSFORM_TEX(v.texcoord0, _MainTex);
                return o;
            }

            [maxvertexcount(3)]
            void geom(triangle v2g i[3], inout TriangleStream<g2f> triangleStream)
            {
                float2 p0 = i[0].projSpaceVertex.xy / i[0].projSpaceVertex.w;
                float2 p1 = i[1].projSpaceVertex.xy / i[1].projSpaceVertex.w;
                float2 p2 = i[2].projSpaceVertex.xy / i[2].projSpaceVertex.w;

                float2 edge0 = p2 - p1;
                float2 edge1 = p2 - p0;
                float2 edge2 = p1 - p0;

                float area = abs(edge1.x * edge2.y - edge1.y * edge2.x);
                float wireThickness = 800 - _WireThickness;

                g2f o;

                o.uv0 = i[0].uv0;
                o.worldSpacePosition = i[0].worldSpacePosition;
                o.projSpaceVertex = i[0].projSpaceVertex;
                o.dist.xyz = float3((area / length(edge0)), 0.0, 0.0) * o.projSpaceVertex.w * wireThickness;
                o.dist.w = 1.0 / o.projSpaceVertex.w;
                UNITY_TRANSFER_VERTEX_OUTPUT_STEREO(i[0], o);
                triangleStream.Append(o);

                o.uv0 = i[1].uv0;
                o.worldSpacePosition = i[1].worldSpacePosition;
                o.projSpaceVertex = i[1].projSpaceVertex;
                o.dist.xyz = float3(0.0, (area / length(edge1)), 0.0) * o.projSpaceVertex.w * wireThickness;
                o.dist.w = 1.0 / o.projSpaceVertex.w;
                UNITY_TRANSFER_VERTEX_OUTPUT_STEREO(i[1], o);
                triangleStream.Append(o);

                o.uv0 = i[2].uv0;
                o.worldSpacePosition = i[2].worldSpacePosition;
                o.projSpaceVertex = i[2].projSpaceVertex;
                o.dist.xyz = float3(0.0, 0.0, (area / length(edge2))) * o.projSpaceVertex.w * wireThickness;
                o.dist.w = 1.0 / o.projSpaceVertex.w;
                UNITY_TRANSFER_VERTEX_OUTPUT_STEREO(i[2], o);
                triangleStream.Append(o);
            }

            fixed4 frag(g2f i) : SV_Target
            {
                float minDistanceToEdge = min(i.dist[0], min(i.dist[1], i.dist[2])) * i.dist[3];

                float4 baseColor = _AlbedoColor * tex2D(_MainTex, i.uv0);

                // Early out if we know we are not on a line segment.
                if (minDistanceToEdge > 0.9)
                {
                    return fixed4(baseColor.rgb,0);
                }

                // Smooth our line out
                float t = exp2(_WireSmoothness * -1.0 * minDistanceToEdge * minDistanceToEdge);
                fixed4 finalColor = lerp(baseColor, _WireColor, t);
                finalColor.a = t;

                return finalColor;
            }
            ENDCG
        }
    }
FallBack "Diffuse"
}

</code>```

Body:
Since I had same, I wrote custom shader.
Code Listing :

Shader "DESS/WireframeShader"
{
    Properties
    {
        _WireColor("Edges Color", Color) = (0,0,0,1)
        _WireThickness("Edge Thickness", RANGE(0, 800)) = 100
        _WireSmoothness("Edge Smoothness", RANGE(0, 20)) = 3
        _AlbedoColor("Albedo Color", Color) = (1,1,1,1)
        _MainTex("Albedo (RGB)", 2D) = "white" {}
    }

    SubShader
    {
        Tags { "RenderType" = "Opaque" }
        LOD 200

        Pass
        {
        CGPROGRAM
            // Use shader model 3.0 target, to get nicer looking lighting
            #pragma target 3.0

            #include "UnityCG.cginc"

            #pragma vertex vert
            #pragma fragment frag
            #pragma geometry geom

            uniform sampler2D _MainTex;
            uniform float4 _MainTex_ST;

            struct Input
            {
                float2 uv_MainTex;
            };

            fixed4 _WireColor;
            fixed4 _AlbedoColor;

            uniform float _WireThickness;
            uniform float _WireSmoothness;

            struct appdata
            {
                float4 vertex : POSITION;
                float2 texcoord0 : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct v2g
            {
                float4 projSpaceVertex : SV_POSITION;
                float2 uv0 : TEXCOORD0;
                float4 worldSpacePosition : TEXCOORD1;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            struct g2f
            {
                float4 projSpaceVertex : SV_POSITION;
                float2 uv0 : TEXCOORD0;
                float4 worldSpacePosition : TEXCOORD1;
                float4 dist : TEXCOORD2;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            v2g vert(appdata v)
            {
                v2g o;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
                o.projSpaceVertex = UnityObjectToClipPos(v.vertex);
                o.worldSpacePosition = mul(unity_ObjectToWorld, v.vertex);
                o.uv0 = TRANSFORM_TEX(v.texcoord0, _MainTex);
                return o;
            }

            [maxvertexcount(3)]
            void geom(triangle v2g i[3], inout TriangleStream<g2f> triangleStream)
            {
                float2 p0 = i[0].projSpaceVertex.xy / i[0].projSpaceVertex.w;
                float2 p1 = i[1].projSpaceVertex.xy / i[1].projSpaceVertex.w;
                float2 p2 = i[2].projSpaceVertex.xy / i[2].projSpaceVertex.w;

                float2 edge0 = p2 - p1;
                float2 edge1 = p2 - p0;
                float2 edge2 = p1 - p0;

                float area = abs(edge1.x * edge2.y - edge1.y * edge2.x);
                float wireThickness = 800 - _WireThickness;

                g2f o;

                o.uv0 = i[0].uv0;
                o.worldSpacePosition = i[0].worldSpacePosition;
                o.projSpaceVertex = i[0].projSpaceVertex;
                o.dist.xyz = float3((area / length(edge0)), 0.0, 0.0) * o.projSpaceVertex.w * wireThickness;
                o.dist.w = 1.0 / o.projSpaceVertex.w;
                UNITY_TRANSFER_VERTEX_OUTPUT_STEREO(i[0], o);
                triangleStream.Append(o);

                o.uv0 = i[1].uv0;
                o.worldSpacePosition = i[1].worldSpacePosition;
                o.projSpaceVertex = i[1].projSpaceVertex;
                o.dist.xyz = float3(0.0, (area / length(edge1)), 0.0) * o.projSpaceVertex.w * wireThickness;
                o.dist.w = 1.0 / o.projSpaceVertex.w;
                UNITY_TRANSFER_VERTEX_OUTPUT_STEREO(i[1], o);
                triangleStream.Append(o);

                o.uv0 = i[2].uv0;
                o.worldSpacePosition = i[2].worldSpacePosition;
                o.projSpaceVertex = i[2].projSpaceVertex;
                o.dist.xyz = float3(0.0, 0.0, (area / length(edge2))) * o.projSpaceVertex.w * wireThickness;
                o.dist.w = 1.0 / o.projSpaceVertex.w;
                UNITY_TRANSFER_VERTEX_OUTPUT_STEREO(i[2], o);
                triangleStream.Append(o);
            }

            fixed4 frag(g2f i) : SV_Target
            {
                float minDistanceToEdge = min(i.dist[0], min(i.dist[1], i.dist[2])) * i.dist[3];

                float4 baseColor = _AlbedoColor * tex2D(_MainTex, i.uv0);

                // Early out if we know we are not on a line segment.
                if (minDistanceToEdge > 0.9)
                {
                    return fixed4(baseColor.rgb,0);
                }

                // Smooth our line out
                float t = exp2(_WireSmoothness * -1.0 * minDistanceToEdge * minDistanceToEdge);
                fixed4 finalColor = lerp(baseColor, _WireColor, t);
                finalColor.a = t;

                return finalColor;
            }
            ENDCG
        }
    }
FallBack "Diffuse"
}


问:
How to disable Redis Caching at run time if redis connection failed
We have rest api application. We use redis for API response caching and internal method caching. If redis connection then it is making our API down. We want to bypass the redis caching if that redis connection fails or any exception instead of making our API down.
There is a interface CacheErrorHandler but it handles the redis get set operation failures not redis connection problems. We are using Spring 4.1.2.</p>

答:
I had same problem, but, unfortunately, none of the above solutions work for me. I checked for the problem and found out that the executed command never timed out if there was no connection to Redis. So I start to study lettuce library for a solution. I solve the problem by rejecting the command when there is no connection:</p>

```<code>@Bean
public LettuceConnectionFactory lettuceConnectionFactory()
{
    final SocketOptions socketOptions = SocketOptions.builder().connectTimeout(Duration.ofSeconds(10)).build();
    ClientOptions clientOptions = ClientOptions.builder()
            .socketOptions(socketOptions)
            .autoReconnect(true)
            .disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
            .build();

    LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
            .commandTimeout(Duration.ofSeconds(10))
            .clientOptions(clientOptions).build();

    RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(this.host, this.port);
    return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);

}
</code>```

Body:
I had same problem, but, unfortunately, none of the above solutions work for me. I checked for the problem and found out that the executed command never timed out if there was no connection to Redis. So I start to study lettuce library for a solution. I solve the problem by rejecting the command when there is no connection:

@Bean
public LettuceConnectionFactory lettuceConnectionFactory()
{
    final SocketOptions socketOptions = SocketOptions.builder().connectTimeout(Duration.ofSeconds(10)).build();
    ClientOptions clientOptions = ClientOptions.builder()
            .socketOptions(socketOptions)
            .autoReconnect(true)
            .disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
            .build();

    LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
            .commandTimeout(Duration.ofSeconds(10))
            .clientOptions(clientOptions).build();

    RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(this.host, this.port);
    return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);

}


问:
JavasScript wait for web element to be visible and click it
I'm trying to automate some tasks with JavaScript. Website is being generated so I cannot use CSS selectors as they change with every website refresh. It is not shown in the example but it is possible to manipulate buttons with their text content (which CSS, sadly, cannot get).

I have figured out (thanks to StackOverflow) how to click web element by its Xpath but still don't know how to tell JS to wait until it is present.

Code for clicking element (working):

```<code>var xPathRes = document.evaluate ('//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
xPathRes.singleNodeValue.click();
</code>```

Attempt to wait for element to be present and then click it (not working):

```<code>var selector = "//*[@id='tsf']/div[2]/div/div[3]/center/input[1]";
var time = 500;
    if(document.evaluate (selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
        selector.singleNodeValue.click();
        return;
        }
    else {
        setTimeout(function() {
        waitForElementToDisplay(selector, time);
        }, time);
    }
</code>```

As you can see code in the example is Google.com search button.

I have always used Python Selenium to do such things but in this case I really cannot.

PS. I suck at JS as it is evident from posted code.

Thank you for trying to help!

EDIT:

Following @folo code I wrote something like this:

```<code>var element = '//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]';
(function checkIfElemExists() {
   if (!document.evaluate (element, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
     console.log('nope')
     window.requestAnimationFrame(checkIfElemExists);
   } else {
     console.log('okay i exist now! lets do something.')
   }
 })()
</code>```

The problem is that it always returns "Okay i exist now!). Even when i run it on a website that does not contain this element.

答:
If I understand you correctly you want to determine when an element starts to exist in the DOM?

If so you should use requestAnimationFrame

```<code> (function checkIfElemExists() {
   if (!document.querySelector('.some-element')) {
     window.requestAnimationFrame(checkIfElemExists);
   } else {
     console.log('okay i exist now! lets do something.')
   }
 })()
</code>```

whenever a new frame is requested in the browser it will check if the element exists, if it does it will stop and do whatever you want to do. its effective and clean.

Edit:

im not sure i understand why you can't use a css selector if you can use xpath, if you were to use a css selector this would be the one:

```<code>#tsf>div:nth-of-type(2)>div>div:nth-of-type(3)>center>input:nth-of-type(1)
</code>```

replace the ".some-element" selector with that.

Body:
I'm trying to automate some tasks with JavaScript. Website is being generated so I cannot use CSS selectors as they change with every website refresh. It is not shown in the example but it is possible to manipulate buttons with their text content (which CSS, sadly, cannot get).

I have figured out (thanks to StackOverflow) how to click web element by its Xpath but still don't know how to tell JS to wait until it is present.

Code for clicking element (working):

var xPathRes = document.evaluate ('//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
xPathRes.singleNodeValue.click();

Attempt to wait for element to be present and then click it (not working):

var selector = "//*[@id='tsf']/div[2]/div/div[3]/center/input[1]";
var time = 500;
    if(document.evaluate (selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
        selector.singleNodeValue.click();
        return;
        }
    else {
        setTimeout(function() {
        waitForElementToDisplay(selector, time);
        }, time);
    }

As you can see code in the example is Google.com search button.

I have always used Python Selenium to do such things but in this case I really cannot.

PS. I suck at JS as it is evident from posted code.

Thank you for trying to help!

EDIT:

Following @folo code I wrote something like this:

var element = '//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]';
(function checkIfElemExists() {
   if (!document.evaluate (element, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
     console.log('nope')
     window.requestAnimationFrame(checkIfElemExists);
   } else {
     console.log('okay i exist now! lets do something.')
   }
 })()

The problem is that it always returns "Okay i exist now!). Even when i run it on a website that does not contain this element.

Body:
If I understand you correctly you want to determine when an element starts to exist in the DOM?

If so you should use requestAnimationFrame

 (function checkIfElemExists() {
   if (!document.querySelector('.some-element')) {
     window.requestAnimationFrame(checkIfElemExists);
   } else {
     console.log('okay i exist now! lets do something.')
   }
 })()

whenever a new frame is requested in the browser it will check if the element exists, if it does it will stop and do whatever you want to do. its effective and clean.

Edit:

im not sure i understand why you can't use a css selector if you can use xpath, if you were to use a css selector this would be the one:

#tsf>div:nth-of-type(2)>div>div:nth-of-type(3)>center>input:nth-of-type(1)

replace the ".some-element" selector with that.


问:
How to implement google authentication in an Angular project?
I have to implement Google Authentication in an Angular project but I can't find an article that explains it properly.

I tried reading the documentation but it didn't really work for me.

Can someone recomend an article or provide a good explanation?

I would be very thankful.

答:
i used this article to start,
https://developers.google.com/identity/sign-in/web/sign-in

** most of the logic should be in the back-end side,

for example if you want to make some kind of authorization for a specific endpoint, the frontend should only send the code in the request and your back end should validate the key using a special private key he holds.

hope it helps


问:
How can I trigger a Python code automatically?
I have a code in Oracle which is optimized and create weekly data. The problem is I also want my Oracle code trigger Python to run and create data in Python and save. Is there any possibility to execute my Python code automatically?</p>

答: i use windows task planner with a .bat script to run my python code everyday.</p>