问:
Optimizing accesing dicts in python
First things first: Python 3.5 and the next libraries: json, urllib, from urllib import request

I have been trying to accomplish something on two different ways (so far) and I find issues on both of them. Could anyone tell me how would you code it?

The code needs to translate information from the next list of dictionaries using the API of GuildWars2 to get the name and position of each of those objects.

```<code>ids = [{'traits': [1451, 1338, 1437], 'id': 4}, {'traits': [1471, 1482, 1711], 'id': 11}, {'traits': [2049, 2011, 1928], 'id': 18}]
</code>```

First try: (This works perfectly, and there's a picture at the end of this post showing the result. However, the issue here is that it creates 12 requests to the server, and waiting for it to answer takes more time than it should. There's a cap on requests per minute on those servers so I'd like to code it with the minimum needed).

```<code>specializations_items = []
for i in ids:
    webpage_stored = request.urlopen("https://api.guildwars2.com/v2/specializations/"+str(i['id'])+"?lang=es").read().decode('utf8')
    api_specialization_data = json.loads(webpage_stored)
    api_specialization_name = api_specialization_data["name"]
    translated_traits = []
    numeric_traits = []
    for j in i['traits']:
        webpage_stored = request.urlopen("https://api.guildwars2.com/v2/traits/"+str(j)+"?lang=es").read().decode('utf8')
        api_trait = json.loads(webpage_stored)
        translated_traits.append(api_trait['name'])
        for k in api_specialization_data['major_traits']:
            if j == k:
                numeric_traits.append(str(api_specialization_data['major_traits'].index(k)+1))
    numeric_traits_new = []
    for l in numeric_traits:
        l = l.replace("9", "3").replace("8", "2").replace("7", "1").replace("6", "3").replace("5", "2").replace("4", "1")
        numeric_traits_new.append(l)
    specializations_items.append("[b]"+api_specialization_name+" ("+"".join(numeric_traits_new)+"):[/b] "+", ".join(translated_traits)+".")
return "\n".join(specializations_items)
</code>```

Second try: (Cool, just 2 requests to the server, but the issue here is that it's Looping Hell. Also, another issue is that I'm not even sure how to assign the numeric info with the positioning of each trait (that part is unfinished):

```<code># Note: Each of the next 2 vars are json.loads dicts of those websites. It's unnecesary long to paste the dicts in here, so just click on the links.
api_traits = https://api.guildwars2.com/v2/traits%3Fids=1451%2C%201338%2C%201437%2C%2C1471%2C%201482%2C%201711%2C%2C2049%2C%202011%2C%201928%26lang=es
api_specializations = https://api.guildwars2.com/v2/specializations%3Fids=4%2C11%2C18%26lang=es

numeric_traits = []
for j in api_specializations:
    for m in j['major_traits']:
        for n in api_traits:
            if n['id'] == m:
                numeric_traits.append(str(j['major_traits'].index(n['id'])+1)+n['name'])
for i in ids:
    for j in api_specializations:
        if i['id'] == j['id']:
            i['name'] = j['name']
    for k in api_traits:
        for l in i['traits']:
            if l == k['id']:
                i['traits'].remove(l)
                i['traits'].append(k['name'])
print(numeric_traits) #Not finished, I don't think using so much loops is a good idea.
</code>```

Desired output:

Bonus:

I will provide 2 different ids more just in case you want to check different outputs with different ids:

```<code>ids = [{'traits': [296, 325, 1510], 'id': 31}, {'traits': [232, 1502, 226], 'id': 41}, {'traits': [1952, 2015, 1986], 'id': 48}]
ids = [{'traits': [815, 816, 801], 'id': 39}, {'traits': [1876, 1844, 778], 'id': 19}, {'traits': [2020, 2031, 1919], 'id': 34}]
</code>```

So...

What is the best way to accomplish my task, in a way that it doesn't create unnecessary server requests, and gets the desired results without me getting crazy because of loops inside loops inside loops inside loops (which is also slow)?

答:
I used the requests library to fetch the JSON from your second code snippet. Here's an approach that works:

```<code>import requests

api_traits = requests.get("https://api.guildwars2.com/v2/traits%3Fids=1451%2C%201338%2C%201437%2C%2C1471%2C%201482%2C%201711%2C%2C2049%2C%202011%2C%201928%26lang=es").json()
api_specializations = requests.get("https://api.guildwars2.com/v2/specializations%3Fids=4%2C11%2C18%26lang=es").json()

traits_dict = { trait["id"]: trait["name"] for trait in api_traits }

for specialization in api_specializations:
    numeric_traits = []
    trait_names = []
    for i, trait_id in enumerate(specialization["major_traits"]):
        if trait_id in traits_dict:
            numeric_traits.append(i % 3 + 1)
            trait_names.append(traits_dict[trait_id])
    print("{} ({}): {}.".format(specialization["name"],
                                "".join(map(str, numeric_traits)),
                                ", ".join(trait_names)))

# Output:
# Fuerza (221): Fuerza restauradora, Mandoble eficaz, Potencia berserker.
# Tácticas (333): Potenciado, Potenciar aliados, Fuerza de falange.
# Berserker (111): Pendenciero aplastante, Reacción sangrienta, Rugido sangriento.
</code>```

Three important things:

I made a dictionary mapping trait IDs to trait names. This lets you avoid the nested loops trying to match things up.

I used enumerate to avoid the index lookup when you're keeping track of which trait is in which position (for the "numeric traits").

I used modulo arithmetic to help with the numeric traits. i % 3 gets the remainder when dividing by three (since the traits are in three columns), and then the + 1 simply gets back to 1-based indexes.

Let me know if anything else in the code is confusing.

Title: Optimizing accesing dicts in python

Body:
First things first: Python 3.5 and the next libraries: json, urllib, from urllib import request

I have been trying to accomplish something on two different ways (so far) and I find issues on both of them. Could anyone tell me how would you code it?

The code needs to translate information from the next list of dictionaries using the API of GuildWars2 to get the name and position of each of those objects.

ids = [{'traits': [1451, 1338, 1437], 'id': 4}, {'traits': [1471, 1482, 1711], 'id': 11}, {'traits': [2049, 2011, 1928], 'id': 18}]

First try: (This works perfectly, and there's a picture at the end of this post showing the result. However, the issue here is that it creates 12 requests to the server, and waiting for it to answer takes more time than it should. There's a cap on requests per minute on those servers so I'd like to code it with the minimum needed).

specializations_items = []
for i in ids:
    webpage_stored = request.urlopen("https://api.guildwars2.com/v2/specializations/"+str(i['id'])+"?lang=es").read().decode('utf8')
    api_specialization_data = json.loads(webpage_stored)
    api_specialization_name = api_specialization_data["name"]
    translated_traits = []
    numeric_traits = []
    for j in i['traits']:
        webpage_stored = request.urlopen("https://api.guildwars2.com/v2/traits/"+str(j)+"?lang=es").read().decode('utf8')
        api_trait = json.loads(webpage_stored)
        translated_traits.append(api_trait['name'])
        for k in api_specialization_data['major_traits']:
            if j == k:
                numeric_traits.append(str(api_specialization_data['major_traits'].index(k)+1))
    numeric_traits_new = []
    for l in numeric_traits:
        l = l.replace("9", "3").replace("8", "2").replace("7", "1").replace("6", "3").replace("5", "2").replace("4", "1")
        numeric_traits_new.append(l)
    specializations_items.append("[b]"+api_specialization_name+" ("+"".join(numeric_traits_new)+"):[/b] "+", ".join(translated_traits)+".")
return "\n".join(specializations_items)

Second try: (Cool, just 2 requests to the server, but the issue here is that it's Looping Hell. Also, another issue is that I'm not even sure how to assign the numeric info with the positioning of each trait (that part is unfinished):

# Note: Each of the next 2 vars are json.loads dicts of those websites. It's unnecesary long to paste the dicts in here, so just click on the links.
api_traits = https://api.guildwars2.com/v2/traits%3Fids=1451%2C%201338%2C%201437%2C%2C1471%2C%201482%2C%201711%2C%2C2049%2C%202011%2C%201928%26lang=es
api_specializations = https://api.guildwars2.com/v2/specializations%3Fids=4%2C11%2C18%26lang=es

numeric_traits = []
for j in api_specializations:
    for m in j['major_traits']:
        for n in api_traits:
            if n['id'] == m:
                numeric_traits.append(str(j['major_traits'].index(n['id'])+1)+n['name'])
for i in ids:
    for j in api_specializations:
        if i['id'] == j['id']:
            i['name'] = j['name']
    for k in api_traits:
        for l in i['traits']:
            if l == k['id']:
                i['traits'].remove(l)
                i['traits'].append(k['name'])
print(numeric_traits) #Not finished, I don't think using so much loops is a good idea.

Desired output:

Bonus:

I will provide 2 different ids more just in case you want to check different outputs with different ids:

ids = [{'traits': [296, 325, 1510], 'id': 31}, {'traits': [232, 1502, 226], 'id': 41}, {'traits': [1952, 2015, 1986], 'id': 48}]
ids = [{'traits': [815, 816, 801], 'id': 39}, {'traits': [1876, 1844, 778], 'id': 19}, {'traits': [2020, 2031, 1919], 'id': 34}]

So...

What is the best way to accomplish my task, in a way that it doesn't create unnecessary server requests, and gets the desired results without me getting crazy because of loops inside loops inside loops inside loops (which is also slow)?

Body:
I used the requests library to fetch the JSON from your second code snippet. Here's an approach that works:

import requests

api_traits = requests.get("https://api.guildwars2.com/v2/traits%3Fids=1451%2C%201338%2C%201437%2C%2C1471%2C%201482%2C%201711%2C%2C2049%2C%202011%2C%201928%26lang=es").json()
api_specializations = requests.get("https://api.guildwars2.com/v2/specializations%3Fids=4%2C11%2C18%26lang=es").json()

traits_dict = { trait["id"]: trait["name"] for trait in api_traits }

for specialization in api_specializations:
    numeric_traits = []
    trait_names = []
    for i, trait_id in enumerate(specialization["major_traits"]):
        if trait_id in traits_dict:
            numeric_traits.append(i % 3 + 1)
            trait_names.append(traits_dict[trait_id])
    print("{} ({}): {}.".format(specialization["name"],
                                "".join(map(str, numeric_traits)),
                                ", ".join(trait_names)))

# Output:
# Fuerza (221): Fuerza restauradora, Mandoble eficaz, Potencia berserker.
# Tácticas (333): Potenciado, Potenciar aliados, Fuerza de falange.
# Berserker (111): Pendenciero aplastante, Reacción sangrienta, Rugido sangriento.

Three important things:

I made a dictionary mapping trait IDs to trait names. This lets you avoid the nested loops trying to match things up.

I used enumerate to avoid the index lookup when you're keeping track of which trait is in which position (for the "numeric traits").

I used modulo arithmetic to help with the numeric traits. i % 3 gets the remainder when dividing by three (since the traits are in three columns), and then the + 1 simply gets back to 1-based indexes.

Let me know if anything else in the code is confusing.


来源: stackexchange

问:
Summation of an array of numbers in javascript
Here, I want to take inputs from users. Split and store them into array. Then show the summation of array numbers.

 summation experiment

```<code><!-- for taking inputs -->
<input id="seriesInput" type="text" placeholder="please use space">
<!-- for submitting inputs -->
<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">
<!-- for placing results -->
<div> Summation is <span id="sum"></span> </div>
<script type="text/javascript">

function seriesFunction()
{
    value = document.getElementById("seriesInput").value;
    // splitting string in an array
    value_arr = value.split(" ");
    alert(value_arr);
    // calling reduce method for summation
    var sum = value_arr.reduce(get_sum,0);
    // assigning result
    document.getElementById("sum").innerHTML =sum;
alert(sum);

    function get_sum(total, currentVal) {
total += currentVal;
return total;
}
}
</script>
</code>```

答:
You are getting currentValue as string in the get_sum function, try making to integer. You can do it like: </p>

```<code>function get_sum(total, currentVal) {
    currentVal = parseInt(currentVal);
    total += currentVal;
    return total;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here, I want to take inputs from users. Split and store them into array. Then show the summation of array numbers.

 summation experiment

<input id="seriesInput" type="text" placeholder="please use space">

<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">

 Summation is

Body:
You are getting currentValue as string in the get_sum function, try making to integer. You can do it like:

function get_sum(total, currentVal) {
    currentVal = parseInt(currentVal);
    total += currentVal;
    return total;
}


问:
How is this variable still NULL
I'm in the process of writing a CasperJS script to automate a search form and capture the subsequent page.  However, the search form goes to a loading splash page first until data arrives.  So i added the waitForSelector function which seems to be working for some of my pages, but others return the variable name as NULL.  How can that be if it is truly "waiting" for that element to be on the DOM?

```<code>casper.each(searchPages,function(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 2;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    month = currentTime.getMonth() + 3;
    var dateEnd = month + "/" + day + "/" + year;

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });

        this.waitForSelector('#destinationForPackage', function() {
            var name = casper.evaluate(function() {
                return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
            });
            if (name != "Going To"){
                if (name == null){
                    console.log("it's null");
                }else{
                    name = name.replace("/","_");
                    casper.capture('Captures/Searches/search_' + name + '.jpg');
                    console.log("Capturing search_" + name);
                }
            }
        },function(){
            console.log("Search page timed-out.");
        },20000);
    });
});
</code>```

答:
I was able to solve this by creating a recursive function if the element is still not available.  Now i'm having a memory issue though, new question here => CasperJS running out of memory</p>

```<code>casper.each(searchPages,function(casper,index){
    loadSearch(casper,index);
});

