问:
pygame: detect Joystick disconnect, and wait for it to be reconnected
I'm using a pygame.joystick.Joystick object and want to be able to print a message asking the user to reconnect a usb joystick once it's been unplugged.

right now I have (roughly):

```<code>js = pygame.joystick.Joystick(0)
#... some game code and stuff
pygame.joystick.quit()
pygame.joystick.init()
while pygame.joystick.get_count() == 0:
    print 'please reconnect joystick'
    pygame.joystick.quit()
    pygame.joystick.init()

js = pygame.joystick.Joystick(0)
js.init()
</code>```

but it doesn't reconnect properly, idk what exactly it's doing, but it's definitely wrong.  Any direction on this would be helpful

答:
I managed to get mine working with Noelkd's suggestion, but I had a similar issue described by Ryan Haining

I had something like this at first, but it doesn't work because the it loses track of the gamepads actions with all the quiting and initing. This works initially to check if a controller is plugged in at all, but not to effectively check while running

I had this issue too. I think you are correct, calling quit too often doesn't give the pad enough time to re-initialise - at least on my computer. I found that if you limit the calls to every second, it works.

It can cause the player input to temporarily disconnect though, so any calls on a joystick won't work.

It's better to only run this code if you detect that there has been no input for a while (say 5 seconds or something). This way you won't quit while a user is actually using the device

```<code>import pygame
import time

INACTIVITY_RECONNECT_TIME = 5
RECONNECT_TIMEOUT = 1

class ControllerInput():
  def __init__(self):
    pygame.joystick.init()
    self.lastTime = 0
    self.lastActive = 0

  def getButtons(self, joystickId):
    joystick = pygame.joystick.Joystick(joystickId)
    joystick.init()

    buttons = {}

    for i in range(joystick.get_numbuttons()):
      buttons[i] = joystick.get_button(i)
      if buttons[i]:
        self.lastActive = time.time()

    return buttons

  def hasController(self):
    now = time.time()
    if now - self.lastActive > INACTIVITY_RECONNECT_TIME and now - self.lastTime > RECONNECT_TIMEOUT:
      self.lastTime = now
      pygame.joystick.quit()
      pygame.joystick.init()

    return pygame.joystick.get_count() > 0
</code>```

Usage

```<code># ... some constructor
controller = ControllerInput()

# ... game loop
if not controller.hasController():
  # handle disconnect
  print('reconnect')
  return

buttons = controller.getButtons(0)

if buttons[0]:
  # buttons[0] was pressed!
</code>```

Body:
I'm using a pygame.joystick.Joystick object and want to be able to print a message asking the user to reconnect a usb joystick once it's been unplugged.

right now I have (roughly):

js = pygame.joystick.Joystick(0)
#... some game code and stuff
pygame.joystick.quit()
pygame.joystick.init()
while pygame.joystick.get_count() == 0:
    print 'please reconnect joystick'
    pygame.joystick.quit()
    pygame.joystick.init()

js = pygame.joystick.Joystick(0)
js.init()

but it doesn't reconnect properly, idk what exactly it's doing, but it's definitely wrong.  Any direction on this would be helpful

Body:
I managed to get mine working with Noelkd's suggestion, but I had a similar issue described by Ryan Haining

I had something like this at first, but it doesn't work because the it loses track of the gamepads actions with all the quiting and initing. This works initially to check if a controller is plugged in at all, but not to effectively check while running

I had this issue too. I think you are correct, calling quit too often doesn't give the pad enough time to re-initialise - at least on my computer. I found that if you limit the calls to every second, it works.

It can cause the player input to temporarily disconnect though, so any calls on a joystick won't work.

It's better to only run this code if you detect that there has been no input for a while (say 5 seconds or something). This way you won't quit while a user is actually using the device

import pygame
import time

INACTIVITY_RECONNECT_TIME = 5
RECONNECT_TIMEOUT = 1

class ControllerInput():
  def __init__(self):
    pygame.joystick.init()
    self.lastTime = 0
    self.lastActive = 0

  def getButtons(self, joystickId):
    joystick = pygame.joystick.Joystick(joystickId)
    joystick.init()

    buttons = {}

    for i in range(joystick.get_numbuttons()):
      buttons[i] = joystick.get_button(i)
      if buttons[i]:
        self.lastActive = time.time()

    return buttons

  def hasController(self):
    now = time.time()
    if now - self.lastActive > INACTIVITY_RECONNECT_TIME and now - self.lastTime > RECONNECT_TIMEOUT:
      self.lastTime = now
      pygame.joystick.quit()
      pygame.joystick.init()

    return pygame.joystick.get_count() > 0

Usage

# ... some constructor
controller = ControllerInput()

# ... game loop
if not controller.hasController():
  # handle disconnect
  print('reconnect')
  return

buttons = controller.getButtons(0)

if buttons[0]:
  # buttons[0] was pressed!


来源: stackexchange

问:
Switch & Case function with Radio Buttons
I have read various questions and answers but I seem to be having a problem with my code and I am unsure why.

Here is what I am attempting to achieve. I have 3 different radio button groups. Each time I click a different radio button I want a single picture to display that corresponds to the value of the 3 radio groups.

I have a picture for all 8 combinations. To make it easy for me to make sure it was working correctly, the image I have is actually the name of the 3 items that are checked off by the radio buttons. Opening the page you will see Wood, Thumb turns, and Face Mounted are checked so the picture below shows the picture that has those words. If I click on aluminum the picture should change to aluminum, thumb turns, and face mounted.

Below is what I have. Any help would be greatly appreciated.

```<code><html>
<head>
<script type='text/javascript'>
$("input:radio[name=guides], input:radio[name=locking], input:radio[name=mounting]").click(function() {
    var guidesValue = $("input:radio[name=guides]:checked").val();
    var lockingValue = $("input:radio[name=locking]:checked").val();
    var mountingValue = $("input:radio[name=mounting]:checked").val();

    var image_name = "";

    switch (guidesValue) {
        case 'WOOD':
            image_name += "Newfolder/WOOD";
            break;
        case 'ALUMINUM':
            image_name += "Newfolder/ALUMINUM";
            break;
        default:
            image_name += "Newfolder/WOOD";
            break;
    }

    switch (lockingValue) {
        case 'THUMB':
            image_name += "_THUMB";
            break;
        case 'KEY':
            image_name += "_KEY";
            break;
        default:
            image_name += "_THUMB";
            break;
    }

    switch (mountingValue) {
        case 'FWM':
            image_name += "_FWM.jpg";
            break;
        case 'BJM':
            image_name += "_BJM.jpg";
            break;
        default:
            image_name += "_FWM.jpg";
            break;
    }

    $('#formula').attr('src', image_name);
});
</script>
</head>

<body>

<table border="1" width="30%" cellspacing="5" cellpadding="3">
  <tr>
    <td width="100%">
    <input type="radio" name="guides" value="WOOD" id="wood" checked> Wood Guides
    <p><input type="radio" name="guides" value="ALUMINUM" id="aluminum"> Aluminum Guides</p>
    </td>
  <tr>
    <td width="100%">
    <input type="radio" name="locking" value="THUMB" id="THUMBTURN" checked> Thumb Turn Lock
    <p><input type="radio" name="locking" value="KEY" id="KEYCYLINDER"> Key Cylinder Lock</p>
    </td>
  <tr>
    <td width="100%">
    <input type="radio" name="mounting" value="FWM" id="FWMounted" checked> Face Wall Mounted
    <p><input type="radio" name="mounting" value="BJM" id="BJMounted"> Between Jamb Mounted</p>
    </td>
  </tr>

</table>

<p>

<img src="Newfolder/WOOD_THUMB_FWM.jpg" name="formula" id="formula" width="384" height="96">

</body>

</html>
</code>```

答:
You need to make sure that the DOM tree for the page is ready before trying to retrieve any element.

To do so, enclose your code inside a callback function which should be called once the page is loaded (window.load event) or the DOM tree is ready ($(document).ready())

Of course, you also need to add the jQuery code.

I have modified your code to log into console the name of the image for checking the changes more easily.

        <input type="radio" name="guides" value="WOOD" id="wood" checked> Wood Guides

<input type="radio" name="guides" value="ALUMINUM" id="aluminum"> Aluminum Guides

          <input type="radio" name="locking" value="THUMB" id="THUMBTURN" checked> Thumb Turn Lock

<input type="radio" name="locking" value="KEY" id="KEYCYLINDER"> Key Cylinder Lock

            <input type="radio" name="mounting" value="FWM" id="FWMounted" checked> Face Wall Mounted

<input type="radio" name="mounting" value="BJM" id="BJMounted"> Between Jamb Mounted

