问:
2 applications on the same port
I have an interesting scenario where 2 applications are listening to the same port. One on the loop-back address and one on the invalid address.

My understanding is that only one application can listen to a port at a time. So, how is this possible?

```<code>Proto  Local Address          Foreign Address        State           PID
TCP    0.0.0.0:10006          0.0.0.0:0              LISTENING       1772
TCP    127.0.0.1:10006        0.0.0.0:0              LISTENING       3876
</code>```

Both were started under the system account and both are running fine, but if I switch one to a local user then the that application fails to start. If I switch both to local user then both starts fine. It seems if both are in the same user context then both are able to run fine.

答:
0.0.0.0 means all IPv4 addresses on the local machine. So if the machine has multiple network addresses, it will serve all of those.

The loopback is distinct from that, so it's legal to be listening on the same port but different adapters.

Title: 2 applications on the same port

Body:
I have an interesting scenario where 2 applications are listening to the same port. One on the loop-back address and one on the invalid address.

My understanding is that only one application can listen to a port at a time. So, how is this possible?

Proto  Local Address          Foreign Address        State           PID
TCP    0.0.0.0:10006          0.0.0.0:0              LISTENING       1772
TCP    127.0.0.1:10006        0.0.0.0:0              LISTENING       3876

Both were started under the system account and both are running fine, but if I switch one to a local user then the that application fails to start. If I switch both to local user then both starts fine. It seems if both are in the same user context then both are able to run fine.


来源: stackexchange

问:
iTextSharp - display text on hover
I am using iTextSharp to generate a PDF that contains words the reader may not know.  So I want to underline these words and then add a feature where (1) when the user hovers the mouse over the word, a definition pops up, and (2) if the user clicks on the popped-up definition, it goes to the Definitions section of the document.

I see example code to do this online, but it always requires that you know where the link will appear on the page, and in my case I'm generating a structured document (Chapters and Sections) so I do not know the position of the word.

I suspect it uses PdfAnnotation and Link but can't figure out exactly how.

Bonus points if the solution also works when the text is in a table cell (some of the solutions I see have problems there).

p.s. Some progress:

When I create my Definitions section, I call

```<code>this.Chunks[0].SetLocalDestination("Definitions");
</code>```

When I add the challenging word to my PDF document, I call SetGenericTag() on the Chunk.  Then, in my override for PdfPageEvent.OnGenericTag() I do this:

```<code>PdfAnnotation link = PdfAnnotation.CreateLink(writer, rect, PdfAnnotation.HIGHLIGHT_INVERT, PdfAction.GotoLocalPage("Definitions", false));
writer.AddAnnotation(link);
</code>```

which satisfies part of what I need - if I click on the word it takes me to the Definitions section of the document.  But there is still no definition that appears when you hover over the word.

答:
Here's what I came up with:</p>

```<code>PushbuttonField button = new PushbuttonField(writer, rect, "DefineButton-" + (++NumButtons));
PdfFormField field = button.Field;
field.Action = PdfAction.GotoLocalPage("Definitions", false);
field.UserName = definition;
writer.AddAnnotation(field);
</code>```

ContentLicense: CC BY-SA 3.0

Title: iTextSharp - display text on hover

Body:
I am using iTextSharp to generate a PDF that contains words the reader may not know.  So I want to underline these words and then add a feature where (1) when the user hovers the mouse over the word, a definition pops up, and (2) if the user clicks on the popped-up definition, it goes to the Definitions section of the document.

I see example code to do this online, but it always requires that you know where the link will appear on the page, and in my case I'm generating a structured document (Chapters and Sections) so I do not know the position of the word.

I suspect it uses PdfAnnotation and Link but can't figure out exactly how.

Bonus points if the solution also works when the text is in a table cell (some of the solutions I see have problems there).

p.s. Some progress:

When I create my Definitions section, I call

this.Chunks[0].SetLocalDestination("Definitions");

When I add the challenging word to my PDF document, I call SetGenericTag() on the Chunk.  Then, in my override for PdfPageEvent.OnGenericTag() I do this:

PdfAnnotation link = PdfAnnotation.CreateLink(writer, rect, PdfAnnotation.HIGHLIGHT_INVERT, PdfAction.GotoLocalPage("Definitions", false));
writer.AddAnnotation(link);

which satisfies part of what I need - if I click on the word it takes me to the Definitions section of the document.  But there is still no definition that appears when you hover over the word.

Body:
Here's what I came up with:

PushbuttonField button = new PushbuttonField(writer, rect, "DefineButton-" + (++NumButtons));
PdfFormField field = button.Field;
field.Action = PdfAction.GotoLocalPage("Definitions", false);
field.UserName = definition;
writer.AddAnnotation(field);


问:
Implementing Like button in recyclerView using shared preference
I have a cardView that has a textView and a Like button. Whenever the like button is pressed it will display that cardView in another fragment, just like favourites.

How can I do this using shared preference or any other method? I've done this to change the color of like button but don't know how to add that cardView to another fragment:

```<code>  likeImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

      int id = (int)likeImageView.getTag();
      if( id == R.drawable.ic_like){

          likeImageView.setTag(R.drawable.ic_liked);
          likeImageView.setImageResource(R.drawable.ic_liked);

          Toast.makeText(getActivity(),titleTextView.getText()+" added to favourites",Toast.LENGTH_SHORT).show();

      } else {

          likeImageView.setTag(R.drawable.ic_like);
          likeImageView.setImageResource(R.drawable.ic_like);
          Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();

      }

    }
  });
</code>```

答:
Create an instance of SharedPreferences in your onclick method

SharedPreferences prefs = getActivity().getSharedPreferences(
      "Preference_reference", Context.MODE_PRIVATE);

Use the name of the 'Liked' item as the key and a boolean as the type
Alternately you could use a Boolean array as the type if the items never change order.

Save whether or not an item is liked to the shared pref in the onclick.

if( id == R.drawable.ic_like){

```<code>    likeImageView.setTag(R.drawable.ic_liked);
    likeImageView.setImageResource(R.drawable.ic_liked);

    prefs.edit().putBoolean("Unique id", true).commit();

    Toast.makeText(getActivity(),titleTextView.getText()+" added to
    favourites",Toast.LENGTH_SHORT).show();

}else{

    likeImageView.setTag(R.drawable.ic_like);
    likeImageView.setImageResource(R.drawable.ic_like);

    prefs.edit().putBoolean("Unique id", false).commit();

    Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();
}
</code>```

In the fragment you want to show items if the are liked, Create another SharedPreferences variable and use it to initialize the fragment so that it shows any item whose key value is set to true.

if(prefs.getBoolean("Unique Id",false)){Show card}

You can find plenty of resources on how to use SharedPreferences so I kept the code to the bare minimum

Body:
I have a cardView that has a textView and a Like button. Whenever the like button is pressed it will display that cardView in another fragment, just like favourites.

How can I do this using shared preference or any other method? I've done this to change the color of like button but don't know how to add that cardView to another fragment:

  likeImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

      int id = (int)likeImageView.getTag();
      if( id == R.drawable.ic_like){

          likeImageView.setTag(R.drawable.ic_liked);
          likeImageView.setImageResource(R.drawable.ic_liked);

          Toast.makeText(getActivity(),titleTextView.getText()+" added to favourites",Toast.LENGTH_SHORT).show();

      } else {

          likeImageView.setTag(R.drawable.ic_like);
          likeImageView.setImageResource(R.drawable.ic_like);
          Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();

      }

    }
  });

Body:
Create an instance of SharedPreferences in your onclick method

SharedPreferences prefs = getActivity().getSharedPreferences(
      "Preference_reference", Context.MODE_PRIVATE);

Use the name of the 'Liked' item as the key and a boolean as the type
Alternately you could use a Boolean array as the type if the items never change order.

Save whether or not an item is liked to the shared pref in the onclick.

