问:
Display success message after downloading CSV
I have developed a small Wordpress Plugin to download as a CSV file users' data from the database.

Everything works fine, although I am having issues figuring out how to display a success message.

Below the code of the method that takes care of the data export:

```<code>/*
* Export CSV File
*/
public function export_CSV()
{

    if ($this->users) {

        $fileName =  "Export_users_" . date("Y-m-d_H:i:s", time());
        $fileName = $fileName.".csv";
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header('Content-Encoding: UTF-8');
        header("Content-type: application/csv;charset=UTF-8");
        header("Content-Disposition: attachment; filename={$fileName}");
        header("Expires: 0");
        header("Pragma: public");
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
        $fh = @fopen( 'php://output', 'w' );
        $headerDisplayed = false;

        foreach ($this->users as $user) {

            if($user) {

                $user_meta = get_user_meta($user->data->ID);

                //Push user meta into $user array

                foreach($user_meta as $key => $var)
                {
                    $user->data->$key = trim($var[0]);
                }

                //convert object in array;

                $usersArray = (array)$user->data;

                // Add a header row if it hasn't been added yet

                if ( $headerDisplayed == false ) {

                    // Use the keys from $directory as the titles

                    fputcsv($fh, array_keys($usersArray));

                    $headerDisplayed = true;
                }

                // Put the data into the stream

                fputcsv($fh,$usersArray);

            }//end if

        }//end foreach

        // Close the file

        fclose($fh);

        // Users exported successfully

        $this->response = "Users exported successfully!";

        // Make sure nothing else is sent

        exit;

    } else {

        // No results found

        $this->response = "Sorry, no results found!";

    }

}
</code>```

I have to use exit otherwise the CSV file will contain all the html of the page. Is there a way to run a javascript file to update the message in the front end?

Thanks in advance!

答:
First of all:

Put the download details in a separate page. You can only send the headers once, that's one of the reasons why you can't print html after sending the csv header.

Secondly you could then create an if/else statement for if the function has succeeded. and if it did you could add some JS code like the example below:

```<code>if($download = true) {
   echo "<script> alert('Download succesfull!'); </script>";
}
else {
   echo "<script> alert('Download failed!'); </script>";
}
</code>```

Tho i'm not sure if it could work like above since it's an server event. Another possible solution would be by creating a ServerEventCheck.

Body:
I have developed a small Wordpress Plugin to download as a CSV file users' data from the database.

Everything works fine, although I am having issues figuring out how to display a success message.

Below the code of the method that takes care of the data export:

/*
* Export CSV File
*/
public function export_CSV()
{

    if ($this->users) {

        $fileName =  "Export_users_" . date("Y-m-d_H:i:s", time());
        $fileName = $fileName.".csv";
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header('Content-Encoding: UTF-8');
        header("Content-type: application/csv;charset=UTF-8");
        header("Content-Disposition: attachment; filename={$fileName}");
        header("Expires: 0");
        header("Pragma: public");
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
        $fh = @fopen( 'php://output', 'w' );
        $headerDisplayed = false;

        foreach ($this->users as $user) {

            if($user) {

                $user_meta = get_user_meta($user->data->ID);

                //Push user meta into $user array

                foreach($user_meta as $key => $var)
                {
                    $user->data->$key = trim($var[0]);
                }

                //convert object in array;

                $usersArray = (array)$user->data;

                // Add a header row if it hasn't been added yet

                if ( $headerDisplayed == false ) {

                    // Use the keys from $directory as the titles

                    fputcsv($fh, array_keys($usersArray));

                    $headerDisplayed = true;
                }

                // Put the data into the stream

                fputcsv($fh,$usersArray);

            }//end if

        }//end foreach

        // Close the file

        fclose($fh);

        // Users exported successfully

        $this->response = "Users exported successfully!";

        // Make sure nothing else is sent

        exit;

    } else {

        // No results found

        $this->response = "Sorry, no results found!";

    }

}

I have to use exit otherwise the CSV file will contain all the html of the page. Is there a way to run a javascript file to update the message in the front end?

Thanks in advance!

Body:
First of all:

Put the download details in a separate page. You can only send the headers once, that's one of the reasons why you can't print html after sending the csv header.

Secondly you could then create an if/else statement for if the function has succeeded. and if it did you could add some JS code like the example below:

if($download = true) {
   echo "<script> alert('Download succesfull!'); </script>";
}
else {
   echo "<script> alert('Download failed!'); </script>";
}

Tho i'm not sure if it could work like above since it's an server event. Another possible solution would be by creating a ServerEventCheck.


来源: stackexchange

问:
Can't open an image in WPF app
In my application I want to display some pictures (I need to have them stored in a list). I have problem with opening them. Firstly, I made a directory Images (using VS). Next I loaded pictures to this folder (also in VS).
I wanted to open one of them like here:
http://msdn.microsoft.com/en-us/library/aa970062.aspx

```<code>Stream imageStreamSource = new FileStream("Images\bulbOff.png", FileMode.Open, FileAccess.Read, FileShare.Read);
PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
</code>```

And then while trying to run the program, I got:

```<code>XamlParseException
</code>```

with hardly any information.
For sure the first line is causing the problem, because the problem disappears only when I delete it.

I tried to do it also like:

```<code>Uri myUri = new Uri("Images\bulbOff.png", UriKind.RelativeOrAbsolute);
PngBitmapDecoder decoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource2 = decoder2.Frames[0];
</code>```

with the same result.
I also tried to copy the image to main folder of app (in SolutionView). When I tried to get "\bulbOff.png" the result was the same.
When I tried to get "bulbOff.png" I got

```<code>XamlParseException
</code>```

again, but with some info - there were hints that path could be wrong.

答: Try to change your image and code to a jpg extension. Seriously.</p>

ContentLicense: CC BY-SA 2.5

Title: Can't open an image in WPF app

Body:
In my application I want to display some pictures (I need to have them stored in a list). I have problem with opening them. Firstly, I made a directory Images (using VS). Next I loaded pictures to this folder (also in VS).
I wanted to open one of them like here:
http://msdn.microsoft.com/en-us/library/aa970062.aspx

Stream imageStreamSource = new FileStream("Images\bulbOff.png", FileMode.Open, FileAccess.Read, FileShare.Read);
PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];

And then while trying to run the program, I got:

XamlParseException

with hardly any information.
For sure the first line is causing the problem, because the problem disappears only when I delete it.

I tried to do it also like:

Uri myUri = new Uri("Images\bulbOff.png", UriKind.RelativeOrAbsolute);
PngBitmapDecoder decoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource2 = decoder2.Frames[0];

with the same result.
I also tried to copy the image to main folder of app (in SolutionView). When I tried to get "\bulbOff.png" the result was the same.
When I tried to get "bulbOff.png" I got

XamlParseException

again, but with some info - there were hints that path could be wrong.


问:
Android app with Push Notifications and Background Process are killed in some cases
We have an Android app that gets Push Notifications via FCM and Background Service that is working even when the app is not active.
We are experiencing some issues with Android Operating System killing the background service and in other cases automatically closing the Notifications for our app. ( By automatically turning off Notifications for our app ).

Our first suspect was Doze mode introduced in Android 6 and later but we are using AlarmManager  with setAndAllowWhileIdle() for scheduling the process and this should be enough for firing even during the doze mode as documented here.
In addition we found out that in certain devices like Xiaomi and Huawei devices there is a known issue of Push Notifications not working and background services not running and we handle it.
But the issue still remains in different device types and Android Versions.

Any ideas for the reason this can happen? Thanks!

答:
The System sometimes kills the service when the memory is low.

In your background Service, override onStartCommand() and return START_STICKY as the result.

It will tell the system that even if it will want to kill your service due to low memory, it should re-create it as soon as memory will be back to normal.

ContentLicense: CC BY-SA 3.0


问:
Redux - Define new state in reducer switch statement with new variable each time?
My reducer looks like this:

```<code>switch (action.type) {
      case "UPDATE_CURRENT_USER":
        let newState = {...state, ...action.payload };
        return newState;
      case "GET_CURRENT_USER":
        return state;
      case "UPDATE_USERNAME":
        newState = {...state, name: action.payload.name};
        return state;
  }
</code>```

Now, the second time I am using newState I am not defining it again. I am simply using the variable I have defined above. Is this ok?
I wanted to define it anew, but got an error. But I am not sure whether this way will still give me the correct result - although everything seems to be working fine?

答:
You do not need to create a variable for new state, assign a value to it and return it. Instead, you can return the new state value right away. And also do not forget to add a default case at the end.</p>

```<code>switch (action.type) {
        case 'UPDATE_CURRENT_USER':
          return { ...state, ...action.payload };
        case 'GET_CURRENT_USER':
          return state;
        case 'UPDATE_USERNAME':
          return { ...state, name: action.payload.name };
        default:
          return state;
      }
</code>```

Body:
My reducer looks like this:

switch (action.type) {
      case "UPDATE_CURRENT_USER":
        let newState = {...state, ...action.payload };
        return newState;
      case "GET_CURRENT_USER":
        return state;
      case "UPDATE_USERNAME":
        newState = {...state, name: action.payload.name};
        return state;
  }

Now, the second time I am using newState I am not defining it again. I am simply using the variable I have defined above. Is this ok?
I wanted to define it anew, but got an error. But I am not sure whether this way will still give me the correct result - although everything seems to be working fine?

Body:
You do not need to create a variable for new state, assign a value to it and return it. Instead, you can return the new state value right away. And also do not forget to add a default case at the end.

switch (action.type) {
        case 'UPDATE_CURRENT_USER':
          return { ...state, ...action.payload };
        case 'GET_CURRENT_USER':
          return state;
        case 'UPDATE_USERNAME':
          return { ...state, name: action.payload.name };
        default:
          return state;
      }


