问:
C# Authentication failed because the remote party has closed the transport stream
I want to point out that I have searched a lot for this without a solution. So, I've created a loop that will go throw listBox2 that contains links, each time creating a http GET request in order to access the full source code.

My code:

```<code> private void button4_Click(object sender, EventArgs e)
    {
        try
        {
            for (int i = 0; i < listBox2.Items.Count; i++)
            {
                code(listBox2.Items[i].ToString() + "\'");
                //await PutTaskDelay();
                //Console.WriteLine(listBox2.Items[i].ToString());
                if (VarrileKeeper.s.ToLower().Contains("mysql"))
                {
                    Console.WriteLine("possitive " + listBox2.Items[i].ToString());
                }
            }
        }
        catch (Exception Fejl)
        {
            Console.WriteLine(Fejl);
        }
    }

 public static String code(string Url)
    {

        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
        myRequest.MaximumAutomaticRedirections = 4;
        myRequest.MaximumResponseHeadersLength = 4;
        myRequest.Credentials = CredentialCache.DefaultCredentials;

        myRequest.Method = "GET";

        WebResponse myResponse = myRequest.GetResponse();

        StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
        string result = sr.ReadToEnd();
        sr.Close();
        myResponse.Dispose();
        myResponse.Close();
        VarrileKeeper.s = result;
        return result;
    }
</code>```

The error below is triggered when the loop hits various of urls for example (http://www.memphremagog.org/fr/lexique.php?id=32). The weird thing is that if I remove the loop and make a http GET reqeust to that site everything works just fine.

A first chance exception of type 'System.Net.WebException' occurred in
  System.dll System.Net.WebException: The underlying connection was
  closed: An unexpected error occurred on a send. --->
  System.IO.IOException: Authentication failed because the remote party
  has closed the transport stream.

I don't think it's a problem with the certificate because otherwise I would still get an error on http://www.memphremagog.org/fr/lexique.php?id=32 when I removed the loop.

Any suggestions are appreciated.

答:
The zvoxaudio.com url, from your comments, is pretty tricky.  They have a some bot detection for adding items to a cart.  The link you specifically used doesn't seem to work no matter what, I think it is using an expired item id; I was able to use it by updating the id to 4007001 and change it to 'https'.  This link however is adding an item to the cart and the site does not allow bots to add items to a cart, the site returns a 400 error with this key:value in the headers:

```<code>X-Error-Message: Bots are not allowed to add items to cart
</code>```

Try adding a UserAgent to your request like this:

```<code>  myRequest.UserAgent = "Nada";
</code>```

With those few changes the ZVOXAUDIO link works!

If you want keep the url as an 'https' request then just add this to your code.

```<code>ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
</code>```

This is required because ZVOXAUDIO does not support TLS 1.0 or earlier protocols.  If the version of .NET you're using doesn't suppoert TLS 1.2, you can use SecurityProtocolType.Tls11 as ZVOXAUDIO does support TLS 1.1 still.

But since, presumably, you are attempting to have this run on as many sites as possible you probably don't want to only allow TLS 1.2, as older servers may not support it.  I would set your security protocol like this:

```<code>ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 |
                                       SecurityProtocolType.Tls11 |
                                       SecurityProtocolType.Tls |
                                       SecurityProtocolType.Ssl3;
</code>```

As a suggestion, you can set the Server Certificate Validation Callback, and the Security Protocol, outside of your loop as it is a static setting for all requests.  Also if you utilize the C# using syntax, the Dispose method takes care of closing and disposing your WebResponse and StreamReader variables for you.  And C# introduced 'var' back in .NET 3.0, your might want to start embracing it, that is presuming you are using the 3.0 or newer framework.  If you want to see what this would look like, look below.

Make sure you have these usings:

```<code>using System;
using System.IO;
using System.Net;
</code>```

Then put these two lines in the static constructor of your form, or object, I assume you are using a form right now:

```<code>ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
</code>```

Then your two methods would look like this:

```<code>private void button4_Click(object sender, EventArgs e)
{
  try
  {
    for (var i = 0; i < listBox2.Items.Count; i++)
    {
      var response = Code(listBox2.Items[i].ToString() + "\'");
      if (response.ToLower().Contains("mysql"))
      {
        Console.WriteLine("positive " + listBox2.Items[i].ToString());
      }
    }
  }
  catch (Exception ex)
  {
    Console.WriteLine(ex.Message);
  }
}

public static string Code(string url)
{
  var webRequest = (HttpWebRequest)WebRequest.Create(url);
  webRequest.MaximumAutomaticRedirections = 4;
  webRequest.MaximumResponseHeadersLength = 4;
  webRequest.UserAgent = "Mozilla/5.0 (Taco2) Gecko/20100101";
  webRequest.Credentials = CredentialCache.DefaultCredentials;

  webRequest.Method = "GET";

  using (var webResponse = webRequest.GetResponse())
  {
    using (var sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8))
    {
      return sr.ReadToEnd();
    }
  }
}
</code>```

Happy Coding!  Feel free to ask any questions in the comments below.

Body:
I want to point out that I have searched a lot for this without a solution. So, I've created a loop that will go throw listBox2 that contains links, each time creating a http GET request in order to access the full source code.

My code:

 private void button4_Click(object sender, EventArgs e)
    {
        try
        {
            for (int i = 0; i < listBox2.Items.Count; i++)
            {
                code(listBox2.Items[i].ToString() + "\'");
                //await PutTaskDelay();
                //Console.WriteLine(listBox2.Items[i].ToString());
                if (VarrileKeeper.s.ToLower().Contains("mysql"))
                {
                    Console.WriteLine("possitive " + listBox2.Items[i].ToString());
                }
            }
        }
        catch (Exception Fejl)
        {
            Console.WriteLine(Fejl);
        }
    }

 public static String code(string Url)
    {

        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
        myRequest.MaximumAutomaticRedirections = 4;
        myRequest.MaximumResponseHeadersLength = 4;
        myRequest.Credentials = CredentialCache.DefaultCredentials;

        myRequest.Method = "GET";

        WebResponse myResponse = myRequest.GetResponse();

        StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
        string result = sr.ReadToEnd();
        sr.Close();
        myResponse.Dispose();
        myResponse.Close();
        VarrileKeeper.s = result;
        return result;
    }

The error below is triggered when the loop hits various of urls for example (http://www.memphremagog.org/fr/lexique.php?id=32). The weird thing is that if I remove the loop and make a http GET reqeust to that site everything works just fine.

A first chance exception of type 'System.Net.WebException' occurred in
  System.dll System.Net.WebException: The underlying connection was
  closed: An unexpected error occurred on a send. --->
  System.IO.IOException: Authentication failed because the remote party
  has closed the transport stream.

I don't think it's a problem with the certificate because otherwise I would still get an error on http://www.memphremagog.org/fr/lexique.php?id=32 when I removed the loop.

Any suggestions are appreciated.

Body:
The zvoxaudio.com url, from your comments, is pretty tricky.  They have a some bot detection for adding items to a cart.  The link you specifically used doesn't seem to work no matter what, I think it is using an expired item id; I was able to use it by updating the id to 4007001 and change it to 'https'.  This link however is adding an item to the cart and the site does not allow bots to add items to a cart, the site returns a 400 error with this key:value in the headers:

X-Error-Message: Bots are not allowed to add items to cart

Try adding a UserAgent to your request like this:

  myRequest.UserAgent = "Nada";

With those few changes the ZVOXAUDIO link works!

If you want keep the url as an 'https' request then just add this to your code.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

This is required because ZVOXAUDIO does not support TLS 1.0 or earlier protocols.  If the version of .NET you're using doesn't suppoert TLS 1.2, you can use SecurityProtocolType.Tls11 as ZVOXAUDIO does support TLS 1.1 still.

But since, presumably, you are attempting to have this run on as many sites as possible you probably don't want to only allow TLS 1.2, as older servers may not support it.  I would set your security protocol like this:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 |
                                       SecurityProtocolType.Tls11 |
                                       SecurityProtocolType.Tls |
                                       SecurityProtocolType.Ssl3;

As a suggestion, you can set the Server Certificate Validation Callback, and the Security Protocol, outside of your loop as it is a static setting for all requests.  Also if you utilize the C# using syntax, the Dispose method takes care of closing and disposing your WebResponse and StreamReader variables for you.  And C# introduced 'var' back in .NET 3.0, your might want to start embracing it, that is presuming you are using the 3.0 or newer framework.  If you want to see what this would look like, look below.

Make sure you have these usings:

using System;
using System.IO;
using System.Net;

Then put these two lines in the static constructor of your form, or object, I assume you are using a form right now:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

Then your two methods would look like this:

private void button4_Click(object sender, EventArgs e)
{
  try
  {
    for (var i = 0; i < listBox2.Items.Count; i++)
    {
      var response = Code(listBox2.Items[i].ToString() + "\'");
      if (response.ToLower().Contains("mysql"))
      {
        Console.WriteLine("positive " + listBox2.Items[i].ToString());
      }
    }
  }
  catch (Exception ex)
  {
    Console.WriteLine(ex.Message);
  }
}

public static string Code(string url)
{
  var webRequest = (HttpWebRequest)WebRequest.Create(url);
  webRequest.MaximumAutomaticRedirections = 4;
  webRequest.MaximumResponseHeadersLength = 4;
  webRequest.UserAgent = "Mozilla/5.0 (Taco2) Gecko/20100101";
  webRequest.Credentials = CredentialCache.DefaultCredentials;

  webRequest.Method = "GET";

  using (var webResponse = webRequest.GetResponse())
  {
    using (var sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8))
    {
      return sr.ReadToEnd();
    }
  }
}

Happy Coding!  Feel free to ask any questions in the comments below.


来源: stackexchange

问:
Execute function according to time
I'm trying to create a way for every minute the execute_func function to be executed.

I have tried to loop in minutes, however the function is never executed, below the function

```<code>void main(void) {
    time_t timer;
    struct tm* tmr;

    timer = time(NULL);
    tmr = localtime(&timer);

        if (tmr->tm_min == 1)
            execute_func();
    }
    return;
}
</code>```

答:
On a linux system, a system call will do it just fine. Here is an example of executing a piece of code or calling a function after every one minute:

```<code>while(true)
    {
      system("sleep 60s");
      computeAFunction(); /* The function that you want to execute after every one minute */

       if( (true ) /* some code that you want to execute */
       {
         exit(0); /* if true exit */

                 }
       else
         {
            continue; /* or else keep running */
               }

      }
</code>```

I have personally used this, when i wanted to keep computing a specif value which was changing with the passage of time, so i had to make decisions on the newly computed value.
You can modify it  a bit in a way which suits your needs.

Alternatively you can use the sleep() function defined in windows.h header file on windows sytems, and in unistd.h on linux.

sleep(1000) is equal to sleep 1s.

ContentLicense: CC BY-SA 3.0

Title: Execute function according to time

Body:
I'm trying to create a way for every minute the execute_func function to be executed.

I have tried to loop in minutes, however the function is never executed, below the function

void main(void) {
    time_t timer;
    struct tm* tmr;

    timer = time(NULL);
    tmr = localtime(&timer);

        if (tmr->tm_min == 1)
            execute_func();
    }
    return;
}

