问:
Netlogo, Moving Turtle along links
I am doing model where I want my agents to move along links between nodes. The idea is that all turtles move a constant distance after each tick. (Note I dont want them jump from one node to the another, also lets assume that its not possible to make the nodes at a constant distances, because I am trying to implement it on a gis model where of course the vertices are not at constant distances)

For this model there are two type of agents butterflies and collectors. Each of the agents placed on nodes which are linked to each other. The collectors find the closest butterfly to them using in-radius and then finds the path using nw: turtles-on-weight-path function. So for example lets suppose collector-02 has located butterfly-19. The path is [node-2 node-5 node-1 node-9]. I want the collector to travel to these nodes to get to the butterfly but instead of jumping to each node. He has to travel a distance of 0.01 netlogo units on the link from node-2 to node-5 and eventually node-9 where the butterfly is located.
The function follow-path is incomplete and it where i getting into trouble.
ANy ideas how to solve this problem. Thanks

```<code>extensions [nw]
globals [current-loc-global butterfly-location link-distance]

breed [nodes node]
breed [collectors collector]
breed [butterflys butterfly]

links-own [dist]
nodes-own [consist-butterfly linked-to]
collectors-own [ distance-from-location current-loc new-location targeted-
butterfly initial-node next-node current-node previous-node
node-butterfly-at commute-path route-length next-pos]
butterflys-own [ initial-node-collectors targeted? node-butterfly-on]

to setup
  clear-all

  ;creating nodes
  create-nodes 60[
    set color blue
    set shape "circle"
    set consist-butterfly nobody
  ]
  ask nodes [create-link-with one-of other nodes]

  repeat 500[layout]
  ask nodes [setxy 0.95 * xcor * 0.95 ycor]

 create-butterflys number-of-butterflys[
    set node-butterfly-on one-of nodes
    set shape "butterfly"
    move-to node-butterfly-on
    set initial-node-collectors current-loc-global
    set targeted? false
  ]

  ask nodes [
    set consist-butterfly min-one-of butterflys in-radius 0.0001 [distance
myself]
  ]

  create-collectors number-of-collectors[
    set current-loc one-of nodes with [consist-butterfly = nobody]
    set color red
    set targeted-butterfly nobody
    move-to current-loc
  ]

  ask collectors[
  set current-loc-global  current-loc
  ]

  ask links [
    let end-point-1 end1
    let end-point-2 end2
    set link-distance 0
    ask end1[set linked-to end-point-2
      set link-distance distance end-point-2
    ]
    set dist link-distance
    ask end2[
      set linked-to end-point-1
    ]
  ]

  reset-ticks
end

to layout
  layout-spring nodes links 0.5 1 1
end

to go
  find-agents
  find-path
  follow-path
end

to find-agents
  ask collectors [
    if targeted-butterfly = nobody[set targeted-butterfly min-one-of
    butterflys in-radius 10 with [not targeted?] [distance myself]]
    if targeted-butterfly != nobody [ask targeted-butterfly [set targeted?
    true]]
  ]

  ask collectors with [targeted-butterfly != nobody][

    ask targeted-butterfly [set butterfly-location node-butterfly-on]
    set node-butterfly-at butterfly-location
  ]
end

to find-path
  ask collectors with [targeted-butterfly != nobody ][

    set initial-node min-one-of nodes in-radius 0.0001 [distance myself]
    let end-location node-butterfly-at

    let path []
    ask initial-node [set path nw:turtles-on-weighted-path-to end-location
    dist]
    set commute-path path

    set route-length length commute-path

    set current-node initial-node
    set previous-node current-node
    set next-node current-node
  ]
end

to follow-path
  ask collectors with [targeted-butterfly != nobody][
  set distance-from-location distance current-node
    ifelse 0.09 < distance-from-location
    [jump 0.09]
    [move-to current-node
     set current-node next-node
      face next-node]
</code>```

]

end

答:
Managed to sort it out. Need to change the follow-path function as follows:</p>

```<code>to follow-path
 ask collectors with [targeted-butterfly != nobody][
  set distance-from-location distance current-node

  set next-pos ((position(current-node) commute-path) + 1)
  if next-pos < route-length [set next-node item(next-pos) commute-path]

    ifelse 0.09 < distance-from-location
    [jump 0.09]
    [move-to current-node
     set current-node next-node
      face next-node]
  ]

end
</code>```

Title: Netlogo, Moving Turtle along links

Body:
I am doing model where I want my agents to move along links between nodes. The idea is that all turtles move a constant distance after each tick. (Note I dont want them jump from one node to the another, also lets assume that its not possible to make the nodes at a constant distances, because I am trying to implement it on a gis model where of course the vertices are not at constant distances)

For this model there are two type of agents butterflies and collectors. Each of the agents placed on nodes which are linked to each other. The collectors find the closest butterfly to them using in-radius and then finds the path using nw: turtles-on-weight-path function. So for example lets suppose collector-02 has located butterfly-19. The path is [node-2 node-5 node-1 node-9]. I want the collector to travel to these nodes to get to the butterfly but instead of jumping to each node. He has to travel a distance of 0.01 netlogo units on the link from node-2 to node-5 and eventually node-9 where the butterfly is located.
The function follow-path is incomplete and it where i getting into trouble.
ANy ideas how to solve this problem. Thanks

extensions [nw]
globals [current-loc-global butterfly-location link-distance]

breed [nodes node]
breed [collectors collector]
breed [butterflys butterfly]

links-own [dist]
nodes-own [consist-butterfly linked-to]
collectors-own [ distance-from-location current-loc new-location targeted-
butterfly initial-node next-node current-node previous-node
node-butterfly-at commute-path route-length next-pos]
butterflys-own [ initial-node-collectors targeted? node-butterfly-on]

to setup
  clear-all

  ;creating nodes
  create-nodes 60[
    set color blue
    set shape "circle"
    set consist-butterfly nobody
  ]
  ask nodes [create-link-with one-of other nodes]

  repeat 500[layout]
  ask nodes [setxy 0.95 * xcor * 0.95 ycor]

 create-butterflys number-of-butterflys[
    set node-butterfly-on one-of nodes
    set shape "butterfly"
    move-to node-butterfly-on
    set initial-node-collectors current-loc-global
    set targeted? false
  ]

  ask nodes [
    set consist-butterfly min-one-of butterflys in-radius 0.0001 [distance
myself]
  ]

  create-collectors number-of-collectors[
    set current-loc one-of nodes with [consist-butterfly = nobody]
    set color red
    set targeted-butterfly nobody
    move-to current-loc
  ]

  ask collectors[
  set current-loc-global  current-loc
  ]

  ask links [
    let end-point-1 end1
    let end-point-2 end2
    set link-distance 0
    ask end1[set linked-to end-point-2
      set link-distance distance end-point-2
    ]
    set dist link-distance
    ask end2[
      set linked-to end-point-1
    ]
  ]

  reset-ticks
end

to layout
  layout-spring nodes links 0.5 1 1
end

to go
  find-agents
  find-path
  follow-path
end

to find-agents
  ask collectors [
    if targeted-butterfly = nobody[set targeted-butterfly min-one-of
    butterflys in-radius 10 with [not targeted?] [distance myself]]
    if targeted-butterfly != nobody [ask targeted-butterfly [set targeted?
    true]]
  ]

  ask collectors with [targeted-butterfly != nobody][

    ask targeted-butterfly [set butterfly-location node-butterfly-on]
    set node-butterfly-at butterfly-location
  ]
end

to find-path
  ask collectors with [targeted-butterfly != nobody ][

    set initial-node min-one-of nodes in-radius 0.0001 [distance myself]
    let end-location node-butterfly-at

    let path []
    ask initial-node [set path nw:turtles-on-weighted-path-to end-location
    dist]
    set commute-path path

    set route-length length commute-path

    set current-node initial-node
    set previous-node current-node
    set next-node current-node
  ]
end

to follow-path
  ask collectors with [targeted-butterfly != nobody][
  set distance-from-location distance current-node
    ifelse 0.09 < distance-from-location
    [jump 0.09]
    [move-to current-node
     set current-node next-node
      face next-node]

]

end

Body:
Managed to sort it out. Need to change the follow-path function as follows:

to follow-path
 ask collectors with [targeted-butterfly != nobody][
  set distance-from-location distance current-node

  set next-pos ((position(current-node) commute-path) + 1)
  if next-pos < route-length [set next-node item(next-pos) commute-path]

    ifelse 0.09 < distance-from-location
    [jump 0.09]
    [move-to current-node
     set current-node next-node
      face next-node]
  ]

end


来源: stackexchange

问:
How can I specify on delete no action in .NET Standard 2.0 mapping? PostgreSQL
I want to define on delete no action in my .NET Standard 2.0 mapping, but I don't find how can I do it.

This is an example of my mappings:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<task>()
                .HasOne<job>(x => x.job).WithMany();
}
</code>```

I'm tried using OnDelete method, but it just has options Restrict, SetNULL, Cascade and ClientSetNULL. If I don't specify OnDelete method, by default it is set to Restrict.

How can I specify no action in my mappings?

答:
Table mapping independent database on entity framework. You will be use the example;

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
        .HasOptional<Standard>(s => s.Standard)
        .WithMany()
        .WillCascadeOnDelete(false);
}
</code>```

referans: https://learn.microsoft.com/tr-tr/ef/core/saving/cascade-delete

ContentLicense: CC BY-SA 4.0

Body:
I want to define on delete no action in my .NET Standard 2.0 mapping, but I don't find how can I do it.

This is an example of my mappings:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<task>()
                .HasOne<job>(x => x.job).WithMany();
}

I'm tried using OnDelete method, but it just has options Restrict, SetNULL, Cascade and ClientSetNULL. If I don't specify OnDelete method, by default it is set to Restrict.

How can I specify no action in my mappings?

Body:
Table mapping independent database on entity framework. You will be use the example;

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
        .HasOptional<Standard>(s => s.Standard)
        .WithMany()
        .WillCascadeOnDelete(false);
}

referans: https://learn.microsoft.com/tr-tr/ef/core/saving/cascade-delete


问:
How to order tr based on td value in Jquery
I'm setting up a table with data which always orders the rows based on the highest value in a td.

I've tried using this function which does sort the rows but then appends new rows into my table so I get replicated rows.

I have my table set up like this and I need to check the TOT column which need to order by highest score.

$(document).ready(function() {
  sortTable($('#table'), 'asc');
});

function sortTable(table, order) {
  var asc = order === 'asc',
    tbody = table.find('tbody');

  tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:first', a).text().localeCompare($('td:first', b).text());
    } else {
      return $('td:first', b).text().localeCompare($('td:first', a).text());
    }
  }).appendTo(tbody);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <table id="table">
    <tr>
      <th></th>
      <th>POS</th>
      <th>TEAM</th>
      <th>DRIVER</th>
      <th>TOT</th>
    </tr>
    <tbody>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>85</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>100</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>34</td>
      </tr>
    </tbody>
  </table>