问:
DASK Dataframe within loops
I'm having some trouble trying to implement loops in Dask.
for example in the following code:

```<code>for i in range(len(col)):
    if df[col[i]].dtype=='object':
        pass
    elif df[col[i]].std().compute()==0:
        cols_constant.append(col[i])
df = df.drop(cols_constant,axis=1)
</code>```

The same code is very quick using pandas but on dask it is taking a considerable amount of time to complete the task.

I understand Dask is inefficient over loops.
But how can I optimize my code for Dask for functions similar to the one above?

I cannot use e.persist() since we intend to do the computation on multiple worker systems.

Will it be useful to use the function 'dask.do' to parallelize the same task?

答:
Every time you call df.column.std.compute() you incur both the costs of calling std() but also the costs of creating df.  If you created df from a pandas dataframe then this is cheap, but if you created df from some more expensive process, like reading in from CSV files, then this can be very expensive.

```<code>df = dd.from_pandas()  # ok to call compute many times, data is already in memory
df = dd.read_csv(...)  # slow to call compute many times, we read the all the csv files every time you call compute
</code>```

If you have the memory then you can avoid this repeated cost by calling persist

```<code>df = df.persist()
</code>```

In your question you say that you can't use persist because you plan to do this on multi-worker systems.  To be clear, if you have the available memory, persist works in all cases both single-worker and multi-worker.

You can also avoid repeated calls to compute by just calling compute once.

```<code>stds = [df[column].std() for column in df.columns]
stds = dask.compute(stds)
</code>```

This computes everything in a single pass

Title: DASK Dataframe within loops

Body:
I'm having some trouble trying to implement loops in Dask.
for example in the following code:

for i in range(len(col)):
    if df[col[i]].dtype=='object':
        pass
    elif df[col[i]].std().compute()==0:
        cols_constant.append(col[i])
df = df.drop(cols_constant,axis=1)

The same code is very quick using pandas but on dask it is taking a considerable amount of time to complete the task.

I understand Dask is inefficient over loops.
But how can I optimize my code for Dask for functions similar to the one above?

I cannot use e.persist() since we intend to do the computation on multiple worker systems.

Will it be useful to use the function 'dask.do' to parallelize the same task?

Body:
Every time you call df.column.std.compute() you incur both the costs of calling std() but also the costs of creating df.  If you created df from a pandas dataframe then this is cheap, but if you created df from some more expensive process, like reading in from CSV files, then this can be very expensive.

df = dd.from_pandas()  # ok to call compute many times, data is already in memory
df = dd.read_csv(...)  # slow to call compute many times, we read the all the csv files every time you call compute

If you have the memory then you can avoid this repeated cost by calling persist

df = df.persist()

In your question you say that you can't use persist because you plan to do this on multi-worker systems.  To be clear, if you have the available memory, persist works in all cases both single-worker and multi-worker.

You can also avoid repeated calls to compute by just calling compute once.

stds = [df[column].std() for column in df.columns]
stds = dask.compute(stds)

This computes everything in a single pass


问:
"The process can not access the file '...' because it is being used by another process" when recreating temporary file for upload with FtpWebRequest
I am uploading a file on FTP. At first it works fine, but as soon as I click the upload button second time it throws an error

The process can not access the file '...' because it is being used by another process

The code is below

```<code>using (StreamWriter sw = new StreamWriter(filename, false)) //THIS LINE THROWS ERROR
{
    if (dt.Rows.Count > 0)
    {
        sw.Write("Column1,Column2");
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            sw.Write(dr["Column1"].ToString());
            sw.Write(",");
            sw.Write(dr["Column2"].ToString());
            sw.Write(",");
        }
        sw.Close();
        sw.Dispose();
    }
    else
    {
        sw.Close();
        sw.Dispose();
    }
}
</code>```

I am saving file in csv, can anyone please help me!! Why i am getting this error in second time?

Following is the code to upload on FTP

```<code>public void UploadToFTP()
{
     string fileName = "ReportName";
     string propfilename = Server.MapPath("~") + fileName + ".csv";

     string FtpUserid = null;
     string FtpPwd = null;
     string sourcePath = string.Empty;
     string destPath = string.Empty;
     string fName = string.Empty;
     FtpUserid = "abc";
     FtpPwd = "abc";

     fName = fileName + ".csv";

     destPath = ConfigurationManager.AppSettings["destipath"].ToString();
     destPath = destPath.Insert(destPath.LastIndexOf("/") + 1, fName);

     FtpWebRequest requestFileExists = (FtpWebRequest)WebRequest.Create(destPath);

     //GET DATA IN CSV
     UploadFTPCode(FtpUserid, FtpPwd, sourcePath, destPath, false);
 }

private void UploadFTPCode(string FtpUserid, string FtpPwd, string sourcePath, string destPath)
{
     FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destPath);
     request.Method = WebRequestMethods.Ftp.UploadFile;
     request.Credentials = new NetworkCredential(FtpUserid, FtpPwd);
     request.Proxy = null;
     request.UseBinary = false;
     request.UsePassive = true;
     request.KeepAlive = false;
     request.Timeout = 500000;

     // Copy the contents of the file to the request stream.
     StreamReader sourceStream = new StreamReader(sourcePath);
     byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
     sourceStream.Dispose();
     sourceStream.Close();
     request.ContentLength = fileContents.Length;

     Stream requestStream = request.GetRequestStream();
     requestStream.Write(fileContents, 0, fileContents.Length);
     requestStream.Flush();
     requestStream.Close();
     requestStream.Dispose();
     sourceStream.Close();
 }
</code>```

答:
Try calling garbage collection after you dispose the file like this:</p>

```<code>GC.Collect();
</code>```

Body:
I am uploading a file on FTP. At first it works fine, but as soon as I click the upload button second time it throws an error

The process can not access the file '...' because it is being used by another process

The code is below

using (StreamWriter sw = new StreamWriter(filename, false)) //THIS LINE THROWS ERROR
{
    if (dt.Rows.Count > 0)
    {
        sw.Write("Column1,Column2");
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            sw.Write(dr["Column1"].ToString());
            sw.Write(",");
            sw.Write(dr["Column2"].ToString());
            sw.Write(",");
        }
        sw.Close();
        sw.Dispose();
    }
    else
    {
        sw.Close();
        sw.Dispose();
    }
}

I am saving file in csv, can anyone please help me!! Why i am getting this error in second time?

Following is the code to upload on FTP

public void UploadToFTP()
{
     string fileName = "ReportName";
     string propfilename = Server.MapPath("~") + fileName + ".csv";

     string FtpUserid = null;
     string FtpPwd = null;
     string sourcePath = string.Empty;
     string destPath = string.Empty;
     string fName = string.Empty;
     FtpUserid = "abc";
     FtpPwd = "abc";

     fName = fileName + ".csv";

     destPath = ConfigurationManager.AppSettings["destipath"].ToString();
     destPath = destPath.Insert(destPath.LastIndexOf("/") + 1, fName);

     FtpWebRequest requestFileExists = (FtpWebRequest)WebRequest.Create(destPath);

     //GET DATA IN CSV
     UploadFTPCode(FtpUserid, FtpPwd, sourcePath, destPath, false);
 }

private void UploadFTPCode(string FtpUserid, string FtpPwd, string sourcePath, string destPath)
{
     FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destPath);
     request.Method = WebRequestMethods.Ftp.UploadFile;
     request.Credentials = new NetworkCredential(FtpUserid, FtpPwd);
     request.Proxy = null;
     request.UseBinary = false;
     request.UsePassive = true;
     request.KeepAlive = false;
     request.Timeout = 500000;

     // Copy the contents of the file to the request stream.
     StreamReader sourceStream = new StreamReader(sourcePath);
     byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
     sourceStream.Dispose();
     sourceStream.Close();
     request.ContentLength = fileContents.Length;

     Stream requestStream = request.GetRequestStream();
     requestStream.Write(fileContents, 0, fileContents.Length);
     requestStream.Flush();
     requestStream.Close();
     requestStream.Dispose();
     sourceStream.Close();
 }

Body:
Try calling garbage collection after you dispose the file like this:

GC.Collect();


问:
How to create a custom checkbox in css

I want to create a checkbox like this. with a white tick and transparent background. Can someone help me on how to do it
I tried
 input[type="checkbox"]{
background-color:rgba(255,255,255,0.1);
color:white;
}

But doesnt work as in this
codepen

答:
you can use below css to get the same

working fiddle

input[type="checkbox"].hidden {
  display: none;
}

.demoCheck {
  border: 1px solid #ddd;
  width: 25px;
  height: 25px;
  display: block;
}

