问:
Running django-admin tutorial erros: no module named django
I just started to try and install/run Django on my cmd prompt and faced this issue although environment variables are set up for Django.

Besides getting a solution, can someone help me understand the root cause of the error below?

```<code>C:\Python>django-admin startproject test
Traceback (most recent call last):
  File "C:\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\windows\syswow64\scripts\django-admin.exe\__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'django'
</code>```

答:
In python based project it is always good to create Virtual Environment and then run your django program .

```<code> pip install virtualenvwrapper-win
 mkvirtualenv test
 workon test
</code>```

this will activate your virtual environment

Now install django

```<code>pip install django
</code>```

After django installation complets

run

```<code>django-admin --version
</code>```

Hope this helps.

Body:
I just started to try and install/run Django on my cmd prompt and faced this issue although environment variables are set up for Django.

Besides getting a solution, can someone help me understand the root cause of the error below?

C:\Python>django-admin startproject test
Traceback (most recent call last):
  File "C:\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\windows\syswow64\scripts\django-admin.exe\__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'django'

Body:
In python based project it is always good to create Virtual Environment and then run your django program .

 pip install virtualenvwrapper-win
 mkvirtualenv test
 workon test

this will activate your virtual environment

Now install django

pip install django

After django installation complets

run

django-admin --version

Hope this helps.


来源: stackexchange

问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答:
"The original question was already using an IList<T>. It was removed when someone edited the formatting. Probably a problem with Markdown."

Thats what i saw but it was edited by someone and that's the reason why I put my explanation about covariance but for some reason i was marked down to -1.

OwnerDisplayName: Sara Chipps

ContentLicense: CC BY-SA 2.5

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?


问:
(VB) Pass variable to Report Parameter
have a
Parameter in Report

How can I pass a variable in real time to the Report Parameter?

答:
You add them via the ReportParameter class.

See here.
https://msdn.microsoft.com/en-us/library/aa337089%28v=sql.100%29.aspx?f=255&MSPPError=-2147217396

ContentLicense: CC BY-SA 3.0

Title: (VB) Pass variable to Report Parameter


问:
Generate all points on the perimeter of a diamond
Given a series of diamonds like this:

How does one generate a list of the black squares for each diamond? Assume the red square is at {0, 0} and the coordinates of the black squares are given relative to that. Examples for the given diamonds:

```<code>0 = {0, 0}
1 = {-1, 0}, {0, -1}, {0, 1}, {1, 0}
2 = {-2, 0}, {-1, -1}, {-1, 1}, {0, -2}, {0, 2}, {1, -1}, {1, 1}, {2, 0}
3 = {-3, 0}, {-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {0, -3}, {0, 3}, {1, -2}, {1, 2}, {2, -1}, {2, 1}, {3, 0}
</code>```

Observations (given n is the distance from origin to corner):

The sum of each coordinate pair is always n or -n.

With the exception of 0, the size of the list is always 4n.

|x| + |y| = n is the Cartesian equation of the diamond.

With the lattermost observation I discovered the following solution in C. But it's in O(n^2) time with a comparison and two calls to abs(). Is there not a faster solution suitable for much larger diamonds?

```<code>void diamond_points(int n) {
    for (int x = -n; x <= n; ++x) {
        for (int y = -n; y <= n; ++y) {
            if (abs(x) + abs(y) == n) {
                printf("{%d, %d}, ", x, y);
            }
        }
    }
}
</code>```

Body:
Given a series of diamonds like this:

How does one generate a list of the black squares for each diamond? Assume the red square is at {0, 0} and the coordinates of the black squares are given relative to that. Examples for the given diamonds:

0 = {0, 0}
1 = {-1, 0}, {0, -1}, {0, 1}, {1, 0}
2 = {-2, 0}, {-1, -1}, {-1, 1}, {0, -2}, {0, 2}, {1, -1}, {1, 1}, {2, 0}
3 = {-3, 0}, {-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {0, -3}, {0, 3}, {1, -2}, {1, 2}, {2, -1}, {2, 1}, {3, 0}

Observations (given n is the distance from origin to corner):

The sum of each coordinate pair is always n or -n.

With the exception of 0, the size of the list is always 4n.

|x| + |y| = n is the Cartesian equation of the diamond.

With the lattermost observation I discovered the following solution in C. But it's in O(n^2) time with a comparison and two calls to abs(). Is there not a faster solution suitable for much larger diamonds?

void diamond_points(int n) {
    for (int x = -n; x <= n; ++x) {
        for (int y = -n; y <= n; ++y) {
            if (abs(x) + abs(y) == n) {
                printf("{%d, %d}, ", x, y);
            }
        }
    }
}

Body:
There is, with O(N)

for(int x = -n; x <= n; x++) {
    int y = n - abs(x);
    printf("{%d, %d}, ", x, y);
    if(y > 0) {
        printf("{%d, %d}, ", x, -y);
    }
}


问:
HTML SELECT JS onchange() disable comment box
This may be an absurdly easy question, but I'm new to JS.

I would like to have a SELECT box allowing a person to indicate where they heard about the event they're registering for.  There would be a comment box, disabled by default but if the user selects 'Other' in the SELECT option the comment box would become available.

I am aware of onchange() but I don't know how to trigger a response in the separate form element.  Any help?

答:
Probably something like this.

HTML:

```<code><select id="IDE">
    <option value="0">Xcode</option>
    <option value="1">Android Studio</option>
    <option value="2">Others</option>
</select>

<input id="comment_box" type="textbox" disabled="true"/>
</code>```

JS:

```<code>document.getElementById('IDE').addEventListener('change', function() {
    if (this.value == 2) {
        document.getElementById('comment_box').disabled = false;
    } else {
        document.getElementById('comment_box').disabled = true;
    }
});
</code>```

Here's a fiddle.

Body:
Probably something like this.

HTML:

<select id="IDE">
    <option value="0">Xcode</option>
    <option value="1">Android Studio</option>
    <option value="2">Others</option>
</select>

<input id="comment_box" type="textbox" disabled="true"/>

JS:

document.getElementById('IDE').addEventListener('change', function() {
    if (this.value == 2) {
        document.getElementById('comment_box').disabled = false;
    } else {
        document.getElementById('comment_box').disabled = true;
    }
});

Here's a fiddle.


问:
Python epoc time to hour only?
Given epoch time like 1491021658 in Python what is the direct way to get the hour (without minutes) in military time?

example

```<code>time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1491021658))
'2017-04-01 00:40:58'
</code>```

get only 00

using Python 3.5.x

答:
Try this, if you want only hours, use %H only.

```<code>time.strftime('%H', time.localtime(1491021658))
</code>```

Title: Python epoc time to hour only?

Body:
Given epoch time like 1491021658 in Python what is the direct way to get the hour (without minutes) in military time?

example

time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1491021658))
'2017-04-01 00:40:58'

get only 00

using Python 3.5.x

Body:
Try this, if you want only hours, use %H only.

time.strftime('%H', time.localtime(1491021658))


问:
xhr does not get invoked from js
i am using phonegap and trying to invoke a xhr POST on click of a button.

my flow goes to the method call but doesn't invoke the xhr code and i am failing to understand why.
The call looks like:

```<code>   function fetchTags(){
            console.log("Fetched url is:" + IMAGE_URL);
            //var url = "http://localhost:8080/echo";
            var url ="http://localhost:8080/echo";
            console.log("#1");
            var xhr = new XMLHttpRequest();
            console.log("#2");
            xhr.addEventListener("error", onError);function onError(evt) { console.log("An error occurred while transferring the file."); }
            console.log("#3");
            xhr.setRequestHeader("Content-type", "application/json");
            console.log("#4");
            xhr.open('POST', url, true);
            console.log("#5");
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                  var response = JSON.parse(xhr.responseText);
                  window.alert(response);
                }else{
                    window.alert(xhr.status);
                }
            };
            console.log("#5");

         //var msg = "{'message' : '" + IMAGE_URL + "'}";
         console.log("sending request");
         xhr.send(JSON.stringify({"message" : "my msg"}));

        }
</code>```

Button code:

```<code>  <button class="button button-raised larger" type="button" onclick="fetchTags()">Vision</button>
</code>```

The console prints:

```<code>Fetched url is:undefined
#1
#2
#3
</code>```

To clarify i can see first console.log getting printed. but that's it. nothing happens after that.

答:
just for everyone's benefit the issue was not the javascript but invoking from the phonegap using the localhost.

I was unders the assumption that phonegap will be able to access my api at localhost (not sure why had this stupid idea) but yes using the actual ip of the host machine made it work right away.

Title: xhr does not get invoked from js

Body:
i am using phonegap and trying to invoke a xhr POST on click of a button.

my flow goes to the method call but doesn't invoke the xhr code and i am failing to understand why.
The call looks like:

   function fetchTags(){
            console.log("Fetched url is:" + IMAGE_URL);
            //var url = "http://localhost:8080/echo";
            var url ="http://localhost:8080/echo";
            console.log("#1");
            var xhr = new XMLHttpRequest();
            console.log("#2");
            xhr.addEventListener("error", onError);function onError(evt) { console.log("An error occurred while transferring the file."); }
            console.log("#3");
            xhr.setRequestHeader("Content-type", "application/json");
            console.log("#4");
            xhr.open('POST', url, true);
            console.log("#5");
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                  var response = JSON.parse(xhr.responseText);
                  window.alert(response);
                }else{
                    window.alert(xhr.status);
                }
            };
            console.log("#5");

         //var msg = "{'message' : '" + IMAGE_URL + "'}";
         console.log("sending request");
         xhr.send(JSON.stringify({"message" : "my msg"}));

        }

Button code:

  <button class="button button-raised larger" type="button" onclick="fetchTags()">Vision</button>

The console prints:

Fetched url is:undefined
#1
#2
#3

To clarify i can see first console.log getting printed. but that's it. nothing happens after that.


问:
PDF printing in java
is there a way to print pdf files from a java webapplication on the local printer of the end user (connected via vpn)?
The simple lookup of a printer via Java Printing Service always returns printer which are not able to print pdfs. Are there other libs which can be used for printing in java?