function loadSearch(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 2;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    month = currentTime.getMonth() + 3;
    var dateEnd = month + "/" + day + "/" + year;

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });

        this.waitForSelector('#destinationForPackage', function() {
            if (this.exists('#destinationForPackage')){
                var name = casper.evaluate(function() {
                    return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
                });
                if (name != "Going To"){
                    if (name == null){
                        console.log("it's null");
                    }else{
                        name = name.replace("/","_");
                        casper.capture('Captures/Searches/search_' + name + '.jpg');
                        console.log("Capturing search_" + name);
                    }
                }
            }else{
                console.log("Still doesn't exist...retry");
                loadSearch(casper,index);
            }

        },function(){
            console.log("Search page timed-out.");
        },20000);
    });
}
</code>```

Title: How is this variable still NULL

Body:
I'm in the process of writing a CasperJS script to automate a search form and capture the subsequent page.  However, the search form goes to a loading splash page first until data arrives.  So i added the waitForSelector function which seems to be working for some of my pages, but others return the variable name as NULL.  How can that be if it is truly "waiting" for that element to be on the DOM?

casper.each(searchPages,function(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 2;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    month = currentTime.getMonth() + 3;
    var dateEnd = month + "/" + day + "/" + year;

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });

        this.waitForSelector('#destinationForPackage', function() {
            var name = casper.evaluate(function() {
                return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
            });
            if (name != "Going To"){
                if (name == null){
                    console.log("it's null");
                }else{
                    name = name.replace("/","_");
                    casper.capture('Captures/Searches/search_' + name + '.jpg');
                    console.log("Capturing search_" + name);
                }
            }
        },function(){
            console.log("Search page timed-out.");
        },20000);
    });
});

Body:
I was able to solve this by creating a recursive function if the element is still not available.  Now i'm having a memory issue though, new question here => CasperJS running out of memory

casper.each(searchPages,function(casper,index){
    loadSearch(casper,index);
});

function loadSearch(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 2;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    month = currentTime.getMonth() + 3;
    var dateEnd = month + "/" + day + "/" + year;

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });

        this.waitForSelector('#destinationForPackage', function() {
            if (this.exists('#destinationForPackage')){
                var name = casper.evaluate(function() {
                    return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
                });
                if (name != "Going To"){
                    if (name == null){
                        console.log("it's null");
                    }else{
                        name = name.replace("/","_");
                        casper.capture('Captures/Searches/search_' + name + '.jpg');
                        console.log("Capturing search_" + name);
                    }
                }
            }else{
                console.log("Still doesn't exist...retry");
                loadSearch(casper,index);
            }

        },function(){
            console.log("Search page timed-out.");
        },20000);
    });
}


问:
PHP and MySQLi - Upload Multiple Image
I am planning to make an image galary using PHP with MySQL as a database.

I already make a multiple upload images using PHP but I got a problem. When I uploaded 8 images in database only show 1 row data. But in folder there are 8 images that I have upload.

Here is my code :

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>

<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
    for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
    {
        $filetmp = $_FILES["file_img"]["tmp_name"][$i];
        $filename = $_FILES["file_img"]["name"][$i];
        $filetype = $_FILES["file_img"]["type"][$i];
        $filepath = "uploads/".$filename;

    move_uploaded_file($filetmp,$filepath);

    $sql = "INSERT INTO files (file,path,type) VALUES ('$filename','$filepath','$filetype')";
    if($connect->query($sql) === TRUE) {
header("Location: a.php");
} else {
header("Location: a.php");
}
    }

    $connect->close();}
?>

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

Can someone help me ? Thanks for ur feedback :)

答:
After some code beautification of your snippet answer became obvious - you only get one new row in database, because in your for loop you redirect user to a.php right after inserting this row.
In other words your for loop will always perform one and only one step.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
</head>
<body>
    <form action="a.php" method="post" enctype="multipart/form-data">
        <input type="file" name="file_img[]" multiple>
        <input type="submit" name="btn_upload" value="Upload">
    </form>

    <?php
    include_once 'koneksi.php';

    if (isset($_POST['btn_upload'])) {
        for ($i = 0; $i < count($_FILES['file_img']['name']); $i++) {
            $filetmp = $_FILES["file_img"]["tmp_name"][$i];
            $filename = $_FILES["file_img"]["name"][$i];
            $filetype = $_FILES["file_img"]["type"][$i];
            $filepath = "uploads/".$filename;

            move_uploaded_file($filetmp, $filepath);

            $sql = "INSERT INTO files (file, path, type) VALUES ('$filename','$filepath','$filetype')";
            // #NOTICE: Read about SQL Injection and why above SQL is bad.

            // #SOLUTION: Place 1

            if ($connect->query($sql) === true) {
                header("Location: a.php");
                exit;  // #NOTICE: Always add `exit` after "header Location:"
            } else {
                header("Location: a.php");
                exit;  // #NOTICE: Always add `exit` after "header Location:"
            }
        }

        $connect->close();

        // #SOLUTION: Place 2
    }
    ?>
</body>
</html>
</code>```

Can you see it now?

Checkout link below! File [1] is your file after performing some cleaning. It's also contains two comments marked as #SOLUTION. Place 1 is the code you should move to Place 2. After moving you should also change if condition to check if all files were uploaded correctly.  File [2] on the other hand is edited by me with (probably) proper solution for your problem.

I hope I helped!

https://github.com/broiniac/stackoverflow/blob/master/44346949/

EDIT: @AdhershMNair:
I think that because of line if($connect->query($sql) === TRUE) { in your solution, data for last uploaded file will be inserted into database twice (once for last iteration in for loop and once for if statement).

Title: PHP and MySQLi - Upload Multiple Image

Body:
I am planning to make an image galary using PHP with MySQL as a database.

I already make a multiple upload images using PHP but I got a problem. When I uploaded 8 images in database only show 1 row data. But in folder there are 8 images that I have upload.

Here is my code :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>

<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
    for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
    {
        $filetmp = $_FILES["file_img"]["tmp_name"][$i];
        $filename = $_FILES["file_img"]["name"][$i];
        $filetype = $_FILES["file_img"]["type"][$i];
        $filepath = "uploads/".$filename;

    move_uploaded_file($filetmp,$filepath);

    $sql = "INSERT INTO files (file,path,type) VALUES ('$filename','$filepath','$filetype')";
    if($connect->query($sql) === TRUE) {
header("Location: a.php");
} else {
header("Location: a.php");
}
    }

    $connect->close();}
?>

Can someone help me ? Thanks for ur feedback :)