input[type="checkbox"]:checked.hidden + label {
  background: url(http://www.clipartsfree.net/vector/small/23493485345_Clipart_Free.png) center center no-repeat;
  background-size:cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" class="hidden" id="demo" >
<label for="demo" class="demoCheck demoCheckLabel"></label></code>```

Title: How to create a custom checkbox in css

Body:
you can use below css to get the same

working fiddle

input[type="checkbox"].hidden {
  display: none;
}

.demoCheck {
  border: 1px solid #ddd;
  width: 25px;
  height: 25px;
  display: block;
}

input[type="checkbox"]:checked.hidden + label {
  background: url(http://www.clipartsfree.net/vector/small/23493485345_Clipart_Free.png) center center no-repeat;
  background-size:cover;
}

<input type="checkbox" class="hidden" id="demo" >
<label for="demo" class="demoCheck demoCheckLabel"></label>


问:
Unit testing async method for specific exception
Does anyone have an example of how to unit test an async method in a Windows 8 Metro application, to ensure that it throws the required exception?

Given a class with an async method

```<code>public static class AsyncMathsStatic
{
    private const int DELAY = 500;

    public static async Task<int> Divide(int A, int B)
    {
        await Task.Delay(DELAY);
        if (B == 0)
            throw new DivideByZeroException();
        else
            return A / B;
    }
}
</code>```

I want to write a test method using the new Async.ExpectsException construction. I've tried :-

```<code>[TestMethod]
public void DivideTest1()
{
    Assert.ThrowsException<DivideByZeroException>(async () => { int Result = await AsyncMathsStatic.Divide(4, 0); });
}
</code>```

but of course the test doesn't wait for the async method to complete, and so results in a failed test that the exception hasn't been thrown.

答:
```<code>[TestMethod]
public void DivideTest1()
{
    Func<Task> action = async () => { int Result = await AsyncMathsStatic.Divide(4, 0); });
    action.ShouldThrow<DivideByZeroException>();
}
</code>```

Using .ShouldThrow() from FluentAssertions nuget package works for me

Body:
Does anyone have an example of how to unit test an async method in a Windows 8 Metro application, to ensure that it throws the required exception?

Given a class with an async method

public static class AsyncMathsStatic
{
    private const int DELAY = 500;

    public static async Task<int> Divide(int A, int B)
    {
        await Task.Delay(DELAY);
        if (B == 0)
            throw new DivideByZeroException();
        else
            return A / B;
    }
}

I want to write a test method using the new Async.ExpectsException construction. I've tried :-

[TestMethod]
public void DivideTest1()
{
    Assert.ThrowsException<DivideByZeroException>(async () => { int Result = await AsyncMathsStatic.Divide(4, 0); });
}

but of course the test doesn't wait for the async method to complete, and so results in a failed test that the exception hasn't been thrown.

Body:
[TestMethod]
public void DivideTest1()
{
    Func<Task> action = async () => { int Result = await AsyncMathsStatic.Divide(4, 0); });
    action.ShouldThrow<DivideByZeroException>();
}

Using .ShouldThrow() from FluentAssertions nuget package works for me


问:
C# Class Process - Control C++ application, impossibility Read Output
I need to control a console application written in C++ from C# app.
The C# app can't read anything from output of C++ app. The application freezes when using the function process.StandardOutput.ReadLine(). I tried to create simple console apps in C#, C++  only with printf("Test sample\r\n") and Console.WriteLine("Test sample"). And the sample C# app works great, C++ not. So I don't know where I'm making a mistake. Probably C++ app writes bad end of line but I don't know how to solve it.

A code sample of main app in C# which controls another app written in C++ or C#.

```<code>            process= new Process()
            {
                StartInfo = new ProcessStartInfo(@"testApp")
                {
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = false,
                    WindowStyle = ProcessWindowStyle.Hidden
                }
            };

            process.Start();
            inputWriter = process.StandardInput;
            string text =process.StandardOutput.ReadLine();//C++ app freezes here
</code>```

And two test applications

In C++

```<code>int main(){
while (true) {
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    printf("Test send data\r\n");

}
return 0;}
</code>```

In C#

```<code>static void Main(string[] args)
    {
        while (true)
        {
            Thread.Sleep(500);
            Console.WriteLine("Test send data");
        }
    }
</code>```

答:
Take a look at these answers: ProcessStartInfo hanging on "WaitForExit"? Why? and
StandardOutput.ReadLine() hang the application using c#,
 they may both provide an explanation and a solution.

I have also tried to use ReadLineAsync:

```<code>while ((line = await process.StandardOutput.ReadLineAsync()) != null)
    Console.WriteLine(line);
</code>```

and it worked. Note that if you chose this solution, you will have to make some changes in your code to make it async (you can wrap it in a task as well, it all depends on your need).

Body:
I need to control a console application written in C++ from C# app.
The C# app can't read anything from output of C++ app. The application freezes when using the function process.StandardOutput.ReadLine(). I tried to create simple console apps in C#, C++  only with printf("Test sample\r\n") and Console.WriteLine("Test sample"). And the sample C# app works great, C++ not. So I don't know where I'm making a mistake. Probably C++ app writes bad end of line but I don't know how to solve it.

A code sample of main app in C# which controls another app written in C++ or C#.

            process= new Process()
            {
                StartInfo = new ProcessStartInfo(@"testApp")
                {
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = false,
                    WindowStyle = ProcessWindowStyle.Hidden
                }
            };

            process.Start();
            inputWriter = process.StandardInput;
            string text =process.StandardOutput.ReadLine();//C++ app freezes here

And two test applications

In C++

int main(){
while (true) {
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    printf("Test send data\r\n");

}
return 0;}

In C#

static void Main(string[] args)
    {
        while (true)
        {
            Thread.Sleep(500);
            Console.WriteLine("Test send data");
        }
    }

Body:
Take a look at these answers: ProcessStartInfo hanging on "WaitForExit"? Why? and
StandardOutput.ReadLine() hang the application using c#,
 they may both provide an explanation and a solution.

I have also tried to use ReadLineAsync:

while ((line = await process.StandardOutput.ReadLineAsync()) != null)
    Console.WriteLine(line);

and it worked. Note that if you chose this solution, you will have to make some changes in your code to make it async (you can wrap it in a task as well, it all depends on your need).


问:
Jboss Java Date daylight saving time
Have an issue where, when clocks are moved due to a Daylight savings time (twice a year), dates are not correct in Java (I am based in Central Europe: GMT+2 in summer, GMT+1 in winter)

If time is moved 1 hour ahead, new Date() still returns old time (1 hour behind of current time).

In Java 7, can this be solved, without restarting the Jboss application servers?

If I change the time manually in Windows, reproduce the problem: Date is not updated to the system date unless jboss is restarted.

```<code>Calendar c = Calendar.getInstance();
c.setTime(new Date());
</code>```

答:
In Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes.

With this, you can handle DST changes easily.

First, you can use the org.threeten.bp.DateTimeUtils to convert from and to Calendar.

The following code converts the Calendar to org.threeten.bp.Instant, which is a class that represents an "UTC instant" (a timestamp independent of timezone: right now, at this moment, everybody in the world are in the same instant, although their local date and time might be different, depending on where they are).

Then, the Instant is converted to a org.threeten.bp.ZonedDateTime (which means: at this instant, what is the date and time at this timezone?). I also used the org.threeten.bp.ZoneId to get the timezone:

```<code>Calendar c = Calendar.getInstance();
c.setTime(new Date());

// get the current instant in UTC timestamp
Instant now = DateTimeUtils.toInstant(c);

// convert to some timezone
ZonedDateTime z = now.atZone(ZoneId.of("Europe/Berlin"));

// today is 08/06/2017, so Berlin is in DST (GMT+2)
System.out.println(z); // 2017-06-08T14:11:58.608+02:00[Europe/Berlin]

// testing with a date in January (not in DST, GMT+1)
System.out.println(z.withMonth(1)); // 2017-01-08T14:11:58.608+01:00[Europe/Berlin]
</code>```

I've just picked some timezone that uses Central Europe timezone (Europe/Berlin): you can't use those 3-letter abbreviations, because they are ambiguous and not standard. You can change the code to the timezone that suits best for your system (you can get a list of all available timezones with ZoneId.getAvailableZoneIds()).

I prefer this solution because it's explicit what timezone we're using to display to the user (Date and Calendar's toString() methods use the default timezone behind the scenes and you never know what they're doing).

And internally, we can keep using the Instant, which is in UTC, so it's not affected by timezones (and you can always convert to and from timezones whenever you need) - if you want to convert the ZonedDateTime back to an Instant, just use the toInstant() method.

Actually, if you want to get the current date/time, just forget the old classes (Date and Calendar) and use just the Instant:

```<code>// get the current instant in UTC timestamp
Instant now = Instant.now();
</code>```

But if you still need to use the old classes, just use DateTimeUtils to do the conversions.

The output of the examples above are the result of the ZonedDateTime.toString() method. If you want to change the format, use the org.threeten.bp.format.DateTimeFormatter class (take a look at the javadoc for more details about all the possible formats):

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss z X");
// DST (GMT+02)
System.out.println(formatter.format(z)); // 08/06/2017 14:11:58 CEST +02
// not DST (GMT+01)
System.out.println(formatter.format(z.withMonth(1))); // 08/01/2017 14:11:58 CET +01
</code>```

Title: Jboss Java Date daylight saving time

Body:
Have an issue where, when clocks are moved due to a Daylight savings time (twice a year), dates are not correct in Java (I am based in Central Europe: GMT+2 in summer, GMT+1 in winter)

If time is moved 1 hour ahead, new Date() still returns old time (1 hour behind of current time).

In Java 7, can this be solved, without restarting the Jboss application servers?

If I change the time manually in Windows, reproduce the problem: Date is not updated to the system date unless jboss is restarted.

Calendar c = Calendar.getInstance();
c.setTime(new Date());

Body:
In Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes.

With this, you can handle DST changes easily.

First, you can use the org.threeten.bp.DateTimeUtils to convert from and to Calendar.

The following code converts the Calendar to org.threeten.bp.Instant, which is a class that represents an "UTC instant" (a timestamp independent of timezone: right now, at this moment, everybody in the world are in the same instant, although their local date and time might be different, depending on where they are).

Then, the Instant is converted to a org.threeten.bp.ZonedDateTime (which means: at this instant, what is the date and time at this timezone?). I also used the org.threeten.bp.ZoneId to get the timezone:

Calendar c = Calendar.getInstance();
c.setTime(new Date());

// get the current instant in UTC timestamp
Instant now = DateTimeUtils.toInstant(c);

// convert to some timezone
ZonedDateTime z = now.atZone(ZoneId.of("Europe/Berlin"));

// today is 08/06/2017, so Berlin is in DST (GMT+2)
System.out.println(z); // 2017-06-08T14:11:58.608+02:00[Europe/Berlin]

// testing with a date in January (not in DST, GMT+1)
System.out.println(z.withMonth(1)); // 2017-01-08T14:11:58.608+01:00[Europe/Berlin]

I've just picked some timezone that uses Central Europe timezone (Europe/Berlin): you can't use those 3-letter abbreviations, because they are ambiguous and not standard. You can change the code to the timezone that suits best for your system (you can get a list of all available timezones with ZoneId.getAvailableZoneIds()).

I prefer this solution because it's explicit what timezone we're using to display to the user (Date and Calendar's toString() methods use the default timezone behind the scenes and you never know what they're doing).

And internally, we can keep using the Instant, which is in UTC, so it's not affected by timezones (and you can always convert to and from timezones whenever you need) - if you want to convert the ZonedDateTime back to an Instant, just use the toInstant() method.

Actually, if you want to get the current date/time, just forget the old classes (Date and Calendar) and use just the Instant:

// get the current instant in UTC timestamp
Instant now = Instant.now();

But if you still need to use the old classes, just use DateTimeUtils to do the conversions.

The output of the examples above are the result of the ZonedDateTime.toString() method. If you want to change the format, use the org.threeten.bp.format.DateTimeFormatter class (take a look at the javadoc for more details about all the possible formats):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss z X");
// DST (GMT+02)
System.out.println(formatter.format(z)); // 08/06/2017 14:11:58 CEST +02
// not DST (GMT+01)
System.out.println(formatter.format(z.withMonth(1))); // 08/01/2017 14:11:58 CET +01


问:
Toolbar setOnScrollChangeListener() for api level 19
Is there any alternate listener which I can use to get scrolling amount in y axis?

I am using android.support.v7.widget.Toolbar but it doesn't have backward compatibility to API level 19.

答:
If i have understood properly , you can use addOnScrollChangedListener() instead.

Hope this helps.
Sorry for my english.


问:
google map - error in iframe
I'm using google map to...show map on my website.

when I run the file (html) I see the map. when I run my website and call the map file from iframe I see
http://80.179.226.44/~israelig/sites/exmytrip/tempmap.php

```<code>error: "Oops! Something went wrong.
This page didn't load Google Maps correctly. See the JavaScript console for technical details."
</code>```

IFRAME:

```<code>    <div id="map-canvas" class="col-md-6 col-xs-12">
        <iframe style="border-radius: 5px; width: 100%;" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="itinMap.html"></iframe>
    </div>
</code>```

itinMap.html file:

```<code><div id="map"></div>

<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var map;
        var elevator;
        var myOptions = {
            zoom: 5,
            center: new google.maps.LatLng(0, 0),
            mapTypeId: 'terrain'
        };
        map = new google.maps.Map($('#map')[0], myOptions);

        var addresses = ['rome', 'milan'];

        for (var x = 0; x < addresses.length; x++) {
            $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
                var p = data.results[0].geometry.location
                var latlng = new google.maps.LatLng(p.lat, p.lng);
                new google.maps.Marker({
                    position: latlng,
                    map: map
                });

            });
        }

    });
</script>
</code>```

答:
This Error is because you had not provided API Keys.

Source Google

The script element that loads the API has no API key. Please make sure
  you include a valid API key as a key parameter. You can generate a new
  API key on the Google API Console.

Getting API Keys
  https://developers.google.com/maps/documentation/javascript/get-api-key

MissingKeyMapError

The script element that loads the API is missing the required
  authentication parameter. If you are using the standard Maps
  JavaScript API, you must use a key parameter with a valid API key. If
  you are a Premium Plan customer, you must use either a client
  parameter with your client ID or a key parameter with a valid API key.

To Debug Such JS Error

Use Chrome, IE or Firefox and Press F12, to check error log.

Title: google map - error in iframe

Body:
I'm using google map to...show map on my website.

when I run the file (html) I see the map. when I run my website and call the map file from iframe I see
http://80.179.226.44/~israelig/sites/exmytrip/tempmap.php

error: "Oops! Something went wrong.
This page didn't load Google Maps correctly. See the JavaScript console for technical details."

IFRAME:

itinMap.html file:


问:
How do I change image on hover of  that the img is in - in jQuery?
You can see the implementation here http://jsfiddle.net/xNSFA/

Right now, when you hover over the cell, it changes some of the characteristics. But the image doesn't change. The image only changes when you hover over the image specifically.

How do I get the image to change with everything else?

By the way, it doesn't HAVE to be done in jQuery. If there is a nice elegant way to do this in CSS, I would love that. But I just assumed it was impossible to do - because of the image manipulation and I didn't want to set the background of the  to be that image. I want the image inside the cell.

Thanks.

答:
The following should work:</p>

```<code>$('td').hover(
  function(){
    $(this).find('img').attr('src','path/to/new/image.png');
  },
  function(){
    $(this).find('img').attr('src','path/too/old/image.png');
  }
);
</code>```

Title: How do I change image on hover of <td> that the img is in - in jQuery?

Body:
The following should work:

$('td').hover(
  function(){
    $(this).find('img').attr('src','path/to/new/image.png');
  },
  function(){
    $(this).find('img').attr('src','path/too/old/image.png');
  }
);


问:
Execute string as C#
I am checking conditions that could change and so would like to build them in a string and then run that string as C#.

```<code>//string conditionToCheck = user.Userdetail.Age > 18
string conditionToCheck = "user." + condition.Table + "." + condition.Column + " " + condition.Operator + " " + condition.Value;
if(conditionToCheck)
{
    ConditionsMet = true;
}
</code>```

Is there someway to convert conditionToCheck into C# ?

Background

I allow a user to create conditions by selecting a table and it's column and then assign and operator of > < == and a value.

Since a user can select any column of any table in the DB i need the code to check the conditions to handle anything.

答:
It's not entirely clear to me what you are trying to solve,

but if you are attempting to dynamically convert text to C#

code maybe you should use a T4 solution:

https://msdn.microsoft.com/en-us/library/bb126445.aspx

Title: Execute string as C#

Body:
I am checking conditions that could change and so would like to build them in a string and then run that string as C#.

//string conditionToCheck = user.Userdetail.Age > 18
string conditionToCheck = "user." + condition.Table + "." + condition.Column + " " + condition.Operator + " " + condition.Value;
if(conditionToCheck)
{
    ConditionsMet = true;
}

Is there someway to convert conditionToCheck into C# ?

Background

I allow a user to create conditions by selecting a table and it's column and then assign and operator of > < == and a value.

Since a user can select any column of any table in the DB i need the code to check the conditions to handle anything.


问:
How to parse a Ternary Statement in C#
I'm accepting an input string that I want to be a ternary statement that works on strings.  So my method signature would look like this:

```<code>public string Parse(string value, string ternaryStatement)
</code>```

and there parameters would give these results:

```<code>Parse(null, "=?It's Null:It's Not Null") == "It's Null" // Empty string would
Parse("", "=?It's Null:It's Not Null") == "It's Null"   // be same as null
</code>```

This example is fairly simple, Split the string first by '?' then by ':'

But of course I need a method to handle escape characters, "\", "\?" and ":", where "\" is valid anywhere, "\?" would only be valid before the first unescaped "?" and ":" would only be valid after that same "?".

```<code>Parse(@"\?\", @"=\\\?\\?\:Match\::\:No Match\:") == ":Match:"
Parse(@"\?\", @"!=\\\?\\?\:No Match\::\:Match\:") == ":Match:"
</code>```

But this is really complicated.  I believe I can perform it using regular expressions, but that just creates another problem since this is well beyond my limited understanding of regular expressions.  What's the best way to tackle this problem?

Edit 1

Some of the background:  I'm storing a format for a URL in a database config table (It's actually Dynamics 365 for Customer Engagement, but that doesn't matter at this point).  The format is stored as strings, and the parameters that are required are defined in code.  So generally it looks like this:

Format: "https://something.com?Foo={0}&Bar={1}"

Description: "0 - Foo, 1 - Bar"

where the description is used both for the person that is formatting the url, and the developer that needs to know how to structure the format statement.

The problem I'm running into right now is that I have a url that requires at least one of two different parameters.  If one of the values is null or empty, it will error if included in the url.  So I need a way of saying, if Foo is null or Bar is null, don't include the name or &.  Ideally I'd like to implement this like this:

```<code>"https://something.com?{0:=?:Foo={{0}}}&}{1:=?:Bar={{1}}}}"
</code>```

So if Foo is null and Bar is "Bar" the output would be

```<code>"https://something.com?Bar=Bar"
</code>```

I could also see this being used if we need to switch between a 0/1 for a boolean to true/false without having to change code:

```<code>"https://something.com?{0:=0?false:true}"
</code>```

答:
The two regexes should be:

```<code>Regex rx = new Regex(@"(?<=(?:^|[^\\])(?:\\\\)*)\?");
Regex rx2 = new Regex(@"(?<=(?:^|[^\\])(?:\\\\)*):");
</code>```

Use them like:

```<code>var m = rx.Match(str);

if (m.Success)
{
    int ix = m.Index;
}
</code>```

The main point of the two rx is that the searched string (\? or :) must be preceded by

```<code>(?<=(?:^|[^\\])(?:\\\\)*)
</code>```

that is the beginning of the string ^ or not a \ ([^\\]) plus zero or an even number of \\ that is (?:\\\\)*.

A all-in-one regex is:

```<code>Regex rx = new Regex(@"^(?<operator>=|!=|<=|>=|<|>)(?<cmp>(?:(?:\\.)|[^?:])*)\?(?<true>(?:(?:\\.)|[^?:])*):(?<false>(?:(?:\\.)|[^?:])*)$");

if (m.Success)
{
    string op = m.Groups["operator"].Value;
    string cmp = m.Groups["cmp"].Value;
    string true1 = m.Groups["true"].Value;
    string false1 = m.Groups["false"].Value;
}
</code>```

In op you'll get the comparison operator used, in cmp the comparand, in true1 and false1 the true and false strings. If !m.Success then the string isn't correctly formatted. Comprehending the regex is left as a simple exercise for the reader (unless you comprehend a regex, you shouldn't ever use it, because before or later you'll have to modify it/fix it/debug it)

Title: How to parse a Ternary Statement in C#

Body:
I'm accepting an input string that I want to be a ternary statement that works on strings.  So my method signature would look like this:

public string Parse(string value, string ternaryStatement)

and there parameters would give these results:

Parse(null, "=?It's Null:It's Not Null") == "It's Null" // Empty string would
Parse("", "=?It's Null:It's Not Null") == "It's Null"   // be same as null

This example is fairly simple, Split the string first by '?' then by ':'

But of course I need a method to handle escape characters, "\", "\?" and ":", where "\" is valid anywhere, "\?" would only be valid before the first unescaped "?" and ":" would only be valid after that same "?".

Parse(@"\?\", @"=\\\?\\?\:Match\::\:No Match\:") == ":Match:"
Parse(@"\?\", @"!=\\\?\\?\:No Match\::\:Match\:") == ":Match:"

But this is really complicated.  I believe I can perform it using regular expressions, but that just creates another problem since this is well beyond my limited understanding of regular expressions.  What's the best way to tackle this problem?

Edit 1

Some of the background:  I'm storing a format for a URL in a database config table (It's actually Dynamics 365 for Customer Engagement, but that doesn't matter at this point).  The format is stored as strings, and the parameters that are required are defined in code.  So generally it looks like this:

Format: "https://something.com?Foo={0}&Bar={1}"

Description: "0 - Foo, 1 - Bar"

where the description is used both for the person that is formatting the url, and the developer that needs to know how to structure the format statement.

The problem I'm running into right now is that I have a url that requires at least one of two different parameters.  If one of the values is null or empty, it will error if included in the url.  So I need a way of saying, if Foo is null or Bar is null, don't include the name or &.  Ideally I'd like to implement this like this:

"https://something.com?{0:=?:Foo={{0}}}&}{1:=?:Bar={{1}}}}"

So if Foo is null and Bar is "Bar" the output would be

"https://something.com?Bar=Bar"

I could also see this being used if we need to switch between a 0/1 for a boolean to true/false without having to change code:

"https://something.com?{0:=0?false:true}"

Body:
The two regexes should be:

Regex rx = new Regex(@"(?<=(?:^|[^\\])(?:\\\\)*)\?");
Regex rx2 = new Regex(@"(?<=(?:^|[^\\])(?:\\\\)*):");

Use them like:

var m = rx.Match(str);

if (m.Success)
{
    int ix = m.Index;
}

The main point of the two rx is that the searched string (\? or :) must be preceded by

(?<=(?:^|[^\\])(?:\\\\)*)

that is the beginning of the string ^ or not a \ ([^\\]) plus zero or an even number of \\ that is (?:\\\\)*.

A all-in-one regex is:

Regex rx = new Regex(@"^(?<operator>=|!=|<=|>=|<|>)(?<cmp>(?:(?:\\.)|[^?:])*)\?(?<true>(?:(?:\\.)|[^?:])*):(?<false>(?:(?:\\.)|[^?:])*)$");

if (m.Success)
{
    string op = m.Groups["operator"].Value;
    string cmp = m.Groups["cmp"].Value;
    string true1 = m.Groups["true"].Value;
    string false1 = m.Groups["false"].Value;
}

In op you'll get the comparison operator used, in cmp the comparand, in true1 and false1 the true and false strings. If !m.Success then the string isn't correctly formatted. Comprehending the regex is left as a simple exercise for the reader (unless you comprehend a regex, you shouldn't ever use it, because before or later you'll have to modify it/fix it/debug it)


问:
TabView Crash when Selected
My app is crashing when I try to select the "inspection" tab I have everything linked Im not sure why I'm getting this error. Can someone lend a hand? Below are my InspectionViewController and my Error Code.

InspectionVC:

```<code>//
//  InspectionVC.swift
//  Chat
//
//  Created by Wiiliam Pettit on 6/2/17.
//  Copyright © 2017 MVI. All rights reserved.
//

import UIKit

class InspectionVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var picker: UIPickerView!

    var pickerData: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        // Connect data:
        self.picker.delegate = self
        self.picker.dataSource = self

        // Input data into the Array:
        pickerData = ["5312", "5387", "53C4", "53W5", "53W8", "5349"]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }

    // Catpure the picker view selection
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if(row == 0)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com/Module_Inspect/perform/22243/230")!)
        }
        else if(row == 1)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
        else if(row == 2)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
        else if(row == 3)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
        else if(row == 4)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
        else if(row == 5)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
    }

}
</code>```

Error:

```<code>Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<QuickChat.InspectionVC 0x7fe83ad275f0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key pickerView.'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010d443b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010c545141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010d443a59 -[NSException raise] + 9
    3   Foundation                          0x000000010c05ae8b -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
    4   UIKit                               0x000000010e369644 -[UIViewController setValue:forKey:] + 87
    5   UIKit                               0x000000010e5d66b9 -[UIRuntimeOutletConnection connect] + 109
    6   CoreFoundation                      0x000000010d3e9e8d -[NSArray makeObjectsPerformSelector:] + 269
    7   UIKit                               0x000000010e5d506f -[UINib instantiateWithOwner:options:] + 1856
    8   UIKit                               0x000000010e36fc73 -[UIViewController _loadViewFromNibNamed:bundle:] + 381
    9   UIKit                               0x000000010e370589 -[UIViewController loadView] + 177
    10  UIKit                               0x000000010e3708ba -[UIViewController loadViewIfRequired] + 195
    11  UIKit                               0x000000010e37110a -[UIViewController view] + 27
    12  UIKit                               0x000000010e3cd40b -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 476
    13  UIKit                               0x000000010e3cc89c -[UITabBarController transitionFromViewController:toViewController:] + 59
    14  UIKit                               0x000000010e3c89d6 -[UITabBarController _setSelectedViewController:] + 410
    15  UIKit                               0x000000010e3c87a5 -[UITabBarController setSelectedViewController:] + 109
    16  UIKit                               0x000000010e3cc741 -[UITabBarController _tabBarItemClicked:] + 384
    17  UIKit                               0x000000010e1cfd22 -[UIApplication sendAction:to:from:forEvent:] + 83
    18  UIKit                               0x000000010e5e26f7 -[UITabBar _sendAction:withEvent:] + 566
    19  UIKit                               0x000000010e1cfd22 -[UIApplication sendAction:to:from:forEvent:] + 83
    20  UIKit                               0x000000010e35425c -[UIControl sendAction:to:forEvent:] + 67
    21  UIKit                               0x000000010e354577 -[UIControl _sendActionsForEvents:withEvent:] + 450
    22  UIKit                               0x000000010e5e4db5 -[UITabBar _buttonUp:] + 113
    23  UIKit                               0x000000010e1cfd22 -[UIApplication sendAction:to:from:forEvent:] + 83
    24  UIKit                               0x000000010e35425c -[UIControl sendAction:to:forEvent:] + 67
    25  UIKit                               0x000000010e354577 -[UIControl _sendActionsForEvents:withEvent:] + 450
    26  UIKit                               0x000000010e3534b2 -[UIControl touchesEnded:withEvent:] + 618
    27  UIKit                               0x000000010e23d49a -[UIWindow _sendTouchesForEvent:] + 2707
    28  UIKit                               0x000000010e23ebb0 -[UIWindow sendEvent:] + 4114
    29  UIKit                               0x000000010e1eb7b0 -[UIApplication sendEvent:] + 352
    30  UIKit                               0x000000010e9ceadc __dispatchPreprocessedEventFromEventQueue + 2926
    31  UIKit                               0x000000010e9c6a3a __handleEventQueue + 1122
    32  CoreFoundation                      0x000000010d3e9c01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    33  CoreFoundation                      0x000000010d3cf0cf __CFRunLoopDoSources0 + 527
    34  CoreFoundation                      0x000000010d3ce5ff __CFRunLoopRun + 911
    35  CoreFoundation                      0x000000010d3ce016 CFRunLoopRunSpecific + 406
    36  GraphicsServices                    0x000000011156ea24 GSEventRunModal + 62
    37  UIKit                               0x000000010e1ce0d4 UIApplicationMain + 159
    38  QuickChat                           0x000000010a83fba7 main + 55
    39  libdyld.dylib                       0x00000001104ae65d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>```

答:
Apart of 'picker' (an IBOutlet of UIPickerView), you have one more outlet connection in your connection inspector.

Open your Connection Inspector and remove connection with 'pickerView' instance.

Steps: Select Storyboard >> Select View Controller >> Open Connection
  Inspector >> Check all IBOutlet connections and find 'pickerView' >>
  Remove connection of 'pickerView'

Title: TabView Crash when Selected

Body:
My app is crashing when I try to select the "inspection" tab I have everything linked Im not sure why I'm getting this error. Can someone lend a hand? Below are my InspectionViewController and my Error Code.

InspectionVC:

//
//  InspectionVC.swift
//  Chat
//
//  Created by Wiiliam Pettit on 6/2/17.
//  Copyright © 2017 MVI. All rights reserved.
//

import UIKit

class InspectionVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var picker: UIPickerView!

    var pickerData: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        // Connect data:
        self.picker.delegate = self
        self.picker.dataSource = self

        // Input data into the Array:
        pickerData = ["5312", "5387", "53C4", "53W5", "53W8", "5349"]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }

    // Catpure the picker view selection
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if(row == 0)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com/Module_Inspect/perform/22243/230")!)
        }
        else if(row == 1)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
        else if(row == 2)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
        else if(row == 3)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
        else if(row == 4)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
        else if(row == 5)
        {
            UIApplication.shared.open(URL(string: "http://mvi.crompco.com")!)
        }
    }

}

