问:
Multiple d3 charts on a page using the same Angular2 component
I have a horizontal bar chart component that takes a data @Input which will then be used by a chart library horizontalBarChart:

```<code>export class HorizontalBarChartComponent implements OnInit {
  @Input() data: Object[];
  ngOnInit() {
    horizontalBarChart.init({
      id: '#horizontal-bar-chart',
      data: this.data
    });
  }
}
</code>```

Inside horizontal-bar-chart.html:

```<code><div id="horizontal-bar-chart"></div>
</code>```

And d3 selects for the given id in the chart library:

```<code> const svg = d3.select(chartOptions.id)
  .append('svg')
  .attr('width', width + margin.left + margin.right)
  .attr('height', height + margin.top + margin.bottom);
</code>```

Now I would like to generate multiple bar chart, each with different data, in a component page:

```<code>      <div>
        <h6>Group</h6>
        <app-horizontal-bar-chart [data]="data.chart1"</app-horizontal-bar-chart>
      </div>
      <div>
        <h6>Ctp</h6>
        <app-horizontal-bar-chart [data]="data.chart2"</app-horizontal-bar-chart>
      </div>
</code>```

The issue is both charts are generated inside the

 of the FIRST component.

What is the best way to solve this kinda scenario?

EDIT:

The way I currently solve this problem is to give each of the chart component a div placeholder:

```<code>          <div>
            <h6>Group</h6>
            <div id="chart1"></div>  // placeholder
            <app-horizontal-bar-chart [id]="chart1" [data]="data.chart1"</app-horizontal-bar-chart>
          </div>
          <div>
            <h6>Ctp</h6>
            <div id="chart2"></div>  // placeholder
            <app-horizontal-bar-chart [id]="chart2"[data]="data.chart2"</app-horizontal-bar-chart>
          </div>
</code>```

However I'm wondering if there is more of a Angular2 way of solving this, probably using ViewContainerRef or something.

答:
If the idea is just to create a reusable d3-chart component, you don't need an Id. I'd implemented it in the following way:

Chart component:

```<code>@Component({
  selector: 'bar-chart',
  template: `
    <svg width="300" height="200"></svg>
  `,
})
export class BarChart implements OnInit {
  @Input() data: Array<any>;

  constructor(private container: ElementRef) {
  }

  ngOnInit() {
    this.initSvg();
    this.initAxis();
    this.drawAxis();
    this.drawBars();
  }

  private initSvg() {
    // This is how you can select the svg tag
    // related to the current cumponent
    this.svg = d3.select(this.container.nativeElement).select("svg");
    ...
  }

  ...
}
</code>```

Chart consumer component:

```<code>@Component({
  selector: 'my-app',
  template: `
    <bar-chart [data]="dataset1"></bar-chart>
    <bar-chart [data]="dataset2"></bar-chart>
  `,
})
export class App {
  dataset1 = [ ... ];
  dataset2 = [ ... ];
}
</code>```

Here is the Plunkr

Body:
I have a horizontal bar chart component that takes a data @Input which will then be used by a chart library horizontalBarChart:

export class HorizontalBarChartComponent implements OnInit {
  @Input() data: Object[];
  ngOnInit() {
    horizontalBarChart.init({
      id: '#horizontal-bar-chart',
      data: this.data
    });
  }
}

Inside horizontal-bar-chart.html:

And d3 selects for the given id in the chart library:

 const svg = d3.select(chartOptions.id)
  .append('svg')
  .attr('width', width + margin.left + margin.right)
  .attr('height', height + margin.top + margin.bottom);

Now I would like to generate multiple bar chart, each with different data, in a component page:

Group

        <app-horizontal-bar-chart [data]="data.chart1"</app-horizontal-bar-chart>

Ctp

        <app-horizontal-bar-chart [data]="data.chart2"</app-horizontal-bar-chart>

The issue is both charts are generated inside the

 of the FIRST component.

What is the best way to solve this kinda scenario?

EDIT:

The way I currently solve this problem is to give each of the chart component a div placeholder:

Group

  // placeholder
            <app-horizontal-bar-chart [id]="chart1" [data]="data.chart1"</app-horizontal-bar-chart>

Ctp

  // placeholder
            <app-horizontal-bar-chart [id]="chart2"[data]="data.chart2"</app-horizontal-bar-chart>

However I'm wondering if there is more of a Angular2 way of solving this, probably using ViewContainerRef or something.

Body:
If the idea is just to create a reusable d3-chart component, you don't need an Id. I'd implemented it in the following way:

Chart component:

@Component({
  selector: 'bar-chart',
  template: `
    <svg width="300" height="200"></svg>
  `,
})
export class BarChart implements OnInit {
  @Input() data: Array<any>;

  constructor(private container: ElementRef) {
  }

  ngOnInit() {
    this.initSvg();
    this.initAxis();
    this.drawAxis();
    this.drawBars();
  }

  private initSvg() {
    // This is how you can select the svg tag
    // related to the current cumponent
    this.svg = d3.select(this.container.nativeElement).select("svg");
    ...
  }

  ...
}

Chart consumer component:

@Component({
  selector: 'my-app',
  template: `
    <bar-chart [data]="dataset1"></bar-chart>
    <bar-chart [data]="dataset2"></bar-chart>
  `,
})
export class App {
  dataset1 = [ ... ];
  dataset2 = [ ... ];
}

Here is the Plunkr


来源: stackexchange

问:
Pass a string to method CREATE RECORD in 4D
Can i pass a string variable to the 4D CREATE RECORD method ? or any other method i just need to set the name table as a variable.
I already tried to pass a string variable but as the method only accepts table object i can't find any way to do that</p>

答:
If you want to specify the table by name, you have to look it up first, as there is no way to call it up by name. Therefore to access the table named "myTableName":

```<code>$vT_tablename:="myTableName"
GET TABLE TITLES(aT_TableTitles;aL_TableNums)
$vL_MyTable_idx:=find in array(aT_TableTitles;$vT_tablename)
$vL_MyTable_Num:=aL_TableNums{$vL_MyTable_idx}
$vP_MyTable:=table($vL_MyTable_Num)
CREATE RECORD(vP_MyTable->)
</code>```

...

ContentLicense: CC BY-SA 3.0

Body:
If you want to specify the table by name, you have to look it up first, as there is no way to call it up by name. Therefore to access the table named "myTableName":

$vT_tablename:="myTableName"
GET TABLE TITLES(aT_TableTitles;aL_TableNums)
$vL_MyTable_idx:=find in array(aT_TableTitles;$vT_tablename)
$vL_MyTable_Num:=aL_TableNums{$vL_MyTable_idx}
$vP_MyTable:=table($vL_MyTable_Num)
CREATE RECORD(vP_MyTable->)

...


问:
strcat segmentation fault
The second call to strcat here is generating a segmentation fault, why?

```<code>#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

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

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}
</code>```

答:
I tried your code, and also see the segfault on the second strcat().  I found that command[250] is allocated immediately after whitespaceseparator[2] on the stack on my system:

```<code>(gdb) p &whitespaceseparator
$1 = (char (*)[2]) 0xbf90acd4
(gdb) p &command
$2 = (char (*)[250]) 0xbf90acd6
</code>```

e.g. (here command begins "foo..."), things are layed out like this:

```<code> whitespaceseparator
  |
  |      command
  |       |
  v       v
+---+---+---+---+---+---+---+---+
|' '| 0 |'f'|'o'|'o'|'.'|'.'|'.'| ...
+---+---+---+---+---+---+---+---+
</code>```

I can't guarantee that the same happens on your system (layout of locals on the stack may vary even between different versions of the same compiler), but it seems likely.  On mine, here is exactly what happens:

As others have said, strcat() appends the second string to the first (and the result will be equal to the first argument).  So, the first strcat() overflows whitespaceseparator[] (and returns whitespaceseparator as whitespace_and_pid):

```<code>+---+---+---+---+---+---+---+---+
|' '|'1'|'2'|'3'|'4'| 0 |'.'|'.'| ...
+---+---+---+---+---+---+---+---+
</code>```

The second strcat() tries to append whitespace_and_pid (== whitespaceseparator) to the string at command.  The first character of the copy will overwrite the terminating 0 of the string at command:

```<code>  |    ===copy===>    |
  v                   v
+---+---+---+---+---+---+---+---+
|' '|'1'|'2'|'3'|'4'|' '|'.'|'.'| ...
+---+---+---+---+---+---+---+---+
</code>```

The copy continues...

```<code>      |    ===copy===>    |
      v                   v
+---+---+---+---+---+---+---+---+
|' '|'1'|'2'|'3'|'4'|' '|'1'|'.'| ...
+---+---+---+---+---+---+---+---+

          |    ===copy===>    |
          v                   v
+---+---+---+---+---+---+---+---+
|' '|'1'|'2'|'3'|'4'|' '|'1'|'2'| ...
+---+---+---+---+---+---+---+---+
</code>```

and will carry on copying " 1234 1234 1234"... until it falls off the end of the process address space, at which point you get a segfault.

ContentLicense: CC BY-SA 2.5

Title: strcat segmentation fault

Body:
The second call to strcat here is generating a segmentation fault, why?

#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

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

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}

Body:
I tried your code, and also see the segfault on the second strcat().  I found that command[250] is allocated immediately after whitespaceseparator[2] on the stack on my system:

(gdb) p &whitespaceseparator
$1 = (char (*)[2]) 0xbf90acd4
(gdb) p &command
$2 = (char (*)[250]) 0xbf90acd6

e.g. (here command begins "foo..."), things are layed out like this:

 whitespaceseparator
  |
  |      command
  |       |
  v       v
+---+---+---+---+---+---+---+---+
|' '| 0 |'f'|'o'|'o'|'.'|'.'|'.'| ...
+---+---+---+---+---+---+---+---+

I can't guarantee that the same happens on your system (layout of locals on the stack may vary even between different versions of the same compiler), but it seems likely.  On mine, here is exactly what happens:

As others have said, strcat() appends the second string to the first (and the result will be equal to the first argument).  So, the first strcat() overflows whitespaceseparator[] (and returns whitespaceseparator as whitespace_and_pid):

+---+---+---+---+---+---+---+---+
|' '|'1'|'2'|'3'|'4'| 0 |'.'|'.'| ...
+---+---+---+---+---+---+---+---+

