问:
DefaultIfEmpty - LINQ to SQL vs In Memory
For unit testing we use in memory collections to verify the logic of our LINQ queries. But, in the below scenario I'm seeing differences between the results from LINQ to SQL vs In Memory.

For this example we have three tables Customer, Order, Item. I would like the count of all items ordered by a customer. I would like to show customers who have not ordered any items as well. In SQL this would be an outer join. In LINQ to SQL I wrote this...

```<code>var itemCounts =
   from c in Customer
   from o in Order.Where(oo=>o.CustomerId==c.CustomerId).DefaultIfEmpty()
   from i in Item.Where(ii=>i.OrderId==o.OrderId).DefaultIfEmpty()
   group i by new { i.ItemId, c.CustomerId } into ig
   select new ItemCountResult {
     CustomerId = ig.Key.CustomerId,
     Count = ig.Count()
   };
</code>```

This works fine when we are going against the database. We get customers with and without orders along with counts. When we substitute in memory collections for unit testing we see an object reference not set exception. I've narrowed it down to the line "i.OrderId==o.OrderId" specifically o is null.

Based on how "DefaultIfEmpty" works, this is actually the behavior I would expect. DefaultIfEmpty returns a single element enumerable of null.

So how do I fix this code to work in both scenarios?

UPDATE:
While I was simplifying the problem I lost some important pieces of information. So let me restate the problem.

A Customer has 0-n Orders.
A Order has 1-n Items.
A Item has 1-n Order.

I need the list of Items along with the number of customers that ordered that item. If 0 customers ordered the item I want it to still be returned but with a count of 0.

The problem is the many-to-many between Order and Item which prevents me from using the join-into syntax.

I currently have something like this (hopefully without mistypes this time):

```<code>var counts =
  from i in Items
  from oi in OrderItems.Where(z=>z.ItemId==i.ItemId).DefaultIfEmpty()
  from o in Orders.Where(z=>z.OrderId==oi.OrderId).DefaultIfEmpty()
  from c in Customers.Where(z=>z.CustomerId==o.CustomerId).DefaultIfEmpty()
  group c by new { i.ItemId, c.CustomerId } into cg
  select new CountResult {
    CustomerId = cg.Key.CustomerId,
    Count = cg.Count()
  };
</code>```

答:
Your query is pooched to start with. This:

```<code>from ...
from o in Order.Where(oo=>o.CustomerId==c.CustomerId).DefaultIfEmpty()
from i in Item.Where(ii=>i.OrderId==o.OrderId).DefaultIfEmpty()
</code>```

... is trying to use o before it's really in scope. I'm surprised that works at all. It looks like you want:

```<code>from ...
from o in Order.Where(oo => oo.CustomerId == c.CustomerId).DefaultIfEmpty()
from i in Item.Where(ii => ii.OrderId == o.OrderId).DefaultIfEmpty()
</code>```

However, that still has the same problem - o will be null if there are no customers for c.CustomerId. The SQL translation may well not exhibit the same behaviour, but it's frankly a little odd to start with IMO.

Try this instead, assuming you have the right relationship set up:

```<code>from c in Customer
join i in Items on c.CustomerId equals i.Order.OrderId into items
select new { CustomerId = c.CustomerId, Count = items.Count() };
</code>```

Here's another alternative, back to using explicit joins:

```<code>from c in Customer
join oi in (from o in Orders
            join i in Items on o.OrderId equals i.OrderId
            select new { o, i })
on c.CustomerId equals oi.o.CustomerId into ordersForCustomer
select new { CustomerId = c.CustomerId, Count = ordersForCustomer.Count() };
</code>```

Body:
For unit testing we use in memory collections to verify the logic of our LINQ queries. But, in the below scenario I'm seeing differences between the results from LINQ to SQL vs In Memory.

For this example we have three tables Customer, Order, Item. I would like the count of all items ordered by a customer. I would like to show customers who have not ordered any items as well. In SQL this would be an outer join. In LINQ to SQL I wrote this...

var itemCounts =
   from c in Customer
   from o in Order.Where(oo=>o.CustomerId==c.CustomerId).DefaultIfEmpty()
   from i in Item.Where(ii=>i.OrderId==o.OrderId).DefaultIfEmpty()
   group i by new { i.ItemId, c.CustomerId } into ig
   select new ItemCountResult {
     CustomerId = ig.Key.CustomerId,
     Count = ig.Count()
   };

This works fine when we are going against the database. We get customers with and without orders along with counts. When we substitute in memory collections for unit testing we see an object reference not set exception. I've narrowed it down to the line "i.OrderId==o.OrderId" specifically o is null.

Based on how "DefaultIfEmpty" works, this is actually the behavior I would expect. DefaultIfEmpty returns a single element enumerable of null.

So how do I fix this code to work in both scenarios?

UPDATE:
While I was simplifying the problem I lost some important pieces of information. So let me restate the problem.

A Customer has 0-n Orders.
A Order has 1-n Items.
A Item has 1-n Order.

I need the list of Items along with the number of customers that ordered that item. If 0 customers ordered the item I want it to still be returned but with a count of 0.

The problem is the many-to-many between Order and Item which prevents me from using the join-into syntax.

I currently have something like this (hopefully without mistypes this time):

var counts =
  from i in Items
  from oi in OrderItems.Where(z=>z.ItemId==i.ItemId).DefaultIfEmpty()
  from o in Orders.Where(z=>z.OrderId==oi.OrderId).DefaultIfEmpty()
  from c in Customers.Where(z=>z.CustomerId==o.CustomerId).DefaultIfEmpty()
  group c by new { i.ItemId, c.CustomerId } into cg
  select new CountResult {
    CustomerId = cg.Key.CustomerId,
    Count = cg.Count()
  };

Body:
Your query is pooched to start with. This:

from ...
from o in Order.Where(oo=>o.CustomerId==c.CustomerId).DefaultIfEmpty()
from i in Item.Where(ii=>i.OrderId==o.OrderId).DefaultIfEmpty()

... is trying to use o before it's really in scope. I'm surprised that works at all. It looks like you want:

from ...
from o in Order.Where(oo => oo.CustomerId == c.CustomerId).DefaultIfEmpty()
from i in Item.Where(ii => ii.OrderId == o.OrderId).DefaultIfEmpty()

However, that still has the same problem - o will be null if there are no customers for c.CustomerId. The SQL translation may well not exhibit the same behaviour, but it's frankly a little odd to start with IMO.

Try this instead, assuming you have the right relationship set up:

from c in Customer
join i in Items on c.CustomerId equals i.Order.OrderId into items
select new { CustomerId = c.CustomerId, Count = items.Count() };

Here's another alternative, back to using explicit joins:

from c in Customer
join oi in (from o in Orders
            join i in Items on o.OrderId equals i.OrderId
            select new { o, i })
on c.CustomerId equals oi.o.CustomerId into ordersForCustomer
select new { CustomerId = c.CustomerId, Count = ordersForCustomer.Count() };


来源: stackexchange

问:
RichTextBox text causing error in Microsoft Visual Studio
I'm trying to make my program display text into a text box but when I paste the text it causes errors

```<code>richTextBox1.Text = "/give @p sign 1 0 {    BlockEntityTag: {        Text1: "{\"text\":\"BUY FOR\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/playsound ui.button.click master @a ~ ~ ~ 10 2\"}}",        Text3: "{\"text\":\"2           LVL\",\"color\":\"white\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/scoreboard players tag @p add SHOP2\"}}"    },    display: { Name: "XP SIGN"    }}";
</code>```

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1056  Unexpected character '\'    MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1513  } expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1513  } expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1010  Newline in constant MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1519  Invalid token '";' in class, struct, or interface member declaration    MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1022  Type or namespace definition, or end-of-file expected   MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

答:
As sticky _bit* has pointed out, you need to escape any quotes within your string.

i.e.

```<code>richTextBox1.Text =  "/give @p sign 1 0 {    BlockEntityTag: {        Text1: \"{\"text\":\"BUY FOR\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/playsound ui.button.click master @a ~ ~ ~ 10 2\"}}\",        Text3: \"{\"text\":\"2           LVL\",\"color\":\"white\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/scoreboard players tag @p add SHOP2\"}}\"    },    display: { Name: \"XP SIGN\"    }}";
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make my program display text into a text box but when I paste the text it causes errors

richTextBox1.Text = "/give @p sign 1 0 {    BlockEntityTag: {        Text1: "{\"text\":\"BUY FOR\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/playsound ui.button.click master @a ~ ~ ~ 10 2\"}}",        Text3: "{\"text\":\"2           LVL\",\"color\":\"white\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/scoreboard players tag @p add SHOP2\"}}"    },    display: { Name: "XP SIGN"    }}";

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1056  Unexpected character '\'    MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1513  } expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1513  } expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1010  Newline in constant MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1519  Invalid token '";' in class, struct, or interface member declaration    MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1022  Type or namespace definition, or end-of-file expected   MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Body:
As sticky _bit* has pointed out, you need to escape any quotes within your string.

i.e.

richTextBox1.Text =  "/give @p sign 1 0 {    BlockEntityTag: {        Text1: \"{\"text\":\"BUY FOR\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/playsound ui.button.click master @a ~ ~ ~ 10 2\"}}\",        Text3: \"{\"text\":\"2           LVL\",\"color\":\"white\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/scoreboard players tag @p add SHOP2\"}}\"    },    display: { Name: \"XP SIGN\"    }}";


问:
Illogical "Bad substitution" in singularity

Problem

One of the configuration scripts from a package in my singularity container contains this perfectly reasonable (to me) bit of bash to trim a trailing / off a path;

```<code>if [ "${MY_DIR_PATH: -1}" = "/" ]; then
    MY_DIR_PATH="${MY_DIR_PATH%?}"
fi
</code>```

It works fine natively on my machine, but when run from the %post section of a singularity container it fails with Bad substitution.
What's going wrong and what is the correct workaround?

Minimal working example

Save the text below as badSubs.def then try; sudo singularity build badSubs.sif badSubs.def.

```<code>BootStrap: docker
From: ubuntu:18.04

# what is done when the container is built
%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    # start
    #echo "${GREEN}~~~ Give the user permission and control ~~~ ${NOCOLOUR}"
    #umask 000

    echo "${GREEN}~~~ this should work fine! ~~~ ${NOCOLOUR}"
    MYSCRIPT=$SINGULAITY_ROOTFS/confuzzel
    touch $MYSCRIPT
    chmod u+x $MYSCRIPT
    echo '#! /bin/bash' >> $MYSCRIPT
    echo 'PATHY="/what/a/path/"' >> $MYSCRIPT
    echo 'if [ "${PATHY: -1}" = "/" ]; then ' >> $MYSCRIPT
    echo '    echo yay!' >> $MYSCRIPT
    echo '    PATHY="${PATHY%?}"' >> $MYSCRIPT
    echo 'fi' >> $MYSCRIPT
    echo 'echo $PATHY' >> $MYSCRIPT
    cat $MYSCRIPT
    ./confuzzel