Error:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<QuickChat.InspectionVC 0x7fe83ad275f0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key pickerView.'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010d443b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010c545141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010d443a59 -[NSException raise] + 9
    3   Foundation                          0x000000010c05ae8b -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
    4   UIKit                               0x000000010e369644 -[UIViewController setValue:forKey:] + 87
    5   UIKit                               0x000000010e5d66b9 -[UIRuntimeOutletConnection connect] + 109
    6   CoreFoundation                      0x000000010d3e9e8d -[NSArray makeObjectsPerformSelector:] + 269
    7   UIKit                               0x000000010e5d506f -[UINib instantiateWithOwner:options:] + 1856
    8   UIKit                               0x000000010e36fc73 -[UIViewController _loadViewFromNibNamed:bundle:] + 381
    9   UIKit                               0x000000010e370589 -[UIViewController loadView] + 177
    10  UIKit                               0x000000010e3708ba -[UIViewController loadViewIfRequired] + 195
    11  UIKit                               0x000000010e37110a -[UIViewController view] + 27
    12  UIKit                               0x000000010e3cd40b -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 476
    13  UIKit                               0x000000010e3cc89c -[UITabBarController transitionFromViewController:toViewController:] + 59
    14  UIKit                               0x000000010e3c89d6 -[UITabBarController _setSelectedViewController:] + 410
    15  UIKit                               0x000000010e3c87a5 -[UITabBarController setSelectedViewController:] + 109
    16  UIKit                               0x000000010e3cc741 -[UITabBarController _tabBarItemClicked:] + 384
    17  UIKit                               0x000000010e1cfd22 -[UIApplication sendAction:to:from:forEvent:] + 83
    18  UIKit                               0x000000010e5e26f7 -[UITabBar _sendAction:withEvent:] + 566
    19  UIKit                               0x000000010e1cfd22 -[UIApplication sendAction:to:from:forEvent:] + 83
    20  UIKit                               0x000000010e35425c -[UIControl sendAction:to:forEvent:] + 67
    21  UIKit                               0x000000010e354577 -[UIControl _sendActionsForEvents:withEvent:] + 450
    22  UIKit                               0x000000010e5e4db5 -[UITabBar _buttonUp:] + 113
    23  UIKit                               0x000000010e1cfd22 -[UIApplication sendAction:to:from:forEvent:] + 83
    24  UIKit                               0x000000010e35425c -[UIControl sendAction:to:forEvent:] + 67
    25  UIKit                               0x000000010e354577 -[UIControl _sendActionsForEvents:withEvent:] + 450
    26  UIKit                               0x000000010e3534b2 -[UIControl touchesEnded:withEvent:] + 618
    27  UIKit                               0x000000010e23d49a -[UIWindow _sendTouchesForEvent:] + 2707
    28  UIKit                               0x000000010e23ebb0 -[UIWindow sendEvent:] + 4114
    29  UIKit                               0x000000010e1eb7b0 -[UIApplication sendEvent:] + 352
    30  UIKit                               0x000000010e9ceadc __dispatchPreprocessedEventFromEventQueue + 2926
    31  UIKit                               0x000000010e9c6a3a __handleEventQueue + 1122
    32  CoreFoundation                      0x000000010d3e9c01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    33  CoreFoundation                      0x000000010d3cf0cf __CFRunLoopDoSources0 + 527
    34  CoreFoundation                      0x000000010d3ce5ff __CFRunLoopRun + 911
    35  CoreFoundation                      0x000000010d3ce016 CFRunLoopRunSpecific + 406
    36  GraphicsServices                    0x000000011156ea24 GSEventRunModal + 62
    37  UIKit                               0x000000010e1ce0d4 UIApplicationMain + 159
    38  QuickChat                           0x000000010a83fba7 main + 55
    39  libdyld.dylib                       0x00000001104ae65d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)


