问:
How to sort values in a map in C++
I am trying to sort my output based on the value and I am unsure on how to approach it.
This is my current output:

```<code> E:2
 H:1
 I:3
 L:2
 N:3
 O:2
 S:2
 T:1
 Y:1
</code>```

This is how I want my output:

```<code> I: 3
 N: 3
 E: 2
 L: 2
 O: 2
 S: 2
 H: 1
 T: 1
 Y: 1
</code>```

My code:

```<code>#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include<string>
using std::string;
#include<map>
using std::map;
#include<algorithm>
using std::sort;

int main()
{
    string input;
    int line = 0;
    map<char, int> letters;
    while (getline(cin, input))
    {
        line += 1;
        for (int i = 0; i < input.length(); i++)
        {
            if (isalpha(input[i]))
            {
                if (letters.count(toupper(input[i])) == 0)
                {
                    letters[toupper(input[i])] = 1;
                }
                else
                {
                    letters[toupper(input[i])] += 1;
                }
            }
        }
    }

    cout << "Processed " << line << " line(s)." << endl;
    cout << "Letters and their frequency:" << endl;
    for (auto it = letters.cbegin(); it != letters.cend(); ++it)
    {

        cout << it->first << ":" << it->second << "\n";

    }
}
</code>```

答:
We beginners should help each other.:)

In any case you need a second container because the std::map is already sorted by key.

A general approach is to copy the map in some other container and sort the new container before outputting it.

For your task you can use std::set as the second container.

Here you are.

```<code>#include <iostream>
#include <map>
#include <set>
#include <utility>

int main()
{
    std::map<char, size_t> m =
    {
        { 'E', 2 }, { 'H', 1 }, { 'I', 3 }, { 'L', 2 },
        { 'N', 3 }, { 'O', 2 }, { 'S', 2 }, { 'T', 1 },
        { 'Y', 1 }
    };

    for (const auto &p : m)
    {
        std::cout << "{ " << p.first << ", " << p.second << " }\n";
    }
    std::cout << std::endl;

    auto cmp = [](const auto &p1, const auto &p2)
    {
        return p2.second < p1.second || !(p1.second < p2.second) && p1.first < p2.first;
    };

    std::set < std::pair<char, size_t>, decltype( cmp )> s(m.begin(), m.end(), cmp);

    for (const auto &p : s)
    {
        std::cout << "{ " << p.first << ", " << p.second << " }\n";
    }
    std::cout << std::endl;
}
</code>```

The program output is

```<code>{ E, 2 }
{ H, 1 }
{ I, 3 }
{ L, 2 }
{ N, 3 }
{ O, 2 }
{ S, 2 }
{ T, 1 }
{ Y, 1 }

{ I, 3 }
{ N, 3 }
{ E, 2 }
{ L, 2 }
{ O, 2 }
{ S, 2 }
{ H, 1 }
{ T, 1 }
{ Y, 1 }
</code>```

Also pay attention to that in your program instead of this if-else statement

```<code>if (letters.count(toupper(input[i])) == 0)
{
    letters[toupper(input[i])] = 1;
}
else
{
    letters[toupper(input[i])] += 1;
}
</code>```

you can just write

```<code>++letters[toupper(input[i])];
</code>```

Title: How to sort values in a map in C++

Body:
I am trying to sort my output based on the value and I am unsure on how to approach it.
This is my current output:

 E:2
 H:1
 I:3
 L:2
 N:3
 O:2
 S:2
 T:1
 Y:1

This is how I want my output:

 I: 3
 N: 3
 E: 2
 L: 2
 O: 2
 S: 2
 H: 1
 T: 1
 Y: 1

My code:

#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include<string>
using std::string;
#include<map>
using std::map;
#include<algorithm>
using std::sort;

int main()
{
    string input;
    int line = 0;
    map<char, int> letters;
    while (getline(cin, input))
    {
        line += 1;
        for (int i = 0; i < input.length(); i++)
        {
            if (isalpha(input[i]))
            {
                if (letters.count(toupper(input[i])) == 0)
                {
                    letters[toupper(input[i])] = 1;
                }
                else
                {
                    letters[toupper(input[i])] += 1;
                }
            }
        }
    }

    cout << "Processed " << line << " line(s)." << endl;
    cout << "Letters and their frequency:" << endl;
    for (auto it = letters.cbegin(); it != letters.cend(); ++it)
    {

        cout << it->first << ":" << it->second << "\n";

    }
}

Body:
We beginners should help each other.:)

In any case you need a second container because the std::map is already sorted by key.

A general approach is to copy the map in some other container and sort the new container before outputting it.

For your task you can use std::set as the second container.

Here you are.

#include <iostream>
#include <map>
#include <set>
#include <utility>

int main()
{
    std::map<char, size_t> m =
    {
        { 'E', 2 }, { 'H', 1 }, { 'I', 3 }, { 'L', 2 },
        { 'N', 3 }, { 'O', 2 }, { 'S', 2 }, { 'T', 1 },
        { 'Y', 1 }
    };

    for (const auto &p : m)
    {
        std::cout << "{ " << p.first << ", " << p.second << " }\n";
    }
    std::cout << std::endl;

    auto cmp = [](const auto &p1, const auto &p2)
    {
        return p2.second < p1.second || !(p1.second < p2.second) && p1.first < p2.first;
    };

    std::set < std::pair<char, size_t>, decltype( cmp )> s(m.begin(), m.end(), cmp);

    for (const auto &p : s)
    {
        std::cout << "{ " << p.first << ", " << p.second << " }\n";
    }
    std::cout << std::endl;
}

The program output is

{ E, 2 }
{ H, 1 }
{ I, 3 }
{ L, 2 }
{ N, 3 }
{ O, 2 }
{ S, 2 }
{ T, 1 }
{ Y, 1 }

{ I, 3 }
{ N, 3 }
{ E, 2 }
{ L, 2 }
{ O, 2 }
{ S, 2 }
{ H, 1 }
{ T, 1 }
{ Y, 1 }

Also pay attention to that in your program instead of this if-else statement

if (letters.count(toupper(input[i])) == 0)
{
    letters[toupper(input[i])] = 1;
}
else
{
    letters[toupper(input[i])] += 1;
}

you can just write

++letters[toupper(input[i])];


来源: stackexchange

问:
What is the best way to execute task five seconds after method call in Java
When I call the following method, I want the code nested inside of it to execute after five seconds. I know there are several ways to do this but I want to know the best and most efficient way to accomplish this in java?

```<code>public void callMe() {
  System.out.println("This is a message!");
}
</code>```

Thanks,
Faraaz

答:
```<code>public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

    for (int i = 0;
         i < importantInfo.length;
         i++) {
        //Pause for 4 seconds
        Thread.sleep(4000);
        //Print a message
        System.out.println(importantInfo[i]);
    }
}
}
}
</code>```

For more information You can also visit the following link:
http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

ContentLicense: CC BY-SA 3.0

Body:
When I call the following method, I want the code nested inside of it to execute after five seconds. I know there are several ways to do this but I want to know the best and most efficient way to accomplish this in java?

public void callMe() {
  System.out.println("This is a message!");
}

Thanks,
Faraaz

Body:
public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

    for (int i = 0;
         i < importantInfo.length;
         i++) {
        //Pause for 4 seconds
        Thread.sleep(4000);
        //Print a message
        System.out.println(importantInfo[i]);
    }
}
}
}

For more information You can also visit the following link:
http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html


答:
Retain the previous plot using hold on. Find the maximum value of y and the value of x for which y is maximum and plot the vertical line like this:

```<code>hold on;
plot([x(y==max(y)); x(y==max(y))], [0; max(y)]);
hold off;
</code>```

which gives:

This works even if you have multiple maximum points.
Here is an output for another random data with 3 maximum points:

As you can see, this makes lines with different colors. If you want the same colors, use the 'Color' property of plot,

Title: A vertical line in the plot

Body:
I want to draw a vertical line for the max Value of y(hier for x near 20), how to do that? (i mean downwards from this value (x=20, ymax) to (x=20, y=0))