Body:
On a linux system, a system call will do it just fine. Here is an example of executing a piece of code or calling a function after every one minute:

while(true)
    {
      system("sleep 60s");
      computeAFunction(); /* The function that you want to execute after every one minute */

       if( (true ) /* some code that you want to execute */
       {
         exit(0); /* if true exit */

                 }
       else
         {
            continue; /* or else keep running */
               }

      }

I have personally used this, when i wanted to keep computing a specif value which was changing with the passage of time, so i had to make decisions on the newly computed value.
You can modify it  a bit in a way which suits your needs.

Alternatively you can use the sleep() function defined in windows.h header file on windows sytems, and in unistd.h on linux.

sleep(1000) is equal to sleep 1s.


问:
How do I limit the dragging area for image views
My first post and I am currently making an app in Xcode 8.1 using Swift 3

I have 9 images that I have made draggable with touchesBegan and touchesMoved functions.

However they are able to be dragged ANYWHERE on the screen and this can cause them to cover up other images I have. I would like to limit their movement by setting a boundary for them so that even when the user tries to drag the images out of that boundary they wont be able to.

I have created this code in draggedimageview.swift this allows the Image views to be dragged.

I have been spending a long time trying to figure out how to do this and if anyone can help I would appreciate it.

Thanks...

```<code>import UIKit

class DraggedImageView: UIImageView {

    var startLocation: CGPoint?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        startLocation = touches.first?.location(in: self)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        let currentLocation = touches.first?.location(in: self)
        let dx = currentLocation!.x - startLocation!.x
        let dy = currentLocation!.y - startLocation!.y

        self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
    }
}
</code>```

答:
You can do this:

```<code>let cx = self.center.x+dx
if (cx > 100) {
   cx = 100
}

self.center = CGPoint(x: cx, y: self.center.y+dy)
</code>```

But alter the if based on what you are trying to do.  This clamps it so that it cannot be moved to a position where center.x > 100

Body:
My first post and I am currently making an app in Xcode 8.1 using Swift 3

I have 9 images that I have made draggable with touchesBegan and touchesMoved functions.

However they are able to be dragged ANYWHERE on the screen and this can cause them to cover up other images I have. I would like to limit their movement by setting a boundary for them so that even when the user tries to drag the images out of that boundary they wont be able to.

I have created this code in draggedimageview.swift this allows the Image views to be dragged.

I have been spending a long time trying to figure out how to do this and if anyone can help I would appreciate it.

Thanks...

import UIKit

class DraggedImageView: UIImageView {

    var startLocation: CGPoint?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        startLocation = touches.first?.location(in: self)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        let currentLocation = touches.first?.location(in: self)
        let dx = currentLocation!.x - startLocation!.x
        let dy = currentLocation!.y - startLocation!.y

        self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
    }
}

Body:
You can do this:

let cx = self.center.x+dx
if (cx > 100) {
   cx = 100
}

self.center = CGPoint(x: cx, y: self.center.y+dy)

But alter the if based on what you are trying to do.  This clamps it so that it cannot be moved to a position where center.x > 100


问:
Substitute everything but letters
I am trying to write a single line bash command that will replace every single not letter into a newline. (I am using bash)

Right now, I have this: tr ^[a-zA-Z]g '\n'

I have also tried tr [^a-zA-Z]g '\n' Both don't work.

I thought that the ^ character would have the regular expression match everything but a-z and A-Z, and thus turn all other characters into newlines, but instead it still jus turns a-z and A-Z into newlines, and keeps the other characters.

How can I make sure that I am using the ^ to reverse the regex, instead of anchor it to the beginning of the line?

Does anyone know the correct syntax? Or should I try using a different command? Thanks.

答:
Your usage of the ^ character is wrong. The character ^ used outside of square brackets matches the start of a line. When it is used within square brackets, it matches all the characters not contained within the square brackets. So your command should be:

```<code>tr [^a-zA-Z]g '\n'
</code>```

Follow this link to get a clear idea about how to use the ^ character: Link to Posix basic matching

Title: Substitute everything but letters

Body:
Your usage of the ^ character is wrong. The character ^ used outside of square brackets matches the start of a line. When it is used within square brackets, it matches all the characters not contained within the square brackets. So your command should be:

tr [^a-zA-Z]g '\n'

Follow this link to get a clear idea about how to use the ^ character: Link to Posix basic matching


问:
MySQL conditional self join

Table

```<code>CREATE TABLE dialoglog (
   userid int,
   appid int,
   type varchar(100) ,
   ds timestamp
 );
</code>```

Data

```<code>userid  appid   type    ds
1        1      imp     January, 19 2016 03:14:07
1        1      click   January, 20 2016 03:14:07
2        1      imp     January, 19 2016 03:14:07
2        1      click   January, 18 2016 03:14:07
3        6       imp    January, 19 2016 03:14:07
10       1      click   January, 19 2016 03:14:07
1        1       imp    January, 20 2016 03:12:07
</code>```

Question

What is the CTR (click/imp) per appid ?

Problem

We want to print the CTR per group

Problem is that we have "bad" data:

User 10 click for appid 1 but has no impression for appid 1 => We should ignore it

User 2 click for appid 1 before he has an impression for appid 1 => We should ignore it

Therefore, a query like this:

```<code>SELECT SUM(CASE WHEN type='click' THEN 1 else 0 END)*1.0/SUM(CASE WHEN dialoglog.type='imp' THEN 1 else 0 END) as ctr,appid
     FROM  dialoglog GROUP BY  appid;
</code>```

Would not work because of the constrain I just said.
    Is it possible to code all these constrain in a single mysql query?

Here is sqlfiddle to play with

Result expected

For appid 1 we have 3 impression and 1 click (that is valid since for user 2 timestamp clicked < timestamp impression and for user 10 there was no impression) therefore we should have a CTR of 1/3.

For appid 6, we only have one impression => CTR = 0

Therefore I am expecting this result:

```<code>appid  CTR
1      0.333
6      0
</code>```

What I tried so far

I thought about doing left join but the problem is that it will duplicate the right table:

```<code>SELECT * FROM dialoglog t1 LEFT JOIN dialoglog t2 on t1.userid=t2.userid and t1.appid=t2.appid and t1.type<>t2.type WHERE t1.type="imp" and t1.ds<t2.ds;

userid  appid   type    ds                   userid appid   type    ds
1        1      imp January, 19 2016 03:14:07   1    1    click January, 20 2016 03:14:07
1        1      imp January, 19 2016 03:12:07   1    1    click January, 20 2016 03:14:07
</code>```

答:
You seem to need the earliest "imp" for each user.  Then you can aggregate by the transactions after that point in time:</p>

```<code>SELECT dl.appid, SUM(dl.type = 'click') / SUM(dl.type = 'imp')
FROM dialoglog dl LEFT JOIN
     (SELECT dl2.userId, MIN(ds) as imp_ds
      FROM dialoglog dl2
      WHERE type = 'imp'
      GROUP BY dl2.userid
     ) dlimp
     ON dl.userid = dlimp.userid
WHERE dl.ds >= dlimp.imp_ds
GROUP BY dl.appid;
</code>```

Title: MySQL conditional self join

Body:
Table

CREATE TABLE dialoglog (
   userid int,
   appid int,
   type varchar(100) ,
   ds timestamp
 );

Data

userid  appid   type    ds
1        1      imp     January, 19 2016 03:14:07
1        1      click   January, 20 2016 03:14:07
2        1      imp     January, 19 2016 03:14:07
2        1      click   January, 18 2016 03:14:07
3        6       imp    January, 19 2016 03:14:07
10       1      click   January, 19 2016 03:14:07
1        1       imp    January, 20 2016 03:12:07

Question

What is the CTR (click/imp) per appid ?

Problem

We want to print the CTR per group

Problem is that we have "bad" data:

User 10 click for appid 1 but has no impression for appid 1 => We should ignore it

User 2 click for appid 1 before he has an impression for appid 1 => We should ignore it

Therefore, a query like this:

SELECT SUM(CASE WHEN type='click' THEN 1 else 0 END)*1.0/SUM(CASE WHEN dialoglog.type='imp' THEN 1 else 0 END) as ctr,appid
     FROM  dialoglog GROUP BY  appid;

Would not work because of the constrain I just said.
    Is it possible to code all these constrain in a single mysql query?

Here is sqlfiddle to play with

Result expected

For appid 1 we have 3 impression and 1 click (that is valid since for user 2 timestamp clicked < timestamp impression and for user 10 there was no impression) therefore we should have a CTR of 1/3.

For appid 6, we only have one impression => CTR = 0

Therefore I am expecting this result:

appid  CTR
1      0.333
6      0

What I tried so far

I thought about doing left join but the problem is that it will duplicate the right table:

SELECT * FROM dialoglog t1 LEFT JOIN dialoglog t2 on t1.userid=t2.userid and t1.appid=t2.appid and t1.type<>t2.type WHERE t1.type="imp" and t1.ds<t2.ds;

userid  appid   type    ds                   userid appid   type    ds
1        1      imp January, 19 2016 03:14:07   1    1    click January, 20 2016 03:14:07
1        1      imp January, 19 2016 03:12:07   1    1    click January, 20 2016 03:14:07

Body:
You seem to need the earliest "imp" for each user.  Then you can aggregate by the transactions after that point in time:

SELECT dl.appid, SUM(dl.type = 'click') / SUM(dl.type = 'imp')
FROM dialoglog dl LEFT JOIN
     (SELECT dl2.userId, MIN(ds) as imp_ds
      FROM dialoglog dl2
      WHERE type = 'imp'
      GROUP BY dl2.userid
     ) dlimp
     ON dl.userid = dlimp.userid
WHERE dl.ds >= dlimp.imp_ds
GROUP BY dl.appid;


问:
Prevent or remove full screen overlay from bootstrap modal
When opening a bootstrap modal, it contains a shadow/dark backdrop. If you set this backdrop to false it removes the shadow, but the large area behind the modal still remains, preventing anything in the background from being clicked.

Is there a way to limit the size of a modal to the size of the actual .modal-content area?

Here is a fiddle demoing the issue: https://jsfiddle.net/s75L8z1v/

Right click and Inspect the background outside of the modal and you will still it still belongs to the modal object, preventing you from clicking the background behind it.

答:
You seem to want popover behavior with modal styling.

I believe it's easier to provide modal styling to a popover than to strip the behavior from a modal and I can't guarantee it's going to work on all devices properly. At first glance, seems like a no-no from user-experience, expectations and, ultimately, satisfaction point of view.

Modals are supposed to focus attention and be dismissed. If you don't need that, you should probably center a popover.

Nonetheless, here is what should be done:

Re-enable scroll on  when modal is open.

disable pointer-events on .modal-content (so elements beneath can catch them).

(re-)enable pointer-events on .modal-content

add display:none to .modal-backdrop. Note this can also be achieved using backdrop: false in modal options.

Or, translated in CSS:

body.modal-open { overflow: auto; }
.modal.in { pointer-events: none; }
.modal-content { pointer-events:all; }
.modal-backdrop { display: none; }
```

<p>Demo: </p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body.modal-open {
  overflow: auto;
}
.modal.in {
  pointer-events: none;
}
.modal-content {
  pointer-events:all;
}
.modal-backdrop {
  display: none;
}

/*
 * you don't need the CSS below, it's only for SO,
 */

.text-center > .btn-primary {
 display: inline-block;
 margin: 7rem auto;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

[32] But I must explain to you how all this mistaken idea of denouncing of a pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

[33] On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammeled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

[32] But I must explain to you how all this mistaken idea of denouncing of a pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

[33] On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammeled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

[32] But I must explain to you how all this mistaken idea of denouncing of a pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

[33] On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammeled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

```

Body:
You seem to want popover behavior with modal styling.

I believe it's easier to provide modal styling to a popover than to strip the behavior from a modal and I can't guarantee it's going to work on all devices properly. At first glance, seems like a no-no from user-experience, expectations and, ultimately, satisfaction point of view.

Modals are supposed to focus attention and be dismissed. If you don't need that, you should probably center a popover.

Nonetheless, here is what should be done:

Re-enable scroll on <body> when modal is open.

disable pointer-events on .modal-content (so elements beneath can catch them).

(re-)enable pointer-events on .modal-content

add display:none to .modal-backdrop. Note this can also be achieved using backdrop: false in modal options.

Or, translated in CSS:

body.modal-open { overflow: auto; }
.modal.in { pointer-events: none; }
.modal-content { pointer-events:all; }
.modal-backdrop { display: none; }

Demo:

body.modal-open {
  overflow: auto;
}
.modal.in {
  pointer-events: none;
}
.modal-content {
  pointer-events:all;
}
.modal-backdrop {
  display: none;
}

/*
 * you don't need the CSS below, it's only for SO,
 */