问:
Ionic 2 - Input ‘Go’ field on Keyboard is doing two things
I am building an Ionic App for iOS & Android and so far I have a form where users can upload or take a photo and then fill in some other information and submit the form.

My issue:

Currently when the user goes to an Input to enter some extra text there is a go button at the bottom of the keyboard. If the user clicks this 'Go' button it tries to submit the form along with opening the choosePicture() function I have.

What happen when I click the
Go button - it opens the Library

The HTML

```<code><ion-item class="file-upload">
    <button  class="btn btn-block" ion-button (click)="choosePhoto()">Choose a Photo</button>
    <span class="sep"></span>
    <button class="btn btn-block" ion-button (click)="takePicture()">Take a Picture</button>
    <div class="uploaded-img">
        <input type="file" value="" formControlName="hazardImage" hidden />
        <span class="img-desc">Please Take or Upload an Image.</span>
        <div class="img-picked" *ngIf="base64Img">
            <img [src]="base64Img" alt="Hazard Picture" />
            <!-- <img src="http://placehold.it/300x300" alt="Test Image" /> -->
        </div>
    </div>
</ion-item>

<small class="small-title">Where is the Hazard Location? (required)</small>
<ion-item class="input-box">
    <ion-input type="text" formControlName="hazardLocation" [class.invalid]="!hazardForm.controls.hazardLocation.valid && (hazardForm.controls.hazardLocation.dirty || submitAttempt)"></ion-input>
</ion-item>
</code>```