By the way, just opening the pdf in the browser is not an option, though it must be possible to run scheduled batch printing without user interaction.

Thanks in advance

答:
I currently have the same problem - having to find a way to print PDF and Word documents.
And the short answer is:

It's not as easy as you'd want it to be.

The problem is that "someone" has to do the interpretation of your document. And that someone is either the printer or you.

Not all printers support DocFlavor.x.PDF. We have four printers at my company (one was bought just last month) and none of them does.
If you find a printer that does accept that DocFlavor you're done.

But since chances are the printer doesn't know what to do with a PDF file, you have to render the document yourself. I can recommend trying PDFRenderer and PDFBox. For me PDFRenderer works great and PDFBox doesn't print text correctly, but other people report the opposite. So, you will have to try for yourself.

All that still doesn't help me with Word docs, but that's not your concern.

Title: PDF printing in java


问:
Error 403 with Git Push to Gogs
I receive the following error whilst trying to push to my newly created repo hosted using gogs on my server:

```<code>$ git push origin master
remote: User permission denied
fatal: unable to access 'https://myserver.co.uk/gogs/jacque/myRepo.git/': The requested URL returned error: 403
</code>```

I can access gogs just fine in my browser, I can clone repositories with no issue, I just can't push to my remote.

I know this question has been asked on multiple occasions but I can't seem to get anywhere trying any of the other answers.

For extra information, I'm using git for windows on windows 10. My server is running raspbian.

Edit: If the repo is initialised using VS it works fine but this doesn't solve my problem.

答: Based on the error message, you have pull access but no push access to the repository.</p>

Title: Error 403 with Git Push to Gogs

Body:
I receive the following error whilst trying to push to my newly created repo hosted using gogs on my server:

$ git push origin master
remote: User permission denied
fatal: unable to access 'https://myserver.co.uk/gogs/jacque/myRepo.git/': The requested URL returned error: 403

I can access gogs just fine in my browser, I can clone repositories with no issue, I just can't push to my remote.

I know this question has been asked on multiple occasions but I can't seem to get anywhere trying any of the other answers.

For extra information, I'm using git for windows on windows 10. My server is running raspbian.

Edit: If the repo is initialised using VS it works fine but this doesn't solve my problem.


问:
Mail script needs running every hour, but cron not working
Below is the fully functioning code. It works when I call it via the browser. However, I can't get my Cron job to run it. I have tried coming up with any solution and am open to any ideas that will make this script fire off once every hour 24/7 365 so to speak.

Info:

Hostgator

PHP 5.4

Link for Hostgator Cron commands: http://support.hostgator.com/articles/cpanel/what-do-i-put-for-the-cron-job-command?utm_source=cPanel&utm_medium=message&utm_campaign=Cron%20Jobs

I have tried the following:

When doing any of these I have yet to have it add a sale to the database or send a single email:

/opt/php54/bin/php /home1/user/public_html/Sales/scripts/sales-notif_em.php - Could not open input file: /home1/user/public_html/scripts/sales-notif_em.php

php /home1/user/public_html/Sales/scripts/sales-notif_em.php - blank email with nothing but this showing: Content-type: text/html

php -q /home1/lotscav1/public_html/Sales/scripts/sales_notif_em.php - I don't get any emails from the system of course

/usr/bin/curl home1/user/public_html/scripts/sales-notif_em.php - curl: (3)  malformed

any command (like php or /usr/bin/curl) that has the second half with http://website.c0m/Sales/scripts/sales_notif_em.php - causes a JSON Error when trying to add the Cron job

I have checked the following things:

File permissions are 655

Timestamp is less than an hour old under the customers table

Here is my code:

```<code><?php
//find out current time and 1 hour ago
date_default_timezone_set('America/New_York');
$current_time = strtotime("now");
$hour_ago = strtotime('-1 hour');

//////////////////////////////////////////////////////////////////
/////////////////l// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

$mysqli_s = new mysqli("localhost", "user", "password",
"server_sales_data");
if ($mysqli_s->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli_s->connect_errno . ")
" . $mysqli_s->connect_error;
}

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////

$mysqli_em = new mysqli("localhost", "user", "password",
"server_dlgEM");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .
") " . $mysqli_em->connect_error;
}

//Grab store name
$dlg_store = "EM";

$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'
AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No
Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_receipt = $em_row["receipt"];

//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////

$request_s = "SELECT * FROM all_products WHERE
dlgprod_num='$em_prod_num' AND dlg_store='$dlg_store'";
$result_s = mysqli_query($mysqli_s, $request_s) or die("Error dlg
prod num EM");
while ($row_s = mysqli_fetch_array($result_s)) {
        $sku_s = $row_s["sku"];
        $dlgprod_num_s = $row_s["dlgprod_num"];
        $book_title_s = addslashes($row_s["book_title"]);
        $dlgprod_price_s = $row_s["dlgprod_price"];
        $author_name_s = addslashes($row_s["author_name"]);
        $author_email_s = $row_s["author_email"];
        $publisher_s = $row_s["publisher"];
        $dlg_store_s = $row_s["dlg_store"];

            $add_sql_s  = "INSERT INTO all_author_sales SET
            `sku`='$sku_s',
            `dlgprod_num`='$dlgprod_num_s',
            `dlgprod_nam`='$book_title_s',
            `dlgprod_price`='$dlgprod_price_s',
            `author_name`='$author_name_s',
            `author_email`='$author_email_s',
            `publisher`='$publisher_s',
            `dlg_store`='$dlg_store_s',
            `dlgcustomer_receipt`='$em_receipt' ";

//create signature
$sig = "The Admin Team at www.website.com";
//to
$admin_email = "admin@website.com";
$to = array($author_email_s, $admin_email);

//setup email headers
$headers='From: ' . $admin_email . "\r\n" .
'Reply-To: ' . $admin_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= $emailbody."\n\n";

//email subject and body
$subject = "Your book stats";
$message = "
Hi $author_name_s,<br />
I just wanted to send you a message and let you know that the book or
books below have just been purchased.<br /><br />

Store: $dlg_store_s<br />
Receipt: $em_receipt<br />
Sku Number: $sku_s<br /><br />

Book Title: $book_title_s<br />
Publisher: $publisher_s<br />
Product Number: $dlgprod_num_s<br />
Price: $dlgprod_price_s<br /><br />

Sincerely,<br />
$sig<br /><br />

To remove yourself from this notification, please send an email to
$admin_email with Unsubscribe in the subject line.
";

            if ($mysqli_s->multi_query($add_sql_s) === TRUE) {
            mail (implode(',', $to), $subject, $message, $headers);
            } else {
                echo "Error: " . $add_sql_s . "<br>" . $mysqli_s-
>error . "<br>" . $string;
            }

    }

}

?>
</code>```

答:
My bet is with wrong path to the php file you want to execute.

Try using terminal if you can, navigate to the folder where the file is placed and try running it from there via command line.

Also mind You are refering to two different names: sales-notif_em.php & sales-notif_me.php.

Body:
Below is the fully functioning code. It works when I call it via the browser. However, I can't get my Cron job to run it. I have tried coming up with any solution and am open to any ideas that will make this script fire off once every hour 24/7 365 so to speak.

Info:

Hostgator

PHP 5.4

Link for Hostgator Cron commands: http://support.hostgator.com/articles/cpanel/what-do-i-put-for-the-cron-job-command?utm_source=cPanel&utm_medium=message&utm_campaign=Cron%20Jobs

I have tried the following:

When doing any of these I have yet to have it add a sale to the database or send a single email:

/opt/php54/bin/php /home1/user/public_html/Sales/scripts/sales-notif_em.php - Could not open input file: /home1/user/public_html/scripts/sales-notif_em.php

php /home1/user/public_html/Sales/scripts/sales-notif_em.php - blank email with nothing but this showing: Content-type: text/html

php -q /home1/lotscav1/public_html/Sales/scripts/sales_notif_em.php - I don't get any emails from the system of course

/usr/bin/curl home1/user/public_html/scripts/sales-notif_em.php - curl: (3)  malformed

any command (like php or /usr/bin/curl) that has the second half with http://website.c0m/Sales/scripts/sales_notif_em.php - causes a JSON Error when trying to add the Cron job

I have checked the following things:

File permissions are 655

Timestamp is less than an hour old under the customers table

Here is my code:

<?php
//find out current time and 1 hour ago
date_default_timezone_set('America/New_York');
$current_time = strtotime("now");
$hour_ago = strtotime('-1 hour');

//////////////////////////////////////////////////////////////////
/////////////////l// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

$mysqli_s = new mysqli("localhost", "user", "password",
"server_sales_data");
if ($mysqli_s->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli_s->connect_errno . ")
" . $mysqli_s->connect_error;
}

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////

$mysqli_em = new mysqli("localhost", "user", "password",
"server_dlgEM");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .
") " . $mysqli_em->connect_error;
}

//Grab store name
$dlg_store = "EM";

$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'
AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No
Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_receipt = $em_row["receipt"];

//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////