</div></code>```

答:
You are appending the sorted rows to the table (.appendTo(tbody)). Instead you should replace the children of your tbody with html for example.

Your first td of each row is empty, so there is nothing to compare and sort.

But your could should look like below to make it work, if the first td is filled:

```<code>function sortTable(table, order) {
  var asc = order === 'asc';
  var tbody = table.find('tbody');

  var sorted = tbody.find('tr').sort(function(a, b) {
    console.log(a,b)
    if (asc) return $('td:first', a).text().localeCompare($('td:first', b).text());

    return $('td:first', b).text().localeCompare($('td:first', a).text());

  })

  tbody.html(sorted);
}
</code>```

Body:
I'm setting up a table with data which always orders the rows based on the highest value in a td.

I've tried using this function which does sort the rows but then appends new rows into my table so I get replicated rows.

I have my table set up like this and I need to check the TOT column which need to order by highest score.

$(document).ready(function() {
  sortTable($('#table'), 'asc');
});

function sortTable(table, order) {
  var asc = order === 'asc',
    tbody = table.find('tbody');

  tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:first', a).text().localeCompare($('td:first', b).text());
    } else {
      return $('td:first', b).text().localeCompare($('td:first', a).text());
    }
  }).appendTo(tbody);
}

      POS
      TEAM
      DRIVER
      TOT

        1ST
        PROSPORT PERFORMANCE (85)
        ROBERT RENAUER
        85

        1ST
        PROSPORT PERFORMANCE (85)
        ROBERT RENAUER
        100

        1ST
        PROSPORT PERFORMANCE (85)
        ROBERT RENAUER
        34

Body:
You are appending the sorted rows to the table (.appendTo(tbody)). Instead you should replace the children of your tbody with html for example.

Your first td of each row is empty, so there is nothing to compare and sort.

But your could should look like below to make it work, if the first td is filled:

function sortTable(table, order) {
  var asc = order === 'asc';
  var tbody = table.find('tbody');

  var sorted = tbody.find('tr').sort(function(a, b) {
    console.log(a,b)
    if (asc) return $('td:first', a).text().localeCompare($('td:first', b).text());

    return $('td:first', b).text().localeCompare($('td:first', a).text());

  })

  tbody.html(sorted);
}


问:
IE11 meta element Breaks SVG
I've embedded an SVG files data directly into my html. It shows in Chrome and Firefox, but in IE11 it doesn't show at all.  The pastebin link to the SVG is http://pastebin.com/eZpLXFfD

I've tried adding a META TAG but to no avail. At first I thought it might be a IE Compatibility view issue, but toggling that feature did not work either.

<meta http-equiv="X-UA-Compatible" content="IE=8">

Any help?  What else Information Can I provide to help answer this question

答:
Check if the Browser is IE -</p>

```<code>  $ua = htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8');
  if (preg_match('~MSIE|Internet Explorer~i', $ua) || (strpos($ua, 'Trident/7.0') !== false && strpos($ua, 'rv:11.0') !== false)) {
    // do stuff for IE Here
  }
</code>```

ContentLicense: CC BY-SA 3.0

Title: IE11 meta element Breaks SVG

Body:
Check if the Browser is IE -

  $ua = htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8');
  if (preg_match('~MSIE|Internet Explorer~i', $ua) || (strpos($ua, 'Trident/7.0') !== false && strpos($ua, 'rv:11.0') !== false)) {
    // do stuff for IE Here
  }


问:
Javascript automatic form submission
I took this quick script from another post on StackOverflow, but it doesn't seem to work on my form. It just throws an error saying 'object expected'. Can anyone help me fix it.

```<code><html>
<head></head>
<body onLoad="document.forms[0].submit()">
    <form name="EPDQForm" method="post" action="mypage.aspx" >
        <input name="item" type="hidden" value="data">
    </form>
</body>
</html>
</code>```

EDIT:

This is the exact page code (I removed most of it for displaying on here):

```<code><html>

    <head></head>

    <body onLoad="document.forms[0].submit()">

        <form id="myform" name="myform" method="post" action="https://secure2.mde.epdq.co.uk/cgi-bin/CcxBarclaysEpdq.e">

            <input name="epdqdata" type="hidden" value="972">
            <input name="returnurl" type="hidden" value="http://www.xxxx.co.uk/Secure/EPDQReturn.aspx">
            <input name="merchantdisplayname" type="hidden" value="xxxxxx">
            <input name="submit" type="hidden" value="purchase">
            <input name="shipping" type="hidden" value="0.00">
            <input name="baddr1" type="hidden" value="152 Smith St">
            <input name="baddr2" type="hidden" value="">
            <input name="bcity" type="hidden" value="Manchester">
            <input name="bcountry" type="hidden" value="UK">
            <input name="bpostalcode" type="hidden" value="M4 6DH">
            <input name="email" type="hidden" value="xxxx@xxxx.co.uk">
            <input name="saddr1" type="hidden" value="152 Smith St">
            <input name="scity" type="hidden" value="Manchester">
            <input name="scountyprovince" type="hidden" value="Alderney">
            <input name="scountry" type="hidden" value="UK">
            <input name="spostalcode" type="hidden" value="M4 5GG">

        </form>

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

This code shows the error. And I don't see why. In firefox it says:

```<code>document.forms[0].submit is not a function
</code>```

答:
What happens if you remove the onload attribute from your opening  tag and place this code just before your closing  tag?

```<code><script>
    var frm = document.getElementById('myform');
    if (frm) {
        frm.submit();
    }
</script>
</code>```

Title: Javascript automatic form submission

Body:
I took this quick script from another post on StackOverflow, but it doesn't seem to work on my form. It just throws an error saying 'object expected'. Can anyone help me fix it.

    <form name="EPDQForm" method="post" action="mypage.aspx" >
        <input name="item" type="hidden" value="data">
    </form>

EDIT:

This is the exact page code (I removed most of it for displaying on here):

        <form id="myform" name="myform" method="post" action="https://secure2.mde.epdq.co.uk/cgi-bin/CcxBarclaysEpdq.e">

            <input name="epdqdata" type="hidden" value="972">
            <input name="returnurl" type="hidden" value="http://www.xxxx.co.uk/Secure/EPDQReturn.aspx">
            <input name="merchantdisplayname" type="hidden" value="xxxxxx">
            <input name="submit" type="hidden" value="purchase">
            <input name="shipping" type="hidden" value="0.00">
            <input name="baddr1" type="hidden" value="152 Smith St">
            <input name="baddr2" type="hidden" value="">
            <input name="bcity" type="hidden" value="Manchester">
            <input name="bcountry" type="hidden" value="UK">
            <input name="bpostalcode" type="hidden" value="M4 6DH">
            <input name="email" type="hidden" value="xxxx@xxxx.co.uk">
            <input name="saddr1" type="hidden" value="152 Smith St">
            <input name="scity" type="hidden" value="Manchester">
            <input name="scountyprovince" type="hidden" value="Alderney">
            <input name="scountry" type="hidden" value="UK">
            <input name="spostalcode" type="hidden" value="M4 5GG">

        </form>

This code shows the error. And I don't see why. In firefox it says:

document.forms[0].submit is not a function

Body:
What happens if you remove the onload attribute from your opening <body> tag and place this code just before your closing </body> tag?

<script>
    var frm = document.getElementById('myform');
    if (frm) {
        frm.submit();
    }
</script>


问:
phpmailer No Relay Access Allowed Error
My website is hosted on godaddy, and I just figured out that my website is no more sending emails through phpmailer since last few months. I uploaded the latest version of phpmailer but still no success. The online web mail of my website runs fine. If I use php's "mail" function, it does send emails to gmail, but not to yahoo accounts.

I tried all the three ports 25, 465, and 587, but no luck

I am getting the following error from phpmailer:

```<code>SERVER -> CLIENT: 554 p3plsmtpa07-10.prod.phx3.secureserver.net ESMTP No Relay Access Allowed From 50.63.196.51
CLIENT -> SERVER: EHLO lostandfound.pakproject.com
SERVER -> CLIENT:
SMTP ERROR: EHLO command failed:
SMTP NOTICE: EOF caught while checking if connected
SMTP Error: Could not authenticate.
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
</code>```

Following is my code that I am trying to test. (User name, passwords, emails are changed...)

```<code><?php

date_default_timezone_set('Etc/UTC');
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "smtpout.... my_server";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "here_i_used_my_website_email";

$mail->Password = "here_password";
$mail->setFrom('website_email', 'From name');
$mail->addReplyTo('website_email', 'From name');
$mail->addAddress('another_email', 'name_used_here');

$mail->Subject = 'About the task';
$mail->Body = 'This is email body';
$mail->AltBody = 'This is a plain-text message body';

if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}
?>
</code>```

答:
I was able to resolve my issue with the following code/settings of phpmailer</p>

```<code><?php

$recipient = "abc@def.com"
$subject = "Subject here";
$emailBody = "This is body";

// PHP MAILER CODE STARTS FROM HERE //
require '../phpmailermaster/PHPMailerAutoload.php';
$mail = new PHPMailer;

//$mail->SMTPDebug = 3;    // Enable verbose debug output

$mail->isSMTP();       // Set mailer to use SMTP
$mail->Host = 'smtpout.secureserver.net'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxx@yyyy.com'; // SMTP username
$mail->Password = '3344123';  // SMTP password

//$mail->SMTPSecure = 'ssl';    // Enable TLS encryption, `ssl` also accepted
//$mail->Port = 465;

$mail->Port = 80;   // TCP port to connect to [THIS PORT ALLOWING EMAILS]
$mail->setFrom('xxx@yyyy.com', 'hello');

//$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient

$mail->addAddress($recipient);                 // Name is optional

//$mail->addReplyTo('info@example.com', 'Information');

//$mail->addBCC('bcc@example.com');
//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
//$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = $subject;
$mail->Body    = $emailBody;
$mail->AltBody = $emailBody;

if(!$mail->send())
{
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
    echo 'Message has been sent';
}

// PHP MAILER CODE ENDS HERE ==

?>
</code>```

Title: phpmailer No Relay Access Allowed Error

Body:
My website is hosted on godaddy, and I just figured out that my website is no more sending emails through phpmailer since last few months. I uploaded the latest version of phpmailer but still no success. The online web mail of my website runs fine. If I use php's "mail" function, it does send emails to gmail, but not to yahoo accounts.

I tried all the three ports 25, 465, and 587, but no luck

I am getting the following error from phpmailer:

SERVER -> CLIENT: 554 p3plsmtpa07-10.prod.phx3.secureserver.net ESMTP No Relay Access Allowed From 50.63.196.51
CLIENT -> SERVER: EHLO lostandfound.pakproject.com
SERVER -> CLIENT:
SMTP ERROR: EHLO command failed:
SMTP NOTICE: EOF caught while checking if connected
SMTP Error: Could not authenticate.
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Following is my code that I am trying to test. (User name, passwords, emails are changed...)