The TypeScript:

```<code>choosePhoto()
{
    this.Camera.getPicture({
        quality: 50,
        destinationType: this.Camera.DestinationType.DATA_URL,
        encodingType: this.Camera.EncodingType.JPEG,
        sourceType: this.Camera.PictureSourceType.PHOTOLIBRARY,
        allowEdit: true
    }).then((ImageData) => {
        // console.log(ImageData);
        this.base64Img = ImageData;
        this.hazardForm.patchValue({
            hazardImage: this.base64Img
        });
    }, (err) => {
        console.log(err);
    })
}
</code>```

I don't understand why the Go Button is opening the function for choosing a photo :/

答:
You can modify the behaviour of the 'Go' keyboard button with:</p>

```<code>@ViewChild('input-box') inputElm: ElementRef;
@HostListener('keyup', ['$event'])
keyEvent(e) {

if(!e.srcElement) return; //browser fix
var code = e.keyCode || e.which;
if (code === 13) {
  if (e.srcElement.tagName === "INPUT") {
    e.preventDefault();
    //handle other behaviours
  }
}
};
</code>```

Body:
I am building an Ionic App for iOS & Android and so far I have a form where users can upload or take a photo and then fill in some other information and submit the form.

My issue:

Currently when the user goes to an Input to enter some extra text there is a go button at the bottom of the keyboard. If the user clicks this 'Go' button it tries to submit the form along with opening the choosePicture() function I have.

What happen when I click the
Go button - it opens the Library

The HTML

<ion-item class="file-upload">
    <button  class="btn btn-block" ion-button (click)="choosePhoto()">Choose a Photo</button>

    <button class="btn btn-block" ion-button (click)="takePicture()">Take a Picture</button>

        <input type="file" value="" formControlName="hazardImage" hidden />
        Please Take or Upload an Image.

</ion-item>

Where is the Hazard Location? (required)
<ion-item class="input-box">
    <ion-input type="text" formControlName="hazardLocation" [class.invalid]="!hazardForm.controls.hazardLocation.valid && (hazardForm.controls.hazardLocation.dirty || submitAttempt)"></ion-input>
</ion-item>

The TypeScript:

choosePhoto()
{
    this.Camera.getPicture({
        quality: 50,
        destinationType: this.Camera.DestinationType.DATA_URL,
        encodingType: this.Camera.EncodingType.JPEG,
        sourceType: this.Camera.PictureSourceType.PHOTOLIBRARY,
        allowEdit: true
    }).then((ImageData) => {
        // console.log(ImageData);
        this.base64Img = ImageData;
        this.hazardForm.patchValue({
            hazardImage: this.base64Img
        });
    }, (err) => {
        console.log(err);
    })
}

I don't understand why the Go Button is opening the function for choosing a photo :/

Body:
You can modify the behaviour of the 'Go' keyboard button with:

@ViewChild('input-box') inputElm: ElementRef;
@HostListener('keyup', ['$event'])
keyEvent(e) {

if(!e.srcElement) return; //browser fix
var code = e.keyCode || e.which;
if (code === 13) {
  if (e.srcElement.tagName === "INPUT") {
    e.preventDefault();
    //handle other behaviours
  }
}
};


问:
Chaining Promises with custom error types with Kovenant
I'm using Retrofit to access a REST API and I would like to use Kovenant's then function to chain several units of work. In other words, I want to feed the output of one API call as a parameter to another API call.

I've defined a custom error type that includes a property to contain API specific error codes defined as follows:

```<code>class ApiError(val statusCode: Int, val apiErrorCode: Int, val message: String)
</code>```

If an error occurs during an API call, an instance of this class is created with the appropriate error codes.

According to Kovenant's documentation, I can create an instance of Deferred<V, E> to obtain a Promise<V, E>. I was hoping that I could supply ApiError for the generic parameter E. I didn't see any generic constraints in Kovenant's definition of Deferred that seem to require E to be an Exception.

That being said, when I attempt to chain two functions that return Promise<V, ApiError> using then, I receive a compiler error stating that the expected type for then is a Promise<V, Exception>.

Can I make Kovenant work with a custom error type and if not, is subclassing Exception to include the properties I need the correct solution for what I'm trying to achieve?