The second strcat() tries to append whitespace_and_pid (== whitespaceseparator) to the string at command.  The first character of the copy will overwrite the terminating 0 of the string at command:

  |    ===copy===>    |
  v                   v
+---+---+---+---+---+---+---+---+
|' '|'1'|'2'|'3'|'4'|' '|'.'|'.'| ...
+---+---+---+---+---+---+---+---+

The copy continues...

      |    ===copy===>    |
      v                   v
+---+---+---+---+---+---+---+---+
|' '|'1'|'2'|'3'|'4'|' '|'1'|'.'| ...
+---+---+---+---+---+---+---+---+

          |    ===copy===>    |
          v                   v
+---+---+---+---+---+---+---+---+
|' '|'1'|'2'|'3'|'4'|' '|'1'|'2'| ...
+---+---+---+---+---+---+---+---+

and will carry on copying " 1234 1234 1234"... until it falls off the end of the process address space, at which point you get a segfault.


问:
How do I pass arguments to pkill, over ssh, through java's ProcessBuilder?
I am trying to kill a process, remotely, through the java interface to the shell, using ProcessBuilder.  My code looks like this:

```<code>ProcessBuilder builder = new ProcessBuilder(
  "ssh",
  "user@host",
  "pkill -f \"'instanceId XXXXXX'\"");
Process process = builder.start();
</code>```

Where instanceId XXXXX matches some command line args from the launching of the process.

When I get the final command string, using

```<code>builder.command()
</code>```

it returns

```ssh user@host pkill -f "'instanceId XXXXX'"```

which, when run manually on the command line works.  Unfortunately, when run by the ProcessBuilder, it is incapable of identifying the target process.

After spending far too many hours fighting with arguments over ssh/ProcessBuilder in the last weeks, could someone shed some light on why it's doing this, and maybe point me at some relevant documentation that isn't completely cryptic?

答:
The issue is with the double quotes.

When you run the command on the command line, the shell will interpret either double or single quotes itself. Thus, if you run

```<code>ssh user@host pkill -f 'instanceId XXXXX'
</code>```

(Or the same with double quotes) from command line, it will strip those quotes. Although the local shell considers the string instanceID XXXX as a single argument, the remote shell sees the command as a whole, doesn't see any quotes, and so sees "InstanceId" and "XXXXX" as two separate entities.

For this reason, when you run from command line, you need to add quotes over the quotes. The local shell will strip the external quotes, and ssh will pass the command with the internal quotes, which will cause the remote shell to see the  instanceID XXXX as a single parameter.

However, when you run from a process builder, you don't run from a local shell. You build the arguments yourself, appropriately, and they are sent literally to the ssh. Thus, when you send "'InstanceID XXXX'", what the remote shell will see is "'InstanceID XXXX'". It will only strip one pair, and 'InstanceID XXXX' is not in any processes command line on the remote machine. Not with those quotes...

Thus, when you use a process builder, you should not be quoting the same way you quote when you run directly in the shell. Only a single pair is needed.

Body:
I am trying to kill a process, remotely, through the java interface to the shell, using ProcessBuilder.  My code looks like this:

ProcessBuilder builder = new ProcessBuilder(
  "ssh",
  "user@host",
  "pkill -f \"'instanceId XXXXXX'\"");
Process process = builder.start();

Where instanceId XXXXX matches some command line args from the launching of the process.

When I get the final command string, using

builder.command()

it returns

ssh user@host pkill -f "'instanceId XXXXX'"

which, when run manually on the command line works.  Unfortunately, when run by the ProcessBuilder, it is incapable of identifying the target process.

After spending far too many hours fighting with arguments over ssh/ProcessBuilder in the last weeks, could someone shed some light on why it's doing this, and maybe point me at some relevant documentation that isn't completely cryptic?

Body:
The issue is with the double quotes.

When you run the command on the command line, the shell will interpret either double or single quotes itself. Thus, if you run

ssh user@host pkill -f 'instanceId XXXXX'

(Or the same with double quotes) from command line, it will strip those quotes. Although the local shell considers the string instanceID XXXX as a single argument, the remote shell sees the command as a whole, doesn't see any quotes, and so sees "InstanceId" and "XXXXX" as two separate entities.

For this reason, when you run from command line, you need to add quotes over the quotes. The local shell will strip the external quotes, and ssh will pass the command with the internal quotes, which will cause the remote shell to see the  instanceID XXXX as a single parameter.

However, when you run from a process builder, you don't run from a local shell. You build the arguments yourself, appropriately, and they are sent literally to the ssh. Thus, when you send "'InstanceID XXXX'", what the remote shell will see is "'InstanceID XXXX'". It will only strip one pair, and 'InstanceID XXXX' is not in any processes command line on the remote machine. Not with those quotes...

Thus, when you use a process builder, you should not be quoting the same way you quote when you run directly in the shell. Only a single pair is needed.


问:
how to view custom provider's events(collected without provider registered) by wpa
I try to use manifested base event to log event for debugging and analyzing.
But I have a problem: when I record with my provider registered, everything is fine, when open .etl file in WPA, I can view as much info as I can.
But if I collect events without my provider registered, when I open .etl file in WPA, everything is not human friendly.
So, must I register my provider before I start collect events? I hope not, because if so, I have to take the risk to leak my .man file, so others may use it to get the detail trace log as well. that's not acceptable!

I don't want my .man file packaged in install file, so I do not need to worry about leak it. and of course I can't register my provider as well.

Is there a way to view the .etl (collect without my provider registed first) as well as possible?

thanks in advance.

below are pictures that may make what i said more easy to understand.

image of record without my provider registered:

image of record with my provider registered:

答:
Use EventSource package if you use .Net, which adds manifest into the ETL (ProviderName/ManifestData).

With this way, you don't need to have manifest installed on capture and decode system. The manifest is now part of the ETL.

Of course, If someone gets the ETL, he can use Perfview to dump the Manifest.


问:
Python: I want to execute shell commands using python script
I want to execute shell command "objdump" using python for my research work
I have used subprocess.call("command") to execute linux command but its not working.

Sample code which i have tried is

```<code>import subprocess
subprocess.call("date")
</code>```

after the execution

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\subprocess.py", line 168, in call
    return Popen(*popenargs, **kwargs).wait()
  File "C:\Python27\lib\subprocess.py", line 390, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
</code>```

答:
Have you tried ? </p>

```<code>import subprocess
subprocess.call("date", shell = True)
</code>```

Body:
I want to execute shell command "objdump" using python for my research work
I have used subprocess.call("command") to execute linux command but its not working.

Sample code which i have tried is

import subprocess
subprocess.call("date")

after the execution

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\subprocess.py", line 168, in call
    return Popen(*popenargs, **kwargs).wait()
  File "C:\Python27\lib\subprocess.py", line 390, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

Body:
Have you tried ?

import subprocess
subprocess.call("date", shell = True)


问:
Discard specific sequence of character when using string method find()
Is there any way to achieve this in Python 3+?

I have a string He said:
Hello how are you? which does include those HTML tags as plain text. The method find() returns a index (a position) withing the searched string. Is there perhaps any regex version of find() where I could input this <[^<]+?> as a regex for finding a tag enclosed in < > (or perhaps its negative lookahead) - and so ignore them to look for the word Hello but still get the absolute position within the original string?

For example:

String = He said:
Hello how are you?

Function could be foo(String, "<[^<]+?>", "Hello") as in foo(search in this string, exclude characters matching this regex, look for this

..and get 13 as a position of the word Hello in the original string in return?

答:
re.search('(?:<[^<]+?>)*'.join('Hello'), 'He said:
Hello how are you?').start() returns 12 (13nth character).

If you are not certain that Hello is in the string, you should check if search returns None before calling start.

Body:
re.search('(?:<[^<]+?>)*'.join('Hello'), 'He said: <p>He<i>ll</i>o how are you?').start() returns 12 (13nth character).

If you are not certain that Hello is in the string, you should check if search returns None before calling start.


问:
C# generics - overload based on type traits
I'm new to C# and I want to create a function that accepts any numeric parameter, no matter if it's int/float, signed/unsigned, short/long etc and another function that accepts any other type.

In C++ this can be easily done using SFINAE and std::is_arithmetic:

```<code>template<typename T>
typename std::enable_if<std::is_arithmetic<T>::value>::type DoSomething(T)
{
    std::cout<<"int/float/char..."<<std::endl;
}

template<typename T>
typename std::enable_if<!std::is_arithmetic<T>::value>::type DoSomething(T)
{
    std::cout<<"any other type except int/float..."<<std::endl;
}
</code>```

How may I achieve similar behavior in C#? I don't want to create an overload for every numeric type as the code for all numeric types as the code is exactly the same.

答:
You can't do this in C#. You are stuck with either defining all possible overloads or choosing the "bigger" type that can hold (precisely or not) all the expected values you would have to deal with.

This is an issue that crops up quite often. Read this or this for very knowledgeable information on the subject.

Body:
I'm new to C# and I want to create a function that accepts any numeric parameter, no matter if it's int/float, signed/unsigned, short/long etc and another function that accepts any other type.

In C++ this can be easily done using SFINAE and std::is_arithmetic:

template<typename T>
typename std::enable_if<std::is_arithmetic<T>::value>::type DoSomething(T)
{
    std::cout<<"int/float/char..."<<std::endl;
}

template<typename T>
typename std::enable_if<!std::is_arithmetic<T>::value>::type DoSomething(T)
{
    std::cout<<"any other type except int/float..."<<std::endl;
}

How may I achieve similar behavior in C#? I don't want to create an overload for every numeric type as the code for all numeric types as the code is exactly the same.

ContentLicense: CC BY-SA 4.0


问:
When to use saveUninitialized and resave in express-session
I am newbie with the MEAN stack. I read the express-session github doc but there are some options which are unclear to me. Those options are saveUninitialized and resave.

Can anyone please explain with examples what are the advatanges of using saveUninitialized and resave, and what will the effect be if we change the boolean values in those options.

Syntax:-

```<code>app.use(session({
  resave: false,
  saveUninitialized: true,
}))
</code>```

答: One thing to note is that if you set saveUninitialized to false, the session cookie will not be set on the browser unless the session is modified. That behavior may be implied but it was not clear to me when I was first reading through the documentation.

Body:
I am newbie with the MEAN stack. I read the express-session github doc but there are some options which are unclear to me. Those options are saveUninitialized and resave.

Can anyone please explain with examples what are the advatanges of using saveUninitialized and resave, and what will the effect be if we change the boolean values in those options.

Syntax:-

app.use(session({
  resave: false,
  saveUninitialized: true,
}))


问:
How to stop reading from NetworkStream?
I'm trying to read data from NetworkStream. I write next code:

```<code>Imports System.Net
Imports System.Net.Sockets