<?php

date_default_timezone_set('Etc/UTC');
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "smtpout.... my_server";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "here_i_used_my_website_email";

$mail->Password = "here_password";
$mail->setFrom('website_email', 'From name');
$mail->addReplyTo('website_email', 'From name');
$mail->addAddress('another_email', 'name_used_here');

$mail->Subject = 'About the task';
$mail->Body = 'This is email body';
$mail->AltBody = 'This is a plain-text message body';

if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}
?>

Body:
I was able to resolve my issue with the following code/settings of phpmailer

<?php

$recipient = "abc@def.com"
$subject = "Subject here";
$emailBody = "This is body";

// PHP MAILER CODE STARTS FROM HERE //
require '../phpmailermaster/PHPMailerAutoload.php';
$mail = new PHPMailer;

//$mail->SMTPDebug = 3;    // Enable verbose debug output

$mail->isSMTP();       // Set mailer to use SMTP
$mail->Host = 'smtpout.secureserver.net'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxx@yyyy.com'; // SMTP username
$mail->Password = '3344123';  // SMTP password

//$mail->SMTPSecure = 'ssl';    // Enable TLS encryption, `ssl` also accepted
//$mail->Port = 465;

$mail->Port = 80;   // TCP port to connect to [THIS PORT ALLOWING EMAILS]
$mail->setFrom('xxx@yyyy.com', 'hello');

//$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient

$mail->addAddress($recipient);                 // Name is optional

//$mail->addReplyTo('info@example.com', 'Information');

//$mail->addBCC('bcc@example.com');
//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
//$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = $subject;
$mail->Body    = $emailBody;
$mail->AltBody = $emailBody;

if(!$mail->send())
{
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
    echo 'Message has been sent';
}

// PHP MAILER CODE ENDS HERE ==

?>


问:
How to simplify sympy vectors?
I am doing some symbolic vector calculations using sympy, but I can't simplify the arguments of the vector class in a proper way. Consider this code:

from sympy.physics.mechanics import ReferenceFrame, dot, cross
from sympy import symbols, sin, cos, simplify

alpha, theta, l = symbols('alpha theta l')

def Rodrigues(v, k, angle):
    return cos(angle) * v + cross(k, v) * sin(angle) + k * dot(k, v) * (1- cos(angle))

N = ReferenceFrame('N')
P0 = -l * N.y

P2 = Rodrigues(
    Rodrigues(P0, -N.z, alpha),
    Rodrigues(N.x, -N.z, alpha),
    theta)
```

<p>which returns:</p>

```

```

<p>trying the <code>simplify(P2)</code> I get the error:</p>

<blockquote>
  <p>AttributeError: 'function' object has no attribute 'x'</p>
</blockquote>

<p>which I think is because the <code>simplify</code> requires a <code>sympy</code> expression object. trying the <code>dir(P2)</code> there is a <code>simplify</code> method which returns: </p>

```<bound method Vector.simplify of - l*sin(alpha)*cos(theta)*N.x - l*cos(alpha)*cos(theta)*N.y + (-l*sin(alpha)**2 - l*cos(alpha)**2)*sin(theta)*N.z>
```

<p>which I have no idea what it is! trying the <code>P2.args</code> I get:</p>

```[(Matrix([
  [                       -l*sin(alpha)*cos(theta)],
  [                       -l*cos(alpha)*cos(theta)],
  [(-l*sin(alpha)**2 - l*cos(alpha)**2)*sin(theta)]]), N)]
```

<p>which is a 1D List of a 2D tuple with a nested 3x1 <code>sympy</code> Matrix! I don't know whos choice was to make the vector class so obscure, but now I can simplify the last element with <code>simplify(P2.args[0][0][2])</code> and change the function to:</p>

<pre class="lang-py prettyprint-override"><code>def Rodrigues(v, k, angle):
    tmpVec = cos(angle) * v + cross(k, v) * sin(angle) + k * dot(k, v) * (1- cos(angle))
    tmpFrame = tmpVec.args[0][1]
    return simplify(tmpVec.args[0][0][0]) * tmpFrame.x + simplify(tmpVec.args[0][0][1]) * tmpFrame.y + simplify(tmpVec.args[0][0][2]) * tmpFrame.z
</code>```

which to me seems like a very bad solution.

I was wondering if you could help me know if there is a more Pythonic way to do this. For example, force sympy to simplify all expressions by default. Or maybe I'm using the vector.simplify method in a wrong way? Thanks for your support in advance.

P.S. Rodrigues rotation formula

答:
An alternative solution is to force sympy to simplify all vectors by default:

from sympy.physics.vector import Vector
Vector.simp = True
```

more info here

Title: How to simplify sympy vectors?

Body:
I am doing some symbolic vector calculations using sympy, but I can't simplify the arguments of the vector class in a proper way. Consider this code:

from sympy.physics.mechanics import ReferenceFrame, dot, cross
from sympy import symbols, sin, cos, simplify

alpha, theta, l = symbols('alpha theta l')

def Rodrigues(v, k, angle):
    return cos(angle) * v + cross(k, v) * sin(angle) + k * dot(k, v) * (1- cos(angle))

N = ReferenceFrame('N')
P0 = -l * N.y

P2 = Rodrigues(
    Rodrigues(P0, -N.z, alpha),
    Rodrigues(N.x, -N.z, alpha),
    theta)

which returns:

trying the simplify(P2) I get the error:

AttributeError: 'function' object has no attribute 'x'

which I think is because the simplify requires a sympy expression object. trying the dir(P2) there is a simplify method which returns:

<bound method Vector.simplify of - l*sin(alpha)*cos(theta)*N.x - l*cos(alpha)*cos(theta)*N.y + (-l*sin(alpha)**2 - l*cos(alpha)**2)*sin(theta)*N.z>

which I have no idea what it is! trying the P2.args I get:

[(Matrix([
  [                       -l*sin(alpha)*cos(theta)],
  [                       -l*cos(alpha)*cos(theta)],
  [(-l*sin(alpha)**2 - l*cos(alpha)**2)*sin(theta)]]), N)]

which is a 1D List of a 2D tuple with a nested 3x1 sympy Matrix! I don't know whos choice was to make the vector class so obscure, but now I can simplify the last element with simplify(P2.args[0][0][2]) and change the function to:

def Rodrigues(v, k, angle):
    tmpVec = cos(angle) * v + cross(k, v) * sin(angle) + k * dot(k, v) * (1- cos(angle))
    tmpFrame = tmpVec.args[0][1]
    return simplify(tmpVec.args[0][0][0]) * tmpFrame.x + simplify(tmpVec.args[0][0][1]) * tmpFrame.y + simplify(tmpVec.args[0][0][2]) * tmpFrame.z

which to me seems like a very bad solution.

I was wondering if you could help me know if there is a more Pythonic way to do this. For example, force sympy to simplify all expressions by default. Or maybe I'm using the vector.simplify method in a wrong way? Thanks for your support in advance.

P.S. Rodrigues rotation formula

Body:
An alternative solution is to force sympy to simplify all vectors by default:

from sympy.physics.vector import Vector
Vector.simp = True

more info here


问:
Consolidate array of numbers without exceeding a predefined maximum value per element
I'm trying to combine numbers in an array by adding them so that the max value can only by 30.

For example, this is my array:

```<code>array(10,30,10,10,15);
</code>```

After combining the numbers in the array to items with a max value 30, the result should be:

```<code>array(30,30,15);
</code>```

How to achieve this?

答:
You can loop only once to get this,

```<code>$temp = array(10,30,10,10,15);
natsort($temp); // sorting to reduce hustle and complication
$result = [];
$i = 0;
$maxValue = 30;
foreach($temp as $v){
    // checking sum is greater or value is greater or $v is greater than equal to
    if(!empty($result[$i]) && (($result[$i]+$v) > $maxValue)){
        $i++;
    }
    $result[$i] = (!empty($result[$i]) ? ($result[$i]+$v) : $v);
}
print_r($result);
</code>```

Working demo.

Body:
I'm trying to combine numbers in an array by adding them so that the max value can only by 30.

For example, this is my array:

array(10,30,10,10,15);

After combining the numbers in the array to items with a max value 30, the result should be:

array(30,30,15);

How to achieve this?

Body:
You can loop only once to get this,

$temp = array(10,30,10,10,15);
natsort($temp); // sorting to reduce hustle and complication
$result = [];
$i = 0;
$maxValue = 30;
foreach($temp as $v){
    // checking sum is greater or value is greater or $v is greater than equal to
    if(!empty($result[$i]) && (($result[$i]+$v) > $maxValue)){
        $i++;
    }
    $result[$i] = (!empty($result[$i]) ? ($result[$i]+$v) : $v);
}
print_r($result);

Working demo.


问:
IsBadReadPtr analogue on Unix
Is there a function analogous to IsBadReadPtr in Unix? At least some functionalities of IsBadReadPtr?
I want to write a procedure which would react if something bad happens to a process (like SIGSEGV) and recover some information. But I want to check the pointers to make sure that the data is not corrupt and see if they can be accessed safely. Otherwise the crash handling procedure itself will crash, thus becoming useless.

Any suggestions?

答:
I ran into the same issue trying to read a 'pixel' from a framebuffer while running Ubuntu from within a virtualbox. There seemed to be no secure way to check access without crashing or acutally hanging gdb. The suggestion made by StasM hinted me towards to following working 'local' solution using fork.</p>

```<code>void *some_address;
int pid = fork();
if (pid== 0)
{
    someaddress[0] = some_address[0];
    _exit(123);
}
bool access_ok = true;
int status;
int result = waitpid(pid, &status, 0);
if (result == -1 || WIFEXITED(status) == 0 || WEXITSTATUS(status) != 123)
{
    access_ok = false;
}
</code>```

Title: IsBadReadPtr analogue on Unix

Body:
I ran into the same issue trying to read a 'pixel' from a framebuffer while running Ubuntu from within a virtualbox. There seemed to be no secure way to check access without crashing or acutally hanging gdb. The suggestion made by StasM hinted me towards to following working 'local' solution using fork.

void *some_address;
int pid = fork();
if (pid== 0)
{
    someaddress[0] = some_address[0];
    _exit(123);
}
bool access_ok = true;
int status;
int result = waitpid(pid, &status, 0);
if (result == -1 || WIFEXITED(status) == 0 || WEXITSTATUS(status) != 123)
{
    access_ok = false;
}


问:
How to use where to query the database using mongoose
I want to create an endpoint for the user to search for something, so im querying the database using where a particular row inlcudes the text the user has searched but $where keeps giving me an error that it is not a function

I have tried using the $where but to no avail

```<code>router.get('/mobile/courses/search/:search_text', async(req, res)=>{
    try {
        const search = await Course.find()
        search.$where(function () {
            return req.params.search_text.toLowerCase().includes(this.course_name.toLowerCase())
        })
        if (!search){
            return res.status(404).send({result: 'No Result found'})
        }

        res.status(200).send({result: search})
    }catch (e) {
        res.status(500).send({error: 'Unknown Error Occurred Try Again', codeerror: e.toString()})
    }
})
</code>```

I want to be able to query the database for what the user has searched from a particular column (course_name) and return a response of the rows containing that at least three letters from the text the user searched

答:
First index the field that you want to search

```<code>Course.index({ course_name: 'text' });
</code>```

Then use $regex

```<code>CourseModal
    .find({
        course_name: {
            $regex: searchString,
            $options: 'i'
        }
    })