Body:
After some code beautification of your snippet answer became obvious - you only get one new row in database, because in your for loop you redirect user to a.php right after inserting this row.
In other words your for loop will always perform one and only one step.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
</head>
<body>
    <form action="a.php" method="post" enctype="multipart/form-data">
        <input type="file" name="file_img[]" multiple>
        <input type="submit" name="btn_upload" value="Upload">
    </form>

    <?php
    include_once 'koneksi.php';

    if (isset($_POST['btn_upload'])) {
        for ($i = 0; $i < count($_FILES['file_img']['name']); $i++) {
            $filetmp = $_FILES["file_img"]["tmp_name"][$i];
            $filename = $_FILES["file_img"]["name"][$i];
            $filetype = $_FILES["file_img"]["type"][$i];
            $filepath = "uploads/".$filename;

            move_uploaded_file($filetmp, $filepath);

            $sql = "INSERT INTO files (file, path, type) VALUES ('$filename','$filepath','$filetype')";
            // #NOTICE: Read about SQL Injection and why above SQL is bad.

            // #SOLUTION: Place 1

            if ($connect->query($sql) === true) {
                header("Location: a.php");
                exit;  // #NOTICE: Always add `exit` after "header Location:"
            } else {
                header("Location: a.php");
                exit;  // #NOTICE: Always add `exit` after "header Location:"
            }
        }

        $connect->close();

        // #SOLUTION: Place 2
    }
    ?>
</body>
</html>

Can you see it now?

Checkout link below! File [1] is your file after performing some cleaning. It's also contains two comments marked as #SOLUTION. Place 1 is the code you should move to Place 2. After moving you should also change if condition to check if all files were uploaded correctly.  File [2] on the other hand is edited by me with (probably) proper solution for your problem.

I hope I helped!

https://github.com/broiniac/stackoverflow/blob/master/44346949/

EDIT: @AdhershMNair:
I think that because of line if($connect->query($sql) === TRUE) { in your solution, data for last uploaded file will be inserted into database twice (once for last iteration in for loop and once for if statement).


问:
JTable is resizing my column widths
I have created a JTreeTable where the TreeCellRenderer is a JTable. This allows me to have different TableColumnModels for each row. Siblings of the JTree share a TableColumnModel. It works great. I can select a row and show a different set of columns without actually changing the the data in the other rows even at different levels.

I have a problem though where when select a different row the JTable is changing my TableColumns width and setting it to the preferred size. So the effect is that dragging the width of one column and then selecting a different row set it back to the preferred size.

I have tried a number of things to fix this, including adding a TableColumnModelListener and when I change the width I set the preferred size of the column. This doesn't work because the JTable is setting the preferred size to 15 after I change it.

I have traced the code back to what is causing this. It is the JTable.doLayout() method causing my grief. That method is calling the private method setWidthsFromPreferredWidths(...). This method is what is setting my TableColumn widths.

I tried overriding the doLayout() method since it is public but I could not make the call to super.doLayout() when I am already overriding the method. Not calling that causes some very weird UI issues as you could imagine. I also tried casting this to the superclass of JTable which is JComponent but I end up with a stack overflow error. This does not feel like the right solution here anyway.

What I think is happening is that because my JTable is inside of a panel as the renderer of a tree cell instead of inside of a scrollpane, that something is going wrong with the layout.I don't know for sure though. Below is the code inside of the private method I referenced above:

```<code>private void setWidthsFromPreferredWidths(final boolean inverse) {
    int totalWidth     = getWidth();
    int totalPreferred = getPreferredSize().width;
    int target = !inverse ? totalWidth : totalPreferred;

    final TableColumnModel cm = columnModel;
    Resizable3 r = new Resizable3() {
        public int  getElementCount()      { return cm.getColumnCount(); }
        public int  getLowerBoundAt(int i) { return cm.getColumn(i).getMinWidth(); }
        public int  getUpperBoundAt(int i) { return cm.getColumn(i).getMaxWidth(); }
        public int  getMidPointAt(int i)  {
            if (!inverse) {
                return cm.getColumn(i).getPreferredWidth();
            }
            else {
                return cm.getColumn(i).getWidth();
            }
        }
        public void setSizeAt(int s, int i) {
            if (!inverse) {
                cm.getColumn(i).setWidth(s);
            }
            else {
                cm.getColumn(i).setPreferredWidth(s);
            }
        }
    };

    adjustSizes(target, r, inverse);
}
</code>```

Looking at the code, I think what's happening is that the getWidth() method is causing the JTable to want to resize the columns to the preferredsize because it thinks it doesn't have enough room. I tried just copy pasting this method locally but since there are private methods involved and it kept getting deeper and deeper I stopped that. The intention was to try to debug why it is choose to adjust the width. If I can address the root cause, that may be the best solution for this.

The JTree itself is inside of JScrollPane. The JTableHeader is set to the ViewPortColumnHeaderView. Below are 2 images where I am selecting different rows. Ignore the header alignment, I already have a solution for that just did not implement it entirely yet.

Any thoughts on the problem would be greatly appreciated. Also happy to post any code you think might be useful if you think it will help.

答: So after a lot of modifications and investigation, It was due not having a scrollpane for the tables. I didn't do that originally because it put a funky border around it and setting border to null did not work. What I had to do was set an empty border. </p>

Title: JTable is resizing my column widths

Body:
I have created a JTreeTable where the TreeCellRenderer is a JTable. This allows me to have different TableColumnModels for each row. Siblings of the JTree share a TableColumnModel. It works great. I can select a row and show a different set of columns without actually changing the the data in the other rows even at different levels.

I have a problem though where when select a different row the JTable is changing my TableColumns width and setting it to the preferred size. So the effect is that dragging the width of one column and then selecting a different row set it back to the preferred size.

I have tried a number of things to fix this, including adding a TableColumnModelListener and when I change the width I set the preferred size of the column. This doesn't work because the JTable is setting the preferred size to 15 after I change it.

I have traced the code back to what is causing this. It is the JTable.doLayout() method causing my grief. That method is calling the private method setWidthsFromPreferredWidths(...). This method is what is setting my TableColumn widths.

I tried overriding the doLayout() method since it is public but I could not make the call to super.doLayout() when I am already overriding the method. Not calling that causes some very weird UI issues as you could imagine. I also tried casting this to the superclass of JTable which is JComponent but I end up with a stack overflow error. This does not feel like the right solution here anyway.

What I think is happening is that because my JTable is inside of a panel as the renderer of a tree cell instead of inside of a scrollpane, that something is going wrong with the layout.I don't know for sure though. Below is the code inside of the private method I referenced above:

private void setWidthsFromPreferredWidths(final boolean inverse) {
    int totalWidth     = getWidth();
    int totalPreferred = getPreferredSize().width;
    int target = !inverse ? totalWidth : totalPreferred;

    final TableColumnModel cm = columnModel;
    Resizable3 r = new Resizable3() {
        public int  getElementCount()      { return cm.getColumnCount(); }
        public int  getLowerBoundAt(int i) { return cm.getColumn(i).getMinWidth(); }
        public int  getUpperBoundAt(int i) { return cm.getColumn(i).getMaxWidth(); }
        public int  getMidPointAt(int i)  {
            if (!inverse) {
                return cm.getColumn(i).getPreferredWidth();
            }
            else {
                return cm.getColumn(i).getWidth();
            }
        }
        public void setSizeAt(int s, int i) {
            if (!inverse) {
                cm.getColumn(i).setWidth(s);
            }
            else {
                cm.getColumn(i).setPreferredWidth(s);
            }
        }
    };

    adjustSizes(target, r, inverse);
}

Looking at the code, I think what's happening is that the getWidth() method is causing the JTable to want to resize the columns to the preferredsize because it thinks it doesn't have enough room. I tried just copy pasting this method locally but since there are private methods involved and it kept getting deeper and deeper I stopped that. The intention was to try to debug why it is choose to adjust the width. If I can address the root cause, that may be the best solution for this.

The JTree itself is inside of JScrollPane. The JTableHeader is set to the ViewPortColumnHeaderView. Below are 2 images where I am selecting different rows. Ignore the header alignment, I already have a solution for that just did not implement it entirely yet.

Any thoughts on the problem would be greatly appreciated. Also happy to post any code you think might be useful if you think it will help.


问:
Simple URI and local path use in MediaPlayer-javaFX
I have the following code to display the spectrum of audio.But it uses URI.But how to use simple paths like C:/abc/asas.wav ...or something?Any idea?
It gives me Exception when i use local paths:

```<code>Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
        at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source)
        at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:722)
</code>```

Code:

```<code>package chartaudiobar;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.media.AudioSpectrumListener;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

public class ChartAudioBar extends Application {

    private XYChart.Data<String, Number>[] series1Data;
    private AudioSpectrumListener audioSpectrumListener;

    private static final String AUDIO_URI = System.getProperty("demo.audio.url","http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv");
    private static MediaPlayer audioMediaPlayer;
    private static final boolean PLAY_AUDIO = Boolean.parseBoolean(System.getProperty("demo.play.audio","true"));

    private void init(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setScene(new Scene(root));
        root.getChildren().add(createChart());
        audioSpectrumListener = new AudioSpectrumListener() {
            @Override public void spectrumDataUpdate(double timestamp, double duration,
                    float[] magnitudes, float[] phases) {
                for (int i = 0; i < series1Data.length; i++) {
                    series1Data[i].setYValue(magnitudes[i] + 60);
                }
            }
        };
    }

    public void play() {
        this.startAudio();
    }

    @Override public void stop() {
        this.stopAudio();
    }

    protected BarChart<String, Number> createChart() {
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis(0,50,10);
        final BarChart<String,Number> bc = new BarChart<String,Number>(xAxis,yAxis);
        bc.setId("barAudioDemo");
        bc.setLegendVisible(false);
        bc.setAnimated(false);
        bc.setBarGap(0);
        bc.setCategoryGap(1);
        bc.setVerticalGridLinesVisible(false);
        // setup chart
        bc.setTitle("Live Audio Spectrum Data");
        xAxis.setLabel("Frequency Bands");
        yAxis.setLabel("Magnitudes");
        yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis,null,"dB"));
        // add starting data
        XYChart.Series<String,Number> series1 = new XYChart.Series<String,Number>();
        series1.setName("Data Series 1");
        //noinspection unchecked
        series1Data = new XYChart.Data[128];
        String[] categories = new String[128];
        for (int i=0; i<series1Data.length; i++) {
            categories[i] = Integer.toString(i+1);
            series1Data[i] = new XYChart.Data<String,Number>(categories[i],50);
            series1.getData().add(series1Data[i]);
        }
        bc.getData().add(series1);
        return bc;
    }

     private void startAudio() {
        if (PLAY_AUDIO) {
            getAudioMediaPlayer().setAudioSpectrumListener(audioSpectrumListener);
            getAudioMediaPlayer().play();
        }
    }

    private void stopAudio() {
        if (getAudioMediaPlayer().getAudioSpectrumListener() == audioSpectrumListener) {
            getAudioMediaPlayer().pause();
        }
    }

    private static MediaPlayer getAudioMediaPlayer() {
        if (audioMediaPlayer == null) {
            Media audioMedia = new Media(AUDIO_URI);
            audioMediaPlayer = new MediaPlayer(audioMedia);
        }
        return audioMediaPlayer;
    }

    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
        play();
    }
    public static void main(String[] args) { launch(args); }
}
</code>```

So how to use local paths here?

答:
It’s 4 years after Jyoti Shaw posted this question, how to use a local music file in class ChartAudioBar. Wafu has the answer on his webpage https://osu.ppy.sh/forum/p/4629060  Look about halfway down on the page, under his heading “Frequency spectrum” and click on “Code” to see the source code.
Wafu’s solution is similar to that of Sam de Meyer in his answer above.

//We don't need this line, because we need to use a local music file.

//private static final String AUDIO_URI = System.getProperty("demo.audio.url","http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv");

```<code>    private static MediaPlayer audioMediaPlayer;
</code>```

//We don't need this as well as it's equally useless as previous thing.

//private static final boolean PLAY_AUDIO = Boolean.parseBoolean(System.getProperty("demo.play.audio","true"));

//We anyway need output of the default chart, so let's say we'll put it to file data.txt, hence the 'import java.io.File' needs to be added to imports.

```<code>   private static File filedata = new File("data.txt");
</code>```

// *****************************************************************************

```<code>    private static MediaPlayer getAudioMediaPlayer() {
        if (audioMediaPlayer == null) {
</code>```

//We need code below, but I commented it anyway to show the difference, we need a local file, so this won't work.

//Media audioMedia = new Media(AUDIO_URI);

//So we create a local file, for example mp3.mp3 in current folder, it can be anything you want.

//File audiofile = new File("mp3.mp3");

```<code>        File audiofile = new File("C:/music/SummerMix.mp3");
</code>```

//Now we need to make audioMedia as it was previously - So it needs to be URI, which .toURI() ensures easily, but as well as that, it needs a string URI, so .toString() will ensure this.

```<code>        Media audioMedia = new Media(audiofile.toURI().toString());
        audioMediaPlayer = new MediaPlayer(audioMedia);
     }
        return audioMediaPlayer;
     }
</code>```

Body:
I have the following code to display the spectrum of audio.But it uses URI.But how to use simple paths like C:/abc/asas.wav ...or something?Any idea?
It gives me Exception when i use local paths:

Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
        at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source)
        at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:722)