.text-center > .btn-primary {
 display: inline-block;
 margin: 7rem auto;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- Button trigger modal -->
<div class="text-center">
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

<div class="container">

<p>[32] But I must explain to you how all this mistaken idea of denouncing of a pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

<p>[33] On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammeled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

<p>[32] But I must explain to you how all this mistaken idea of denouncing of a pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

<p>[33] On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammeled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

<p>[32] But I must explain to you how all this mistaken idea of denouncing of a pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

<p>[33] On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammeled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.
</div>


问:
Python math range error
I'm getting an error when trying to calculate a very large number in Python. Here is my code:

```<code># Where fourthNumber = 2790
# and dee = 413
emm = math.pow(fourthNumber, dee)
</code>```

An my error is:

```<code>line 44, in <module>
    emm = math.pow(fourthNumber, dee)
OverflowError: math range error
</code>```

Is there a way around this error? I thought Python could handle arbitrarily large numbers? Or am I wrong? Any help is appreciated. Thanks!

答: There might be a bug in the math library - besides, math.pow is kind of redundant, you can do fourthNumber ** dee instead

Title: Python math range error

Body:
I'm getting an error when trying to calculate a very large number in Python. Here is my code:

# Where fourthNumber = 2790
# and dee = 413
emm = math.pow(fourthNumber, dee)

An my error is:

line 44, in <module>
    emm = math.pow(fourthNumber, dee)
OverflowError: math range error

Is there a way around this error? I thought Python could handle arbitrarily large numbers? Or am I wrong? Any help is appreciated. Thanks!


问:
Get specific value from nested collections using LINQ
I have a collection of "product" objects that each contain a collection of benefit objects. See below:

```<code><Products>
        <Product ID="454">
            <ProductName>Economy</ProductName>
            <Benefits>
                <Benefit>
                    <Name>Medical</Name>
                    <Value>5000000</Value>
                    <Excess>100</Excess>
                </Benefit>
                <Benefit>
                    <Name>Emergency</Name>
                    <Value>350</Value>
                    <Excess>100</Excess>
                </Benefit>
        </Product>
</Products>
</code>```

I'm trying to create a LINQ query to get the "Medical" benefit value for product "454":

```<code><%: Model.Products.Where(x => x.ProductId == "454").SelectMany(p => p.Benefits).Where(b => b.Name == "Medical").Select(v => v.Value.ToString()) %>
</code>```

However this just returns:

```<code>System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String
</code>```

How do I get it to return the actual value I'm after?

答:
try this</p>

```<code>Model.Products
    .Where(p => p.ID == 454)
    .SelectMany(p => p.Benefits)
    .Where(b => b.Name == "Medical")
    .Single()
    .Value.ToString();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a collection of "product" objects that each contain a collection of benefit objects. See below:

<Products>
        <Product ID="454">
            <ProductName>Economy</ProductName>
            <Benefits>
                <Benefit>
                    <Name>Medical</Name>
                    <Value>5000000</Value>
                    <Excess>100</Excess>
                </Benefit>
                <Benefit>
                    <Name>Emergency</Name>
                    <Value>350</Value>
                    <Excess>100</Excess>
                </Benefit>
        </Product>
</Products>

I'm trying to create a LINQ query to get the "Medical" benefit value for product "454":

<%: Model.Products.Where(x => x.ProductId == "454").SelectMany(p => p.Benefits).Where(b => b.Name == "Medical").Select(v => v.Value.ToString()) %>

However this just returns:

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String

How do I get it to return the actual value I'm after?

Body:
try this

Model.Products
    .Where(p => p.ID == 454)
    .SelectMany(p => p.Benefits)
    .Where(b => b.Name == "Medical")
    .Single()
    .Value.ToString();


问:
C convert char* to network byte order before transfer
I'm working on a project where I must send data to server and this client will run on different os's. I knwo the problem with endians on different machines, so I'm converting 'everything' (almost) to network byte order, using htonl and vice-versa on the other end.
Also, I know that for a single byte, I don't need to convert anything. But, what should I do for char*? ex:

```<code>send(sock,(char*)text,sizeof(text));
</code>```

What's the best approach to solve this? Should I create an 'intermediate function' do intercept this 'send', then really send char-by-char of this char array? If so, do I need to convert every char to network byte order? I think no, since every char is only one byte.
Thinking of this, if I create this 'intermediate functions', I don't have to convert nothing more to network byte order, since this function will send char by char, thus don't need conversion of endians.
I any advice on this.

答:
I am presuming from your question that the application layer protocol (more specifically everything above level 4) is under your design control.  For single byte-wide (octet-wide in networking parlance) data there is no issue with endian ordering and you need do nothing special to accommodate that.  Now if the character data is prepended with a length specifier that is, say 2 octets, then the ordering of the bytes must be treated consistently.

Going with network byte ordering (big-endian) will certainly fill the bill, but so would consistently using little-endian.  Consistency of byte ordering on each end of a connection is the crucial issue.

If the protocol is not under your design control, then the protocol specification should offer guidance on the issue of byte ordering for multi-byte integers and you should follow that.

Body:
I'm working on a project where I must send data to server and this client will run on different os's. I knwo the problem with endians on different machines, so I'm converting 'everything' (almost) to network byte order, using htonl and vice-versa on the other end.
Also, I know that for a single byte, I don't need to convert anything. But, what should I do for char*? ex:

send(sock,(char*)text,sizeof(text));

What's the best approach to solve this? Should I create an 'intermediate function' do intercept this 'send', then really send char-by-char of this char array? If so, do I need to convert every char to network byte order? I think no, since every char is only one byte.
Thinking of this, if I create this 'intermediate functions', I don't have to convert nothing more to network byte order, since this function will send char by char, thus don't need conversion of endians.
I any advice on this.


问:
Searching a different dictionary depending on what Radio Button is selected
I have a program that uses libraries to retrieve notes on a keyword.
Currently it works great however I wanted to add in a feature that would allow me to select different dictionaries to pull a different set of notes using radio buttons to change what dictionary I am currently searching in.

Dictionaries being called:

```<code>rms_notes = { "SomeKey" : "Some random notes" }
vzt_notes = { "SomeKey" : "Some random notes" }
nsr_notes = { "SomeKey" : "Some random notes" }
</code>```

So my RadioButtons are as follows.

```<code>RaBu1 = tkinter.Radiobutton(root,text="Lib1",variable = vl, value = 1)
RaBu2 = tkinter.Radiobutton(root,text="Lib2",variable = vl, value = 2)
RaBu3 = tkinter.Radiobutton(root,text="Lib3",variable = vl, value = 3)
RaBu1.place(#all the formatting here)
RaBu2.place(#all the formatting here)
RaBu3.place(#all the formatting here)
</code>```

for now my libraries are called using:

```<code>keywordEntry = Entry(root)
keywordEntry.bind('<Return>', kw_entry)
KeywordEntry.place(#all the formatting here)
</code>```

And the function I use to access each different dictionary while a radio button is selected is as follows:

```<code>v1 = IntVar()
def kw_entry(event=None):
    libvar = v1.get()
    e1Current = keywordEntry.get().lower()
    if libvar == 1:
        if e1Current in rms_notes:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, rms_notes[e1Current])
            root.text.see(tkinter.END)
        else:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, "Not a Keyword")
            root.text.see(tkinter.END)
    elif libvar == 2:
        if e1Current in vzt_notes:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, vzt_notes[e1Current])
            root.text.see(tkinter.END)
        else:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, "Not a Keyword")
            root.text.see(tkinter.END)
    elif libvar == 3:
        if e1Current in nsr_notes:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, nsr_notes[e1Current])
            root.text.see(tkinter.END)
        else:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, "Not a Keyword")
            root.text.see(tkinter.END)
    else:
        root.text.delete(1.0, END)
        root.text.insert(tkinter.END, "No Library select")
        root.text.see(tkinter.END)
</code>```

This works how I expected but I am wondering is there a better way to call each dictionary into this function? It just feels like there should be a cleaner way to perform this task with a shorter code.

I could be wrong but if anyone has some ideas or input on the matter I would appreciate it.

答:
You could hold them in an array of dicts, using the index of the array, and the radio button variable value to access the dict in question. Once your dicts are declared, something like:

```<code>dict_Container = [rms_notes, vzt_notes, nsr_notes]
</code>```

Then:

```<code>if e1Current in dictContainer[libvar]:
</code>```

Body:
I have a program that uses libraries to retrieve notes on a keyword.
Currently it works great however I wanted to add in a feature that would allow me to select different dictionaries to pull a different set of notes using radio buttons to change what dictionary I am currently searching in.

Dictionaries being called:

rms_notes = { "SomeKey" : "Some random notes" }
vzt_notes = { "SomeKey" : "Some random notes" }
nsr_notes = { "SomeKey" : "Some random notes" }

So my RadioButtons are as follows.

RaBu1 = tkinter.Radiobutton(root,text="Lib1",variable = vl, value = 1)
RaBu2 = tkinter.Radiobutton(root,text="Lib2",variable = vl, value = 2)
RaBu3 = tkinter.Radiobutton(root,text="Lib3",variable = vl, value = 3)
RaBu1.place(#all the formatting here)
RaBu2.place(#all the formatting here)
RaBu3.place(#all the formatting here)

for now my libraries are called using:

keywordEntry = Entry(root)
keywordEntry.bind('<Return>', kw_entry)
KeywordEntry.place(#all the formatting here)

And the function I use to access each different dictionary while a radio button is selected is as follows:

v1 = IntVar()
def kw_entry(event=None):
    libvar = v1.get()
    e1Current = keywordEntry.get().lower()
    if libvar == 1:
        if e1Current in rms_notes:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, rms_notes[e1Current])
            root.text.see(tkinter.END)
        else:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, "Not a Keyword")
            root.text.see(tkinter.END)
    elif libvar == 2:
        if e1Current in vzt_notes:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, vzt_notes[e1Current])
            root.text.see(tkinter.END)
        else:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, "Not a Keyword")
            root.text.see(tkinter.END)
    elif libvar == 3:
        if e1Current in nsr_notes:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, nsr_notes[e1Current])
            root.text.see(tkinter.END)
        else:
            root.text.delete(1.0, END)
            root.text.insert(tkinter.END, "Not a Keyword")
            root.text.see(tkinter.END)
    else:
        root.text.delete(1.0, END)
        root.text.insert(tkinter.END, "No Library select")
        root.text.see(tkinter.END)

This works how I expected but I am wondering is there a better way to call each dictionary into this function? It just feels like there should be a cleaner way to perform this task with a shorter code.

I could be wrong but if anyone has some ideas or input on the matter I would appreciate it.

Body:
You could hold them in an array of dicts, using the index of the array, and the radio button variable value to access the dict in question. Once your dicts are declared, something like:

dict_Container = [rms_notes, vzt_notes, nsr_notes]

Then:

if e1Current in dictContainer[libvar]:


问:
Pass node.js option via grunt
When I start grunt on the command line, how can I pass an argument to the node process?

In concrete, I'd like to pass the option --expose-gc to node running grunt.
The command I run is:

```<code>grunt mocha:mytests
</code>```

I want to achieve, that my mocha tests get the garbage collection interface exposed.

If that is of any help: the grunt file section looks like this:

```<code>myTest: {
    src: [
        'mocha.hooks/*.spec.js',
        'build/ch.actifsource.*/**/test/*.spec.js',
        'mocha.hooks/*.spec.server.js',
        'build/ch.actifsource.*/**/test/*.spec.server.js'
    ],
    options: {
        timeout: 500,
        logErrors: true
    },
    ignore: [
        './src/**/RegisterResourceTypes.js'
    ]
}
</code>```

答:
The API's for the various grunt mocha plugins do not provide an option to pass --expose-gc, including this one.

You could install grunt-shell instead and configure it to run the same mocha command as you would via the CLI.

Your grunt-shell command would be:

// ...
shell: {
    myTest: {
        command: './node_modules/mocha/bin/mocha -t 500 -gc path/to/files'
    }
}
// ...
```