Public Class Form1
    Dim tcpclnt1 As New TcpClient
    Dim streamTcp1 As NetworkStream
    Dim DataBuffer(1024) As Byte    'Buffer for reading
    Dim numberOfBytes As Integer
    ' event for reading data from stream
    Dim evtDataArrival As New AsyncCallback(AddressOf DataProcessing)

    Private Sub Btn_Connect5000_Click(sender As Object, e As EventArgs)_
            Handles Btn_Connect5000.Click
        ' Connecting to server
        tcpclnt1 = New TcpClient
        tcpclnt1.Connect("192.168.1.177", 5000)
        streamTcp1 = tcpclnt1.GetStream()   'Create stream for current tcpClient
        ' HERE WE START TO READ
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)

    End Sub

    Public Sub DataProcessing(ByVal dr As IAsyncResult)
        numberOfBytes = streamTcp1.EndRead(dr) 'END READ
        ' ...HERE SOME ROUTINE FOR PRINT DATA TO TEXTBOXES...
        'START NEW READING
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)
    End Sub

    Private Sub Btn_Disconnect5000_Click(sender As Object, e As EventArgs)_
            Handles Btn_Disconnect5000.Click
        ' Disconnect from port 5000. Close TcpClient
        streamTcp1.Dispose()
        streamTcp1.EndRead(Nothing) 'And here mistake appears !!!
        streamTcp1.Close()
        tcpclnt1.Close()
    End Sub
End Class
</code>```

Problem: I  create new client and new stream. By using BeginRead as I understand it starts to read data in new thread. So to do it for real time data, I start new BeginRead at the end of DataProcessing function. But I face the problem when try to disconnect (look at Btn_Disconnect5000_Click function): I try to close stream and client but it sill try to read in DataProcessing method and says me:

Cannot access a disposed object

(Thanks to djv for correct translation!).

So I suppose I need to stop thread first but can't figure out how to do this: I tried Dispose() method, tried close stream first but still can't. Also I tried to call EndRead method manually, but can't understand what I have to assign to it as argument (parameter).

答:
EndRead does not actually stop the asynchronous reading. It gets the amount of bytes read, ends the current read operation and throws any exceptions that might have occurred during the operation. Thus calling it will not stop further async operations from happening.

I suggest you insert a null check in the callback instead which will exit the method and stop BeginRead from being called even more.

```<code>Public Sub DataProcessing(ByVal dr As IAsyncResult)
    If streamTcp1 Is Nothing Then _
        Return 'Stream is disposed, stop any further reading.

    numberOfBytes = streamTcp1.EndRead(dr)
</code>```

As the_lotus says you might also need to add exception handling, because if you are unlucky enough streamTcp1 might get disposed after passing the null check.

The reason why you should check the stream in the callback is because, as we discussed, after "closing" a TCP connection it enters  CLOSE_WAIT, TIME_WAIT or one of the FIN_* states so that the OS can still map late/retransmitted packets to it.

NetworkStream.BeginRead() ultimately calls WSARecv which registers an asynchronous operation on the native side, thus it is not aware if your socket is disposed or not because all it cares about is if the connection is active (CLOSE_WAIT and TIME_WAIT connections are still considered active to the OS). This may cause the callback to be called even if the socket/stream is disposed.

Title: How to stop reading from NetworkStream?

Body:
I'm trying to read data from NetworkStream. I write next code:

Imports System.Net
Imports System.Net.Sockets

Public Class Form1
    Dim tcpclnt1 As New TcpClient
    Dim streamTcp1 As NetworkStream
    Dim DataBuffer(1024) As Byte    'Buffer for reading
    Dim numberOfBytes As Integer
    ' event for reading data from stream
    Dim evtDataArrival As New AsyncCallback(AddressOf DataProcessing)

    Private Sub Btn_Connect5000_Click(sender As Object, e As EventArgs)_
            Handles Btn_Connect5000.Click
        ' Connecting to server
        tcpclnt1 = New TcpClient
        tcpclnt1.Connect("192.168.1.177", 5000)
        streamTcp1 = tcpclnt1.GetStream()   'Create stream for current tcpClient
        ' HERE WE START TO READ
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)

    End Sub

    Public Sub DataProcessing(ByVal dr As IAsyncResult)
        numberOfBytes = streamTcp1.EndRead(dr) 'END READ
        ' ...HERE SOME ROUTINE FOR PRINT DATA TO TEXTBOXES...
        'START NEW READING
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)
    End Sub

    Private Sub Btn_Disconnect5000_Click(sender As Object, e As EventArgs)_
            Handles Btn_Disconnect5000.Click
        ' Disconnect from port 5000. Close TcpClient
        streamTcp1.Dispose()
        streamTcp1.EndRead(Nothing) 'And here mistake appears !!!
        streamTcp1.Close()
        tcpclnt1.Close()
    End Sub
End Class

Problem: I  create new client and new stream. By using BeginRead as I understand it starts to read data in new thread. So to do it for real time data, I start new BeginRead at the end of DataProcessing function. But I face the problem when try to disconnect (look at Btn_Disconnect5000_Click function): I try to close stream and client but it sill try to read in DataProcessing method and says me:

Cannot access a disposed object

(Thanks to djv for correct translation!).

So I suppose I need to stop thread first but can't figure out how to do this: I tried Dispose() method, tried close stream first but still can't. Also I tried to call EndRead method manually, but can't understand what I have to assign to it as argument (parameter).

Body:
EndRead does not actually stop the asynchronous reading. It gets the amount of bytes read, ends the current read operation and throws any exceptions that might have occurred during the operation. Thus calling it will not stop further async operations from happening.

I suggest you insert a null check in the callback instead which will exit the method and stop BeginRead from being called even more.

Public Sub DataProcessing(ByVal dr As IAsyncResult)
    If streamTcp1 Is Nothing Then _
        Return 'Stream is disposed, stop any further reading.

    numberOfBytes = streamTcp1.EndRead(dr)

As the_lotus says you might also need to add exception handling, because if you are unlucky enough streamTcp1 might get disposed after passing the null check.

The reason why you should check the stream in the callback is because, as we discussed, after "closing" a TCP connection it enters  CLOSE_WAIT, TIME_WAIT or one of the FIN_* states so that the OS can still map late/retransmitted packets to it.

NetworkStream.BeginRead() ultimately calls WSARecv which registers an asynchronous operation on the native side, thus it is not aware if your socket is disposed or not because all it cares about is if the connection is active (CLOSE_WAIT and TIME_WAIT connections are still considered active to the OS). This may cause the callback to be called even if the socket/stream is disposed.


问:
change in input with angular 2 dynamic detection
I have a textbox which act as a search text box. I would like to update the search on text change. This is what I tried with:

```<code><input id="searchTextField" [(ngModel)]="searchText" (change)="SearchTextChange()" />
</code>```

and the typescript backend code

```<code>private SearchTextChange(): void
{
//dostuff
}
</code>```

problem is this only gets triggered off when I click somewhere outside of textbox.
It doesn't gets triggered off when on the change of text.
Why is this so?

答:
I suspect this should work for you</p>

```<code>[(ngModel)]="searchText" (ngModelChange)="SearchTextChange()"
</code>```

Body:
I have a textbox which act as a search text box. I would like to update the search on text change. This is what I tried with:

<input id="searchTextField" [(ngModel)]="searchText" (change)="SearchTextChange()" />

and the typescript backend code

private SearchTextChange(): void
{
//dostuff
}

problem is this only gets triggered off when I click somewhere outside of textbox.
It doesn't gets triggered off when on the change of text.
Why is this so?

Body:
I suspect this should work for you

[(ngModel)]="searchText" (ngModelChange)="SearchTextChange()"


问:
Sorting array of structs (missing Len method)
I have two structs defined as below:

```<code>// DuplicatedAd format
type DuplicatedAd struct {
    // Ad Identifier
    AdID int `form:"ad_id" json:"ad_id,omitempty" xml:"ad_id"`
    // Parameters of an Ad, can be empty
    AdParams string `form:"ad_params" json:"ad_params,omitempty" xml:"ad_params"`
    // Body of the Ad
    Body string `form:"body" json:"body,omitempty" xml:"body"`
    // Body Duplicate Percentage
    BodyScore float64 `form:"body_score" json:"body_score,omitempty" xml:"body_score"`
    // Category of the Ad
    Category int `form:"category" json:"category,omitempty" xml:"category"`
    // The ad uploaded main image
    Image string `form:"image,omitempty" json:"image,omitempty" xml:"image,omitempty"`
    // Ad Listing ID
    ListID int `form:"list_id" json:"list_id,omitempty" xml:"list_id"`
    // Listing time for the ad
    ListTime string `form:"list_time" json:"list_time,omitempty" xml:"list_time"`
    // the ad Phone number
    Phone string `form:"phone,omitempty" json:"phone,omitempty" xml:"phone,omitempty"`
    // Region of the Ad
    Region int `form:"region" json:"region,omitempty" xml:"region"`
    // Ad Status
    Status string `form:"status" json:"status,omitempty" xml:"status"`
    // Subject of the Ad
    Subject string `form:"subject" json:"subject,omitempty" xml:"subject"`
    // Subject Duplicate Percentage
    SubjectScore float64 `form:"subject_score" json:"subject_score,omitempty" xml:"subject_score"`
    // Type of the Ad
    Type string `form:"type" json:"type,omitempty" xml:"type"`
    // Total Score
    TotalScore float64 `form:"total_score" json:"total_score,omitempty" xml:"total_score"`
}