$request_s = "SELECT * FROM all_products WHERE
dlgprod_num='$em_prod_num' AND dlg_store='$dlg_store'";
$result_s = mysqli_query($mysqli_s, $request_s) or die("Error dlg
prod num EM");
while ($row_s = mysqli_fetch_array($result_s)) {
        $sku_s = $row_s["sku"];
        $dlgprod_num_s = $row_s["dlgprod_num"];
        $book_title_s = addslashes($row_s["book_title"]);
        $dlgprod_price_s = $row_s["dlgprod_price"];
        $author_name_s = addslashes($row_s["author_name"]);
        $author_email_s = $row_s["author_email"];
        $publisher_s = $row_s["publisher"];
        $dlg_store_s = $row_s["dlg_store"];

            $add_sql_s  = "INSERT INTO all_author_sales SET
            `sku`='$sku_s',
            `dlgprod_num`='$dlgprod_num_s',
            `dlgprod_nam`='$book_title_s',
            `dlgprod_price`='$dlgprod_price_s',
            `author_name`='$author_name_s',
            `author_email`='$author_email_s',
            `publisher`='$publisher_s',
            `dlg_store`='$dlg_store_s',
            `dlgcustomer_receipt`='$em_receipt' ";

//create signature
$sig = "The Admin Team at www.website.com";
//to
$admin_email = "admin@website.com";
$to = array($author_email_s, $admin_email);

//setup email headers
$headers='From: ' . $admin_email . "\r\n" .
'Reply-To: ' . $admin_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= $emailbody."\n\n";

//email subject and body
$subject = "Your book stats";
$message = "
Hi $author_name_s,

I just wanted to send you a message and let you know that the book or
books below have just been purchased.

Store: $dlg_store_s

Receipt: $em_receipt

Sku Number: $sku_s

Book Title: $book_title_s

Publisher: $publisher_s

Product Number: $dlgprod_num_s

Price: $dlgprod_price_s

Sincerely,

$sig

To remove yourself from this notification, please send an email to
$admin_email with Unsubscribe in the subject line.
";

            if ($mysqli_s->multi_query($add_sql_s) === TRUE) {
            mail (implode(',', $to), $subject, $message, $headers);
            } else {
                echo "Error: " . $add_sql_s . "
" . $mysqli_s-
>error . "
" . $string;
            }

    }

}

?>


问:
Why Access path denied?
I'm trying to read a text file with File.ReadAllText and FileStream, but for some reason I get the System.UnauthorizedAccessException every time.

```<code> class consultas
{
    public consultas()
    {

    }

    private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";

    public string getInativos()
    {
        try
        {
            // string path = Directory.GetCurrentDirectory();
            this.Inativos = File.ReadAllText(this.Inativos);

        }
        catch(Exception e)
        {
            throw e;

        }
        return this.Inativos;

    }
}
</code>```

Why? I have permissions in that folder, so why do I get this exception?

答:
Because the path is a directory.
Please check your file address.
This method needs a file address.
Here is a sample code:

```<code>File.ReadAllText("C:\\yourfile.txt");
</code>```

Title: Why Access path denied?

Body:
I'm trying to read a text file with File.ReadAllText and FileStream, but for some reason I get the System.UnauthorizedAccessException every time.

 class consultas
{
    public consultas()
    {

    }

    private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";

    public string getInativos()
    {
        try
        {
            // string path = Directory.GetCurrentDirectory();
            this.Inativos = File.ReadAllText(this.Inativos);

        }
        catch(Exception e)
        {
            throw e;

        }
        return this.Inativos;

    }
}

Why? I have permissions in that folder, so why do I get this exception?

Body:
Because the path is a directory.
Please check your file address.
This method needs a file address.
Here is a sample code:

File.ReadAllText("C:\\yourfile.txt");

ContentLicense: CC BY-SA 4.0


问:
how i can acess to elements of arraylist<class>
hi i want to know how i can access to elements of arraylist in java?
i have this class .

```<code>class flight
{
    public String start;
    public String end;
    public int timethatend ;
    public int timethatstart;
    flight ( int ts , int tf , String s , String e )
    {
        this.start = s;
        this.end =e;
        this.timethatend = tf;
        this.timethatstart = ts;
    }
}
</code>```

and i have this arraylist in my main class

```<code>ArrayList<flight>list = new ArrayList<flight>();
</code>```

now i want print the elements of arraylist i use this syntax

```<code>System.out.println(list.get(0));
</code>```

but the out put is this
flight@1f96302
what should i do?
                                                                           another question how i can change them for example i want change the time of takeoff the first flight.

答:
Add a toString method in the class like below:

```<code>class flight
{
    public String start;
    public String end;
    public int timethatend ;
    public int timethatstart;
    flight ( int ts , int tf , String s , String e )
    {
        this.start = s;
        this.end =e;
        this.timethatend = tf;
        this.timethatstart = ts;
    }

    @Override
    public String toString() {
        return "flight{" +
                "start='" + start + '\'' +
                ", end='" + end + '\'' +
                ", timethatend=" + timethatend +
                ", timethatstart=" + timethatstart +
                '}';
    }
}
</code>```

To add new flight elements in the arraylist, to the following:

```<code>flight f = new flight(1,2,"12","34");
ArrayList<flight> list = new ArrayList<flight>();
list.add(f);
</code>```

To change the value of some element, do the following:

```<code>list.get(0).start = "1234";
</code>```

Body:
hi i want to know how i can access to elements of arraylist in java?
i have this class .

class flight
{
    public String start;
    public String end;
    public int timethatend ;
    public int timethatstart;
    flight ( int ts , int tf , String s , String e )
    {
        this.start = s;
        this.end =e;
        this.timethatend = tf;
        this.timethatstart = ts;
    }
}

and i have this arraylist in my main class

ArrayList<flight>list = new ArrayList<flight>();

now i want print the elements of arraylist i use this syntax

System.out.println(list.get(0));

but the out put is this
flight@1f96302
what should i do?
                                                                           another question how i can change them for example i want change the time of takeoff the first flight.

Body:
Add a toString method in the class like below:

class flight
{
    public String start;
    public String end;
    public int timethatend ;
    public int timethatstart;
    flight ( int ts , int tf , String s , String e )
    {
        this.start = s;
        this.end =e;
        this.timethatend = tf;
        this.timethatstart = ts;
    }

    @Override
    public String toString() {
        return "flight{" +
                "start='" + start + '\'' +
                ", end='" + end + '\'' +
                ", timethatend=" + timethatend +
                ", timethatstart=" + timethatstart +
                '}';
    }
}

To add new flight elements in the arraylist, to the following:

flight f = new flight(1,2,"12","34");
ArrayList<flight> list = new ArrayList<flight>();
list.add(f);

To change the value of some element, do the following:

list.get(0).start = "1234";


问:
Blink from loading (isPending) to resolved. Why?
This is my ember-twiddle that explain the entire situation:

https://ember-twiddle.com/758a294c26d4f66b201462c997f79e57

My problem is the loading message.

My posts are sideloaded and it can be a very very long time for download.

In the meantime I need to show a loading message (in twiddle this is green).

When I enter the category route from categories route I need the green loading directly, not a blink with red as you can see.

Why it's happening?