The path/to/files part should be replaced with your src files.

Note, the command runs local mocha via the bin folder so you also need to install mocha:

$ npm i -D mocha

Title: Pass node.js option via grunt

Body:
When I start grunt on the command line, how can I pass an argument to the node process?

In concrete, I'd like to pass the option --expose-gc to node running grunt.
The command I run is:

grunt mocha:mytests

I want to achieve, that my mocha tests get the garbage collection interface exposed.

If that is of any help: the grunt file section looks like this:

myTest: {
    src: [
        'mocha.hooks/*.spec.js',
        'build/ch.actifsource.*/**/test/*.spec.js',
        'mocha.hooks/*.spec.server.js',
        'build/ch.actifsource.*/**/test/*.spec.server.js'
    ],
    options: {
        timeout: 500,
        logErrors: true
    },
    ignore: [
        './src/**/RegisterResourceTypes.js'
    ]
}

Body:
The API's for the various grunt mocha plugins do not provide an option to pass --expose-gc, including this one.

You could install grunt-shell instead and configure it to run the same mocha command as you would via the CLI.

Your grunt-shell command would be:

// ...
shell: {
    myTest: {
        command: './node_modules/mocha/bin/mocha -t 500 -gc path/to/files'
    }
}
// ...

The path/to/files part should be replaced with your src files.

Note, the command runs local mocha via the bin folder so you also need to install mocha:

$ npm i -D mocha


问:
Android Google Maps basic map
I am trying to display a very basic MapView on one of my activities, however, my MapView is forever blank never loading any map. Said MapView is just a 200px height of an activity that has other elements. I did not create a Map activity from the wizard.

My manifest has:

```<code><meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

<!--
     The API key for Google Maps-based APIs.
-->
<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="my real code" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

My build.gradle has the dependency:

```<code>compile 'com.google.android.gms:play-services-maps:10.2.1'
</code>```

My AndroidStudio HAS the GooglePlay package. Would you know what I am missing?

This is the xml code for my mapView:

```<code><LinearLayout
    android:id="@+id/geolocationLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Geolocation"
        android:textStyle="bold|italic" />

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="200dp" />
</LinearLayout>
</code>```

This is my activity java class map declaration and loading:

Declarations:

```<code>MapView mapView;
GoogleMap map;
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
</code>```

Inside OnCreateView:

```<code>mapView = (MapView) view.findViewById(R.id.mapView);
mapView.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
    }
});
</code>```

答:
Note : I'm assuming you have valid key

```<code>mapView = (MapView) view.findViewById(R.id.mapView);
mapView .onCreate(null);
mapView.getMapAsync(...)
</code>```

And also use other required methods like below, see the documentation below for all methods

```<code>@Override
public void onResume() {
    super.onResume();
    mapView .onResume();
}
</code>```

Check documentation

Check google sample

Title: Android Google Maps basic map

Body:
I am trying to display a very basic MapView on one of my activities, however, my MapView is forever blank never loading any map. Said MapView is just a 200px height of an activity that has other elements. I did not create a Map activity from the wizard.

My manifest has:

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="my real code" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

My build.gradle has the dependency:

compile 'com.google.android.gms:play-services-maps:10.2.1'

My AndroidStudio HAS the GooglePlay package. Would you know what I am missing?

This is the xml code for my mapView:

<LinearLayout
    android:id="@+id/geolocationLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Geolocation"
        android:textStyle="bold|italic" />

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="200dp" />
</LinearLayout>

This is my activity java class map declaration and loading:

Declarations:

MapView mapView;
GoogleMap map;
static final LatLng HAMBURG = new LatLng(53.558, 9.927);

Inside OnCreateView:

mapView = (MapView) view.findViewById(R.id.mapView);
mapView.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
    }
});

Body:
Note : I'm assuming you have valid key

mapView = (MapView) view.findViewById(R.id.mapView);
mapView .onCreate(null);
mapView.getMapAsync(...)

And also use other required methods like below, see the documentation below for all methods

@Override
public void onResume() {
    super.onResume();
    mapView .onResume();
}

Check documentation

Check google sample


问:
Not exactly converts from double to int  - seems problem is in CPU instructions
I got surprised when I debugged my code. Here I provide example code

```<code>#include<QMessageBox>
#include<iostream>
#include<math.h>
#include<QApplication>
using namespace std;

class MyMessageBox: public QMessageBox
{
    public:
        MyMessageBox(string message,QWidget *parent=0) :
            QMessageBox(
                QMessageBox::NoIcon,
                QString("ErrorMessage"),
                QString(message.c_str()),
                QMessageBox::Ok,
                parent,
                Qt::Widget)
        {
        }
};

void Hai()
{
    int tempi = 4;
    double a = pow(10,tempi);
    int temp = int(pow(10,tempi));

    //int temp=a;

    MyMessageBox mb1((QString::number(pow(10,tempi))+
                      " *** "+
                      QString::number(temp)).toStdString());
    mb1.exec();
}

int main(int argc, char * argv[])
{

    QApplication app(argc,argv);
    Hai();

    return app.exec();
}
</code>```

and the result is,

```<code>10000 *** 9999
</code>```

And the main point is, this thing happens only for power 4 (=pow(x,4), not for any other powers.

EDIT:

I tried a minimal code with Visual Studio, but it yields 10,000 exactly. But, it never compiled until I made the type conversion explicitly. The code is given below

```<code>#include<iostream>
#include<math.h>

using namespace std;

void Hai()
{
    int tempi = 4;
    double a=pow(10.0,tempi);
    int temp=pow(10.0,tempi);

    cout << " a " << a << " temp " << temp << endl ;
}

int main(int argc, char * argv[])
{
    Hai();
    return 1;
}
</code>```

答: Remember pow(10,4) and pow(10.0,4) and pow(10.0,4.0) don't call the same function.</p>

Body:
I got surprised when I debugged my code. Here I provide example code

#include<QMessageBox>
#include<iostream>
#include<math.h>
#include<QApplication>
using namespace std;

class MyMessageBox: public QMessageBox
{
    public:
        MyMessageBox(string message,QWidget *parent=0) :
            QMessageBox(
                QMessageBox::NoIcon,
                QString("ErrorMessage"),
                QString(message.c_str()),
                QMessageBox::Ok,
                parent,
                Qt::Widget)
        {
        }
};

void Hai()
{
    int tempi = 4;
    double a = pow(10,tempi);
    int temp = int(pow(10,tempi));

    //int temp=a;

    MyMessageBox mb1((QString::number(pow(10,tempi))+
                      " *** "+
                      QString::number(temp)).toStdString());
    mb1.exec();
}

int main(int argc, char * argv[])
{

    QApplication app(argc,argv);
    Hai();

    return app.exec();
}

and the result is,

10000 *** 9999

And the main point is, this thing happens only for power 4 (=pow(x,4), not for any other powers.

EDIT:

I tried a minimal code with Visual Studio, but it yields 10,000 exactly. But, it never compiled until I made the type conversion explicitly. The code is given below

#include<iostream>
#include<math.h>

using namespace std;

void Hai()
{
    int tempi = 4;
    double a=pow(10.0,tempi);
    int temp=pow(10.0,tempi);

    cout << " a " << a << " temp " << temp << endl ;
}

int main(int argc, char * argv[])
{
    Hai();
    return 1;
}


问:
Using a nightly TensorFlow build for training with Cloud ML Engine
If I need to use a nightly TensorFlow build in a Cloud ML Engine training job, how do I do it?</p>

答:
Download a nightly build from https://github.com/tensorflow/tensorflow#installation.
How to pick the right build:

use "Linux CPU-only" or "Linux GPU" depending on whether you need to use GPUs for training,

use the Python 2 build.

Rename the .whl file, for example

```
mv tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl \
   tensorflow-1.0.1-cp27-none-linux_x86_64.whl