if( id == R.drawable.ic_like){

    likeImageView.setTag(R.drawable.ic_liked);
    likeImageView.setImageResource(R.drawable.ic_liked);

    prefs.edit().putBoolean("Unique id", true).commit();

    Toast.makeText(getActivity(),titleTextView.getText()+" added to
    favourites",Toast.LENGTH_SHORT).show();

}else{

    likeImageView.setTag(R.drawable.ic_like);
    likeImageView.setImageResource(R.drawable.ic_like);

    prefs.edit().putBoolean("Unique id", false).commit();

    Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();
}

In the fragment you want to show items if the are liked, Create another SharedPreferences variable and use it to initialize the fragment so that it shows any item whose key value is set to true.

if(prefs.getBoolean("Unique Id",false)){Show card}

You can find plenty of resources on how to use SharedPreferences so I kept the code to the bare minimum


问:
Java untyped generic classes, removing their functions generics types
Ok Question about javas generics, iterable, and for-each loop.  The problem being that, if I declare my 'Test' class untyped,  I lose all generic information on all my functions and for-each is not likeing that at all.

Example

```<code>public class Test<T> implements Iterable<Integer>{

    public Test() {}

    public Iterator<Integer> iterator() {return null;}

    public static void main(String[] args) {
        Test t = new Test();

        //Good,
        //its returning an Iterator<object> but it automatically changes to  Iterator<Integer>
        Iterator<Integer> it = t.iterator();

        //Bad
        //incompatable types, required Integer, found Object
        for(Integer i : t){
        }
    }Untyped generic classes losing
}
</code>```

When 'Test t' is untyped, the 'iterator()' function returns 'iterator' instead of a 'iterator < Integer >'.

I'm not exactly sure for the reason behind it, I know a fix for that is just use a wild card on 'Test < ? > t = new test()'.  However this is a less than ideal solution.

Is their any way to only edit the class declaration and its functions and have the for each loop work untyped?

答:
You should just do the following:

```<code>public class Test implements Iterable<Integer>{
</code>```

Remove the generic type all together.

Your Test class is not generic at all.  It is simply implementing a generic interface.  Declaring a generic type is not necessary.  This will also have the benefit of remove that generic warning you were getting.

@Eugene makes a good point.  If you actually wanted a generic Test type, you should declare Test as a generic iterator:

You should just do the following:

```<code>public class Test implements Iterable<Integer>{
</code>```

Remove the generic type all together.

Your Test class is not generic at all.  It is simply implementing a generic interface.  Declaring a generic type is not necessary.  This will also have the benefit of remove that generic warning you were getting.

```<code>public class Test<T> implements Iterable<T>{
</code>```

And then, make sure you make Test generic when you instantiate it.

```<code>Test<Integer> t = new Test<Integer>;
</code>```

Then calls to for(Integer i: t) will compile.

Body:
Ok Question about javas generics, iterable, and for-each loop.  The problem being that, if I declare my 'Test' class untyped,  I lose all generic information on all my functions and for-each is not likeing that at all.

Example

public class Test<T> implements Iterable<Integer>{

    public Test() {}

    public Iterator<Integer> iterator() {return null;}

    public static void main(String[] args) {
        Test t = new Test();

        //Good,
        //its returning an Iterator<object> but it automatically changes to  Iterator<Integer>
        Iterator<Integer> it = t.iterator();

        //Bad
        //incompatable types, required Integer, found Object
        for(Integer i : t){
        }
    }Untyped generic classes losing
}

When 'Test t' is untyped, the 'iterator()' function returns 'iterator' instead of a 'iterator < Integer >'.

I'm not exactly sure for the reason behind it, I know a fix for that is just use a wild card on 'Test < ? > t = new test()'.  However this is a less than ideal solution.

Is their any way to only edit the class declaration and its functions and have the for each loop work untyped?

Body:
You should just do the following:

public class Test implements Iterable<Integer>{

Remove the generic type all together.

Your Test class is not generic at all.  It is simply implementing a generic interface.  Declaring a generic type is not necessary.  This will also have the benefit of remove that generic warning you were getting.

@Eugene makes a good point.  If you actually wanted a generic Test type, you should declare Test as a generic iterator:

You should just do the following:

public class Test implements Iterable<Integer>{

Remove the generic type all together.

Your Test class is not generic at all.  It is simply implementing a generic interface.  Declaring a generic type is not necessary.  This will also have the benefit of remove that generic warning you were getting.

public class Test<T> implements Iterable<T>{

And then, make sure you make Test generic when you instantiate it.

Test<Integer> t = new Test<Integer>;

Then calls to for(Integer i: t) will compile.

ContentLicense: CC BY-SA 2.5


问:
Codeigniter Not allowing to post data in REST API post method via url. it's showing error like unknown method
I am trying to send data through url like

http://localhost/api/index.php/society/?date=20/04/2017&s_name=ssr

but it's showing error message:

{"status":false,"error":"Unknown method"}

When I am testing with postman or advance rest client application, it's working fine and data is posting and updating database.

url: http://localhost/api/index.php/society

My Controller....

```<code><?php

defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH . 'libraries/REST_Controller.php';

use Restserver\Libraries\REST_Controller;

class Society extends REST_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('Society_model');
    }

    public function index_get()
    {
        $data = $this->Society_model->society_get();
        $this->response($data);
    }

    public function index_post()
    {

        $data = array(
            'date' =>$this->post('date'),
            'society_name' => $this->post('s_name'),
            'society_group' => $this->post('g_name'),
            'contact_name' => $this->post('c_name'),
            'mobile_no' => $this->post('mobile'),
            'address' => $this->post('address'),
            'city' => $this->post('city'),
            'state' => $this->post('state'),
            'pincode' => $this->post('pincode'),
            'email_id' =>$this->post('email')
           );

         $this->Society_model->insert($data);

         $this->set_response($data, REST_Controller::HTTP_CREATED);
    }
}
</code>```

My Model....

```<code><?php

class Society_model extends CI_Model
{

    function __construct()
    {
        parent::__construct();
    }

    public function society_get(){
        $this->db->select('*');
        $this->db->from('society_contact');
        $result = $this->db->get();
        return $result->result();
    }

    public function insert($data)
    {
         if ($this->db->insert("society_contact", $data))
         {
            return true;
         }
    }
}
</code>```

答:
You can't use the POST method via a browser. You must use POSTMAN or another REST Client. URL in browser only allows you to GET information.

Please refer to this post How do I manually fire HTTP POST requests with Firefox or Chrome?

Also your URL http://localhost/api/index.php/society/?date=20/04/2017&s_name=ssr

it is not correct because when you added ?something=something, this is a parameter, also if you added / this are separate parts of the url. That is why you are getting Unknow Method.

Body:
I am trying to send data through url like

http://localhost/api/index.php/society/?date=20/04/2017&s_name=ssr

but it's showing error message:

{"status":false,"error":"Unknown method"}

When I am testing with postman or advance rest client application, it's working fine and data is posting and updating database.

url: http://localhost/api/index.php/society

My Controller....

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH . 'libraries/REST_Controller.php';

use Restserver\Libraries\REST_Controller;

class Society extends REST_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('Society_model');
    }

    public function index_get()
    {
        $data = $this->Society_model->society_get();
        $this->response($data);
    }

    public function index_post()
    {

        $data = array(
            'date' =>$this->post('date'),
            'society_name' => $this->post('s_name'),
            'society_group' => $this->post('g_name'),
            'contact_name' => $this->post('c_name'),
            'mobile_no' => $this->post('mobile'),
            'address' => $this->post('address'),
            'city' => $this->post('city'),
            'state' => $this->post('state'),
            'pincode' => $this->post('pincode'),
            'email_id' =>$this->post('email')
           );

         $this->Society_model->insert($data);

         $this->set_response($data, REST_Controller::HTTP_CREATED);
    }
}

My Model....

<?php

class Society_model extends CI_Model
{

    function __construct()
    {
        parent::__construct();
    }

    public function society_get(){
        $this->db->select('*');
        $this->db->from('society_contact');
        $result = $this->db->get();
        return $result->result();
    }

    public function insert($data)
    {
         if ($this->db->insert("society_contact", $data))
         {
            return true;
         }
    }
}


问:
Numbers bigger than 8 bytes in C
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

```<code>unsigned char n[16];
</code>```

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

```<code>//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}
</code>```

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

```<code>//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)
</code>```

答:
Numbers have a "base" that determines the range of each digit (e.g. "base 10" is decimal).

One uint8_t is a single digit in "base 256". One uint16_t is a single digit in "base 65536". One uint32_t is a single digit in "base 4294967296".

For mathematical operations, performance is heavily effected by the number of digits. By using a larger base you need fewer digits for the same number, which improves performance (until you exceed the CPU's native word size).

For subtraction of unsigned numbers:

```<code>#define DIGITS 4

int subtract(uint32_t *result, uint32_t *src1, uint32_t *src2) {
    int carry = 0;
    int oldCarry;
    int i;

    for(i = 0; i < DIGITS; i++) {
        oldCarry = carry;
        if(src2[i] < src1[i]) {
            carry = 1;
        } else if( (src2[i] == src1[i]) && (oldCarry != 0) ) {
            carry = 1;
        } else {
            carry = 0;
        }
        result[i] = src1[i] - src2[i] - oldCarry;
    }
    return carry;
}
</code>```

Title: Numbers bigger than 8 bytes in C

Body:
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

unsigned char n[16];

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)

Body:
Numbers have a "base" that determines the range of each digit (e.g. "base 10" is decimal).

One uint8_t is a single digit in "base 256". One uint16_t is a single digit in "base 65536". One uint32_t is a single digit in "base 4294967296".

For mathematical operations, performance is heavily effected by the number of digits. By using a larger base you need fewer digits for the same number, which improves performance (until you exceed the CPU's native word size).

For subtraction of unsigned numbers:

#define DIGITS 4

int subtract(uint32_t *result, uint32_t *src1, uint32_t *src2) {
    int carry = 0;
    int oldCarry;
    int i;

    for(i = 0; i < DIGITS; i++) {
        oldCarry = carry;
        if(src2[i] < src1[i]) {
            carry = 1;
        } else if( (src2[i] == src1[i]) && (oldCarry != 0) ) {
            carry = 1;
        } else {
            carry = 0;
        }
        result[i] = src1[i] - src2[i] - oldCarry;
    }
    return carry;
}


问:
Run JavaScript promises in order. One after the other ends
I am trying to run to promises (which make some rest API calls on each). Based on the result of the two promises, use the third function to process the data. Also, the functions running in sequence can be changing. So I made them in a dynamic way of constructing promise.

However, the promises seem to be starting without the previous one ending. Here is a simplified model for testing the same concept.

var funcs = [
 () => {
    console.log('Task 1 Sart =', new Date());
   sleeper(6000, 'Task 1  Resolved');
    console.log('Task 1  Return');
  },
  () => {
  console.log('Task 2  Sart=', new Date());
   sleeper(5000, 'Task 2  Resolved');
    console.log('Task 2  Return');
  },
  () => {
  console.log('Task 3  Start=', new Date());
  console.log('Task 2  Return');
  }
];

function sleeper(m, msg) {
 return new Promise(function(resolve, reject) {
   setTimeout(function() {
    resolve(console.log(msg, new Date()));
   }, m);
 });
}

function runSequence(functionSequence) {
   return functionSequence.reduce((p, func) => {
       return p.then(func);
   }, Promise.resolve());
}

var v = runSequence(funcs);```

The results look like this
VM128:51 Task 1 Sart = Wed Jun 07 2017 13:54:34 GMT-0700 (PDT)
VM128:53 Task 1  Return
VM128:56 Task 2  Sart= Wed Jun 07 2017 13:54:34 GMT-0700 (PDT)
VM128:58 Task 2  Return
VM128:61 Task 3  Start= Wed Jun 07 2017 13:54:34 GMT-0700 (PDT)
VM128:62 Task 2  Return
VM238:69 Task 2  Resolved Wed Jun 07 2017 13:54:39 GMT-0700 (PDT)
VM238:69 Task 1  Resolved Wed Jun 07 2017 13:54:40 GMT-0700 (PDT)

I would assume I don't see the second task start till the first one ended. Looked like they all started in sequence. Is anything I missed or totally misunderstand how the promises work. What I tried to achieve is to have the first one completed and then the following starts

答:
Based on the comments. Here is the version works. A simple return is missing from original codes

var funcs = [
 () => {
    console.log('Task 1 Sart =', new Date());
   return sleeper(7000, 'Task 1  Resolved');
  },
  () => {
   console.log('Task 2  Sart=', new Date());
   return sleeper(3000, 'Task 2  Resolved');
  },
  () => {
  console.log('Task 3  Start=', new Date());
  console.log('Task 3  Return');
  }
];

function sleeper(m, msg) {
 return new Promise(function(resolve, reject) {
   setTimeout(function() {
    resolve(console.log(msg, new Date()));
   }, m);
 });
}

function runSequence(functionSequence) {
   return functionSequence.reduce((p, func) => {
     return p.then(func);
   }, Promise.resolve());
}

runSequence(funcs);```

Body:
I am trying to run to promises (which make some rest API calls on each). Based on the result of the two promises, use the third function to process the data. Also, the functions running in sequence can be changing. So I made them in a dynamic way of constructing promise.

However, the promises seem to be starting without the previous one ending. Here is a simplified model for testing the same concept.

var funcs = [
 () => {
    console.log('Task 1 Sart =', new Date());
   sleeper(6000, 'Task 1  Resolved');
    console.log('Task 1  Return');
  },
  () => {
  console.log('Task 2  Sart=', new Date());
   sleeper(5000, 'Task 2  Resolved');
    console.log('Task 2  Return');
  },
  () => {
  console.log('Task 3  Start=', new Date());
  console.log('Task 2  Return');
  }
];

function sleeper(m, msg) {
 return new Promise(function(resolve, reject) {
   setTimeout(function() {
    resolve(console.log(msg, new Date()));
   }, m);
 });
}

function runSequence(functionSequence) {
   return functionSequence.reduce((p, func) => {
       return p.then(func);
   }, Promise.resolve());
}

var v = runSequence(funcs);

The results look like this
VM128:51 Task 1 Sart = Wed Jun 07 2017 13:54:34 GMT-0700 (PDT)
VM128:53 Task 1  Return
VM128:56 Task 2  Sart= Wed Jun 07 2017 13:54:34 GMT-0700 (PDT)
VM128:58 Task 2  Return
VM128:61 Task 3  Start= Wed Jun 07 2017 13:54:34 GMT-0700 (PDT)
VM128:62 Task 2  Return
VM238:69 Task 2  Resolved Wed Jun 07 2017 13:54:39 GMT-0700 (PDT)
VM238:69 Task 1  Resolved Wed Jun 07 2017 13:54:40 GMT-0700 (PDT)

I would assume I don't see the second task start till the first one ended. Looked like they all started in sequence. Is anything I missed or totally misunderstand how the promises work. What I tried to achieve is to have the first one completed and then the following starts


问:
Sublime Text 3: How to install plugins from Github
How do I install plugins from github for Sublime Text 3? I am trying to install this. What I have done so far is installing displayfunctions.py into Packages/Display-Functions/displayfunctions.py (I created a new folder Display-Functions in the Packages folder to hold displayfuntions.py). It still doesn't work. How can I fix this?

答:
In Sublime Text 3, if you already have Package Control, but the package isn't showing up in Install Packages, for instance ChainOfCommand, you need to "Add the Repository" to add the package to Package Control, only then can you install it.

Here's a step-by-step process:

In a Web Browser, navigate to your plugin, copy the git url (should end with a .git).

for ChainOfCommand, this is https://github.com/jisaacks/ChainOfCommand.git

In Sublime, Open Package Control

Select Package Control: Add Repository

At the bottom of the Sublime window, an input box will appear. Paste the URL. AND REMOVE THE .GIT EXTENSION;  hit Enter.

Now the Repo has been added to Package Control, it's not installed though

Open Package Control again (like in step 2).

Select Package Control: Install Packages

Now you should be able to search for, and install the package that had previously been missing, ie ChainOfCommand.

Alternatively, If you have TortoiseGit, you can do a manual install:

Similar to above, go copy the URL (include .git this time).

In Sublime, go to Preferences > Browse Packages (This opens the Packages folder).

Right-click on an empty space of the folder > Git Clone

Because the URL is already on your clipboard, it should automatically appear in the URL of the Git Clone Window. Press OK and Voila, Installed.

ContentLicense: CC BY-SA 4.0


问:
Change id name of ImageView with a String
Suppose we have :

```<code>ImageView imageView_A = findViewById(R.id.imageview_dhze);
ImageView imageView_B = findViewById(R.id.imageview_dhhkjhkze);
ImageView imageView_C = findViewById(R.id.imageview_dhkhkjze);
ImageView imageView_D = findViewById(R.id.imageview_dhhuihuybze);
</code>```

I want to make a function like this :

```<code>changeImages(String NAME) {
    imageView_1_NAME.setImageResource(R.drawable.img);
    imageView_2_NAME.setImageResource(R.drawable.img);
    imageView_3_NAME.setImageResource(R.drawable.img);
}
</code>```

And for example, I could use it like this :

```<code>changeImage("A");
</code>```

to obtain :

```<code>imageView_1_A.setImageResource(R.drawable.img);
imageView_2_A.setImageResource(R.drawable.img);
imageView_3_A.setImageResource(R.drawable.img);
</code>```

It is possible ? How can I do that ?

答:
You could put all the ImageViews in a HashMap like this:

```<code>HashMap<String, ImageView> imageViews = new HashMap<>();
</code>```

Then you add the ImageViews to the HashMap:

```<code>imageViews.put("A", imageView_A);
imageViews.put("B", imageView_B);
...
</code>```

And your function could look like this then:

```<code>private void changeImage(String name) {
    imageViews.get(name).setImageResource(R.drawable.img);
}
</code>```

In this case you should only call changeImage() when the HashMap contains a key with the same value of String name. If you are not sure if a key exists you need to check if imageViews.containsKey(name) first.

Body:
Suppose we have :

ImageView imageView_A = findViewById(R.id.imageview_dhze);
ImageView imageView_B = findViewById(R.id.imageview_dhhkjhkze);
ImageView imageView_C = findViewById(R.id.imageview_dhkhkjze);
ImageView imageView_D = findViewById(R.id.imageview_dhhuihuybze);

I want to make a function like this :

changeImages(String NAME) {
    imageView_1_NAME.setImageResource(R.drawable.img);
    imageView_2_NAME.setImageResource(R.drawable.img);
    imageView_3_NAME.setImageResource(R.drawable.img);
}

And for example, I could use it like this :

changeImage("A");

to obtain :

imageView_1_A.setImageResource(R.drawable.img);
imageView_2_A.setImageResource(R.drawable.img);
imageView_3_A.setImageResource(R.drawable.img);

It is possible ? How can I do that ?

Body:
You could put all the ImageViews in a HashMap like this:

HashMap<String, ImageView> imageViews = new HashMap<>();

Then you add the ImageViews to the HashMap:

imageViews.put("A", imageView_A);
imageViews.put("B", imageView_B);
...

And your function could look like this then:

private void changeImage(String name) {
    imageViews.get(name).setImageResource(R.drawable.img);
}

In this case you should only call changeImage() when the HashMap contains a key with the same value of String name. If you are not sure if a key exists you need to check if imageViews.containsKey(name) first.


问:
DOM specified Property return true
Someone told me if the attribute not defined, the specified value will return false. xms attribute did not have definition, but specified return true. What situation does specified return false?</p>

```<code><!DOCTYPE html>
<html>
<body>

<p>Click the button find out if the button has an onclick attribute specified.</p>

<button onclick="myFunction()" class="" xms >Try it</button>

<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
function myFunction() {
    var btn = document.getElementsByTagName("BUTTON")[0];
    var x = btn.getAttributeNode("onclick").specified;
    document.getElementById("demo").innerHTML = x;

        var y = btn.getAttributeNode("class").specified;
    document.getElementById("demo2").innerHTML = y;

        var z = btn.getAttributeNode("xms").specified;
    document.getElementById("demo3").innerHTML = z;

}
</script>

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

答:
I added 3 alert command and get the results as below.</p>

```<code>var z = btn.getAttributeNode("xms").specified;
alert (btn.getAttributeNode("xms").nodeName);   //display xms
alert (btn.getAttributeNode("xms").nodeValue);   //display nothing
alert (btn.getAttributeNode("xms").innerHTML);    //display undefined
document.getElementById("demo3").innerHTML = z;
</code>```

Title: DOM specified Property return true

Body:
Someone told me if the attribute not defined, the specified value will return false. xms attribute did not have definition, but specified return true. What situation does specified return false?

<!DOCTYPE html>

Click the button find out if the button has an onclick attribute specified.

<button onclick="myFunction()" class="" xms >Try it</button>

Body:
I added 3 alert command and get the results as below.

var z = btn.getAttributeNode("xms").specified;
alert (btn.getAttributeNode("xms").nodeName);   //display xms
alert (btn.getAttributeNode("xms").nodeValue);   //display nothing
alert (btn.getAttributeNode("xms").innerHTML);    //display undefined
document.getElementById("demo3").innerHTML = z;


问:
Is there a way with numpy to memmap a big-endian complex number?
I'm trying to load data from very large files that are formatted to be complex64 but in big-endian. Because of their size I want to use memmap. I can load the array as big-endian floats like such:

```<code>arr = np.memmap(fn, dtype='>f4', shape=(M,N,2))
</code>```

but if I try to get a view of it as a complex number it reverts the byteswapping ie

```<code>arr[m,n,0]+1j*arr[m,n,1] != arr[m,n].view(dtype=np.complex64)
</code>```

but

```<code>arr[m,n,0]+1j*arr[m,n,1] == arr[m,n].view(dtype=np.complex64).byteswap()
</code>```

But this either creates a copy of the data or modifies the files. Is there a way to make this work without making a copy of the data or modifying the existing files?

答:
It appears that the .byteswap() method doesn't modify or copy the data. So

narr = arr[m,n].view(dtype=np.complex64).byteswap()

Is the way to go. Hopefully that helps someone else.

Body:
I'm trying to load data from very large files that are formatted to be complex64 but in big-endian. Because of their size I want to use memmap. I can load the array as big-endian floats like such:

arr = np.memmap(fn, dtype='>f4', shape=(M,N,2))

but if I try to get a view of it as a complex number it reverts the byteswapping ie

arr[m,n,0]+1j*arr[m,n,1] != arr[m,n].view(dtype=np.complex64)

but

arr[m,n,0]+1j*arr[m,n,1] == arr[m,n].view(dtype=np.complex64).byteswap()

But this either creates a copy of the data or modifies the files. Is there a way to make this work without making a copy of the data or modifying the existing files?


答:
```<code>int[] images = {R.id.imageA,R.id.imageB,R.id.imageC,R.id.imageD,R.id.imageE};
int[] drawables = {R.drawable.imageA,R.drawable.imageB,R.drawable.imageC,R.drawable.imageD,R.drawable.imageE};
for(int i=0;i<5;i++)
{
    findViewById(images[i]).setImageResource(drawables[i]);
}
</code>```

It's easier.

Title: Change id name of ImageView with a String

Body:
int[] images = {R.id.imageA,R.id.imageB,R.id.imageC,R.id.imageD,R.id.imageE};
int[] drawables = {R.drawable.imageA,R.drawable.imageB,R.drawable.imageC,R.drawable.imageD,R.drawable.imageE};
for(int i=0;i<5;i++)
{
    findViewById(images[i]).setImageResource(drawables[i]);
}

It's easier.


问:
How to set metada in PDF being created with FlyingSaucer
I'm trying to set the metadata (such as Title or Author) in a PDF file that I'm creating with FlyingSaucer (https://github.com/flyingsaucerproject/flyingsaucer) from an HTML file.

Here's the code that creates the PDF file:

```<code>    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ITextRenderer renderer = new ITextRenderer();
    renderer.getFontResolver().addFont("fonts/VERDANA.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAB.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAZ.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.setDocumentFromString(... HTML as a String ...);
    renderer.layout();
    renderer.createPDF(out);

    FileOutputStream fos = new FileOutputStream(pathPdf);

    PdfReader reader = new PdfReader(baos.toByteArray());
    PdfStamper stamper = new PdfStamper(reader, fos);

    ... sets watermark image if available ...

    stamper.close();
    reader.close();
</code>```

I've tried getting the PdfDictionary and setting the metadata, getting the info map and setting the metadata, and getting the Document to set the metadata, but I cannot make it work.

答:
Found the solution:</p>

```<code>    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ITextRenderer renderer = new ITextRenderer();
    renderer.getFontResolver().addFont("fonts/VERDANA.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAB.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAZ.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.setDocumentFromString(... HTML as a String ...);
    renderer.layout();
    renderer.createPDF(out);

    FileOutputStream fos = new FileOutputStream(pathPdf);

    PdfReader reader = new PdfReader(baos.toByteArray());
    PdfStamper stamper = new PdfStamper(reader, fos);

    ... sets watermark image if available ...

    PdfDictionary info = reader.getTrailer().getAsDict(PdfName.INFO);
    info.getKeys().forEach((k) -> {
        System.out.println("k: " + k + ", v:" + info.get((PdfName) k));
    });
    info.put(PdfName.TITLE, new PdfString("Title", PdfObject.TEXT_UNICODE));
    info.put(PdfName.AUTHOR, new PdfString("Author", PdfObject.TEXT_UNICODE));

    stamper.close();
    reader.close();
</code>```

Body:
I'm trying to set the metadata (such as Title or Author) in a PDF file that I'm creating with FlyingSaucer (https://github.com/flyingsaucerproject/flyingsaucer) from an HTML file.

Here's the code that creates the PDF file:

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ITextRenderer renderer = new ITextRenderer();
    renderer.getFontResolver().addFont("fonts/VERDANA.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAB.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAZ.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.setDocumentFromString(... HTML as a String ...);
    renderer.layout();
    renderer.createPDF(out);

    FileOutputStream fos = new FileOutputStream(pathPdf);

    PdfReader reader = new PdfReader(baos.toByteArray());
    PdfStamper stamper = new PdfStamper(reader, fos);

    ... sets watermark image if available ...

    stamper.close();
    reader.close();

I've tried getting the PdfDictionary and setting the metadata, getting the info map and setting the metadata, and getting the Document to set the metadata, but I cannot make it work.

Body:
Found the solution:

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ITextRenderer renderer = new ITextRenderer();
    renderer.getFontResolver().addFont("fonts/VERDANA.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAB.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.getFontResolver().addFont("fonts/VERDANAZ.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    renderer.setDocumentFromString(... HTML as a String ...);
    renderer.layout();
    renderer.createPDF(out);

    FileOutputStream fos = new FileOutputStream(pathPdf);

    PdfReader reader = new PdfReader(baos.toByteArray());
    PdfStamper stamper = new PdfStamper(reader, fos);

    ... sets watermark image if available ...

    PdfDictionary info = reader.getTrailer().getAsDict(PdfName.INFO);
    info.getKeys().forEach((k) -> {
        System.out.println("k: " + k + ", v:" + info.get((PdfName) k));
    });
    info.put(PdfName.TITLE, new PdfString("Title", PdfObject.TEXT_UNICODE));
    info.put(PdfName.AUTHOR, new PdfString("Author", PdfObject.TEXT_UNICODE));

    stamper.close();
    reader.close();


问:
Pass a cython allocated buffer to python
I am aware of this post about passing over Cython malloc'ed data to Python. I however wonder if casting to a memoryview before returning avoids the memory leak:

```<code>def someCythonFunction():
    try:
        mPtr = <double *>PyMem_Malloc(N * M * sizeof(double)
        for n in range(N):
            for m in range(M):
                mPtr[m + n*M]= ...
        return <double[:N,:M]> mPtr
    finally:
        print("In cython %d" % <int>mPtr)
        PyMem_Free(mPtr)
</code>```

then in Python:

```<code>mView = someCythonFunction()
</code>```

Is this safe and correct ?

答:
This is unsafe and incorrect. It deallocates the memory as the function ends which means the pointer that you return is immediately invalid.

You need to tie the lifetime of the memory to the lifetime of a Python object (as in the example you linked to, the memory is freed in the destructor). The simplest and recommended way of doing this is to use a numpy array or a standard library array array (or other library of your choice).

If you can't avoid using malloc one option is to use the cython.view.array class. You can assign it a callback function of your choice to use on destruction and it can be happily assigned to memoryviews:

```<code>cdef double[:,:] mview
cdef double* mPtr = <double *>PyMem_Malloc(N * M * sizeof(double))
a = cython.view.array(shape=(N, M), itemsize=sizeof(double), format="d",
                      mode="C", allocate_buffer=False)
a.data = <char *> mPtr
a.callback_free_data = PyMem_Free

mview = a
</code>```

You can safely return either a or mview (if you return a then there's no need to bother with mview) and they will get correctly at the right time.

Body:
I am aware of this post about passing over Cython malloc'ed data to Python. I however wonder if casting to a memoryview before returning avoids the memory leak:

def someCythonFunction():
    try:
        mPtr = <double *>PyMem_Malloc(N * M * sizeof(double)
        for n in range(N):
            for m in range(M):
                mPtr[m + n*M]= ...
        return <double[:N,:M]> mPtr
    finally:
        print("In cython %d" % <int>mPtr)
        PyMem_Free(mPtr)

then in Python:

mView = someCythonFunction()

Is this safe and correct ?

Body:
This is unsafe and incorrect. It deallocates the memory as the function ends which means the pointer that you return is immediately invalid.

You need to tie the lifetime of the memory to the lifetime of a Python object (as in the example you linked to, the memory is freed in the destructor). The simplest and recommended way of doing this is to use a numpy array or a standard library array array (or other library of your choice).

If you can't avoid using malloc one option is to use the cython.view.array class. You can assign it a callback function of your choice to use on destruction and it can be happily assigned to memoryviews:

cdef double[:,:] mview
cdef double* mPtr = <double *>PyMem_Malloc(N * M * sizeof(double))
a = cython.view.array(shape=(N, M), itemsize=sizeof(double), format="d",
                      mode="C", allocate_buffer=False)
a.data = <char *> mPtr
a.callback_free_data = PyMem_Free

mview = a

You can safely return either a or mview (if you return a then there's no need to bother with mview) and they will get correctly at the right time.


问:
Do SELECT query based on statement returned from other SELECT
I have two tables:

```<code>notifications
- email_address
- notification_email

users
- username
- domain
- notifications
</code>```

My question is if I can build MySQL query which can do SELECT query based on statement returned from other SELECT without using scripting (Perl, Python, etc) and IF...ELSE statement?

Current code logic is set for queries below

```<code>SELECT notifications FROM users WHERE (username LIKE 'tester') AND (domain LIKE 'my.testdomain.com')

If notifications='Y' then

SELECT notification_email FROM notifications WHERE email_address = 'tester@my.testdomain.com'
</code>```

答:
You can put the first query in a WHERE clause.

```<code>SELECT notification_email FROM notifications
WHERE email_address = 'tester@my.testdomain.com'
AND EXISTS (
    SELECT 1
    FROM users
    WHERE username LIKE 'tester'
    AND domain LIKE 'my.testdomain.com'
    AND notifications = 'Y'
)
</code>```

FYI, if you don't have any wildcard characters, LIKE is the same as =.

Body:
I have two tables:

notifications
- email_address
- notification_email

users
- username
- domain
- notifications

My question is if I can build MySQL query which can do SELECT query based on statement returned from other SELECT without using scripting (Perl, Python, etc) and IF...ELSE statement?

Current code logic is set for queries below

SELECT notifications FROM users WHERE (username LIKE 'tester') AND (domain LIKE 'my.testdomain.com')

If notifications='Y' then

SELECT notification_email FROM notifications WHERE email_address = 'tester@my.testdomain.com'

Body:
You can put the first query in a WHERE clause.

SELECT notification_email FROM notifications
WHERE email_address = 'tester@my.testdomain.com'
AND EXISTS (
    SELECT 1
    FROM users
    WHERE username LIKE 'tester'
    AND domain LIKE 'my.testdomain.com'
    AND notifications = 'Y'
)

FYI, if you don't have any wildcard characters, LIKE is the same as =.


问:
How to serialize only not null properties in derived class in Json.Net
Entity objects needs converted to string to store them in log file for human reading.
Properties may added to derived entities at runtime. Serialize is defined in entity base class.
I triesd code below but it returns properties with null values also.
Since many properties have null values, it makes logs difficult to read.

Hoq to serialize only not-null properties ?
I tried also

```<code>        var jsonSettings = new JsonSerializerSettings()
        {
            DefaultValueHandling = DefaultValueHandling.Ignore,
            Formatting = Formatting.Indented,
            TypeNameHandling= TypeNameHandling.All
        };
        return JsonConvert.SerializeObject(this, GetType(), jsonSettings);
</code>```

this serializes only EntityBase class properties as confirmed in newtonsoft json does not serialize derived class properties

```<code>public class EntityBase {

        public string Serialize()
        {
            var s = new System.Web.Script.Serialization.JavaScriptSerializer();
            s.Serialize(this);

        }
     }

public class Customer: EntityBase {
  public string Name, Address;
  }
</code>```

testcase:

```<code>  var cust= new Customer() { Name="Test"};
  Debug.Writeline( cust.Serialize());
</code>```

Observed:  result contains "Address": null

Expected: result shoud not contain Address property.

ASP.NET/Mono MVC4, .NET 4.6 are used

答:
You can create your own serializer to ignore null properties.</p>

```<code>            JsonConvert.SerializeObject(
                object,
                Newtonsoft.Json.Formatting.None,
                new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
</code>```

Body:
Entity objects needs converted to string to store them in log file for human reading.
Properties may added to derived entities at runtime. Serialize is defined in entity base class.
I triesd code below but it returns properties with null values also.
Since many properties have null values, it makes logs difficult to read.

Hoq to serialize only not-null properties ?
I tried also

        var jsonSettings = new JsonSerializerSettings()
        {
            DefaultValueHandling = DefaultValueHandling.Ignore,
            Formatting = Formatting.Indented,
            TypeNameHandling= TypeNameHandling.All
        };
        return JsonConvert.SerializeObject(this, GetType(), jsonSettings);

this serializes only EntityBase class properties as confirmed in newtonsoft json does not serialize derived class properties

public class EntityBase {

        public string Serialize()
        {
            var s = new System.Web.Script.Serialization.JavaScriptSerializer();
            s.Serialize(this);

        }
     }

public class Customer: EntityBase {
  public string Name, Address;
  }

testcase:

  var cust= new Customer() { Name="Test"};
  Debug.Writeline( cust.Serialize());

Observed:  result contains "Address": null

Expected: result shoud not contain Address property.

ASP.NET/Mono MVC4, .NET 4.6 are used

Body:
You can create your own serializer to ignore null properties.

            JsonConvert.SerializeObject(
                object,
                Newtonsoft.Json.Formatting.None,
                new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });


问:
Java program to paint shows nothing
Using eclipse, I wrote a program trying to copy mspaint in Windows,there is no errors when build or run, I only complete several functions to test if it can be paint.

    I wrote the class named "drawings" to sotre drawings which has been paint,
if I set  current=0,it shows nothing ; if I set       current=1, a circle shows up   but when I release mouse,the circle disappear.

```<code>import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;

public class MyDraw extends JFrame{
static int current = 0;  // choice of different drawings, 0 means pencil
// 1 means circle
static int index=0; // the number of drawings
static int R,G,B;    // the color of drawings
static float Stroke=17.0f;  // the stroke of drawings
JLabel statusBar = new JLabel();// show the state of mouse
drawings []indexList=new drawings[5000];// store drawings to paint
DrawArea drawArea = new DrawArea();
public MyDraw(){
    R=G=B=0;// initialize color
//add components to main window
    add(drawArea);
    setVisible(true);
    setSize(1000,1000);
    createNewItem();  // new a drawing
    add(statusBar, BorderLayout.SOUTH);
     show();
}
 // new a drawing
public void createNewItem(){
    switch(current){
    case 0 :indexList[index]=new pencil();break;
    case 1 :indexList[index]=new circle();break;
    }
}
public static void main(String args[]){
    new MyDraw();
}
// the panel to paint on
 class DrawArea extends JPanel{
    public DrawArea(){
        setBackground(Color.white);
        setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        addMouseListener(new MousePolice1());
        addMouseMotionListener(new MousePolice2());
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d =(Graphics2D)g;
        for(int j=0;j<=index;j++){
            pass(indexList[index],g2d);
        }
    }
    public void pass(drawings i,Graphics2D g2d){
        i.draw(g2d);
    }

}
 class MousePolice2 extends MouseAdapter{
    public void mouseDragged(MouseEvent e){

             statusBar.setText("     Mouse Dragged @:[" + e.getX() +
                        ", " + e.getY() + "]");
                if (current == 0) {

                    indexList[index - 1].x1 = indexList[index].x2 =
indexList[index].x1 = e.getX();
                    indexList[index - 1].y1 = indexList[index].y2 =
indexList[index].y1 = e.getY();
                    index++;
                    createNewItem();

                } else {
                    indexList[index].x2 = e.getX();
                    indexList[index].y2 = e.getY();
                }
                repaint();
            }

}
class MousePolice1 extends MouseAdapter{
    public void mousePressed(MouseEvent e){
           statusBar.setText("     Mouse Pressed @:[" + e.getX() +
                    ", " + e.getY() + "]");
            indexList[index].x1 = indexList[index].x2 = e.getX();
            indexList[index].y1 = indexList[index].y2 = e.getY();

            if (current == 0 ) {
                indexList[index].x1 = indexList[index].x2 = e.getX();
                indexList[index].y1 = indexList[index].y2 = e.getY();
                index++;
                createNewItem();
            }

    }

    public void mouseReleased(MouseEvent e){

           statusBar.setText("     Mouse Released @:[" + e.getX() +
                    ", " + e.getY() + "]");
            if (current ==0) {
                indexList[index].x1 = e.getX();
                indexList[index].y1 = e.getY();
            }
            indexList[index].x2 = e.getX();
            indexList[index].y2 = e.getY();
            repaint();
            index++;
            createNewItem();
    }
}

}

//the father
class drawings implements Serializable{
    int x1,x2,y1,y2;
    void draw(Graphics2D g2d){}
}
// the drawing pencil
class pencil extends drawings{
void draw(Graphics2D g2d){
    g2d.setPaint(new Color(MyDraw.R,MyDraw.G,MyDraw.B));
    g2d.setStroke(new BasicStroke(MyDraw.Stroke,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
       g2d.drawLine(x1, y1, x2, y2);
}
}
class circle extends drawings
{
void draw(Graphics2D g2d) {
    g2d.setPaint(new Color(MyDraw.R,MyDraw.G,MyDraw.B));
    g2d.setStroke(new BasicStroke(MyDraw.Stroke));
    g2d.drawOval(Math.min(x1, x2), Math.min(y1, y2),
            Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)),
            Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)));
}
}
</code>```

答:
Didn't I see it or where is the method show()?

Otherwise I just saw some programs which they need to do something like this with the windows:

```<code>setVisible(true);
</code>```

Title: Java program to paint shows nothing

Body:
Using eclipse, I wrote a program trying to copy mspaint in Windows,there is no errors when build or run, I only complete several functions to test if it can be paint.

    I wrote the class named "drawings" to sotre drawings which has been paint,
if I set  current=0,it shows nothing ; if I set       current=1, a circle shows up   but when I release mouse,the circle disappear.

import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;

public class MyDraw extends JFrame{
static int current = 0;  // choice of different drawings, 0 means pencil
// 1 means circle
static int index=0; // the number of drawings
static int R,G,B;    // the color of drawings
static float Stroke=17.0f;  // the stroke of drawings
JLabel statusBar = new JLabel();// show the state of mouse
drawings []indexList=new drawings[5000];// store drawings to paint
DrawArea drawArea = new DrawArea();
public MyDraw(){
    R=G=B=0;// initialize color
//add components to main window
    add(drawArea);
    setVisible(true);
    setSize(1000,1000);
    createNewItem();  // new a drawing
    add(statusBar, BorderLayout.SOUTH);
     show();
}
 // new a drawing
public void createNewItem(){
    switch(current){
    case 0 :indexList[index]=new pencil();break;
    case 1 :indexList[index]=new circle();break;
    }
}
public static void main(String args[]){
    new MyDraw();
}
// the panel to paint on
 class DrawArea extends JPanel{
    public DrawArea(){
        setBackground(Color.white);
        setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        addMouseListener(new MousePolice1());
        addMouseMotionListener(new MousePolice2());
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d =(Graphics2D)g;
        for(int j=0;j<=index;j++){
            pass(indexList[index],g2d);
        }
    }
    public void pass(drawings i,Graphics2D g2d){
        i.draw(g2d);
    }

}
 class MousePolice2 extends MouseAdapter{
    public void mouseDragged(MouseEvent e){

             statusBar.setText("     Mouse Dragged @:[" + e.getX() +
                        ", " + e.getY() + "]");
                if (current == 0) {

                    indexList[index - 1].x1 = indexList[index].x2 =
indexList[index].x1 = e.getX();
                    indexList[index - 1].y1 = indexList[index].y2 =
indexList[index].y1 = e.getY();
                    index++;
                    createNewItem();

                } else {
                    indexList[index].x2 = e.getX();
                    indexList[index].y2 = e.getY();
                }
                repaint();
            }

}
class MousePolice1 extends MouseAdapter{
    public void mousePressed(MouseEvent e){
           statusBar.setText("     Mouse Pressed @:[" + e.getX() +
                    ", " + e.getY() + "]");
            indexList[index].x1 = indexList[index].x2 = e.getX();
            indexList[index].y1 = indexList[index].y2 = e.getY();

            if (current == 0 ) {
                indexList[index].x1 = indexList[index].x2 = e.getX();
                indexList[index].y1 = indexList[index].y2 = e.getY();
                index++;
                createNewItem();
            }

    }

    public void mouseReleased(MouseEvent e){

           statusBar.setText("     Mouse Released @:[" + e.getX() +
                    ", " + e.getY() + "]");
            if (current ==0) {
                indexList[index].x1 = e.getX();
                indexList[index].y1 = e.getY();
            }
            indexList[index].x2 = e.getX();
            indexList[index].y2 = e.getY();
            repaint();
            index++;
            createNewItem();
    }
}

}

//the father
class drawings implements Serializable{
    int x1,x2,y1,y2;
    void draw(Graphics2D g2d){}
}
// the drawing pencil
class pencil extends drawings{
void draw(Graphics2D g2d){
    g2d.setPaint(new Color(MyDraw.R,MyDraw.G,MyDraw.B));
    g2d.setStroke(new BasicStroke(MyDraw.Stroke,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
       g2d.drawLine(x1, y1, x2, y2);
}
}
class circle extends drawings
{
void draw(Graphics2D g2d) {
    g2d.setPaint(new Color(MyDraw.R,MyDraw.G,MyDraw.B));
    g2d.setStroke(new BasicStroke(MyDraw.Stroke));
    g2d.drawOval(Math.min(x1, x2), Math.min(y1, y2),
            Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)),
            Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)));
}
}

Body:
Didn't I see it or where is the method show()?

Otherwise I just saw some programs which they need to do something like this with the windows:

setVisible(true);


问:
The default remember_me token in Laravel is too long
TL;DR How can I use my own way of generating the remember_me token?

I have an old site, written without any framework, and I have been given the job to rewrite it in Laravel (5.4.23). The DB is untouchable, cannot be refactored, cannot be modified in any way.

I was able to customise the Laravel authentication process using a different User model, one that reflect the old DB. But when it comes to the "Remember me" functionality, I have an issue with the length of the token.

The old site already uses the "Remember me" functionality but its DB field has been defined as BINARY(25). The token generated by the SessionGuard class is 60 characters long.

My first attempt was to try and find a way to shorten the token before writing it into the DB, and expand it again after reading it from the DB. I couldn't find such a way (and I'm not even sure there is such a way).

Then I looked into writing my own guard to override the cycleRememberToken (where the token is generated). I couldn't make it work, I think because the SessionGuard class is actually instantiated in a couple of places (as opposed to instantiate a class based on configuration).

So, I am stuck. I need a shorten token and I don't know how to get it.

答:
Well, I was on the right track at one point.

I had to create my own guard, register it and use it. My problem, when I tried the first time, was that I did not register it in the right way. Anyway, this is what I did.

I put the following in AuthServiceProvides

```<code>Auth::extend('mysession', function ($app, $name, array $config) {
  $provider = Auth::createUserProvider($config['provider']);

  $guard = new MyGuard('lrb', $provider, app()->make('session.store'));

  $guard->setCookieJar($this->app['cookie']);
  $guard->setDispatcher($this->app['events']);
  $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));

  return $guard;
});
</code>```

I change the guard in config/auth.php as

```<code>'guards' => [
    'web' => [
        'driver' => 'mysession',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],
</code>```

and finally my new guard

```<code>class MyGuard extends SessionGuard implements StatefulGuard, SupportsBasicAuth
{
    /**
     * @inheritdoc
     */
    protected function cycleRememberToken(AuthenticatableContract $user)
    {
        $user->setRememberToken($token = Str::random(25));

        $this->provider->updateRememberToken($user, $token);
    }

}
</code>```

Body:
Well, I was on the right track at one point.

I had to create my own guard, register it and use it. My problem, when I tried the first time, was that I did not register it in the right way. Anyway, this is what I did.

I put the following in AuthServiceProvides

Auth::extend('mysession', function ($app, $name, array $config) {
  $provider = Auth::createUserProvider($config['provider']);

  $guard = new MyGuard('lrb', $provider, app()->make('session.store'));

  $guard->setCookieJar($this->app['cookie']);
  $guard->setDispatcher($this->app['events']);
  $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));

  return $guard;
});

I change the guard in config/auth.php as

'guards' => [
    'web' => [
        'driver' => 'mysession',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

and finally my new guard

class MyGuard extends SessionGuard implements StatefulGuard, SupportsBasicAuth
{
    /**
     * @inheritdoc
     */
    protected function cycleRememberToken(AuthenticatableContract $user)
    {
        $user->setRememberToken($token = Str::random(25));

        $this->provider->updateRememberToken($user, $token);
    }

}


问:
fetchXML use multiple filters on a linked entity
In an SSRS report I am trying to use multiply filters on a link-entity; however, it doesn't seem to be working.

Could someone look at this and tell me why it's wrong?

```<code><fetch distinct="false" no-lock="false" mapping="logical">
<entity name="jobsite" enableprefiltering="1" prefilterparametername="CRM_Filteredjobsite">
    <attribute name="jobsiteid" />
    <link-entity name="invoice" to="jobsiteid" from="jobsite" link-type="outer">
        <attribute name="jobtype" />
        <attribute name="service_completed_on" />
        <attribute name="invoicedate" />
        <attribute name="statecode" />
        <order attribute="service_completed_on" descending="true" />
        <order attribute="invoicedate" descending="true" />
        <filter type="or">
              <condition attribute='statecode' operator='ne' value='Canceled'/>
              <condition attribute='jobtype' operator='ne' value='Internal'/>
        </filter>
    </link-entity>
</entity>
</code>```

I have tried using no type, type='and', type='or', a filter within a filter

```<code><filter>
  ...
</filter>

<filter type="or">
          <condition attribute='statecode' operator='ne' value='Canceled'/>
          <filter type="or">
                  <condition attribute='gsdac_jobtype' operator='ne' value='Internal'/>
          </filter>
</filter>
</code>```

and varying combinations of these.

Any assistance you could offer would be most helpful, and I would be ever grateful.

Thank you,
William

EDIT: I should also say that the fetchxml works, it even filters the canceled invoices, but it seems to be ignoring the 2nd filter.

答:
So apparently Jobtype is a calculated field, and not a simple field as I was told.

can't sort on a calculated field.... so that answers that I guess.

Thanks for your efforts.

```<code>    <filter type="or">
          <condition attribute='field1' operator='ne' value='somevalue'/>
          <condition attribute='field2' operator='ne' value='somevalue'/>
    </filter>
</code>```

is the correct syntax for using multiply filters.

Body:
In an SSRS report I am trying to use multiply filters on a link-entity; however, it doesn't seem to be working.

Could someone look at this and tell me why it's wrong?

<fetch distinct="false" no-lock="false" mapping="logical">
<entity name="jobsite" enableprefiltering="1" prefilterparametername="CRM_Filteredjobsite">
    <attribute name="jobsiteid" />
    <link-entity name="invoice" to="jobsiteid" from="jobsite" link-type="outer">
        <attribute name="jobtype" />
        <attribute name="service_completed_on" />
        <attribute name="invoicedate" />
        <attribute name="statecode" />
        <order attribute="service_completed_on" descending="true" />
        <order attribute="invoicedate" descending="true" />
        <filter type="or">
              <condition attribute='statecode' operator='ne' value='Canceled'/>
              <condition attribute='jobtype' operator='ne' value='Internal'/>
        </filter>
    </link-entity>
</entity>

I have tried using no type, type='and', type='or', a filter within a filter

<filter>
  ...
</filter>

<filter type="or">
          <condition attribute='statecode' operator='ne' value='Canceled'/>
          <filter type="or">
                  <condition attribute='gsdac_jobtype' operator='ne' value='Internal'/>
          </filter>
</filter>

and varying combinations of these.

Any assistance you could offer would be most helpful, and I would be ever grateful.

Thank you,
William

EDIT: I should also say that the fetchxml works, it even filters the canceled invoices, but it seems to be ignoring the 2nd filter.

Body:
So apparently Jobtype is a calculated field, and not a simple field as I was told.

can't sort on a calculated field.... so that answers that I guess.

Thanks for your efforts.

    <filter type="or">
          <condition attribute='field1' operator='ne' value='somevalue'/>
          <condition attribute='field2' operator='ne' value='somevalue'/>
    </filter>

is the correct syntax for using multiply filters.


问:
How to Dynamically build Select as relates to Linq & Entity Framework
I would like to do the following

```<code>public async Task<List<dynamic>> searchEntities(string query, list<string> columnNames)
{
   var columNames = GetPropertiesUsingReflectionAndfilter<Entity>(columnNames);
   await db.entities.select(x => { columnNames }).where(...)..ToListAsync();
}
</code>```

I need to expose a custom EF Search Method in a Controller.  I would like to offer a partial response.  $search is not avail in version of OData I am using.

Is this possible with IQueryable perhaps?

Alternative would be to build Parameterized SQL query.  Would like to know if there is a better way using EF and Linq?  Thanks..

Solution:

Thanks to @IvanStoev, I ultimately added a library, System.Linq.Dynamic (free with > 1 million downloads), to accomplish this.  I now have.

```<code>using System.Linq.Dynamic;

            var columnNames = GetColumNames<Entity>(qry.TableList);
            var selector = "new(" + String.Join(", ", columnNames.ToArray()) + ")";

            var results = await db.Lessons
                .Where(x => x.LessonName.Contains(qry.Query) == true || x.HTML.Contains(qry.Query) == true)
                .Select(selector)
                .ToListAsync();

            return Ok(results);
</code>```

TLDR.  Full usage for my scenario.

Controller:

```<code>[HttpPost, Route("Search/Lessons")]
public async Task<IHttpActionResult> SearchLessons([FromBody] SearchQuery qry)
{
    var columnNames = GetColumNames<Lesson>(qry.TableList);

    if (columnNames.Count < 1) {
        return BadRequest();
    }

    var selector = "new(" + String.Join(", ", columnNames.ToArray()) + ")";

    var results = await db.Lessons
        .Where(x => x.LessonName.Contains(qry.Query) == true || x.HTML.Contains(qry.Query) == true)
        .Select(selector)
        .ToListAsync();

    return Ok(results);
}
</code>```

And Helpers:..

```<code>private List<string> GetColumNames<T>(List<string> columnsToFetch = null)
{
    var properties = GetProperties<T>();
    var columnNames = new List<string>();

    if (columnsToFetch == null)
    {
        return properties;
    }

    foreach (var columnRequested in columnsToFetch)
    {
        var matchedColumn = properties
            .Where(x => x.ToLower() == columnRequested.ToLower())
            .FirstOrDefault();

        if (matchedColumn != default(string))
        {
            columnNames.Add(matchedColumn);
        }
    }

    return columnNames;
}
</code>```

And..

```<code>private List<string> GetProperties<T>()
    {
        dynamic model = TypeDescriptor.GetProperties(Activator.CreateInstance<T>());

        List<string> result = new List<string>();
        foreach (var prop in model)
        {
            result.Add(prop.Name);
        }
        return result;
    }
</code>```

答:
I don't see how that would be possible.

First of all, to return the list from searchEntities, the select would need to create a named object.

What you could do is pass in a function-expression to searchEntities

```<code>public Task<List<T>>  searchEntities<T>(EXpression<Func<Entity, T> selector)
{
    return await db.entities.select(selector).where(...)..ToListAsync();
}

Expression<Func<Entity, AdHocClass1> selector1 = (Entity e)=> new AdHocClass1 {...};
</code>```

Body:
I would like to do the following

public async Task<List<dynamic>> searchEntities(string query, list<string> columnNames)
{
   var columNames = GetPropertiesUsingReflectionAndfilter<Entity>(columnNames);
   await db.entities.select(x => { columnNames }).where(...)..ToListAsync();
}

I need to expose a custom EF Search Method in a Controller.  I would like to offer a partial response.  $search is not avail in version of OData I am using.

Is this possible with IQueryable perhaps?

Alternative would be to build Parameterized SQL query.  Would like to know if there is a better way using EF and Linq?  Thanks..

Solution:

Thanks to @IvanStoev, I ultimately added a library, System.Linq.Dynamic (free with > 1 million downloads), to accomplish this.  I now have.

using System.Linq.Dynamic;

            var columnNames = GetColumNames<Entity>(qry.TableList);
            var selector = "new(" + String.Join(", ", columnNames.ToArray()) + ")";

            var results = await db.Lessons
                .Where(x => x.LessonName.Contains(qry.Query) == true || x.HTML.Contains(qry.Query) == true)
                .Select(selector)
                .ToListAsync();

            return Ok(results);

TLDR.  Full usage for my scenario.

Controller:

[HttpPost, Route("Search/Lessons")]
public async Task<IHttpActionResult> SearchLessons([FromBody] SearchQuery qry)
{
    var columnNames = GetColumNames<Lesson>(qry.TableList);

    if (columnNames.Count < 1) {
        return BadRequest();
    }

    var selector = "new(" + String.Join(", ", columnNames.ToArray()) + ")";

    var results = await db.Lessons
        .Where(x => x.LessonName.Contains(qry.Query) == true || x.HTML.Contains(qry.Query) == true)
        .Select(selector)
        .ToListAsync();

    return Ok(results);
}

And Helpers:..

private List<string> GetColumNames<T>(List<string> columnsToFetch = null)
{
    var properties = GetProperties<T>();
    var columnNames = new List<string>();

    if (columnsToFetch == null)
    {
        return properties;
    }

    foreach (var columnRequested in columnsToFetch)
    {
        var matchedColumn = properties
            .Where(x => x.ToLower() == columnRequested.ToLower())
            .FirstOrDefault();

        if (matchedColumn != default(string))
        {
            columnNames.Add(matchedColumn);
        }
    }

    return columnNames;
}

And..

private List<string> GetProperties<T>()
    {
        dynamic model = TypeDescriptor.GetProperties(Activator.CreateInstance<T>());

        List<string> result = new List<string>();
        foreach (var prop in model)
        {
            result.Add(prop.Name);
        }
        return result;
    }

Body:
I don't see how that would be possible.

First of all, to return the list from searchEntities, the select would need to create a named object.

What you could do is pass in a function-expression to searchEntities

public Task<List<T>>  searchEntities<T>(EXpression<Func<Entity, T> selector)
{
    return await db.entities.select(selector).where(...)..ToListAsync();
}

Expression<Func<Entity, AdHocClass1> selector1 = (Entity e)=> new AdHocClass1 {...};


问:
Why, exactly, does performance suffer when I request more .js files rather than less?
Say I have a javacsript file containing ten components. Why, exactly, is this better for performance than loading 10 files containing a component each? It seems like it's the same amount of data? So what's the difference?</p>

答:
The difference is that browsers don't load all resources at the same time.  Most browsers only have 2-4 concurrent requests open, so if you have 5 JS files, the browser will request the first four and then wait until one of them completes before requesting the 5th.  Some older browsers only request one JavaScript file at a time, and wait until it's fully parsed before fetching the next.

Often the network time is the worst part of the user experience (especially in some parts of the world or on some devices), so having a bundle where only one request is made instead of 5 means your app will feel more responsive.

There are a number of good articles online about this as well, YSlow was one of the first tools & metrics used to check these things, but there are others.


问:
OneNote Graph API Expose author information for individual edits
The OneNote Graph API allows the content of OneNote notebooks to be retreived. The section and sectionGroup resources have a lastModifiedBy and lastModifiedDate which gives us author and timestamp information.

The OneNote application itself (both web and desktop versions) exposes author information about individual edits within the HTML content of a page. Given this information is available to OneNote, can it be exposed through the Graph API?

Also, we would appreciate lastModifiedBy on the page object (it already has lastModifiedDateTime).

答:
In theory, both asks you mentioned are possible. Could you create uservoice entries so we can track these asks?

https://onenote.uservoice.com/forums/245490-onenote-developer-apis


问:
React Native Android Slider cannot slide vertically on device
I've used the Slider component on React Native 0.43 using the following code. It works fine for iOS as it has a nice big "button" for user to hold and drag. But on android it is just a small dot and I find that I could not drag it vertically (1/10 tries are successful). I find that the "drag" get captured by the ScrollView in the background instead. Help?

```<code>      <Slider
        minimumValue={minValue}
        maximumValue={maxValue}
        step={step}
        style={styles.slider}
        value={parseInt(input.value)}
        onSlidingComplete={onSlidingComplete}
        onValueChange={onValueChange}
      />

  slider: {
    marginRight:-100,
    marginLeft:-100,
    width:250,
    transform: [
      { rotateZ : '-90deg' },
    ],
  },
</code>```

答: I had some issues with react-native's slider component behaving weird on real iOS devices so I opted to use react-native-slider instead.

Body:
I've used the Slider component on React Native 0.43 using the following code. It works fine for iOS as it has a nice big "button" for user to hold and drag. But on android it is just a small dot and I find that I could not drag it vertically (1/10 tries are successful). I find that the "drag" get captured by the ScrollView in the background instead. Help?

      <Slider
        minimumValue={minValue}
        maximumValue={maxValue}
        step={step}
        style={styles.slider}
        value={parseInt(input.value)}
        onSlidingComplete={onSlidingComplete}
        onValueChange={onValueChange}
      />

  slider: {
    marginRight:-100,
    marginLeft:-100,
    width:250,
    transform: [
      { rotateZ : '-90deg' },
    ],
  },


答:
Simply put, it's not about the size of the requests it's about the amount of requests and whether or not they are synchronous or asynchronous.

Synchronous programming means that, barring conditionals and function calls, code is executed sequentially from top-to-bottom, blocking on long-running tasks such as network requests and disk I/O.

Asynchronous programming means that the engine runs in an event loop. When a blocking operation is needed, the request is started, and the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations.

And as this answer by Cletus explains:

JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The code will stop executing until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.

This is why your performance suffers when you load more JavaScript files.

Title: Why, exactly, does performance suffer when I request more .js files rather than less?

Body: Say I have a javacsript file containing ten components. Why, exactly, is this better for performance than loading 10 files containing a component each? It seems like it's the same amount of data? So what's the difference?


问:
T-SQL Combine Ranges Based On Value
I am using SQL Server 2012 and have been struggling with this query for hours.    I am trying to aggregate mile post ranges based off the value in the Value column. The results should have unique segments with the highest value from the Value field for each segment.  Here's an example:

```<code>Mile_Marker_Start | Mile_Marker_End | Value
      0                100              5
     50                150              6
    100                200             10
     75                300              9
    150                200              7
</code>```

And here's the result I'm looking for:

```<code>Mile_Marker_Start | Mile_Marker_End | Value
       0                 50             5
      50                 75             6
      75                100             9
     100                200            10
     200                300             9
</code>```

As you can see, the row with a value of 9 got split into 2 rows because Value 10 was bigger. Also, the row with Value 7 does not display because Value 10 was bigger.  Can this be done without using a cursor?  Any help would be much appreciated.

Thanks

答:
Since you are on 2012 you could maybe use LEAD. Here is my code but as noted on your question by @stevelovell , we need clarification on how you are getting your result table.
<s>
    --test date
    declare  @tablename TABLE
    (
       Mile_Marker_Start int,
       Mile_Marker_End int,
       Value int
    );

```<code>insert into @tablename
      values(0,100, 5),
     (50,150, 6),
    (100,200,10),
     (75,300, 9),
    (150,200, 7);

--query
select  *
from @tablename
order by Mile_Marker_Start

select Mile_Marker_Start,
    case when lead(mile_marker_start) over(order by mile_marker_start) < Mile_Marker_End THEN
        lead(mile_marker_start) over(order by mile_marker_start)
        ELSE
            Mile_marker_end
        END
        AS MILE_MARKER_END,
     Value
from @tablename
order by Mile_Marker_Start
</code>```

</S>
Once you update your notes I will come back and update my answer.
Update: wasn't able to get LEAD and the other windowing functions to work with your requirements. With the way you need to move up and down the table current, and calculated values...

Title: T-SQL Combine Ranges Based On Value

Body:
I am using SQL Server 2012 and have been struggling with this query for hours.    I am trying to aggregate mile post ranges based off the value in the Value column. The results should have unique segments with the highest value from the Value field for each segment.  Here's an example:

Mile_Marker_Start | Mile_Marker_End | Value
      0                100              5
     50                150              6
    100                200             10
     75                300              9
    150                200              7

And here's the result I'm looking for:

Mile_Marker_Start | Mile_Marker_End | Value
       0                 50             5
      50                 75             6
      75                100             9
     100                200            10
     200                300             9

As you can see, the row with a value of 9 got split into 2 rows because Value 10 was bigger. Also, the row with Value 7 does not display because Value 10 was bigger.  Can this be done without using a cursor?  Any help would be much appreciated.

Thanks

Body:
Since you are on 2012 you could maybe use LEAD. Here is my code but as noted on your question by @stevelovell , we need clarification on how you are getting your result table.
<s>
    --test date
    declare  @tablename TABLE
    (
       Mile_Marker_Start int,
       Mile_Marker_End int,
       Value int
    );

insert into @tablename
      values(0,100, 5),
     (50,150, 6),
    (100,200,10),
     (75,300, 9),
    (150,200, 7);

--query
select  *
from @tablename
order by Mile_Marker_Start

select Mile_Marker_Start,
    case when lead(mile_marker_start) over(order by mile_marker_start) < Mile_Marker_End THEN
        lead(mile_marker_start) over(order by mile_marker_start)
        ELSE
            Mile_marker_end
        END
        AS MILE_MARKER_END,
     Value
from @tablename
order by Mile_Marker_Start

</S>
Once you update your notes I will come back and update my answer.
Update: wasn't able to get LEAD and the other windowing functions to work with your requirements. With the way you need to move up and down the table current, and calculated values...


问:
AOT (Ahead-Of-Time) Compilation with ES5
Is it possible to do AOT compilation in Angular using only ES5?

More to the point, can I use the NGTools Webpack plugin with ES5?

I know TypeScript is the preferable language of choice for Angular, however my place of employment did not approve using TypeScript for our Angular project.  My hands are a bit tied, and I don't want performance to suffer on the client due to this.

Some relevant info on my project:

Webpack 2 for build/packaging

Written in ES2015 transpiled to ES5 using Babel

I have looked all over and have not been able to find a clear answer on this, I would really appreciate any info anyone can provide.

Thanks in advance!

答:
Angular is supposed to be fully ES5 compatible.

The AOT compiling process uses the metadata attached to components. This is how it finds the templates and styles that need compiling.

TypeScript is the preferred method for writing components. As it allows you to use the @Component annotation function to attach metadata .

ES6 is secondary method and Angular supports ES6 decorators to attach metadata to components.

ES5 is more basic. There isn't any automatic way to attach metadata, but the AOT compiler will look for a annotations array attached to the object's prototype.

This is how you would do it using ES5

```<code>HeroComponent.annotations = [
     new ng.core.Component({
        selector: 'hero-view',
        template: '<h1>{{title}}: {{getName()}}</h1>'
     })
];
</code>```

So to answer your question. Yes, you can still use AOT with ES5.

Body:
Angular is supposed to be fully ES5 compatible.

The AOT compiling process uses the metadata attached to components. This is how it finds the templates and styles that need compiling.

TypeScript is the preferred method for writing components. As it allows you to use the @Component annotation function to attach metadata .

ES6 is secondary method and Angular supports ES6 decorators to attach metadata to components.

ES5 is more basic. There isn't any automatic way to attach metadata, but the AOT compiler will look for a annotations array attached to the object's prototype.

This is how you would do it using ES5

HeroComponent.annotations = [
     new ng.core.Component({
        selector: 'hero-view',
        template: '<h1>{{title}}: {{getName()}}</h1>'
     })
];

So to answer your question. Yes, you can still use AOT with ES5.


问:
adding "last edit time" to trac wiki pages
My organization has a sprawling wiki that isn't kept up to date very well. To reduce the danger of new people reading a page and not realizing how outdated it is, I'd like to modify the page header so that instead of

Page Name

at the top, it says something like

Page Name - last modified 5/8/10 by Joe

I see that Trac allows page templates, but if we haven't used those before, is there a 'blank' template I could alter to change all existing pages?

答: Unless you have changed something, Trac wiki pages should have a "Last Modified" entry in the top right-hand corner of each page.  Hovering the mouse over different parts of the text will show you more details, like the user name of the last person to edit the page and a detailed timestamp of when the last edit was made.  Is this different from the functionality that you are asking about?</p>


问:
how to get the days and exact minutes,exact hours from two dates in javascript?
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

```<code>var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}
</code>```

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance

答:
Well, if you look at documentation for javascript Date objects, there is a getTime() method . You can also use the valueOf() method. They both return the number of milliseconds representing your Date object.

You can simply call that on both Date objects and then find the difference. Once you have the difference you can find the amount of secs, mins , hrs, days, etc. Here is an example:

```<code>var start = new Date(*some date*);
var end = new Date(*some date*);
var dif = end.valueOf() - start.valueOf();
if (dif >= 0) {
    var secs = Math.floor(dif / 1000 % 60);
    var mins = Math.floor(dif / 1000 / 60 % 60);
    var hrs = Math.floor(dif / 1000 / 60 / 60 % 24);
    var days =
        Math.floor(dif / 1000 / 60 / 60 / 24 % 365);
    var yrs =
        Math.floor(dif / 1000 / 60 / 60 / 24 / 365);
</code>```

Body:
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance

Body:
Well, if you look at documentation for javascript Date objects, there is a getTime() method . You can also use the valueOf() method. They both return the number of milliseconds representing your Date object.

You can simply call that on both Date objects and then find the difference. Once you have the difference you can find the amount of secs, mins , hrs, days, etc. Here is an example:

var start = new Date(*some date*);
var end = new Date(*some date*);
var dif = end.valueOf() - start.valueOf();
if (dif >= 0) {
    var secs = Math.floor(dif / 1000 % 60);
    var mins = Math.floor(dif / 1000 / 60 % 60);
    var hrs = Math.floor(dif / 1000 / 60 / 60 % 24);
    var days =
        Math.floor(dif / 1000 / 60 / 60 / 24 % 365);
    var yrs =
        Math.floor(dif / 1000 / 60 / 60 / 24 / 365);


问:
@SuppressWarnings ArrayList<X> may not contain objects of type Y
I have a class called CompressedCardInfo that has an MtgCard as a member of it, and CompressedCardInfo's (or classes extending it) have overloaded the equals method to take into account checking if a CompressedCardInfo equals an MtgCard.

Now this isn't extremely important, as they are only warnings (they bother me however), but when I have CompressedCardInfo in an ArrayList and call ArrayList.contains or .indexOf I get the warning telling me that the list might not have objects of type MtgCard in it.

How do I suppress this specific warning about this List? Or is there a better way of handling that kind of comparison?

Thanks.

```<code>for (Pair<MtgCard, Boolean> card : decklist) {
            /* Translate the set code to TCG name of course it's not saved */
            card.first.setName = CardDbAdapter.getSetNameFromCode(card.first.setCode, database);
            if (changedCardName == null || changedCardName.equals(card.first.mName)) {
                if (mCompressedDecklist.contains(card.first)) {
                    CompressedDecklistInfo existingCard = mCompressedDecklist.get(mCompressedDecklist.indexOf(card.first));
                    if (existingCard.mIsSideboard == card.second) {
                        mCompressedDecklist.get(mCompressedDecklist.indexOf(card.first)).add(card.first);
                    } else {
                        mCompressedDecklist.add(new CompressedDecklistInfo(card.first, card.second));
                    }
                } else {
                    mCompressedDecklist.add(new CompressedDecklistInfo(card.first, card.second));
                }
                if (mShowTotalDecklistPrice) {
                    loadPrice(card.first.mName, card.first.setCode, card.first.mNumber);
                }
            }
        }
</code>```

The calls on lines 5 (contains), 6 (indexOf), and 8 (indexOf). I get warnings there because the ArrayList is of type CompressedDecklistInfo (which is extended from CompressedCardInfo. This also happens in other places.

答: So I'm just going to follow best practices and fix these issues properly.</p>

Body:
I have a class called CompressedCardInfo that has an MtgCard as a member of it, and CompressedCardInfo's (or classes extending it) have overloaded the equals method to take into account checking if a CompressedCardInfo equals an MtgCard.

Now this isn't extremely important, as they are only warnings (they bother me however), but when I have CompressedCardInfo in an ArrayList and call ArrayList.contains or .indexOf I get the warning telling me that the list might not have objects of type MtgCard in it.

How do I suppress this specific warning about this List? Or is there a better way of handling that kind of comparison?

Thanks.

for (Pair<MtgCard, Boolean> card : decklist) {
            /* Translate the set code to TCG name of course it's not saved */
            card.first.setName = CardDbAdapter.getSetNameFromCode(card.first.setCode, database);
            if (changedCardName == null || changedCardName.equals(card.first.mName)) {
                if (mCompressedDecklist.contains(card.first)) {
                    CompressedDecklistInfo existingCard = mCompressedDecklist.get(mCompressedDecklist.indexOf(card.first));
                    if (existingCard.mIsSideboard == card.second) {
                        mCompressedDecklist.get(mCompressedDecklist.indexOf(card.first)).add(card.first);
                    } else {
                        mCompressedDecklist.add(new CompressedDecklistInfo(card.first, card.second));
                    }
                } else {
                    mCompressedDecklist.add(new CompressedDecklistInfo(card.first, card.second));
                }
                if (mShowTotalDecklistPrice) {
                    loadPrice(card.first.mName, card.first.setCode, card.first.mNumber);
                }
            }
        }

The calls on lines 5 (contains), 6 (indexOf), and 8 (indexOf). I get warnings there because the ArrayList is of type CompressedDecklistInfo (which is extended from CompressedCardInfo. This also happens in other places.


问:
how to find totally duplicate object in array?
Here is an example js array:

```<code>var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
]
</code>```

Is there a way to find duplicate object (by all key/value pairs)?
If so - how to do that?
Thanks in advance.

答:
Assuming it’s enough to just decide whether an object o1 is a duplicate of o2 or not, you can try the following:

```<code>function isDuplicate(o1, o2) {
  return JSON.stringify(o1) == JSON.stringify(o2);
}
</code>```

Body:
Here is an example js array:

var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
]

Is there a way to find duplicate object (by all key/value pairs)?
If so - how to do that?
Thanks in advance.

Body:
Assuming it’s enough to just decide whether an object o1 is a duplicate of o2 or not, you can try the following:

function isDuplicate(o1, o2) {
  return JSON.stringify(o1) == JSON.stringify(o2);
}


问:
Escape special characters of JSON in c#
I hava JSON object with one field has string value

```<code>" Ran a defrag removed a few virus' and tried again "
</code>```

' is special character in JSON. I am using c#, NewtonSoftJSON library.

Is there any best way to  escape all special character with Newtonsoft and c#.

答:
This worked for me ->

System.Web.Helpers.Json.Encode(inputString).Substring(1, System.Web.Helpers.Json.Encode(inputString).Length - 2);

Title: Escape special characters of JSON in c#

Body:
I hava JSON object with one field has string value

" Ran a defrag removed a few virus' and tried again "

' is special character in JSON. I am using c#, NewtonSoftJSON library.

Is there any best way to  escape all special character with Newtonsoft and c#.