// CpResponse format
type CpResponse struct {
    // Number of doublets
    Count int `json:"count"`
    // The Doublet Ads to show
    Duplicated []DuplicatedAd `json:"duplicated"`
}
</code>```

i'm defining a variable var DuplicatedAds = CpResponse{}and in a loop i'm appending some results to it as follow:

```<code>DuplicatedAds.Duplicated = append(DuplicatedAds.Duplicated, t)
DuplicatedAds.Count = len(DuplicatedAds.Duplicated)
</code>```

i wish that the DuplicatedAds.Duplicated be sorted by TotalScore.

i'm new to golang, so after a little research i found out that i must implement theses three functions before i can sort

```<code>func (slice DuplicatedAd) Len() int {
    return len(slice)
}

func (slice DuplicatedAd) Less(i, j int) bool {
    return slice[i].TotalScore < slice[j].TotalScore
}

func (slice DuplicatedAd) Swap(i, j int) {
    slice[i], slice[j] = slice[j], slice[i]
}
</code>```

but when i try to compile i get this errors:

```<code>./duplicates.go:165: cannot use DuplicatedAds.Duplicated (type []DuplicatedAd) as type sort.Interface in argument to sort.Sort:
    []DuplicatedAd does not implement sort.Interface (missing Len method)
./types.go:68: invalid argument slice (type DuplicatedAd) for len
./types.go:72: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
./types.go:72: invalid operation: slice[j] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[j] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
</code>```

How could i have an CpResponse object which his Duplicated array is sorted by DuplicatedAd.TotalScore ?

答:
cd1 offers a good solution. As for the reason your methods aren't working, it's because they're operating on a single struct and not a slice of structs.

You would want something more like this where each method works on the DuplicatedAdSlice type rather than the DuplicatedAd type.

```<code>type DuplicatedAdSlice []DuplicatedAd // Type alias

func (slice DuplicatedAdSlice) Len() int {
    return len(slice)
}
</code>```

And update the CpResponse struct to use the type alias

```<code>// The Doublet Ads to show
Duplicated DuplicatedAdSlice `json:"duplicated"`
</code>```

Body:
I have two structs defined as below:

// DuplicatedAd format
type DuplicatedAd struct {
    // Ad Identifier
    AdID int `form:"ad_id" json:"ad_id,omitempty" xml:"ad_id"`
    // Parameters of an Ad, can be empty
    AdParams string `form:"ad_params" json:"ad_params,omitempty" xml:"ad_params"`
    // Body of the Ad
    Body string `form:"body" json:"body,omitempty" xml:"body"`
    // Body Duplicate Percentage
    BodyScore float64 `form:"body_score" json:"body_score,omitempty" xml:"body_score"`
    // Category of the Ad
    Category int `form:"category" json:"category,omitempty" xml:"category"`
    // The ad uploaded main image
    Image string `form:"image,omitempty" json:"image,omitempty" xml:"image,omitempty"`
    // Ad Listing ID
    ListID int `form:"list_id" json:"list_id,omitempty" xml:"list_id"`
    // Listing time for the ad
    ListTime string `form:"list_time" json:"list_time,omitempty" xml:"list_time"`
    // the ad Phone number
    Phone string `form:"phone,omitempty" json:"phone,omitempty" xml:"phone,omitempty"`
    // Region of the Ad
    Region int `form:"region" json:"region,omitempty" xml:"region"`
    // Ad Status
    Status string `form:"status" json:"status,omitempty" xml:"status"`
    // Subject of the Ad
    Subject string `form:"subject" json:"subject,omitempty" xml:"subject"`
    // Subject Duplicate Percentage
    SubjectScore float64 `form:"subject_score" json:"subject_score,omitempty" xml:"subject_score"`
    // Type of the Ad
    Type string `form:"type" json:"type,omitempty" xml:"type"`
    // Total Score
    TotalScore float64 `form:"total_score" json:"total_score,omitempty" xml:"total_score"`
}

// CpResponse format
type CpResponse struct {
    // Number of doublets
    Count int `json:"count"`
    // The Doublet Ads to show
    Duplicated []DuplicatedAd `json:"duplicated"`
}

i'm defining a variable var DuplicatedAds = CpResponse{}and in a loop i'm appending some results to it as follow:

DuplicatedAds.Duplicated = append(DuplicatedAds.Duplicated, t)
DuplicatedAds.Count = len(DuplicatedAds.Duplicated)

i wish that the DuplicatedAds.Duplicated be sorted by TotalScore.

i'm new to golang, so after a little research i found out that i must implement theses three functions before i can sort

func (slice DuplicatedAd) Len() int {
    return len(slice)
}

func (slice DuplicatedAd) Less(i, j int) bool {
    return slice[i].TotalScore < slice[j].TotalScore
}

func (slice DuplicatedAd) Swap(i, j int) {
    slice[i], slice[j] = slice[j], slice[i]
}

but when i try to compile i get this errors:

./duplicates.go:165: cannot use DuplicatedAds.Duplicated (type []DuplicatedAd) as type sort.Interface in argument to sort.Sort:
    []DuplicatedAd does not implement sort.Interface (missing Len method)
./types.go:68: invalid argument slice (type DuplicatedAd) for len
./types.go:72: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
./types.go:72: invalid operation: slice[j] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[i] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[j] (type DuplicatedAd does not support indexing)
./types.go:76: invalid operation: slice[i] (type DuplicatedAd does not support indexing)

How could i have an CpResponse object which his Duplicated array is sorted by DuplicatedAd.TotalScore ?

Body:
cd1 offers a good solution. As for the reason your methods aren't working, it's because they're operating on a single struct and not a slice of structs.

You would want something more like this where each method works on the DuplicatedAdSlice type rather than the DuplicatedAd type.

type DuplicatedAdSlice []DuplicatedAd // Type alias

func (slice DuplicatedAdSlice) Len() int {
    return len(slice)
}

And update the CpResponse struct to use the type alias

// The Doublet Ads to show
Duplicated DuplicatedAdSlice `json:"duplicated"`


问:
Can I store an object constructor into an array or hashtable?
Let's say I have a class Foo and another class Bar that both extends from a superclass Foobar, each one with it's own  constructor.

So, I want to make an application in Java 8 that let's a user choose from a list of objects to implement, and add them to a list —I was thinking of using an array or hashtable—, in this case I want to show a message like:

```<code>Choose an object of the following list:
 [1] Foo
 [2] Bar
</code>```

The idea is to let the user create multiple instances of such classes and add them to an array. For example, if the user chooses 1, I want to assign a variable with a[0] = new Foo(), and then if he chooses 2, a[1] = new Bar(), but then, if the user chooses 1 again, then a[2] should be a new instance of Foo. My first idea was to initialize an array with the constructors like:

```<code>anArray[1] = new Foo();
anArray[2] = new Bar();
</code>```

The problem with that implementation is that if I call a[0] = anArray[1] and then a[1] = anArray[1], then a[0]and a[1] would be the same object.

What I am looking for is if there is a way of creating an undefined number of instances of each object without having to implement it as a chain of if else (because in reality I have more than 2 type of objects). I was thinking of using an array or a hashtable, but I don't know if there is actually a way of doing it.

答: You are looking for the Factory pattern. In java 8 you can do it quite succinctly using lambda expressions.</p>

Body:
Let's say I have a class Foo and another class Bar that both extends from a superclass Foobar, each one with it's own  constructor.

So, I want to make an application in Java 8 that let's a user choose from a list of objects to implement, and add them to a list —I was thinking of using an array or hashtable—, in this case I want to show a message like:

Choose an object of the following list:
 [1] Foo
 [2] Bar

The idea is to let the user create multiple instances of such classes and add them to an array. For example, if the user chooses 1, I want to assign a variable with a[0] = new Foo(), and then if he chooses 2, a[1] = new Bar(), but then, if the user chooses 1 again, then a[2] should be a new instance of Foo. My first idea was to initialize an array with the constructors like:

anArray[1] = new Foo();
anArray[2] = new Bar();

The problem with that implementation is that if I call a[0] = anArray[1] and then a[1] = anArray[1], then a[0]and a[1] would be the same object.

What I am looking for is if there is a way of creating an undefined number of instances of each object without having to implement it as a chain of if else (because in reality I have more than 2 type of objects). I was thinking of using an array or a hashtable, but I don't know if there is actually a way of doing it.


问:
PHP MongoDB manager exception for aggregate command: "Failed to decode document from the server."
My Sample collection:

```<code>{
    "_id" : ObjectId("58dbc09b19d7a17e44201982"),
    "process_id" : "2-1490770330177",
    "contacts" : [
        {
            "party_id" : 6636,
            "completed" : true,
            "kind" : 1
        },
        {
            "party_id" : 139611,
            "completed" : true,
            "kind" : 1
        },
        {
            "party_id" : 32609,
            "completed" : true,
            "kind" : 1
        },

        {
            "party_id" : 49520,
            "completed" : false,
            "kind" : 1
        },
        {
            "party_id" : 204031,
            "completed" : false,
            "kind" : 1
        },
        {
            "party_id" : 204379,
            "completed" : false,
            "kind" : 1
        }
    ],
    "tags" : [
        1277
    ]
}
</code>```

And When I test this document with RoboMongo via followig query:

```<code>db.getCollection('BatchTag').aggregate(
                        {'$match':{"process_id":'2-1490770330177'}},
                        {'$unwind':'$contacts'},
                        {'$match':{'contacts.completed':false}},
                        {'$group':{_id:'$_id','contacts':{'$push':'$contacts'}}}
    )
</code>```

I've received this result.

```<code>{
    "_id" : ObjectId("58dbc09b19d7a17e44201982"),
    "contacts" : [
        {
            "party_id" : 49520,
            "completed" : false,
            "kind" : 1
        },
        {
            "party_id" : 204031,
            "completed" : false,
            "kind" : 1
        },
        {
            "party_id" : 204379,
            "completed" : false,
            "kind" : 1
        }
    ]
}
</code>```

Bu When I execute some query on PHP. I've received "Failed to decode document from the server." exception.
My PHP code is here:

```<code>            $command = new Command([
                "aggregate"=>"BatchTag",
                "pipeline" => [
                    ['$match'=>["process_id"=>$processUID]],
                    ['$unwind'=>'$contacts'],
                    ['$match'=>['contacts.completed'=>false]],
                    ['$group'=>['_id'=>'$_id','contacts'=>['$push'=>'$contacts']]]
                ]
            ]);
            $rows = $this->getMongoManager()->executeCommand($this->container->getParameter("mongodb_db_name").".BatchTag",$command)->toArray();