```

(here we renamed the cpu27mu to none. Pip parses that part to detect whether a .whl package is suitable for a platform, but that particular name doesn't work on some older versions of pip)

Upload the .whl file to GCS and specify it as one of the package_uris
when submitting a Cloud ML Engine training job.

Note that instead of using a nightly build you can also build TensorFlow from source as described in https://www.tensorflow.org/install/install_sources.

Body:
Download a nightly build from https://github.com/tensorflow/tensorflow#installation.
How to pick the right build:

use "Linux CPU-only" or "Linux GPU" depending on whether you need to use GPUs for training,

use the Python 2 build.

Rename the .whl file, for example

mv tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl \
   tensorflow-1.0.1-cp27-none-linux_x86_64.whl

(here we renamed the cpu27mu to none. Pip parses that part to detect whether a .whl package is suitable for a platform, but that particular name doesn't work on some older versions of pip)

Upload the .whl file to GCS and specify it as one of the package_uris
when submitting a Cloud ML Engine training job.

Note that instead of using a nightly build you can also build TensorFlow from source as described in https://www.tensorflow.org/install/install_sources.


问:
Express server takes 500ms to return a 304 response
I have a very simple express server. It has compression and uses static-serve to serve files. I have cacheControl set to false, so it only uses the ETag.

The server will return a 304 for the files (which is desired), but it takes about 500ms to do so. That's the same amount of time it takes to actually send the file.

Is there some configuration I can do (outside of things like Varnish and nginx) to speed it up?

The server only has about 6 different files to serve up, all static.

Express server code:

```<code>const path = require('path');
const express = require('express');
const compression = require('compression');
const serveStatic = require('serve-static');

const PORT = process.env.PORT || 9095;

const app = express();

app.use(compression({ threshold: 0 }));

app.use(/regex pattern here/, serveStatic(path.join(__dirname, '../dist/client/assets'), { cacheControl: false }));

app.listen(PORT, (error) => {
  console.log(error || `Listening on port ${PORT}`);
});
</code>```

答:
You should use nginx or something similar to serve static content because node serve-static module need to calculate hash from file content. So this is even slower than just serving file especially on local machine.
Here is deep dive into serve-static mechanics https://evanhahn.com/express-dot-static-deep-dive/</p>

Body:
I have a very simple express server. It has compression and uses static-serve to serve files. I have cacheControl set to false, so it only uses the ETag.

The server will return a 304 for the files (which is desired), but it takes about 500ms to do so. That's the same amount of time it takes to actually send the file.

Is there some configuration I can do (outside of things like Varnish and nginx) to speed it up?

The server only has about 6 different files to serve up, all static.

Express server code:

const path = require('path');
const express = require('express');
const compression = require('compression');
const serveStatic = require('serve-static');

const PORT = process.env.PORT || 9095;

const app = express();

app.use(compression({ threshold: 0 }));

app.use(/regex pattern here/, serveStatic(path.join(__dirname, '../dist/client/assets'), { cacheControl: false }));

app.listen(PORT, (error) => {
  console.log(error || `Listening on port ${PORT}`);
});


答:
Willem, ** is different from math.pow

Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.

You can also use numpy if you have to manipulate huge numbers.

Title: Python math range error


问:
How to get the prediction at a value that inputted from user?
I'm doing Polynomial Regression. I can plot it on the real value, but the problem is, I want to give an X value, for example 125, then I want to get the prediction.

How will I do that?

Thank You

答:
I believe you're looking for the model.predict method.

Here's an example:

```<code>model = make_pipeline(PolynomialFeatures(), Ridge())
model.fit(X, y)
print(model.predict([[125]]))
</code>```

Body:
I believe you're looking for the model.predict method.

Here's an example:

model = make_pipeline(PolynomialFeatures(), Ridge())
model.fit(X, y)
print(model.predict([[125]]))


问:
What are all the audio types available in iPhone SDK?
What are the audio types with which we can record and play back in iPhone? Is any majorly used audio types missed by them?</p>

答:
Most widely used audio formats can be used, including:

MPEG, WAVE, CAFF, AIFF

Formats that cannot be used (without an external library) are:

FLAC (unfortunately), OGG-Vorbis

CAFF is the format Apple uses for sound recording in the iOS SDK.


问:
opencpu not working with data.table in R
I am using the R package data.table to deal with big data files. However, I found it cannot be used with opencpu.

For example, my R function is,

```<code>foo <- function() {
    library(data.table)
    iris = data.table(iris)
    o = iris[,.N,Species]
    return(list(o,dim(o)))
    }
</code>```

and I tried to ocpu.call this function by running,

```<code>  var req = ocpu.call("hello",{},
   function(session){
     console.log(session)
   });
</code>```

And when I check the session, the result output is

```<code>[[1]]
Null data.table (0 rows and 0 cols)

[[2]]
[1] 0 0
</code>```

So you can see that opencpu cannot be used with R package, data.table.

I wonder if this is right or I just missed something here?

答:
opencpu works by providing ajax/client access to R packages in a server's R library location, so in your custom package's NAMESPACE file, make sure these lines are there

```<code>export(my_custom_function_name)
import(data.table)
</code>```

The export() line should already be in there. You should also use the explicit "data.table::data.table(example_df)" namespace syntax convention in your R functions.

I am curious myself why the import() is required (by opencpu?), but I'm new to R package development. I notice this public example from the opencpu public app page uses import(ggplot2). For namespaces, this has been helpful.

Body:
I am using the R package data.table to deal with big data files. However, I found it cannot be used with opencpu.

For example, my R function is,

foo <- function() {
    library(data.table)
    iris = data.table(iris)
    o = iris[,.N,Species]
    return(list(o,dim(o)))
    }

and I tried to ocpu.call this function by running,

  var req = ocpu.call("hello",{},
   function(session){
     console.log(session)
   });

And when I check the session, the result output is

[[1]]
Null data.table (0 rows and 0 cols)

[[2]]
[1] 0 0

So you can see that opencpu cannot be used with R package, data.table.

I wonder if this is right or I just missed something here?

Body:
opencpu works by providing ajax/client access to R packages in a server's R library location, so in your custom package's NAMESPACE file, make sure these lines are there

export(my_custom_function_name)
import(data.table)

The export() line should already be in there. You should also use the explicit "data.table::data.table(example_df)" namespace syntax convention in your R functions.

I am curious myself why the import() is required (by opencpu?), but I'm new to R package development. I notice this public example from the opencpu public app page uses import(ggplot2). For namespaces, this has been helpful.


问:
Javascript - reduce to an object
Execute below code in chrome console - for the google page.

```<code>[].slice.call(document.querySelectorAll("input"))
                       .map(el => el.name?el.name:el.id)
</code>```

I see this output.

I wanted to reduce this list to an object.

```<code>         .reduce((acc,el) => acc[el] = el.toUpperCase(), {});
</code>```

I expected something like below...

```<code>            {
                "sclient":"SCLIENT",
                "site":"SITE",
                ...
            }