Code:

package chartaudiobar;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.media.AudioSpectrumListener;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

public class ChartAudioBar extends Application {

    private XYChart.Data<String, Number>[] series1Data;
    private AudioSpectrumListener audioSpectrumListener;

    private static final String AUDIO_URI = System.getProperty("demo.audio.url","http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv");
    private static MediaPlayer audioMediaPlayer;
    private static final boolean PLAY_AUDIO = Boolean.parseBoolean(System.getProperty("demo.play.audio","true"));

    private void init(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setScene(new Scene(root));
        root.getChildren().add(createChart());
        audioSpectrumListener = new AudioSpectrumListener() {
            @Override public void spectrumDataUpdate(double timestamp, double duration,
                    float[] magnitudes, float[] phases) {
                for (int i = 0; i < series1Data.length; i++) {
                    series1Data[i].setYValue(magnitudes[i] + 60);
                }
            }
        };
    }

    public void play() {
        this.startAudio();
    }

    @Override public void stop() {
        this.stopAudio();
    }

    protected BarChart<String, Number> createChart() {
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis(0,50,10);
        final BarChart<String,Number> bc = new BarChart<String,Number>(xAxis,yAxis);
        bc.setId("barAudioDemo");
        bc.setLegendVisible(false);
        bc.setAnimated(false);
        bc.setBarGap(0);
        bc.setCategoryGap(1);
        bc.setVerticalGridLinesVisible(false);
        // setup chart
        bc.setTitle("Live Audio Spectrum Data");
        xAxis.setLabel("Frequency Bands");
        yAxis.setLabel("Magnitudes");
        yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis,null,"dB"));
        // add starting data
        XYChart.Series<String,Number> series1 = new XYChart.Series<String,Number>();
        series1.setName("Data Series 1");
        //noinspection unchecked
        series1Data = new XYChart.Data[128];
        String[] categories = new String[128];
        for (int i=0; i<series1Data.length; i++) {
            categories[i] = Integer.toString(i+1);
            series1Data[i] = new XYChart.Data<String,Number>(categories[i],50);
            series1.getData().add(series1Data[i]);
        }
        bc.getData().add(series1);
        return bc;
    }

     private void startAudio() {
        if (PLAY_AUDIO) {
            getAudioMediaPlayer().setAudioSpectrumListener(audioSpectrumListener);
            getAudioMediaPlayer().play();
        }
    }

    private void stopAudio() {
        if (getAudioMediaPlayer().getAudioSpectrumListener() == audioSpectrumListener) {
            getAudioMediaPlayer().pause();
        }
    }

    private static MediaPlayer getAudioMediaPlayer() {
        if (audioMediaPlayer == null) {
            Media audioMedia = new Media(AUDIO_URI);
            audioMediaPlayer = new MediaPlayer(audioMedia);
        }
        return audioMediaPlayer;
    }

    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
        play();
    }
    public static void main(String[] args) { launch(args); }
}

So how to use local paths here?

Body:
It’s 4 years after Jyoti Shaw posted this question, how to use a local music file in class ChartAudioBar. Wafu has the answer on his webpage https://osu.ppy.sh/forum/p/4629060  Look about halfway down on the page, under his heading “Frequency spectrum” and click on “Code” to see the source code.
Wafu’s solution is similar to that of Sam de Meyer in his answer above.

//We don't need this line, because we need to use a local music file.

//private static final String AUDIO_URI = System.getProperty("demo.audio.url","http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv");

    private static MediaPlayer audioMediaPlayer;

//We don't need this as well as it's equally useless as previous thing.

//private static final boolean PLAY_AUDIO = Boolean.parseBoolean(System.getProperty("demo.play.audio","true"));

//We anyway need output of the default chart, so let's say we'll put it to file data.txt, hence the 'import java.io.File' needs to be added to imports.

   private static File filedata = new File("data.txt");

// *****************************************************************************

    private static MediaPlayer getAudioMediaPlayer() {
        if (audioMediaPlayer == null) {

//We need code below, but I commented it anyway to show the difference, we need a local file, so this won't work.

//Media audioMedia = new Media(AUDIO_URI);

//So we create a local file, for example mp3.mp3 in current folder, it can be anything you want.

//File audiofile = new File("mp3.mp3");

        File audiofile = new File("C:/music/SummerMix.mp3");

//Now we need to make audioMedia as it was previously - So it needs to be URI, which .toURI() ensures easily, but as well as that, it needs a string URI, so .toString() will ensure this.

        Media audioMedia = new Media(audiofile.toURI().toString());
        audioMediaPlayer = new MediaPlayer(audioMedia);
     }
        return audioMediaPlayer;
     }


问:
How do I write this function of this class?
I'm a beginner in C++ so I'm not sure how to make the question more detail. I'm sorry.
So my professor gave me this header file and told me to write the function definition:

```<code>    class Move
    { private:
    double x;
    double y;
    public:
    Move( double a = 0, double b = 0 ); // sets x_, y_ to a, b

    void showmove(Move number) const; // shows current x_, y_ values

    // add : Move --> Move
    // to add x_ of input object to x_ of invoking object to get new x_,
    // to add y_ of input object to y_ of invoking object to get new y_,
    // to create new object initialized to new values and return it
    Move add( const Move &m ) const;

    void reset( double a = 0, double b = 0 ); // resets x, y to a, b
    };
</code>```

I don't understand the function Move add( const Move &m ) const;. Usually an add function look like this int add( int a, int b) . So combine 2 inputs together to make 1 output. But the function Move add only has one input. I don't know how to write a definition for it. I asked my friends and we come up with something like A.add(B), but I'm not sure if it makes any sense.
Thank you for reading and sorry for my English

答:
The definition should be

```<code>Move add(const Move& m) {
  return Move(this->x+m.x, this->y+m.y);
}
</code>```

It wants you to use m's attributes to get the results directly with only one parameter (reference to a Move object) instead of two  (coordinates) .

Indeed, to invoke this method :

```<code>Move A/*sthg*/;
Move B/*sthg*/;
Move C = A.add(B);
</code>```

Body:
I'm a beginner in C++ so I'm not sure how to make the question more detail. I'm sorry.
So my professor gave me this header file and told me to write the function definition:

    class Move
    { private:
    double x;
    double y;
    public:
    Move( double a = 0, double b = 0 ); // sets x_, y_ to a, b

    void showmove(Move number) const; // shows current x_, y_ values

    // add : Move --> Move
    // to add x_ of input object to x_ of invoking object to get new x_,
    // to add y_ of input object to y_ of invoking object to get new y_,
    // to create new object initialized to new values and return it
    Move add( const Move &m ) const;

    void reset( double a = 0, double b = 0 ); // resets x, y to a, b
    };

I don't understand the function Move add( const Move &m ) const;. Usually an add function look like this int add( int a, int b) . So combine 2 inputs together to make 1 output. But the function Move add only has one input. I don't know how to write a definition for it. I asked my friends and we come up with something like A.add(B), but I'm not sure if it makes any sense.
Thank you for reading and sorry for my English

Body:
The definition should be

Move add(const Move& m) {
  return Move(this->x+m.x, this->y+m.y);
}