x = logspace(0,5);
y=[0;0;0;0;0;0;0;0.15;0.34;0.51;0.71;0.84;0.88;0.856;0.75;0.63;0.47;0.36;0.32;0.33;0.37;0.45;0.5;0.51;0.48;0.4;0.33;0.22;0.14;0.07;0.02;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0];
y=y';

figure(5)
plot(x,y,'-o','LineWidth',2);
%ax(1) = axes('Position',[0.35 0.13 0.3 0.8]);
xlim([0,10000]);
ylim([0,1]);
set(gca, 'XScale', 'log')

grid on
grid minor
set(gca,'FontSize', 20);
set(gca,'Linewidth',1.8);

title('\rm Verteilung der Porengrößen');
xlabel('Porengröße [{\fontsize{24}\mu}{\fontsize{20}m}]');
ylabel('Amplitude des NMR-Signals [V]');

Body:
Retain the previous plot using hold on. Find the maximum value of y and the value of x for which y is maximum and plot the vertical line like this:

hold on;
plot([x(y==max(y)); x(y==max(y))], [0; max(y)]);
hold off;

which gives:

This works even if you have multiple maximum points.
Here is an output for another random data with 3 maximum points:

As you can see, this makes lines with different colors. If you want the same colors, use the 'Color' property of plot,


问:
Excel 2016 Chart Axis-X not showing the correctly
I have a Excel file (.xlsm type) contains lot of Charts. After switch to Excel 2016, certain charts not showing Label correctly (axis-x).
Eg. It suppose showing WK10'17, WK11'17, WK12'17,...
but it showing 1,2,3,4,....

1) I tried to reselect the data, then the label showing correctly, but after save and reopen, it become 1,2,3,4.... again

2) also tried delete the existing chart, and create a new one in Excel 2010 & 2016, problem not solve.

3) Axis Type have been set as Text

Is this a bug in Excel 2016 ? Did anyone have a solution for this ?

Below Chart showing 1,2,3,4,..., which is wrong.

Below chart is showing correctly.

Below are my table look like

1st Experiment:

Firstly, I create a whole new file in Excel 2016. Then do below step:
- Create 4 Indicators for performance review, with dummy data
- Create new chart and format it
- Create simple VBA code to hide everything, and only show related Indicator that selected

Everything work just fine, even switching around the indicator many times.
Later, Close it and reopen, 3 out of 4 charts having Axis-x label became 1,2,3,...

2nd Experiment:

I created Whole new file in Excel 2010, with 4 indicators and same VBA code.
Then Close and reopen, Axis-x format remain Perfectly good.
Transfer the file into Excel 2016 machine. Close and reopen, the Axis-x became 1,2,3....

*** Current Excel Version 1705 (Build 8201.2075)

*** Attach with these experiment files
4Q Demo.zip

Appreciate, who got interested into this issue, have a look on my file.
Share with me, if you do have any solution for that. Thanks

答:
I found out as long as the Chart is not hide, then the axis-x will remain correctly. But this do not really help, when hiding additional chart is a must.

Another temporary workaround method is :

1) moving the data table to another worksheet.

2) Then the set the Chart's data range to another worksheet (Cannot be the same worksheet with Chart).

That will work perfectly, now can hide the chart while maintain axis-x correctly.

**** Only drawback, table have to move or duplicate into another worksheet

**** Probably Microsoft will solve this after Version 1705 (Build 8201.2075)


问:
Permission Denied When Making Request to GCP Video Intelligence API
so I am able to make a valid request to the video intelligence api with the sample video given in the quickstart. https://cloud.google.com/video-intelligence/docs/getting-started I have tried many different ways of authenticating to the api as well. The API token I am using was created from the Credentials page in the console. There are no options to tie it to the video api so I figured it should automatically work. The API has been enabled on my account.

```<code>export TOKEN="foobar"
curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://custom-bucket/IMG_3591.mov", "features": ["LABEL_DETECTION"]}'
{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://cloud-ml-sandbox/video/chicago.mp4", "features": ["LABEL_DETECTION"]}'
{
  "name": "us-east1.18013173402060296928"
}
</code>```

Update:

I set the file as public and it worked. But I need to access this as private, so I gave the service account access to the file and tried to get the API key like suggested.

```<code>export TOKEN="$(gcloud auth print-access-token)"
curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://custom-bucket/IMG_3591.mov", "features":["LABEL_DETECTION"]}'
{
  "error": {
    "code": 400,
    "message": "API key not valid. Please pass a valid API key.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developers console",
            "url": "https://console.developers.google.com"
          }
        ]
      }
    ]
  }
}
</code>```

It seems like the token returned by this print-access-token function does not work. I do have an API key, but it does not have access to the bucket and I don't see a way to give an API key access.

Update 2:

So it looks like we were setting our token wrong. We were following this example https://cloud.google.com/video-intelligence/docs/analyze-labels#videointelligence-label-file-protocol which is where we got the apiKey=$TOKEN from. But it looks like we needed to set the Bearer Header. We did try this at first but we were having the first issue of not having access to the bucket. So thank you.

答: I can repro this issue. I believe the problem is that you don't have proper permission setup for your video file in your gs bucket. To test out this hypothesis try sharing it publicly (checkbox next to the blob in Google Storage) and then run the request again.</p>

Body:
so I am able to make a valid request to the video intelligence api with the sample video given in the quickstart. https://cloud.google.com/video-intelligence/docs/getting-started I have tried many different ways of authenticating to the api as well. The API token I am using was created from the Credentials page in the console. There are no options to tie it to the video api so I figured it should automatically work. The API has been enabled on my account.

export TOKEN="foobar"
curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://custom-bucket/IMG_3591.mov", "features": ["LABEL_DETECTION"]}'
{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://cloud-ml-sandbox/video/chicago.mp4", "features": ["LABEL_DETECTION"]}'
{
  "name": "us-east1.18013173402060296928"
}

Update:

I set the file as public and it worked. But I need to access this as private, so I gave the service account access to the file and tried to get the API key like suggested.

export TOKEN="$(gcloud auth print-access-token)"
curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://custom-bucket/IMG_3591.mov", "features":["LABEL_DETECTION"]}'
{
  "error": {
    "code": 400,
    "message": "API key not valid. Please pass a valid API key.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developers console",
            "url": "https://console.developers.google.com"
          }
        ]
      }
    ]
  }
}

It seems like the token returned by this print-access-token function does not work. I do have an API key, but it does not have access to the bucket and I don't see a way to give an API key access.

Update 2:

So it looks like we were setting our token wrong. We were following this example https://cloud.google.com/video-intelligence/docs/analyze-labels#videointelligence-label-file-protocol which is where we got the apiKey=$TOKEN from. But it looks like we needed to set the Bearer Header. We did try this at first but we were having the first issue of not having access to the bucket. So thank you.


问:
Make li background color span whole ul width CSS
This is probably an easy solution, but I am wracking my brain over this. I am trying to hover over a li that opens another ul, and once I hover over the li in the mentioned ul, the background takes up the whole width of the ul background.

ul {
  margin: 0;
  padding: 0;
  list-style: none;
  z-index: 1000;
}

li {
  position: relative;
  cursor: pointer;
}

ul>li {
  color: #000000;
  float: left;
  padding: 10px;
  height: 22px;
}

ul>li a {
  color: #000000;
  text-decoration: none;
  display: block;
}

ul>li li {
  float: left;
  clear: left;
}

ul>li ul {
  display: none;
  left: 0;
  top: 100%;
}

ul>li li>ul {
  top: 0;
  left: 100%;
}

li>ul {
  position: absolute;
  min-width: 100%;
  display: none;
  background: #f0f0f0;
  list-style: none;
}

li:hover>ul,
li:focus>ul {
  display: block;
}