```

ContentLicense: CC BY-SA 3.0

Body:
I have read various questions and answers but I seem to be having a problem with my code and I am unsure why.

Here is what I am attempting to achieve. I have 3 different radio button groups. Each time I click a different radio button I want a single picture to display that corresponds to the value of the 3 radio groups.

I have a picture for all 8 combinations. To make it easy for me to make sure it was working correctly, the image I have is actually the name of the 3 items that are checked off by the radio buttons. Opening the page you will see Wood, Thumb turns, and Face Mounted are checked so the picture below shows the picture that has those words. If I click on aluminum the picture should change to aluminum, thumb turns, and face mounted.

Below is what I have. Any help would be greatly appreciated.

    <input type="radio" name="guides" value="WOOD" id="wood" checked> Wood Guides

<input type="radio" name="guides" value="ALUMINUM" id="aluminum"> Aluminum Guides

    <input type="radio" name="locking" value="THUMB" id="THUMBTURN" checked> Thumb Turn Lock

<input type="radio" name="locking" value="KEY" id="KEYCYLINDER"> Key Cylinder Lock

    <input type="radio" name="mounting" value="FWM" id="FWMounted" checked> Face Wall Mounted

<input type="radio" name="mounting" value="BJM" id="BJMounted"> Between Jamb Mounted

Body:
You need to make sure that the DOM tree for the page is ready before trying to retrieve any element.

To do so, enclose your code inside a callback function which should be called once the page is loaded (window.load event) or the DOM tree is ready ($(document).ready())

Of course, you also need to add the jQuery code.

I have modified your code to log into console the name of the image for checking the changes more easily.

<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type='text/javascript'>
    $(document).ready(function() {
      $("input:radio[name=guides], input:radio[name=locking], input:radio[name=mounting]").click(function() {
        var guidesValue = $("input:radio[name=guides]:checked").val();
        var lockingValue = $("input:radio[name=locking]:checked").val();
        var mountingValue = $("input:radio[name=mounting]:checked").val();

        var image_name = "";

        switch (guidesValue) {
          case 'WOOD':
            image_name += "Newfolder/WOOD";
            break;
          case 'ALUMINUM':
            image_name += "Newfolder/ALUMINUM";
            break;
          default:
            image_name += "Newfolder/WOOD";
            break;
        }

        switch (lockingValue) {
          case 'THUMB':
            image_name += "_THUMB";
            break;
          case 'KEY':
            image_name += "_KEY";
            break;
          default:
            image_name += "_THUMB";
            break;
        }

        switch (mountingValue) {
          case 'FWM':
            image_name += "_FWM.jpg";
            break;
          case 'BJM':
            image_name += "_BJM.jpg";
            break;
          default:
            image_name += "_FWM.jpg";
            break;
        }

        $('#formula').attr('src', image_name);
        console.log(image_name);
      });
    });
  </script>
</head>

<body>

  <table border="1" width="30%" cellspacing="5" cellpadding="3">
    <tr>
      <td width="100%">
        <input type="radio" name="guides" value="WOOD" id="wood" checked> Wood Guides
        <p><input type="radio" name="guides" value="ALUMINUM" id="aluminum"> Aluminum Guides</p>
      </td>
      <tr>
        <td width="100%">
          <input type="radio" name="locking" value="THUMB" id="THUMBTURN" checked> Thumb Turn Lock
          <p><input type="radio" name="locking" value="KEY" id="KEYCYLINDER"> Key Cylinder Lock</p>
        </td>
        <tr>
          <td width="100%">
            <input type="radio" name="mounting" value="FWM" id="FWMounted" checked> Face Wall Mounted
            <p><input type="radio" name="mounting" value="BJM" id="BJMounted"> Between Jamb Mounted</p>
          </td>
        </tr>

  </table>

  <p>

    <img src="Newfolder/WOOD_THUMB_FWM.jpg" name="formula" id="formula" width="384" height="96">

</body>

</html>


问:
How can we differentiate between State Changes of the Switch set programmatically to the ones set by user?
I have a Switch. It works like this
1. Turn it ON shows you AlertDialog with Download/locate/cancel options to perform (download)/(locate locally)/(cancel the dialog)

2.Turn it OFF shows you AlertDialog with Yes/No options to delete the files

Now Assume initially, the Switch state is OFF. Now if I turn it ON, Listener will register OnChecked as true. Next, if I press cancel the Dialog, OnChecked will be set to false, since no files were located/downloaded. Now this change is detected by the listener even though it is set programmatically. I need a way to divide Switch state Changes caused by user and program.

My listener is OnCheckedChangeListener.

I know there are similar questions having solutions online which are either makeshift or incomplete.

EDIT: I edited and changed the complete structure of the question to address my root objective. It shouldn't be a problem since there are no answers by the time of this edit.

答:
There are several answers online for this issue.
They include writing Custom Switches extending SwitchCompat, CompundButton etc; with a SilentlySetChecked method.

If instead of OnCheckedChangeListener, if we implement the OnClickListener, there will not be any recursion of alert dialog's issue. But we cannot detect Swipe changes in this listener.

Simply, we need to detect State Changes done by clicking/swiping without recursion issue:

    CompoundButton.OnCheckedChangeListener downloadButtonListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.downloadSwitch.isPressed() & isChecked) {
//if switch is turned on by click/swipe
}
else if(holder.downloadSwitch.isPressed() & !isChecked{
//if switch is turned on by click/swipe
}
}
});```

This is a simple enough solution that solves the issue. But, It never came up on search, except partially here. Let me know if there is a better solution that I am missing.

NOTE: I posted this as a solution since it also answers the edited question. I will wait for few days for better answers before accepting my own as the solution.

Body:
There are several answers online for this issue.
They include writing Custom Switches extending SwitchCompat, CompundButton etc; with a SilentlySetChecked method.

If instead of OnCheckedChangeListener, if we implement the OnClickListener, there will not be any recursion of alert dialog's issue. But we cannot detect Swipe changes in this listener.

Simply, we need to detect State Changes done by clicking/swiping without recursion issue:

    CompoundButton.OnCheckedChangeListener downloadButtonListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.downloadSwitch.isPressed() & isChecked) {
//if switch is turned on by click/swipe
}
else if(holder.downloadSwitch.isPressed() & !isChecked{
//if switch is turned on by click/swipe
}
}
});

This is a simple enough solution that solves the issue. But, It never came up on search, except partially here. Let me know if there is a better solution that I am missing.

NOTE: I posted this as a solution since it also answers the edited question. I will wait for few days for better answers before accepting my own as the solution.


问:
How do we know if a typeclass is a sub-typeclass of another typeclass?
If we do
let add a b = a+b
then add :: Num a => a -> a -> a.

We also know that 1.5 :: Fractional a => a.
And add 1 1.5 works flawlessly.

If I understand correctly every type which has an instance of Fractional has also an instance of Num, but how is this fact made explicit?

答:
It's in the definition of the Fractional class:

```<code>class Num a => Fractional a where
   ...
</code>```

You can see it typing :i Fractional in GHCi, or on the Haddock docs.

Body:
It's in the definition of the Fractional class:

class Num a => Fractional a where
   ...

You can see it typing :i Fractional in GHCi, or on the Haddock docs.


问:
fscanf always returns 0(CLOSED)
I am a beginner in C programming, and I am trying to write a simple code to read a text file and write its content into an array, then print it on console. However, I always get 0.0000, and I could not solve the problem.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

int numOfLines(FILE *fp1);
void printarr(float arr[], int size);
float *filetoArr(FILE *fp, int arrsize);

int main(int argc, const char *argv[]) {
    char *fileName1 = argv[1];
    FILE *fp1 = fopen(fileName1, "r");
    printf("File name: %s", fileName1);
    int size = numOfLines(fp1);
    printf("Number of lines in the file: %d\n", size);
    float *arr = filetoArr(fp1, size);
    printarr(arr, size);
    free(arr);
    fclose(fp1);
}

void printarr(float *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%f ", *(arr + i));
    }
}

float *filetoArr(FILE *fp, int arrsize) {
    int size = arrsize;
    float *arr = (float *)malloc(sizeof(float) * size);
    for (int i = 0; i < size; i++) {
        fscanf(fp, "%f\n", (arr+i));
    }
    return (arr);
}