# metadata
%labels
    Author ClumsyCat
    Version v1.0

%help
    to build me
    > sudo singularity build badSubs.sif badSubs.def
    to run me do
    > singularity run badSubs.sif

</code>```

答:
I'm not familiar with singularity, so this is a guess, but I think your script is being run by a shell other than bash (maybe dash?). ${var: number} is a nonstandard extension to the variable expansion syntax; bash and a few other shells support it, others (like dash) don't.

If the only reason for the test is to find out if the variable ends in "/" so you can remove it if it's there, don't bother. This is POSIX-standard syntax that'll remove a "/" from the end of the variable if the variable ends in "/":

```<code>MY_DIR_PATH=${MY_DIR_PATH%/}
</code>```

If you really do need to test, use this instead:

```<code>if [ "${MY_DIR_PATH%/}" != "${MY_DIR_PATH}" ]; then
</code>```

Explanation: This compares the variable with "/" remove from the end to the original value; if they're different, there must've been a "/" at the end.

Body:
Problem

One of the configuration scripts from a package in my singularity container contains this perfectly reasonable (to me) bit of bash to trim a trailing / off a path;

if [ "${MY_DIR_PATH: -1}" = "/" ]; then
    MY_DIR_PATH="${MY_DIR_PATH%?}"
fi

It works fine natively on my machine, but when run from the %post section of a singularity container it fails with Bad substitution.
What's going wrong and what is the correct workaround?

Minimal working example

Save the text below as badSubs.def then try; sudo singularity build badSubs.sif badSubs.def.

BootStrap: docker
From: ubuntu:18.04

# what is done when the container is built
%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    # start
    #echo "${GREEN}~~~ Give the user permission and control ~~~ ${NOCOLOUR}"
    #umask 000

    echo "${GREEN}~~~ this should work fine! ~~~ ${NOCOLOUR}"
    MYSCRIPT=$SINGULAITY_ROOTFS/confuzzel
    touch $MYSCRIPT
    chmod u+x $MYSCRIPT
    echo '#! /bin/bash' >> $MYSCRIPT
    echo 'PATHY="/what/a/path/"' >> $MYSCRIPT
    echo 'if [ "${PATHY: -1}" = "/" ]; then ' >> $MYSCRIPT
    echo '    echo yay!' >> $MYSCRIPT
    echo '    PATHY="${PATHY%?}"' >> $MYSCRIPT
    echo 'fi' >> $MYSCRIPT
    echo 'echo $PATHY' >> $MYSCRIPT
    cat $MYSCRIPT
    ./confuzzel

# metadata
%labels
    Author ClumsyCat
    Version v1.0

%help
    to build me
    > sudo singularity build badSubs.sif badSubs.def
    to run me do
    > singularity run badSubs.sif

Body:
I'm not familiar with singularity, so this is a guess, but I think your script is being run by a shell other than bash (maybe dash?). ${var: number} is a nonstandard extension to the variable expansion syntax; bash and a few other shells support it, others (like dash) don't.

If the only reason for the test is to find out if the variable ends in "/" so you can remove it if it's there, don't bother. This is POSIX-standard syntax that'll remove a "/" from the end of the variable if the variable ends in "/":

MY_DIR_PATH=${MY_DIR_PATH%/}

If you really do need to test, use this instead:

if [ "${MY_DIR_PATH%/}" != "${MY_DIR_PATH}" ]; then

Explanation: This compares the variable with "/" remove from the end to the original value; if they're different, there must've been a "/" at the end.


问:
How to spread the inner array elements of an array?
I am trying to spread the inner array elements of an array but couldn't figure it out how it works.

Input:

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

Output:

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

How do I convert the first array into 2nd one?

答:
Use the flat function:

var a = [1,2,[3,4],[5,6]] ;
a = a.flat();
console.log(a);```

Body:
I am trying to spread the inner array elements of an array but couldn't figure it out how it works.

Input:

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

Output:

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

How do I convert the first array into 2nd one?


问:
What is the best way to fetch Tree/Hierarchical structure data from Oracle
I want to fetch Hierarchical/Tree data something like below from a Table which has following definiton.

```<code>Tree Table:
"""""""""""
Id   |ParentId
"""""""""""
Work1|null
Work2|Work1
Work3|Work2
...
</code>```

Required Query result Data (no need to be tabbed)- If I Pick 'Work1' I should complete Ids which are under its root something like below. If I pick 'Work2' then also I should complete Ids above and below its root.

```<code>> Work1
----------
>   Work2
----------
>     Work3
---------
</code>```

I used below query but it is giving me duplicate records.

```<code>select Id from TreeTable start with Id in ('Work1','Work2') connect by nocycle Parentid=prior Id or Id = prior Parentid
</code>```

Note: I want to get the data within a SINGLE QUERY (optimized) way

Thanks and Regards,
PV.

答:
```<code>SELECT  id
FROM    q
START WITH
        id IN ('Work1', 'Work2')
CONNECT BY
        parent = PRIOR id
        AND id NOT IN ('Work1', 'Work2')
</code>```

This condition:

```<code>AND id NOT IN ('Work1', 'Work2')
</code>```

will cut off the branches already selected with START WITH.

ContentLicense: CC BY-SA 3.0

Body:
I want to fetch Hierarchical/Tree data something like below from a Table which has following definiton.

Tree Table:
"""""""""""
Id   |ParentId
"""""""""""
Work1|null
Work2|Work1
Work3|Work2
...

Required Query result Data (no need to be tabbed)- If I Pick 'Work1' I should complete Ids which are under its root something like below. If I pick 'Work2' then also I should complete Ids above and below its root.

> Work1
----------
>   Work2
----------
>     Work3
---------

I used below query but it is giving me duplicate records.

select Id from TreeTable start with Id in ('Work1','Work2') connect by nocycle Parentid=prior Id or Id = prior Parentid

Note: I want to get the data within a SINGLE QUERY (optimized) way

Thanks and Regards,
PV.

Body:
SELECT  id
FROM    q
START WITH
        id IN ('Work1', 'Work2')
CONNECT BY
        parent = PRIOR id
        AND id NOT IN ('Work1', 'Work2')

This condition:

AND id NOT IN ('Work1', 'Work2')

will cut off the branches already selected with START WITH.


问:
Find the missing and duplicate elements in an array in linear time and constant space
You’re given an array of N 64 bit integers. N may be very large. You know that every integer 1..N appears once in the array, except there is one integer missing and one integer duplicated.

Write a linear time algorithm to find the missing and duplicated numbers. Further, your algorithm should run in small constant space and leave the array untouched.

Source: http://maxschireson.com/2011/04/23/want-a-job-working-on-mongodb-your-first-online-interview-is-in-this-post/

答:
```<code>    long long int len = A.size();
    long long int sumOfN = (len * (len+1) ) /2, sumOfNsq = (len * (len +1) *(2*len +1) )/6;
    long long int missingNumber1=0, missingNumber2=0;

    for(int i=0;i<A.size(); i++){
       sumOfN -= (long long int)A[i];
       sumOfNsq -= (long long int)A[i]*(long long int)A[i];
    }

    missingno = (sumOfN + sumOfNsq/sumOfN)/2;
    reaptingNO = missingNumber1 - sumOfN;
</code>```


问:
Getting Last Modified by Name of xlsx file
I have an excel file that gets modified by a group of people and we need to keep track of when the file was last modified and by whom

I was able to retrieve the file properties through .properties but trying to figure out how to isolate the lastModifiedby and insert its value in to a column

```<code>from openpyxl import load_workbook
wb = load_workbook('Rec1.xlsx')
wb.properties.lastModifiedBy
</code>```

It gets me the information I need but I am stumped on how to create a new column "lastmodifiedby" with the information provided in properties

答:
From the documentation: https://openpyxl.readthedocs.io/en/stable/usage.html#write-a-workbook

Perhaps something like this?

```<code>ws1 = wb.active
ws1.cell(column=1, row=1, value=wb.properties.lastModifiedBy)
wb.save(filename='Rec1.xlsx')
</code>```

Body:
I have an excel file that gets modified by a group of people and we need to keep track of when the file was last modified and by whom

I was able to retrieve the file properties through .properties but trying to figure out how to isolate the lastModifiedby and insert its value in to a column

from openpyxl import load_workbook
wb = load_workbook('Rec1.xlsx')
wb.properties.lastModifiedBy

It gets me the information I need but I am stumped on how to create a new column "lastmodifiedby" with the information provided in properties

Body:
From the documentation: https://openpyxl.readthedocs.io/en/stable/usage.html#write-a-workbook

Perhaps something like this?

ws1 = wb.active
ws1.cell(column=1, row=1, value=wb.properties.lastModifiedBy)
wb.save(filename='Rec1.xlsx')


问:
macOS scan/detect screen in real time
There are some apps which can scan the screen and detect things in real time. For example, the macOS preinstalled app "Digital Color Meter". I can move the cursor and the app detects immediately which color is in the area around my cursor. So my question is, how can I do things like this? How can I "scan" the screen and detect objects or colors in a selected area in real time? I can't find a solution.</p>

答:
Digital Color Meter only captures a small square of the screen. If that's all you need, try CGDisplayCreateImageForRect and see if it's fast enough.

If that's not fast enough, look at the CGDisplayStream functions, starting with CGDisplayStreamCreate or CGDisplayStreamCreateWithDispatchQueue. These functions are significantly more complicated than CGDisplayCreateImageForRect and you'll have to learn about IOSurfaceRef to get at the pixel data from a CGDisplayStream.

Title: macOS scan/detect screen in real time


问:
jQuery Autocalculate based on Radio Button Click
I am stuck on the last part of this jQuery auto-calculation script that I am working on. I want to automatically re-calculate the subtotal values based on a "radio button click". The calculation will automatically add a 10% discount when the radio button "special_(n)" gets clicked.

View the script in action here: http://www.ppleasysavings.com/calcscript/index.html
(tip): enter a value into the 'qty' field, and the totals will auto calculate.

Here is the HTML 'part'