答:
Some of the base definitions do not have generic bounds for E but almost all of the extension functions do indicate the E is of type Exception.  Viewing the source code in Kovenant promises-api.kt shows that it is clear that most things have this expectation.

You can simply change your error class to be a descendant of Exception:

```<code>class ApiError(val statusCode: Int, val apiErrorCode: Int, message: String) : Exception(message)
</code>```

Then you can throw it to fail the Promise or use it to call fail on the  Deferred.

Body:
I'm using Retrofit to access a REST API and I would like to use Kovenant's then function to chain several units of work. In other words, I want to feed the output of one API call as a parameter to another API call.

I've defined a custom error type that includes a property to contain API specific error codes defined as follows:

class ApiError(val statusCode: Int, val apiErrorCode: Int, val message: String)

If an error occurs during an API call, an instance of this class is created with the appropriate error codes.

According to Kovenant's documentation, I can create an instance of Deferred<V, E> to obtain a Promise<V, E>. I was hoping that I could supply ApiError for the generic parameter E. I didn't see any generic constraints in Kovenant's definition of Deferred that seem to require E to be an Exception.

That being said, when I attempt to chain two functions that return Promise<V, ApiError> using then, I receive a compiler error stating that the expected type for then is a Promise<V, Exception>.

Can I make Kovenant work with a custom error type and if not, is subclassing Exception to include the properties I need the correct solution for what I'm trying to achieve?

Body:
Some of the base definitions do not have generic bounds for E but almost all of the extension functions do indicate the E is of type Exception.  Viewing the source code in Kovenant promises-api.kt shows that it is clear that most things have this expectation.

You can simply change your error class to be a descendant of Exception:

class ApiError(val statusCode: Int, val apiErrorCode: Int, message: String) : Exception(message)

Then you can throw it to fail the Promise or use it to call fail on the  Deferred.


问:
How does uTorrent choose between TCP and uTP?
I'm trying to analyse how uTorrent works using Wireshark to capture sent packets.
There are three hosts in the same local network, one of them creates the torrent and starts seeding, while the other two download the torrent. From the trace it looks like uTorrent uses both TCP and uTP, sometimes switching between protocols in the middle of the download. How does uTorrent choose? I've checked on the bittorrent documentation and found nothing. Is there a way to force uTorrent to use only one of the two?</p>

答:
Of what I have observed, uTorrent seems to prefer uTP over TCP, which is generally a good choice.

In Preferences > BitTorrent: Enable bandwidth management [uTP] can be used to turn uTP on/off.

More precise control can be done in Preferences > Advanced: bt.transp_disposition

Default value: 31

From µTorrent User Manual: (Press  F1)

bt.transp_disposition: This option controls µTorrent's level of bias towards using TCP or uTP for transporting data (assuming the peer at the other end of the connection supports both transport protocols). The following is a list of the accepted values:

1 allows µTorrent to attempt outgoing TCP connections

2 allows µTorrent to attempt outgoing uTP connections

4 allows µTorrent to accept incoming TCP connections

8 allows µTorrent to accept incoming uTP connections

16 tells µTorrent to use the new uTP header. This is an improved communication header, but is not backwards compatible with clients that do not understand it.

This option is interpreted as a bitfield, so values can be added together to obtain a combination of behaviors. Setting this value to 255 guarantees that all behaviors are enabled.


问:
How range and phrase query work in elasticsearch?
If elastic search is using inverted index, I want to know how elasticsearch is able to support range queries and phrase queries.
Note: I saw that inverted index supports them but i am not clear on how they do it internally.</p>

答:
Found the link ..
Reference : https://blog.parse.ly/post/1691/lucene/
Here’s a snippet from Lucene in Action on the topic: “If you indexed your field with NumericField, you can efficiently search a particular range for that field using NumericRangeQuery. Under the hood, Lucene translates the requested range into the equivalent set of brackets in the indexed trie structure.”
This blog actually has some nice information on lucene indexes.</p>


问:
Extracting data from pixels of a contour plot figure in Python or MATLAB
I have a contour plot like this:

Now, if I do not have the data to generate the contour plot and all I have is the image, how can I extract the values for each and every pixel from the image and store it in an array?

Any suggestions or examples in MATLAB/Python would be helpful!

答:
If you know the pixle values, using find, you can find the locations you want.

```<code>I = imread('y5dZ1.png');
I1 = rgb2gray(I) ;
%%
pix = [48 : 10 : 200] ;
[y,x] = find(I1==200) ;

imshow(I)
hold on
plot(x,y,'.r')
</code>```

Body:
If you know the pixle values, using find, you can find the locations you want.

I = imread('y5dZ1.png');
I1 = rgb2gray(I) ;
%%
pix = [48 : 10 : 200] ;
[y,x] = find(I1==200) ;

imshow(I)
hold on
plot(x,y,'.r')


问:
.Net fail to connect to Apple Push Notification service
I'm using .NET 4.5 c# to connect to a server that supports only TLS 1.2. (Apple Push Notification Server).

My code fails here:

```<code>sslStream.AuthenticateAsClient(server, myAppleCertificates, SslProtocols.Tls12, true);
</code>```

I did a lot of testing and Googling and found the following:

1) This code works fine if i use a window 10 pc, but doesn't if I run this on my development server or production server. Windows Server 2008 R2.

2) All the pc's and servers are running .net 4.6+

3) I can add the line "ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;" - its still behaves exactly the same.

4) I can replicate the issue on Windows 10, buy simply changing it to:
sslStream.AuthenticateAsClient(server, myAppleCertificates, SslProtocols.Tls11, true);

5) I have added the following registry entries and rebooted the server will no effect:

```<code>[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
</code>```

5) Server is up to date with windows updates. (actually... im not 100% on this one)

6) IISCrypto, says the protocols are there, and set as defaults correctly.

7) I can use Chrome to connect to APN, no problems, on my PC, and both the servers.

8) If i use Fiddler to test, it behaves exactly the same as my application, after i enable the TLS12 setting in the fiddler settings. I guess this is because Fiddler is build in .net 4.

Its as though even if you force .NET to use TLS1.2, it simply doesn't, and reverts back to 1.1. Does anyone have any more idea's here.

Thanks

Here is my test code:

```<code>public class SslTcpClient
    {
        private static Hashtable certificateErrors = new Hashtable();

        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None) return true;

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            return false;
        }
        public static X509Certificate SelectLocalCertificate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
        {
            Console.WriteLine("Client is selecting a local certificate.");
            if (acceptableIssuers != null && acceptableIssuers.Length > 0 && localCertificates != null && localCertificates.Count > 0)
            {
                // Use the first certificate that is from an acceptable issuer.
                foreach (X509Certificate certificate in localCertificates)
                {
                    string issuer = certificate.Issuer;
                    if (Array.IndexOf(acceptableIssuers, issuer) != -1) return certificate;
                }
            }
            if (localCertificates != null && localCertificates.Count > 0)  return localCertificates[0];

            return null;
        }

        public static void RunClient(string server)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            TcpClient client = new TcpClient(server, 443);
            Console.WriteLine("Client connected.");
            SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            Console.WriteLine("SSL stream obtained");

            try
            {
                X509Certificate localCertificate = new X509Certificate("VOIPPush.p12", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

                Console.WriteLine("Local Certificte features");
                Console.WriteLine("=========================");

                Console.WriteLine("Issuer: " + localCertificate.Issuer);
                Console.WriteLine("Subject: " + localCertificate.Subject);

                Console.WriteLine("CertHash: " + localCertificate.GetCertHashString());
                Console.WriteLine("EffectiveDate: " + localCertificate.GetEffectiveDateString());
                Console.WriteLine("ExpirationDate: " + localCertificate.GetExpirationDateString());
                Console.WriteLine("Format: " + localCertificate.GetFormat());
                Console.WriteLine("HashCode: " + localCertificate.GetHashCode().ToString());
                Console.WriteLine("KeyAlgorithm: " + localCertificate.GetKeyAlgorithm());
                Console.WriteLine("KeyAlgorithmParameters: " + localCertificate.GetKeyAlgorithmParametersString());
                Console.WriteLine("PublicKey: " + localCertificate.GetPublicKeyString());
                Console.WriteLine("SerialNumber: " + localCertificate.GetSerialNumberString());
                X509CertificateCollection localCertificates = new X509CertificateCollection();
                localCertificates.Add(localCertificate);

                sslStream.AuthenticateAsClient(server, localCertificates, SslProtocols.Tls12, true);
                Console.WriteLine("Authenticated as client");

                X509Certificate remoteCertificate = sslStream.RemoteCertificate;

                Console.WriteLine("Remote Certificte features");
                Console.WriteLine("==========================");

                Console.WriteLine("Issuer: " + remoteCertificate.Issuer);
                Console.WriteLine("Subject: " + remoteCertificate.Subject);

                Console.WriteLine("CertHash: " + remoteCertificate.GetCertHashString());
                Console.WriteLine("EffectiveDate: " + remoteCertificate.GetEffectiveDateString());
                Console.WriteLine("ExpirationDate: " + remoteCertificate.GetExpirationDateString());
                Console.WriteLine("Format: " + remoteCertificate.GetFormat());
                Console.WriteLine("HashCode: " + remoteCertificate.GetHashCode().ToString());
                Console.WriteLine("KeyAlgorithm: " + remoteCertificate.GetKeyAlgorithm());
                Console.WriteLine("KeyAlgorithmParameters: " + remoteCertificate.GetKeyAlgorithmParametersString());
                Console.WriteLine("PublicKey: " + remoteCertificate.GetPublicKeyString());
                Console.WriteLine("SerialNumber: " + remoteCertificate.GetSerialNumberString());

            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
                client.Close();
                return;
            }
            byte[] messsage = Encoding.UTF8.GetBytes(@"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");

            // no use in writing more, this is just a test...

            Console.WriteLine("Writing to sslStream...");
            sslStream.Write(messsage);
            Console.WriteLine("Writing done");
            sslStream.Flush();

            Console.WriteLine("Reading Response...");
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);

            client.Close();
            Console.WriteLine("Client closed.");
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                // Check for EOF.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);

            return messageData.ToString();
        }

        public static void Main(string[] args)
        {
            SslTcpClient.RunClient("api.push.apple.com");
            Console.ReadLine();
        }
    }
</code>```