</code>```

I don't understand, what is wrong!

答:
You are passing the collection name too to the executeCommand.

You should only pass db name as command obj already has collection name.

Try something like

```<code>$rows = $this->getMongoManager()->executeCommand($this->container->getParameter("mongodb_db_name"),$command)->toArray();
</code>```

Body:
My Sample collection:

{
    "_id" : ObjectId("58dbc09b19d7a17e44201982"),
    "process_id" : "2-1490770330177",
    "contacts" : [
        {
            "party_id" : 6636,
            "completed" : true,
            "kind" : 1
        },
        {
            "party_id" : 139611,
            "completed" : true,
            "kind" : 1
        },
        {
            "party_id" : 32609,
            "completed" : true,
            "kind" : 1
        },

        {
            "party_id" : 49520,
            "completed" : false,
            "kind" : 1
        },
        {
            "party_id" : 204031,
            "completed" : false,
            "kind" : 1
        },
        {
            "party_id" : 204379,
            "completed" : false,
            "kind" : 1
        }
    ],
    "tags" : [
        1277
    ]
}

And When I test this document with RoboMongo via followig query:

db.getCollection('BatchTag').aggregate(
                        {'$match':{"process_id":'2-1490770330177'}},
                        {'$unwind':'$contacts'},
                        {'$match':{'contacts.completed':false}},
                        {'$group':{_id:'$_id','contacts':{'$push':'$contacts'}}}
    )

I've received this result.

{
    "_id" : ObjectId("58dbc09b19d7a17e44201982"),
    "contacts" : [
        {
            "party_id" : 49520,
            "completed" : false,
            "kind" : 1
        },
        {
            "party_id" : 204031,
            "completed" : false,
            "kind" : 1
        },
        {
            "party_id" : 204379,
            "completed" : false,
            "kind" : 1
        }
    ]
}

Bu When I execute some query on PHP. I've received "Failed to decode document from the server." exception.
My PHP code is here:

            $command = new Command([
                "aggregate"=>"BatchTag",
                "pipeline" => [
                    ['$match'=>["process_id"=>$processUID]],
                    ['$unwind'=>'$contacts'],
                    ['$match'=>['contacts.completed'=>false]],
                    ['$group'=>['_id'=>'$_id','contacts'=>['$push'=>'$contacts']]]
                ]
            ]);
            $rows = $this->getMongoManager()->executeCommand($this->container->getParameter("mongodb_db_name").".BatchTag",$command)->toArray();

I don't understand, what is wrong!

Body:
You are passing the collection name too to the executeCommand.

You should only pass db name as command obj already has collection name.

Try something like

$rows = $this->getMongoManager()->executeCommand($this->container->getParameter("mongodb_db_name"),$command)->toArray();


问:
Continuation token - CreateDocumentQuery ExecuteNextAsync function not exist
I develop in c# in azure documentDB platform .
I try to implement paging architecture in my application .
My code :

```<code>var userQuery = _client.CreateDocumentQuery<User>(
                _uriUsersCollection, queryStr, options).AsDocumentQuery();
</code>```

my code show error on the  AsDocumentQuery() function (it's not recognize as part of the IQueryable methods (I see several example in the internet that the function is recognize ).So when I try to activate the query.ExecuteNextAsync it is not exist.
I work with Microsoft.Azure.Documents.Client dll version 1.11.0.0.
Thanks for your help
MAK

答:
For scenarios with Continuation Token I often use this helper class:

```<code>public class PagedResults<T>
{
    public PagedResults()
    {
        Results = new List<T>();
    }
    /// <summary>
    /// Continuation Token for DocumentDB
    /// </summary>
    public string ContinuationToken { get; set; }

    /// <summary>
    /// Results
    /// </summary>
    public List<T> Results { get; set; }
}
</code>```

With this extension:

```<code>public static async Task<PagedResults<T>> ToPagedResults<T>(this IQueryable<T> source)
{
    var documentQuery = source.AsDocumentQuery();
    var results = new PagedResults<T>();

    try
    {
        var queryResult = await documentQuery.ExecuteNextAsync<T>();
        if (!queryResult.Any())
        {
            return results;
        }
        results.ContinuationToken = queryResult.ResponseContinuation;
        results.Results.AddRange(queryResult);
    }
    catch
    {
        //documentQuery.ExecuteNextAsync throws an Exception if there are no results
        return results;
    }

    return results;
}
</code>```

Now, you can use it in your code more or less like this:

```<code>var options = new FeedOptions() { MaxItemCount = 20 };//If 20 is your page size
var continuationToken = string.Empty;
var allResults = new List<User>();
do{
    if (!string.IsNullOrEmpty(continuationToken))
    {
            options.RequestContinuation = continuationToken;
    }
    var userQuery = _client.CreateDocumentQuery<User>(_uriUsersCollection, queryStr, options).ToPagedResults();
    continuationToken = userQuery.ContinuationToken;
    allResults.AddRange(userQuery.Results);
}while(!string.IsNullOrEmpty(continuationToken));
</code>```

Body:
I develop in c# in azure documentDB platform .
I try to implement paging architecture in my application .
My code :

var userQuery = _client.CreateDocumentQuery<User>(
                _uriUsersCollection, queryStr, options).AsDocumentQuery();

my code show error on the  AsDocumentQuery() function (it's not recognize as part of the IQueryable methods (I see several example in the internet that the function is recognize ).So when I try to activate the query.ExecuteNextAsync it is not exist.
I work with Microsoft.Azure.Documents.Client dll version 1.11.0.0.
Thanks for your help
MAK

Body:
For scenarios with Continuation Token I often use this helper class:

public class PagedResults<T>
{
    public PagedResults()
    {
        Results = new List<T>();
    }
    /// <summary>
    /// Continuation Token for DocumentDB
    /// </summary>
    public string ContinuationToken { get; set; }

    /// <summary>
    /// Results
    /// </summary>
    public List<T> Results { get; set; }
}

With this extension:

public static async Task<PagedResults<T>> ToPagedResults<T>(this IQueryable<T> source)
{
    var documentQuery = source.AsDocumentQuery();
    var results = new PagedResults<T>();

    try
    {
        var queryResult = await documentQuery.ExecuteNextAsync<T>();
        if (!queryResult.Any())
        {
            return results;
        }
        results.ContinuationToken = queryResult.ResponseContinuation;
        results.Results.AddRange(queryResult);
    }
    catch
    {
        //documentQuery.ExecuteNextAsync throws an Exception if there are no results
        return results;
    }

    return results;
}

Now, you can use it in your code more or less like this:

var options = new FeedOptions() { MaxItemCount = 20 };//If 20 is your page size
var continuationToken = string.Empty;
var allResults = new List<User>();
do{
    if (!string.IsNullOrEmpty(continuationToken))
    {
            options.RequestContinuation = continuationToken;
    }
    var userQuery = _client.CreateDocumentQuery<User>(_uriUsersCollection, queryStr, options).ToPagedResults();
    continuationToken = userQuery.ContinuationToken;
    allResults.AddRange(userQuery.Results);
}while(!string.IsNullOrEmpty(continuationToken));


问:
Python3 Django -> HTML to PDF
There are a lot of different ways of generating pdfs from a django webpage in python2. The most clean, probably, is pisa and reportlab.
These do not work for python3 though.

So far, the only method I've had success with is to render the template, write it to a file, and then use wkhtmltopdf via subprocess.popen. This works alright, but it doesn't load any of my static files, such as css and images.

Are there any proper solutions? can wkhtmltopdf read my staticfiles from the command line, in some way, or is there a library like pisa/reportlab, which supports python3?

I haven't been able to finde such a library

答:
I looked into Weasyprint, wkhtmltopdf and even LaTeX, but all have external binary dependencies that are difficult to deploy to services such as Heroku.

The best combination I found so far that works in Django on Python 3 is using Reportlab (now works on Python 3) + xhtml2pdf. xhtml2pdf only recently added beta Python 3 support so you need to install it with:

```<code>pip install --pre xhtml2pdf
</code>```

If you have these two installed, you can either use xhtml2pdf directly or install the django-easy-pdf package which provides a TemplateView to inherit from and an example base template & styling to get you started quickly. Follow their quickstart instructions and you can quickly prepare something like a detail view that renders to PDF like:

```<code>class InvoicePDFView(PDFTemplateView):
    template_name = "invoice_pdf.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        myinstance = get_object_or_404(MyModel, pk=context['pk'])
        context['myinstance'] = myinstance
        return context
</code>```

And in your urls.py you'd add something like:

```<code>url(r'invoice/(?P<pk>[^/]+)/$', InvoicePDFView.as_view(), name='invoice')
</code>```

Title: Python3 Django -> HTML to PDF

Body:
I looked into Weasyprint, wkhtmltopdf and even LaTeX, but all have external binary dependencies that are difficult to deploy to services such as Heroku.

The best combination I found so far that works in Django on Python 3 is using Reportlab (now works on Python 3) + xhtml2pdf. xhtml2pdf only recently added beta Python 3 support so you need to install it with:

pip install --pre xhtml2pdf

If you have these two installed, you can either use xhtml2pdf directly or install the django-easy-pdf package which provides a TemplateView to inherit from and an example base template & styling to get you started quickly. Follow their quickstart instructions and you can quickly prepare something like a detail view that renders to PDF like:

class InvoicePDFView(PDFTemplateView):
    template_name = "invoice_pdf.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        myinstance = get_object_or_404(MyModel, pk=context['pk'])
        context['myinstance'] = myinstance
        return context

And in your urls.py you'd add something like:

url(r'invoice/(?P<pk>[^/]+)/$', InvoicePDFView.as_view(), name='invoice')


答:
Because your time range is large, it is interesting to use an interactive plot, where you can zoom in. To that end you could use the package vistime. After installing the package, run the following code:

```<code># your code
site <- c("LA", "LA", "LA", "WR", "WR", "WR", "SS", "SS", "SS", "SS")
startdate <- as.Date(c('1601-01-01', '1836-01-01','1672-01-01','1912-01-01','1946-01-01', '1835-01-01','1454-01-01','1672-01-01','1877-01-01','1978-01-01'))
enddate <-as.Date(c('1605-01-01','1841-01-01','1676-01-01','1918-01-01','1951-01-01', '1839-01-01','1459-01-01','1676-01-01','1881-01-01','1983-01-01'))
data.frame <-data.frame(site, startdate, enddate)