```<code>Yes<input name="special_1" type="radio" value="1" />
No<input name="special_1" type="radio" value="0" />
<input name="total_item_1" type="text" id="total_item_1" style="text-align:right;" value="$0.00" size="7" maxlength="8" readonly="readonly">

Yes<input name="special_2" type="radio" value="1" />
No<input name="special_2" type="radio" value="0" />
<input name="total_item_2" type="text" id="total_item_2" style="text-align:right;" value="$0.00" size="7" maxlength="8" readonly="readonly">
</code>```

Here is the jQuery

As you can see, I have already added a bit of code to include the special "radio button", and have started on the equation => qty * price * special. Now, I need to modify it so that it works.

```<code>var bIsFirebugReady = (!!window.console && !!window.console.log);
$(document).ready(
    function (){
        // update the plug-in version
        $("#idPluginVersion").text($.Calculation.version);

    // bind the recalc function to the quantity fields
        $("input[name^=qty_item_]").bind("keyup", recalc);
        $("input[name^=special_]").bind("checked", recalc);
        // run the calculation function now
        recalc();
    }
);
function recalc(){
    $("[id^=total_item]").calc(
        // the equation to use for the calculation
        "qty * price * special",
        // define the variables used in the equation, these can be a jQuery object
        {
            qty: $("input[name^=qty_item_]"),
            price: $("[id^=price_item_]"),
            special: $("input[name^=special_]")
        },
        // define the formatting callback, the results of the calculation are passed to this function
        function (s){
            // return the number as a dollar amount
            return "$" + s.toFixed(2);
        },
        // define the finish callback, this runs after the calculation has been complete
        function ($this){
            // sum the total of the $("[id^=total_item]") selector
            var sum = $this.sum();

            $("#grandTotal").val(
                // round the results to 2 digits
                "$" + sum.toFixed(2)
            );
        }
    );
}
</code>```

答:
```<code>$("input[name^=special_]").change(recalc);
</code>```

In addition, it seems that your 'special' input item has values of 0 and 1, instead of 0 or .9 (for the 10% off).  Set the value of the radio to those values and then use it in your calculation.

EDIT: I kept looking at it and I've decided I'm not a fan of your use of the calculate plugin.  Seems to me that it could be accomplished much cleaner with normal functionality.  You further complicate your looping and actual calculation like this....

Body:
I am stuck on the last part of this jQuery auto-calculation script that I am working on. I want to automatically re-calculate the subtotal values based on a "radio button click". The calculation will automatically add a 10% discount when the radio button "special_(n)" gets clicked.

View the script in action here: http://www.ppleasysavings.com/calcscript/index.html
(tip): enter a value into the 'qty' field, and the totals will auto calculate.

Here is the HTML 'part'

Yes<input name="special_1" type="radio" value="1" />
No<input name="special_1" type="radio" value="0" />
<input name="total_item_1" type="text" id="total_item_1" style="text-align:right;" value="$0.00" size="7" maxlength="8" readonly="readonly">

Yes<input name="special_2" type="radio" value="1" />
No<input name="special_2" type="radio" value="0" />
<input name="total_item_2" type="text" id="total_item_2" style="text-align:right;" value="$0.00" size="7" maxlength="8" readonly="readonly">

Here is the jQuery

As you can see, I have already added a bit of code to include the special "radio button", and have started on the equation => qty * price * special. Now, I need to modify it so that it works.

var bIsFirebugReady = (!!window.console && !!window.console.log);
$(document).ready(
    function (){
        // update the plug-in version
        $("#idPluginVersion").text($.Calculation.version);

    // bind the recalc function to the quantity fields
        $("input[name^=qty_item_]").bind("keyup", recalc);
        $("input[name^=special_]").bind("checked", recalc);
        // run the calculation function now
        recalc();
    }
);
function recalc(){
    $("[id^=total_item]").calc(
        // the equation to use for the calculation
        "qty * price * special",
        // define the variables used in the equation, these can be a jQuery object
        {
            qty: $("input[name^=qty_item_]"),
            price: $("[id^=price_item_]"),
            special: $("input[name^=special_]")
        },
        // define the formatting callback, the results of the calculation are passed to this function
        function (s){
            // return the number as a dollar amount
            return "$" + s.toFixed(2);
        },
        // define the finish callback, this runs after the calculation has been complete
        function ($this){
            // sum the total of the $("[id^=total_item]") selector
            var sum = $this.sum();

            $("#grandTotal").val(
                // round the results to 2 digits
                "$" + sum.toFixed(2)
            );
        }
    );
}

Body:
$("input[name^=special_]").change(recalc);

In addition, it seems that your 'special' input item has values of 0 and 1, instead of 0 or .9 (for the 10% off).  Set the value of the radio to those values and then use it in your calculation.

EDIT: I kept looking at it and I've decided I'm not a fan of your use of the calculate plugin.  Seems to me that it could be accomplished much cleaner with normal functionality.  You further complicate your looping and actual calculation like this....


问:
ggplot2 alternatives to fill in barplots, occurence of factor in multiple rows
I'm pretty new to R and I have a problem with plotting a barplot out of my data which looks like this:

```<code>condition answer
2    H
1    H
8    H
5    W
4    M
7    H
9    H
10   H
6    H
3    W
</code>```

The data consists of 100 rows with the conditions 1 to 10, each randomly generated 10 times (10 times condition 1, 10 times condition 8,...). Each of the conditions  also has a answer which could be H for Hit, M for Miss or W for wrong.

I want to plot the number of Hits for each condition in a barplot (for example 8 Hits out of 10 for condition 1,...) for that I tried to do the following in ggplot2

```<code>ggplot(data=test, aes(x=test$condition, fill=answer=="H"))+
  geom_bar()+labs(x="Conditions", y="Hitrate")+
  coord_cartesian(xlim = c(1:10), ylim = c(0:10))+
  scale_x_continuous(breaks=seq(1,10,1))
</code>```

And it looked like this:

This actually exactly what I need except for the red color which covers everything. You can see that conditions 3 to 5 have no blue bar, because there are no hits for these conditions.

Is there any way to get rid of this red color and to maybe count the amount of hits for the different conditions? -> I tried the count function of dplyr but it only showed me the amount of H when there where some for this particular condition. 3-5 where just "ignored" by count, there wasn't even a 0 in the output.-> but I'd still need those numbers for the plot

I'm sorry for this particular long post but I'm really at the end of knowledge considering this. I'd be open for suggestions or alternatives! Thanks in advance!

答:
Another option is to pick your fill colors explicitly and make FALSE transparent by using scale_fill_manual. Since FALSE comes alphabetically first, the first value to specify is FALSE, the second TRUE.

```<code>ggplot(data=test, aes(x=condition, fill=answer=="H"))+
  geom_bar()+labs(x="Conditions", y="Hitrate")+
  coord_cartesian(xlim = c(1:10), ylim = c(0:10))+
  scale_x_continuous(breaks=seq(1,10,1)) +
  scale_fill_manual(values = c(alpha("red", 0), "cadetblue")) +
  guides(fill = F)
</code>```

Body:
I'm pretty new to R and I have a problem with plotting a barplot out of my data which looks like this:

condition answer
2    H
1    H
8    H
5    W
4    M
7    H
9    H
10   H
6    H
3    W

The data consists of 100 rows with the conditions 1 to 10, each randomly generated 10 times (10 times condition 1, 10 times condition 8,...). Each of the conditions  also has a answer which could be H for Hit, M for Miss or W for wrong.

I want to plot the number of Hits for each condition in a barplot (for example 8 Hits out of 10 for condition 1,...) for that I tried to do the following in ggplot2

ggplot(data=test, aes(x=test$condition, fill=answer=="H"))+
  geom_bar()+labs(x="Conditions", y="Hitrate")+
  coord_cartesian(xlim = c(1:10), ylim = c(0:10))+
  scale_x_continuous(breaks=seq(1,10,1))

And it looked like this:

This actually exactly what I need except for the red color which covers everything. You can see that conditions 3 to 5 have no blue bar, because there are no hits for these conditions.

Is there any way to get rid of this red color and to maybe count the amount of hits for the different conditions? -> I tried the count function of dplyr but it only showed me the amount of H when there where some for this particular condition. 3-5 where just "ignored" by count, there wasn't even a 0 in the output.-> but I'd still need those numbers for the plot

I'm sorry for this particular long post but I'm really at the end of knowledge considering this. I'd be open for suggestions or alternatives! Thanks in advance!

Body:
Another option is to pick your fill colors explicitly and make FALSE transparent by using scale_fill_manual. Since FALSE comes alphabetically first, the first value to specify is FALSE, the second TRUE.

ggplot(data=test, aes(x=condition, fill=answer=="H"))+
  geom_bar()+labs(x="Conditions", y="Hitrate")+
  coord_cartesian(xlim = c(1:10), ylim = c(0:10))+
  scale_x_continuous(breaks=seq(1,10,1)) +
  scale_fill_manual(values = c(alpha("red", 0), "cadetblue")) +
  guides(fill = F)


问:
"Error: Cannot fit requested classes in a single dex file (# methods: 66653 > 65536)" when generating a signed apk
I am trying to generate a signed apk so I can export my app to the Google Play store. However I keep getting the same error. Is there anything to fix this.

```<code>apply plugin: 'com.android.application'

    android {
        compileSdkVersion 28
        defaultConfig {
            applicationId "com.example.sean.monacoball"
            minSdkVersion 15
            targetSdkVersion 28
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner
    "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'),
    'proguard-rules.pro'
            }
        }
    }

    dependencies {
        implementation fileTree(include: ['*.jar'], dir: 'libs')
        implementation 'com.android.support:appcompat-v7:12.0.1'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.android.gms:play-services:12.0.1'
    }
}
</code>```

Error in depth :

答:
As per the Google Play services setup guide:

Note: Don't use the combined play-services target. It brings in dozens of libraries, bloating your application. Instead, specify only the specific Google Play services APIs your app uses.

As you're using com.google.android.gms:play-services:12.0.1, you're pulling in every Google Play services library. You should switch to only using the libraries you actually use. This will almost certainly put you under the 64k method limit of a single dex file.

Body:
I am trying to generate a signed apk so I can export my app to the Google Play store. However I keep getting the same error. Is there anything to fix this.

apply plugin: 'com.android.application'

    android {
        compileSdkVersion 28
        defaultConfig {
            applicationId "com.example.sean.monacoball"
            minSdkVersion 15
            targetSdkVersion 28
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner
    "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'),
    'proguard-rules.pro'
            }
        }
    }

    dependencies {
        implementation fileTree(include: ['*.jar'], dir: 'libs')
        implementation 'com.android.support:appcompat-v7:12.0.1'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.android.gms:play-services:12.0.1'
    }
}

Error in depth :