</code>```

Body:
I want to create an endpoint for the user to search for something, so im querying the database using where a particular row inlcudes the text the user has searched but $where keeps giving me an error that it is not a function

I have tried using the $where but to no avail

router.get('/mobile/courses/search/:search_text', async(req, res)=>{
    try {
        const search = await Course.find()
        search.$where(function () {
            return req.params.search_text.toLowerCase().includes(this.course_name.toLowerCase())
        })
        if (!search){
            return res.status(404).send({result: 'No Result found'})
        }

        res.status(200).send({result: search})
    }catch (e) {
        res.status(500).send({error: 'Unknown Error Occurred Try Again', codeerror: e.toString()})
    }
})

I want to be able to query the database for what the user has searched from a particular column (course_name) and return a response of the rows containing that at least three letters from the text the user searched

Body:
First index the field that you want to search

Course.index({ course_name: 'text' });

Then use $regex

CourseModal
    .find({
        course_name: {
            $regex: searchString,
            $options: 'i'
        }
    })


问:
How to select and show thousands of records
I have an SQLite query that, potentially, returns thousands of records. I need to show these records in a ListView but, obviously, I cannot show them all together. Which is the Android-way to solve this problem?</p>

答: You can limit amount of items or make page-links (0-100, 101-200 etc).</p>


问:
Remove data with non-datetime input in DataFrame
I have a dataframe and I would like to filter the data based on the 'timestamp' column. Supposedly, if there are non-numerical data (which also mean string) in the timestamp column, I would like to extract the entire row of data and save it into another file.

答:
You can check if the values in the timestamps columns are timestamps by using the isinstance() function. This will allow you to store them in a list. Here is a way you could do it :

```<code>import datetime

df = pd.DataFrame({'Timestamp' : [datetime.datetime(2020, 1, 1), 'aer', datetime.datetime(2019, 3, 1)]})