li:hover {
  background: #27B3CF;
  outline: 1px dotted red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li style="color: white;">Reports
    <ul>
      <li>Lvl 1</li>
      <li><span class="title">Show a List</span>
        <ul>
          <li>Details</li>
        </ul>
      </li>
      <li>Lvl 1</li>
    </ul>
  </li>
</ul></code>```

I have tried using display: block; as much as I can but for some reason I cannot make the background width span the width of the drop down. I am still a beginner and could use some help to lead me in the right direction. Do you see where I can add CSS to make this adjustment? Any help would be much appreciated.

答:
By giving the list items a fixed width, the background color will display across that width, versus only the size of the text and padding.

Here's your snippet, with the following addition to the ul>li class:

width: 50px;

ul {
  margin: 0;
  padding: 0;
  list-style: none;
  z-index: 1000;
}

li {
  position: relative;
  cursor: pointer;
}

ul>li {
  color: #000000;
  float: left;
  padding: 10px;
  height: 22px;
  width: 50px;
}

ul>li a {
  color: #000000;
  text-decoration: none;
  display: block;
}

ul>li li {
  float: left;
  clear: left;
}

ul>li ul {
  display: none;
  left: 0;
  top: 100%;
}

ul>li li>ul {
  top: 0;
  left: 100%;
}

li>ul {
  position: absolute;
  min-width: 100%;
  display: none;
  background: #f0f0f0;
  list-style: none;
}

li:hover>ul,
li:focus>ul {
  display: block;
}

li:hover {
  background: #27B3CF;
  outline: 1px dotted red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li >Reports
    <ul>
      <li>Lvl 1</li>
      <li><span class="title">Show a List</span>
        <ul>
          <li>Details</li>
        </ul>
      </li>
      <li>Lvl 1</li>
    </ul>
  </li>
</ul></code>```

Body:
This is probably an easy solution, but I am wracking my brain over this. I am trying to hover over a li that opens another ul, and once I hover over the li in the mentioned ul, the background takes up the whole width of the ul background.

ul {
  margin: 0;
  padding: 0;
  list-style: none;
  z-index: 1000;
}

li {
  position: relative;
  cursor: pointer;
}

ul>li {
  color: #000000;
  float: left;
  padding: 10px;
  height: 22px;
}

ul>li a {
  color: #000000;
  text-decoration: none;
  display: block;
}

ul>li li {
  float: left;
  clear: left;
}

ul>li ul {
  display: none;
  left: 0;
  top: 100%;
}

ul>li li>ul {
  top: 0;
  left: 100%;
}

li>ul {
  position: absolute;
  min-width: 100%;
  display: none;
  background: #f0f0f0;
  list-style: none;
}

li:hover>ul,
li:focus>ul {
  display: block;
}

li:hover {
  background: #27B3CF;
  outline: 1px dotted red;
}

Reports

Lvl 1

Show a List

Details

Lvl 1

I have tried using display: block; as much as I can but for some reason I cannot make the background width span the width of the drop down. I am still a beginner and could use some help to lead me in the right direction. Do you see where I can add CSS to make this adjustment? Any help would be much appreciated.

Body:
By giving the list items a fixed width, the background color will display across that width, versus only the size of the text and padding.

Here's your snippet, with the following addition to the ul>li class:

width: 50px;

ul {
  margin: 0;
  padding: 0;
  list-style: none;
  z-index: 1000;
}

li {
  position: relative;
  cursor: pointer;
}

ul>li {
  color: #000000;
  float: left;
  padding: 10px;
  height: 22px;
  width: 50px;
}

ul>li a {
  color: #000000;
  text-decoration: none;
  display: block;
}

ul>li li {
  float: left;
  clear: left;
}

ul>li ul {
  display: none;
  left: 0;
  top: 100%;
}

ul>li li>ul {
  top: 0;
  left: 100%;
}

li>ul {
  position: absolute;
  min-width: 100%;
  display: none;
  background: #f0f0f0;
  list-style: none;
}

li:hover>ul,
li:focus>ul {
  display: block;
}

li:hover {
  background: #27B3CF;
  outline: 1px dotted red;
}

<ul>
  <li >Reports
    <ul>
      <li>Lvl 1</li>
      <li><span class="title">Show a List</span>
        <ul>
          <li><a href="#">Details</a></li>
        </ul>
      </li>
      <li>Lvl 1</li>
    </ul>
  </li>
</ul>


问:
NVIDIA-SMI failed. Could'nt communicate with Nvidia driver
I am running a cloud instance on a gpu node. I installed CUDA and nvidia-smi showed the driver details, memory utlilization. After a couple of days, I face this error
"NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running".

I installed the latest driver (Nvidia-375.39 for Tesla M40 Gpus). I still face the same issue. Is there any way to
i) debug why nvidia-smi is not able to communicate with the driver?
ii)check if the driver is running properly.

答: I met the same question as you, I solved this by modify the security option, the step is when I reboot the system,enter the bios,modify secure boot option as disabled,then reboot,It is ok!</p>

ContentLicense: CC BY-SA 4.0


问:
TTask slower than TThread
I have below two methods of multi-threading code doing the same job.

TTask:

```<code>const
  MaxThreadCount = 80;

procedure TWorkerTask.Update;
var
  aTasks  : array of ITask;
  I: Integer;
begin
  Stopwatch := TStopwatch.StartNew;
  SetLength(aTasks, MaxThreadCount);
  for I := Low(aTasks) to High(aTasks) do begin
    aTasks[I] := TTask.Create( procedure
    begin
      Writeln('Thread ', TTask.CurrentTask.Id, ' Stared');
      Sleep(5000);
      Writeln('Thread ', TTask.CurrentTask.Id, ' Finshed');
    end);
    aTasks[I].Start;
  end;
  TTask.WaitForAll(aTasks);
  Elapsed := Stopwatch.Elapsed;
  Writeln('Done in ', Round(Elapsed.TotalSeconds));
end;
</code>```

Output e.g Done in 29

TThread:

```<code>const
  MaxThreadCount = 80;

procedure TWorker.Execute;
begin
  Writeln('Thread ', ThreadID, ' Stared');
  Sleep(5000);
  Writeln('Thread ', ThreadID, ' Finshed');
end;

....

var
  Workers   : array of TWorker;
  I         : Integer;
  Stopwatch : TStopwatch;
  Elapsed   : TTimeSpan;
begin
  SetLength(Workers, MaxThreadCount);
  for I := Low(Workers) to High(Workers) do begin
    Workers[I] := TWorker.Create;
    Workers[I].Start;
  end;
  for I := Low(Workers) to High(Workers) do
    Workers[I].WaitFor;
  Elapsed := Stopwatch.Elapsed;
  Writeln('Done ', Round(Elapsed.TotalSeconds));
</code>```

Output e.g Done 8

Q: Why the TTask is extremely slower than the TThread class on the above method? Is there a way to speed it up to get similar result?

答:
It's because your threads and tasks do no work.

You have more threads than processors. In the version using threads, you can create one thread per task and although the processors are oversubscribed, that doesn't matter because the threads are sleeping.

In the task based version there is, typically, one thread per processor. So not all tasks can run simultaneously.

Were you to replace the sleep with busy work running the CPU at full utilisation then you would see that both versions performed similarly. Indeed I would expect the task based version to be better since it would not oversubscribe the processors.

Title: TTask slower than TThread

Body:
I have below two methods of multi-threading code doing the same job.

TTask:

const
  MaxThreadCount = 80;

procedure TWorkerTask.Update;
var
  aTasks  : array of ITask;
  I: Integer;
begin
  Stopwatch := TStopwatch.StartNew;
  SetLength(aTasks, MaxThreadCount);
  for I := Low(aTasks) to High(aTasks) do begin
    aTasks[I] := TTask.Create( procedure
    begin
      Writeln('Thread ', TTask.CurrentTask.Id, ' Stared');
      Sleep(5000);
      Writeln('Thread ', TTask.CurrentTask.Id, ' Finshed');
    end);
    aTasks[I].Start;
  end;
  TTask.WaitForAll(aTasks);
  Elapsed := Stopwatch.Elapsed;
  Writeln('Done in ', Round(Elapsed.TotalSeconds));
end;

Output e.g Done in 29

TThread:

const
  MaxThreadCount = 80;

procedure TWorker.Execute;
begin
  Writeln('Thread ', ThreadID, ' Stared');
  Sleep(5000);
  Writeln('Thread ', ThreadID, ' Finshed');