答:
This type of data loading can get a bit tricky (as you've run into ;-).  In your setup, do you want your category to display if the data hasn't loaded?

If you don't, then you can block your UI loading by requesting that your posts data get side-loaded your category route model hook:

```<code>model(params) {
  return this.store.findRecord('category', params.category_id, { include: 'posts' });

  // see the guides page about this
  // https://guides.emberjs.com/v2.12.0/models/relationships/#toc_retrieving-related-records
}
</code>```

Right now, your posts data request seems to be triggered by your template accessing the posts data (which is why you are seeing that flash).

If you do want to show category data while your post data loads (this is often the desired effect), then doing your secondary data loading in a posts component (that uses the appropriate category id) may be the cleanest way to handle this.

I've personally found using ember-concurrency for this type of task makes it much simpler.  This example might help point you in the right direction: http://ember-concurrency.com/#/docs/examples/autocomplete

Does that help?

Body:
This type of data loading can get a bit tricky (as you've run into ;-).  In your setup, do you want your category to display if the data hasn't loaded?

If you don't, then you can block your UI loading by requesting that your posts data get side-loaded your category route model hook:

model(params) {
  return this.store.findRecord('category', params.category_id, { include: 'posts' });

  // see the guides page about this
  // https://guides.emberjs.com/v2.12.0/models/relationships/#toc_retrieving-related-records
}

Right now, your posts data request seems to be triggered by your template accessing the posts data (which is why you are seeing that flash).

If you do want to show category data while your post data loads (this is often the desired effect), then doing your secondary data loading in a posts component (that uses the appropriate category id) may be the cleanest way to handle this.

I've personally found using ember-concurrency for this type of task makes it much simpler.  This example might help point you in the right direction: http://ember-concurrency.com/#/docs/examples/autocomplete

Does that help?


问:
How to add EditText input to custom model using data binding adapter?
This is my data binding adapter:

```<code>@BindingAdapter("taskMinutes")
public static void taskMinutes(@NonNull TextView view, @NonNull Task task) {
    if (task.getDueDate() == null) {
        view.setText("");
        return;
    }
    view.setText(String.valueOf(DateUtils.getDateMinutes(task.getDueDate())));
}
</code>```

And in xml:

```<code>app:taskMinutes="@{task}"
</code>```

And minutes show in EditText normally but didn't add to task.dueDate.

But how can I add adapter for add new input from EditText filed to task.dueDate?

答:
I think you should find this article useful for conversions with EditText

https://medium.com/google-developers/android-data-binding-inverse-functions-95aab4b11873

You can do 2-way conversion functions in an easier way than InverseBindingAdapers.

Body:
This is my data binding adapter:

@BindingAdapter("taskMinutes")
public static void taskMinutes(@NonNull TextView view, @NonNull Task task) {
    if (task.getDueDate() == null) {
        view.setText("");
        return;
    }
    view.setText(String.valueOf(DateUtils.getDateMinutes(task.getDueDate())));
}

And in xml:

app:taskMinutes="@{task}"

And minutes show in EditText normally but didn't add to task.dueDate.

But how can I add adapter for add new input from EditText filed to task.dueDate?


问:
Waiting time is too high to Get Response from HTTPS site compared with http site
I am having an MVC website and deployed as both https and http (test version) in amazon aws. I noticed latency with log-in for specific user role in https site compared to http site. When I checked in fiddler/developer tool, I noticed that waiting time is too high (33715 ms) to get html response for https site compared to http site (700 ms). Same log-in module has been used for other role and there is no latency for other roles.

I have checked the code and I did not see any issue with code or database performance and it also working perfectly for http site.

Any idea what could be possible issue for this slowness?

答:
After adding below code, site looks to be working as normal - </p>

```<code> $(document).ready(function () {
        $.ajaxSetup({ cache: false });
 });
</code>```

Body:
After adding below code, site looks to be working as normal -

 $(document).ready(function () {
        $.ajaxSetup({ cache: false });
 });


问:
In Redux, is it necessary to do deep copy
The below object is action.data has a nested object address

```<code>{
    name: 'Ben',
    address: {
        country: 'Australia',
        state: 'NSW'
    }
}
</code>```

How should I handle it in the reducer?

```<code>const rootReducer = (state = initState, action) {
    switch(action.type) {
        switch RECEIVE_DATA:
            return {...state, data: action.data}
    }
}
</code>```

Can I do it as above? that I just assign the whole object to data without copying?

or

```<code>const rootReducer = (state = initState, action) {
    switch(action.type) {
        switch RECEIVE_DATA:
            const address = {...action.data.address}
            const data = {...action.data, address}
            return {...state, data}
    }
}
</code>```

Or should I do a deep copy of the object and assign it to data?
thanks

答:
The "correct" way to handle updates of nested data is with multiple shallow copies, one for each level of nesting.  It's also certainly okay to create a new object that just replaces one field completely, per your first example.

See the Redux docs section on Immutable Update Patterns for some info on how to properly do immutable updates, and also the Redux FAQ entry regarding deep cloning.

Body:
The below object is action.data has a nested object address

{
    name: 'Ben',
    address: {
        country: 'Australia',
        state: 'NSW'
    }
}

How should I handle it in the reducer?

const rootReducer = (state = initState, action) {
    switch(action.type) {
        switch RECEIVE_DATA:
            return {...state, data: action.data}
    }
}

Can I do it as above? that I just assign the whole object to data without copying?

or

const rootReducer = (state = initState, action) {
    switch(action.type) {
        switch RECEIVE_DATA:
            const address = {...action.data.address}
            const data = {...action.data, address}
            return {...state, data}
    }
}

Or should I do a deep copy of the object and assign it to data?
thanks


问:
How to get/create/impersonate InitiatorSession in AEM workflow
In AEM workflow, When i try to impersonate workflowSession to initiator this throws exception :

javax.security.auth.login.FailedLoginException: Impersonation not
  allowed.

I necessarily need initiator's session to trigger some task in my workflow, earlier i used to get this using :

```<code>initiatorSession= adminSession.impersonate(new SimpleCredentials(initiatorUser,"".toCharArray()));
</code>```

where adminSession is now deprecated and we use system users now, and so i cannot impersonate system user to initiator user, any suggestions?

答: I don't know your use case, but you should not impersonate the initiator if the workflow is now assigned to a new user. You can always adapt the WorkflowSession to a Session: Session session = workflowSession.adaptTo(Session.class) which will get you the initiators session unless the workflow went through a user step and changed to a new user. Otherwise you can create a system User session as you mentioned and use that.

Body:
In AEM workflow, When i try to impersonate workflowSession to initiator this throws exception :

javax.security.auth.login.FailedLoginException: Impersonation not
  allowed.

I necessarily need initiator's session to trigger some task in my workflow, earlier i used to get this using :

initiatorSession= adminSession.impersonate(new SimpleCredentials(initiatorUser,"".toCharArray()));

where adminSession is now deprecated and we use system users now, and so i cannot impersonate system user to initiator user, any suggestions?


问:
"Ineligible value used in/as type annotation" error with Flow
I have a JS file:

```<code>// @flow
import type SomeType from './types';

export class MyClass extends React.Component {
  props: {
    someProp: Array<SomeType>
  };
}
</code>```

In types.js:

```<code>// @flow
export type SomeType = {
  someKey: number
}
</code>```

Running flow gives me the following error on Array<SomeType>:

```<code>exports. Ineligible value used in/as type annotation (did you forget 'typeof'?)
</code>```

答:
This is me being an ES6 noob. The fix is in how the type is imported. It should be:</p>

```<code>import type {SomeType} from './types';
</code>```

Body:
I have a JS file:

// @flow
import type SomeType from './types';

export class MyClass extends React.Component {
  props: {
    someProp: Array<SomeType>
  };
}

In types.js:

// @flow
export type SomeType = {
  someKey: number
}

Running flow gives me the following error on Array<SomeType>:

exports. Ineligible value used in/as type annotation (did you forget 'typeof'?)

Body:
This is me being an ES6 noob. The fix is in how the type is imported. It should be:

import type {SomeType} from './types';


问:
Increment and bitwise shift operator precedence?
Increment suffix and prefix are both of higher operator precedence than bitwise left shift, but the following prints out different results.

```<code>int testValue = 1;
std::cout << ++testValue; //prints 2
//saw it as std::cout << (++testValue);

testValue = 1;
std::cout << testValue++; //prints 1
//thought it was std::cout << (testValue++);
</code>```

Why does increment suffix as shown in the second example print 1 before incrmenting? I thought it was bound more tightly to testValue like in the increment prefix case, so I thought it'd be incremented first before being printed with std::cout.

答:
<< not bitwise operator, but insertion operator. cplusplus reference:

As an object of class ostream, characters can be written to it either
  as formatted data using the insertion operator (operator<<).

```<code>testValue = 1;
std::cout << testValue++; //prints 1
</code>```

Post increment means the increment is done after the variable is read.

Body:
Increment suffix and prefix are both of higher operator precedence than bitwise left shift, but the following prints out different results.

int testValue = 1;
std::cout << ++testValue; //prints 2
//saw it as std::cout << (++testValue);

testValue = 1;
std::cout << testValue++; //prints 1
//thought it was std::cout << (testValue++);

Why does increment suffix as shown in the second example print 1 before incrmenting? I thought it was bound more tightly to testValue like in the increment prefix case, so I thought it'd be incremented first before being printed with std::cout.

Body:
<< not bitwise operator, but insertion operator. cplusplus reference:

As an object of class ostream, characters can be written to it either
  as formatted data using the insertion operator (operator<<).

testValue = 1;
std::cout << testValue++; //prints 1

Post increment means the increment is done after the variable is read.


问:
How to change angular scope values using Casperjs
I was trying to automate some test cases for an angular booking app I was working on ,where I wanted to write a test case that was to be integrated with bitbucket pipeline. I found casperjs easy to start with.

There came a stage when I had to change the $scope values of the app .
Here is how I did it .

答:
CasperJS (also phantomjs) comes with an evaluate() method that takes a function inside which we could access the current page DOM context . It is recently that I understood how eval works wherever it be. Angular also comes with the angular.element(<element>).scope() that lets you access the scope of that particular element . In my case I wanted to change the start_time and end_time of a booking before clicking submit .

```<code>  casper.evaluate(function () {
    var scope = angular.element('booking-element').scope()
    var bookingForm = scope.booking;
    bookingForm.start_time = "2017-09-05 12:00";
    bookingForm.end_time = "2017-09-05 16:00"
    scope.$apply();
  });
</code>```

A casper.click('.submit-button') should be submit the button for you with the updated values .

Body:
CasperJS (also phantomjs) comes with an evaluate() method that takes a function inside which we could access the current page DOM context . It is recently that I understood how eval works wherever it be. Angular also comes with the angular.element(<element>).scope() that lets you access the scope of that particular element . In my case I wanted to change the start_time and end_time of a booking before clicking submit .

  casper.evaluate(function () {
    var scope = angular.element('booking-element').scope()
    var bookingForm = scope.booking;
    bookingForm.start_time = "2017-09-05 12:00";
    bookingForm.end_time = "2017-09-05 16:00"
    scope.$apply();
  });

A casper.click('.submit-button') should be submit the button for you with the updated values .


问:
How do I to make a member variable equal another member variable which is set in main()?
Consider the following C++ code for my program: CODE

When I run this program, it outputs the following:

**Chocolate mass: 41

Chocolate density: nan**

I want the program to output the volume variable divided by the mass variable. It seems to be doing this correctly, but it is dividing the values initialized to the variables in the object class, rather than dividing the values assigned to the variables in the main() function. How do I fix this?

All help is greatly appreciated!

答: You told the software the "updated" input i.e. weight, volume and mass but you never told the software to update its density given the new values of volume and mass. The value of density is calculated once in the constructor, which is only called once when you created the object (not to mention that I feel pretty nervous when people do things like 0/0). Need a separate function to update the density and call it.


问:
When should you check if a view != null before implementing it?
I am looking at Cheesesquare to learn some new design tools and I came across this bit of code that left me wondering. The code finds a view, then checks if it is null before continuing its setup.

Why would the view ever return null, assuming it exists and the id matches?

I trust the expertise of the person who wrote this code and I assume it is not a mistake, but what is its purpose? When should I check for null values and when is it unnecessary?

```<code>    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    if (navigationView != null) {
        setupDrawerContent(navigationView);
    }

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    if (viewPager != null) {
        setupViewPager(viewPager);
    }
</code>```

...

```<code>private void setupViewPager(ViewPager viewPager) {
    Adapter adapter = new Adapter(getSupportFragmentManager());
    adapter.addFragment(new CheeseListFragment(), "Category 1");
    adapter.addFragment(new CheeseListFragment(), "Category 2");
    adapter.addFragment(new CheeseListFragment(), "Category 3");
    viewPager.setAdapter(adapter);
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            menuItem.setChecked(true);
</code>```

答: The view would return null if, for whatever reason, findViewById(R.id.nav_view) returns null. This could happen if nav_view is missing, for example. Since that function has the possibility of returning null, the null value is checked to avoid a NullPointerException.

Body:
I am looking at Cheesesquare to learn some new design tools and I came across this bit of code that left me wondering. The code finds a view, then checks if it is null before continuing its setup.

Why would the view ever return null, assuming it exists and the id matches?

I trust the expertise of the person who wrote this code and I assume it is not a mistake, but what is its purpose? When should I check for null values and when is it unnecessary?

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    if (navigationView != null) {
        setupDrawerContent(navigationView);
    }

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    if (viewPager != null) {
        setupViewPager(viewPager);
    }

...

private void setupViewPager(ViewPager viewPager) {
    Adapter adapter = new Adapter(getSupportFragmentManager());
    adapter.addFragment(new CheeseListFragment(), "Category 1");
    adapter.addFragment(new CheeseListFragment(), "Category 2");
    adapter.addFragment(new CheeseListFragment(), "Category 3");
    viewPager.setAdapter(adapter);
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            menuItem.setChecked(true);


问:
array inside function
Create a function to display array.  </p>

答:
```<code>#include<stdio.h>

#define SIZE 5

int scoreList[SIZE];
int i;

int findTotal(int scoreList[SIZE], int inSmall, int inLarge){
        int total =0;
        int index;
        for (index = 0; index < SIZE; index++)
        {
                if (scoreList[index]!= inSmall && scoreList[index]!= inLarge)
                total = total + scoreList[index];
        }
        return total;
}
int findLarge(int scoreList[SIZE]){
        int index;
        int largest = scoreList[0];
        for (index=1; index < SIZE; index++)
        {
                if (scoreList[index] > largest)
                largest = scoreList[index];
        }
        return largest;
}
int findSmall(int scoreList[SIZE]){
        int index;
        int smallest = scoreList[0];
        for (index=1; index < SIZE; index++)
        {
                if (scoreList[index] < smallest)
                smallest = scoreList[index];
        }
        return smallest;
}

int main(){

        const char* question[] = { "I don't talk a lot", "I have people around me", "I love nature", "I talk about science", "And bla bla bla" };

        // char question[SIZE][100] = {"I don't talk a lot","why this is good","one two","fourth","fifth"}; // If you don't wish to use pointer, You will have to use a 2D char array that will store the total number of element and second one will store length of each element (here 100)

        for(i=0; i<SIZE; i++){
                printf("%s :\nYour Score: ", question[i]);
                scanf("%d", &scoreList[i]);
        }

        int smallest = findSmall(scoreList);
        int largest = findLarge(scoreList);
        int total = findTotal(scoreList, smallest, largest);

        printf("smallest: %d, largest: %d, total: %d\n", smallest, largest, total);
return 0;
}
</code>```

I have run it on my system. Working fine!

Title: array inside function

Body: Create a function to display array.

Body:
#include<stdio.h>

#define SIZE 5

int scoreList[SIZE];
int i;

int findTotal(int scoreList[SIZE], int inSmall, int inLarge){
        int total =0;
        int index;
        for (index = 0; index < SIZE; index++)
        {
                if (scoreList[index]!= inSmall && scoreList[index]!= inLarge)
                total = total + scoreList[index];
        }
        return total;
}
int findLarge(int scoreList[SIZE]){
        int index;
        int largest = scoreList[0];
        for (index=1; index < SIZE; index++)
        {
                if (scoreList[index] > largest)
                largest = scoreList[index];
        }
        return largest;
}
int findSmall(int scoreList[SIZE]){
        int index;
        int smallest = scoreList[0];
        for (index=1; index < SIZE; index++)
        {
                if (scoreList[index] < smallest)
                smallest = scoreList[index];
        }
        return smallest;
}

int main(){

        const char* question[] = { "I don't talk a lot", "I have people around me", "I love nature", "I talk about science", "And bla bla bla" };

        // char question[SIZE][100] = {"I don't talk a lot","why this is good","one two","fourth","fifth"}; // If you don't wish to use pointer, You will have to use a 2D char array that will store the total number of element and second one will store length of each element (here 100)

        for(i=0; i<SIZE; i++){
                printf("%s :\nYour Score: ", question[i]);
                scanf("%d", &scoreList[i]);
        }

        int smallest = findSmall(scoreList);
        int largest = findLarge(scoreList);
        int total = findTotal(scoreList, smallest, largest);

        printf("smallest: %d, largest: %d, total: %d\n", smallest, largest, total);
return 0;
}

I have run it on my system. Working fine!


答:
I hope the following tips will help:

Initialize the class members using class constructors, that's why constructors exist.

Use the existing setters to update the density. Each time setMass or setVolume is called, recalculate the density.

Whenever you use division, make sure you don't divide by 0.

Initialize variable with constants of the proper type. 0 is of type int by default while 0.0 is of type double.

Title: How do I to make a member variable equal another member variable which is set in main()?

Body:
Consider the following C++ code for my program: CODE

When I run this program, it outputs the following:

**Chocolate mass: 41

Chocolate density: nan**

I want the program to output the volume variable divided by the mass variable. It seems to be doing this correctly, but it is dividing the values initialized to the variables in the object class, rather than dividing the values assigned to the variables in the main() function. How do I fix this?

All help is greatly appreciated!


问:
WWF or WPF for flowcharts?
I want to be able to present my data using a flowchart. I can use wpf to do this, but I dont want to have to code all the arrows, connectors etc - I would like to use a library if possible..

Also could I use windows workflow foundation to do this in any way? Would this help? I get the impression although WWF is workflow, its more to do with the process as opposed to presenting data.

It appears that I might have to obtain a third party control to do this....any recommendations - the component should be able to draw a flowchart at the minimum!

Thanks

答: WWF is not intended to draw anything. So it will not help anyway. Writing the drawing code yourself or finding a 3rd party library to do it is up to you. I would have chosen the latter, because once I tried to do the former. I takes a lot of time and effort to do everything right.

Title: WWF or WPF for flowcharts?


问:
Async IDataErrorInfo - WPF
I have a problem when I want to use IDataErrorInfo (.NET 4.0) asynchronously. This code works perfectly.

```<code>EditViewModel.cs

public class EditViewModel : CustomViewModel, IDataErrorInfo
{
    string IDataErrorInfo.Error
    {
        get { throw new NotImplementedException(); }
    }

    string IDataErrorInfo.this[string propertyName] => _validationHandler.Validate(this, propertyName);

}

ValidationHandler.cs

public string Validate(object currentInstance, string propertyName)
{
    // BLA BLA BLA BLA BLA

    return ReturnErrorString

}
</code>```

What I want now is to be able to do it asynchronously. The code I leave below does not work. It does not return error or anything, only my form does not open and my application freezes.

```<code>private async Task<string> AsyncValidation(object currentInstance, string propertyName)
{
    return await TaskEx.Run(() =>
        {
            // BLA BLA BLA BLA BLA

            return ReturnErrorString
        }
    );
}

public string Validate(object currentInstance, string propertyName)
{
    return AsyncValidation(currentInstance, propertyName).Result;
}
</code>```

What am I doing wrong? Thank you

答:
Your new Validate function should look like this :

```<code>public async string Validate(object currentInstance, string propertyName)
{
    result = await AsyncValidation(currentInstance, propertyName);
    return result;
}
</code>```

Title: Async IDataErrorInfo - WPF

Body:
I have a problem when I want to use IDataErrorInfo (.NET 4.0) asynchronously. This code works perfectly.

EditViewModel.cs

public class EditViewModel : CustomViewModel, IDataErrorInfo
{
    string IDataErrorInfo.Error
    {
        get { throw new NotImplementedException(); }
    }

    string IDataErrorInfo.this[string propertyName] => _validationHandler.Validate(this, propertyName);

}

ValidationHandler.cs

public string Validate(object currentInstance, string propertyName)
{
    // BLA BLA BLA BLA BLA

    return ReturnErrorString

}

What I want now is to be able to do it asynchronously. The code I leave below does not work. It does not return error or anything, only my form does not open and my application freezes.

private async Task<string> AsyncValidation(object currentInstance, string propertyName)
{
    return await TaskEx.Run(() =>
        {
            // BLA BLA BLA BLA BLA

            return ReturnErrorString
        }
    );
}

public string Validate(object currentInstance, string propertyName)
{
    return AsyncValidation(currentInstance, propertyName).Result;
}

What am I doing wrong? Thank you

Body:
Your new Validate function should look like this :

public async string Validate(object currentInstance, string propertyName)
{
    result = await AsyncValidation(currentInstance, propertyName);
    return result;
}


问:
What's the difference between using `.catch(function(error)` and `function(errResponse)` when handing errors from AngularJS promises?
I'm reading AngularJS Up and Running. In chapter 6, it mentions handing errors from promises like this:

```<code>$http.get('/api/server-config').then(function(configResponse) {
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}, function(error) {
    // Common error handling
});
</code>```

And in other places, I see .catch() being used (for example, the answer here: Assigning variable from a factory to a control doesn't work uses .catch() like so:

```<code>BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}).catch(function(errorResponse) {
    self.cerrorMessages = errorResponse.data;
});
</code>```

My question is, what's the difference between the above menthod and the method shown in the book:

```<code>BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}, function(error) {
    self.cerrorMessages = errorResponse.data;
});
</code>```

What's preferred?

答:
According to AngularJS 1.2 documentation

catch(errorCallback) – shorthand for promise.then(null, errorCallback)

It means you can use the 2 syntaxes interchangeably.

Body:
I'm reading AngularJS Up and Running. In chapter 6, it mentions handing errors from promises like this:

$http.get('/api/server-config').then(function(configResponse) {
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}, function(error) {
    // Common error handling
});

And in other places, I see .catch() being used (for example, the answer here: Assigning variable from a factory to a control doesn't work uses .catch() like so:

BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}).catch(function(errorResponse) {
    self.cerrorMessages = errorResponse.data;
});

My question is, what's the difference between the above menthod and the method shown in the book:

BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}, function(error) {
    self.cerrorMessages = errorResponse.data;
});

What's preferred?


问:
What is the different between web/static and priv/static in phoenix?
I am new to elixir and phoenix. Now I have trouble with the static assets in phoenix.

I want to add a js file in my page, and I add the following code in my template:

```<code><script src="<%= static_path(@conn, "/js/test.js") %>"></script>
</code>```

and then create a js file at web/static/js/test.js.

However, I got the error about test.js is not found in the browser's console.

I notice there is a priv/static/js folder, and I try to create the js file at priv/static/js/test.js.

This time, the error gone.

I am really confuse about this.

What is the different between web/static and priv/static ? If I need to test my static files in develop environment, where should I put the static files?
and how about the production environment ?

Thanks.

答:
Priv/static contains processed and concatenated files. I.e they will be saved in this folder after the compilation. However check if your Brunch is working as it takes files from web/static. For better understanding i recommend you go through the doc
 http://www.phoenixframework.org/docs/static-assets</p>

Body:
I am new to elixir and phoenix. Now I have trouble with the static assets in phoenix.

I want to add a js file in my page, and I add the following code in my template:

and then create a js file at web/static/js/test.js.

However, I got the error about test.js is not found in the browser's console.

I notice there is a priv/static/js folder, and I try to create the js file at priv/static/js/test.js.

This time, the error gone.

I am really confuse about this.

What is the different between web/static and priv/static ? If I need to test my static files in develop environment, where should I put the static files?
and how about the production environment ?

Thanks.


答:
Ok there is a bug in your program...
Change this line:

```<code>Double getDensity()const{return density;}
</code>```

To:

```<code>Double getDensity(){density=volume/mass;return density;}
</code>```

And replace:

```<code>Double density = volume/mass;
</code>```

To:

```<code>Double density;
</code>```

Next time please paste code. Screen shots will not work...

Body:
Ok there is a bug in your program...
Change this line:

Double getDensity()const{return density;}

To:

Double getDensity(){density=volume/mass;return density;}

And replace:

Double density = volume/mass;

To:

Double density;

Next time please paste code. Screen shots will not work...


问:
Deprecated header <codecvt> replacement
A bit of foreground: my task required converting UTF-8 XML file to UTF-16 (with proper header, of course). And so I searched about usual ways of converting UTF-8 to UTF-16, and found out that one should use templates from <codecvt>.

But now when it is deprecated, I wonder what is the new common way of doing the same task?

(Don't mind using Boost at all, but other than that I prefer to stay as close to standard library as possible.)

答:
Don't worry about that.

According to the same information source:

this library component should be retired to Annex D, along side ,
  until a suitable replacement is standardized.

So, you can still use it until a new standardized, more-secure version is done.

Title: Deprecated header <codecvt> replacement


问:
Android: How do I prevent the soft keyboard from pushing my view up?
I have a vertical sliding drawer at the bottom of my app. When the soft keyboard opens, it pushes the tab for the drawer up, so it sits atop the keyboard. I actually want it to remain at the bottom of the screen, becoming hidden when the keyboard is shown.

Anyone else run into this issue? Know how to fix it?

答:
Include in your manifest file under activity which you want to display .But make sure not using Full screen Activity </p>

```<code>android:windowSoftInputMode="adjustPan"
</code>```

Body:
Include in your manifest file under activity which you want to display .But make sure not using Full screen Activity

android:windowSoftInputMode="adjustPan"


问:
read lines in txt file [java]
I'll try to be as clear as possible but pardon me if my question is not perfect.
I have a txt file with several lines of data. example:

123 ralph bose 20000 200 1 2

256 ed shane 30000 100 2 4

...

I need to read each line sequentially and pass it back to a method in a separate class for processing. I know how to break down each line into elements by using StringTokenizer.

However, i'm not sure how to read one line at a time, pass back the elements to the other class and then, once the processing is done, to read the NEXT line. Method cooperation between my classes works fine (tested) but how do i read one line at a time?

I was thinking of creating an array where each line would be an array element but as the number of lines will be unknown i cannot create an array as i don't know its final length.

Thanks

Baba

EDIT

rough setup :

Class A

```<code>end_of_file = f1.readRecord(emp);

        if(!end_of_file)
        {
           slip.printPay(slipWrite);
        }
</code>```

Class B

```<code>public boolean readRecord(Employee pers) throws IOException {

        boolean eof = false ;

        String line = in.readLine() ;

                ???

                }
</code>```

filename is never passed around

so up until here i can read the first line but i think i need a way to loop through the lines to read them one by one with back and forth between classes.

tricky...

答:
```<code>void readLine(String fileName)
{
   java.io.BufferedReader br = null;
   try
   {
      br = new java.io.BufferedReader(new java.io.FileReader(fileName));
      String line = null;
      while(true)
      {
          line = br.readLine();
          if(line == null)
             break;
          // process your line here
      }
   }catch(Exception e){
   }finally{
     if(br != null)
      {
         try{br.close();}catch(Exception e){}
       }
   }
}
</code>```

Also if you want to split strings... use

String classes split method. for splitting depending on space... you can do ... line.split("\\s*")

Hope it works

Title: read lines in txt file [java]

Body:
I'll try to be as clear as possible but pardon me if my question is not perfect.
I have a txt file with several lines of data. example:

123 ralph bose 20000 200 1 2

256 ed shane 30000 100 2 4

...

I need to read each line sequentially and pass it back to a method in a separate class for processing. I know how to break down each line into elements by using StringTokenizer.

However, i'm not sure how to read one line at a time, pass back the elements to the other class and then, once the processing is done, to read the NEXT line. Method cooperation between my classes works fine (tested) but how do i read one line at a time?

I was thinking of creating an array where each line would be an array element but as the number of lines will be unknown i cannot create an array as i don't know its final length.

Thanks

Baba

EDIT

rough setup :

Class A

end_of_file = f1.readRecord(emp);

        if(!end_of_file)
        {
           slip.printPay(slipWrite);
        }

Class B

public boolean readRecord(Employee pers) throws IOException {

        boolean eof = false ;

        String line = in.readLine() ;

                ???

                }

filename is never passed around

so up until here i can read the first line but i think i need a way to loop through the lines to read them one by one with back and forth between classes.

tricky...

Body:
void readLine(String fileName)
{
   java.io.BufferedReader br = null;
   try
   {
      br = new java.io.BufferedReader(new java.io.FileReader(fileName));
      String line = null;
      while(true)
      {
          line = br.readLine();
          if(line == null)
             break;
          // process your line here
      }
   }catch(Exception e){
   }finally{
     if(br != null)
      {
         try{br.close();}catch(Exception e){}
       }
   }
}

Also if you want to split strings... use

String classes split method. for splitting depending on space... you can do ... line.split("\\s*")

Hope it works


问:
Positioning div right under an a tag
I'm trying to make a drop down menu to appear right under the URL that opens it up. So far I've managed to make a menu appear, but I can't figure out how to position it properly. My HTML looks like this

```<code><div id="container">
  Content here
  <div class="line-gray-footer"></div>
  <div class="footer">
    <a href="#">Link 1</a> | <a id="langSwitch">English ▼</a>
    <div id="dropdown" class="drop-choices">
      <a class="choice" href="/de">Deutsch</a>
      <a class="choice" href="/fr">Français</a>
      <a class="choice" href="/it">Italiano</a>
      <a class="choice" href="/es">Español</a>
    </div>
  </div>
  <div class="morestuff">
  <table>
  <tr>
    <th>Test</th><th>Test</th>
  </tr>
  <tr>
    <td>A</td><td>b</td>
  </tr>
  </table>
  </div>
</div>
</code>```

CSS

```<code>#container{
  width:70%;
  background: red;
  margin: 0 auto;
  height:800px;
}
.line-gray-footer {
    background: #ececec none repeat scroll 0 0;
    height: 3px;
    margin: 10px 10px;
}
.footer {
    text-align: center;
}

.drop-choices.inuse {
    opacity: 1;
    visibility: visible;
    display: block;
}

.drop-choices {
    background-color: white;
    border: 1px solid gray;
    border: medium none;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.24);
    display: none;
    line-height: normal;
    margin-top: 0;
    opacity: 0;
    position: absolute;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1) 0s;
    visibility: hidden;
    white-space: nowrap;
    z-index: 100;

}

.drop-choices a.choice {
    border-bottom: 1px solid #edf1f3;
    color: #777;
    padding: 3px 12px;
    transition: all 0.1s ease 0s;
    cursor: pointer;
    display: block;
    padding: 2px 3px 1px;
}
.morestuff table{
  width: 100%;
  border: 1px solid black;
}
</code>```

Here is a jsFiddle URL of the whole thing https://jsfiddle.net/jaktav3t/

答:
You just put parent div and set display: inline-block it will work

```<code> <div class="footer">
        <a href="#">Link 1</a> | <div style="display: inline-block">

            <a id="langSwitch">English ▼</a>
            <div id="dropdown" class="drop-choices">
          <a class="choice" href="/de">Deutsch</a>
          <a class="choice" href="/fr">Français</a>
          <a class="choice" href="/it">Italiano</a>
          <a class="choice" href="/es">Español</a>
        </div>
        </div>

      </div>
</code>```

Title: Positioning div right under an a tag

Body:
I'm trying to make a drop down menu to appear right under the URL that opens it up. So far I've managed to make a menu appear, but I can't figure out how to position it properly. My HTML looks like this

  Content here

    Link 1 | English ▼

      Deutsch
      Français
      Italiano
      Español

    Test	Test

    A	b

CSS

#container{
  width:70%;
  background: red;
  margin: 0 auto;
  height:800px;
}
.line-gray-footer {
    background: #ececec none repeat scroll 0 0;
    height: 3px;
    margin: 10px 10px;
}
.footer {
    text-align: center;
}

.drop-choices.inuse {
    opacity: 1;
    visibility: visible;
    display: block;
}

.drop-choices {
    background-color: white;
    border: 1px solid gray;
    border: medium none;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.24);
    display: none;
    line-height: normal;
    margin-top: 0;
    opacity: 0;
    position: absolute;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1) 0s;
    visibility: hidden;
    white-space: nowrap;
    z-index: 100;

}