It wants you to use m's attributes to get the results directly with only one parameter (reference to a Move object) instead of two  (coordinates) .

Indeed, to invoke this method :

Move A/*sthg*/;
Move B/*sthg*/;
Move C = A.add(B);


问:
Transition doesn't work on hover off
i have problem. I wanted to transform div's background when hovering on, it works fine except when i put mouse off the div, the transition doesn't work then. How can i fix this?

When i put mouse off, it instantly changes to original flag.

```<code>$("#flag").hover(function(){
 $(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
'background-size':'cover',
'transition':'1 s'
 });
}, function(){
$(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
'background-size':'cover',
'transition':'1 s'
});
})
</code>```

答:
try using jQuery stop() like so:

$("#flag").hover(function(){
     $(this).animate({
         'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
         'background-size':'cover'
  }, 1000);
}, function(){
     $(this).stop(true,false).animate({
         'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
         'background-size':'cover'
     }, 1000);
})

this should interrupt the animation queue and reset it, ready for the next one.

Title: Transition doesn't work on hover off

Body:
i have problem. I wanted to transform div's background when hovering on, it works fine except when i put mouse off the div, the transition doesn't work then. How can i fix this?

When i put mouse off, it instantly changes to original flag.

$("#flag").hover(function(){
 $(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
'background-size':'cover',
'transition':'1 s'
 });
}, function(){
$(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
'background-size':'cover',
'transition':'1 s'
});
})


问:
How to build flexible web forms in ASP.NET
I'm using asp.net and I need to build an application where we can easily create forms without recreating the database, and preferably without changing the create/read/update/delete queries. The goal is to allow customers to create their own forms with dropdowns, textboxes, checkboxes, even many-to-one relationship to another simple form (that's stretching it). The user does not have to be able to create the forms themselves, but I don't want to be adding tables, fields, queries, web page, etc. each time a new form is requested/modified.

2 questions:
1) How do I structure a flexible database to do this (in SQL Server)? I can think of two ways: a) Create a table for each datatype (int, varchar(x), smalldatetime, bit, etc). This would be very difficult to create the adequate queries. b) Create the form table with lots of extra fields and various datatypes in case the user needs 5 integers or 5 date fields. This seems the easiest, but is probably pretty inefficient use of space.

2) How do I build the forms? I thought about creating an xml sheet that had the validations, data type, control to display, etc. as a list. Then I would parse through the xml to build the form on the fly. Probably using css to do the layout (that would have to be manual, which is ok).

Is there a  better/best way? Is there something out there that I could look at to get ideas? Any help is much appreciated.

答:
We created a forms system like the one you're describing with a schema very similar to the one at the end of Tim's post. It has been pretty complicated, and we really had to wrestle with the standard WebForms controls like the DetailsView and GridView to make them be able to perform CRUD operations on groups of answers. They're used to binding straight to properties on an object, and we're forcing them to look up a field ID in a dictionary first. They don't like it. You may want to consider using MVC.

One tricky question is how to store the answers. We ended up using a table that's keyed on FieldId, InstanceId (for example, if 10 people are filling out your form, there are 10 instances), and RowNumber (because we support multi-row forms for things like employment history). Instead of doing it this way, I would recommend making your AnswerRow a first-class concept with its own table tied to an Instance, and having the answers be linked to the AnswerRow and Field.

In order to support different value types, we had to create multiple answer fields on our answer table (AnswerChar, AnswerDate, AnswerInt, AnswerDecimal). Each of these maps to one or more Field Types (Date, Time, Number, etc.). Each Field Type has its own logic to represent the value in the UI, and put the value into the appropriate property on our answer objects.

All in all, it's been a lot of work. It's worth it for us, since this is the crux of the product, but you will definitely want to keep the cost in mind before embarking on a project like this.

ContentLicense: CC BY-SA 2.5


问:
Pass array of CimInstance to CimMethod
I am working with WMI API through Cim cmdlets. The problem is that I can't figure out how to pass wmi object to wmi method that accepts array of wmi objects.

Here are method parameters definition:

```<code>Name                                            CimType Qualifiers
----                                            ------- ----------
Path                                             String {ID, in}
Permissions                               InstanceArray {EmbeddedInstance, ID, in}
ResetChildren                                   Boolean {ID, in}
</code>```

Path and ResetChildren are simple parameters. They accepts simple values like "/path" and $true respectively. But I have troubles with Permissions parameter.

Here is my code

```<code>#Acquiring object that I want to pass to method
$group = Get-CimInstance -Namespace "root\VisualSVN" -ClassName VisualSVN_Group -Filter "Name='Readers'"

#Acquiring object which method will be called
$repositories = Get-CimInstance -Namespace "root\VisualSVN" -ClassName VisualSVN_Repository

#Preparing method arguments
$args = @{
    Path = "/";
    Permissions = @($group[0]); #Trouble here
    ResetChildren = $true
}

#Invoking method with arguments
Invoke-CimMethod -InputObject ($repositories[0]) -MethodName SetSecurity -Arguments $args
</code>```

Execution of this code will result in error:

```<code>Invoke-CimMethod : Unable to cast object of type 'Microsoft.Management.Infrastructure.CimInstance' to type 'M
icrosoft.Management.Infrastructure.Native.InstanceHandle'.
Parameter name: value
At C:\somepath\script1.ps1:11 char:1
+ Invoke-CimMethod -InputObject ($repositories[0]) -MethodName SetSecurity -Argume ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-CimMethod], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.Management.Infrastructure.CimCmdlets.Invoke
   CimMethodCommand
</code>```

If you change code

```<code>Permissions = @($group[0]); #Trouble here
</code>```

To code

```<code>Permissions = $group; #Trouble here
</code>```

Then error message will also change:

```<code>Invoke-CimMethod : Unable to cast object of type 'Microsoft.Management.Infrastructure.Native.InstanceHandle'
to type 'System.Collections.IList'.
Parameter name: value
At C:\somepath\script1.ps1:11 char:1
+ Invoke-CimMethod -InputObject ($repositories[0]) -MethodName SetSecurity -Argume ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-CimMethod], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.Management.Infrastructure.CimCmdlets.Invoke
   CimMethodCommand
</code>```

Any ideas how to pass $group to method properly?

答:
I had exactly same problem with VisualSVN_Repository::SetSecurity method.

When working with CIM method arguments, you must cast ANY array arguments to [CimInstance[]].

For example, this worked for me:

```<code>$Everyone = Get-CimInstance -Namespace root/VisualSVN -ClassName VisualSVN_Everyone
# Grant Everyone a Read/Write access:
$AccessRule = New-CimInstance -Namespace root/VisualSVN -ClassName VisualSVN_PermissionEntry -ClientOnly -Property @{ Account = $Everyone; AccessLevel = [UInt32]2 }
$SvnRepo = Get-CimInstance -Namespace root/VisualSVN -ClassName VisualSVN_Repository -Filter "Name='MY_REPOSITORY_NAME'"

Invoke-CimMethod -InputObject $SvnRepo -MethodName SetSecurity -Arguments @{
    Path = '/';
    Permissions = [CimInstance[]]$AccessRule;
    ResetChildren = $true
} | Out-Null
</code>```

You must cast array argument to [CimInstance[]] even when it is just a single item.

P.S.: Be careful with Ref array arguments too: you must first cast it to [CimInstance[]] and then to [ref[]]. For example, when calling VisualSVN_Group::Create method:

```<code>[CimInstance[]] $SvnUsers = [CimInstance[]]($ArrayOf_VisualSVN_User_Objects)

Invoke-CimMethod -ClassName VisualSVN_Group -Namespace root/VisualSVN -MethodName Create -Arguments @{
    Members = [ref[]]$SvnUsers;
    Name = 'MY_NEW_GROUP_NAME'
} | Out-Null
</code>```

See also: Tip#5: Passing ref and embedded instances on PowerShell Blog.

Title: Pass array of CimInstance to CimMethod

Body:
I am working with WMI API through Cim cmdlets. The problem is that I can't figure out how to pass wmi object to wmi method that accepts array of wmi objects.

Here are method parameters definition:

Name                                            CimType Qualifiers
----                                            ------- ----------
Path                                             String {ID, in}
Permissions                               InstanceArray {EmbeddedInstance, ID, in}
ResetChildren                                   Boolean {ID, in}

Path and ResetChildren are simple parameters. They accepts simple values like "/path" and $true respectively. But I have troubles with Permissions parameter.

Here is my code

#Acquiring object that I want to pass to method
$group = Get-CimInstance -Namespace "root\VisualSVN" -ClassName VisualSVN_Group -Filter "Name='Readers'"

#Acquiring object which method will be called
$repositories = Get-CimInstance -Namespace "root\VisualSVN" -ClassName VisualSVN_Repository

#Preparing method arguments
$args = @{
    Path = "/";
    Permissions = @($group[0]); #Trouble here
    ResetChildren = $true
}

#Invoking method with arguments
Invoke-CimMethod -InputObject ($repositories[0]) -MethodName SetSecurity -Arguments $args

Execution of this code will result in error:

Invoke-CimMethod : Unable to cast object of type 'Microsoft.Management.Infrastructure.CimInstance' to type 'M
icrosoft.Management.Infrastructure.Native.InstanceHandle'.
Parameter name: value
At C:\somepath\script1.ps1:11 char:1
+ Invoke-CimMethod -InputObject ($repositories[0]) -MethodName SetSecurity -Argume ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-CimMethod], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.Management.Infrastructure.CimCmdlets.Invoke
   CimMethodCommand

If you change code

Permissions = @($group[0]); #Trouble here

To code

Permissions = $group; #Trouble here

Then error message will also change:

Invoke-CimMethod : Unable to cast object of type 'Microsoft.Management.Infrastructure.Native.InstanceHandle'
to type 'System.Collections.IList'.
Parameter name: value
At C:\somepath\script1.ps1:11 char:1
+ Invoke-CimMethod -InputObject ($repositories[0]) -MethodName SetSecurity -Argume ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-CimMethod], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.Management.Infrastructure.CimCmdlets.Invoke
   CimMethodCommand

Any ideas how to pass $group to method properly?