end;

....

var
  Workers   : array of TWorker;
  I         : Integer;
  Stopwatch : TStopwatch;
  Elapsed   : TTimeSpan;
begin
  SetLength(Workers, MaxThreadCount);
  for I := Low(Workers) to High(Workers) do begin
    Workers[I] := TWorker.Create;
    Workers[I].Start;
  end;
  for I := Low(Workers) to High(Workers) do
    Workers[I].WaitFor;
  Elapsed := Stopwatch.Elapsed;
  Writeln('Done ', Round(Elapsed.TotalSeconds));

Output e.g Done 8

Q: Why the TTask is extremely slower than the TThread class on the above method? Is there a way to speed it up to get similar result?


问:
Visual Studio Online Jmeter throws exception: Unable to load or invoke class: org.apache.jmeter.protocol.http.control.HC3CookieHandler
I'm trying to run a load test using the Visual Studio Online support for JMeter tests. I'm getting an error below. I tried these 2 settings but with the same results

```<code><stringProp name="CookieManager.implementation">org.apache.jmeter.protocol.http.control.HC3CookieHandler</stringProp>

<stringProp name="CookieManager.implementation">org.apache.jmeter.protocol.http.control.HC4CookieHandler</stringProp>
</code>```

based on the advice from here

Unable to load or invoke class:
  org.apache.jmeter.protocol.http.control.HC3CookieHandler
  org.apache.jorphan.util.JMeterException:
  java.lang.reflect.InvocationTargetException   at
  org.apache.jorphan.reflect.ClassTools.construct(ClassTools.java:112)
    at
  org.apache.jmeter.protocol.http.control.CookieManager.testStarted(CookieManager.java:397)
    at
  org.apache.jmeter.engine.StandardJMeterEngine.notifyTestListenersOfStart(StandardJMeterEngine.java:214)
    at
  org.apache.jmeter.engine.StandardJMeterEngine.run(StandardJMeterEngine.java:336)
    at java.lang.Thread.run(Unknown Source) Caused by:
  java.lang.reflect.InvocationTargetException   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
  Source)   at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
  Source)   at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at
  org.apache.jorphan.reflect.ClassTools.construct(ClassTools.java:100)
    ... 4 more Caused by: java.lang.IllegalStateException: Unsupported
  cookie spec standard  at
  org.apache.commons.httpclient.cookie.CookiePolicy.getCookieSpec(CookiePolicy.java:220)
    at
  org.apache.jmeter.protocol.http.control.HC3CookieHandler.(HC3Coo

答: I think I found my answer it seems vs-team-services only supports Apache JMeter 2.13 </p>

Body:
I'm trying to run a load test using the Visual Studio Online support for JMeter tests. I'm getting an error below. I tried these 2 settings but with the same results

<stringProp name="CookieManager.implementation">org.apache.jmeter.protocol.http.control.HC3CookieHandler</stringProp>

<stringProp name="CookieManager.implementation">org.apache.jmeter.protocol.http.control.HC4CookieHandler</stringProp>

based on the advice from here

Unable to load or invoke class:
  org.apache.jmeter.protocol.http.control.HC3CookieHandler
  org.apache.jorphan.util.JMeterException:
  java.lang.reflect.InvocationTargetException   at
  org.apache.jorphan.reflect.ClassTools.construct(ClassTools.java:112)
    at
  org.apache.jmeter.protocol.http.control.CookieManager.testStarted(CookieManager.java:397)
    at
  org.apache.jmeter.engine.StandardJMeterEngine.notifyTestListenersOfStart(StandardJMeterEngine.java:214)
    at
  org.apache.jmeter.engine.StandardJMeterEngine.run(StandardJMeterEngine.java:336)
    at java.lang.Thread.run(Unknown Source) Caused by:
  java.lang.reflect.InvocationTargetException   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
  Source)   at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
  Source)   at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at
  org.apache.jorphan.reflect.ClassTools.construct(ClassTools.java:100)
    ... 4 more Caused by: java.lang.IllegalStateException: Unsupported
  cookie spec standard  at
  org.apache.commons.httpclient.cookie.CookiePolicy.getCookieSpec(CookiePolicy.java:220)
    at
  org.apache.jmeter.protocol.http.control.HC3CookieHandler.(HC3Coo


问:
Cannot get product of if statement to write to a new .txt file
I'm working on a sales tool for my Java class and I'm able to get everything working except for writing my results to a new .txt file.  To give some backstory, I have a GUI that is writing data to a text file named out1.txt.  I am reading data back in from this file and displaying anything with computesales >= 8,000 in a JtextArea as shown in the code below.

```<code> private void evaluateButtonActionPerformed(java.awt.event.ActionEvent evt) {
    saleOutput.setText("");
    SaleReader reader = new SaleReader();

    try
    {
        List<Sales> sale = reader.readSale("out1.txt");
        for (Sales s : sale)
        {
            if(s.computeSales()>= 8000)
            {
            saleOutput.append(s.toString());
            saleOutput.append("\n");

            }
        }
    }catch (IOException ex) {
        JOptionPane.showMessageDialog(this, "Unable to open file");
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }

}
</code>```

I have tried a variation of what I have below that writes to my out1.txt file, but it doesn't seem to work at all.  It won't even create the file.  My coworker seemed to think that it may be an issues with the filewriter not being flushed?

```<code> public void writeSales(Sales s) throws IOException
{
    File testWriter = new File ("out1.txt");
    BufferedWriter out = new BufferedWriter(new FileWriter(testWriter, true));

    out.write("" + s.getSalesID());
    out.write(", ");
    out.write(s.getFirstName());
    out.write(", ");
    out.write(s.getLastName());
    out.write(", ");
    out.write("" + s.getOfficeSupplies());
    out.write(", ");
    out.write("" + s.getBooks());
    out.write(", ");
    out.write("" + s.getPaper());
    out.write(", ");
    out.write("" + s.getDistrictValue());
    out.write(", ");
    out.write("" + s.getPreferredContact());
    out.write(", ");
    out.write("" + s.computeSales());
    out.newLine();
    out.close();
}
</code>```

Here is what I'm writing in a separate class to write to the new stars.txt file, but is not working.  Any suggestions?

```<code>public void writeStars(Sales f) throws IOException
{
    File testStars = new File ("stars.txt");
    BufferedWriter outStars = new BufferedWriter(new FileWriter(testStars, true));
    SaleReader reader = new SaleReader();

     try
    {
        List<Sales> sale = reader.readSale("out1.txt");
        for (Sales s : sale)
        {
            if(s.computeSales()>= 8000)
            {
            outStars.write("" + s.getDistrictValue());
            outStars.newLine();
            outStars.close();

            }
        }
    }catch (IOException ex) {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }
}
</code>```

I'm calling it from here.

```<code>public class Sales
{
 private int salesID;
 private String firstName;
 private String lastName;
 private double officeSupplies;
 private double books;
 private double paper;
 private String districtValue;
 private String preferredContact;

public int getSalesID() {
    return salesID;
}

public void setSalesID(int salesID) {
    this.salesID = salesID;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public double getOfficeSupplies() {
    return officeSupplies;
}

public void setOfficeSupplies(double officeSupplies) {
    this.officeSupplies = officeSupplies;
}

public double getBooks() {
    return books;
}

public void setBooks(double books) {
    this.books = books;
}

public double getPaper() {
    return paper;
}

public void setPaper(double paper) {
    this.paper = paper;
}

public String getPreferredContact() {
    return preferredContact;
}

public void setPreferredContact(String preferredContact) {
    this.preferredContact = preferredContact;
}

public String getDistrictValue() {
    return districtValue;
}

public void setDistrictValue(String districtValue) {
    this.districtValue = districtValue;
}

@Override
public String toString() {
    return "Sales{" + "salesID=" + salesID + ", firstName=" + firstName + ", lastName=" + lastName + ", officeSupplies=" + officeSupplies + ", books=" + books + ", paper=" + paper + ", districtValue=" + districtValue + ", preferredContact=" + preferredContact + '}';
}

public double computeSales()
{
    return officeSupplies + books + paper;
}
</code>```

}