timestamps = [x for x in df['Timestamp'] if not(isinstance(x, datetime.date)) ]
new_df = pd.DataFrame({'Timestamp' : timestamps }))
</code>```

Out :

```<code>Timestamp
0   aer
</code>```

Body:
You can check if the values in the timestamps columns are timestamps by using the isinstance() function. This will allow you to store them in a list. Here is a way you could do it :

import datetime

df = pd.DataFrame({'Timestamp' : [datetime.datetime(2020, 1, 1), 'aer', datetime.datetime(2019, 3, 1)]})

timestamps = [x for x in df['Timestamp'] if not(isinstance(x, datetime.date)) ]
new_df = pd.DataFrame({'Timestamp' : timestamps }))

Out :

Timestamp
0   aer


问:
How do I write a join query across multiple tables in CakePHP?
can anyone tell me, how to retrieve joined result from multiple tables in cakePHP ( using cakePHP mvc architecture). For example, I have three tables to join (tbl_topics, tbl_items, tbl_votes. Their relationship is defined as following: a topic can have many items and an item can have many votes. Now I want to retrieve a list of topics with the count of all votes on all items for each topic. The SQL query for this is written below:

```<code>SELECT Topic.*, count(Vote.id) voteCount
FROM
tbl_topics AS Topic
LEFT OUTER JOIN tbl_items AS Item
ON (Topic.id = Item.topic_id)
LEFT OUTER JOIN tbl_votes AS Vote
ON (Item.id = Vote.item_id);
</code>```

My problem is I can do it easily using $this-><Model Name>->query function, but this requires sql code to be written in the controller which I don't want. I'm trying to find out any other way to do this (like find()).

答:
I think this answer is already submitted, but I am posting here for someone who seeks still for this.
The joins can be done with find() method can be like below</p>

```<code>$result = $this->ModelName1->find("all",array(
'fields' => array('ModelName1.field_name','Table2.field_names'), // retrieving fileds
'joins' => array(  // join array
    array(
        'table' => 'table_name',
        'alias' => 'Table2',
        'type' => 'inner',
        'foreignKey' => false,
        'conditions'=> array('ModelName1.id = Table2.id') // joins conditions array
    ),
    array(
        'table' => 'table_name3',
        'alias' => 'Table3',
        'type' => 'inner',
        'foreignKey' => false,
        'conditions'=> array('Table3.id = Table2.id')
    )
)));
</code>```

Body:
can anyone tell me, how to retrieve joined result from multiple tables in cakePHP ( using cakePHP mvc architecture). For example, I have three tables to join (tbl_topics, tbl_items, tbl_votes. Their relationship is defined as following: a topic can have many items and an item can have many votes. Now I want to retrieve a list of topics with the count of all votes on all items for each topic. The SQL query for this is written below:

SELECT Topic.*, count(Vote.id) voteCount
FROM
tbl_topics AS Topic
LEFT OUTER JOIN tbl_items AS Item
ON (Topic.id = Item.topic_id)
LEFT OUTER JOIN tbl_votes AS Vote
ON (Item.id = Vote.item_id);

My problem is I can do it easily using $this-><Model Name>->query function, but this requires sql code to be written in the controller which I don't want. I'm trying to find out any other way to do this (like find()).

Body:
I think this answer is already submitted, but I am posting here for someone who seeks still for this.
The joins can be done with find() method can be like below

$result = $this->ModelName1->find("all",array(
'fields' => array('ModelName1.field_name','Table2.field_names'), // retrieving fileds
'joins' => array(  // join array
    array(
        'table' => 'table_name',
        'alias' => 'Table2',
        'type' => 'inner',
        'foreignKey' => false,
        'conditions'=> array('ModelName1.id = Table2.id') // joins conditions array
    ),
    array(
        'table' => 'table_name3',
        'alias' => 'Table3',
        'type' => 'inner',
        'foreignKey' => false,
        'conditions'=> array('Table3.id = Table2.id')
    )
)));


问:
Why am I getting 'undefined:x:y : property' missing error when running jest tests?
I am using jest & styled-components, or more specifically jest-styled-components for testing.

I have made changes to a component called FormField, which used the component Form, when running the tests, I am getting the following error.

```<code>    undefined:42:16: property missing ':'

      31 |     );
      32 |     const tree = component.toJSON();
    > 33 |     expect(tree).toMatchSnapshot();
         |                  ^
      34 |   });
      35 |
      36 |   test('update', () => {

</code>```

The jest test is as following

```<code>  test('with field', () => {
    const component = renderer.create(
      <Grommet>
        <Form>
          <FormField name="test" />
        </Form>
      </Grommet>,
    );
    const tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
</code>```

I can't pinpoint what the problem is, the changes I made to the component did not show any errors, and I'm getting the same errors in the testing of FormField component.

答:
I have fixed the problem.
The problem was caused because I did not update the snapshot after the changes I made to the component.

It can be done with

```<code>jest --updateSnapshot or jest --u
</code>```

Body:
I am using jest & styled-components, or more specifically jest-styled-components for testing.

I have made changes to a component called FormField, which used the component Form, when running the tests, I am getting the following error.

    undefined:42:16: property missing ':'

      31 |     );
      32 |     const tree = component.toJSON();
    > 33 |     expect(tree).toMatchSnapshot();
         |                  ^
      34 |   });
      35 |
      36 |   test('update', () => {

The jest test is as following

  test('with field', () => {
    const component = renderer.create(
      <Grommet>
        <Form>
          <FormField name="test" />
        </Form>
      </Grommet>,
    );
    const tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });

I can't pinpoint what the problem is, the changes I made to the component did not show any errors, and I'm getting the same errors in the testing of FormField component.

Body:
I have fixed the problem.
The problem was caused because I did not update the snapshot after the changes I made to the component.

It can be done with

jest --updateSnapshot or jest --u


问:
Why is fprintf causing memory leak and behaving unpredictably when width argument is missing
The following simple program is behaving unpredictably. Sometimes it prints "0.00000", sometimes it prints more "0" than I can count. Some times it uses up all memory on the system, before the system either kills some process, or it fails with bad_alloc.

```<code>#include "stdio.h"

int main() {
  fprintf(stdout, "%.*f", 0.0);
}
</code>```

I'm aware that this is incorrect usage of fprintf. There should be another argument specifying the width of the formatting. It's just surprising that the behavior is so unpredictable. Sometimes it seems to use a default width, while sometimes it fails very badly. Could this not be made to always fail or always use some default behaviour?

I came over similar usage in some code at work, and spent a lot of time figuring out what was happening. It only seemed to happen with debug builds, but would not happen while debugging with gdb. Another curiosity is that running it through valgrind would consistently bring about the printing of many "0"s case, which otherwise happens quite seldom, but the memory usage issue would never occur then either.

I am running Red Hat Enterprise Linux 7, and compiled with gcc 4.8.5.

答:
This is undefined behaviour in the standard. It means "anything is fair game" because you're doing wrong things.

The worst part is that most certainly any compiler will warn you, but you have ignored the warning. Putting some kind of validation other than the compiler will incurr in a cost that everybody will pay just so you can do what's wrong.

That's the opposite of what C and C++ stand for: you pay for what you use. If you want to pay the cost, it's up to you to do the checking.

What's really happening depends on the ABI, compiler and architecture. It's undefined behaviour because the language gives the implementer the freedom to do what's better on every machine (meaning, sometimes faster code, sometimes shorter code).

As an example, when you call a function on the machine, it just means that you're instructing the microprocessor to go to a certain code location.

In some made up assembly and ABI, then, printf("%.*f", 5, 1); will translate into something like

```<code>mov A, STR_F ; // load into register A the 32 bit address of the string "%.*f"
mov B, 5 ; // load second 32 bit parameter into B
mov F0, 1.0 ; // load first floating point parameter into register F0
call printf ; // call the function
</code>```

Now, if you miss some parameter, in this case B, it will take any value that was there before.

The thing with functions like printf is that they allow anything in their parameter list (it's printf(const char*, ...), so anything is valid). That's why you shouldn't use printf on C++: you have better alternatives, like streams. printf avoids the checkings of the compiler. streams are better aware of types and are extensible to your own types. Also, that's why your code should compile without warnings.

Body:
The following simple program is behaving unpredictably. Sometimes it prints "0.00000", sometimes it prints more "0" than I can count. Some times it uses up all memory on the system, before the system either kills some process, or it fails with bad_alloc.

#include "stdio.h"

int main() {
  fprintf(stdout, "%.*f", 0.0);
}

I'm aware that this is incorrect usage of fprintf. There should be another argument specifying the width of the formatting. It's just surprising that the behavior is so unpredictable. Sometimes it seems to use a default width, while sometimes it fails very badly. Could this not be made to always fail or always use some default behaviour?

I came over similar usage in some code at work, and spent a lot of time figuring out what was happening. It only seemed to happen with debug builds, but would not happen while debugging with gdb. Another curiosity is that running it through valgrind would consistently bring about the printing of many "0"s case, which otherwise happens quite seldom, but the memory usage issue would never occur then either.

I am running Red Hat Enterprise Linux 7, and compiled with gcc 4.8.5.

Body:
This is undefined behaviour in the standard. It means "anything is fair game" because you're doing wrong things.

The worst part is that most certainly any compiler will warn you, but you have ignored the warning. Putting some kind of validation other than the compiler will incurr in a cost that everybody will pay just so you can do what's wrong.

That's the opposite of what C and C++ stand for: you pay for what you use. If you want to pay the cost, it's up to you to do the checking.

What's really happening depends on the ABI, compiler and architecture. It's undefined behaviour because the language gives the implementer the freedom to do what's better on every machine (meaning, sometimes faster code, sometimes shorter code).

As an example, when you call a function on the machine, it just means that you're instructing the microprocessor to go to a certain code location.

In some made up assembly and ABI, then, printf("%.*f", 5, 1); will translate into something like

mov A, STR_F ; // load into register A the 32 bit address of the string "%.*f"
mov B, 5 ; // load second 32 bit parameter into B
mov F0, 1.0 ; // load first floating point parameter into register F0
call printf ; // call the function

Now, if you miss some parameter, in this case B, it will take any value that was there before.

The thing with functions like printf is that they allow anything in their parameter list (it's printf(const char*, ...), so anything is valid). That's why you shouldn't use printf on C++: you have better alternatives, like streams. printf avoids the checkings of the compiler. streams are better aware of types and are extensible to your own types. Also, that's why your code should compile without warnings.


问:
Working with more than one xml file in android
I am new to android development.

If I have more than one xml file, other than the main.xml, then how can I call the other files?

答:
create new activity. (add new .java). then in main.java call

Intent myIntent = new Intent(this, NEW_ACTIVITY.class);

        startActivityForResult(myIntent, 0);

and on start of onCreate OF NEW_ACTIVITY add

```<code> this.setContentView(R.layout.NEW_XML);
</code>```

in manifest.xml you must also add

```<code><activity android:name=".NEW_ACTIVITY"></activity>
</code>```

Body:
create new activity. (add new .java). then in main.java call

Intent myIntent = new Intent(this, NEW_ACTIVITY.class);

        startActivityForResult(myIntent, 0);

and on start of onCreate OF NEW_ACTIVITY add

 this.setContentView(R.layout.NEW_XML);

in manifest.xml you must also add

<activity android:name=".NEW_ACTIVITY"></activity>


问:
Decimal numbers get round up while formatting python
Here is what I have tried:

```<code>>>> pi = 3.14159265
>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.1f') #print 3.1
'3.1'
>>> format(pi, '.10f') #print 3.1415926500, more precision than the original
'3.1415926500'
>>> format(pi, '.5f') #print 3.14159, more precision than the original
'3.14159'
>>> format(pi, '.4f')
'3.1416'
</code>```

The concern part is this:

```<code>>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.4f')
'3.1416'
</code>```

Where I was expecting to have 3.1415, I am getting 3.1416. Please suggest me.

The SO is showing these 2 links:

http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate

http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary

But these are not the one I am looking for.

答:
You could simply strip the last character:</p>

```<code>pi = 3.14159

print(format(pi, '.5f')[:-1]) # 3.1415
</code>```

Body:
Here is what I have tried:

>>> pi = 3.14159265
>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.1f') #print 3.1
'3.1'
>>> format(pi, '.10f') #print 3.1415926500, more precision than the original
'3.1415926500'
>>> format(pi, '.5f') #print 3.14159, more precision than the original
'3.14159'
>>> format(pi, '.4f')
'3.1416'

The concern part is this:

>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.4f')
'3.1416'

Where I was expecting to have 3.1415, I am getting 3.1416. Please suggest me.

The SO is showing these 2 links:

http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate

http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary

But these are not the one I am looking for.

Body:
You could simply strip the last character:

pi = 3.14159

print(format(pi, '.5f')[:-1]) # 3.1415


问:
Specify frame rate while reading a video using skvideo.io.vread
I'm reading a video using skvideo.io.vread

```<code>import skvideo.io
video_frames = skvideo.io.vread(video_filepath)
</code>```

My video has a frame rate of 50fps. But I want to read the video at 4fps, I mean I need to read only 4 frames per second of the video. Is there any option to read at specified frame rate or do I have to manually discard extra frames read?

答:
skvideo.io.vread takes input parameters in form of dictionary. So, you can pass the frame rate like this:

```<code>import skvideo.io

video_frames = skvideo.io.vread(video_filepath, inputdict={'-r' : 4}) # Specify frame rate
</code>```

Here is the official documentation:
http://www.scikit-video.org/stable/examples/io.html

Body:
I'm reading a video using skvideo.io.vread

import skvideo.io
video_frames = skvideo.io.vread(video_filepath)

My video has a frame rate of 50fps. But I want to read the video at 4fps, I mean I need to read only 4 frames per second of the video. Is there any option to read at specified frame rate or do I have to manually discard extra frames read?

Body:
skvideo.io.vread takes input parameters in form of dictionary. So, you can pass the frame rate like this:

import skvideo.io

video_frames = skvideo.io.vread(video_filepath, inputdict={'-r' : 4}) # Specify frame rate

Here is the official documentation:
http://www.scikit-video.org/stable/examples/io.html


问:
How to get hours difference between now and next friday
I want to get hours difference between now and next friday 18:00 (weekend) using momentjs, I tried this but it doesn't work :

```<code>public getWeekend() {
    const nextFriday = moment().weekday(4)
    nextFriday.hours(18) // Weekend time: 18:00
    nextFriday.minutes(0)
    nextFriday.seconds(0)

    const diff = moment(nextFriday.diff(moment()))
    console.log(diff.days())
    if (diff.days() * 24 + diff.hours() <= 99) {
      return nextFriday.toString()
    } else {
      return 0
    }
  }
}
</code>```

console.log(diff.days()) is printing 6 days whereas we are Wednesday

答:
https://jsfiddle.net/7ehoq06n/

If you just call moment().weekday(5) it will go to Friday of "this week", which means that if you're on a saturday, it will go to YESTERDAY.

If you want the next friday, always in the future, use this:

```<code>var today = moment();
var friday = moment().weekday(5);
if (friday < today) {
    friday.add(1, 'weeks');
}
</code>```

Body:
I want to get hours difference between now and next friday 18:00 (weekend) using momentjs, I tried this but it doesn't work :

public getWeekend() {
    const nextFriday = moment().weekday(4)
    nextFriday.hours(18) // Weekend time: 18:00
    nextFriday.minutes(0)
    nextFriday.seconds(0)

    const diff = moment(nextFriday.diff(moment()))
    console.log(diff.days())
    if (diff.days() * 24 + diff.hours() <= 99) {
      return nextFriday.toString()
    } else {
      return 0
    }
  }
}

console.log(diff.days()) is printing 6 days whereas we are Wednesday

Body:
https://jsfiddle.net/7ehoq06n/

If you just call moment().weekday(5) it will go to Friday of "this week", which means that if you're on a saturday, it will go to YESTERDAY.

If you want the next friday, always in the future, use this:

var today = moment();
var friday = moment().weekday(5);
if (friday < today) {
    friday.add(1, 'weeks');
}


问:
calculate total hours spent and total cost by person
There are two tables

A table: 50000 rows with emp_name,date,hours_worked

B table: hourly_rates and name of about 100 people

I need to calculate total time spent and total cost per employee.

I have tried below query and it gives sum of total_hours but emp names are repeating.

```<code>SELECT A. Name ,sum(A.hours_worked) as total_hours ,sum(B.hourly_rates) as hourly_rates from
    `soy-antenna-242009.Nik.Employee`  A
      INNER JOIN
    `soy-antenna-242009.Nik.cost`  B

on A. Name = B. name
group by A. Name,A.hours,B. hourly_rates
</code>```

答:
remove A.hours,B. hourly_rates from group by

```<code>SELECT A. Name ,sum(A.hours_worked) as total_hours ,sum(B.hourly_rates) as hourly_rates
from `soy-antenna-242009.Nik.Employee`  A
      INNER JOIN `soy-antenna-242009.Nik.cost`  B on A. Name = B. name
group by A. Name
</code>```

Body:
There are two tables

A table: 50000 rows with emp_name,date,hours_worked

B table: hourly_rates and name of about 100 people

I need to calculate total time spent and total cost per employee.

I have tried below query and it gives sum of total_hours but emp names are repeating.

SELECT A. Name ,sum(A.hours_worked) as total_hours ,sum(B.hourly_rates) as hourly_rates from
    `soy-antenna-242009.Nik.Employee`  A
      INNER JOIN
    `soy-antenna-242009.Nik.cost`  B

on A. Name = B. name
group by A. Name,A.hours,B. hourly_rates

Body:
remove A.hours,B. hourly_rates from group by

SELECT A. Name ,sum(A.hours_worked) as total_hours ,sum(B.hourly_rates) as hourly_rates
from `soy-antenna-242009.Nik.Employee`  A
      INNER JOIN `soy-antenna-242009.Nik.cost`  B on A. Name = B. name
group by A. Name


问:
Getting data from file stream in c
I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?

```<code>char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");

fgets(string, sizeof string, fp);
</code>```

Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?

答:
One possibility is to dynamically allocate the buffer and then grow it (e.g., with realloc) as needed.  That would likely require writing a wrapper function for fgets that would check to see if it read the full line (the newline character is stored into the buffer).  It would also have to handle EOF conditions.

This probably goes without saying, but using C to read and parse text files with variable width data is quite a lot of work.  It may not make sense for your situation or even be possible, but if you can use something like Ruby, Python, Perl, Awk, etc. you can probably get the task done in a fraction of the time.  You can accomplish in a few lines of code with those tools what could take a hundred lines of C. They are a perfect fit for reading and parsing a delimited text file.  For example, the following chunk of ruby reads a text file line by line and splits it up by vertical bars:

```<code>File.open("myfile.txt") { |file|
   while ( line = file.gets )
       puts "line: #{line}"
       a = line.split( /\|/ )
       puts "array: #{a}"
   end
}
</code>```

Just for fun, here is a possible implementation with a few TBDs to handle (error checking). The main issue (aside from the subtle bugs that I didn't see) would be to address the freeing of the buffer if you don't read completely to EOF.

```<code>int myReadLine   // return non-zero if line returned, 0 on eof (see tbd below)
(
   FILE *fp,     // (I) open file handle for reading
   char **buf,   // (IO) buffer allocated by this function.  It is freed by
                 // this function when EOF is hit.  TBD: Should write a myFreeLine
                 // (for encapsulation purposes) to free this buffer for cases where
                 // you quit calling
   int  *len     // (IO) current length of buffer pointed to by buf
)
{
   char *ret;
   char *pos;
   int  curlen;
   int  remaining;

   if ( *len == 0 )
      {
      assert( *buf == NULL );
      // pick a number out of the air.  Could be app-specific.  In debug
      // it may be nice to start very small to force reallocs to exercise all
      // code paths.
      *len = 2;
      // tbd: need error checking
      *buf = (char*)malloc( *len * sizeof( char ));
      }

   pos = *buf;
   remaining = *len;

   while ( 1 )
      {
      ret = fgets( pos, remaining, fp );
      if ( ret == NULL )
         {
         // tbd: should check if error occurred here.  For now assuming eof
         free( *buf );
         *buf = NULL;
         *len = 0;
         return 0;
         }

      // check to see if we got the entire line.
      curlen = strlen( *buf );
      if ( (*buf)[curlen - 1] == '\n' )  // tbd:  check for \r?
         {
         // apparently we got the whole line
         // remove the end of line (at least that's what I would want)
         (*buf)[curlen - 1] = '\0';
         return 1;
         }
      else
         {
         // failed to get entire line
         assert( curlen + 1 == *len );

         // grow the buffer (tbd: realloc is a pain ... need error checking)
         *len *= 2;  // doubling is often a good plan
         *buf = (char*)realloc( *buf, *len );

         // set the "amount left" variables correctly for next iteration
         remaining = *len - curlen;
         pos = *buf + curlen;
         }
      }  // while forever

   // don't expect to get here
   assert( 0 );

}
</code>```

And here is a sample call:

```<code>void readfile(char *filepath)
{
   int len = 0;
   char *buf = NULL;

   FILE *fp=fopen(filepath,"rt");
   while ( myReadLine( fp, &buf, &len  ))
      printf( "'%s'\n", buf );
   fclose(fp);
}
</code>```

Title: Getting data from file stream in c

Body:
I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?

char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");

fgets(string, sizeof string, fp);

Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?

Body:
One possibility is to dynamically allocate the buffer and then grow it (e.g., with realloc) as needed.  That would likely require writing a wrapper function for fgets that would check to see if it read the full line (the newline character is stored into the buffer).  It would also have to handle EOF conditions.

This probably goes without saying, but using C to read and parse text files with variable width data is quite a lot of work.  It may not make sense for your situation or even be possible, but if you can use something like Ruby, Python, Perl, Awk, etc. you can probably get the task done in a fraction of the time.  You can accomplish in a few lines of code with those tools what could take a hundred lines of C. They are a perfect fit for reading and parsing a delimited text file.  For example, the following chunk of ruby reads a text file line by line and splits it up by vertical bars:

File.open("myfile.txt") { |file|
   while ( line = file.gets )
       puts "line: #{line}"
       a = line.split( /\|/ )
       puts "array: #{a}"
   end
}

Just for fun, here is a possible implementation with a few TBDs to handle (error checking). The main issue (aside from the subtle bugs that I didn't see) would be to address the freeing of the buffer if you don't read completely to EOF.

int myReadLine   // return non-zero if line returned, 0 on eof (see tbd below)
(
   FILE *fp,     // (I) open file handle for reading
   char **buf,   // (IO) buffer allocated by this function.  It is freed by
                 // this function when EOF is hit.  TBD: Should write a myFreeLine
                 // (for encapsulation purposes) to free this buffer for cases where
                 // you quit calling
   int  *len     // (IO) current length of buffer pointed to by buf
)
{
   char *ret;
   char *pos;
   int  curlen;
   int  remaining;

   if ( *len == 0 )
      {
      assert( *buf == NULL );
      // pick a number out of the air.  Could be app-specific.  In debug
      // it may be nice to start very small to force reallocs to exercise all
      // code paths.
      *len = 2;
      // tbd: need error checking
      *buf = (char*)malloc( *len * sizeof( char ));
      }

   pos = *buf;
   remaining = *len;

   while ( 1 )
      {
      ret = fgets( pos, remaining, fp );
      if ( ret == NULL )
         {
         // tbd: should check if error occurred here.  For now assuming eof
         free( *buf );
         *buf = NULL;
         *len = 0;
         return 0;
         }

      // check to see if we got the entire line.
      curlen = strlen( *buf );
      if ( (*buf)[curlen - 1] == '\n' )  // tbd:  check for \r?
         {
         // apparently we got the whole line
         // remove the end of line (at least that's what I would want)
         (*buf)[curlen - 1] = '\0';
         return 1;
         }
      else
         {
         // failed to get entire line
         assert( curlen + 1 == *len );

         // grow the buffer (tbd: realloc is a pain ... need error checking)
         *len *= 2;  // doubling is often a good plan
         *buf = (char*)realloc( *buf, *len );

         // set the "amount left" variables correctly for next iteration
         remaining = *len - curlen;
         pos = *buf + curlen;
         }
      }  // while forever

   // don't expect to get here
   assert( 0 );

}

And here is a sample call:

void readfile(char *filepath)
{
   int len = 0;
   char *buf = NULL;

   FILE *fp=fopen(filepath,"rt");
   while ( myReadLine( fp, &buf, &len  ))
      printf( "'%s'\n", buf );
   fclose(fp);
}


答:
Most likely you would have to discard the extra frames manually.

Although something you can try: The documentation for vread says that you can pass in inputdict as an argument, which is passed to the FFMpeg reader. This example shows how the rate can be set by the reader. I think this would most likely result in the video being sped up or slowed down, however.

```<code>import skvideo.io

rate = 4
video_frames = skvideo.io.vread(video_filepath, \
    inputdict={'-r': rate})
</code>```

Title: Specify frame rate while reading a video using skvideo.io.vread

Body:
Most likely you would have to discard the extra frames manually.

Although something you can try: The documentation for vread says that you can pass in inputdict as an argument, which is passed to the FFMpeg reader. This example shows how the rate can be set by the reader. I think this would most likely result in the video being sped up or slowed down, however.

import skvideo.io

rate = 4
video_frames = skvideo.io.vread(video_filepath, \
    inputdict={'-r': rate})


问:
Displaying images via link from database ? (PHP/MYSQLI) NEWBIE
Is it okay if i store links in the database to the  images and then just display them in the website ? is this a bad practice ? Example code below </p>

```<code><?
  echo "<img src='/projects".$row['image']."' >";
</code>```

答:
as requested by the comments.
  Depending on your application and it's complexity, you would want to simplify your image loading as much as possible and storing image url's in the DB isn't the best approach. ideally you would want to group your images in to directories by type and keep a common structure to image names so that you could easily swap images with only replacing thair id or single string. Here is an example of a very simplified image loader class:

Directory structure:

```<code>images
    -> products
        -> product-123.png
    -> icons
        -> arrow.png
</code>```

Image loader class:

```<code>class ImageLoader {
    const IMAGE_PATH = '/images'
    const PROCUCT_IMAGE_PATH = '/products/'
    const ICON_IMAGE_PATH = '/icons'
    const IMAGE_EXTENSION = '.png'

    static public function getIconImage($identifier) {
        return self::IMAGE_PATH
            . self::ICON_IMAGE_PATH
            . $identifier
            . self::IMAGE_EXTENSION;
    }

    static public function getProductImage($identifier) {
        return self::IMAGE_PATH
            . self::PROCUCT_IMAGE_PATH
            . 'product-'
            . $identifier
            . self::IMAGE_EXTENSION;
    }
}
</code>```

Usage

Manually passing image name:

```<code><img src="<?= ImageLoader::getIconImage('arrow') ?>" />
</code>```

Passing a variable as id stored in the DB:

```<code><img src="<?= ImageLoader::getProductImage($productIdFromDatabase) ?>" />
</code>```

Body:
Is it okay if i store links in the database to the  images and then just display them in the website ? is this a bad practice ? Example code below

<?
  echo "";

Body:
as requested by the comments.
  Depending on your application and it's complexity, you would want to simplify your image loading as much as possible and storing image url's in the DB isn't the best approach. ideally you would want to group your images in to directories by type and keep a common structure to image names so that you could easily swap images with only replacing thair id or single string. Here is an example of a very simplified image loader class:

Directory structure:

images
    -> products
        -> product-123.png
    -> icons
        -> arrow.png

Image loader class:

class ImageLoader {
    const IMAGE_PATH = '/images'
    const PROCUCT_IMAGE_PATH = '/products/'
    const ICON_IMAGE_PATH = '/icons'
    const IMAGE_EXTENSION = '.png'

    static public function getIconImage($identifier) {
        return self::IMAGE_PATH
            . self::ICON_IMAGE_PATH
            . $identifier
            . self::IMAGE_EXTENSION;
    }

    static public function getProductImage($identifier) {
        return self::IMAGE_PATH
            . self::PROCUCT_IMAGE_PATH
            . 'product-'
            . $identifier
            . self::IMAGE_EXTENSION;
    }
}

Usage

Manually passing image name:

<img src="<?= ImageLoader::getIconImage('arrow') ?>" />

Passing a variable as id stored in the DB:

<img src="<?= ImageLoader::getProductImage($productIdFromDatabase) ?>" />


问:
jQuery / Ajax to get html and save with php
I am trying to get a jQuery script to run behind the scenes with php. It basically will get the contents of a div with jQuery (works) then calls a script with ajax (works) but I need the ajax script that called the php to send the vars to php so I can save the conents.

Here is the code:

```<code><script>
$( document ).ready(function() {

$( ".tweets" ).click(function() {
var htmlString = $( this ).html();
tweetUpdate(htmlString);
});

});
</script>

<script>
function tweetUpdate(htmlString)
{
$.ajax({
    type: "POST",
    url: 'saveTweets.php',
    data: htmlString,
    success: function (data) {
        // this is executed when ajax call finished well
        alert('content of the executed page: ' + data);
    },
    error: function (xhr, status, error) {
        // executed if something went wrong during call
        if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
    }
});
}
</script>
</code>```

and my code for saveTweets.php

```<code><?
// SUPPOSED TO receive html conents called htmlString taken from a div
// and then I will write this code to a file with php and save it.
echo $_POST[htmlString];

?>
</code>```

答:
Using  json is better for sending data:

```<code>data_htlm=[];

data_html.push({"htmlString": htmlString});
 $.ajax(
   {

      type: "POST",
      dataType: "json",
      url: "saveTweets.php",
      data: JSON.stringify(data_html),
      success: function(html)
        {
          console.log(html);
        }
   });
</code>```

now with php you can just do this:

```<code>echo $_POST['htmlString'];
</code>```

Body:
I am trying to get a jQuery script to run behind the scenes with php. It basically will get the contents of a div with jQuery (works) then calls a script with ajax (works) but I need the ajax script that called the php to send the vars to php so I can save the conents.

Here is the code:

and my code for saveTweets.php

<?
// SUPPOSED TO receive html conents called htmlString taken from a div
// and then I will write this code to a file with php and save it.
echo $_POST[htmlString];

?>

Body:
Using  json is better for sending data:

data_htlm=[];

data_html.push({"htmlString": htmlString});
 $.ajax(
   {

      type: "POST",
      dataType: "json",
      url: "saveTweets.php",
      data: JSON.stringify(data_html),
      success: function(html)
        {
          console.log(html);
        }
   });

now with php you can just do this:

echo $_POST['htmlString'];


答: there is 3.1416 for format(pi, '.4f') for the same reason there is 3.142 for format(pi, '.3f') - the next digit after your desired number of digits in formatted output is at least five - it is rounded up.

Title: Decimal numbers get round up while formatting python


问:
C++ binary search for a class
I have a class and I want to implement binary_search (from  library) to it:

```<code>#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class T_value{
public:

    T_value(const int _timestamp, const string _value) :
        timestamp(_timestamp),
        value(_value)
    {}
    int get_time() {return timestamp;}

private:
    int timestamp;
    string value;
};

int main()
{

    T_value one(1, "one"),
    two(3, "two"),
    three(43, "three"),
    four(-1, "four");
    vector<T_value> v{one,two,three, four};

    cout << binary_search(begin(v), end(v), 3);
}
</code>```

Is that possible? Should I overload '==' and '<' operators (tried, didn't succeed) or something else?

Thank you in advance!

答:
Yes. Although you just need to implement operator<. Also the argument to binary_search is mismatched and the container must be pre-sorted.

Link to working example:

http://coliru.stacked-crooked.com/a/0343dd205abac6f2

Operator less:

```<code>bool operator<(const T_value& other) const {
    return timestamp < other.timestamp;//you may wan't another sort criteria
}
</code>```

Pre-sort container and binary_search:

```<code>std::sort(v.begin(), v.end());
cout << (binary_search(begin(v), end(v), T_value(3, "not used") ) ? "found" : "not found") << std::endl;
</code>```

Title: C++ binary search for a class

Body:
I have a class and I want to implement binary_search (from  library) to it:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class T_value{
public:

    T_value(const int _timestamp, const string _value) :
        timestamp(_timestamp),
        value(_value)
    {}
    int get_time() {return timestamp;}

private:
    int timestamp;
    string value;
};

int main()
{

    T_value one(1, "one"),
    two(3, "two"),
    three(43, "three"),
    four(-1, "four");
    vector<T_value> v{one,two,three, four};

    cout << binary_search(begin(v), end(v), 3);
}

Is that possible? Should I overload '==' and '<' operators (tried, didn't succeed) or something else?

Thank you in advance!

Body:
Yes. Although you just need to implement operator<. Also the argument to binary_search is mismatched and the container must be pre-sorted.

Link to working example:

http://coliru.stacked-crooked.com/a/0343dd205abac6f2

Operator less:

bool operator<(const T_value& other) const {
    return timestamp < other.timestamp;//you may wan't another sort criteria
}

Pre-sort container and binary_search:

std::sort(v.begin(), v.end());
cout << (binary_search(begin(v), end(v), T_value(3, "not used") ) ? "found" : "not found") << std::endl;


问:
How to debug a class library that is not a dependency of the main C# application (in Visual Studio)?
I have a solution where I load some dlls at runtime with Assembly.LoadFile. Because these dlls can come from multiple sources at any time, I cannot add them as a dependency to the main application. It seems that Visual Studio won't load pdb files for dlls that are not marked as a dependency.

I don't want to add each dll I'm debugging to the dependencies just to debug them. Is there a way to manually load symbols for these external dlls?

答:
You should set the (plugin) assembly as startup project and in the properties screen at the Debug tab, you can change the start action.
Change it to "Start external program" and select the main project assembly(exe).

When you copied the output of the plugin to the main projects output by hand, you have to change the output path in the Build tab, so the plugin comes in the right path to be loaded by the main program.


问:
Javascript Stuck in Cache
I have a HTML document which I am developing a .js file for. My problem is, my browser is still using an outdated version of the .js script, which it stored in the cache when it was used. Any modifications to the actual .js script make no difference. Clearing the cache didn't help... How can I fix this?

答:
Rename the file on the server. Load the page. Ensure that it didn't find the script. Rename the script back to its original name. Test to see of it loads properly.

If this fails, it may be time to reboot your web server.

Title: Javascript Stuck in Cache


问:
Unable to create process : .ui to .py
I have been trying for a long time to generate a python code frome qtDesigner but I always have the same issue :

The command I used : pyuic5 ExtraInfo_Design.ui -o ExtraInfo_Designui.py

```<code>Fatal error in launcher: Unable to create process using '"c:\users\Dorian\appdata\local\programs\python\python37-32\python.exe"  "C:\Users\lDorian\Desktop\extrInfo\pyuic5.exe" ExtraInfo_Design.ui -o ExtraInfo_Designui.py'
</code>```

I think that all these problems happen because I changed the name of my laptop so I have other files that had been created "lDorian".

I have tried to open the shell as ana administrator.
I had tried to generate the code from a (.bat) file.
I had tried to add python path to the path directory.

Thanks, folks.

答:
As far as I get it from your question and the error message, you changed your laptop username from lDorian to Dorian . For programs that set the path variable during installation, this is now wrong as you see in your error message.

For python the path starts with "c:\users\Dorian", for pyuic5 it start with "C:\Users\lDorian" which I guess is the user that does not exist anymore.

The python path you changed, so it looks fine now. Also change the path for pyuic5 and it should work.

If you still encounter problems, a clean reinstall of python and qt should do the job and might be faster than searching for all misset paths.

Title: Unable to create process : .ui to .py

Body:
I have been trying for a long time to generate a python code frome qtDesigner but I always have the same issue :

The command I used : pyuic5 ExtraInfo_Design.ui -o ExtraInfo_Designui.py

Fatal error in launcher: Unable to create process using '"c:\users\Dorian\appdata\local\programs\python\python37-32\python.exe"  "C:\Users\lDorian\Desktop\extrInfo\pyuic5.exe" ExtraInfo_Design.ui -o ExtraInfo_Designui.py'

I think that all these problems happen because I changed the name of my laptop so I have other files that had been created "lDorian".

I have tried to open the shell as ana administrator.
I had tried to generate the code from a (.bat) file.
I had tried to add python path to the path directory.

Thanks, folks.


问:
Update one dataframe value with another dataframe column value based on the condition
I have two dataframe say df1 and df2.

```<code>df1:

id code remarks
1   a12
2   b32
3   c12

df2:

id code remarks
1   aaa12  ok
2   b32    done
3   ccc12  not ok
</code>```

I want to update the df1 remarks value with df2 remarks value based on the id and code.

Here second value matches (id-2 , code-b32) so update the value of remarks 'done' with df1 remarks column.

End result of df1 will be like below,

```<code>df1:

id code remarks
1   a12
2   b32  done
3   c12
</code>```

So far i tried like below, I know this is not correct, but i need something like this

```<code>df1_key = df1['id'].astype(str) + df1['code'].astype(str)
df2_key = df2['id'].astype(str) + df2['code'].astype(str)

df['flag'] = df1_key.isin(df2_key, df1['remarks']=df2['remarks'])
</code>```

According to this one i tried the below also, but did n't work for me.

```<code> df3 = df1.merge(df2[['remarks']], on=['id','code'], how='left')
</code>```

答:
Use DataFrame.merge with filtered columns by list:

```<code>df3 = df1[['id','code']].merge(df2, on=['id','code'], how='left')
</code>```

Or by DataFrame.drop:

```<code>df3 = df1.drop('remarks', axis=1).merge(df2, on=['id','code'], how='left')

print (df3)
   id code remarks
0   1  a12     NaN
1   2  b32    done
2   3  c12     NaN
</code>```

Body:
I have two dataframe say df1 and df2.

df1:

id code remarks
1   a12
2   b32
3   c12

df2:

id code remarks
1   aaa12  ok
2   b32    done
3   ccc12  not ok

I want to update the df1 remarks value with df2 remarks value based on the id and code.

Here second value matches (id-2 , code-b32) so update the value of remarks 'done' with df1 remarks column.

End result of df1 will be like below,

df1:

id code remarks
1   a12
2   b32  done
3   c12

So far i tried like below, I know this is not correct, but i need something like this

df1_key = df1['id'].astype(str) + df1['code'].astype(str)
df2_key = df2['id'].astype(str) + df2['code'].astype(str)

df['flag'] = df1_key.isin(df2_key, df1['remarks']=df2['remarks'])

According to this one i tried the below also, but did n't work for me.

 df3 = df1.merge(df2[['remarks']], on=['id','code'], how='left')

Body:
Use DataFrame.merge with filtered columns by list:

df3 = df1[['id','code']].merge(df2, on=['id','code'], how='left')

Or by DataFrame.drop:

df3 = df1.drop('remarks', axis=1).merge(df2, on=['id','code'], how='left')

print (df3)
   id code remarks
0   1  a12     NaN
1   2  b32    done
2   3  c12     NaN


问:
WPF Child Window - Windows 7 Taskbar
We have a main application that loads several plugins that have their own individual icons and child windows.

Problem is in Windows 7, the icon in the taskbar is always the icon of the main application, even on the child windows.  However, the Alt+Tab menu displays the appropriate icon.

I understand this is due to the pinning feature, and Windows 7 probably uses the icon of the main exe to handle this.

Is there a way we can change the taskbar icon on our child windows?  And possibly disabled pinning as well?  It would be confusing to be able to pin these child windows, as it wouldn't work properly.

答:
You can't pin a child window - pinning works at the level of the application.  If you pin/unpin a child window, you're (un)pinning the app as a whole.  There's no way to disable this behaviour, since it's OS-level functionality that applies to any window in the taskbar (though you could choose not to display those windows in the taskbar).

I'm not sure about the Window icons, but I'd imagine you're right when you say it's just using the application icon.

Title: WPF Child Window - Windows 7 Taskbar


答:
Moment.js has a build in function .fromNow() it returns the time beween the given time and the local time. So the only 2 line you need to change are the .weekday(4) because friday is weekday(5). and call the .fromnow() function.

console.log(getWeekend());
function getWeekend() {
    const nextFriday = moment().weekday(5);
    nextFriday.hours(18); // Weekend time: 18:00
    nextFriday.minutes(0);
    nextFriday.seconds(0);
    return nextFriday.fromNow();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://momentjs.com/downloads/moment.min.js"></script></code>```

Note that fromNow will return a string Moment.js has a build in solution for this.

Title: How to get hours difference between now and next friday

Body:
Moment.js has a build in function .fromNow() it returns the time beween the given time and the local time. So the only 2 line you need to change are the .weekday(4) because friday is weekday(5). and call the .fromnow() function.

console.log(getWeekend());
function getWeekend() {
    const nextFriday = moment().weekday(5);
    nextFriday.hours(18); // Weekend time: 18:00
    nextFriday.minutes(0);
    nextFriday.seconds(0);
    return nextFriday.fromNow();
}

<script src="https://momentjs.com/downloads/moment.min.js"></script>

Note that fromNow will return a string Moment.js has a build in solution for this.


问:
Why are my password validation rules not working?
I configured the Password Validation Rules in the startup class services.AddIdentity<> section, but it does not work. I used Asp Core Identity API such that:

```<code>Password.RequiredLength = 8
</code>```

but I need a password with an arbitrary length in my project.

This is the content of my current files (i.e. CreateController and StartUp.cs)

```<code>public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddDbContext<AppIdentityDBContext>(options     =>options.UseSqlServer(
            Configuration["ConnectionStrings:IdentityConnection"]
            ));
        services.AddIdentity<AppUser, IdentityRole>(opts => {
              opts.Password.RequiredLength = 8;
              opts.Password.RequireNonAlphanumeric = false;
              opts.Password.RequireLowercase = false;
              opts.Password.RequireUppercase = false;
              opts.Password.RequireDigit = false;
        }).AddEntityFrameworkStores<AppIdentityDBContext>()
        .AddDefaultTokenProviders();
}

public async Task<IActionResult> Create(UserCreateVM model)
    {
        if(ModelState.IsValid)
        {
            AppUser user = new AppUser
            {
                UserName = model.Name,
                Email = model.Email,
            };

            IdentityResult Result = await _userManager.CreateAsync(user);

            if(Result.Succeeded)
            {
                return RedirectToAction("Index");
            }

            else
            {
                foreach (var item in Result.Errors)
                {
                    ModelState.AddModelError("", item.Description);
                }
            }
        }

        else
        {
            return View(model);
        }
    }
</code>```

答:
I Edit this Line :

```<code>IdentityResult Result = await _userManager.CreateAsync(user);
</code>```

to :

```<code>IdentityResult Result = await _userManager.CreateAsync(user,model.Password);
</code>```

and problem Solved.

Body:
I configured the Password Validation Rules in the startup class services.AddIdentity<> section, but it does not work. I used Asp Core Identity API such that:

Password.RequiredLength = 8

but I need a password with an arbitrary length in my project.

This is the content of my current files (i.e. CreateController and StartUp.cs)

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddDbContext<AppIdentityDBContext>(options     =>options.UseSqlServer(
            Configuration["ConnectionStrings:IdentityConnection"]
            ));
        services.AddIdentity<AppUser, IdentityRole>(opts => {
              opts.Password.RequiredLength = 8;
              opts.Password.RequireNonAlphanumeric = false;
              opts.Password.RequireLowercase = false;
              opts.Password.RequireUppercase = false;
              opts.Password.RequireDigit = false;
        }).AddEntityFrameworkStores<AppIdentityDBContext>()
        .AddDefaultTokenProviders();
}

public async Task<IActionResult> Create(UserCreateVM model)
    {
        if(ModelState.IsValid)
        {
            AppUser user = new AppUser
            {
                UserName = model.Name,
                Email = model.Email,
            };

            IdentityResult Result = await _userManager.CreateAsync(user);

            if(Result.Succeeded)
            {
                return RedirectToAction("Index");
            }

            else
            {
                foreach (var item in Result.Errors)
                {
                    ModelState.AddModelError("", item.Description);
                }
            }
        }

        else
        {
            return View(model);
        }
    }

Body:
I Edit this Line :

IdentityResult Result = await _userManager.CreateAsync(user);

to :

IdentityResult Result = await _userManager.CreateAsync(user,model.Password);

and problem Solved.


问:
How to randomly permutate string without adjacent equal elements
So, I have an example string like "aaabbbc", i would like to shuffle it randomly but no two consecutive letters should be same in the result. The output should be "abababc" or "cbababa" or "abacbab" etc.

I've tried a code using PriorityQueue, its solve the problem, but only one way not randomly generate many ways to shuffle my string with no two consecutive. Below is code that i've used.

```<code>    int n = str.length();
    int[] count = new int[MAX_CHAR];

    for (int i = 0; i < n; i++) {
        count[str.charAt(i) - 'a']++;
    }

    PriorityQueue<Key> pq = new PriorityQueue<>(new KeyComparator());
    for (char c = 'a'; c <= 'z'; c++) {
        int val = c - 'a';
        if (count[val] > 0) {
            pq.add(new Key(count[val], c));
        }
    }
    str = "";

    Key prev = new Key(-1, '#');
    while (pq.size() != 0) {
        Key k = pq.peek();
        pq.poll();
        str = str + k.ch;

        if (prev.freq > 0) {
            pq.add(prev);
        }

        (k.freq)--;
        prev = k;
    }

    if (n != str.length()) {
        return "";
    } else {
        return str;
    }
</code>```

I am stuck when trying to make it randomly by that algorithm. The result i wanted is dynamic output like i described above. Thanks

答:
Assuming you want an equal distribution of the valid permutations:
If you do not care about memory or runtime complexity, you can generate all permutations of the string (Generating all permutations of a given string), then remove all Strings which have adjacent same letters, and finally pick a random one from that list.

If you do care about optimizing memory or runtime, see the similar questions linked.

Some other approaches if you do not need an equal distribution, but still a chance for any valid permutation to be found:

You can build up the string by randomly picking from the remaining letters (similar as to what you did), and backtracking when you hit a dead end (no valid letter left to pick). See Python permutation using backtracking

You can make a string where you pick random letters from the input without caring about adjacent repetitions, and then swap-shuffle (see Heap's algorithm) this random starting point iteratively until the result matches your condition (or until you're back to the start).

Backtracking solution

Here I pick a random nextChar, and try to build a random String that does not start with that char. If that fails, try another one. By recursion, this eventually tries out all combinations in a random order, until a valid one is found.

```<code>private static final Random RANDOM = new Random();

public static void main(String[] args) {
    System.out.println(randomPerm("aaabcc"));
}

public static String randomPerm(String str) {
    Map<Character, Long> counts = str
            .chars()
            .mapToObj(c -> (char) c)
            .collect(groupingBy(Function.identity(), Collectors.counting()));
    return restPerm(null, counts);
}

public static String restPerm(Character previous, Map<Character, Long> leftover) {
    List<Character> leftKeys = new ArrayList<>(leftover.keySet());
    while (!leftKeys.isEmpty()) {
        Character nextChar = leftKeys.get(RANDOM.nextInt(leftKeys.size()));
        leftKeys.remove(nextChar);
        if (nextChar.equals(previous) || leftover.get(nextChar) == 0) {
            continue; // invalid next char
        }
        // modify map in place, reduce count by one
        Long count = leftover.compute(nextChar, (ch, co) -> co - 1);
        if (leftover.values().stream().noneMatch(c -> c > 0)) {
            return nextChar.toString();  // last char to use
        }
        String rest = restPerm(nextChar, leftover); // recurse
        if (rest != null) {
            return nextChar + rest; // solution found
        }
        leftover.put(nextChar, count + 1);
    }
    return null;
}
</code>```

This solution will more likely find results where rare characters are used in the beginning of the result, so the distribution would not be equal. As an example input "aaaaaaabbbbbc" will have c more often on the left than on the right, like "acabababababa" in 50% of cases. But it uses limited memory and may complete before computing all permutations, and it is somewhat similar to your approach.

Body:
So, I have an example string like "aaabbbc", i would like to shuffle it randomly but no two consecutive letters should be same in the result. The output should be "abababc" or "cbababa" or "abacbab" etc.

I've tried a code using PriorityQueue, its solve the problem, but only one way not randomly generate many ways to shuffle my string with no two consecutive. Below is code that i've used.

    int n = str.length();
    int[] count = new int[MAX_CHAR];

    for (int i = 0; i < n; i++) {
        count[str.charAt(i) - 'a']++;
    }

    PriorityQueue<Key> pq = new PriorityQueue<>(new KeyComparator());
    for (char c = 'a'; c <= 'z'; c++) {
        int val = c - 'a';
        if (count[val] > 0) {
            pq.add(new Key(count[val], c));
        }
    }
    str = "";

    Key prev = new Key(-1, '#');
    while (pq.size() != 0) {
        Key k = pq.peek();
        pq.poll();
        str = str + k.ch;

        if (prev.freq > 0) {
            pq.add(prev);
        }

        (k.freq)--;
        prev = k;
    }

    if (n != str.length()) {
        return "";
    } else {
        return str;
    }

I am stuck when trying to make it randomly by that algorithm. The result i wanted is dynamic output like i described above. Thanks

Body:
Assuming you want an equal distribution of the valid permutations:
If you do not care about memory or runtime complexity, you can generate all permutations of the string (Generating all permutations of a given string), then remove all Strings which have adjacent same letters, and finally pick a random one from that list.

If you do care about optimizing memory or runtime, see the similar questions linked.

Some other approaches if you do not need an equal distribution, but still a chance for any valid permutation to be found:

You can build up the string by randomly picking from the remaining letters (similar as to what you did), and backtracking when you hit a dead end (no valid letter left to pick). See Python permutation using backtracking

You can make a string where you pick random letters from the input without caring about adjacent repetitions, and then swap-shuffle (see Heap's algorithm) this random starting point iteratively until the result matches your condition (or until you're back to the start).

Backtracking solution

Here I pick a random nextChar, and try to build a random String that does not start with that char. If that fails, try another one. By recursion, this eventually tries out all combinations in a random order, until a valid one is found.

private static final Random RANDOM = new Random();

public static void main(String[] args) {
    System.out.println(randomPerm("aaabcc"));
}

public static String randomPerm(String str) {
    Map<Character, Long> counts = str
            .chars()
            .mapToObj(c -> (char) c)
            .collect(groupingBy(Function.identity(), Collectors.counting()));
    return restPerm(null, counts);
}

public static String restPerm(Character previous, Map<Character, Long> leftover) {
    List<Character> leftKeys = new ArrayList<>(leftover.keySet());
    while (!leftKeys.isEmpty()) {
        Character nextChar = leftKeys.get(RANDOM.nextInt(leftKeys.size()));
        leftKeys.remove(nextChar);
        if (nextChar.equals(previous) || leftover.get(nextChar) == 0) {
            continue; // invalid next char
        }
        // modify map in place, reduce count by one
        Long count = leftover.compute(nextChar, (ch, co) -> co - 1);
        if (leftover.values().stream().noneMatch(c -> c > 0)) {
            return nextChar.toString();  // last char to use
        }
        String rest = restPerm(nextChar, leftover); // recurse
        if (rest != null) {
            return nextChar + rest; // solution found
        }
        leftover.put(nextChar, count + 1);
    }
    return null;
}

This solution will more likely find results where rare characters are used in the beginning of the result, so the distribution would not be equal. As an example input "aaaaaaabbbbbc" will have c more often on the left than on the right, like "acabababababa" in 50% of cases. But it uses limited memory and may complete before computing all permutations, and it is somewhat similar to your approach.