</code>```

But it returns only the last element.

What is wrong with this reduce function?

答:
If you are a huge fan of one-liners and browser support is the least of your concerns, you could use Object.assign (ES6).

```<code>.reduce( (acc,el) => Object.assign(acc, {[el]: el.toUpperCase()}), {});
</code>```

Object.assign takes an object as the first argument, and return the very same object (strict equality).

Note the [el] as the object key - a computed property (ES6).

Title: Javascript - reduce to an object

Body:
Execute below code in chrome console - for the google page.

[].slice.call(document.querySelectorAll("input"))
                       .map(el => el.name?el.name:el.id)

I see this output.

I wanted to reduce this list to an object.

         .reduce((acc,el) => acc[el] = el.toUpperCase(), {});

I expected something like below...

            {
                "sclient":"SCLIENT",
                "site":"SITE",
                ...
            }

But it returns only the last element.

What is wrong with this reduce function?

Body:
If you are a huge fan of one-liners and browser support is the least of your concerns, you could use Object.assign (ES6).

.reduce( (acc,el) => Object.assign(acc, {[el]: el.toUpperCase()}), {});

Object.assign takes an object as the first argument, and return the very same object (strict equality).

Note the [el] as the object key - a computed property (ES6).


问:
Passing JSON array to view CodeIgniter through AJAX
I'm having a problem trying to pass a JSON array from my controller to the view to be able to produce a chart using chart js.
I've tried echoing the JSON from the controller and it gets the necessary values.

In my PHP file, there is an ajax call that gets data using a function in the controller.

```<code>$.ajax({
    url: "index.php/Sales/topClients",
    method: "GET",
    success: function(data){
        var parsedData = JSON.parse(data);
        console.log(parsedData[0].Name);
        var clientname = [];
        var orqty = [];

        for(var i in parsedData){
            clientname.push(parsedData[i].Name);
            orqty.push(parsedData[i].Quantity);
        }
        var chartdata= {
            labels: clientname,
            datasets:[
                {
                    label: 'Ordered Quantity',
                    backgroundColor: [
                        'rgba(231, 76, 60,0.7)',
                        'rgba(52, 152, 219,0.7)',
                        'rgba(46, 204, 113,0.7)',
                        'rgba(230, 126, 34,0.7)',
                        'rgba(155, 89, 182,0.7)',
                    ],
                    borderColor: [
                        'rgba(231, 76, 60,1.0)',
                        'rgba(52, 152, 219,1.0)',
                        'rgba(46, 204, 113,1.0)',
                        'rgba(230, 126, 34,1.0)',
                        'rgba(155, 89, 182,1.0)',
                    ],
                    borderWidth: 1,
                    data: orqty
                }
            ]
        };
        Chart.defaults.scale.ticks.beginAtZero=true;
        Chart.defaults.global.title.display= true;

        var ctx= $("#RMCanvas");
        var barGraph= new Chart(ctx,{
            type: 'bar',
            data: chartdata
        });
    },
    error: function(data){
        console.log(data);
    }
});
</code>```

This is the controller (Inventory)

```<code>public function topGoods(){
    $top5fgsold= $this -> Inventory_Model -> getTopGoods();
    echo json_encode($top5fgsold);
    //$this->load->view("SA_Home-Latest");
}
</code>```

This is the model: Inventory_Model

```<code><?php date_default_timezone_set('Asia/Manila');

class Sales_Model extends CI_Model {
    public function __construct() {
        $this->load->database();
    }
    public function getTopClients(){
        $this->db-> select("clients.ClientName, SUM(salesinvoicedetails.orderedQuantity) as q");
        $this->db         -> from("salesinvoicedetails");
        $this->db         -> join ("salesinvoice", "salesinvoicedetails.InvoiceNo = salesinvoice.InvoiceNo");
        $this->db         -> join("clients", "clients.ClientNo = salesinvoice.ClientNo");
        $this->db         -> where("salesinvoice.Status", 2);
        $this->db         -> where("OrderDate >=", " DATE_ADD(NOW(), INTERVAL -30 DAY)");
        $this->db         -> where("OrderDate <= NOW()");
        $this->db         ->group_by("1");
        $this->db         ->order_by("q", "desc");
        $this->db         ->limit(5);

        $topclientresult= $this-> db -> get();
        return $topclientresult-> result_array();
    }
}
</code>```

?>

答:
First of all you need to check if your service working fine, I can see that you using a GET method, so if you put the link in browser you will see a JSON array, if you can't see anything the problem is in your back-end, then you need to check your PHP code.

Second, if you recieve the JSON in your browser, then you can make a request using AJAX,

you can see the result print the data result in console:

```<code>success: function(data){
     console.log(data);
</code>```

For view the result you need to enable the console using F12 then you recharge the page and verify if the JSON appear.

Body:
I'm having a problem trying to pass a JSON array from my controller to the view to be able to produce a chart using chart js.
I've tried echoing the JSON from the controller and it gets the necessary values.

In my PHP file, there is an ajax call that gets data using a function in the controller.

$.ajax({
    url: "index.php/Sales/topClients",
    method: "GET",
    success: function(data){
        var parsedData = JSON.parse(data);
        console.log(parsedData[0].Name);
        var clientname = [];
        var orqty = [];

        for(var i in parsedData){
            clientname.push(parsedData[i].Name);
            orqty.push(parsedData[i].Quantity);
        }
        var chartdata= {
            labels: clientname,
            datasets:[
                {
                    label: 'Ordered Quantity',
                    backgroundColor: [
                        'rgba(231, 76, 60,0.7)',
                        'rgba(52, 152, 219,0.7)',
                        'rgba(46, 204, 113,0.7)',
                        'rgba(230, 126, 34,0.7)',
                        'rgba(155, 89, 182,0.7)',
                    ],
                    borderColor: [
                        'rgba(231, 76, 60,1.0)',
                        'rgba(52, 152, 219,1.0)',
                        'rgba(46, 204, 113,1.0)',
                        'rgba(230, 126, 34,1.0)',
                        'rgba(155, 89, 182,1.0)',
                    ],
                    borderWidth: 1,
                    data: orqty
                }
            ]
        };
        Chart.defaults.scale.ticks.beginAtZero=true;
        Chart.defaults.global.title.display= true;

        var ctx= $("#RMCanvas");
        var barGraph= new Chart(ctx,{
            type: 'bar',
            data: chartdata
        });
    },
    error: function(data){
        console.log(data);
    }
});

This is the controller (Inventory)

public function topGoods(){
    $top5fgsold= $this -> Inventory_Model -> getTopGoods();
    echo json_encode($top5fgsold);
    //$this->load->view("SA_Home-Latest");
}

This is the model: Inventory_Model

<?php date_default_timezone_set('Asia/Manila');

class Sales_Model extends CI_Model {
    public function __construct() {
        $this->load->database();
    }
    public function getTopClients(){
        $this->db-> select("clients.ClientName, SUM(salesinvoicedetails.orderedQuantity) as q");
        $this->db         -> from("salesinvoicedetails");
        $this->db         -> join ("salesinvoice", "salesinvoicedetails.InvoiceNo = salesinvoice.InvoiceNo");
        $this->db         -> join("clients", "clients.ClientNo = salesinvoice.ClientNo");
        $this->db         -> where("salesinvoice.Status", 2);
        $this->db         -> where("OrderDate >=", " DATE_ADD(NOW(), INTERVAL -30 DAY)");
        $this->db         -> where("OrderDate <= NOW()");
        $this->db         ->group_by("1");
        $this->db         ->order_by("q", "desc");
        $this->db         ->limit(5);

        $topclientresult= $this-> db -> get();
        return $topclientresult-> result_array();
    }
}

?>

Body:
First of all you need to check if your service working fine, I can see that you using a GET method, so if you put the link in browser you will see a JSON array, if you can't see anything the problem is in your back-end, then you need to check your PHP code.

Second, if you recieve the JSON in your browser, then you can make a request using AJAX,

you can see the result print the data result in console:

success: function(data){
     console.log(data);

For view the result you need to enable the console using F12 then you recharge the page and verify if the JSON appear.


问:
Latest value = "Not Downloaded"
I have several projects in TFS which visually appear in the directory hierarchy as grayed out.  When I browse within the projects in Visual Studio 2010/Source Control/TFS 2010, I notice that all of their contents have a Latest value of "Not downloaded".  Normally, I have only seen Latest values of "Yes" or "No".

I have tried all of the varieties of "Get latest" that I know, but I am always alerted that "All files are up to date".

If I try to "Check out for edit", I am not allowed.

When I observe the properties of these grayed out files, they always say Workspace Version = "Not applicable".

How do I fix TFS so that I can download and check out the projects again?  My suspicion is that my workspace is messed up, but I do not know what to do to restore/reconfigure it.

答:
I had some weirdness with this after :

updating to TFS2017

updating to VS2017

trying to change my TFS URL to https (gave up and reverted back to http)

So somewhere along the line this broke my workspace such that all my projects were showing as unbound. I was able to do a get latest again. This should not overwrite any files you have changed providing they are writable, but if you have any doubt whatsoever then backup your local workspace before doing get latest. It will ask you to resolve conflicts - so make sure to select 'keep local copy'.

ContentLicense: CC BY-SA 4.0

Title: Latest value = "Not Downloaded"


问:
C++ - Splitting Filename and File Extension
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

```<code>void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}
</code>```

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.

答:
You could create a look-up table of file extensions that you think you might encounter. And also add a command line option to add a new one to the look-up table if you encounter anything new. Then parse through the file name to see if it any entry in the look-up table is a sub-string in the file name.

EDIT: You can also refer to this question: C++/STL string: How to mimic regex like function with wildcards?

Body:
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.


问:
How to use Telerik GridHyperLinkColumn to open folder
Very quickly, I have a Telerik RadGrid that allows users to upload files to a specific shared server folder location when in edit mode. The users would like a way to select a button on the grid and open the specific folder to show all attachments for that unique row. I am able to successfully use an asp hyperlink control on the popup editing form to show them all attachments within the folder.

I tried adding a GridHyperlinkColumn and a GridTemplateColumn on the RadGrid itself and set the navigation URL to what I did in the code behind, but I am getting a 404 ERROR. Is this relating to how I am writing the folder address?

OPTION 1

```<code><Telerik:GridTemplateColumn UniqueName="hyperlink">
  <ItemTemplate>
    <asp:HyperLink ID="hypDirLink" runat="server" Target="_self"
      NavigateUrl='<%# String.Format("\\server-name\data$\CADLog\{0}, Eval("CAD_ID")) %>'>
      <img src="../Images/Files-icon.png" alt="Open Folder" />
    </asp:HyperLink>
  </ItemTemplate>