# new code
library(vistime)
vistime(data = data.frame, events = "site" ,start="startdate", end = "enddate")
</code>```

it takes the events (the site) with startdate and enddate and plots it.
You may zoom in using the mouse, other options are in the buttons at the top-right.

Title: How to create a floating bar graph that identifies similar events with a sequence of start and end dates

Body:
I am trying to create the following image using ggplot2. The code I have attempted isn't working at all, so I'd be happy with any suggestions with a fresh approach.

site <- c("LA", "LA", "LA", "WR", "WR", "WR", "SS", "SS", "SS", "SS")
startdate <- as.Date(c('1601-01-01', '1836-01-01','1672-01-01','1912-01-01','1946-01-01',
                       '1835-01-01','1454-01-01','1672-01-01','1877-01-01','1978-01-01'))
enddate <-as.Date(c('1605-01-01','1841-01-01','1676-01-01','1918-01-01','1951-01-01',
                    '1839-01-01','1459-01-01','1676-01-01','1881-01-01','1983-01-01'))

data.frame <-data.frame(site, startdate, enddate)

Body:
Because your time range is large, it is interesting to use an interactive plot, where you can zoom in. To that end you could use the package vistime. After installing the package, run the following code:

# your code
site <- c("LA", "LA", "LA", "WR", "WR", "WR", "SS", "SS", "SS", "SS")
startdate <- as.Date(c('1601-01-01', '1836-01-01','1672-01-01','1912-01-01','1946-01-01', '1835-01-01','1454-01-01','1672-01-01','1877-01-01','1978-01-01'))
enddate <-as.Date(c('1605-01-01','1841-01-01','1676-01-01','1918-01-01','1951-01-01', '1839-01-01','1459-01-01','1676-01-01','1881-01-01','1983-01-01'))
data.frame <-data.frame(site, startdate, enddate)

# new code
library(vistime)
vistime(data = data.frame, events = "site" ,start="startdate", end = "enddate")

it takes the events (the site) with startdate and enddate and plots it.
You may zoom in using the mouse, other options are in the buttons at the top-right.


问:
PHP date returning wrong Month on subtracting one month
Current Date is 29th March 2017

When I subtract 2 months using PHP and I get January

```<code>$prevmonth = date('M', strtotime('-2 months'));
echo $prevmonth;
</code>```

But when I subtract 1 month it gives March

```<code>$prevmonth = date('M', strtotime('-1 months'));
echo $prevmonth;
</code>```

答:
As covered in the comments, there's no 29th Feb.

29th Feb becomes 1st March.

You may be better to get the current month number, -1 from it, and then get the textual representation.

```<code>$prevMonth = date('n') - 1;
$prevMonthText = date('M', mktime(0, 0, 0, $prevMonth, 10));
</code>```

Or, you could use DateTime if your PHP version allows (it should).

```<code>$prevMonth = date('n') - 1;
$dateObj   = DateTime::createFromFormat('!m', $prevMonth);
$monthName = $dateObj->format('M'); // March
</code>```

The only issue with this, that you might have spotted, is January will never return December. A quick ternary statement will catch that.

```<code>$prevMonth = ((date('n') - 1) < 1) ? 12 : date('n') - 1;
</code>```

Body:
Current Date is 29th March 2017

When I subtract 2 months using PHP and I get January

$prevmonth = date('M', strtotime('-2 months'));
echo $prevmonth;

But when I subtract 1 month it gives March

$prevmonth = date('M', strtotime('-1 months'));
echo $prevmonth;

Body:
As covered in the comments, there's no 29th Feb.

29th Feb becomes 1st March.

You may be better to get the current month number, -1 from it, and then get the textual representation.

$prevMonth = date('n') - 1;
$prevMonthText = date('M', mktime(0, 0, 0, $prevMonth, 10));

Or, you could use DateTime if your PHP version allows (it should).

$prevMonth = date('n') - 1;
$dateObj   = DateTime::createFromFormat('!m', $prevMonth);
$monthName = $dateObj->format('M'); // March

The only issue with this, that you might have spotted, is January will never return December. A quick ternary statement will catch that.

$prevMonth = ((date('n') - 1) < 1) ? 12 : date('n') - 1;


问:
Regex doesn't match in Kotlin
I can't understand why this simple regex doesn't match anything. It always fails and throws exception:</p>

```<code>    val match = Regex("""\d+""").matchEntire("A123B")?: throw Exception("Regex fail")
</code>```

答:
You want to match an entire input with matchEntire and a \d+ pattern:

fun matchEntire(input: CharSequence): MatchResult? (source)

  Attempts to match the entire input CharSequence against the pattern.

  Return An instance of MatchResult if the entire input matches or null otherwise.

However, A123B does not only consist of digits. If you need to find a partial match, use find.

Title: Regex doesn't match in Kotlin

Body:
I can't understand why this simple regex doesn't match anything. It always fails and throws exception:

    val match = Regex("""\d+""").matchEntire("A123B")?: throw Exception("Regex fail")


问:
circleci 2.0 can't find awscli
I'm using circleCI 2.0 and they can't find aws but their documents clearly say that aws is installed in default

when I use this circle.yml

```<code>version: 2
jobs:
  build:
    working_directory: ~/rian
    docker:
        - image: node:boron
    steps:
        - checkout
        - run:
            name: Pre-Dependencies
            command: mkdir ~/rian/artifacts
        - restore_cache:
            keys:
              - rian-{{ .Branch }}-{{ checksum "yarn.lock" }}
              - rian-{{ .Branch }}
              - rian-master
        - run:
            name: Install Dependencies
            command: yarn install
        - run:
            name: Test
            command: |
              node -v
              yarn run test:ci
        - save_cache:
            key: rian-{{ .Branch }}-{{ checksum "yarn.lock" }}
            paths:
              - "~/.cache/yarn"
        - store_artifacts:
            path: ~/rian/artifacts
            destination: prefix
        - store_test_results:
            path: ~/rian/test-results
        - deploy:
            command: aws s3 sync ~/rian s3://rian-s3-dev/ --delete
</code>```

following error occurs:

```<code>/bin/bash: aws: command not found
Exited with code 127
</code>```

so if I edit the code this way

```<code>    - deploy:
        command: |
          apt-get install awscli
          aws s3 sync ~/rian s3://rian-s3-dev/ --delete
</code>```

then i get another kind of error:

```<code>Reading package lists... Done

Building dependency tree

Reading state information... Done

E: Unable to locate package awscli
Exited with code 100
</code>```

Anyone knows how to fix this???

答:
The document you are reading is for CircleCI 1.0 and for 2.0 is here:

https://circleci.com/docs/2.0/

In CircleCI 2.0, you can use your favorite Docker image. The image you are currently setting is node:boron, which does not include the aws command.

https://hub.docker.com/_/node/

https://github.com/nodejs/docker-node/blob/14681db8e89c0493e8af20657883fa21488a7766/6.10/Dockerfile

If you just want to make it work for now, you can install the aws command yourself in circle.yml.

```<code>apt-get update && apt-get install -y awscli
</code>```

However, to take full advantage of Docker's benefits, it is recommended that you build a custom Docker image that contains the necessary dependencies such as the aws command.

You can write your custom aws-cli Docker image something like this:

```<code>FROM circleci/python:3.7-stretch

ENV AWS_CLI_VERSION=1.16.138
RUN sudo pip install awscli==${AWS_CLI_VERSION}
</code>```

Title: circleci 2.0 can't find awscli

Body:
I'm using circleCI 2.0 and they can't find aws but their documents clearly say that aws is installed in default

when I use this circle.yml

version: 2
jobs:
  build:
    working_directory: ~/rian
    docker:
        - image: node:boron
    steps:
        - checkout
        - run:
            name: Pre-Dependencies
            command: mkdir ~/rian/artifacts
        - restore_cache:
            keys:
              - rian-{{ .Branch }}-{{ checksum "yarn.lock" }}
              - rian-{{ .Branch }}
              - rian-master
        - run:
            name: Install Dependencies
            command: yarn install
        - run:
            name: Test
            command: |
              node -v
              yarn run test:ci
        - save_cache:
            key: rian-{{ .Branch }}-{{ checksum "yarn.lock" }}
            paths:
              - "~/.cache/yarn"
        - store_artifacts:
            path: ~/rian/artifacts
            destination: prefix
        - store_test_results:
            path: ~/rian/test-results
        - deploy:
            command: aws s3 sync ~/rian s3://rian-s3-dev/ --delete

following error occurs:

/bin/bash: aws: command not found
Exited with code 127

so if I edit the code this way

    - deploy:
        command: |
          apt-get install awscli
          aws s3 sync ~/rian s3://rian-s3-dev/ --delete

then i get another kind of error:

Reading package lists... Done

Building dependency tree

Reading state information... Done

E: Unable to locate package awscli
Exited with code 100

Anyone knows how to fix this???

Body:
The document you are reading is for CircleCI 1.0 and for 2.0 is here:

https://circleci.com/docs/2.0/

In CircleCI 2.0, you can use your favorite Docker image. The image you are currently setting is node:boron, which does not include the aws command.

https://hub.docker.com/_/node/

https://github.com/nodejs/docker-node/blob/14681db8e89c0493e8af20657883fa21488a7766/6.10/Dockerfile

If you just want to make it work for now, you can install the aws command yourself in circle.yml.

apt-get update && apt-get install -y awscli

However, to take full advantage of Docker's benefits, it is recommended that you build a custom Docker image that contains the necessary dependencies such as the aws command.

You can write your custom aws-cli Docker image something like this:

FROM circleci/python:3.7-stretch

ENV AWS_CLI_VERSION=1.16.138
RUN sudo pip install awscli==${AWS_CLI_VERSION}


问:
AccessToken changes between calls
With the Facebook C# SDK, are you supposed to create an instance many times?

app = new Facebook.FacebookApp();

When I do, i get a new accessToken in the session and then i get an error

{"Error validating access token."}

Has anyone seen this?

12/7/2010 - Update on this error.  I'm able to replicate this.  It is related to login in and out with two user accounts and keeping the checkbox for "Keep me logged in" selected.

I have modified the Facebook.Samples.MvcFacebookApp given with the SDK to reproduce.  Nathan if there is a way i can send you this or post it somewhere let me know.

How to replicate while debugging in Visual Studio (running localhost on port 8181)

Login with User 1 with "Keep me logged in" selected.

Make calls to the Graph API (like getting user information) - this should prompt for granting permissions.

Log out.

Stop debugging

Run project and log in with User 2 with "Keep me logged in" selected.

IMPORTANT: This user is new to app and you would expect for the permissions prompt that never will show.

Perform same action that calls Graph API to get user info (name, picture, etc.) as before with this user.

You get the 'Error Validating access token' message.

答:
You can create an instance of FacebookApp with the default constructor as long as you are in the context of an HttpRequest to read the access token.

There shouldn't be a problem with what you are doing, but if you include more code I could be more specific.

Title: AccessToken changes between calls


问:
C# - Getting the 3 lowest values in a List, measured by a public property of the objects within the List
Sorry if my terminology is not great, I'm not a professional programmer.

I have a List< Something >, whereby the 'Something' is a struct. This struct contains objects, which each have their own public properties/fields in the classes. I want to sort the list in order - but by the values found in these nested properties/fields. Then I want to return a list of these values, not the structs.

I know this is very confusing but I've had trouble trying to do it. At the moment I just get a list returned with a count of 20 (which is the full data set I'm using), but I want the 3 values only with the smallest value.

For context and further explanation, here is some code I'm using:

```<code>        // Returns 3 nearest stations to the location specified
    public static List<TrainStation> nearbyStations(GeoCoordinate location)
    {
        List<StationWalk> stations = new List<StationWalk>();
        foreach (TrainStation s in All)
        {
            stations.Add(new StationWalk(s, new Walk(location, s.location)));
        }

        // return 3 TrainStation objects that have the lowest StationWalk.Walk.duration values corresponding with them in the StationWalk struct
        stations.OrderBy(walks => walks.walk.duration).Take(3);

        List<TrainStation> returnList = new List<TrainStation>();
        foreach (StationWalk s in stations)
        {
            returnList.Add(s.station);
        }
        return returnList;
    }

    private struct StationWalk
    {
        public StationWalk(TrainStation station, Walk walk)
        {
            this.station = station;
            this.walk = walk;
        }

        public TrainStation station;
        public Walk walk;
    }