答:
If your class is called for example SalesWriter and you have this code in it

```<code>public void writeStars() throws IOException
{
    File testStars = new File ("stars.txt");
    BufferedWriter outStars = new BufferedWriter(new FileWriter(testStars, true));
    SaleReader reader = new SaleReader();

     try
    {
        List<Sales> sale = reader.readSale("out1.txt");
        for (Sales s : sale)
        {
            if(s.computeSales()>= 8000)
            {
            outStars.write(s);
            outStars.newLine();

            }
        }
        outStars.close();

    }catch (IOException ex) {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }
}
</code>```

Then from your main code you can call it like

```<code>new SalesWriter ().writeStars ();
</code>```

edit

See how I have removed the parameter to this method, as your are reading the file in this method anyway.

Body:
I'm working on a sales tool for my Java class and I'm able to get everything working except for writing my results to a new .txt file.  To give some backstory, I have a GUI that is writing data to a text file named out1.txt.  I am reading data back in from this file and displaying anything with computesales >= 8,000 in a JtextArea as shown in the code below.

 private void evaluateButtonActionPerformed(java.awt.event.ActionEvent evt) {
    saleOutput.setText("");
    SaleReader reader = new SaleReader();

    try
    {
        List<Sales> sale = reader.readSale("out1.txt");
        for (Sales s : sale)
        {
            if(s.computeSales()>= 8000)
            {
            saleOutput.append(s.toString());
            saleOutput.append("\n");

            }
        }
    }catch (IOException ex) {
        JOptionPane.showMessageDialog(this, "Unable to open file");
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }

}

I have tried a variation of what I have below that writes to my out1.txt file, but it doesn't seem to work at all.  It won't even create the file.  My coworker seemed to think that it may be an issues with the filewriter not being flushed?

 public void writeSales(Sales s) throws IOException
{
    File testWriter = new File ("out1.txt");
    BufferedWriter out = new BufferedWriter(new FileWriter(testWriter, true));

    out.write("" + s.getSalesID());
    out.write(", ");
    out.write(s.getFirstName());
    out.write(", ");
    out.write(s.getLastName());
    out.write(", ");
    out.write("" + s.getOfficeSupplies());
    out.write(", ");
    out.write("" + s.getBooks());
    out.write(", ");
    out.write("" + s.getPaper());
    out.write(", ");
    out.write("" + s.getDistrictValue());
    out.write(", ");
    out.write("" + s.getPreferredContact());
    out.write(", ");
    out.write("" + s.computeSales());
    out.newLine();
    out.close();
}

Here is what I'm writing in a separate class to write to the new stars.txt file, but is not working.  Any suggestions?

public void writeStars(Sales f) throws IOException
{
    File testStars = new File ("stars.txt");
    BufferedWriter outStars = new BufferedWriter(new FileWriter(testStars, true));
    SaleReader reader = new SaleReader();

     try
    {
        List<Sales> sale = reader.readSale("out1.txt");
        for (Sales s : sale)
        {
            if(s.computeSales()>= 8000)
            {
            outStars.write("" + s.getDistrictValue());
            outStars.newLine();
            outStars.close();

            }
        }
    }catch (IOException ex) {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }
}

I'm calling it from here.