问:
Nuxt: Unexpected token <
<img src="https://i.stack.imgur.com/MbM9f.png" alt="Nuxt: Unexpected token < ">

I am working on a nuxt project, and I'm trying to build a map component using google maps and the plugin https://www.npmjs.com/package/vue2-google-maps. I have installed the plugin using npm

In my index.html page I have a normally working page that looks like:

```<code><template>
   <div>

<br>
<br>
       <Card/>
<br>
<br>
<br>
<br>
       <!-- <Googlemap/> -->
       <Panel/>
       <Four/>
       </div>
</template>

<script>

import Panel from '~/components/panel.vue'
import Card from '~/components/detailCard.vue'
// import GoogleMap from '~/components/googleMap.vue'

export default {

  components: {

    Panel,
    Card,
//     GoogleMap
  }

}
</script>
</code>```

When I Uncomment the 3 lines with Googlemap in them I get the error in the screenshot .

The Googlemap component is:

```<code><template>
  <GmapMap
  :center="{lat:10, lng:10}"
  :zoom="7"
  map-type-id="terrain"
  style="width: 500px; height: 300px"
>
  <GmapMarker
    :key="index"
    v-for="(m, index) in markers"
    :position="m.position"
    :clickable="true"
    :draggable="true"
    @click="center=m.position"
  />
</GmapMap>

</template>

<script>
import Vue from "vue";
import * as VueGoogleMaps from "vue2-google-maps";

Vue.use(VueGoogleMaps, {
  load: {
    key: "MYTOKEN",
    libraries: "places"
  }
});

export default {

}

</script>

<style>

</style>
</code>```

What am I doing wrong?

edit:

答:
Most likely you are missed transpile

https://github.com/xkjyeah/vue-google-maps/blob/0985d475496083f2459db2960ba8f9317aab50ef/README.md#nuxtjs-config

```<code>transpile: [/^vue2-google-maps($|\/)/]
</code>```

Title: Nuxt: Unexpected token <

Body:
<img src="https://i.stack.imgur.com/MbM9f.png" alt="Nuxt: Unexpected token < ">

I am working on a nuxt project, and I'm trying to build a map component using google maps and the plugin https://www.npmjs.com/package/vue2-google-maps. I have installed the plugin using npm

In my index.html page I have a normally working page that looks like:

<template>

       <Card/>

       <Panel/>
       <Four/>

</template>

When I Uncomment the 3 lines with Googlemap in them I get the error in the screenshot .

The Googlemap component is:

<template>
  <GmapMap
  :center="{lat:10, lng:10}"
  :zoom="7"
  map-type-id="terrain"
  style="width: 500px; height: 300px"
>
  <GmapMarker
    :key="index"
    v-for="(m, index) in markers"
    :position="m.position"
    :clickable="true"
    :draggable="true"
    @click="center=m.position"
  />
</GmapMap>

</template>

What am I doing wrong?

edit:

Body:
Most likely you are missed transpile

https://github.com/xkjyeah/vue-google-maps/blob/0985d475496083f2459db2960ba8f9317aab50ef/README.md#nuxtjs-config

transpile: [/^vue2-google-maps($|\/)/]


问:
powershell : changing the culture of current session
I am using powershell on windows vista.
How do I change the culture of current session?
My computer's culture is tr-TR so I am getting the error messages on Turkish. I would like to change to EN?

any chance?

答:
As the accepted solution by @manojlds actually doesn't work (PS 5.1 on Windows 10) here what works for me (found on github):

$culture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-US")
$assembly = [System.Reflection.Assembly]::Load("System.Management.Automation")
$type = $assembly.GetType("Microsoft.PowerShell.NativeCultureResolver")
$field = $type.GetField("m_uiCulture", [Reflection.BindingFlags]::NonPublic -bor [Reflection.BindingFlags]::Static)
$field.SetValue($null, $culture)
```


问:
It takes a long time to loop over 1000 entries from my database in Laravel
I am setting up an api end point that is responsible for getting movies from my database. I have a many to many relationship with genre. They are connected with a pivot table. I am trying to group all the movies by their genre before I send it over the response. Chrome is showing that it is taking 7+s TTFB (Time To First Byte). I need to know where the slow down is happening. I have also tested the endpoint with Postman and showing the same results. I don't know if I'm doing something wrong with the relationships, looping over the database, getting the data.

I am using Laradock to provide my Mysql, PHP, NGINX. I have tried to break out of the loop so that each genre group only can have 10 movies with in them. Doing this sped up my time from 20+s -> 7+s.

There are:
11 genres
1300 movies
3205 genre_movie

Example of the database
movie:

```<code> |id|name|...|
 |1 |mov1|...|
 |2 |mov2|...|
 |3 |mov3|...|
 |4 |mov4|...|
</code>```

genre:

```<code>|id|genre   |...|
|1 |action  |...|
|2 |drama   |...|
|3 |thriller|...|
|4 |cartoon |...|
</code>```

pivot: genre_movie

```<code>|movie_id|genre_id|
|1       |1       |
|1       |2       |
|2       |2       |
|3       |4       |
</code>```

Here is my Relations
Genre:

```<code>    public function movie(){
        return $this->belongsToMany('App\Movie');
    }

</code>```

Movie:

```<code>    public function genre(){
        return $this->belongsToMany('App\Genre');
    }

</code>```

Here is my migrations
movies:

```<code>    public function up()
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->string('title', 100);
            $table->text('synopsis');
            $table->integer('released_year');
            $table->string('imdb_url', 100);
            $table->string('s3_location', 100);
            $table->string('poster_location', 100);
            $table->boolean('isRestricted');
            $table->timestamps();
        });
    }

</code>```

genres:

```<code>    public function up()
    {
        Schema::create('genres', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->string('genre');
            $table->longText('description');
        });
    }