</code>```

'Walk' is a class that contains a 'duration' field. This represents the time it takes to walk. More specifically, my overall goal here is to figure out which 3 walks are the fastest walks out of all 20 in the list. But the 'walks' are properties of the StationWalk struct, and the 'duration' is a property of the Walk.

How would I go about doing this? Really sorry if this isn't well explained, it's confusing to myself despite writing it myself, yet alone trying to explain it to others.Appreciate any help.

答:
The OrderBy and Take both return a new collection, they do not modify the existing collection, so you would need to store the reference to new collection returned by the methods like:

```<code>stations =  stations.OrderBy(walks => walks.walk.duration).Take(3).ToList();
</code>```

and if you want to keep reference to the original list for further usage down in your code, then just store the result in a local variable:

```<code>var lowestThreeStations =  stations.OrderBy(walks => walks.walk.duration).Take(3).ToList();
</code>```

Body:
Sorry if my terminology is not great, I'm not a professional programmer.

I have a List< Something >, whereby the 'Something' is a struct. This struct contains objects, which each have their own public properties/fields in the classes. I want to sort the list in order - but by the values found in these nested properties/fields. Then I want to return a list of these values, not the structs.

I know this is very confusing but I've had trouble trying to do it. At the moment I just get a list returned with a count of 20 (which is the full data set I'm using), but I want the 3 values only with the smallest value.

For context and further explanation, here is some code I'm using:

        // Returns 3 nearest stations to the location specified
    public static List<TrainStation> nearbyStations(GeoCoordinate location)
    {
        List<StationWalk> stations = new List<StationWalk>();
        foreach (TrainStation s in All)
        {
            stations.Add(new StationWalk(s, new Walk(location, s.location)));
        }

        // return 3 TrainStation objects that have the lowest StationWalk.Walk.duration values corresponding with them in the StationWalk struct
        stations.OrderBy(walks => walks.walk.duration).Take(3);

        List<TrainStation> returnList = new List<TrainStation>();
        foreach (StationWalk s in stations)
        {
            returnList.Add(s.station);
        }
        return returnList;
    }

    private struct StationWalk
    {
        public StationWalk(TrainStation station, Walk walk)
        {
            this.station = station;
            this.walk = walk;
        }

        public TrainStation station;
        public Walk walk;
    }

'Walk' is a class that contains a 'duration' field. This represents the time it takes to walk. More specifically, my overall goal here is to figure out which 3 walks are the fastest walks out of all 20 in the list. But the 'walks' are properties of the StationWalk struct, and the 'duration' is a property of the Walk.

How would I go about doing this? Really sorry if this isn't well explained, it's confusing to myself despite writing it myself, yet alone trying to explain it to others.Appreciate any help.

Body:
The OrderBy and Take both return a new collection, they do not modify the existing collection, so you would need to store the reference to new collection returned by the methods like:

stations =  stations.OrderBy(walks => walks.walk.duration).Take(3).ToList();

and if you want to keep reference to the original list for further usage down in your code, then just store the result in a local variable:

var lowestThreeStations =  stations.OrderBy(walks => walks.walk.duration).Take(3).ToList();


问:
Storing the entire output of a while loop
I'm having problems storing the ouput of a while loop in Python3. The code below just stores the last output: 5702887

```<code>x = 1
y = 2
answer = []

while x < 4000000:
    y = x + y
    x = y - x
    answer.append(x)
</code>```

How do I get x to store:

```<code>1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887
</code>```

答:
i get the intended result with

```<code>print answer
</code>```

and the result 5702887 with

```<code>print x
</code>```

how do you try to get the result?

edit: without modifying the loop, you could start with

```<code>answer = [1]
</code>```

Body:
I'm having problems storing the ouput of a while loop in Python3. The code below just stores the last output: 5702887

x = 1
y = 2
answer = []

while x < 4000000:
    y = x + y
    x = y - x
    answer.append(x)

How do I get x to store:

1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887

Body:
i get the intended result with

print answer

and the result 5702887 with

print x

how do you try to get the result?

edit: without modifying the loop, you could start with

answer = [1]


问:
django-rest-swagger: How can I specify the parameter type in the docstring
I am using django-rest-framwork and django-rest-swagger.

The problem is that I'm fetching data directly from the body of the request:

```<code>def put(self, request, format=None):
    """
    This text is the description for this API
    username -- username
    password -- password
    """
    username = request.DATA['username']
    password = request.DATA['password']
</code>```

but when I try the request from the swagger-ui I can't specify the "parameter type" (it's by default query and can't find a way to change it from the docstring)

I have managed to get around my problem by changing some line in the function build_query_params_from_docstring from the file "introspectors.py" but I was wondering if there is another way to do it.

答:
The only way I've had success in defining parameter types is by creating a view that defines what I want without using the generator.

```<code>class SwaggerSchemaView(APIView):
permission_classes = [IsAuthenticatedOrReadOnly,]
renderer_classes = [renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer]

schema = coreapi.Document(
    title='Thingy API thing',
        'range': coreapi.Link(
            url='/range/{start}/{end}',
            action='get',
            fields=[
                coreapi.Field(
                    name='start',
                    required=True,
                    location='path',
                    description='start time as an epoch',
                    type='integer'
                ),
                coreapi.Field(
                    name='end',
                    required=True,
                    location='path',
                    description='end time as an epoch',
                    type='integer'
                )
            ],
            description='show the things between the things'
        ),
    }
)
</code>```

and then using that class in urls.py

```<code>urlpatterns = [
    url(r'^$', SwaggerSchemaView.as_view()),
    ...
]
</code>```

Body:
I am using django-rest-framwork and django-rest-swagger.

The problem is that I'm fetching data directly from the body of the request:

def put(self, request, format=None):
    """
    This text is the description for this API
    username -- username
    password -- password
    """
    username = request.DATA['username']
    password = request.DATA['password']

but when I try the request from the swagger-ui I can't specify the "parameter type" (it's by default query and can't find a way to change it from the docstring)

I have managed to get around my problem by changing some line in the function build_query_params_from_docstring from the file "introspectors.py" but I was wondering if there is another way to do it.

Body:
The only way I've had success in defining parameter types is by creating a view that defines what I want without using the generator.

class SwaggerSchemaView(APIView):
permission_classes = [IsAuthenticatedOrReadOnly,]
renderer_classes = [renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer]

schema = coreapi.Document(
    title='Thingy API thing',
        'range': coreapi.Link(
            url='/range/{start}/{end}',
            action='get',
            fields=[
                coreapi.Field(
                    name='start',
                    required=True,
                    location='path',
                    description='start time as an epoch',
                    type='integer'
                ),
                coreapi.Field(
                    name='end',
                    required=True,
                    location='path',
                    description='end time as an epoch',
                    type='integer'
                )
            ],
            description='show the things between the things'
        ),
    }
)

and then using that class in urls.py

urlpatterns = [
    url(r'^$', SwaggerSchemaView.as_view()),
    ...
]


问:
Symfony2 Use Doctrine in Service Container
How do I use Doctrine in a service container?

The Code just causes an error message "Fatal error: Call to undefined method ...::get()".

```<code><?php

namespace ...\Service;

use Doctrine\ORM\EntityManager;
use ...\Entity\Header;

class dsdsf
{
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function create()
    {
        $id = 10;
        $em = $this->get('doctrine')->getEntityManager();
        $em->getRepository('...')->find($id);
    }
}
</code>```

services.yml

```<code>service:
    site:
        class: ...\Service\Site
</code>```

答:
for anyone who works with symfony3: u need to do the following inside config/services.yml in order to use doctrine in Service Container:</p>

```<code>servicename_manager:
          class: AppBundle\Services\MyServiceClass
          arguments: [ "@doctrine.orm.entity_manager" ]