int numOfLines(FILE *fp1) {
    int numberOfLines = 0;
    char c;
    do {
        c = getc(fp1);
        if (c == '\n') {
            numberOfLines++;
        }
    } while (c != EOF);
    return numberOfLines;
}
</code>```

答:
There are multiple problems in your code:

you read the whole file in numOfLines(): you must reset the file pointer to the beginning of file with rewind(fp1); so fscanf() can read the file instead of hitting the end of file immediately.

the variable c used to read bytes from the file must be defined as an int for the test for end of file to be reliable. Otherwise, depending on whether char is signed or not by default, the EOF would never match or could potentially match the character \377 as end of file erroneously.

you do not check for failure to open the file.

Although returning 0 is implicit for function main() since C99, it is advisable to write the return 0; statement explicitly for better clarity.

Title: fscanf always returns 0(CLOSED)

Body:
I am a beginner in C programming, and I am trying to write a simple code to read a text file and write its content into an array, then print it on console. However, I always get 0.0000, and I could not solve the problem.

#include <stdio.h>
#include <stdlib.h>

int numOfLines(FILE *fp1);
void printarr(float arr[], int size);
float *filetoArr(FILE *fp, int arrsize);

int main(int argc, const char *argv[]) {
    char *fileName1 = argv[1];
    FILE *fp1 = fopen(fileName1, "r");
    printf("File name: %s", fileName1);
    int size = numOfLines(fp1);
    printf("Number of lines in the file: %d\n", size);
    float *arr = filetoArr(fp1, size);
    printarr(arr, size);
    free(arr);
    fclose(fp1);
}

void printarr(float *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%f ", *(arr + i));
    }
}

float *filetoArr(FILE *fp, int arrsize) {
    int size = arrsize;
    float *arr = (float *)malloc(sizeof(float) * size);
    for (int i = 0; i < size; i++) {
        fscanf(fp, "%f\n", (arr+i));
    }
    return (arr);
}

int numOfLines(FILE *fp1) {
    int numberOfLines = 0;
    char c;
    do {
        c = getc(fp1);
        if (c == '\n') {
            numberOfLines++;
        }
    } while (c != EOF);
    return numberOfLines;
}


问:
Access file sharing
I have a nicely designed access database, complete with layed out forms and macros behind many buttons that filter through search boxes and do many other functions.

My problem is that I am sending this database to multiple people who want to add new records, however when they give me back their edited database (now with new records", i cant import them, because another person who has also handed me their edited version of the database needs their records added and access doesnt allow me to import these records because unique ID's have been created by both people and clash when i try to import them both in.

I have tried some websites that claim to import my database and allow cloud editing, however i lose all the functionality and layout of my forms / macros as the websites dont support it.

What would be the best solution so that i can get multiple people adding new records at the same time? Are there any websites that offer this? Or is there a way inside access to reassign the Unique ID's if they are already in the system?

答:
Split the database into frontend and backend parts. Backend sits on server and frontend links to backend. Each user runs their own copy of frontend. However, if your users do not have access to same network, you are in a pickle. Have you looked into Sharepoint and Azure?

I have designed a db for users that did not have connection to our network. These were construction site field offices. The main office had the master database. Field offices were given an Access file where they entered records during life of the project and at the end they sent in the file and code in the master imported records. Since all data was new there was no concern for conflicting updates. Simplest way I found to accomplish was to not use Autonumber primary key.

I do have another db that required merging data from multiple Access files and those files did use Autonumber primary key. The import code was more complicated.

Title: Access file sharing


问:
Laravel: why does this cause error - call to undefined method?
Why calling a method with parenthesis in a template causes error, but without doesn't? How would I pass a parameter then?

Error:

```<code>Call to undefined method Illuminate\Database\Query\Builder::test()
</code>```

index.blade.php

```<code>...
<p class="product-price-old"><s>{{ $product->test("123") }}</s></p>
...
</code>```

Product.php

```<code>...
public function getTestAttribute($value)
{
    return $value;
}
...
</code>```

but if I do something like this it works fine:

index.blade.php

```<code>...
<p class="product-price-old"><s>{{ $product->test }}</s></p>
...
</code>```

Product.php

```<code>...
public function getTestAttribute()
{
    return "123";
}
...
</code>```

答:
If you are assigning an instance of Product.php (which should be a model of a product table in your database) to a blade variable, and your Product table has a column called 'test' , Then you're just printing that value from your model and the instance of Product.php does not have a test() method in it. You can just retrieve the value of test attribute.

If you want to pass parameters to a function in your model, Use a different name for your function. You can not pass parameters to accessors in Laravel.

Body:
Why calling a method with parenthesis in a template causes error, but without doesn't? How would I pass a parameter then?

Error:

Call to undefined method Illuminate\Database\Query\Builder::test()

index.blade.php

...

<s>{{ $product->test("123") }}</s>

...

Product.php

...
public function getTestAttribute($value)
{
    return $value;
}
...

but if I do something like this it works fine:

index.blade.php

...

<s>{{ $product->test }}</s>

...

Product.php

...
public function getTestAttribute()
{
    return "123";
}
...


问:
Options for upload files bigger than 2Gb using web browser
Good day!

I'm looking for options on uploading really big files (over 2Gb) using web browsers. I know that Java applet solutions will work, I know (and have tested by myself) that Flash has internal limitation about 2Gb. What about Silverlight? Have I missed some way\technology of doing this?

Thanks in advance!

答:
To my knowledge upload in .NET 4 is limited to "2097151" (2 GB). It could be set in web.config

```<code><system.web>
  <httpRuntime maxRequestLength="2097151" />
</system.web>
</code>```

OK, so there's another idea: you can upload files in chunks.
There's a project on codeplex that might be of use to you.

ContentLicense: CC BY-SA 2.5

Body:
To my knowledge upload in .NET 4 is limited to "2097151" (2 GB). It could be set in web.config

<system.web>
  <httpRuntime maxRequestLength="2097151" />
</system.web>

OK, so there's another idea: you can upload files in chunks.
There's a project on codeplex that might be of use to you.


问:
Trying the following code to run an application but am getting the following error."Manifest merger failed with multiple errors, see logs"
Trying the following code to run an application but am getting the following error."Manifest merger failed with multiple errors, see logs". I made some changes in the app gradle file earlier as the application involves use of "CardView and Recycler view"(Changes was advised on few questions in stackoverflow) Attaching all the app files below. Can someone please help me on this ?
Gradle Console:

```<code>Executing tasks: [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature.
NDK is missing a "platforms" directory.
If you are using NDK, verify the ndk.dir is set to a valid NDK directory.  It is currently set to C:\Users\Sumeet\AppData\Local\Android\Sdk\ndk-bundle.
If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning.

Observed package id 'add-ons;addon-google_apis-google-23' in inconsistent location 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23-1' (Expected 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23')
Already observed package id 'add-ons;addon-google_apis-google-23' in 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23'. Skipping duplicate at 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23-1'
Observed package id 'add-ons;addon-google_apis-google-23' in inconsistent location 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23-1' (Expected 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23')
Already observed package id 'add-ons;addon-google_apis-google-23' in 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23'. Skipping duplicate at 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23-1'
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2531Library
:app:prepareComAndroidSupportAppcompatV72531Library
:app:prepareComAndroidSupportCardviewV72103Library
:app:prepareComAndroidSupportConstraintConstraintLayout100Beta5Library
:app:prepareComAndroidSupportDesign2220Library
:app:prepareComAndroidSupportRecyclerviewV72600Alpha1Library
:app:prepareComAndroidSupportSupportCompat2600Alpha1Library
:app:prepareComAndroidSupportSupportCoreUi2600Alpha1Library
:app:prepareComAndroidSupportSupportCoreUtils2531Library
:app:prepareComAndroidSupportSupportFragment2531Library
:app:prepareComAndroidSupportSupportMediaCompat2531Library
:app:prepareComAndroidSupportSupportV42531Library
:app:prepareComAndroidSupportSupportVectorDrawable2531Library
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest
C:\Users\Sumeet\Desktop\Workspace\CardViewReclyerView_try1\app\src\main\AndroidManifest.xml:27:9-31 Error:
    Attribute meta-data#android.support.VERSION@value value=(25.3.1) from [com.android.support:appcompat-v7:25.3.1] AndroidManifest.xml:27:9-31
    is also present at [com.android.support:recyclerview-v7:26.0.0-alpha1] AndroidManifest.xml:24:9-38 value=(26.0.0-alpha1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:25:5-27:34 to override.
C:\Users\Sumeet\Desktop\Workspace\CardViewReclyerView_try1\app\src\main\AndroidManifest.xml Error:
    uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library [com.android.support:recyclerview-v7:26.0.0-alpha1] C:\Users\Sumeet\.android\build-cache\b9c913425a87cdfd18c66664e6c35b4ec1a4f53e\output\AndroidManifest.xml
    Suggestion: use tools:overrideLibrary="android.support.v7.recyclerview" to force usage

See http://g.co/androidstudio/manifest-merger for more information about the manifest merger.

:app:processDebugManifest FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs

* Try:
Run with --stack trace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 2 mins 18.389 secs
</code>```

MainActivity.java

```<code>    package com.example.sumeet.cardviewreclyerview_try1;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return super.onCreateOptionsMenu(menu);
    }
}
</code>```

VersionAdapter.java

```<code>package com.example.sumeet.cardviewreclyerview_try1;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Sumeet on 03-04-2017.
 */

public class VersionAdapter extends RecyclerView.Adapter<VersionAdapter.VersionViewHolder> {

    private String[] version = {"Alpha", "Beta", "CupCake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean", "KitKat", "Lollipop", "Marshmallow", "Nougat", "O"};

    @Override
    public VersionAdapter.VersionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_row, parent, false);
        VersionViewHolder viewHolder = new VersionViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(VersionAdapter.VersionViewHolder holder, int position) {
        holder.text.setText(version[position]);
    }

    @Override
    public int getItemCount() {
        return version.length;
    }

    public static class VersionViewHolder extends RecyclerView.ViewHolder {
        private TextView text;

        public VersionViewHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.textview_card);
        }
    }
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sumeet.cardviewreclyerview_try1.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        android:layout_above="@+id/floatingActionButton"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"></android.support.v7.widget.RecyclerView>

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:clickable="true"
        android:src="@android:drawable/ic_dialog_email"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="312dp"
        tools:layout_editor_absoluteY="439dp"
        android:id="@+id/floatingActionButton" />

</RelativeLayout>
</code>```

each_row.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/textview_card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />
</android.support.v7.widget.CardView>
</code>```

menu_home.xml(The Menu File)

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/add_item"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Item"
        app:showAsAction="always" />
    <item
        android:id="@+id/delete_item"
        android:icon="@android:drawable/ic_menu_delete"
        android:title="Item"
        app:showAsAction="always" />
    <item
        android:id="@+id/search_item"
        android:title="Search" />
    <item
        android:id="@+id/settings_item"
        android:title="Settings" />