</code>```

genre_movie:

```<code>    public function up()
    {
        Schema::create('genre_movie', function (Blueprint $table) {
            $table->bigInteger('genre_id')->unsigned();
            $table->foreign('genre_id')->references('id')->on('genres');

            $table->bigInteger('movie_id')->unsigned();
            $table->foreign('movie_id')->references('id')->on('movies');
        });

</code>```

Here is how I'm seeding my Data:
Movie Factory

```<code>$factory->define(App\Movie::class, function (Faker $faker) {
    $faker->addProvider(new Image($faker));
    $faker->addProvider(new Base($faker));
    return [
        //
        'title' => $faker->name,
        'synopsis' => $faker->paragraph,
        'poster_location' => $faker->imageUrl($width=680, $height=680),
        'imdb_url' => 'https://www.imdb.com/title/tt5884052/',
        's3_location' => 'movie.mp4',
        'released_year' => $faker->numberBetween($min=1900, $max=1960),
        'isRestricted' => $faker->numberBetween($min=0, $max=1)
    ];
});

</code>```

GenreTable Seeder

```<code>    public function run()
    {
        //

        $genres = ['action', 'adventure', 'comedy', 'crime','drama','fantasy','historical','horror','romance','science fiction','thriller'];
        $seeds = [];
        foreach($genres as $genre){
            array_push($seeds,[
                'genre' => $genre,
                'description' => Str::random(150)
            ]);

        }
        DB::table('genres')->insert($seeds);

    }

</code>```

MovieTable Seeder

```<code>    public function run()
    {
        //
        $this->call([GenreSeeder::class]);
        factory(App\Movie::class, 1300)->create();

        $genres = App\Genre::all();

        App\Movie::all()->each(function ($movie) use ($genres) {
            $movie->genre()->attach(
                $genres->random(rand(1,4))->pluck('id')->toArray()
            );
        });

    }

</code>```

Api Route

```<code>    Route::get('movies/filteredByGenre', 'MovieController@filteredByGenre');

</code>```

MovieController@filteredByGenre

```<code>    public function filteredByGenre(Request $request){

        $movies = Movie::with('genre:genre')->get();
        $sizeofMovies = count($movies);
        $formatedMovie = [];

        $count = 0;
        for($x = 0; $x < $sizeofMovies; $x++){
            $sizeofGenre = count($movies[$x]->genre);
            for($y = 0; $y < $sizeofGenre; $y++){
                $genre = $movies[$x]->genre[$y];
                try{
                    if(isset($formatedMovie[$genre['genre']])){
                        if(sizeof($formatedMovie[$genre['genre']]) > 10){
                            break;
                        }
                        $formatedMovie[$genre['genre']][] = $movies[$x];
                    }else{
                        $formatedMovie[$genre['genre']][] = $movies[$x];
                    }
                } catch(ErrorException $e) {
                    $formatedMovie[$genre['genre']][] = $movies[$x];
                }

            }
        }
        $response = ['success' => true, 'data' => $formatedMovie ];
        return response()->json($response, 201);
    }

</code>```

How I'm receiving the data in the front-end

```<code>    componentDidMount() {
        var url = '/api/movies/filteredByGenre';
        axios
            .get(url)
            .then(response => {
                return response.data;
            })
            .then(json => {
                console.log(json);
                this.setState({ frontPageMovies: json.data });
            });
    }

</code>```

Commands to start my sever and seed the code

```<code>docker-compose up -d nginx mysql phpmyadmin workspace
php artisan db:seed --class=MoviesTableSeeder
</code>```

I expect movies sorted by their genre and the time it takes is no more than 1-3s to retrieve the data.

答:
If none of your tables are indexed, I'd start there.  You can often get a big performance boost just by adding indexes and/or primary keys on your primary columns (The IDs in this case).  You can think of them a bit like the index of a book ... sure you could scan every single page but its a lot faster if you have a map of where everything is.

```<code>Schema::create('movies', function (Blueprint $table) {
    $table->bigIncrements('id')->primary();
    ... or ...
    $table->index(['id']);
});
</code>```

I'd also suggest installing or enabling the Laravel Debug Bar from https://github.com/barryvdh/laravel-debugbar.  This can show you whats happening in your  application behind the scenes, including each and every database query that is made and how long those took to complete.  Sort of like TTFB in Dev Tools but for the stuff Chrome can't see.

One final option I use a lot, is to have Laravel generate my database query but not execute it ...

```<code>$movies = Movie::with('genre:genre')->toSql();
</code>```

... and then executing it directly in my database (phpMyAdmin or your preferred console) If it's fast there, I know its my php code.  Otherwise I know I need to look at other DB optimizations.

Body:
I am setting up an api end point that is responsible for getting movies from my database. I have a many to many relationship with genre. They are connected with a pivot table. I am trying to group all the movies by their genre before I send it over the response. Chrome is showing that it is taking 7+s TTFB (Time To First Byte). I need to know where the slow down is happening. I have also tested the endpoint with Postman and showing the same results. I don't know if I'm doing something wrong with the relationships, looping over the database, getting the data.

I am using Laradock to provide my Mysql, PHP, NGINX. I have tried to break out of the loop so that each genre group only can have 10 movies with in them. Doing this sped up my time from 20+s -> 7+s.

There are:
11 genres
1300 movies
3205 genre_movie

Example of the database
movie:

 |id|name|...|
 |1 |mov1|...|
 |2 |mov2|...|
 |3 |mov3|...|
 |4 |mov4|...|

genre:

|id|genre   |...|
|1 |action  |...|
|2 |drama   |...|
|3 |thriller|...|
|4 |cartoon |...|

pivot: genre_movie

|movie_id|genre_id|
|1       |1       |
|1       |2       |
|2       |2       |
|3       |4       |

Here is my Relations
Genre:

    public function movie(){
        return $this->belongsToMany('App\Movie');
    }

Movie:

    public function genre(){
        return $this->belongsToMany('App\Genre');
    }

Here is my migrations
movies:

    public function up()
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->string('title', 100);
            $table->text('synopsis');
            $table->integer('released_year');
            $table->string('imdb_url', 100);
            $table->string('s3_location', 100);
            $table->string('poster_location', 100);
            $table->boolean('isRestricted');
            $table->timestamps();
        });
    }

genres:

    public function up()
    {
        Schema::create('genres', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->string('genre');
            $table->longText('description');
        });
    }

genre_movie:

    public function up()
    {
        Schema::create('genre_movie', function (Blueprint $table) {
            $table->bigInteger('genre_id')->unsigned();
            $table->foreign('genre_id')->references('id')->on('genres');

            $table->bigInteger('movie_id')->unsigned();
            $table->foreign('movie_id')->references('id')->on('movies');
        });

Here is how I'm seeding my Data:
Movie Factory

$factory->define(App\Movie::class, function (Faker $faker) {
    $faker->addProvider(new Image($faker));
    $faker->addProvider(new Base($faker));
    return [
        //
        'title' => $faker->name,
        'synopsis' => $faker->paragraph,
        'poster_location' => $faker->imageUrl($width=680, $height=680),
        'imdb_url' => 'https://www.imdb.com/title/tt5884052/',
        's3_location' => 'movie.mp4',
        'released_year' => $faker->numberBetween($min=1900, $max=1960),
        'isRestricted' => $faker->numberBetween($min=0, $max=1)
    ];
});

GenreTable Seeder

    public function run()
    {
        //

        $genres = ['action', 'adventure', 'comedy', 'crime','drama','fantasy','historical','horror','romance','science fiction','thriller'];
        $seeds = [];
        foreach($genres as $genre){
            array_push($seeds,[
                'genre' => $genre,
                'description' => Str::random(150)
            ]);

        }
        DB::table('genres')->insert($seeds);

    }

MovieTable Seeder

    public function run()
    {
        //
        $this->call([GenreSeeder::class]);
        factory(App\Movie::class, 1300)->create();

        $genres = App\Genre::all();

        App\Movie::all()->each(function ($movie) use ($genres) {
            $movie->genre()->attach(
                $genres->random(rand(1,4))->pluck('id')->toArray()
            );
        });

    }

Api Route

    Route::get('movies/filteredByGenre', 'MovieController@filteredByGenre');

MovieController@filteredByGenre

    public function filteredByGenre(Request $request){

        $movies = Movie::with('genre:genre')->get();
        $sizeofMovies = count($movies);
        $formatedMovie = [];

        $count = 0;
        for($x = 0; $x < $sizeofMovies; $x++){
            $sizeofGenre = count($movies[$x]->genre);
            for($y = 0; $y < $sizeofGenre; $y++){
                $genre = $movies[$x]->genre[$y];
                try{
                    if(isset($formatedMovie[$genre['genre']])){
                        if(sizeof($formatedMovie[$genre['genre']]) > 10){
                            break;
                        }
                        $formatedMovie[$genre['genre']][] = $movies[$x];
                    }else{
                        $formatedMovie[$genre['genre']][] = $movies[$x];
                    }
                } catch(ErrorException $e) {
                    $formatedMovie[$genre['genre']][] = $movies[$x];
                }

            }
        }
        $response = ['success' => true, 'data' => $formatedMovie ];
        return response()->json($response, 201);
    }

How I'm receiving the data in the front-end

    componentDidMount() {
        var url = '/api/movies/filteredByGenre';
        axios
            .get(url)
            .then(response => {
                return response.data;
            })
            .then(json => {
                console.log(json);
                this.setState({ frontPageMovies: json.data });
            });
    }

Commands to start my sever and seed the code

docker-compose up -d nginx mysql phpmyadmin workspace
php artisan db:seed --class=MoviesTableSeeder

I expect movies sorted by their genre and the time it takes is no more than 1-3s to retrieve the data.

Body:
If none of your tables are indexed, I'd start there.  You can often get a big performance boost just by adding indexes and/or primary keys on your primary columns (The IDs in this case).  You can think of them a bit like the index of a book ... sure you could scan every single page but its a lot faster if you have a map of where everything is.

Schema::create('movies', function (Blueprint $table) {
    $table->bigIncrements('id')->primary();
    ... or ...
    $table->index(['id']);
});

I'd also suggest installing or enabling the Laravel Debug Bar from https://github.com/barryvdh/laravel-debugbar.  This can show you whats happening in your  application behind the scenes, including each and every database query that is made and how long those took to complete.  Sort of like TTFB in Dev Tools but for the stuff Chrome can't see.

One final option I use a lot, is to have Laravel generate my database query but not execute it ...

$movies = Movie::with('genre:genre')->toSql();

... and then executing it directly in my database (phpMyAdmin or your preferred console) If it's fast there, I know its my php code.  Otherwise I know I need to look at other DB optimizations.


问:
Handling keyboard input in regard to its source in Kivy
I am currently experimenting a bit with Kivy and added a TextInput to my GUI.

I now want to keep features such as deleting the last character when pressing backspace and so on but also want Kivy to execute a method when a new letter is entered to my textInput.

How would I do that? I tried the following code which works in terms of calling said function but doesn't keep the backspace and delete functionality.

Code:

KV

```<code>#:kivy 1.9.0
<PageLayout>:
    GridLayout:

        searchterm: searchterm

        cols: 2
        rows: 2
        spacing: 5
        padding: 5

        Button:
            text: "maybe a listview of latest traces here"
            size_hint: .2,.5

        BoxLayout:
            orientation:'vertical'

            TextInput:
                id: searchterm
                multiLine: False
                hint_text: "Search for specific processes here"
                keyboard_on_key_down: root.on_search
        Button:
            text: "room for imagination"
            size_hint: 0.2, .5

        Button:
            text: "out of ideas"

    BoxLayout:
        orientation: "vertical"
        Button:
            text: "this is a new page for additional information"

        Label:
            halign: 'center'
            valign: 'center'
            size_hint: None, .025
            width: self.parent.width
            text: "About:"
            color: 0,0,0,1 #textcolor
            canvas.before:
                Color:
                    rgba: 0.5,0.5,0.5,1
                Rectangle:
                    pos: self.pos
                    size: self.size

        Label:
            halign: 'center'
            valign: 'center'
            size_hint: None, .025
            width: self.parent.width
            text: "This tool was written by me"
            color: 0,0,0,1 #textcolor
            canvas.before:
                Color:
                    rgba: 0.5,0.5,0.5,1
                Rectangle:
                    pos: self.pos
                    size: self.size

        Label:
            halign: 'center'
            valign: 'center'
            size_hint: None, .025
            width: self.parent.width
            text: "It is only meant for evaluation and testing purposes."
            color: 0,0,0,1 #textcolor
            canvas.before:
                Color:
                    rgba: 0.5,0.5,0.5,1
                Rectangle:
                    pos: self.pos
                    size: self.size
</code>```

Python

```<code>import kivy

from kivy.app import App
from kivy.uix.pagelayout import PageLayout
from kivy.config import Config
from kivy.properties import ObjectProperty
from kivy.uix.widget import Widget

#WINDOW ATTRIBUTES
Config.set('graphics','resizable','1')
Config.set('graphics','width','1000')
Config.set('graphics','height','800')

class Visualizer(PageLayout):
    searchterm = ObjectProperty(None)
    def on_search(self,*args,**kwargs):
        print("Test")
        print(*args)
        print(**kwargs)

class VisualizerApp(App):

    def build(self):
        self.title = "MQTT IDS Visualizer. Author: Daniel"
        return Visualizer()

GLAPP = VisualizerApp()
GLAPP.run()
</code>```

答:
You need to call the super for keyboard_on_key_down. I believe the easiest way to do that is to define a subclass of TextInput like so:

```<code>class MyTextInput(TextInput):
    def keyboard_on_key_down(self, window, keycode, text, modifiers):
        App.get_running_app().root.on_search( window, keycode, text, modifiers)  # calls your `on_search()` method
        return super(MyTextInput, self).keyboard_on_key_down(window, keycode, text, modifiers)
</code>```

Then replace TextInput with MyTextInput in your kv file.

Body:
I am currently experimenting a bit with Kivy and added a TextInput to my GUI.

I now want to keep features such as deleting the last character when pressing backspace and so on but also want Kivy to execute a method when a new letter is entered to my textInput.

How would I do that? I tried the following code which works in terms of calling said function but doesn't keep the backspace and delete functionality.

Code:

KV

#:kivy 1.9.0
<PageLayout>:
    GridLayout:

        searchterm: searchterm

        cols: 2
        rows: 2
        spacing: 5
        padding: 5

        Button:
            text: "maybe a listview of latest traces here"
            size_hint: .2,.5

        BoxLayout:
            orientation:'vertical'

            TextInput:
                id: searchterm
                multiLine: False
                hint_text: "Search for specific processes here"
                keyboard_on_key_down: root.on_search
        Button:
            text: "room for imagination"
            size_hint: 0.2, .5

        Button:
            text: "out of ideas"

    BoxLayout:
        orientation: "vertical"
        Button:
            text: "this is a new page for additional information"

        Label:
            halign: 'center'
            valign: 'center'
            size_hint: None, .025
            width: self.parent.width
            text: "About:"
            color: 0,0,0,1 #textcolor
            canvas.before:
                Color:
                    rgba: 0.5,0.5,0.5,1
                Rectangle:
                    pos: self.pos
                    size: self.size

        Label:
            halign: 'center'
            valign: 'center'
            size_hint: None, .025
            width: self.parent.width
            text: "This tool was written by me"
            color: 0,0,0,1 #textcolor
            canvas.before:
                Color:
                    rgba: 0.5,0.5,0.5,1
                Rectangle:
                    pos: self.pos
                    size: self.size

        Label:
            halign: 'center'
            valign: 'center'
            size_hint: None, .025
            width: self.parent.width
            text: "It is only meant for evaluation and testing purposes."
            color: 0,0,0,1 #textcolor
            canvas.before:
                Color:
                    rgba: 0.5,0.5,0.5,1
                Rectangle:
                    pos: self.pos
                    size: self.size

Python

import kivy

from kivy.app import App
from kivy.uix.pagelayout import PageLayout
from kivy.config import Config
from kivy.properties import ObjectProperty
from kivy.uix.widget import Widget

#WINDOW ATTRIBUTES
Config.set('graphics','resizable','1')
Config.set('graphics','width','1000')
Config.set('graphics','height','800')

class Visualizer(PageLayout):
    searchterm = ObjectProperty(None)
    def on_search(self,*args,**kwargs):
        print("Test")
        print(*args)
        print(**kwargs)

class VisualizerApp(App):

    def build(self):
        self.title = "MQTT IDS Visualizer. Author: Daniel"
        return Visualizer()

GLAPP = VisualizerApp()
GLAPP.run()

Body:
You need to call the super for keyboard_on_key_down. I believe the easiest way to do that is to define a subclass of TextInput like so:

class MyTextInput(TextInput):
    def keyboard_on_key_down(self, window, keycode, text, modifiers):
        App.get_running_app().root.on_search( window, keycode, text, modifiers)  # calls your `on_search()` method
        return super(MyTextInput, self).keyboard_on_key_down(window, keycode, text, modifiers)

Then replace TextInput with MyTextInput in your kv file.


问:
Is it possible to run ipython with some packages already imported?
Is it possible to run ipython with some packages already imported?
almost every time when I run ipython I do import numpy as np, is it possible to automate this process? i.e. just after I run ipython I want to be able to write something like np.array([0,1]). Is it possible?

答: In the case of Mac add a script like load_numpy.py under ~/.ipython/profile_default/startup/ directory and add the import statements you need to that script. Every time you run ipython, all the scripts in the startup directory will be executed first and so the imports will be there. in case of Ubuntu add the file to ~/.config/ipython/profile_default/startup/


问:
Multiple if else statements within a function - form only redirecting to top listed option
I am using contact form 7 on this page: https://www.thenetwork360group.com/cilt-exam-series/. I am trying to redirect the user based on what exam they enrol on at the end.

I realise having this many if / else statements in one function is messy. I have tried multiple things, I tried switch statements but the form did not redirect after sending.

This is currently what I have:

```<code>document.addEventListener( 'wpcf7submit', function( event ) {
    if ( '5686' == event.detail.contactFormId ) {

        var lt2 = document.getElementById("_lt2").value;
        var lt3 = document.getElementById("_lt3").value;
        var lt5 = document.getElementById("_lt5").value;
        var om3 = document.getElementById("_om3").value;
        var om5 = document.getElementById("_om5").value;

      if (lt2 == "1 - £44") {
        location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5683';
      } else if (lt2 == "2 - £88") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5684';
      } else if (lt2 == "3 - £132") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5682';
      } else if (lt3 == "1 - £72") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5707';
      } else if (lt3 == "2 - £144") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5708';
      } else if (lt5 == "1 - £74") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5709';
      } else if (lt5 == "2 - £148") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5710';
      } else if (lt5 == "3 - £222") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5711';
      } else if (om3 == "1 - £72") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5712';
      } else if (om5 == "1 - £74") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5713';
      } else if (om5 == "2 - £148") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5714';
      } else if (om5 == "3 - £222") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5715';
      }
    }

}, false )
</code>```

The ID's related to the form, so var lt2 related to the following ID:

```<code>[select lt2 id:_lt2 "1 - £44" "2 - £88" "3 - £132"]
</code>```

I am expeting the user to be redirected based on which option they have selected, above. However, it only seems to be redirecting to the first option.

Any advice would be great.

答:
Have you tried doing

```<code>window.location = url;
</code>```

instead of

```<code>location = url;
</code>```

Just to point out, you are not handling every single scenario. What happens when the value is not any of them? Is that a possibility? You should also consider a different way to design this - for instance, these elements can have an ID or other attribute that you can validate then simply do:

```<code>window.location = 'https://www.thenetwork360group.com/cart/?add-to-cart='+id;
</code>```

Body:
I am using contact form 7 on this page: https://www.thenetwork360group.com/cilt-exam-series/. I am trying to redirect the user based on what exam they enrol on at the end.

I realise having this many if / else statements in one function is messy. I have tried multiple things, I tried switch statements but the form did not redirect after sending.

This is currently what I have:

document.addEventListener( 'wpcf7submit', function( event ) {
    if ( '5686' == event.detail.contactFormId ) {

        var lt2 = document.getElementById("_lt2").value;
        var lt3 = document.getElementById("_lt3").value;
        var lt5 = document.getElementById("_lt5").value;
        var om3 = document.getElementById("_om3").value;
        var om5 = document.getElementById("_om5").value;

      if (lt2 == "1 - £44") {
        location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5683';
      } else if (lt2 == "2 - £88") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5684';
      } else if (lt2 == "3 - £132") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5682';
      } else if (lt3 == "1 - £72") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5707';
      } else if (lt3 == "2 - £144") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5708';
      } else if (lt5 == "1 - £74") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5709';
      } else if (lt5 == "2 - £148") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5710';
      } else if (lt5 == "3 - £222") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5711';
      } else if (om3 == "1 - £72") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5712';
      } else if (om5 == "1 - £74") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5713';
      } else if (om5 == "2 - £148") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5714';
      } else if (om5 == "3 - £222") {
          location = 'https://www.thenetwork360group.com/cart/?add-to-cart=5715';
      }
    }

}, false )

The ID's related to the form, so var lt2 related to the following ID:

[select lt2 id:_lt2 "1 - £44" "2 - £88" "3 - £132"]

I am expeting the user to be redirected based on which option they have selected, above. However, it only seems to be redirecting to the first option.

Any advice would be great.

Body:
Have you tried doing

window.location = url;

instead of

location = url;

Just to point out, you are not handling every single scenario. What happens when the value is not any of them? Is that a possibility? You should also consider a different way to design this - for instance, these elements can have an ID or other attribute that you can validate then simply do:

window.location = 'https://www.thenetwork360group.com/cart/?add-to-cart='+id;


问:
upload a table in javafx to an excel sheet
I have been trying to find a way to upload a simple JavaFX table into an excel sheet. I can't find anywhere a simple solution to upload my JavaFX table into an excel sheet. I need a button that I will click and the current table will go to an excel sheet.

I have been trying a couple of tutorials and other things what I found on youtube and other sources. But everything I have been trying to find is kinda different than I need.

```<code>public class Main extends Application {

    Stage window;
    TableView<Person> table;
    TextField nameInput, middlenameInput, backnameInput, adressInput, housenumberInput, zipcodeInput, residenceInput, dateofbirthInput, emailInput, phoneInput;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("thenewboston - JavaFX");

        TableColumn<Person, String> nameColumn = new TableColumn<>("name");
        nameColumn.setMinWidth(150);
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));

        TableColumn<Person, String> middlenameColumn = new TableColumn<>("t.v.");
        middlenameColumn.setMinWidth(75);
        middlenameColumn.setCellValueFactory(new PropertyValueFactory<>("Middlename"));

        TableColumn<Person, String> backnameColumn = new TableColumn<>("last name");
        backnameColumn.setMinWidth(150);
        backnameColumn.setCellValueFactory(new PropertyValueFactory<>("backname"));

        TableColumn<Person, String> adressColumn = new TableColumn<>("adress");
        adressColumn.setMinWidth(150);
        adressColumn.setCellValueFactory(new PropertyValueFactory<>("adress"));

        TableColumn<Person, String> housenumberColumn = new TableColumn<>("Nr");
        housenumberColumn.setMinWidth(30);
        housenumberColumn.setCellValueFactory(new PropertyValueFactory<>("housenumber"));

        TableColumn<Person, String> zipcodeColumn = new TableColumn<>("zipcode");
        zipcodeColumn.setMinWidth(75);
        zipcodeColumn.setCellValueFactory(new PropertyValueFactory<>("zipcode"));

        TableColumn<Person, String> residenceColumn = new TableColumn<>("place");
        residenceColumn.setMinWidth(150);
        residenceColumn.setCellValueFactory(new PropertyValueFactory<>("residence"));

        TableColumn<Person, String> dateofbirthColumn = new TableColumn<>("date of birth");
        dateofbirthColumn.setMinWidth(100);
        dateofbirthColumn.setCellValueFactory(new PropertyValueFactory<>("dateofbirth"));

        TableColumn<Person, String> emailColumn = new TableColumn<>("Email");
        emailColumn.setMinWidth(200);
        emailColumn.setCellValueFactory(new PropertyValueFactory<>("email"));

        TableColumn<Person, String> phoneColumn = new TableColumn<>("phone");
        phoneColumn.setMinWidth(150);
        phoneColumn.setCellValueFactory(new PropertyValueFactory<>("phone"));

        nameInput = new TextField();
        nameInput.setPromptText("name");
        nameInput.setMinWidth(100);

        middlenameInput = new TextField();
        middlenameInput.setPromptText("t.v.");

        backnameInput = new TextField();
        backnameInput.setPromptText("lastName");

        adressInput = new TextField();
        adressInput.setPromptText("Adress");

        housenumberInput = new TextField();
        housenumberInput.setPromptText("nr");

        zipcodeInput = new TextField();
        zipcodeInput.setPromptText("zipcode");

        residenceInput = new TextField();
        residenceInput.setPromptText("place");

        dateofbirthInput = new TextField();
        dateofbirthInput.setPromptText("date of birth");

        emailInput = new TextField();
        emailInput.setPromptText("Email");

        phoneInput = new TextField();
        phoneInput.setPromptText("phone number");

        Button addButton = new Button("Add");
        addButton.setOnAction(e -> addButtonClicked());

        Button deleteButton = new Button("Delete");
        deleteButton.setOnAction(e -> deleteButtonClicked());

        HBox hBox = new HBox();
        hBox.setPadding(new Insets(10,10,10,10));
        hBox.setSpacing(10);
        hBox.getChildren().addAll(nameInput, middlenameInput, backnameInput, adressInput, housenumberInput, zipcodeInput, residenceInput, dateofbirthInput, emailInput, phoneInput, addButton, deleteButton);

        table = new TableView<>();
        table.setItems(getPerson());
        table.getColumns().addAll(nameColumn, middlenameColumn, backnameColumn, adressColumn, housenumberColumn, zipcodeColumn, residenceColumn, dateofbirthColumn, emailColumn, phoneColumn);

        VBox vBox = new VBox();
        vBox.getChildren().addAll(table, hBox);

        Scene scene = new Scene(vBox);
        window.setScene(scene);
        window.show();
    }

    //Add button clicked
    public void addButtonClicked(){
        Person product = new Person();
        product.setName(nameInput.getText());
        product.setMiddlename(middlenameInput.getText());
        product.setBackname(backnameInput.getText());
        product.setAdress(adressInput.getText());
        product.setHousenumber(housenumberInput.getText());
        product.setZipcode(zipcodeInput.getText());
        product.setResidence(residenceInput.getText());
        product.setDateofbirth(dateofbirthInput.getText());
        product.setEmail(emailInput.getText());
        product.setPhone(phoneInput.getText());

        table.getItems().add(product);
        nameInput.clear();
        middlenameInput.clear();
        backnameInput.clear();
        adressInput.clear();
        housenumberInput.clear();
        zipcodeInput.clear();
        residenceInput.clear();
        dateofbirthInput.clear();
        emailInput.clear();
        phoneInput.clear();

    }

    //Delete button clicked
    public void deleteButtonClicked(){
        ObservableList<Person> PersonSelected, allPersons;
        allPersons = table.getItems();
        PersonSelected = table.getSelectionModel().getSelectedItems();

        PersonSelected.forEach(allPersons::remove);
    }

    public ObservableList<Person> getPerson(){
        ObservableList<Person> persons = FXCollections.observableArrayList();
        persons.add(new Person("testName", "" , "lastName", "adressName", "nr", "zipcode", "place", "dateOfBirth", "email@gmail.com", "phoneNumber"));
        persons.add(new Person("testName", "" , "lastName", "adressName", "nr", "zipcode", "place", "dateOfBirth", "email@gmail.com", "phoneNumber"));
        persons.add(new Person("testName", "" , "lastName", "adressName", "nr", "zipcode", "place", "dateOfBirth", "email@gmail.com", "phoneNumber"));
        return persons;
    }

}
</code>```

This is just a table with some common information. This I need to upload to an excel sheet by a button

答:
You cannot directly paste the entire JavaFx table into Microsoft Excel sheet. You have to use Apache POI library to write into an Excel sheet. On click on JavaFx button, you have to take all the fields of your desired object model like Person object in your case and write to excel sheet using Apache POI library. Refer the link below.

https://poi.apache.org/

Body:
I have been trying to find a way to upload a simple JavaFX table into an excel sheet. I can't find anywhere a simple solution to upload my JavaFX table into an excel sheet. I need a button that I will click and the current table will go to an excel sheet.

I have been trying a couple of tutorials and other things what I found on youtube and other sources. But everything I have been trying to find is kinda different than I need.

public class Main extends Application {

    Stage window;
    TableView<Person> table;
    TextField nameInput, middlenameInput, backnameInput, adressInput, housenumberInput, zipcodeInput, residenceInput, dateofbirthInput, emailInput, phoneInput;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("thenewboston - JavaFX");

        TableColumn<Person, String> nameColumn = new TableColumn<>("name");
        nameColumn.setMinWidth(150);
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));

        TableColumn<Person, String> middlenameColumn = new TableColumn<>("t.v.");
        middlenameColumn.setMinWidth(75);
        middlenameColumn.setCellValueFactory(new PropertyValueFactory<>("Middlename"));

        TableColumn<Person, String> backnameColumn = new TableColumn<>("last name");
        backnameColumn.setMinWidth(150);
        backnameColumn.setCellValueFactory(new PropertyValueFactory<>("backname"));

        TableColumn<Person, String> adressColumn = new TableColumn<>("adress");
        adressColumn.setMinWidth(150);
        adressColumn.setCellValueFactory(new PropertyValueFactory<>("adress"));

        TableColumn<Person, String> housenumberColumn = new TableColumn<>("Nr");
        housenumberColumn.setMinWidth(30);
        housenumberColumn.setCellValueFactory(new PropertyValueFactory<>("housenumber"));

        TableColumn<Person, String> zipcodeColumn = new TableColumn<>("zipcode");
        zipcodeColumn.setMinWidth(75);
        zipcodeColumn.setCellValueFactory(new PropertyValueFactory<>("zipcode"));

        TableColumn<Person, String> residenceColumn = new TableColumn<>("place");
        residenceColumn.setMinWidth(150);
        residenceColumn.setCellValueFactory(new PropertyValueFactory<>("residence"));

        TableColumn<Person, String> dateofbirthColumn = new TableColumn<>("date of birth");
        dateofbirthColumn.setMinWidth(100);
        dateofbirthColumn.setCellValueFactory(new PropertyValueFactory<>("dateofbirth"));

        TableColumn<Person, String> emailColumn = new TableColumn<>("Email");
        emailColumn.setMinWidth(200);
        emailColumn.setCellValueFactory(new PropertyValueFactory<>("email"));

        TableColumn<Person, String> phoneColumn = new TableColumn<>("phone");
        phoneColumn.setMinWidth(150);
        phoneColumn.setCellValueFactory(new PropertyValueFactory<>("phone"));

        nameInput = new TextField();
        nameInput.setPromptText("name");
        nameInput.setMinWidth(100);

        middlenameInput = new TextField();
        middlenameInput.setPromptText("t.v.");

        backnameInput = new TextField();
        backnameInput.setPromptText("lastName");

        adressInput = new TextField();
        adressInput.setPromptText("Adress");

        housenumberInput = new TextField();
        housenumberInput.setPromptText("nr");

        zipcodeInput = new TextField();
        zipcodeInput.setPromptText("zipcode");

        residenceInput = new TextField();
        residenceInput.setPromptText("place");

        dateofbirthInput = new TextField();
        dateofbirthInput.setPromptText("date of birth");

        emailInput = new TextField();
        emailInput.setPromptText("Email");

        phoneInput = new TextField();
        phoneInput.setPromptText("phone number");

        Button addButton = new Button("Add");
        addButton.setOnAction(e -> addButtonClicked());

        Button deleteButton = new Button("Delete");
        deleteButton.setOnAction(e -> deleteButtonClicked());

        HBox hBox = new HBox();
        hBox.setPadding(new Insets(10,10,10,10));
        hBox.setSpacing(10);
        hBox.getChildren().addAll(nameInput, middlenameInput, backnameInput, adressInput, housenumberInput, zipcodeInput, residenceInput, dateofbirthInput, emailInput, phoneInput, addButton, deleteButton);

        table = new TableView<>();
        table.setItems(getPerson());
        table.getColumns().addAll(nameColumn, middlenameColumn, backnameColumn, adressColumn, housenumberColumn, zipcodeColumn, residenceColumn, dateofbirthColumn, emailColumn, phoneColumn);

        VBox vBox = new VBox();
        vBox.getChildren().addAll(table, hBox);

        Scene scene = new Scene(vBox);
        window.setScene(scene);
        window.show();
    }

    //Add button clicked
    public void addButtonClicked(){
        Person product = new Person();
        product.setName(nameInput.getText());
        product.setMiddlename(middlenameInput.getText());
        product.setBackname(backnameInput.getText());
        product.setAdress(adressInput.getText());
        product.setHousenumber(housenumberInput.getText());
        product.setZipcode(zipcodeInput.getText());
        product.setResidence(residenceInput.getText());
        product.setDateofbirth(dateofbirthInput.getText());
        product.setEmail(emailInput.getText());
        product.setPhone(phoneInput.getText());

        table.getItems().add(product);
        nameInput.clear();
        middlenameInput.clear();
        backnameInput.clear();
        adressInput.clear();
        housenumberInput.clear();
        zipcodeInput.clear();
        residenceInput.clear();
        dateofbirthInput.clear();
        emailInput.clear();
        phoneInput.clear();

    }

    //Delete button clicked
    public void deleteButtonClicked(){
        ObservableList<Person> PersonSelected, allPersons;
        allPersons = table.getItems();
        PersonSelected = table.getSelectionModel().getSelectedItems();

        PersonSelected.forEach(allPersons::remove);
    }

    public ObservableList<Person> getPerson(){
        ObservableList<Person> persons = FXCollections.observableArrayList();
        persons.add(new Person("testName", "" , "lastName", "adressName", "nr", "zipcode", "place", "dateOfBirth", "email@gmail.com", "phoneNumber"));
        persons.add(new Person("testName", "" , "lastName", "adressName", "nr", "zipcode", "place", "dateOfBirth", "email@gmail.com", "phoneNumber"));
        persons.add(new Person("testName", "" , "lastName", "adressName", "nr", "zipcode", "place", "dateOfBirth", "email@gmail.com", "phoneNumber"));
        return persons;
    }

}

This is just a table with some common information. This I need to upload to an excel sheet by a button


问:
SocketChannel: java.io.IOException: An existing connection was forcibly closed by the remote host
I'm using a SocketChannel with a network socket, and have to handle the expected exception of the other end of the socket closing the channel unexpectedly.

The problem is, I get this IOException:

```<code>java.io.IOException: An existing connection was forcibly closed by the remote host
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(Unknown Source)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.read(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
    ...
</code>```

I need to distinguish between this exception, which is expected to happen, and unexpected exceptions, so that I can log/print the unexpected ones and handle this one. But it's just an ordinary IOException with a different text message, and although I always check SocketChannel.isOpen() and SocketChannel.isConnected(), they seem to return true in this case even though the other end of the socket has been closed.

What can/should I do?

答:
the isOpen() and isConnected() should be more accurately called hasBeenOpenned() and hasBeenConnected().  Once they are true, they do not return to false.

You may have to do a e.getMessage().contains("closed by the remote host"). Unfortunately, this is likely to be a platform dependant.

Instead I suggest you allow the protocol to send a "Closed" message of some kind and treat any exception without this first as unexpected.

Body:
I'm using a SocketChannel with a network socket, and have to handle the expected exception of the other end of the socket closing the channel unexpectedly.

The problem is, I get this IOException:

java.io.IOException: An existing connection was forcibly closed by the remote host
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(Unknown Source)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.read(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
    ...

I need to distinguish between this exception, which is expected to happen, and unexpected exceptions, so that I can log/print the unexpected ones and handle this one. But it's just an ordinary IOException with a different text message, and although I always check SocketChannel.isOpen() and SocketChannel.isConnected(), they seem to return true in this case even though the other end of the socket has been closed.

What can/should I do?


问:
Connecting to SQL Server via SQL magics in Jupyter Lab
I am trying to connect to our remote sql server db via Jupyter Labs using the SQL magics.  I can connect with a traditional connection string, but the SQL magics doesnt seem to work (which means I am doing something wrong).  Below is the working pyodbc connection:

```<code>conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=Server;'
                      'Database=DB;'
                      'Trusted_Connection=yes;')