Body:
I had exactly same problem with VisualSVN_Repository::SetSecurity method.

When working with CIM method arguments, you must cast ANY array arguments to [CimInstance[]].

For example, this worked for me:

$Everyone = Get-CimInstance -Namespace root/VisualSVN -ClassName VisualSVN_Everyone
# Grant Everyone a Read/Write access:
$AccessRule = New-CimInstance -Namespace root/VisualSVN -ClassName VisualSVN_PermissionEntry -ClientOnly -Property @{ Account = $Everyone; AccessLevel = [UInt32]2 }
$SvnRepo = Get-CimInstance -Namespace root/VisualSVN -ClassName VisualSVN_Repository -Filter "Name='MY_REPOSITORY_NAME'"

Invoke-CimMethod -InputObject $SvnRepo -MethodName SetSecurity -Arguments @{
    Path = '/';
    Permissions = [CimInstance[]]$AccessRule;
    ResetChildren = $true
} | Out-Null

You must cast array argument to [CimInstance[]] even when it is just a single item.

P.S.: Be careful with Ref array arguments too: you must first cast it to [CimInstance[]] and then to [ref[]]. For example, when calling VisualSVN_Group::Create method:

[CimInstance[]] $SvnUsers = [CimInstance[]]($ArrayOf_VisualSVN_User_Objects)

Invoke-CimMethod -ClassName VisualSVN_Group -Namespace root/VisualSVN -MethodName Create -Arguments @{
    Members = [ref[]]$SvnUsers;
    Name = 'MY_NEW_GROUP_NAME'
} | Out-Null

See also: Tip#5: Passing ref and embedded instances on PowerShell Blog.

ContentLicense: CC BY-SA 4.0


问:
MKMapView centerCoordinate not returning proper values
In my app, I am saving coordinates from an MKMapView into a property list. After the user hits "save" I set the center coordinate of the selection view to that on the main view, and then save the mapView.centerCoodinate.latitude and longitude into a pList. However, this gives me a value like "1078114215" which the map says is not a vail coordinate. What am I doing wrong?</p>

答: Saving a pointer instead of the two floats in the coordinate? Not saving as a float?</p>


问:
Socket IO Won't work on public IP, Works fine localhost
So I am using socket io and I have successfully deployed the app on localhost.

To connect client side, I am using :

```<code>var socket = io.connect(window.location.origin + ":3333");
</code>```

for scalability.
Server side I am using

```<code>var express = require("express"),
app = express(),
http = require("http"),
server = http.createServer(app),
io = require("socket.io").listen(server),
request = require("request");

server.listen(3333);
io.sockets.on("connection", function(socket) {
...
});
</code>```

and I have verified my app is up an running on the server by performing an nmap on :3333.

But I keep getting ERR_CONNECTION_TIMED_OUT on the client.

Any suggestions?

答:
The solution was to add rules to the firewall on the server for the port:</p>

```<code>sudo iptables -I INPUT -p tcp --dport 3333 -m state --state NEW -j ACCEPT
</code>```

Body:
So I am using socket io and I have successfully deployed the app on localhost.

To connect client side, I am using :

var socket = io.connect(window.location.origin + ":3333");

for scalability.
Server side I am using

var express = require("express"),
app = express(),
http = require("http"),
server = http.createServer(app),
io = require("socket.io").listen(server),
request = require("request");

server.listen(3333);
io.sockets.on("connection", function(socket) {
...
});

and I have verified my app is up an running on the server by performing an nmap on :3333.

But I keep getting ERR_CONNECTION_TIMED_OUT on the client.

Any suggestions?

Body:
The solution was to add rules to the firewall on the server for the port:

sudo iptables -I INPUT -p tcp --dport 3333 -m state --state NEW -j ACCEPT


问:
printing blanks instead of NA's when using formattable in R
Consider the example data.frame

```<code>df <- data.frame(
  id = 1:4,
  name = c("Bob", "Ashley", "James", "David"),
  age = c(48, NA, 40, 28),
  test1_score = c(18.9, 19.5, NA, 12.9),
  stringsAsFactors = FALSE)
</code>```

I'm using the R package formattable to make a pretty table.

```<code>library(formattable)
formattable(df, list(
age = color_tile("white", "orange"),
test1_score = color_bar("pink", 'proportion', 0.2)
))
</code>```

It used to be that NA's were automatically not printed, and a blank was printed instead. It seems like this is no longer the default, but I would still like to print a blank for the NA. Replacing NA like this works:

```<code>df[is.na(df)]=''
formattable(df, list(
  age = color_tile("white", "orange"),
  test1_score = color_bar("pink", 'proportion', 0.2)
))
</code>```

However if I try to format one of the columns to force it to have 2 decimal places, the pesky NA's return:

```<code>df$age = digits(df$age, digits=2)
formattable(df, list(
age = color_tile("white", "orange"),
test1_score = color_bar("pink", 'proportion', 0.2)
))
</code>```

If I remove the NA again, the NA goes away, but so do the decimal places

```<code>df[is.na(df)] = ''
formattable(df, list(
age = color_tile("white", "orange"),
test1_score = color_bar("pink", 'proportion', 0.2)
))
</code>```

I believe the reason is that digits converts df$age to a formattable numeric object and creates the NA, and df[is.na(df)] = '' converts df$age to a formattable character object:

```<code>> df$age = digits(df$age, digits=2)
> df$age
[1] 48.00  NA   40.00 28.00
> class(df$age)
[1] "formattable" "numeric"
> df[is.na(df)] = ''
> df$age
[1] "48" "  " "40" "28"
> class(df$age)
[1] "formattable" "character"
</code>```

Any ideas on a solution?

Ultimately I'd also like to use this with a filtered data.frame, where I use the code from Filtering dataframes with formattable to ensure that the color scale stays the same when filtering the data.frame:

```<code>df$age = digits(df$age, digits=2)
  subset_df <- function(m) {
    formattable(df[m, ], list(
      age = x ~ color_tile("white", "orange")(df$age)[m],
      test1_score = x ~ color_bar("pink", 'proportion', 0.2)(df$test1_score)[m],
      test2_score = x ~ color_bar("pink", 'proportion', 0.2)(df$test2_score)[m]
    ))
  }

subset_df(1:3)
</code>```

The problem doesn't seem to be with this code though.

答:
You could use the sprintf function to format the numeric columns as strings with the desired number of decimal places. In the code below, sprintf converts NA to the string "NA", which we then convert to an empty string.

```<code># Function to convert numeric values to strings with a given number of
#  decimal places, and convert NA to empty string
fnc = function(var, decimal.places) {
  var = sprintf(paste0("%1.",decimal.places,"f"), var)
  var[var=="NA"] = ""
  var
}

# Select the columns we want to reformat
vars = c('age', 'test1_score')

# Apply the function to the desired columns with the desired number of decimal places
df[ , vars] = mapply(fnc, df[ ,vars], 2:3)

formattable(df, list(
  age = color_tile("white", "orange"),
  test1_score = color_bar("pink", 'proportion', 0.2)
))
</code>```

Body:
Consider the example data.frame

df <- data.frame(
  id = 1:4,
  name = c("Bob", "Ashley", "James", "David"),
  age = c(48, NA, 40, 28),
  test1_score = c(18.9, 19.5, NA, 12.9),
  stringsAsFactors = FALSE)

I'm using the R package formattable to make a pretty table.

library(formattable)
formattable(df, list(
age = color_tile("white", "orange"),
test1_score = color_bar("pink", 'proportion', 0.2)
))

It used to be that NA's were automatically not printed, and a blank was printed instead. It seems like this is no longer the default, but I would still like to print a blank for the NA. Replacing NA like this works:

df[is.na(df)]=''
formattable(df, list(
  age = color_tile("white", "orange"),
  test1_score = color_bar("pink", 'proportion', 0.2)
))

However if I try to format one of the columns to force it to have 2 decimal places, the pesky NA's return:

df$age = digits(df$age, digits=2)
formattable(df, list(
age = color_tile("white", "orange"),
test1_score = color_bar("pink", 'proportion', 0.2)
))

If I remove the NA again, the NA goes away, but so do the decimal places

df[is.na(df)] = ''
formattable(df, list(
age = color_tile("white", "orange"),
test1_score = color_bar("pink", 'proportion', 0.2)
))

I believe the reason is that digits converts df$age to a formattable numeric object and creates the NA, and df[is.na(df)] = '' converts df$age to a formattable character object:

> df$age = digits(df$age, digits=2)
> df$age
[1] 48.00  NA   40.00 28.00
> class(df$age)
[1] "formattable" "numeric"
> df[is.na(df)] = ''
> df$age
[1] "48" "  " "40" "28"
> class(df$age)
[1] "formattable" "character"

Any ideas on a solution?

Ultimately I'd also like to use this with a filtered data.frame, where I use the code from Filtering dataframes with formattable to ensure that the color scale stays the same when filtering the data.frame:

df$age = digits(df$age, digits=2)
  subset_df <- function(m) {
    formattable(df[m, ], list(
      age = x ~ color_tile("white", "orange")(df$age)[m],
      test1_score = x ~ color_bar("pink", 'proportion', 0.2)(df$test1_score)[m],
      test2_score = x ~ color_bar("pink", 'proportion', 0.2)(df$test2_score)[m]
    ))
  }

subset_df(1:3)

The problem doesn't seem to be with this code though.

Body:
You could use the sprintf function to format the numeric columns as strings with the desired number of decimal places. In the code below, sprintf converts NA to the string "NA", which we then convert to an empty string.

# Function to convert numeric values to strings with a given number of
#  decimal places, and convert NA to empty string
fnc = function(var, decimal.places) {
  var = sprintf(paste0("%1.",decimal.places,"f"), var)
  var[var=="NA"] = ""
  var
}

# Select the columns we want to reformat
vars = c('age', 'test1_score')

# Apply the function to the desired columns with the desired number of decimal places
df[ , vars] = mapply(fnc, df[ ,vars], 2:3)

formattable(df, list(
  age = color_tile("white", "orange"),
  test1_score = color_bar("pink", 'proportion', 0.2)
))