</menu>
</code>```

build.gradle(app)

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.sumeet.cardviewreclyerview_try1"
        minSdkVersion 9
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
        compile 'com.android.support:cardview-v7:21.+'
        compile 'com.android.support:recyclerview-v7:21.+'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta5'
    compile 'com.android.support:recyclerview-v7:+'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
You are attempting to use multiple versions of the Android Support Library:

compile 'com.android.support:appcompat-v7:25.3.1'

compile 'com.android.support:design:22.2.0'

compile 'com.android.support:recyclerview-v7:+'

Use the same version for all com.android.support artifacts. And that version should not be +. Given these three lines, I would go with 25.3.1.

Body:
Trying the following code to run an application but am getting the following error."Manifest merger failed with multiple errors, see logs". I made some changes in the app gradle file earlier as the application involves use of "CardView and Recycler view"(Changes was advised on few questions in stackoverflow) Attaching all the app files below. Can someone please help me on this ?
Gradle Console:

Executing tasks: [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature.
NDK is missing a "platforms" directory.
If you are using NDK, verify the ndk.dir is set to a valid NDK directory.  It is currently set to C:\Users\Sumeet\AppData\Local\Android\Sdk\ndk-bundle.
If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning.

Observed package id 'add-ons;addon-google_apis-google-23' in inconsistent location 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23-1' (Expected 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23')
Already observed package id 'add-ons;addon-google_apis-google-23' in 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23'. Skipping duplicate at 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23-1'
Observed package id 'add-ons;addon-google_apis-google-23' in inconsistent location 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23-1' (Expected 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23')
Already observed package id 'add-ons;addon-google_apis-google-23' in 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23'. Skipping duplicate at 'C:\Users\Sumeet\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-23-1'
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2531Library
:app:prepareComAndroidSupportAppcompatV72531Library
:app:prepareComAndroidSupportCardviewV72103Library
:app:prepareComAndroidSupportConstraintConstraintLayout100Beta5Library
:app:prepareComAndroidSupportDesign2220Library
:app:prepareComAndroidSupportRecyclerviewV72600Alpha1Library
:app:prepareComAndroidSupportSupportCompat2600Alpha1Library
:app:prepareComAndroidSupportSupportCoreUi2600Alpha1Library
:app:prepareComAndroidSupportSupportCoreUtils2531Library
:app:prepareComAndroidSupportSupportFragment2531Library
:app:prepareComAndroidSupportSupportMediaCompat2531Library
:app:prepareComAndroidSupportSupportV42531Library
:app:prepareComAndroidSupportSupportVectorDrawable2531Library
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest
C:\Users\Sumeet\Desktop\Workspace\CardViewReclyerView_try1\app\src\main\AndroidManifest.xml:27:9-31 Error:
    Attribute meta-data#android.support.VERSION@value value=(25.3.1) from [com.android.support:appcompat-v7:25.3.1] AndroidManifest.xml:27:9-31
    is also present at [com.android.support:recyclerview-v7:26.0.0-alpha1] AndroidManifest.xml:24:9-38 value=(26.0.0-alpha1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:25:5-27:34 to override.
C:\Users\Sumeet\Desktop\Workspace\CardViewReclyerView_try1\app\src\main\AndroidManifest.xml Error:
    uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library [com.android.support:recyclerview-v7:26.0.0-alpha1] C:\Users\Sumeet\.android\build-cache\b9c913425a87cdfd18c66664e6c35b4ec1a4f53e\output\AndroidManifest.xml
    Suggestion: use tools:overrideLibrary="android.support.v7.recyclerview" to force usage

See http://g.co/androidstudio/manifest-merger for more information about the manifest merger.

:app:processDebugManifest FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs

* Try:
Run with --stack trace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 2 mins 18.389 secs

MainActivity.java

    package com.example.sumeet.cardviewreclyerview_try1;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return super.onCreateOptionsMenu(menu);
    }
}

VersionAdapter.java

package com.example.sumeet.cardviewreclyerview_try1;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Sumeet on 03-04-2017.
 */

public class VersionAdapter extends RecyclerView.Adapter<VersionAdapter.VersionViewHolder> {

    private String[] version = {"Alpha", "Beta", "CupCake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean", "KitKat", "Lollipop", "Marshmallow", "Nougat", "O"};

    @Override
    public VersionAdapter.VersionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_row, parent, false);
        VersionViewHolder viewHolder = new VersionViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(VersionAdapter.VersionViewHolder holder, int position) {
        holder.text.setText(version[position]);
    }

    @Override
    public int getItemCount() {
        return version.length;
    }

    public static class VersionViewHolder extends RecyclerView.ViewHolder {
        private TextView text;

        public VersionViewHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.textview_card);
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sumeet.cardviewreclyerview_try1.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        android:layout_above="@+id/floatingActionButton"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"></android.support.v7.widget.RecyclerView>

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:clickable="true"
        android:src="@android:drawable/ic_dialog_email"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="312dp"
        tools:layout_editor_absoluteY="439dp"
        android:id="@+id/floatingActionButton" />

</RelativeLayout>

each_row.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/textview_card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />
</android.support.v7.widget.CardView>

menu_home.xml(The Menu File)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/add_item"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Item"
        app:showAsAction="always" />
    <item
        android:id="@+id/delete_item"
        android:icon="@android:drawable/ic_menu_delete"
        android:title="Item"
        app:showAsAction="always" />
    <item
        android:id="@+id/search_item"
        android:title="Search" />
    <item
        android:id="@+id/settings_item"
        android:title="Settings" />
</menu>

build.gradle(app)

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.sumeet.cardviewreclyerview_try1"
        minSdkVersion 9
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
        compile 'com.android.support:cardview-v7:21.+'
        compile 'com.android.support:recyclerview-v7:21.+'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta5'
    compile 'com.android.support:recyclerview-v7:+'
    testCompile 'junit:junit:4.12'
}


问:
Allowing Elastic beanstalk app access to elasticsearch domain
I'm trying to allow beanstalk applications to access our elasticsearch service, but every method I find in your documentation fails to grant access to these apps. So far the only methods that worked for me in enabling access was to open the cluster to the entire world, and enabling specific IPs (which is clearly not an option, given the dynamic nature of Elastic beanstalk).
What I have tried -
Creating a policy from the "Allow or deny access to one or more accounts..." to the root of our AWS account.
Creating a policy from the "Allow or deny access to one or more accounts..." to the IAM role assigned to beanstalk EC2 servers
Attaching a policy to the beanstalk IAM role, allowing him ES:* privileges on the elasticsearch domain.

Why are all of these methods failing? The documentation seems to indicate each of those methods should work, so what am I missing here?

答:
You can use elasticsearch-net-aws, it automatically signs the requests sent to Amazon Elastic Search. Works with Elasticsearch.Net and NEST

https://github.com/bcuff/elasticsearch-net-aws


问:
Passing function with 2 arguments to addEvent Listener method
I am trying to pass a function Which has 2 arguments to the addEventListener method on specific button but the problem is function executing directly when page loading instead of executing it when some one clicked the button.

I know how to make it work with anonymous function but I need it to work with a specific defined function instead.

```<code>function changeContent(elem,str){
    elem.textContent = str;
}

var btn = document.querySelector("button");

var p = document.querySelector("p");

var content = "Someone Clicked the Button!";

// add event listener on click to the button

// version 1 with anonymous function worked as expected

btn.addEventListener("click",function(){
    p.textContent = content;
});

// version 2 with specific defined function not working as expected

 btn.addEventListener("click",changeContent(p,content));