</code>```

But when I try to connect with the magics I get an error that says no connection string supplied

```<code>%load_ext sql
%sql engine = create_engine("mssql+pyodbc://user:password@server/db")
</code>```

Ideally, I would like to connect with Magics using a DSN (I tried this also and didnt work):

```<code>%load_ext sql
%sql engine = create_engine("mssql+pyodbc://DSN;Trusted_Connection = Yes")
</code>```

Any help on getting a connection working?

答:
Try this from a Jupyter cell:

```<code>import urllib
params = urllib.parse.quote_plus("DRIVER={SQL SERVER};SERVER=Server;DATABASE=DB;TRUSTED_CONNECTION=YES")
"mssql+pyodbc:///?odbc_connect=%s" % params
</code>```

Then run the cell and copy/paste the encoded string that is returned from its evaluation into the magic.

```<code>%%sql mssql+pyodbc:///?odbc_connect=DRIVER%3D%7BSQL+SERVER%7D%3BSERVER%3DServer%3BDATABASE%3DDB%3BTRUSTED_CONNECTION%3DYES
   [your SQL code here]
</code>```

Body:
I am trying to connect to our remote sql server db via Jupyter Labs using the SQL magics.  I can connect with a traditional connection string, but the SQL magics doesnt seem to work (which means I am doing something wrong).  Below is the working pyodbc connection:

conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=Server;'
                      'Database=DB;'
                      'Trusted_Connection=yes;')

But when I try to connect with the magics I get an error that says no connection string supplied

%load_ext sql
%sql engine = create_engine("mssql+pyodbc://user:password@server/db")

Ideally, I would like to connect with Magics using a DSN (I tried this also and didnt work):

%load_ext sql
%sql engine = create_engine("mssql+pyodbc://DSN;Trusted_Connection = Yes")

Any help on getting a connection working?

Body:
Try this from a Jupyter cell:

import urllib
params = urllib.parse.quote_plus("DRIVER={SQL SERVER};SERVER=Server;DATABASE=DB;TRUSTED_CONNECTION=YES")
"mssql+pyodbc:///?odbc_connect=%s" % params

Then run the cell and copy/paste the encoded string that is returned from its evaluation into the magic.

%%sql mssql+pyodbc:///?odbc_connect=DRIVER%3D%7BSQL+SERVER%7D%3BSERVER%3DServer%3BDATABASE%3DDB%3BTRUSTED_CONNECTION%3DYES
   [your SQL code here]


问:
Run some actions at the same time in a makefile
I have the following makefile.

I would like step0 to run then I would like all of the b*.R scripts to run at the same time in step1. When step1 is complete I would like final to run.

When I run make or make -j 8 it seems like all of the b*.R files still run sequentially. Is this makefile set up correctly to run all of the b*.R files at the same time? If not what do I need to change.

```<code>final : step1
    Rscript c.R