.drop-choices a.choice {
    border-bottom: 1px solid #edf1f3;
    color: #777;
    padding: 3px 12px;
    transition: all 0.1s ease 0s;
    cursor: pointer;
    display: block;
    padding: 2px 3px 1px;
}
.morestuff table{
  width: 100%;
  border: 1px solid black;
}

Here is a jsFiddle URL of the whole thing https://jsfiddle.net/jaktav3t/

Body:
You just put parent div and set display: inline-block it will work

 <div class="footer">
        <a href="#">Link 1</a> | <div style="display: inline-block">

            <a id="langSwitch">English ▼</a>
            <div id="dropdown" class="drop-choices">
          <a class="choice" href="/de">Deutsch</a>
          <a class="choice" href="/fr">Français</a>
          <a class="choice" href="/it">Italiano</a>
          <a class="choice" href="/es">Español</a>
        </div>
        </div>

      </div>


问:
nodejs how to serve node_modules directory to front end for access?
Without using any packaging software such as Browserify or Webpack, I have a simple server that in nodejs.

```<code>var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
app.use(bodyParser());
app.use(express.static('public'));
app.use(express.static('node_modules'));

app.post('/api/searchjob', function (req, res) {
  res.json({data: "hello"});
});

app.get('/', function(req,res) {
  res.sendfile('public/index.html');
});

app.get('/*', function(req, res){
  res.redirect('/');
})

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!')
});
</code>```