</code>```

any idea of the reason why second version isn't working and how to make it work as expected.

Update:

my intended and important question:

is there any way to make changeContent(p,content) function work
  without wrap it with a (anonymous) function in addEventListener
  method ?

答:
Wrap it also in an anonymous function

```<code>btn.addEventListener("click",function() {
    changeContent(p, content)
});
</code>```

any idea of the reason why second version isn't working

Because changeContent is intermediate called because you're passing arguments to it (with the round brackets). In general you could pass a function to a function in two ways:

Only the name, e.g. passFunction(changeContent);

Wrap in a (anonymous) function, as shown above passFunction(function() { changeContent( ...);} );. The anonymous function isn't called intermediately, because you aren't passing parameters to it.

can you explain this point changeContent is intermediate called

If you pass arguments to a function, it's called. If you wrap it in an (anonymous) function, without passing arguments to the (anonymous) function, the (anonymous) function isn't called and hence also not the wrapped function.

is there any way to make it work without wrap it with a (anonymous) function

Use the .bind function. The first argument is the value of this. So you need 3 parameters for this case:

```<code>btn.addEventListener("click",changeContent.bind(this, p, content));
</code>```

For more info, see the docs of .bind

Body:
I am trying to pass a function Which has 2 arguments to the addEventListener method on specific button but the problem is function executing directly when page loading instead of executing it when some one clicked the button.

I know how to make it work with anonymous function but I need it to work with a specific defined function instead.

function changeContent(elem,str){
    elem.textContent = str;
}

var btn = document.querySelector("button");

var p = document.querySelector("p");

var content = "Someone Clicked the Button!";

// add event listener on click to the button

// version 1 with anonymous function worked as expected

btn.addEventListener("click",function(){
    p.textContent = content;
});

// version 2 with specific defined function not working as expected

 btn.addEventListener("click",changeContent(p,content));

any idea of the reason why second version isn't working and how to make it work as expected.

Update:

my intended and important question:

is there any way to make changeContent(p,content) function work
  without wrap it with a (anonymous) function in addEventListener
  method ?

Body:
Wrap it also in an anonymous function

btn.addEventListener("click",function() {
    changeContent(p, content)
});

any idea of the reason why second version isn't working

Because changeContent is intermediate called because you're passing arguments to it (with the round brackets). In general you could pass a function to a function in two ways:

Only the name, e.g. passFunction(changeContent);

Wrap in a (anonymous) function, as shown above passFunction(function() { changeContent( ...);} );. The anonymous function isn't called intermediately, because you aren't passing parameters to it.

can you explain this point changeContent is intermediate called

If you pass arguments to a function, it's called. If you wrap it in an (anonymous) function, without passing arguments to the (anonymous) function, the (anonymous) function isn't called and hence also not the wrapped function.

is there any way to make it work without wrap it with a (anonymous) function

Use the .bind function. The first argument is the value of this. So you need 3 parameters for this case:

btn.addEventListener("click",changeContent.bind(this, p, content));

For more info, see the docs of .bind


问:
Recursive Formula method implemented on another method
I have two recursive methods. One of them has a special formula that I must use on the second method. My task is to write a recursive method named reportOnValues that will use each value in
 a list to compute a recursive formula implemented in the method
 specialRecursiveFunction. I am currently having trouble on implementing the formula to my reportValues method. How could I achieve this.

1st method

```<code>public static void reportOnValues(MyListOfInts m){
    if (m == null) return;
    else
        return specialRecursiveFunction(m.firstInt) +   reportOnValues(m.restOfTheInts);
}
</code>```

2nd Method

```<code>public static double specialRecursiveFunction(int x){
    if (x == 1) return 0;
    else if (x%2==1)
        return 1 + specialRecursiveFunction(x-1);
    else
        return 1 + specialRecursiveFunction(x/2);

}
</code>```

Constructed Linked list

```<code>public class MyListOfInts {

public int firstInt; // contain data
public MyListOfInts restOfTheInts; // points to next node

public MyListOfInts(int f){ // constructor 1
    firstInt=f;
}

public MyListOfInts(int f, MyListOfInts r){ // constructor 2 implements nodes and data
    firstInt=f;
    restOfTheInts=r;
}
</code>```

}

答:
I did some changes on your code. I think that this is what you looking for

```<code>    /*
     * I changed the return type to double.
     * And if (x == 1) return; To if (x == 1) return 0;
     */
    public static double specialRecursiveFunction(int x){
        if (x == 1) return 0;
        else if (x%2==1)
            return 1 + specialRecursiveFunction(x-1);
        else
            return 1 + specialRecursiveFunction(x/2);
    }

    public static double reportOnValues(MyListOfInts m){
        if (m == null) return 0;
        else
            return specialRecursiveFunction(m.firstInt) + reportOnValues(m.restOfTheInts);
    }
</code>```

MyListOfInts Class

```<code>    /*
     * I Added restOfTheInts = null; in MyListOfInts Method
     */
    public class MyListOfInts {

        public int firstInt; // contain data
        public MyListOfInts restOfTheInts; // points to next node

        public MyListOfInts(int f){ // constructor 1
            firstInt=f;
            restOfTheInts = null;
        }

        public MyListOfInts(int f, MyListOfInts r){ // constructor 2 implements nodes and data
            firstInt=f;
            restOfTheInts=r;
        }
    }
</code>```

And This is How I Tested it

```<code>public static void main(String[] args) {
        MyListOfInts list1 = new MyListOfInts(5, new MyListOfInts(13, new MyListOfInts(18, new MyListOfInts(4, new MyListOfInts(36, new MyListOfInts(5))))));
        System.out.println(reportOnValues(list1));

    }
</code>```

I hope That this is What you looking for, if Not I can help through tell you reach your goal.

Body:
I have two recursive methods. One of them has a special formula that I must use on the second method. My task is to write a recursive method named reportOnValues that will use each value in
 a list to compute a recursive formula implemented in the method
 specialRecursiveFunction. I am currently having trouble on implementing the formula to my reportValues method. How could I achieve this.

1st method

public static void reportOnValues(MyListOfInts m){
    if (m == null) return;
    else
        return specialRecursiveFunction(m.firstInt) +   reportOnValues(m.restOfTheInts);
}

2nd Method

public static double specialRecursiveFunction(int x){
    if (x == 1) return 0;
    else if (x%2==1)
        return 1 + specialRecursiveFunction(x-1);
    else
        return 1 + specialRecursiveFunction(x/2);

}

Constructed Linked list

public class MyListOfInts {

public int firstInt; // contain data
public MyListOfInts restOfTheInts; // points to next node

public MyListOfInts(int f){ // constructor 1
    firstInt=f;
}

public MyListOfInts(int f, MyListOfInts r){ // constructor 2 implements nodes and data
    firstInt=f;
    restOfTheInts=r;
}

}

Body:
I did some changes on your code. I think that this is what you looking for

    /*
     * I changed the return type to double.
     * And if (x == 1) return; To if (x == 1) return 0;
     */
    public static double specialRecursiveFunction(int x){
        if (x == 1) return 0;
        else if (x%2==1)
            return 1 + specialRecursiveFunction(x-1);
        else
            return 1 + specialRecursiveFunction(x/2);
    }

    public static double reportOnValues(MyListOfInts m){
        if (m == null) return 0;
        else
            return specialRecursiveFunction(m.firstInt) + reportOnValues(m.restOfTheInts);
    }

MyListOfInts Class

    /*
     * I Added restOfTheInts = null; in MyListOfInts Method
     */
    public class MyListOfInts {

        public int firstInt; // contain data
        public MyListOfInts restOfTheInts; // points to next node

        public MyListOfInts(int f){ // constructor 1
            firstInt=f;
            restOfTheInts = null;
        }

        public MyListOfInts(int f, MyListOfInts r){ // constructor 2 implements nodes and data
            firstInt=f;
            restOfTheInts=r;
        }
    }

And This is How I Tested it

public static void main(String[] args) {
        MyListOfInts list1 = new MyListOfInts(5, new MyListOfInts(13, new MyListOfInts(18, new MyListOfInts(4, new MyListOfInts(36, new MyListOfInts(5))))));
        System.out.println(reportOnValues(list1));

    }

I hope That this is What you looking for, if Not I can help through tell you reach your goal.


问:
Can I subclass and redefine a method in Golang?
I'm using a Github Client that allows me to call github API methods more easily.

This library allows me to provide my own *http.Client when I initialize it:

```<code>httpClient := &http.Client{}
githubClient := github.NewClient(httpClient)
</code>```

It works fine but now I need something else. I want to customize the Client so that every request (i.e. the Do method) gets a custom header added.

I've read a bit about embedding and this is what I've tried so far:

```<code>package trackerapi

import(
    "net/http"
)

type MyClient struct{
    *http.Client
}

func (my *MyClient)Do(req *http.Request) (*http.Response, error){

    req.Header.Set("cache-control","max-stale=3600")

    return my.Client.Do(req)

}
</code>```

But the compiler does not let me use my custom MyClient in place of the default one:

```<code>httpClient := &trackerapi.MyClient{}

// ERROR: Cannot use httpClient (type *MyClient) as type
//*http.Client.
githubClient := github.NewClient(httpClient)
</code>```

I'm a bit of a golang newbie so my question is: Is this the right way to do what I want to and, if not, what's the recommended approach?

答:
Can I subclass ... in Golang?

Short answer: No. Go is not object oriented, therefore it has no classes, therefore subclassing is categorically an impossibility.

Longer answer:

You're on the right track with embedding, but you won't be able to substitute your custom client for anything that expects an *http.Client. This is what Go interfaces are for.  But the standard library doesn't use an interface here (it does for some things, where it makes sense).

Another possible approach which may, depending on exact needs, work, is to use a custom transport, rather than a custom client. This does use an interface. You may be able to use a custom RoundTripper that adds the necessary headers, and this you can assign to an *http.Client struct.

Body:
I'm using a Github Client that allows me to call github API methods more easily.

This library allows me to provide my own *http.Client when I initialize it:

httpClient := &http.Client{}
githubClient := github.NewClient(httpClient)

It works fine but now I need something else. I want to customize the Client so that every request (i.e. the Do method) gets a custom header added.

I've read a bit about embedding and this is what I've tried so far:

package trackerapi

import(
    "net/http"
)

type MyClient struct{
    *http.Client
}

func (my *MyClient)Do(req *http.Request) (*http.Response, error){

    req.Header.Set("cache-control","max-stale=3600")

    return my.Client.Do(req)

}

But the compiler does not let me use my custom MyClient in place of the default one:

httpClient := &trackerapi.MyClient{}

// ERROR: Cannot use httpClient (type *MyClient) as type
//*http.Client.
githubClient := github.NewClient(httpClient)

I'm a bit of a golang newbie so my question is: Is this the right way to do what I want to and, if not, what's the recommended approach?


问:
SVN: Merging two branches together
We have multiple developers working on a project. We're employing a feature-branch method of branching in which we do the following:

All maintenance work and bug fixes are done on the trunk

All new functionality is done on a new branch

Branch is updated regularly (via merging changes from trunk to branch)

However, we've run into a situation that 2 branches [we'll call them feature-branch-1 and feature-branch-2] need to be merged together. What is the best way to accomplish this? Part of me thinks we should create a new branch. Then, merge that branch with the first feature branch [feature-branch-1]. And then merge with the second feature branch [feature-branch-2] and take care of the conflicts (which will most likely be the project files).

Is there a better way?

Thanks guys!

答: Is merging the current state of one of the feature branches to trunk an option? If so, I recommend merging that feature branch to trunk and then updating the other feature branch to the latest in trunk. That way you avoid creating an additional branch and get rid of one of the branches.</p>

Title: SVN: Merging two branches together


问:
finding next month, previous month giving wrong result
I want to find 2 months after current month and previous month. I have coded as below,

```<code>$current = strtotime(date('m',time()) . '-01 00:00:01');
$next_month = date('m', strtotime('+1 month', $current));
$next_next_month = date('m', strtotime('+2 month', $current));
$previous_month = date('m', strtotime('-0 month', $current));

echo $previous_month.$next_month.$next_next_month;

output : 01 02 03
</code>```

I want to get the result from current month. And the expected output is 04 05 06.

How to achieve this result. Is there any solution. Thankyou.

Body:
I want to find 2 months after current month and previous month. I have coded as below,

$current = strtotime(date('m',time()) . '-01 00:00:01');
$next_month = date('m', strtotime('+1 month', $current));
$next_next_month = date('m', strtotime('+2 month', $current));
$previous_month = date('m', strtotime('-0 month', $current));

echo $previous_month.$next_month.$next_next_month;

output : 01 02 03

I want to get the result from current month. And the expected output is 04 05 06.

How to achieve this result. Is there any solution. Thankyou.

Body:
$m = date('m');
printf("%02d %02d %02d", ($m+10) % 12 + 1, $m, $m % 12 + 1);

Output (on 2nd April):

03 04 05


问:
Pass C++ Eigen matrix to Matlab mex output
How can I pass an Eigen Matrix as a Matlab output parameter?

I tried this from [EIGEN] How to get in and out data from Eigen matrix:

```<code>MatrixXd resultEigen;   // Eigen matrix with some result (non NULL!)
double *resultC;                // NULL pointer
Map<MatrixXd>( resultC, resultEigen.rows(), resultEigen.cols() ) = resultEigen;
</code>```

But it lack information, how to pass the info in resultC to plhs[0] ?
Also, when I run the code using this Map, Matlab closes.

答:
You need to first allocate the output MATLAB array, then create an Eigen::Map around it:

```<code>MatrixXd resultEigen; // Eigen matrix with some result (non NULL!)
mwSize rows = resultEigen.rows();
mwSize cols = resultEigen.cols();
plhs[0] = mxCreateDoubleMatrix(rows, cols, mxREAL); // Create MATLAB array of same size
Eigen::Map<Eigen::MatrixXd> map(mxGetPr(plhs[0]), rows, cols); // Map the array
map = resultEigen; // Copy
</code>```

What this does is make an Eigen matrix (map) that has the MATLAB array (plhs[0]) as data. When you write into it, you are actually writing into the MATLAB array.

Note that you can create this map before doing your Eigen calculations, and use it instead of resultEigen, to avoid that final copy.

Note also that you can do exactly the same thing with the input arrays. Just make sure they are of class double (using mxIsDouble), or things might go horribly wrong... :)

Body:
How can I pass an Eigen Matrix as a Matlab output parameter?

I tried this from [EIGEN] How to get in and out data from Eigen matrix:

MatrixXd resultEigen;   // Eigen matrix with some result (non NULL!)
double *resultC;                // NULL pointer
Map<MatrixXd>( resultC, resultEigen.rows(), resultEigen.cols() ) = resultEigen;

But it lack information, how to pass the info in resultC to plhs[0] ?
Also, when I run the code using this Map, Matlab closes.

Body:
You need to first allocate the output MATLAB array, then create an Eigen::Map around it:

MatrixXd resultEigen; // Eigen matrix with some result (non NULL!)
mwSize rows = resultEigen.rows();
mwSize cols = resultEigen.cols();
plhs[0] = mxCreateDoubleMatrix(rows, cols, mxREAL); // Create MATLAB array of same size
Eigen::Map<Eigen::MatrixXd> map(mxGetPr(plhs[0]), rows, cols); // Map the array
map = resultEigen; // Copy

What this does is make an Eigen matrix (map) that has the MATLAB array (plhs[0]) as data. When you write into it, you are actually writing into the MATLAB array.

Note that you can create this map before doing your Eigen calculations, and use it instead of resultEigen, to avoid that final copy.

Note also that you can do exactly the same thing with the input arrays. Just make sure they are of class double (using mxIsDouble), or things might go horribly wrong... :)

ContentLicense: CC BY-SA 4.0


问:
How to perform non-linear optimization with scipy/numpy or sympy?
I am trying to find the optimal solution to the follow system of equations in Python:

```<code>(x-x1)^2 + (y-y1)^2 - r1^2 = 0
(x-x2)^2 + (y-y2)^2 - r2^2 = 0
(x-x3)^2 + (y-y3)^2 - r3^2 = 0
</code>```

Given the values a point(x,y) and a radius (r):

```<code>x1, y1, r1 = (0, 0, 0.88)
x2, y2, r2 = (2, 0, 1)
x3, y3, r3 = (0, 2, 0.75)
</code>```

What is the best way to find the optimal solution for the point (x,y)
Using the above example it would be:

 ~ (1, 1)

答:
I noticed that the code in the accepted solution doesn't work any longer... I think maybe scipy.optimize has changed its interface since the answer was posted.  I could be wrong. Regardless, I second the suggestion to use the algorithms in scipy.optimize, and the accepted answer does demonstrate how (or did at one time, if the interface has changed).

I'm adding an additional answer here, purely to suggest an alternative package that uses the scipy.optimize algorithms at the core, but is much more robust for constrained optimization. The package is mystic.  One of the big improvements is that mystic gives constrained global optimization.

First, here's your example, done very similarly to the scipy.optimize.minimize way, but using a global optimizer.

```<code>from mystic import reduced

@reduced(lambda x,y: abs(x)+abs(y)) #choice changes answer
def objective(x, a, b, c):
  x,y = x
  eqns = (\
    (x - a[0])**2 + (y - b[0])**2 - c[0]**2,
    (x - a[1])**2 + (y - b[1])**2 - c[1]**2,
    (x - a[2])**2 + (y - b[2])**2 - c[2]**2)
  return eqns

bounds = [(None,None),(None,None)] #unnecessary

a = (0,2,0)
b = (0,0,2)
c = (.88,1,.75)
args = a,b,c

from mystic.solvers import diffev2
from mystic.monitors import VerboseMonitor
mon = VerboseMonitor(10)

result = diffev2(objective, args=args, x0=bounds, bounds=bounds, npop=40, \
                 ftol=1e-8, disp=False, full_output=True, itermon=mon)

print result[0]
print result[1]
</code>```

With results looking like this:

```<code>Generation 0 has Chi-Squared: 38868.949133
Generation 10 has Chi-Squared: 2777.470642
Generation 20 has Chi-Squared: 12.808055
Generation 30 has Chi-Squared: 3.764840
Generation 40 has Chi-Squared: 2.996441
Generation 50 has Chi-Squared: 2.996441
Generation 60 has Chi-Squared: 2.996440
Generation 70 has Chi-Squared: 2.996433
Generation 80 has Chi-Squared: 2.996433
Generation 90 has Chi-Squared: 2.996433
STOP("VTRChangeOverGeneration with {'gtol': 1e-06, 'target': 0.0, 'generations': 30, 'ftol': 1e-08}")
[ 0.66667151  0.66666422]
2.99643333334
</code>```

As noted, the choice of the lambda in reduced affects which point the optimizer finds as there is no actual solution to the equations.

mystic also provides the ability to convert symbolic equations to a function, where the resulting function can be used as an objective, or as a penalty function.  Here is the same problem, but using the equations as a penalty instead of the objective.

```<code>def objective(x):
    return 0.0

equations = """
(x0 - 0)**2 + (x1 - 0)**2 - .88**2 == 0
(x0 - 2)**2 + (x1 - 0)**2 - 1**2 == 0
(x0 - 0)**2 + (x1 - 2)**2 - .75**2 == 0
"""

bounds = [(None,None),(None,None)] #unnecessary

from mystic.symbolic import generate_penalty, generate_conditions
from mystic.solvers import diffev2

pf = generate_penalty(generate_conditions(equations), k=1e12)

result = diffev2(objective, x0=bounds, bounds=bounds, penalty=pf, \
                 npop=40, gtol=50, disp=False, full_output=True)

print result[0]
print result[1]
</code>```

With results:

```<code>[ 0.77958328  0.8580965 ]
3.6473132399e+12
</code>```

The results are different than before because the penalty applied is different than we applied earlier in reduced.  In mystic, you can select what penalty you want to apply.

The point was made that the equation has no solution.  You can see from the result above, that the result is heavily penalized, so that's a good indication that there is no solution.  However, mystic has another way you can see there in no solution.  Instead of applying a more traditional penalty, which penalizes the solution where the constraints are violated... mystic provides a constraint, which is essentially a kernel transformation, that removes all potential solutions that don't meet the constants.

```<code>def objective(x):
    return 0.0

equations = """
(x0 - 0)**2 + (x1 - 0)**2 - .88**2 == 0
(x0 - 2)**2 + (x1 - 0)**2 - 1**2 == 0
(x0 - 0)**2 + (x1 - 2)**2 - .75**2 == 0
"""

bounds = [(None,None),(None,None)] #unnecessary

from mystic.symbolic import generate_constraint, generate_solvers, simplify
from mystic.symbolic import generate_penalty, generate_conditions
from mystic.solvers import diffev2

cf = generate_constraint(generate_solvers(simplify(equations)))

result = diffev2(objective, x0=bounds, bounds=bounds, \
                 constraints=cf, \
                 npop=40, gtol=50, disp=False, full_output=True)

print result[0]
print result[1]
</code>```

With results:

```<code>[          nan  657.17740835]
0.0
</code>```

Where the nan essentially indicates there is no valid solution.

FYI, I'm the author, so I have some bias.  However, mystic has been around almost as long as scipy.optimize, is mature, and has had a more stable interface over that length of time.  The point being, if you need a much more flexible and powerful constrained nonlinear optimizer, I suggest mystic.

Body:
I am trying to find the optimal solution to the follow system of equations in Python:

(x-x1)^2 + (y-y1)^2 - r1^2 = 0
(x-x2)^2 + (y-y2)^2 - r2^2 = 0
(x-x3)^2 + (y-y3)^2 - r3^2 = 0

Given the values a point(x,y) and a radius (r):

x1, y1, r1 = (0, 0, 0.88)
x2, y2, r2 = (2, 0, 1)
x3, y3, r3 = (0, 2, 0.75)

What is the best way to find the optimal solution for the point (x,y)
Using the above example it would be:

 ~ (1, 1)

Body:
I noticed that the code in the accepted solution doesn't work any longer... I think maybe scipy.optimize has changed its interface since the answer was posted.  I could be wrong. Regardless, I second the suggestion to use the algorithms in scipy.optimize, and the accepted answer does demonstrate how (or did at one time, if the interface has changed).

I'm adding an additional answer here, purely to suggest an alternative package that uses the scipy.optimize algorithms at the core, but is much more robust for constrained optimization. The package is mystic.  One of the big improvements is that mystic gives constrained global optimization.

First, here's your example, done very similarly to the scipy.optimize.minimize way, but using a global optimizer.

from mystic import reduced

@reduced(lambda x,y: abs(x)+abs(y)) #choice changes answer
def objective(x, a, b, c):
  x,y = x
  eqns = (\
    (x - a[0])**2 + (y - b[0])**2 - c[0]**2,
    (x - a[1])**2 + (y - b[1])**2 - c[1]**2,
    (x - a[2])**2 + (y - b[2])**2 - c[2]**2)
  return eqns

bounds = [(None,None),(None,None)] #unnecessary

a = (0,2,0)
b = (0,0,2)
c = (.88,1,.75)
args = a,b,c

from mystic.solvers import diffev2
from mystic.monitors import VerboseMonitor
mon = VerboseMonitor(10)

result = diffev2(objective, args=args, x0=bounds, bounds=bounds, npop=40, \
                 ftol=1e-8, disp=False, full_output=True, itermon=mon)

print result[0]
print result[1]

With results looking like this:

Generation 0 has Chi-Squared: 38868.949133
Generation 10 has Chi-Squared: 2777.470642
Generation 20 has Chi-Squared: 12.808055
Generation 30 has Chi-Squared: 3.764840
Generation 40 has Chi-Squared: 2.996441
Generation 50 has Chi-Squared: 2.996441
Generation 60 has Chi-Squared: 2.996440
Generation 70 has Chi-Squared: 2.996433
Generation 80 has Chi-Squared: 2.996433
Generation 90 has Chi-Squared: 2.996433
STOP("VTRChangeOverGeneration with {'gtol': 1e-06, 'target': 0.0, 'generations': 30, 'ftol': 1e-08}")
[ 0.66667151  0.66666422]
2.99643333334

As noted, the choice of the lambda in reduced affects which point the optimizer finds as there is no actual solution to the equations.

mystic also provides the ability to convert symbolic equations to a function, where the resulting function can be used as an objective, or as a penalty function.  Here is the same problem, but using the equations as a penalty instead of the objective.

def objective(x):
    return 0.0

equations = """
(x0 - 0)**2 + (x1 - 0)**2 - .88**2 == 0
(x0 - 2)**2 + (x1 - 0)**2 - 1**2 == 0
(x0 - 0)**2 + (x1 - 2)**2 - .75**2 == 0
"""

bounds = [(None,None),(None,None)] #unnecessary

from mystic.symbolic import generate_penalty, generate_conditions
from mystic.solvers import diffev2

pf = generate_penalty(generate_conditions(equations), k=1e12)

result = diffev2(objective, x0=bounds, bounds=bounds, penalty=pf, \
                 npop=40, gtol=50, disp=False, full_output=True)

print result[0]
print result[1]

With results:

[ 0.77958328  0.8580965 ]
3.6473132399e+12

The results are different than before because the penalty applied is different than we applied earlier in reduced.  In mystic, you can select what penalty you want to apply.

The point was made that the equation has no solution.  You can see from the result above, that the result is heavily penalized, so that's a good indication that there is no solution.  However, mystic has another way you can see there in no solution.  Instead of applying a more traditional penalty, which penalizes the solution where the constraints are violated... mystic provides a constraint, which is essentially a kernel transformation, that removes all potential solutions that don't meet the constants.

def objective(x):
    return 0.0

equations = """
(x0 - 0)**2 + (x1 - 0)**2 - .88**2 == 0
(x0 - 2)**2 + (x1 - 0)**2 - 1**2 == 0
(x0 - 0)**2 + (x1 - 2)**2 - .75**2 == 0
"""

bounds = [(None,None),(None,None)] #unnecessary

from mystic.symbolic import generate_constraint, generate_solvers, simplify
from mystic.symbolic import generate_penalty, generate_conditions
from mystic.solvers import diffev2

cf = generate_constraint(generate_solvers(simplify(equations)))

result = diffev2(objective, x0=bounds, bounds=bounds, \
                 constraints=cf, \
                 npop=40, gtol=50, disp=False, full_output=True)

print result[0]
print result[1]

With results:

[          nan  657.17740835]
0.0

Where the nan essentially indicates there is no valid solution.

FYI, I'm the author, so I have some bias.  However, mystic has been around almost as long as scipy.optimize, is mature, and has had a more stable interface over that length of time.  The point being, if you need a much more flexible and powerful constrained nonlinear optimizer, I suggest mystic.


问:
listen to clipboard changes, check ownership?
I want to be notified if a string is copied to the system clipboard. When a new string is copied from the same source application, the FlavorListener won't get an event. To get informed when another string is copied, i read the string from the clipboard, convert it to a SrtingSelection, which is able to take the ownership, and put it back to the clipboard. Now I got informed twice, once the StringSelection lost ownership and once it takes it back. Is there a way to check for the ownership directly, instead of storing the string and check it equals the new one?
Here is my code so far:

```<code> import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws Exception {
        // The clipboard
        final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
        // read clipboard and take ownership to get the FlavorListener notified
        // when the content has changed but the owner has not
        processClipboard(cb);
        cb.addFlavorListener(new FlavorListener() {
            @Override
            public void flavorsChanged(FlavorEvent e) {
                processClipboard(cb);
            }
        });
        // keep thread for testing
        Thread.sleep(100000L);
    }

    public static void processClipboard(Clipboard cb) {
        // gets the content of clipboard
        Transferable trans = cb.getContents(null);
        if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            try {
                // cast to string
                String s = (String) trans
                        .getTransferData(DataFlavor.stringFlavor);
                System.out.println(s);
                // only StringSelection can take ownership, i think
                StringSelection ss = new StringSelection(s);
                // set content, take ownership
                cb.setContents(ss, ss);
            } catch (UnsupportedFlavorException e2) {
                e2.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }
}
</code>```

I hope you understand my bad english :-(

答:
I think this would work :)

```<code>import java.awt.AWTEvent;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;

public final class ClipboardMonitor extends Observable implements ClipboardOwner {
  private static ClipboardMonitor monitor = null;

  public ClipboardMonitor() {
        gainOwnership();
  }

  private void gainOwnership() {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        try {
              Transferable content = clip.getContents(null);
              DataFlavor[] f = content.getTransferDataFlavors();
              boolean imageDetected = false;
              for (int i = 0; i < f.length; i++) {
                    //                        System.out.println("Name: " + f[i].getHumanPresentableName());
                    //                        System.out.println("MimeType: " + f[i].getMimeType());
                    //                        System.out.println("PrimaryType: " + f[i].getPrimaryType());
                    //                        System.out.println("SubType: " + f[i].getSubType());
                    if (f[i].equals(DataFlavor.imageFlavor)) {
                          imageDetected = true;
                          break;
                    }
              }
              if (imageDetected) {
                    System.out.println("Image content detected");
                    Transferable t = new Transferable() {
                          public DataFlavor[] getTransferDataFlavors() {
                                return new DataFlavor[] { DataFlavor.stringFlavor };
                          }
                          public boolean isDataFlavorSupported(DataFlavor flavor) {
                                return false;
                          }
                          public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                                return "dummy text instead of snapshot image";
                          }
                    };
                    clip.setContents(t, this);
              } else {
                    clip.setContents(content, this);
              }
              setChanged();
              notifyObservers(content);
        } catch (IllegalArgumentException istateexception) {
              istateexception.printStackTrace();
        } catch (Exception ioexception) {
              ioexception.printStackTrace();
        }
  }

  private int getCurrentEventModifiers() {
        int modifiers = 0;
        AWTEvent currentEvent = EventQueue.getCurrentEvent();
        if (currentEvent instanceof InputEvent) {
              modifiers = ((InputEvent) currentEvent).getModifiers();
        } else
              if (currentEvent instanceof ActionEvent) {
                    modifiers = ((ActionEvent) currentEvent).getModifiers();
              }
        return modifiers;
  }

  public void lostOwnership(Clipboard clipboard, Transferable contents) {
        System.out.println("Ownership lost ...");
        new Thread(new Runnable() {
              public void run() {
                    try {
                          Thread.sleep(200);
                          gainOwnership();
                    } catch (Exception e) {
                          e.printStackTrace();
                    }
              }
        }).start();
  }

  public void flushClipboard() {
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(""), null);
  }

  public static final ClipboardMonitor getMonitor() {
        if (monitor == null)
              monitor = new ClipboardMonitor();
        return (monitor);
  }

  public static void main(String[] args) {
        JFrame f = new JFrame();
        ClipboardMonitor monitor = ClipboardMonitor.getMonitor();
        monitor.addObserver(new Observer() {
              public void update(Observable o, Object arg) {
                    System.out.println("Clipboard has been regained!");
              }
        });

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500, 100);
        f.setVisible(true);
  }