step1 : step0
    Rscript b1.R
    Rscript b2.R
    Rscript b3.R
    Rscript b4.R
    Rscript b5.R
    Rscript b6.R

step0 :
    Rscript a.R
</code>```

答:
When I run make or make -j 8 it seems like all of the b*.R files still run sequentially.

-jN allows parallel execution of different recipes, not the individual commands constituting a recipe.

So the makefile should be restructured like this:

```<code>.PHONY: final b1 b2 b3 b4 b5 b6 step0

final: b1 b2 b3 b4 b5 b6
b1 b2 b3 b4 b5 b6: step0

b1: ;Rscript b1.R
b2: ;Rscript b2.R
b3: ;Rscript b3.R
b4: ;Rscript b4.R
b5: ;Rscript b5.R
b6: ;Rscript b6.R

step0: ;Rscript a.R
</code>```

Body:
I have the following makefile.

I would like step0 to run then I would like all of the b*.R scripts to run at the same time in step1. When step1 is complete I would like final to run.

When I run make or make -j 8 it seems like all of the b*.R files still run sequentially. Is this makefile set up correctly to run all of the b*.R files at the same time? If not what do I need to change.

final : step1
    Rscript c.R

step1 : step0
    Rscript b1.R
    Rscript b2.R
    Rscript b3.R
    Rscript b4.R
    Rscript b5.R
    Rscript b6.R

step0 :
    Rscript a.R

Body:
When I run make or make -j 8 it seems like all of the b*.R files still run sequentially.

-jN allows parallel execution of different recipes, not the individual commands constituting a recipe.

So the makefile should be restructured like this:

.PHONY: final b1 b2 b3 b4 b5 b6 step0

final: b1 b2 b3 b4 b5 b6
b1 b2 b3 b4 b5 b6: step0

b1: ;Rscript b1.R
b2: ;Rscript b2.R
b3: ;Rscript b3.R
b4: ;Rscript b4.R
b5: ;Rscript b5.R
b6: ;Rscript b6.R

step0: ;Rscript a.R


问:
When is it "acceptable" to use ViewBag/ViewData in ASP.NET MVC?
I realize that the best practice is to use strongly typed Views and pass in all needed data in a ViewModel, but I am curious if there are situations where it is actually considered "best practice" to pass data in the ViewBag/ViewData.

In what scenarios is the ViewBag/ViewData preferred for passing data to a view?

update

It's great to hear the various uses everyone has come up with for ViewBag/ViewData. We may never arrive at a "best practice" but it will be great to see the different solutions people have come up with that rely on the ViewBag/ViewData.

答:
I typically will use a strongly typed view for displaying any content but will often set ViewBag.Member to the currently logged in member so that it can be used in the main Layout in addition to the specific view.

I have an attribute called PopulateMemberContext which populates ViewBag.Member and I add that attribute to my base controller so that every view will always have the necessary data.

"Right" or "Wrong" I don't know - but it works wonderfully.


问:
Football teams league
Imagine I have 3 teams, and I want to generate random matches between the three teams. I used itertools permutations to print all matches. The problem is generating a score in a game. Imagine team A vs team B (2-1). How do I input the 2 goals by team A and 1 goal by team B in a match?

I have printed all possible matches. Note that I used permutations because Team A vs Team B is different from Team B vs Team A because one team plays at home, and in another game plays at the other team's home.

```<code>import itertools
import random