</Telerik:GridTemplateColumn>
</code>```

OPTION 2

```<code><Telerik:GridHyperLinkColumn DataTextField="CAD_ID" UniqueName="hyperLinkColumn"
  DataNavigateUrlFields="CAD_ID" ImageUrl="~/Images/Files-icon.png" Target="_self"
  DataNavigateUrlFormatString="~//server-name/data$/CADLog/{0}" />
</code>```

OPTION 3

I have tried a few different ways of formatting the server folder location such as:

```<code>~\\server-name\data$\CADLog\{0}
.\\server-name\data$\CADLog\{0}
~//server-name/data$/CADLog/{0}
.//server-name/data$/CADLog/{0}
\\server-name\data$\CADLog\{0} <-- this is the URL I get when I copy from Windows Explorer
//server-name/data$/CADLog/{0}
</code>```

I have double, triple, quadruple checked that this file does exist on the server and that I have the correct permissions setup on this shared server location. Whenever I click on the link it tries to open the navigation URL within the browser instead of opening Windows Explorer.

I have a ticket open with Telerik Support to try and resolve this, but they do not know what I am trying to do with the above control and have said the controls should be working if it is modeled the same.

答:
To open a folder location on the shared server, I only needed to add one thing to the GridHyperLinkColumn:

```<code>DataNavigateUrlFormatString="File://server-name/data$/CADLog/{0}"
</code>```

This worked perfectly for me and works on the server.

Body:
Very quickly, I have a Telerik RadGrid that allows users to upload files to a specific shared server folder location when in edit mode. The users would like a way to select a button on the grid and open the specific folder to show all attachments for that unique row. I am able to successfully use an asp hyperlink control on the popup editing form to show them all attachments within the folder.

I tried adding a GridHyperlinkColumn and a GridTemplateColumn on the RadGrid itself and set the navigation URL to what I did in the code behind, but I am getting a 404 ERROR. Is this relating to how I am writing the folder address?

OPTION 1

<Telerik:GridTemplateColumn UniqueName="hyperlink">
  <ItemTemplate>
    <asp:HyperLink ID="hypDirLink" runat="server" Target="_self"
      NavigateUrl='<%# String.Format("\\server-name\data$\CADLog\{0}, Eval("CAD_ID")) %>'>

    </asp:HyperLink>
  </ItemTemplate>
</Telerik:GridTemplateColumn>

OPTION 2

<Telerik:GridHyperLinkColumn DataTextField="CAD_ID" UniqueName="hyperLinkColumn"
  DataNavigateUrlFields="CAD_ID" ImageUrl="~/Images/Files-icon.png" Target="_self"
  DataNavigateUrlFormatString="~//server-name/data$/CADLog/{0}" />

OPTION 3

I have tried a few different ways of formatting the server folder location such as:

~\\server-name\data$\CADLog\{0}
.\\server-name\data$\CADLog\{0}
~//server-name/data$/CADLog/{0}
.//server-name/data$/CADLog/{0}
\\server-name\data$\CADLog\{0} <-- this is the URL I get when I copy from Windows Explorer
//server-name/data$/CADLog/{0}

I have double, triple, quadruple checked that this file does exist on the server and that I have the correct permissions setup on this shared server location. Whenever I click on the link it tries to open the navigation URL within the browser instead of opening Windows Explorer.

I have a ticket open with Telerik Support to try and resolve this, but they do not know what I am trying to do with the above control and have said the controls should be working if it is modeled the same.

Body:
To open a folder location on the shared server, I only needed to add one thing to the GridHyperLinkColumn:

DataNavigateUrlFormatString="File://server-name/data$/CADLog/{0}"

This worked perfectly for me and works on the server.


问:
Routing is not working for web api with realtions
I am creating web api using asp.net core. The api end point is logically mapped to resource's relations based on guidelines here
So my API looks like

```<code>      http://tax.mydomain.com/api/v1/clients/1/batches/12/start
</code>```

Where Client is parent of Batch,  1 is clientid and 12 is batchid, and Start is POST action method.

Here is the corresponding controller

```<code>public class TaxController : Controller
{
    [HttpPost]
    [Route("clients/{clientid}/batches/{batchid}/start")]
    public void Start([FromRoute]string clientId, [FromRoute]string batchId,
                      [FromBody]IEnumerable<string> urls)
    {
       // do something
    }
}
</code>```

since api/v1 is common to all controllers i configured that in startup's Configure method. Also i want Home as default controller.

```<code>    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
      app.UseMvc(routes =>
      {
        routes.MapRoute("default","api/v1/{controller=Home}/{action=Index}/{id?}");
      });
    }
</code>```

However client is getting not found error for api http://tax.mydomain.com/api/v1/clients/1/batches/12/start

答:
Any controller methods that do not have a route attribute use convention-based routing.

When you use [Route] attribute, you define attribute routing and so conventional routing is not used for that action/controller. Therefore, your controller is accessible by

```<code>http://tax.mydomain.com/clients/1/batches/12/start
</code>```

As an option, you can use the fact, that attribute routes can be combined with inheritance. Set a Route attribute on the entire controller and this will work as route prefix (the same behavior as [RoutePrefix] attribute in WebApi):

```<code>[Route("api/v1")]
public class TaxController : Controller
{

}
</code>```

More general example from routing documentation:

```<code>[Route("api/[controller]")]
public abstract class MyBaseController : Controller { ... }

public class ProductsController : MyBaseController
{
   [HttpGet] // Matches '/api/Products'
   public IActionResult List() { ... }

   [HttpPost("{id}")] // Matches '/api/Products/{id}'
   public IActionResult Edit(int id) { ... }
}
</code>```

Body:
I am creating web api using asp.net core. The api end point is logically mapped to resource's relations based on guidelines here
So my API looks like

      http://tax.mydomain.com/api/v1/clients/1/batches/12/start

Where Client is parent of Batch,  1 is clientid and 12 is batchid, and Start is POST action method.

Here is the corresponding controller

public class TaxController : Controller
{
    [HttpPost]
    [Route("clients/{clientid}/batches/{batchid}/start")]
    public void Start([FromRoute]string clientId, [FromRoute]string batchId,
                      [FromBody]IEnumerable<string> urls)
    {
       // do something
    }
}

since api/v1 is common to all controllers i configured that in startup's Configure method. Also i want Home as default controller.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
      app.UseMvc(routes =>
      {
        routes.MapRoute("default","api/v1/{controller=Home}/{action=Index}/{id?}");
      });
    }

However client is getting not found error for api http://tax.mydomain.com/api/v1/clients/1/batches/12/start

Body:
Any controller methods that do not have a route attribute use convention-based routing.

When you use [Route] attribute, you define attribute routing and so conventional routing is not used for that action/controller. Therefore, your controller is accessible by

http://tax.mydomain.com/clients/1/batches/12/start

As an option, you can use the fact, that attribute routes can be combined with inheritance. Set a Route attribute on the entire controller and this will work as route prefix (the same behavior as [RoutePrefix] attribute in WebApi):

[Route("api/v1")]
public class TaxController : Controller
{

}

More general example from routing documentation:

[Route("api/[controller]")]
public abstract class MyBaseController : Controller { ... }

public class ProductsController : MyBaseController
{
   [HttpGet] // Matches '/api/Products'
   public IActionResult List() { ... }

   [HttpPost("{id}")] // Matches '/api/Products/{id}'
   public IActionResult Edit(int id) { ... }
}