</code>```

}

Body:
I want to be notified if a string is copied to the system clipboard. When a new string is copied from the same source application, the FlavorListener won't get an event. To get informed when another string is copied, i read the string from the clipboard, convert it to a SrtingSelection, which is able to take the ownership, and put it back to the clipboard. Now I got informed twice, once the StringSelection lost ownership and once it takes it back. Is there a way to check for the ownership directly, instead of storing the string and check it equals the new one?
Here is my code so far:

 import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws Exception {
        // The clipboard
        final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
        // read clipboard and take ownership to get the FlavorListener notified
        // when the content has changed but the owner has not
        processClipboard(cb);
        cb.addFlavorListener(new FlavorListener() {
            @Override
            public void flavorsChanged(FlavorEvent e) {
                processClipboard(cb);
            }
        });
        // keep thread for testing
        Thread.sleep(100000L);
    }

    public static void processClipboard(Clipboard cb) {
        // gets the content of clipboard
        Transferable trans = cb.getContents(null);
        if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            try {
                // cast to string
                String s = (String) trans
                        .getTransferData(DataFlavor.stringFlavor);
                System.out.println(s);
                // only StringSelection can take ownership, i think
                StringSelection ss = new StringSelection(s);
                // set content, take ownership
                cb.setContents(ss, ss);
            } catch (UnsupportedFlavorException e2) {
                e2.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }
}

I hope you understand my bad english :-(

Body:
I think this would work :)

import java.awt.AWTEvent;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;

public final class ClipboardMonitor extends Observable implements ClipboardOwner {
  private static ClipboardMonitor monitor = null;

  public ClipboardMonitor() {
        gainOwnership();
  }

  private void gainOwnership() {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        try {
              Transferable content = clip.getContents(null);
              DataFlavor[] f = content.getTransferDataFlavors();
              boolean imageDetected = false;
              for (int i = 0; i < f.length; i++) {
                    //                        System.out.println("Name: " + f[i].getHumanPresentableName());
                    //                        System.out.println("MimeType: " + f[i].getMimeType());
                    //                        System.out.println("PrimaryType: " + f[i].getPrimaryType());
                    //                        System.out.println("SubType: " + f[i].getSubType());
                    if (f[i].equals(DataFlavor.imageFlavor)) {
                          imageDetected = true;
                          break;
                    }
              }
              if (imageDetected) {
                    System.out.println("Image content detected");
                    Transferable t = new Transferable() {
                          public DataFlavor[] getTransferDataFlavors() {
                                return new DataFlavor[] { DataFlavor.stringFlavor };
                          }
                          public boolean isDataFlavorSupported(DataFlavor flavor) {
                                return false;
                          }
                          public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                                return "dummy text instead of snapshot image";
                          }
                    };
                    clip.setContents(t, this);
              } else {
                    clip.setContents(content, this);
              }
              setChanged();
              notifyObservers(content);
        } catch (IllegalArgumentException istateexception) {
              istateexception.printStackTrace();
        } catch (Exception ioexception) {
              ioexception.printStackTrace();
        }
  }

  private int getCurrentEventModifiers() {
        int modifiers = 0;
        AWTEvent currentEvent = EventQueue.getCurrentEvent();
        if (currentEvent instanceof InputEvent) {
              modifiers = ((InputEvent) currentEvent).getModifiers();
        } else
              if (currentEvent instanceof ActionEvent) {
                    modifiers = ((ActionEvent) currentEvent).getModifiers();
              }
        return modifiers;
  }

  public void lostOwnership(Clipboard clipboard, Transferable contents) {
        System.out.println("Ownership lost ...");
        new Thread(new Runnable() {
              public void run() {
                    try {
                          Thread.sleep(200);
                          gainOwnership();
                    } catch (Exception e) {
                          e.printStackTrace();
                    }
              }
        }).start();
  }

  public void flushClipboard() {
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(""), null);
  }

  public static final ClipboardMonitor getMonitor() {
        if (monitor == null)
              monitor = new ClipboardMonitor();
        return (monitor);
  }

  public static void main(String[] args) {
        JFrame f = new JFrame();
        ClipboardMonitor monitor = ClipboardMonitor.getMonitor();
        monitor.addObserver(new Observer() {
              public void update(Observable o, Object arg) {
                    System.out.println("Clipboard has been regained!");
              }
        });

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500, 100);
        f.setVisible(true);
  }

}


问:
Neo4j filter on relationship
I have two types of nodes (node1) and (node2) with about 100,000 records in each. I have one type of relationship [:TYPE1] between those two nodes on only 100 rows of (a)

If I profile:
    MATCH (a:node1)-[:TYPE1]->(b:node2) RETURN a.field1, b.field2

it says it does a NodeByLabelScan with 80,000+ db hits, then uses the relationship to filter down to the 100 rows I want with many more db hits. The query does return the rows I want, but how can I get the neo4j analyzer to look at [:TYPE1] as the lowest cardinality to start the execution path?

Using Neo4j V 3.1.2 on Windows 10

Thanks

答:
Neo4j's schema indexes don't apply to relationships, so you'll need to use the legacy indexes instead. APOC Procedures has support for these, and will be the easiest way to lookup relationships by type. Definitely install APOC when you get the chance to take advantage of this.

However, APOC's approach for these indexes is by type and a property, not type alone. This may require you to add a placeholder property on all relationships of that type so they can be added to the manual index and queried later.

Something like this:

```<code>MATCH (:node1)-[r:TYPE1]->(:node2)
SET r.indexed = true
CALL apoc.index.addRelationship(r,['indexed'])
RETURN DISTINCT 1
</code>```

Once that's done, you can use APOC to lookup relationships via the relationship index:

```<code>CALL apoc.index.relationships('TYPE1','indexed:true') YIELD rel
WITH startNode(rel) as a, endNode(rel) as b
RETURN a.field1, b.field2
</code>```

You can also use *:* in the above query for the property lookup to save a few keystrokes.

Note that these indexes are manual, not automatic, so you'll need to apply this to any new :TYPE1 relationships you want to add.

Support is being implemented for automatically updating manual indexes in APOC, a few issues are being ironed out still, and I don't think the instructions for this have been added to the documentation yet.

Title: Neo4j filter on relationship

Body:
Neo4j's schema indexes don't apply to relationships, so you'll need to use the legacy indexes instead. APOC Procedures has support for these, and will be the easiest way to lookup relationships by type. Definitely install APOC when you get the chance to take advantage of this.

However, APOC's approach for these indexes is by type and a property, not type alone. This may require you to add a placeholder property on all relationships of that type so they can be added to the manual index and queried later.

Something like this:

MATCH (:node1)-[r:TYPE1]->(:node2)
SET r.indexed = true
CALL apoc.index.addRelationship(r,['indexed'])
RETURN DISTINCT 1

Once that's done, you can use APOC to lookup relationships via the relationship index:

CALL apoc.index.relationships('TYPE1','indexed:true') YIELD rel
WITH startNode(rel) as a, endNode(rel) as b
RETURN a.field1, b.field2

You can also use *:* in the above query for the property lookup to save a few keystrokes.

Note that these indexes are manual, not automatic, so you'll need to apply this to any new :TYPE1 relationships you want to add.

Support is being implemented for automatically updating manual indexes in APOC, a few issues are being ironed out still, and I don't think the instructions for this have been added to the documentation yet.


问:
How to give each JButton in a 10 x 10 grid button layout a unique ID/name
I am trying to give each JButton from a 10 x 10 button layout (so 100 buttons) each unique name or ID or number so I can call them later. I made an ArrayList because that's what some other person did.

```<code>public ArrayList<JButton> myList;