teams=['A','B','C']

def games():
  permutations=itertools.permutations(teams,2)
  for i in permutations:
    print(i)
    result=random.randint(0,5)
</code>```

My doubt is when I have to generate a result in a game in every iteration.

答:
You are generating a single integer, but you need two to represent a match score:

```<code>import itertools
import random

teams = ['A','B','C']

def games():
    permutations = itertools.permutations(teams, 2)
    for match in permutations:
        home_team_score, away_team_score = random.randint(0, 5), random.randint(0, 5)
        print(match, home_team_score, away_team_score)

games()
</code>```

Sample output

```<code>('A', 'B') 4 2
('A', 'C') 0 1
('B', 'A') 2 5
('B', 'C') 1 2
('C', 'A') 2 4
('C', 'B') 1 1
</code>```

Then you can play around with the format, for example

```<code>for (home_team, away_team) in permutations:
    home_team_score, away_team_score = random.randint(0, 5), random.randint(0, 5)
    print('{} {} - {} {}'.format(home_team, home_team_score, away_team_score, away_team))
</code>```

to get

```<code>A 4 - 4 B
A 0 - 4 C
B 3 - 4 A
B 1 - 0 C
C 2 - 1 A
C 3 - 5 B
</code>```

Title: Football teams league

Body:
Imagine I have 3 teams, and I want to generate random matches between the three teams. I used itertools permutations to print all matches. The problem is generating a score in a game. Imagine team A vs team B (2-1). How do I input the 2 goals by team A and 1 goal by team B in a match?

I have printed all possible matches. Note that I used permutations because Team A vs Team B is different from Team B vs Team A because one team plays at home, and in another game plays at the other team's home.

import itertools
import random

teams=['A','B','C']

def games():
  permutations=itertools.permutations(teams,2)
  for i in permutations:
    print(i)
    result=random.randint(0,5)

My doubt is when I have to generate a result in a game in every iteration.

Body:
You are generating a single integer, but you need two to represent a match score:

import itertools
import random

teams = ['A','B','C']

def games():
    permutations = itertools.permutations(teams, 2)
    for match in permutations:
        home_team_score, away_team_score = random.randint(0, 5), random.randint(0, 5)
        print(match, home_team_score, away_team_score)

games()

Sample output

('A', 'B') 4 2
('A', 'C') 0 1
('B', 'A') 2 5
('B', 'C') 1 2
('C', 'A') 2 4
('C', 'B') 1 1

Then you can play around with the format, for example

for (home_team, away_team) in permutations:
    home_team_score, away_team_score = random.randint(0, 5), random.randint(0, 5)
    print('{} {} - {} {}'.format(home_team, home_team_score, away_team_score, away_team))

to get

A 4 - 4 B
A 0 - 4 C
B 3 - 4 A
B 1 - 0 C
C 2 - 1 A
C 3 - 5 B


问:
How to show full content of another website in Django?
I am trying to get the full content of another website, or modify the links that are clicked on when people use other websites on my site in django?</p>

```<code>import requests
import urllib.request
def one(request, myurl='google.com'):
    url = 'http://' + myurl
    r = requests.get(url)
    return HttpResponse(r)
</code>```

答:
The outcome of requests.get  is a Response [requests-doc] object, not a string. You can obtain the content with content [requests-doc]. For example:

```<code>import requests
import urllib.request

def one(request, myurl='google.com'):
    url = 'http://' + myurl
    r = requests.get(url)
    return HttpResponse(
        content=<b>r.content</b>,
        content_type=r.headers.get('Content-Type'),
        status=r.status_code
    )</code>```

Body:
I am trying to get the full content of another website, or modify the links that are clicked on when people use other websites on my site in django?

import requests
import urllib.request
def one(request, myurl='google.com'):
    url = 'http://' + myurl
    r = requests.get(url)
    return HttpResponse(r)

Body:
The outcome of requests.get  is a Response [requests-doc] object, not a string. You can obtain the content with content [requests-doc]. For example:

import requests
import urllib.request

def one(request, myurl='google.com'):
    url = 'http://' + myurl
    r = requests.get(url)
    return HttpResponse(
        content=r.content,
        content_type=r.headers.get('Content-Type'),
        status=r.status_code
    )