</code>```

Body:
How do I use Doctrine in a service container?

The Code just causes an error message "Fatal error: Call to undefined method ...::get()".

<?php

namespace ...\Service;

use Doctrine\ORM\EntityManager;
use ...\Entity\Header;

class dsdsf
{
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function create()
    {
        $id = 10;
        $em = $this->get('doctrine')->getEntityManager();
        $em->getRepository('...')->find($id);
    }
}

services.yml

service:
    site:
        class: ...\Service\Site

Body:
for anyone who works with symfony3: u need to do the following inside config/services.yml in order to use doctrine in Service Container:

servicename_manager:
          class: AppBundle\Services\MyServiceClass
          arguments: [ "@doctrine.orm.entity_manager" ]


问:
Mongoid greater than date or not nil
I have two models

```<code>class Conversation
  include Mongoid::Document

  field :last_moderated_at, type: DateTime
  has_many :messages
end

class Message
  include Mongoid::Document
  include Mongoid::Timestamps
end
</code>```

I want to get the list of all messages that were created after the moderation date, or all of them if the moderation date is nil

I had expected the following to work

```<code>conversation.messages.where(
      :created_at.gte => conversation.last_moderated_at
    )
</code>```

But apparently the comparison with nil fails (when last_moderated_at == nil)

Do I have no choice but to use an if/else or is there a mongoDB operator of type greater than that also works when compared to nil dates ?

EDIT : A simpler example : Conversation.where(:created_at.gte => nil).count will always return 0

答: The syntax is correct. It does work on Mongoid version 6, at least.</p>

Title: Mongoid greater than date or not nil

Body:
I have two models

class Conversation
  include Mongoid::Document

  field :last_moderated_at, type: DateTime
  has_many :messages
end

class Message
  include Mongoid::Document
  include Mongoid::Timestamps
end

I want to get the list of all messages that were created after the moderation date, or all of them if the moderation date is nil

I had expected the following to work

conversation.messages.where(
      :created_at.gte => conversation.last_moderated_at
    )

But apparently the comparison with nil fails (when last_moderated_at == nil)

Do I have no choice but to use an if/else or is there a mongoDB operator of type greater than that also works when compared to nil dates ?

EDIT : A simpler example : Conversation.where(:created_at.gte => nil).count will always return 0


问:
animate rotation UIImageView in swift
I'm trying to animate a rotation of 180 degrees of a UIImageView in Swift

```<code>    UIView.animateWithDuration(1.0, animations: { () -> Void in
        self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(180 * M_PI))
    }) { (succeed) -> Void in

    }
</code>```

But isnt animating at all.
I want to use animateWithDuration cause i want to make it back at some point using CGAffineTransformMakeIdentity

Using UIView animations works.

```<code>    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationDuration(1)
    UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn)
    let radians = CGFloat(180 * M_PI / 180)
    arrowImageView.transform = CGAffineTransformMakeRotation(radians)
    UIView.commitAnimations()
</code>```

答:
Be sure to be in the Main thread</p>

```<code>DispatchQueue.main.async {
   UIView.animateWithDuration(1.0, animations: { () -> Void in
     self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(180 * M_PI))
   }) { (succeed) -> Void in

   }
}
</code>```

Title: animate rotation UIImageView in swift

Body:
I'm trying to animate a rotation of 180 degrees of a UIImageView in Swift

    UIView.animateWithDuration(1.0, animations: { () -> Void in
        self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(180 * M_PI))
    }) { (succeed) -> Void in

    }

But isnt animating at all.
I want to use animateWithDuration cause i want to make it back at some point using CGAffineTransformMakeIdentity

Using UIView animations works.

    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationDuration(1)
    UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn)
    let radians = CGFloat(180 * M_PI / 180)
    arrowImageView.transform = CGAffineTransformMakeRotation(radians)
    UIView.commitAnimations()

Body:
Be sure to be in the Main thread

DispatchQueue.main.async {
   UIView.animateWithDuration(1.0, animations: { () -> Void in
     self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(180 * M_PI))
   }) { (succeed) -> Void in

   }
}


问:
VB6 / WinAPI: How can I get the hwnd of a ListView.ListItem?
I have a VB6 application with a ListView (MSCOMCTL.OCX). I need to get the window handle (hwnd) for a listviewitem, or preferably (if something like that exists) - of a specific subitem.

I know I can get the handle for the column headers using FindWindowEx and looking for the class msvb_lib_header, but I don't know how to get the handle for the item. Spy++ shows a msvb_lib_header window as the child of the listview, but does not show any other windows.

答:
ListView.ListItem object has not hwnd.

You should search ListView by class name, next use SendMessage() to send the message LVM_GETITEM and using the LVITEM structure to get info about items:

LVM_GETITEM message (Windows)

https://msdn.microsoft.com/en-us/library/windows/desktop/bb774953(v=vs.85).aspx

LVITEM structure (Windows)

https://msdn.microsoft.com/en-us/library/windows/desktop/bb774760(v=vs.85).aspx

this reference page may help you:

List-View Control Reference (Windows)
https://msdn.microsoft.com/en-us/library/windows/desktop/ff485973(v=vs.85).aspx


答:
strtotime() uses 30 day months and there are only 28 in days in February (this year) so will not yield a valid date in February.  You could use the current day d or j and subtract that which will always put you in the previous month (-29 days):

```<code>$prevmonth = date('M', strtotime('-' . date('d') . ' days'));
</code>```

This will get December from January as well.

Title: PHP date returning wrong Month on subtracting one month

Body:
strtotime() uses 30 day months and there are only 28 in days in February (this year) so will not yield a valid date in February.  You could use the current day d or j and subtract that which will always put you in the previous month (-29 days):

$prevmonth = date('M', strtotime('-' . date('d') . ' days'));

This will get December from January as well.


问:
Saving an Image of Chart With a SaveFileDialog
On button click, my program captures a screenshot of a chart, titled chartMain. Code below:

```<code>private void buttonScreenshot_Click(object sender, EventArgs e)
{
    this.chartMain.SaveImage("C:/capture.png", ChartImageFormat.Png);
}
</code>```

However, this doesn't allow the user to specify the save location so I was wondering how I would implement SaveFileDialog to allow the user to choose where to save it.

Could someone please point me in the right direction as I am currently stuck.

Thank you in advance.

答:
This should take care of it for you:</p>

```<code>SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
   this.chartMain.SaveImage(dialog.FileName, ChartImageFormat.Png);
}
</code>```

Body:
On button click, my program captures a screenshot of a chart, titled chartMain. Code below:

private void buttonScreenshot_Click(object sender, EventArgs e)
{
    this.chartMain.SaveImage("C:/capture.png", ChartImageFormat.Png);
}

However, this doesn't allow the user to specify the save location so I was wondering how I would implement SaveFileDialog to allow the user to choose where to save it.

Could someone please point me in the right direction as I am currently stuck.

Thank you in advance.

Body:
This should take care of it for you:

SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
   this.chartMain.SaveImage(dialog.FileName, ChartImageFormat.Png);
}


问:
How to understand array sorting in Swift
Can someone please visualize the process of sorting?

```<code>let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }
</code>```

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?

答:
It is a syntactic simplification, it is equivalent to:

```<code>numbers.sorted {(a, b) -> Bool in
        return a > b
    }
</code>```

In fact $0 is the first parameter of the closure, $1 is the second one...

Edit: The fact that it is called 4 times, it's just because of the sort algorithm used. And you should not take care of it.

Body:
Can someone please visualize the process of sorting?

let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?

Body:
It is a syntactic simplification, it is equivalent to:

numbers.sorted {(a, b) -> Bool in
        return a > b
    }

In fact $0 is the first parameter of the closure, $1 is the second one...

Edit: The fact that it is called 4 times, it's just because of the sort algorithm used. And you should not take care of it.


问:
how to use @JoinColumn in OneToOne mapping in hibernate?
I have seen many questions asked on @JoinColumn and this concept was clear to me until I came across the following situation.

Let's consider mapping is OneToOne Unidirectional mapping. i have used following annatation in the parent class:
Case 1:-
@JoinColumn(name="test_Id",referencedColumnName="refToPrimaryKey") and  Entity class is not implementing Serializable interface. in this case program is executing without any exception.
Case 2:-
@JoinColumn(name="test_Id",referencedColumnName="refToNonPrimaryKey") and  Entity class is not implementing Serializable interface.

Here program is throwing exception like:

```<code>threw exception [java.lang.ClassCastException:
com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable] with root cause
java.lang.ClassCastException: com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable at org.hibernate.type.CollectionType.getKeyOfOwner(CollectionType.java:414)
</code>```

Can you Guys help me out to know the concept why it is happening?

答:
```<code>Please find below code.let me know  if you need  any other information:
@Setter
@Getter
@Entity
@Table(name="test")
public class TestEntity imple`enter code here`ments Serializable{
     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     @Column(name = "id")
     private int id;
     @Column(name="name")
     private String name;
     @Column(name="roll")
     private int roll;
     @Column(name="stream")
     private String stream;
     @OneToMany(cascade=CascadeType.ALL)
     @JoinColumn(name="for_Key",referencedColumnName="roll")
     private List<TestEntityChild> testEntityChildList;
}
Chile Entity class
 @Getter
@Setter
@Entity
@Table(name="testchild")
public class TestEntityChild {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name="Test_id")
  private int testId;

  @Column(name="city")
  private String city;
  @Column(name="state")
  private String state;

}
</code>```

Body:
I have seen many questions asked on @JoinColumn and this concept was clear to me until I came across the following situation.

Let's consider mapping is OneToOne Unidirectional mapping. i have used following annatation in the parent class:
Case 1:-
@JoinColumn(name="test_Id",referencedColumnName="refToPrimaryKey") and  Entity class is not implementing Serializable interface. in this case program is executing without any exception.
Case 2:-
@JoinColumn(name="test_Id",referencedColumnName="refToNonPrimaryKey") and  Entity class is not implementing Serializable interface.

Here program is throwing exception like:

threw exception [java.lang.ClassCastException:
com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable] with root cause
java.lang.ClassCastException: com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable at org.hibernate.type.CollectionType.getKeyOfOwner(CollectionType.java:414)

Can you Guys help me out to know the concept why it is happening?