I want the front end to also have access to some node_modules packages, what can i do? my index.html file is in "public" directory, the folder structure look like this:

```<code>├── README.md
├── index.js
├── node_modules
├── package.json
├── public
└── yarn.lock
</code>```

I tried simply put the script tag in index.html, but doesn't work
>

答:
You are already using the express static middleware to serve files from your node_modules directory, so a path like this should work:</p>

```<code><script src="/vue2-google-maps/dist/vue-google-maps.js"></script>
</code>```

Body:
Without using any packaging software such as Browserify or Webpack, I have a simple server that in nodejs.

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
app.use(bodyParser());
app.use(express.static('public'));
app.use(express.static('node_modules'));

app.post('/api/searchjob', function (req, res) {
  res.json({data: "hello"});
});

app.get('/', function(req,res) {
  res.sendfile('public/index.html');
});

app.get('/*', function(req, res){
  res.redirect('/');
})

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!')
});

I want the front end to also have access to some node_modules packages, what can i do? my index.html file is in "public" directory, the folder structure look like this:

├── README.md
├── index.js
├── node_modules
├── package.json
├── public
└── yarn.lock

I tried simply put the script tag in index.html, but doesn't work
>

Body:
You are already using the express static middleware to serve files from your node_modules directory, so a path like this should work:

<script src="/vue2-google-maps/dist/vue-google-maps.js"></script>


问:
'printf' vs. 'cout' in C++
What is the difference between printf() and cout in C++?

答:
TL;DR: Always do your own research, in regard of generated machine code size, performance, readability and coding time before trusting random comments online, including this one.

I'm no expert. I just happened to overhear two co-workers talking about how we should avoid using C++ in embedded systems because of performance issues. Well, interesting enough, I did a benchmark based on a real project task.

In said task, we had to write some config to RAM. Something like:

coffee=hot

  sugar=none

  milk=breast

  mac=AA:BB:CC:DD:EE:FF

Here's my benchmark programs (Yes, I know OP asked about printf(), not fprintf(). Try to capture the essence and by the way, OP's link points to fprintf() anyway.)

C program:

```<code>char coffee[10], sugar[10], milk[10];
unsigned char mac[6];

/* Initialize those things here. */

FILE * f = fopen("a.txt", "wt");

fprintf(f, "coffee=%s\nsugar=%s\nmilk=%s\nmac=%02X:%02X:%02X:%02X:%02X:%02X\n", coffee, sugar, milk, mac[0], mac[1],mac[2],mac[3],mac[4],mac[5]);

fclose(f);
</code>```

C++ program:

```<code>//Everything else is identical except:

std::ofstream f("a.txt", std::ios::out);

f << "coffee=" << coffee << "\n";
f << "sugar=" << sugar << "\n";
f << "milk=" << milk << "\n";
f << "mac=" << (int)mac[0] << ":"
    << (int)mac[1] << ":"
    << (int)mac[2] << ":"
    << (int)mac[3] << ":"
    << (int)mac[4] << ":"
    << (int)mac[5] << endl;
f.close();
</code>```

I did my best to polish them before I looped them both 100,000 times. Here are the results:

C program:

```<code>real    0m 8.01s
user    0m 2.37s
sys     0m 5.58s
</code>```

C++ program:

```<code>real    0m 6.07s
user    0m 3.18s
sys     0m 2.84s
</code>```

Object file size:

```<code>C   - 2,092 bytes
C++ - 3,272 bytes
</code>```

Conclusion: On my very specific platform, with a very specific processor, running a very specific version of Linux kernel, to run a program which is compiled with a very specific version of GCC, in order to accomplish a very specific task, I would say the C++ approach is more suitable because it runs significantly faster and provide much better readability. On the other hand, C offers small footprint, in my opinion, means nearly nothing because program size is not of our concern.

Remeber, YMMV.

Title: 'printf' vs. 'cout' in C++

Body:
TL;DR: Always do your own research, in regard of generated machine code size, performance, readability and coding time before trusting random comments online, including this one.

I'm no expert. I just happened to overhear two co-workers talking about how we should avoid using C++ in embedded systems because of performance issues. Well, interesting enough, I did a benchmark based on a real project task.

In said task, we had to write some config to RAM. Something like:

coffee=hot

  sugar=none

  milk=breast

  mac=AA:BB:CC:DD:EE:FF

Here's my benchmark programs (Yes, I know OP asked about printf(), not fprintf(). Try to capture the essence and by the way, OP's link points to fprintf() anyway.)

C program:

char coffee[10], sugar[10], milk[10];
unsigned char mac[6];

/* Initialize those things here. */

FILE * f = fopen("a.txt", "wt");

fprintf(f, "coffee=%s\nsugar=%s\nmilk=%s\nmac=%02X:%02X:%02X:%02X:%02X:%02X\n", coffee, sugar, milk, mac[0], mac[1],mac[2],mac[3],mac[4],mac[5]);

fclose(f);

C++ program:

//Everything else is identical except:

std::ofstream f("a.txt", std::ios::out);

f << "coffee=" << coffee << "\n";
f << "sugar=" << sugar << "\n";
f << "milk=" << milk << "\n";
f << "mac=" << (int)mac[0] << ":"
    << (int)mac[1] << ":"
    << (int)mac[2] << ":"
    << (int)mac[3] << ":"
    << (int)mac[4] << ":"
    << (int)mac[5] << endl;
f.close();

I did my best to polish them before I looped them both 100,000 times. Here are the results:

C program:

real    0m 8.01s
user    0m 2.37s
sys     0m 5.58s

C++ program:

real    0m 6.07s
user    0m 3.18s
sys     0m 2.84s

Object file size:

C   - 2,092 bytes
C++ - 3,272 bytes

Conclusion: On my very specific platform, with a very specific processor, running a very specific version of Linux kernel, to run a program which is compiled with a very specific version of GCC, in order to accomplish a very specific task, I would say the C++ approach is more suitable because it runs significantly faster and provide much better readability. On the other hand, C offers small footprint, in my opinion, means nearly nothing because program size is not of our concern.

Remeber, YMMV.


问:
Unexpected token with es6 map in reactjs
I have this in jsx where is an array like breadcrumb = ['food','hotdogt'] but I got an error of unexpected token .?

```<code>{breadcrumb.map(obj => {
   {obj}
})}
</code>```

答:
Write it like this:

```<code>{
    breadcrumb.map(obj => {
         return <div> {obj} </div>
    })
}
</code>```

or

```<code>{
   breadcrumb.map(obj => <div> {obj} </div>)
}
</code>```

or

```<code>{
   breadcrumb.map(obj => obj)
}
</code>```

{} braces are required when you are using js code inside html element, you are using {obj} but didn't use any html element. And you forgot to use return also.

Check this example:

var breadcrumb = ['food','hotdogt'];

var App = () => {
   return(

          {
             breadcrumb.map(obj =>
 {obj}
)
          }
          {
             breadcrumb.map((obj, i) => {
                return
                            {obj}
                           {i != breadcrumb.length -1 ?  ->  : null}

             })
          }

   )
}