//Some other code

        for(int row = 0; row < 10; row++)
        {
            for(int col = 0; col < 10; col++)
            {
                    button = new JButton();
                    button.addActionListener( al );
                    myList.add(button);
                    for(JButton button : myList)
                        button.setText("");
                    panel_1.add(button);
            }
        }
</code>```

The program compiles but it doesn't run. It's showing error at

```<code>myList.add(button);
</code>```

It's a null pointer exception apparently.

but I don't know why. Is it not adding the buttons to the ArrayList? Also how do I give each button a unique name or string?

答:
The program compiles but it doesn't run. It's showing error at

The ArrayList is null because you didn't create an ArrayList object.

The code should be:

```<code>private ArrayList<JButton> myList = new ArrayList<JButton>();
</code>```

Also how do I give each button a unique name or string?

There is no need to give the button a unique name. Its unique name is the "index" used to access the JButton in the ArrayList.

You probably don't even need the ArrayList.

Normally you add an ActionListener to the button. Then you can just use the getSource() method of the ActionEvent to get the reference to the button.

Body:
I am trying to give each JButton from a 10 x 10 button layout (so 100 buttons) each unique name or ID or number so I can call them later. I made an ArrayList because that's what some other person did.

public ArrayList<JButton> myList;

//Some other code

        for(int row = 0; row < 10; row++)
        {
            for(int col = 0; col < 10; col++)
            {
                    button = new JButton();
                    button.addActionListener( al );
                    myList.add(button);
                    for(JButton button : myList)
                        button.setText("");
                    panel_1.add(button);
            }
        }

The program compiles but it doesn't run. It's showing error at

myList.add(button);

It's a null pointer exception apparently.

but I don't know why. Is it not adding the buttons to the ArrayList? Also how do I give each button a unique name or string?

Body:
The program compiles but it doesn't run. It's showing error at

The ArrayList is null because you didn't create an ArrayList object.

The code should be:

private ArrayList<JButton> myList = new ArrayList<JButton>();

Also how do I give each button a unique name or string?

There is no need to give the button a unique name. Its unique name is the "index" used to access the JButton in the ArrayList.

You probably don't even need the ArrayList.

Normally you add an ActionListener to the button. Then you can just use the getSource() method of the ActionEvent to get the reference to the button.