public class Sales
{
 private int salesID;
 private String firstName;
 private String lastName;
 private double officeSupplies;
 private double books;
 private double paper;
 private String districtValue;
 private String preferredContact;

public int getSalesID() {
    return salesID;
}

public void setSalesID(int salesID) {
    this.salesID = salesID;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public double getOfficeSupplies() {
    return officeSupplies;
}

public void setOfficeSupplies(double officeSupplies) {
    this.officeSupplies = officeSupplies;
}

public double getBooks() {
    return books;
}

public void setBooks(double books) {
    this.books = books;
}

public double getPaper() {
    return paper;
}

public void setPaper(double paper) {
    this.paper = paper;
}

public String getPreferredContact() {
    return preferredContact;
}

public void setPreferredContact(String preferredContact) {
    this.preferredContact = preferredContact;
}

public String getDistrictValue() {
    return districtValue;
}

public void setDistrictValue(String districtValue) {
    this.districtValue = districtValue;
}

@Override
public String toString() {
    return "Sales{" + "salesID=" + salesID + ", firstName=" + firstName + ", lastName=" + lastName + ", officeSupplies=" + officeSupplies + ", books=" + books + ", paper=" + paper + ", districtValue=" + districtValue + ", preferredContact=" + preferredContact + '}';
}

public double computeSales()
{
    return officeSupplies + books + paper;
}

}

Body:
If your class is called for example SalesWriter and you have this code in it

public void writeStars() throws IOException
{
    File testStars = new File ("stars.txt");
    BufferedWriter outStars = new BufferedWriter(new FileWriter(testStars, true));
    SaleReader reader = new SaleReader();

     try
    {
        List<Sales> sale = reader.readSale("out1.txt");
        for (Sales s : sale)
        {
            if(s.computeSales()>= 8000)
            {
            outStars.write(s);
            outStars.newLine();

            }
        }
        outStars.close();

    }catch (IOException ex) {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Then from your main code you can call it like

new SalesWriter ().writeStars ();

edit

See how I have removed the parameter to this method, as your are reading the file in this method anyway.


问:
How to exit a gw basic program at any time?
I am creating a game and i want that if the user hit F10 or any other function key then they the program should end.</p>

答:
This code snip exits a program when function key is pressed in Qbasic:</p>

```<code>DO
    DO
        ' read keyboard
        X$ = INKEY$
        IF LEN(X$) THEN
            EXIT DO
        END IF
    LOOP
    IF LEN(X$) = 2 THEN
        x = ASC(RIGHT$(X$, 1))
        ' exit program on F1 to F10
        IF x >= 59 AND x <= 68 THEN
            END
        END IF
    END IF
LOOP
</code>```

Body:
This code snip exits a program when function key is pressed in Qbasic:

DO
    DO
        ' read keyboard
        X$ = INKEY$
        IF LEN(X$) THEN
            EXIT DO
        END IF
    LOOP
    IF LEN(X$) = 2 THEN
        x = ASC(RIGHT$(X$, 1))
        ' exit program on F1 to F10
        IF x >= 59 AND x <= 68 THEN
            END
        END IF
    END IF
LOOP


问:
How to use fromString() with currentDate()
I'm trying to get current date from the system clock and change its format (i.e. to this format dd/MM/yyyy). After that I need to set QDateEdit using setDate(). My problem is that using fromString() with QDate::currentDate() returns an invalid date. This is the piece of code regarding this issue

```<code>QDate date = QDate::currentDate().fromString("dd/MM/yyyy");
qDebug() << date.toString(); // <-- returns empty string
StartDateEdit->setDate(date); // <-- adding invalid date shows 1-1-2000
</code>```

My system clock has this format M/d/yyyy in Windows 10. Any suggestions?

答:
QDate::currentDate() is a static function, this returns the current date, the object stores the date, not the format. If you want to display the form: "dd/MM/yyyy" you must use the setDisplayFormat function of QDateEdit.

```<code>QDate date = QDate::currentDate();
StartDateEdit->setDate(date);
StartDateEdit->setDisplayFormat("dd/MM/yyyy");
</code>```

Note:The fromString function converts a string to QDate indicating the format of the string.

Body:
I'm trying to get current date from the system clock and change its format (i.e. to this format dd/MM/yyyy). After that I need to set QDateEdit using setDate(). My problem is that using fromString() with QDate::currentDate() returns an invalid date. This is the piece of code regarding this issue

QDate date = QDate::currentDate().fromString("dd/MM/yyyy");
qDebug() << date.toString(); // <-- returns empty string
StartDateEdit->setDate(date); // <-- adding invalid date shows 1-1-2000

My system clock has this format M/d/yyyy in Windows 10. Any suggestions?

Body:
QDate::currentDate() is a static function, this returns the current date, the object stores the date, not the format. If you want to display the form: "dd/MM/yyyy" you must use the setDisplayFormat function of QDateEdit.

QDate date = QDate::currentDate();
StartDateEdit->setDate(date);
StartDateEdit->setDisplayFormat("dd/MM/yyyy");

Note:The fromString function converts a string to QDate indicating the format of the string.


答: If you can't set a fixed width, you can get rid of the float:left in the ul>li li selector setting it as float:none. It seems ok when I test in developer tools and I can't see the particular reason to have a float in that element. </p>

Title: Make li background color span whole ul width CSS


问:
The compiler is unhappy about my generics in Java
It always complains with:

```<code>The method add(Matrix<T>) in the type List<Matrix<T>> is not applicable for the arguments (Matrix<String>)
</code>```

In the line of the Extractor class:

```<code>matrixList.add(new Matrix<String>(attributes));
</code>```

It seems there is a problem in defining my generics in these 3 classes. Is there an easy way to fix that? Tried different ways and can't figure it out.

```<code>public class Test {

    public static void main(String[] args) {

        Extractor<String> extractor = new Extractor<>();
        extractor.extract();
    }
}

class Extractor<T> {

    private List<Matrix<T>> matrixList;

    public Extractor() {
        this.matrixList = new ArrayList<>();
    }

    public void extract() {
        List<Attribute<String>> attributes = new ArrayList<>();

        attributes.add(new Attribute<String>("Test 1"));
        attributes.add(new Attribute<String>("Test 2"));

       // !!!! The compiler is complaining here!
        matrixList.add(new Matrix<String>(attributes));
    }

    public List<Matrix<T>> getList() {
        return matrixList;
    }
}

class Matrix<T> {

    private List<Attribute<T>> attributes;

    public Matrix(List<Attribute<T>> attributes) {
        this.attributes = attributes;
    }

    public List<Attribute<T>> getAttributes() {
        return attributes;
    }
}

class Attribute<T> {
    private T attribute;
    public Attribute(T attr) {
        attribute = attr;
    }

    public T getAttr() {
        return attribute;
    }
}
</code>```

答:
A simple solution is to use matrixList.add((Matrix<T>) new Matrix<String>(attributes)); instead.

The code imposes a very common casting problem of generics.

The approach presented in the code matrixList.add(new Matrix<String>(attributes)) implies that you want to add a Matrix element to container matrixList which is defined to contain generic template type.

You may find simpler illustrations of such hurdles in the documentation over here

Body:
It always complains with:

The method add(Matrix<T>) in the type List<Matrix<T>> is not applicable for the arguments (Matrix<String>)

In the line of the Extractor class:

matrixList.add(new Matrix<String>(attributes));

It seems there is a problem in defining my generics in these 3 classes. Is there an easy way to fix that? Tried different ways and can't figure it out.

public class Test {

    public static void main(String[] args) {

        Extractor<String> extractor = new Extractor<>();
        extractor.extract();
    }
}

class Extractor<T> {

    private List<Matrix<T>> matrixList;

    public Extractor() {
        this.matrixList = new ArrayList<>();
    }

    public void extract() {
        List<Attribute<String>> attributes = new ArrayList<>();

        attributes.add(new Attribute<String>("Test 1"));
        attributes.add(new Attribute<String>("Test 2"));

       // !!!! The compiler is complaining here!
        matrixList.add(new Matrix<String>(attributes));
    }

    public List<Matrix<T>> getList() {
        return matrixList;
    }
}

class Matrix<T> {

    private List<Attribute<T>> attributes;

    public Matrix(List<Attribute<T>> attributes) {
        this.attributes = attributes;
    }

    public List<Attribute<T>> getAttributes() {
        return attributes;
    }
}

class Attribute<T> {
    private T attribute;
    public Attribute(T attr) {
        attribute = attr;
    }

    public T getAttr() {
        return attribute;
    }
}


问:
Access urandom device get "permission denied", why?
I can create a new urandom device on a some directory (test_urandom in below example), and it works as expected. E.g.

```<code>test_urandom$ sudo mknod -m 0444 ./urandom c 1 9
test_urandom$ ls -l
total 0
cr--r--r-- 1 root root 1, 9 Jun  9 09:06 urandom
test_urandom$ head -c 10 ./urandom
�׫O1�9�^
</code>```

However, if I create the same device node in another directory, which in my case is an ext4 filesystem on a LVM (Logical Volume Management), it failed and system complained with permission denied.

```<code>test_urandom_lvm$ sudo mknod -m 0444 ./urandom c 1 9
test_urandom_lvm$ ls -l
total 0
cr--r--r-- 1 root root 1, 9 Jun  9 09:06 urandom
test_urandom_lvm$ head -c 10 ./urandom
head: cannot open ‘./urandom’ for reading: Permission denied
</code>```

If I am allowed to create a device in the filesystem, why not allowed to read the device? What caused the permission denied? What changes is needed to make it work?

答: The filesystem is mounted with the nodev option, which inhibits block and character special device operation. Mounting it dev will allow them to work.

Body:
I can create a new urandom device on a some directory (test_urandom in below example), and it works as expected. E.g.

test_urandom$ sudo mknod -m 0444 ./urandom c 1 9
test_urandom$ ls -l
total 0
cr--r--r-- 1 root root 1, 9 Jun  9 09:06 urandom
test_urandom$ head -c 10 ./urandom
�׫O1�9�^

However, if I create the same device node in another directory, which in my case is an ext4 filesystem on a LVM (Logical Volume Management), it failed and system complained with permission denied.

test_urandom_lvm$ sudo mknod -m 0444 ./urandom c 1 9
test_urandom_lvm$ ls -l
total 0
cr--r--r-- 1 root root 1, 9 Jun  9 09:06 urandom
test_urandom_lvm$ head -c 10 ./urandom
head: cannot open ‘./urandom’ for reading: Permission denied

If I am allowed to create a device in the filesystem, why not allowed to read the device? What caused the permission denied? What changes is needed to make it work?


问:
Xcode 8 playground live view doesn't work
In my Swift playground, I entered the following code to test the live view feature:

```<code>let view = UIView()

PlaygroundPage.current.liveView = view
</code>```

But for some reason the live view doesn't display on the right in the Assistant Editor. Initially I thought that Xcode wasn't finished running the playground. But I waited and waited and it still doesn't show.

Screenshot:

Any help?

答:
I had the same issue as well and the following line of code fixed it for me:

```<code>PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

Setting a live view is supposed to auto-enable it for you, but for me it wasn't doing it. Must be a bug in Xcode.

Body:
In my Swift playground, I entered the following code to test the live view feature:

let view = UIView()

PlaygroundPage.current.liveView = view

But for some reason the live view doesn't display on the right in the Assistant Editor. Initially I thought that Xcode wasn't finished running the playground. But I waited and waited and it still doesn't show.

Screenshot:

Any help?

Body:
I had the same issue as well and the following line of code fixed it for me:

PlaygroundPage.current.needsIndefiniteExecution = true

Setting a live view is supposed to auto-enable it for you, but for me it wasn't doing it. Must be a bug in Xcode.


问:
No 'Access-Control-Allow-Origin' Angular 4 app
I am trying to access this address:
http://52.208.91.209:3000/?paging=1

Accessing manually works fine.
Accessing via an Angular 4 request returns:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I have googled it for a few hours and did not find a solution.

The only "solution" I have found is using Allow-Control-Allow-Origin plugin.

The address I am trying to access is not mine.

I am just trying to work with it.

I have even read about proxies when using ng serve with angular CLI but didnt fully understand.

All of the solutions I saw are simply a response headers problem on the server side. However, This is NOT my server so I cannot configure it.

Any help would be appreciated. Thank you.

答:
You can't access that API the way you want to from the browser. There are security measures in place to prevent this from happening. If you do not control the source of the data, you cannot do anything to fix this. Your only option is to have your own server request the data, and you then go through your server to get the data.

Edit: You actually can do this if you only plan to run it locally. Chrome has flags to ignore this security measure. If you don't plan on using this on any machine other than your own, you can force chrome to allow this locally.


问:
Make TypeScript produce prototypes for ES6
Is it possible within the latest TypeScript to make specific class methods to be prototypes, even though the general target is ES6?

And as a side question - to have a specific class produce prototypes only.

Example of a TypeScript class:

```<code>class Test {
    constructor() {
    }

    methodName() {
    }
}
</code>```

For ES6 as the general target it produces the same JavaScript code, while I want it to be:

```<code>class Test {
    constructor() {
    }
}

Test.prototype.methodName = function () {
}
</code>```

i.e. either for a specific method or for all methods within the class I want to get prototypes instead, despite using ES6 as the general target.

The main reason for asking is as follows. I have a module that needs to create a very large number of such class instances, and after reading many posts here it seems the consensus is that prototypes will perform better in such a case:

Javascript prototype operator performance

Defining methods via prototype vs using this in the constructor

P.S. I'm mostly interested in the server-side of things, i.e. Node.js 4-8.

答:
There isn't a way to do this (source: I work on the TypeScript team).

Perhaps there's a follow-up question for why you would want to do this. AFAIK these two outcomes are almost indistinguishable behaviorally.

Body:
Is it possible within the latest TypeScript to make specific class methods to be prototypes, even though the general target is ES6?

And as a side question - to have a specific class produce prototypes only.

Example of a TypeScript class:

class Test {
    constructor() {
    }

    methodName() {
    }
}

For ES6 as the general target it produces the same JavaScript code, while I want it to be:

class Test {
    constructor() {
    }
}

Test.prototype.methodName = function () {
}

i.e. either for a specific method or for all methods within the class I want to get prototypes instead, despite using ES6 as the general target.

The main reason for asking is as follows. I have a module that needs to create a very large number of such class instances, and after reading many posts here it seems the consensus is that prototypes will perform better in such a case:

Javascript prototype operator performance

Defining methods via prototype vs using this in the constructor

P.S. I'm mostly interested in the server-side of things, i.e. Node.js 4-8.


问:
NuGet.targets" cannot be imported again. It was already imported warning
I am getting this warning in Visual Studio 2013 for some of my projects:

```<code>NuGet.targets" cannot be imported again. It was already imported
</code>```

My Main WCF project in the solution file has this:

```<code>Project("{FAE04EC0-301F-11D3-BF4B-01C04F79EFBC}") = "WCF.Project", "Website\WCF.Project.csproj", "{AEFE3DD8-6E77-4449-9632-E2F0BADB6EBC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{778ACFB4-FB04-4E26-93DD-260E7B406E48}"
    ProjectSection(SolutionItems) = preProject
        .nuget\NuGet.Config = .nuget\NuGet.Config
        .nuget\NuGet.exe = .nuget\NuGet.exe
        .nuget\NuGet.targets = .nuget\NuGet.targets
    EndProjectSection
EndProject
</code>```

In my WCF project file it has:

```<code><Import Project="$(SolutionDir).nuget\NuGet.targets" Condition="Exists('$(SolutionDir).nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir).nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir).nuget\NuGet.targets'))" />
  </Target>
  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</code>```

Now that I look at it.. it looks like there is double in the for some reason?

答:
Despite this is an old question I got to it having exactly same error after migrating VS2015 solution to VS2017.
Cleaning the NuGet cache solved this issue (see the picture).

HTH!

Edit: Problem re-appeared when building multiple projects. So, maybe a better approach is to move all sources to a new project with (possibly!) the same name, or at least same namespace/assembly name. Comparing converted/generated VS2015 and VS2017 .csproj files revealed a much more concise project structure in VS2017 even after downloading missing NuGets, not sure if it is worth editing each and every .csproj instead of replacing it with a newly generated one.

Body:
I am getting this warning in Visual Studio 2013 for some of my projects:

NuGet.targets" cannot be imported again. It was already imported

My Main WCF project in the solution file has this:

Project("{FAE04EC0-301F-11D3-BF4B-01C04F79EFBC}") = "WCF.Project", "Website\WCF.Project.csproj", "{AEFE3DD8-6E77-4449-9632-E2F0BADB6EBC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{778ACFB4-FB04-4E26-93DD-260E7B406E48}"
    ProjectSection(SolutionItems) = preProject
        .nuget\NuGet.Config = .nuget\NuGet.Config
        .nuget\NuGet.exe = .nuget\NuGet.exe
        .nuget\NuGet.targets = .nuget\NuGet.targets
    EndProjectSection
EndProject

In my WCF project file it has:

<Import Project="$(SolutionDir).nuget\NuGet.targets" Condition="Exists('$(SolutionDir).nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir).nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir).nuget\NuGet.targets'))" />
  </Target>
  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />

Now that I look at it.. it looks like there is double in the for some reason?


问:
Object Oriented questions in Javascript
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

```<code>function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

```<code>function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

```<code>var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());
</code>```

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

```<code>var user = new User("Bob", 44);
</code>```

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

答: You seem to have some good answers here but you might like to look at this question: best-approach-to-member-variables-in-object-oriented-javascript. This was my answer which describes the differences and similaries. </p>

OwnerDisplayName: BrianH

ContentLicense: CC BY-SA 2.5

Title: Object Oriented questions in Javascript

Body:
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

var user = new User("Bob", 44);

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

LastEditorDisplayName: BrianH

OwnerDisplayName: meouw


问:
Is it possible to run CUDA on AMD GPUs?
I'd like to extend my skill set into GPU computing. I am familiar with raytracing and realtime graphics(OpenGL), but the next generation of graphics and high performance computing seems to be in GPU computing or something like it.

I currently use an AMD HD 7870 graphics card on my home computer. Could I write CUDA code for this? (my intuition is no, but since Nvidia released the compiler binaries I might be wrong).

A second more general question is, Where do I start with GPU computing? I'm certain this is an often asked question, but the best I saw was from 08' and I figure the field has changed quite a bit since then.

答:
You can run NVIDIA® CUDA™ code on Mac, and indeed on OpenCL 1.2 GPUs in general, using Coriander . Disclosure: I'm the author.  Example usage:

```<code>cocl cuda_sample.cu
./cuda_sample
</code>```

Result:

Title: Is it possible to run CUDA on AMD GPUs?

Body:
You can run NVIDIA® CUDA™ code on Mac, and indeed on OpenCL 1.2 GPUs in general, using Coriander . Disclosure: I'm the author.  Example usage:

cocl cuda_sample.cu
./cuda_sample

Result:


问:
Unable to run my first wordcount example in mapreduce
Can anyone help me solve my this problem?

I am beginner to hadoop.

The steps I followed to run my program:

```<code>export JAVA_HOME=/usr/lib/jvm/java-8-oracle
export PATH=${JAVA_HOME}/bin:${PATH}
export HADOOP_CLASSPATH=${JAVA_HOME}/lib/tools.jar
bin/hadoop com.sun.tools.javac.Main WordCount.java
sudo jar cf wc.jar WordCount*.class
bin/hadoop jar wc.jar WordCount myfileName outputFile
</code>```

This is what I got when I try to run my program

```<code>abbas@abbas:~/hadoop-2.7.3$ export JAVA_HOME=/usr/lib/jvm/java-8-oracle
abbas@abbas:~/hadoop-2.7.3$ export PATH=${JAVA_HOME}/bin:${PATH}
abbas@abbas:~/hadoop-2.7.3$ export HADOOP_CLASSPATH=${JAVA_HOME}/lib/tools.jar
abbas@abbas:~/hadoop-2.7.3$ bin/hadoop com.sun.tools.javac.Main WordCount.java
abbas@abbas:~/hadoop-2.7.3$ sudo jar cf wc.jar WordCount*.class
abbas@abbas:~/hadoop-2.7.3$ bin/hadoop jar wc.jar WordCount tempfile output8

17/06/09 02:20:24 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
17/06/09 02:20:25 WARN mapreduce.JobResourceUploader: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
17/06/09 02:20:26 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/abbas/.staging/job_1496953867826_0001

Exception in thread "main" org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://localhost:9000/user/abbas/tempfile
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:323)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:265)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:387)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:301)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:318)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:196)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1290)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1287)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1698)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1308)
    at WordCount.main(WordCount.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
</code>```

答:
Self explanatory.

Input path does not exist: hdfs://localhost:9000/user/abbas/tempfile

Do you have an hdfs user directory?

```<code>hdfs dfs -ls /user | grep $(whoami)
</code>```

Did you put any file named tempfile there?

```<code>hdfs dfs -mkdir -p "/user/$(whoami)"
hdfs dfs -copyFromLocal /path/to/tempfile "/user/$(whoami)"
</code>```

It's worth pointing out that the example assumes you have files in HDFS already

Body:
Can anyone help me solve my this problem?

I am beginner to hadoop.

The steps I followed to run my program:

export JAVA_HOME=/usr/lib/jvm/java-8-oracle
export PATH=${JAVA_HOME}/bin:${PATH}
export HADOOP_CLASSPATH=${JAVA_HOME}/lib/tools.jar
bin/hadoop com.sun.tools.javac.Main WordCount.java
sudo jar cf wc.jar WordCount*.class
bin/hadoop jar wc.jar WordCount myfileName outputFile

This is what I got when I try to run my program

abbas@abbas:~/hadoop-2.7.3$ export JAVA_HOME=/usr/lib/jvm/java-8-oracle
abbas@abbas:~/hadoop-2.7.3$ export PATH=${JAVA_HOME}/bin:${PATH}
abbas@abbas:~/hadoop-2.7.3$ export HADOOP_CLASSPATH=${JAVA_HOME}/lib/tools.jar
abbas@abbas:~/hadoop-2.7.3$ bin/hadoop com.sun.tools.javac.Main WordCount.java
abbas@abbas:~/hadoop-2.7.3$ sudo jar cf wc.jar WordCount*.class
abbas@abbas:~/hadoop-2.7.3$ bin/hadoop jar wc.jar WordCount tempfile output8

17/06/09 02:20:24 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
17/06/09 02:20:25 WARN mapreduce.JobResourceUploader: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
17/06/09 02:20:26 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/abbas/.staging/job_1496953867826_0001

Exception in thread "main" org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://localhost:9000/user/abbas/tempfile
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:323)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:265)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:387)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:301)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:318)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:196)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1290)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1287)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1698)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1308)
    at WordCount.main(WordCount.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

Body:
Self explanatory.

Input path does not exist: hdfs://localhost:9000/user/abbas/tempfile

Do you have an hdfs user directory?

hdfs dfs -ls /user | grep $(whoami)

Did you put any file named tempfile there?

hdfs dfs -mkdir -p "/user/$(whoami)"
hdfs dfs -copyFromLocal /path/to/tempfile "/user/$(whoami)"

It's worth pointing out that the example assumes you have files in HDFS already


问:
Error while defining a variable as time.time()
I am making a code to change a variable using "random" functions in each iteration, constantly checking if the variable equals a specific, predefined value. When equal, the code stops, recording the amount of time needed to reach the value. The code worked fine and as expected until I introduced my method of timing, using time.time().

Why do I get an error claiming that my syntax in the line "start = time.time()" is invalid (line 5)?

I have tested the same setup in other codes and it works perfectly. How can I fix the problem?

Thanks in advance.

```<code>import random
import time
VARIABLE = int(random.randint(1, 16))
function = int(0)
start = time.time()
while True:
  function = int(random.randint(1,16))
  if not VARIABLE == int("0"):
    if function == int("1"):
      VARIABLE = int(VARIABLE) + int(random.randint(1,1000))
    if function == int("2"):
      VARIABLE = int(VARIABLE) - int(random.randint(1,1000))
    if function == int("3"):
      VARIABLE = int(VARIABLE) * int(random.randint(1,1000))
    if function == int("4"):
      VARIABLE = int(VARIABLE) / int(random.randint(1,1000))
    if function == int("5"):
      VARIABLE = int(random.randint(1,1000)) / int(VARIABLE)
    if function == int("6"):
      VARIABLE = int(VARIABLE) + int(random.randint(1,1000))
    if function == int("7"):
      VARIABLE = int(random.randint(1,1000)) - int(VARIABLE)
    if function == int("8"):
      VARIABLE = int(VARIABLE) ^ int(random.randint(1,1000))
    if function == int("9"):
      VARIABLE = int(random.randint(1,1000)) ^ int(VARIABLE)
    if function == int("10"):
      VARIABLE = (int(VARIABLE) * int(random.randint(1,1000)))^2
    if function == int("11"):
      VARIABLE = (int(VARIABLE) + int(random.randint(1,1000)))^2
    if function == int("12"):
      VARIABLE = (int(VARIABLE) - int(random.randint(1,1000)))^2
    if function == int("13"):
      VARIABLE = (int(VARIABLE) / int(random.randint(1,1000)))^2
    if function == int("14"):
      VARIABLE = (int(random.randint(1,1000))/int(VARIABLE))^2
    if function == int("15"):
      VARIABLE = (int(random.randint(1,1000)) - int(VARIABLE))^2
    if function == int("16"):
      VARIABLE = (int(VARIABLE) ^ int(random.randint(1,1000)))^2
    if function == int("16"):
      VARIABLE = (int(random.randint(1,1000))^int(VARIABLE))^2
  print int(VARIABLE)
  time.sleep(.75)
  if VARIABLE == int("42"):
    end = time.time()
    print("Task completed.")
    break
print("This time, we completed the task in "+(end-start)+ "seconds.")
</code>```

答: While the time.time() portion of the code works for me, on line 24 you can't use ^ to denote an exponent. In python you use **. As Nick pointed out below, ^ is the bitwise exclusive or operator in python.

Body:
I am making a code to change a variable using "random" functions in each iteration, constantly checking if the variable equals a specific, predefined value. When equal, the code stops, recording the amount of time needed to reach the value. The code worked fine and as expected until I introduced my method of timing, using time.time().

Why do I get an error claiming that my syntax in the line "start = time.time()" is invalid (line 5)?

I have tested the same setup in other codes and it works perfectly. How can I fix the problem?

Thanks in advance.

import random
import time
VARIABLE = int(random.randint(1, 16))
function = int(0)
start = time.time()
while True:
  function = int(random.randint(1,16))
  if not VARIABLE == int("0"):
    if function == int("1"):
      VARIABLE = int(VARIABLE) + int(random.randint(1,1000))
    if function == int("2"):
      VARIABLE = int(VARIABLE) - int(random.randint(1,1000))
    if function == int("3"):
      VARIABLE = int(VARIABLE) * int(random.randint(1,1000))
    if function == int("4"):
      VARIABLE = int(VARIABLE) / int(random.randint(1,1000))
    if function == int("5"):
      VARIABLE = int(random.randint(1,1000)) / int(VARIABLE)
    if function == int("6"):
      VARIABLE = int(VARIABLE) + int(random.randint(1,1000))
    if function == int("7"):
      VARIABLE = int(random.randint(1,1000)) - int(VARIABLE)
    if function == int("8"):
      VARIABLE = int(VARIABLE) ^ int(random.randint(1,1000))
    if function == int("9"):
      VARIABLE = int(random.randint(1,1000)) ^ int(VARIABLE)
    if function == int("10"):
      VARIABLE = (int(VARIABLE) * int(random.randint(1,1000)))^2
    if function == int("11"):
      VARIABLE = (int(VARIABLE) + int(random.randint(1,1000)))^2
    if function == int("12"):
      VARIABLE = (int(VARIABLE) - int(random.randint(1,1000)))^2
    if function == int("13"):
      VARIABLE = (int(VARIABLE) / int(random.randint(1,1000)))^2
    if function == int("14"):
      VARIABLE = (int(random.randint(1,1000))/int(VARIABLE))^2
    if function == int("15"):
      VARIABLE = (int(random.randint(1,1000)) - int(VARIABLE))^2
    if function == int("16"):
      VARIABLE = (int(VARIABLE) ^ int(random.randint(1,1000)))^2
    if function == int("16"):
      VARIABLE = (int(random.randint(1,1000))^int(VARIABLE))^2
  print int(VARIABLE)
  time.sleep(.75)
  if VARIABLE == int("42"):
    end = time.time()
    print("Task completed.")
    break
print("This time, we completed the task in "+(end-start)+ "seconds.")