ReactDOM.render(<App/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

Body:
I have this in jsx where is an array like breadcrumb = ['food','hotdogt'] but I got an error of unexpected token .?

{breadcrumb.map(obj => {
   {obj}
})}

Body:
Write it like this:

{
    breadcrumb.map(obj => {
         return <div> {obj} </div>
    })
}

or

{
   breadcrumb.map(obj => <div> {obj} </div>)
}

or

{
   breadcrumb.map(obj => obj)
}

{} braces are required when you are using js code inside html element, you are using {obj} but didn't use any html element. And you forgot to use return also.

Check this example:

var breadcrumb = ['food','hotdogt'];

var App = () => {
   return(
       <div>
          {
             breadcrumb.map(obj => <p key={obj}> {obj} </p>)
          }
          {
             breadcrumb.map((obj, i) => {
                return <span key={obj}>
                           <span className="bold"> {obj} </span>
                           {i != breadcrumb.length -1 ? <span className="seperator"> -> </span> : null}
                       </span>
             })
          }
       </div>
   )
}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


问:
Dplyr: filter last entry for date in a series
I want to filter only the last date entry in a time series for every occurrence where there was more than one for a given month.

As an example in a table like this:

```<code>obs <- c("A", "B", "A", "B", "A", "B", "A", "B")
date <- c("2017-01-01", "2017-01-01", "2017-02-01", "2017-02-01", "2017-03-01", "2017-03-01", "2017-03-02","2017-03-02")
num <- c(1000, 1800, 2000, 2900, 3000, 3400, 3500, 3400)
dat <- data.frame(obs, date, num)

    obs       date  num
1   A 2017-01-01 1000
2   B 2017-01-01 1800
3   A 2017-02-01 2000
4   B 2017-02-01 2900
5   A 2017-03-01 3000
6   B 2017-03-01 3400
7   A 2017-03-02 3500
8   B 2017-03-02 3400
</code>```

A simple selection for "A" would be:

```<code>x <- dat %>%
  filter(obs=="A") %>%
  select(obs, date, num) %>%
  mutate(date = ymd(date))

  obs       date  num
1   A 2017-01-01 1000
2   A 2017-02-01 2000
3   A 2017-03-01 3000
4   A 2017-03-02 3500
</code>```

So, there are now two entries for the third month and I would like to keep only the most recent entry for that month. I thought it would be a straightforward thing to do so I did:

```<code>x <- dat %>%
  filter(obs=="A") %>%
  select(obs, date, num) %>%
  mutate(date = ymd(date)) %>%
  arrange(date) %>%
  slice(which.max(date))
</code>```

But I get just the last entry instead with the other ones removed. What am I missing? The output should be:

```<code>  obs       date  num
1   A 2017-01-01 1000
2   A 2017-02-01 2000
4   A 2017-03-02 3500
</code>```

答:
We can do this using base R

```<code>i1 <- with(dat, ave(as.integer(as.Date(date)), obs,
     format(as.Date(date), "%m"), FUN = function(x) x== max(x)) & obs=="A")
dat[i1,]
#  obs       date  num
#1   A 2017-01-01 1000
#3   A 2017-02-01 2000
#7   A 2017-03-02 3500
</code>```

Body:
I want to filter only the last date entry in a time series for every occurrence where there was more than one for a given month.

As an example in a table like this:

obs <- c("A", "B", "A", "B", "A", "B", "A", "B")
date <- c("2017-01-01", "2017-01-01", "2017-02-01", "2017-02-01", "2017-03-01", "2017-03-01", "2017-03-02","2017-03-02")
num <- c(1000, 1800, 2000, 2900, 3000, 3400, 3500, 3400)
dat <- data.frame(obs, date, num)

    obs       date  num
1   A 2017-01-01 1000
2   B 2017-01-01 1800
3   A 2017-02-01 2000
4   B 2017-02-01 2900
5   A 2017-03-01 3000
6   B 2017-03-01 3400
7   A 2017-03-02 3500
8   B 2017-03-02 3400

A simple selection for "A" would be:

x <- dat %>%
  filter(obs=="A") %>%
  select(obs, date, num) %>%
  mutate(date = ymd(date))

  obs       date  num
1   A 2017-01-01 1000
2   A 2017-02-01 2000
3   A 2017-03-01 3000
4   A 2017-03-02 3500

So, there are now two entries for the third month and I would like to keep only the most recent entry for that month. I thought it would be a straightforward thing to do so I did:

x <- dat %>%
  filter(obs=="A") %>%
  select(obs, date, num) %>%
  mutate(date = ymd(date)) %>%
  arrange(date) %>%
  slice(which.max(date))

But I get just the last entry instead with the other ones removed. What am I missing? The output should be:

  obs       date  num
1   A 2017-01-01 1000
2   A 2017-02-01 2000
4   A 2017-03-02 3500

Body:
We can do this using base R

i1 <- with(dat, ave(as.integer(as.Date(date)), obs,
     format(as.Date(date), "%m"), FUN = function(x) x== max(x)) & obs=="A")
dat[i1,]
#  obs       date  num
#1   A 2017-01-01 1000
#3   A 2017-02-01 2000
#7   A 2017-03-02 3500


问:
Codeigniter 3 really slow query when Group By is called
I have this query

```<code>SELECT `PR_CODIGO`, `PR_EXIBIR`, `PR_NOME`, `PRC_DETALHES` FROM `PROPRIETARIOS` LEFT JOIN `PROPRIETARIOSCONTATOS` ON `PROPRIETARIOSCONTATOS`.`PRC_COD_CAD` = `PROPRIETARIOS`.`PR_CODIGO` WHERE `PR_EXIBIR` = 'T' LIMIT 20
</code>```

It runs very fast, less than 1 second.

If i add GROUP BY, it takes several seconds (5+) to run. Even the Group By field being index.

I'm using group by because the query above returns repeated rows (i search for a name and his contacts on another table, show's 4 times same name).

How do i fix this?

答:
With the GROUP BY clause, the LIMIT clause isn't applied until after the rows are collapsed by the group by operation.

To get an understanding of the operations that MySQL is performing and which indexes are being considered and chosen by the optimizer, we use EXPLAIN.

Unstated in the question is what "field" (columns or expressions) are in the GROUP BY clause. So we are only guessing.

Based on the query shown in the question...

```<code>SELECT pr.pr_codigo
     , pr.pr_exibir
     , pr.pr_nome
     , prc.prc_detalhes
  FROM `PROPRIETARIOS` pr
  LEFT
  JOIN `PROPRIETARIOSCONTATOS` prc
    ON prc.prc_cod_cad = pr.pr_codigo
 WHERE pr.pr_exibir = 'T'
 LIMIT 20
</code>```

Our guess at the most appropriate indexes...

```<code> ... ON PROPRIETARIOSCONTATOS (prc_cod_cad, prc_detalhes)

 ... ON PROPRIETARIOS (pr_exibir, pr_codigo, pr_exibir, pr_nome)
</code>```

Our guess is going to change depending on what column(s) are listed in the GROUP BY clause.  And we might also suggest an alternative query to return an equivalent result.

But without knowing the GROUP BY clause, without knowing if our guesses about which table each column is from are correct, without knowing the column datatypes, without any estimates of cardinality, and without example data and expected output, ... we're flying blind and just making guesses.

Body:
I have this query

SELECT `PR_CODIGO`, `PR_EXIBIR`, `PR_NOME`, `PRC_DETALHES` FROM `PROPRIETARIOS` LEFT JOIN `PROPRIETARIOSCONTATOS` ON `PROPRIETARIOSCONTATOS`.`PRC_COD_CAD` = `PROPRIETARIOS`.`PR_CODIGO` WHERE `PR_EXIBIR` = 'T' LIMIT 20

It runs very fast, less than 1 second.

If i add GROUP BY, it takes several seconds (5+) to run. Even the Group By field being index.

I'm using group by because the query above returns repeated rows (i search for a name and his contacts on another table, show's 4 times same name).

How do i fix this?

Body:
With the GROUP BY clause, the LIMIT clause isn't applied until after the rows are collapsed by the group by operation.

To get an understanding of the operations that MySQL is performing and which indexes are being considered and chosen by the optimizer, we use EXPLAIN.

Unstated in the question is what "field" (columns or expressions) are in the GROUP BY clause. So we are only guessing.

Based on the query shown in the question...

SELECT pr.pr_codigo
     , pr.pr_exibir
     , pr.pr_nome
     , prc.prc_detalhes
  FROM `PROPRIETARIOS` pr
  LEFT
  JOIN `PROPRIETARIOSCONTATOS` prc
    ON prc.prc_cod_cad = pr.pr_codigo
 WHERE pr.pr_exibir = 'T'
 LIMIT 20

Our guess at the most appropriate indexes...

 ... ON PROPRIETARIOSCONTATOS (prc_cod_cad, prc_detalhes)

 ... ON PROPRIETARIOS (pr_exibir, pr_codigo, pr_exibir, pr_nome)

Our guess is going to change depending on what column(s) are listed in the GROUP BY clause.  And we might also suggest an alternative query to return an equivalent result.

But without knowing the GROUP BY clause, without knowing if our guesses about which table each column is from are correct, without knowing the column datatypes, without any estimates of cardinality, and without example data and expected output, ... we're flying blind and just making guesses.


问:
Issue with WPF StringFormat
I have had this line in several location in my xaml for awhile StringFormat={}{0:#,##0.00} ISK}

Visual Studio has long since had it underlined but it always compiled fine. Today each one of these entries throws 3 errors one complaining type # doesn't exist, another that a period is expected for the , for the thousands separator, and finally that there is a space.

Is there a more reliable way to format this number as a string?

EDIT:
For completion I undid the one change I made between the last build and the current one just to make sure that wasn't some how messing it up.

答:
Is there a more reliable way to format this number as a string?

I haven't been able to reproduce your failure to compile the code. The XAML editor does complain, with the blue squiggly line and the complaint about the type not being found. If you don't mind the in-editor warning, I would expect that you should be able to get it to convert okay.

However, as a general replacement for the StringFormat binding property, you might consider a simple converter:

```<code>class StringFormatConverter : IValueConverter
{
    public string Format { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        dynamic o = value;

        return o.ToString(Format);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

It will work with any type that has a ToString(string) method. You can use it like this:

```<code><Window x:Class="TestSO43152859StringFormatNumber.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:l="clr-namespace:TestSO43152859StringFormatNumber"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">

  <Window.DataContext>
    <s:Double>98123.45</s:Double>
  </Window.DataContext>

  <Window.Resources>
    <l:StringFormatConverter x:Key="iskNumericConverter" Format="#,##0.00 ISK"/>
  </Window.Resources>

  <Grid>
    <TextBlock HorizontalAlignment="Left" VerticalAlignment="Top"
               Text="{Binding Converter={StaticResource iskNumericConverter}}"/>
  </Grid>
</Window>
</code>```

Title: Issue with WPF StringFormat

Body:
Is there a more reliable way to format this number as a string?

I haven't been able to reproduce your failure to compile the code. The XAML editor does complain, with the blue squiggly line and the complaint about the type not being found. If you don't mind the in-editor warning, I would expect that you should be able to get it to convert okay.

However, as a general replacement for the StringFormat binding property, you might consider a simple converter:

class StringFormatConverter : IValueConverter
{
    public string Format { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        dynamic o = value;

        return o.ToString(Format);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

It will work with any type that has a ToString(string) method. You can use it like this:

<Window x:Class="TestSO43152859StringFormatNumber.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:l="clr-namespace:TestSO43152859StringFormatNumber"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">

  <Window.DataContext>
    <s:Double>98123.45</s:Double>
  </Window.DataContext>

  <Window.Resources>
    <l:StringFormatConverter x:Key="iskNumericConverter" Format="#,##0.00 ISK"/>
  </Window.Resources>

  <Grid>
    <TextBlock HorizontalAlignment="Left" VerticalAlignment="Top"
               Text="{Binding Converter={StaticResource iskNumericConverter}}"/>
  </Grid>
</Window>