问:
Getting Spark Logging class not found when using Spark SQL
I am trying to do a simple Spark SQL programming in Java. In the program, I am getting data from a Cassandra table, converting the RDD into a Dataset and displaying the data. When I run the spark-submit command, I am getting the error: java.lang.ClassNotFoundException: org.apache.spark.internal.Logging.

My program is:

```<code>SparkConf sparkConf = new SparkConf().setAppName("DataFrameTest")
        .set("spark.cassandra.connection.host", "abc")
        .set("spark.cassandra.auth.username", "def")
        .set("spark.cassandra.auth.password", "ghi");
SparkContext sparkContext = new SparkContext(sparkConf);
JavaRDD<EventLog> logsRDD = javaFunctions(sparkContext).cassandraTable("test", "log",
        mapRowTo(Log.class));
SparkSession sparkSession = SparkSession.builder().appName("Java Spark SQL").getOrCreate();
Dataset<Row> logsDF = sparkSession.createDataFrame(logsRDD, Log.class);
logsDF.show();
</code>```

My POM dependencies are:

```<code><dependencies>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.0.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.11</artifactId>
        <version>2.0.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector_2.11</artifactId>
        <version>1.6.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>2.0.2</version>
    </dependency>
</dependencies>
</code>```

My spark-submit command is: /home/ubuntu/spark-2.0.2-bin-hadoop2.7/bin/spark-submit --class "com.jtv.spark.dataframes.App" --master local[4] spark.dataframes-0.1-jar-with-dependencies.jar

How do I solve this error? Downgrading to 1.5.2 does not work as 1.5.2 does not have org.apache.spark.sql.Dataset and org.apache.spark.sql.SparkSession.

答: This may be a problem into your IDE. As some of this packages are created and Scala the Java project, sometimes the IDE is unable to understand what is going on. I am using the Intellij and it keeps displaying this message to me. But, when I try to run the "mvn test" or "mvn package" everything is fine. Please check if this is really some package error or just the IDE that is lost.</p>

Body:
I am trying to do a simple Spark SQL programming in Java. In the program, I am getting data from a Cassandra table, converting the RDD into a Dataset and displaying the data. When I run the spark-submit command, I am getting the error: java.lang.ClassNotFoundException: org.apache.spark.internal.Logging.

My program is:

SparkConf sparkConf = new SparkConf().setAppName("DataFrameTest")
        .set("spark.cassandra.connection.host", "abc")
        .set("spark.cassandra.auth.username", "def")
        .set("spark.cassandra.auth.password", "ghi");
SparkContext sparkContext = new SparkContext(sparkConf);
JavaRDD<EventLog> logsRDD = javaFunctions(sparkContext).cassandraTable("test", "log",
        mapRowTo(Log.class));
SparkSession sparkSession = SparkSession.builder().appName("Java Spark SQL").getOrCreate();
Dataset<Row> logsDF = sparkSession.createDataFrame(logsRDD, Log.class);
logsDF.show();

My POM dependencies are:

<dependencies>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.0.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.11</artifactId>
        <version>2.0.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector_2.11</artifactId>
        <version>1.6.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>2.0.2</version>
    </dependency>
</dependencies>

My spark-submit command is: /home/ubuntu/spark-2.0.2-bin-hadoop2.7/bin/spark-submit --class "com.jtv.spark.dataframes.App" --master local[4] spark.dataframes-0.1-jar-with-dependencies.jar

How do I solve this error? Downgrading to 1.5.2 does not work as 1.5.2 does not have org.apache.spark.sql.Dataset and org.apache.spark.sql.SparkSession.


答:
Probably the easiest approach would be:</p>

```<code>SomeInfo.objects.annotate(
    last_pubdate=Max('people__someinfo__data_pubdate')
).filter(last_pubdate=F('data_pubdate'))
</code>```

Title: About GROUP BY in Django

Body:
I have some question:

# models.py
class someinfo(models.Model):
    data1 = models.BigIntegerField(verbose_name='data1')
    data2 = models.BigIntegerField(verbose_name='data2')
    data_pubdate = models.DateTimeField(default=timezone.now, verbose_name='data_pubdate')
    people = models.ForeignKey(Drive, on_delete=models.CASCADE, verbose_name='people')

data table have:

# row data
data1    data2        data_pubdate                people
7777129  23232        2017-05-18 05:04:08.377     9
158160   4573279      2017-05-18 05:04:08.737     8
158200   5709307      2017-05-18 05:04:08.787     6
10073    11612        2017-05-18 05:04:19.727     6
2458     5245466      2017-05-18 05:04:19.727     4
2458     5245466      2017-05-18 05:04:19.724     4
14879    9727         2017-05-18 05:04:19.897     7
...etc

I want select data1 and data2 from new data_pubdate in each people, like this table:

# select data
data1    data2        data_pubdate                people
7777129  23232        2017-05-18 05:04:08.377     9
158160   4573279      2017-05-18 05:04:08.737     8
10073    11612        2017-05-18 05:04:19.727     6
2458     5245466      2017-05-18 05:04:19.727     4
14879    9727         2017-05-18 05:04:19.897     7

So...What should I do?

P.S. django version is "1.10", database is "MSSQL server 2012"

Body:
Probably the easiest approach would be:

SomeInfo.objects.annotate(
    last_pubdate=Max('people__someinfo__data_pubdate')
).filter(last_pubdate=F('data_pubdate'))


问:
Java minesweeper game problem. hiding mines when the game begins?
I've been able to successfully initiate a minefield when the game begins with 10 mines randomly scattered over the field. However, I'm having problems hiding these mines from the user when the game begins. As you know, the point of minesweeper is to find where the mines are WITHOUT being able to see them. I need help figuring out how to hide the mines.

Below is the code I have written for my Grid class which initiates the grid and includes a method which fills it with mines. How can I hide these mines and only reveal them when they are clicked on? Thanks for the help!

```<code>public class Grid {

 private int[][] grid;
 private boolean isHidden;
 private  int rows;
 private final int columns;
 private final int mines;

 public Grid() {
  this.rows = 8;
  this.columns = 8;
  this.mines = 10;
  this.grid = new int[rows][columns];

 }

 public int[][] getGrid() {
  return grid;
 }

 public int getRows() {
  return rows;
 }

 public int getColumns() {
  return columns;
  }

 public void fillGrid() {
  Random ranGen = new Random();

  for(int i = 0; i < this.mines; ) {
   int row = ranGen.nextInt(this.rows - 1);
   int column = ranGen.nextInt(this.columns - 1);

   if(grid[row][column] != MinesweeperGUI.MINE) {
    grid[row][column] = MinesweeperGUI.MINE;
    i++;
   }
  }
    }
</code>```

答:
You should have two matrices: One for the mines (MineMatrix) and one to track the user clicks (UserClickMatrix).

You should only show the end user UserClickMatrix and initialize all the cells with NotClicked at the start of the game. Whenever the user clicks on a cell, change the status of the cell to Clicked. Then, grab the cell indices from UserClickMatrix and check against MineMatrix (MineMatrix[clickedRow][clickedColumn] == MINE). If the condition evaluates to TRUE, game ends.

Body:
I've been able to successfully initiate a minefield when the game begins with 10 mines randomly scattered over the field. However, I'm having problems hiding these mines from the user when the game begins. As you know, the point of minesweeper is to find where the mines are WITHOUT being able to see them. I need help figuring out how to hide the mines.

Below is the code I have written for my Grid class which initiates the grid and includes a method which fills it with mines. How can I hide these mines and only reveal them when they are clicked on? Thanks for the help!

public class Grid {

 private int[][] grid;
 private boolean isHidden;
 private  int rows;
 private final int columns;
 private final int mines;

 public Grid() {
  this.rows = 8;
  this.columns = 8;
  this.mines = 10;
  this.grid = new int[rows][columns];

 }

 public int[][] getGrid() {
  return grid;
 }

 public int getRows() {
  return rows;
 }

 public int getColumns() {
  return columns;
  }

 public void fillGrid() {
  Random ranGen = new Random();

  for(int i = 0; i < this.mines; ) {
   int row = ranGen.nextInt(this.rows - 1);
   int column = ranGen.nextInt(this.columns - 1);

   if(grid[row][column] != MinesweeperGUI.MINE) {
    grid[row][column] = MinesweeperGUI.MINE;
    i++;
   }
  }
    }


问:
Mysql error with my SELECT DISTINCT query
I keep running into the same error, using MySQL.

The totaal value is marked as wrong, but i have no idea what is wrong with the function at all.

My original code example

```<code>CREATE or REPLACE FUNCTION functiondave
 (p_in date)
 return date is sumMediaExpression int;

 begin;

 select distinct count(Beoordelingen) into totaal
 from media_uitingen
 where Beoordelingen like 'Positief' and DATUM like '01-07-14';

 dbms_output.put_line('Number of positive MediaExpressions op 01-07-14
 zijn : ' || sumMediaExpression);

 end;
</code>```

答:
The SELECT DISTINCT statement is used to return only distinct (different) values.

Your query is wrong.
You need to write it like this:

SELECT COUNT(DISTINCT Beoordelingen) INTO totaal FROM media_uitingen (the rest of your query);

You can check this website for further information about SQL queries: https://www.w3schools.com/sql

Body:
I keep running into the same error, using MySQL.

The totaal value is marked as wrong, but i have no idea what is wrong with the function at all.

My original code example

CREATE or REPLACE FUNCTION functiondave
 (p_in date)
 return date is sumMediaExpression int;

 begin;

 select distinct count(Beoordelingen) into totaal
 from media_uitingen
 where Beoordelingen like 'Positief' and DATUM like '01-07-14';