答:
On a Windows Server 2008 R2 production server I am using:

```<code>_iPhoneSslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
</code>```

Complete source code for authentication:

```<code>String hostname = "gateway.push.apple.com";

X509Certificate2 clientCertificate = new X509Certificate2(_iPhoneCertificate, _iPhonePassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);

_iPhoneClient = new TcpClient(hostname, 2195);
_iPhoneSslStream = new SslStream(_iPhoneClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

_iPhoneSslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
</code>```

and

```<code>public static bool ValidateServerCertificate(object sender,
                                         X509Certificate certificate,
                                         X509Chain chain,
                                         SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
        return true;

     // Do not allow this client to communicate with unauthenticated servers.
     return false;
}
</code>```

PS I am still using the Legacy Binary Provider API:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/BinaryProviderAPI.html

Body:
I'm using .NET 4.5 c# to connect to a server that supports only TLS 1.2. (Apple Push Notification Server).

My code fails here:

sslStream.AuthenticateAsClient(server, myAppleCertificates, SslProtocols.Tls12, true);

I did a lot of testing and Googling and found the following:

1) This code works fine if i use a window 10 pc, but doesn't if I run this on my development server or production server. Windows Server 2008 R2.

2) All the pc's and servers are running .net 4.6+

3) I can add the line "ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;" - its still behaves exactly the same.

4) I can replicate the issue on Windows 10, buy simply changing it to:
sslStream.AuthenticateAsClient(server, myAppleCertificates, SslProtocols.Tls11, true);

5) I have added the following registry entries and rebooted the server will no effect:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000

5) Server is up to date with windows updates. (actually... im not 100% on this one)

6) IISCrypto, says the protocols are there, and set as defaults correctly.

7) I can use Chrome to connect to APN, no problems, on my PC, and both the servers.

8) If i use Fiddler to test, it behaves exactly the same as my application, after i enable the TLS12 setting in the fiddler settings. I guess this is because Fiddler is build in .net 4.

Its as though even if you force .NET to use TLS1.2, it simply doesn't, and reverts back to 1.1. Does anyone have any more idea's here.

Thanks

Here is my test code:

public class SslTcpClient
    {
        private static Hashtable certificateErrors = new Hashtable();

        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None) return true;

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            return false;
        }
        public static X509Certificate SelectLocalCertificate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
        {
            Console.WriteLine("Client is selecting a local certificate.");
            if (acceptableIssuers != null && acceptableIssuers.Length > 0 && localCertificates != null && localCertificates.Count > 0)
            {
                // Use the first certificate that is from an acceptable issuer.
                foreach (X509Certificate certificate in localCertificates)
                {
                    string issuer = certificate.Issuer;
                    if (Array.IndexOf(acceptableIssuers, issuer) != -1) return certificate;
                }
            }
            if (localCertificates != null && localCertificates.Count > 0)  return localCertificates[0];

            return null;
        }

        public static void RunClient(string server)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            TcpClient client = new TcpClient(server, 443);
            Console.WriteLine("Client connected.");
            SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            Console.WriteLine("SSL stream obtained");

            try
            {
                X509Certificate localCertificate = new X509Certificate("VOIPPush.p12", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

                Console.WriteLine("Local Certificte features");
                Console.WriteLine("=========================");

                Console.WriteLine("Issuer: " + localCertificate.Issuer);
                Console.WriteLine("Subject: " + localCertificate.Subject);

                Console.WriteLine("CertHash: " + localCertificate.GetCertHashString());
                Console.WriteLine("EffectiveDate: " + localCertificate.GetEffectiveDateString());
                Console.WriteLine("ExpirationDate: " + localCertificate.GetExpirationDateString());
                Console.WriteLine("Format: " + localCertificate.GetFormat());
                Console.WriteLine("HashCode: " + localCertificate.GetHashCode().ToString());
                Console.WriteLine("KeyAlgorithm: " + localCertificate.GetKeyAlgorithm());
                Console.WriteLine("KeyAlgorithmParameters: " + localCertificate.GetKeyAlgorithmParametersString());
                Console.WriteLine("PublicKey: " + localCertificate.GetPublicKeyString());
                Console.WriteLine("SerialNumber: " + localCertificate.GetSerialNumberString());
                X509CertificateCollection localCertificates = new X509CertificateCollection();
                localCertificates.Add(localCertificate);

                sslStream.AuthenticateAsClient(server, localCertificates, SslProtocols.Tls12, true);
                Console.WriteLine("Authenticated as client");

                X509Certificate remoteCertificate = sslStream.RemoteCertificate;

                Console.WriteLine("Remote Certificte features");
                Console.WriteLine("==========================");

                Console.WriteLine("Issuer: " + remoteCertificate.Issuer);
                Console.WriteLine("Subject: " + remoteCertificate.Subject);

                Console.WriteLine("CertHash: " + remoteCertificate.GetCertHashString());
                Console.WriteLine("EffectiveDate: " + remoteCertificate.GetEffectiveDateString());
                Console.WriteLine("ExpirationDate: " + remoteCertificate.GetExpirationDateString());
                Console.WriteLine("Format: " + remoteCertificate.GetFormat());
                Console.WriteLine("HashCode: " + remoteCertificate.GetHashCode().ToString());
                Console.WriteLine("KeyAlgorithm: " + remoteCertificate.GetKeyAlgorithm());
                Console.WriteLine("KeyAlgorithmParameters: " + remoteCertificate.GetKeyAlgorithmParametersString());
                Console.WriteLine("PublicKey: " + remoteCertificate.GetPublicKeyString());
                Console.WriteLine("SerialNumber: " + remoteCertificate.GetSerialNumberString());

            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
                client.Close();
                return;
            }
            byte[] messsage = Encoding.UTF8.GetBytes(@"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");

            // no use in writing more, this is just a test...

            Console.WriteLine("Writing to sslStream...");
            sslStream.Write(messsage);
            Console.WriteLine("Writing done");
            sslStream.Flush();

            Console.WriteLine("Reading Response...");
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);

            client.Close();
            Console.WriteLine("Client closed.");
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                // Check for EOF.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);

            return messageData.ToString();
        }

        public static void Main(string[] args)
        {
            SslTcpClient.RunClient("api.push.apple.com");
            Console.ReadLine();
        }
    }

Body:
On a Windows Server 2008 R2 production server I am using:

_iPhoneSslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);

Complete source code for authentication:

String hostname = "gateway.push.apple.com";

X509Certificate2 clientCertificate = new X509Certificate2(_iPhoneCertificate, _iPhonePassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);

_iPhoneClient = new TcpClient(hostname, 2195);
_iPhoneSslStream = new SslStream(_iPhoneClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

_iPhoneSslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);

and

public static bool ValidateServerCertificate(object sender,
                                         X509Certificate certificate,
                                         X509Chain chain,
                                         SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
        return true;

     // Do not allow this client to communicate with unauthenticated servers.
     return false;
}

PS I am still using the Legacy Binary Provider API:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/BinaryProviderAPI.html


问:
Find top 10 students mark using array of object
I recently had an interview,they asked me a small question
the question is follows

There is list of Students

```<code>    List<Student> students;

    Class Student{
     String rollNo;
     Map<String, Integer> marks ;
}
</code>```

Stdunt.marks is actually cobination of subject and mark

Should write an method which should return top 10 students array according to the subject.

```<code>List<Student> getTop10(String subjectName){
}
</code>```

答:
In general your idea is correct, to sort the entire list and take top N students, in fact with java 8 it would look cleaner.</p>

```<code>private static void PrintTop5(ArrayList<Student> list,String subject){
    list.sort(Comparator
                    .comparing((Student student) -> student.getSubjectMark(subject))
                    .reversed());

    List<Student> studentList = list.stream().limit(5).collect(Collectors.toList());
    for(Student student : studentList){
        System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
    }
}
</code>```

Body:
I recently had an interview,they asked me a small question
the question is follows

There is list of Students

    List<Student> students;

    Class Student{
     String rollNo;
     Map<String, Integer> marks ;
}

Stdunt.marks is actually cobination of subject and mark

Should write an method which should return top 10 students array according to the subject.

List<Student> getTop10(String subjectName){
}

Body:
In general your idea is correct, to sort the entire list and take top N students, in fact with java 8 it would look cleaner.

private static void PrintTop5(ArrayList<Student> list,String subject){
    list.sort(Comparator
                    .comparing((Student student) -> student.getSubjectMark(subject))
                    .reversed());

    List<Student> studentList = list.stream().limit(5).collect(Collectors.toList());
    for(Student student : studentList){
        System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
    }
}


问:
Is it possible to put a single monitor to sleep using WinAPI/C#?
By using the Windows API it is possible to put the monitors into sleep mode:

```<code>[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
</code>```

and then

```<code>SendMessage(this.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)2);
</code>```

When running the command above, both monitors go to sleep. Is it possible to make this affect only one of multiple connected monitors?

答:
According to this...no.

The reason being is that the API is turning off the display which is defined as both monitors. Turning off a specific monitor would be a hardware tie in.

Body:
By using the Windows API it is possible to put the monitors into sleep mode:

[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

and then

SendMessage(this.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)2);

When running the command above, both monitors go to sleep. Is it possible to make this affect only one of multiple connected monitors?