 dbms_output.put_line('Number of positive MediaExpressions op 01-07-14
 zijn : ' || sumMediaExpression);

 end;


问:
Dividing strings in python 2.7
I have been working on a automated blinds/ curtains project for some time now It all works well but I would like to add the function of the Blinds gradually opening in the morning. I am reading my values from a config file and have converted the values into strings which works fine, just can't divide that value for some reason. I have tried many ways of doing this but I seem to come across errors such as- SyntaxError: can't assign to operator and TypeError: cannot concatenate 'str' and 'int' objects. Has anyone got any idea's on how I can divide a python string then use that string as a sleep value??

I am fairly new to programming (I'm 13)

```<code>from ConfigParser import SafeConfigParser
config = SafeConfigParser()

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

## code to divide openTime by 5 and print the value

print 'gradual open time' + DividedOpenTime + ' seconds'

## code to repeat in a loop 5 times with a sleep of the value of
## DividedOpenTime
</code>```

EDIT 1

Hi again I have done what I was told to add to the code and it has solved the issue of the division and sleep time but for some reason I can't print the values. Both lines 11 and 15 have the following error:

```<code>Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print 'gradual open time' + divOpenTime + ' this will repeat 5 times'
TypeError: cannot concatenate 'str' and 'float' objects
</code>```

Does anyone know how I can fix this issue?

```<code>from ConfigParser import SafeConfigParser
config = SafeConfigParser()
import time

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

divOpenTime = float(openTime)/5 #working (:
loop = 0
print 'gradual open time' + divOpenTime + ' this will repeat 5 times'

for x in range(0, 5):
    loop += 1
    print 'gradual opening stage ' + loop + '/5'
    #GPIO true- I know how to do this
    time.sleep(divOpenTime) #working (:
    #GPIO False- I know how to do this
    time.sleep(15) #time between each interval fixed value
</code>```

Thanks Ed

答:
You need to convert the string into a number to do computations with it,</p>

```<code>DividedOpenTime = float(openTime)/5
</code>```

Title: Dividing strings in python 2.7

Body:
I have been working on a automated blinds/ curtains project for some time now It all works well but I would like to add the function of the Blinds gradually opening in the morning. I am reading my values from a config file and have converted the values into strings which works fine, just can't divide that value for some reason. I have tried many ways of doing this but I seem to come across errors such as- SyntaxError: can't assign to operator and TypeError: cannot concatenate 'str' and 'int' objects. Has anyone got any idea's on how I can divide a python string then use that string as a sleep value??

I am fairly new to programming (I'm 13)

from ConfigParser import SafeConfigParser
config = SafeConfigParser()

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

## code to divide openTime by 5 and print the value

print 'gradual open time' + DividedOpenTime + ' seconds'

## code to repeat in a loop 5 times with a sleep of the value of
## DividedOpenTime

EDIT 1

Hi again I have done what I was told to add to the code and it has solved the issue of the division and sleep time but for some reason I can't print the values. Both lines 11 and 15 have the following error:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print 'gradual open time' + divOpenTime + ' this will repeat 5 times'
TypeError: cannot concatenate 'str' and 'float' objects

Does anyone know how I can fix this issue?

from ConfigParser import SafeConfigParser
config = SafeConfigParser()
import time

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

divOpenTime = float(openTime)/5 #working (:
loop = 0
print 'gradual open time' + divOpenTime + ' this will repeat 5 times'

for x in range(0, 5):
    loop += 1
    print 'gradual opening stage ' + loop + '/5'
    #GPIO true- I know how to do this
    time.sleep(divOpenTime) #working (:
    #GPIO False- I know how to do this
    time.sleep(15) #time between each interval fixed value

Thanks Ed

Body:
You need to convert the string into a number to do computations with it,

DividedOpenTime = float(openTime)/5


问:
upgrade or install a homebrew formula
In my CI-setup, i would like to make sure that the newest version of a given formula is installed, regardless of whether it is already installed or not.

i'm currently using something like:

```<code>brew update
brew install FORMULA || (brew upgrade FORMULA && brew cleanup FORMULA)
</code>```

What are the pitfalls with that approach? Is there a nicer approach to the problem (e.g. by first querying whether FORMULA is already installed, rather than relying on brew install to fail only if FORMULA is installed)?

答:
I you want to install a Homebrew package if it does not already exist, and upgrade it otherwise, the best solution is to use Homebrew Bundle which is officially part of the Homebrew family. If that doesn't work for you, and you want to roll your own solution, you should reference at the suggestions below.

There are other situation where a brew install might fail, other than a package already being installed. I'm not sure, but it doesn't look like the brew install command emits an exit status other than 1 on failure, so you have two options:

Search stderr for "not installed" and check against that

Use a different approach

The most common approach I've seen used for this purpose is to check if the package is installed with the command brew ls --versions:

```<code>function install_or_upgrade {
    if brew ls --versions "$1" >/dev/null; then
        HOMEBREW_NO_AUTO_UPDATE=1 brew upgrade "$1"
    else
        HOMEBREW_NO_AUTO_UPDATE=1 brew install "$1"
    fi
}
</code>```

You'll want to use HOMEBREW_NO_AUTO_UPDATE=1 if you're installing multiple packages so that Homebrew does not try to update in between each install/upgrade.

Title: upgrade or install a homebrew formula

Body:
In my CI-setup, i would like to make sure that the newest version of a given formula is installed, regardless of whether it is already installed or not.

i'm currently using something like:

brew update
brew install FORMULA || (brew upgrade FORMULA && brew cleanup FORMULA)

What are the pitfalls with that approach? Is there a nicer approach to the problem (e.g. by first querying whether FORMULA is already installed, rather than relying on brew install to fail only if FORMULA is installed)?

Body:
I you want to install a Homebrew package if it does not already exist, and upgrade it otherwise, the best solution is to use Homebrew Bundle which is officially part of the Homebrew family. If that doesn't work for you, and you want to roll your own solution, you should reference at the suggestions below.

There are other situation where a brew install might fail, other than a package already being installed. I'm not sure, but it doesn't look like the brew install command emits an exit status other than 1 on failure, so you have two options:

Search stderr for "not installed" and check against that

Use a different approach

The most common approach I've seen used for this purpose is to check if the package is installed with the command brew ls --versions:

function install_or_upgrade {
    if brew ls --versions "$1" >/dev/null; then
        HOMEBREW_NO_AUTO_UPDATE=1 brew upgrade "$1"
    else
        HOMEBREW_NO_AUTO_UPDATE=1 brew install "$1"
    fi
}

You'll want to use HOMEBREW_NO_AUTO_UPDATE=1 if you're installing multiple packages so that Homebrew does not try to update in between each install/upgrade.


问:
Why is this invulnerable to styling?
I just want to change it's color to #DD4814 but I can't. It's a "share button" btw.
What could be the reason?</p>

```<code><span class='st_sharethis' st_title='<?php the_title(); ?>' st_url='<?php the_permalink() ?>' displayText='Compartir'></span>

<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script><script type="text/javascript">stLight.options({publisher:'eb2f12b2-11c6-4013-bf2c-e42dcf3112f5'});</script>
</code>```

答:
This works for me:</p>

```<code>.stButton .sharethis {color:#DD4814}
</code>```

Title: Why is this invulnerable to styling?

Body:
I just want to change it's color to #DD4814 but I can't. It's a "share button" btw.
What could be the reason?

<span class='st_sharethis' st_title='<?php the_title(); ?>' st_url='<?php the_permalink() ?>' displayText='Compartir'>

Body:
This works for me:

.stButton .sharethis {color:#DD4814}


问:
REST API - should JSON content be HtmlEncoded?
We have a setup with angular front-end app and asp.net core web api backend. API responds with json.
Question is, should json properties be html encoded or not?

I can see reasons for both: pro and con.

On one hand, REST API should be client agnostic (thus, shouldn't care about html in particular), on the other hand it feels a bit risky to rely on client-side XSS prevention alone.

Thoughts?

答:
A few points:

Different encodings are needed for different contexts. Baking in html-encoding for all data may not always be good, especially if you somehow write into a Javascript context, where it is useless against XSS. So from this perspective I'd consider JSON as data, which only needs json encoding and not html. Of course client-side data binding or something else needs to take care of encoding or safe binding then.

If JSON is returned in an API call, the content-type of the response is crucial. It needs to be application/json, otherwise the json endpoint itself will be vulnerable to XSS if it contains
```

<p>This looks fine, but take a look at this:</p>

```
<script>
  var data = "{'key1': 'val1', 'key2': '</script><script>alert(1)</script>'}";
</script>
```

It looks like a simple string, but the browser is primarily an html parser. It finds stuff between  and executes that as Javascript. The first </script> inside the string happens to be paired with the very first

Body:
A few points:

Different encodings are needed for different contexts. Baking in html-encoding for all data may not always be good, especially if you somehow write into a Javascript context, where it is useless against XSS. So from this perspective I'd consider JSON as data, which only needs json encoding and not html. Of course client-side data binding or something else needs to take care of encoding or safe binding then.

If JSON is returned in an API call, the content-type of the response is crucial. It needs to be application/json, otherwise the json endpoint itself will be vulnerable to XSS if it contains <script> etc.

If you write JSON data into a script block for example to initialize a variable, it gets tricky. Consider the following:

<script>
  var data = "{'key1': 'val1', 'key2': 'val2'}";
</script>

This looks fine, but take a look at this:

<script>
  var data = "{'key1': 'val1', 'key2': '</script><script>alert(1)</script>'}";
</script>

It looks like a simple string, but the browser is primarily an html parser. It finds stuff between <script> and </script> and executes that as Javascript. The first </script> inside the string happens to be paired with the very first <script> tag, and the first open tag in the string will start a completely new script, thus resulting in XSS.

So if you are intending to write JSON into the html as part of Javascript (a very common use), you need to encode JSON contents to HTML unfortunately. It's much better to avoid this and download data separately.


问:
Xamarin .net standard effect on APK size
When you use a .net standard lib from the full .net framework you end up having to include/deploy .net standard versions of all the System.* assemblies the .net standard library uses.

Now that Xamarin supports .net standard and microsoft is recommending people use .net standard rather than PCL we will soon need to switch (library developers are abandoning PCL support).

My question is does using a .net standard library in a Xamarin for Android project mean that multiple system assemblies will be deployed (the .net standard version and the mono version)?

Xamarin apps are already much bigger than native and having to include duplicates of all the system assemblies we need could be a deal breaker going forward.

答:
The .NET Standard(s) define the API surface of each version. The implementation of the API surface lies with the platform.

In the case of Xamarin the surface is implemented in the Mono framework which is deployed with every app. (And has been before)

If you reference nothing but the NETStandard Library the final .apk file will not increase.

Additional NuGet packages might bring in extra NetStandard specific dependencies (which could previously have been handled by the .net / mono framework itself)