问:
Checking if an item is in an array in C
I am checking whether an item is in a an array in C using a for loop to iterate through every item in the array and comparing it one by one with a user input.

```<code>int main()
{
    char birds[] =
    {
        [0] = "a",
        [1] = "b",
        [2] = "c",
        [3] = "d",
        [4] = "e",
        [5] = "f",
        [6] = "g",
        [7] = "h"
    };
    int birdfound;
    int i;
    printf("Enter bird:");
    scanf("%c", &birdfound);
    //printf("%c", birdfound);
    for(i=0; i<8; i++)
    {
        //printf("Y");
        if(birdfound == birds[i]){
            printf("Bird in array, found at position %d\n", i);
        }
    }
    system("pause");
    return 0;
}
</code>```

I know for a fact that the issue lies within branch logic, as for some reason it fails to compare the character input with any character from the array. Therefore, the output is nothing and the program simply ends.

答:
You have already got the answer, however, there's another way of achieving the same without getting into the scenario which caused the problem.

Code is self-explanatory, with comments.

Reference: man page for strchr()

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

int main(void)  // correct signature
{
    char *str = "abcdefgh";                   // define the string in which to search
    char check = -1;                          // to hold the user input
    if (scanf("%c", &check) != 1) {           // basic sanity check with scanf
        exit (-1);
    }

    char * res = strchr (str, check);          // check whether the input is preset or not

    if (!res) {                                // return null pointer, means not found
        printf("not Found!!");
    }
    else {                                     // not null, match found
        printf("Found %c\n", *res);
    }
    return 0;
}
</code>```

Title: Checking if an item is in an array in C

Body:
I am checking whether an item is in a an array in C using a for loop to iterate through every item in the array and comparing it one by one with a user input.

int main()
{
    char birds[] =
    {
        [0] = "a",
        [1] = "b",
        [2] = "c",
        [3] = "d",
        [4] = "e",
        [5] = "f",
        [6] = "g",
        [7] = "h"
    };
    int birdfound;
    int i;
    printf("Enter bird:");
    scanf("%c", &birdfound);
    //printf("%c", birdfound);
    for(i=0; i<8; i++)
    {
        //printf("Y");
        if(birdfound == birds[i]){
            printf("Bird in array, found at position %d\n", i);
        }
    }
    system("pause");
    return 0;
}

I know for a fact that the issue lies within branch logic, as for some reason it fails to compare the character input with any character from the array. Therefore, the output is nothing and the program simply ends.

Body:
You have already got the answer, however, there's another way of achieving the same without getting into the scenario which caused the problem.

Code is self-explanatory, with comments.

Reference: man page for strchr()

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

int main(void)  // correct signature
{
    char *str = "abcdefgh";                   // define the string in which to search
    char check = -1;                          // to hold the user input
    if (scanf("%c", &check) != 1) {           // basic sanity check with scanf
        exit (-1);
    }

    char * res = strchr (str, check);          // check whether the input is preset or not

    if (!res) {                                // return null pointer, means not found
        printf("not Found!!");
    }
    else {                                     // not null, match found
        printf("Found %c\n", *res);
    }
    return 0;
}


来源: stackexchange

问:
Edit request data before validation

Request data:

```<code>    [
        "invoice_data" => [
            ...
            "discount" => null,
        ],
        "product_credit" => [
            ...
            "discount" => null,
        ]
    ];
</code>```

What I am trying to do

I am trying to create an if statement to check if the

$request -> invoice_data['discount'] == null then set it to 0 ALSO

$request -> product_credit['discount'] == null then set it to 0

Before the validation process because the validation will fail.

What I have tried:

I have found a method in Laravel called prepareForValidation() and it use $this -> merge([...]) which is what I am looking for but problem is that I cannot access the discount in invoice_data and product_credit.

答:
Cleaner way to set a default value of attributes than editing in request payload:

```<code>Model {
   protected $attributes = [
      'inovice_data' => 0,
      'discount' => 0,
      'product_credit' => 0
   ];
}
</code>```

In this way, if no values are provided, or undefined value or null, Eloquent will set these attributes to defined default values while populating in db.

ContentLicense: CC BY-SA 4.0

Title: Edit request data before validation

Body:
Request data:

    [
        "invoice_data" => [
            ...
            "discount" => null,
        ],
        "product_credit" => [
            ...
            "discount" => null,
        ]
    ];

What I am trying to do

I am trying to create an if statement to check if the

$request -> invoice_data['discount'] == null then set it to 0 ALSO

$request -> product_credit['discount'] == null then set it to 0

Before the validation process because the validation will fail.

What I have tried:

I have found a method in Laravel called prepareForValidation() and it use $this -> merge([...]) which is what I am looking for but problem is that I cannot access the discount in invoice_data and product_credit.

Body:
Cleaner way to set a default value of attributes than editing in request payload:

Model {
   protected $attributes = [
      'inovice_data' => 0,
      'discount' => 0,
      'product_credit' => 0
   ];
}

In this way, if no values are provided, or undefined value or null, Eloquent will set these attributes to defined default values while populating in db.


问:
multiple flutter emulator instances
On terminal instance 1 I navigate to /myprojects/my_app and execute flutter run

following is output :

```<code>Launching lib/main.dart on iPhone Xʀ in debug mode...
Running Xcode build...

 ├─Assembling Flutter resources...                           1.7s
 └─Compiling, linking and signing...                        15.1s
Xcode build done.                                           19.2s
This is taking longer than expected...
</code>```

On a new terminal window I navigate to /myprojects/my_app and execute flutter run

following is output :

```<code>Launching lib/main.dart on iPhone Xʀ in debug mode...
Running Xcode build...

 ├─Assembling Flutter resources...                           1.7s
 └─Compiling, linking and signing...                         8.0s
Xcode build done.                                           12.4s
This is taking longer than expected...
</code>```

But the existing emulator is overwritten with the existing emulator. How to run multiple flutter emulator instances ?

答:
type flutter emulators to get a list of all available emulators for you..

Then run flutter emulators --launch <id>

Start as many as you want with the above command

And finally, to run the app on all emulators you should do flutter run -d all

Title: multiple flutter emulator instances

Body:
On terminal instance 1 I navigate to /myprojects/my_app and execute flutter run

following is output :

Launching lib/main.dart on iPhone Xʀ in debug mode...
Running Xcode build...

 ├─Assembling Flutter resources...                           1.7s
 └─Compiling, linking and signing...                        15.1s
Xcode build done.                                           19.2s
This is taking longer than expected...

On a new terminal window I navigate to /myprojects/my_app and execute flutter run

following is output :

Launching lib/main.dart on iPhone Xʀ in debug mode...
Running Xcode build...

 ├─Assembling Flutter resources...                           1.7s
 └─Compiling, linking and signing...                         8.0s
Xcode build done.                                           12.4s
This is taking longer than expected...

But the existing emulator is overwritten with the existing emulator. How to run multiple flutter emulator instances ?


问:
A repository, according to the Repository pattern, should provide queries or actual entities?
I am currently refactoring my code for a web application developed using ASP.NET MVC3 with C# and Razor. One of the pattern I am using in order to better structure my application is the Repository pattern, which, besides being a really useful pattern, is also a frequent matter of discussion  within the developers' community.

In this context I found an article by Fredrik Normen which states that, according to the definition of Repository,a repository class must provide actual entities (for instance List in .NET) and not queriable objects (IQueriable in .NET). Instead in the NerdDinner tutorial from ASP.NET MVC official website they use IQueriable when the Repository has to provide multiple instances of the same object and the actual entity when the repository has to provide a single instance of the object.

What is the most correct approach to use when modeling a repository class/interface according to the Repository pattern?

Thanks

Francesco

答:
Opinions will differ on that, as you've already found. For small scale applications it's probably OK to let your repositories expose IQueryable.

One thing that you certainly should not do is pass IQueryable to your views. Make sure your views receive only materialized objects and collections (like List or arrays).
This way if an error exists in a query somewhere, it will occur in the controller (or repository) and not in your view. This enables you to test the queries and handle errors gracefully.

ContentLicense: CC BY-SA 3.0


问:
Problems playing two raw files at the same time through two MediaPlayers
I'm developing a Voip-Application and i have an edge case where i want to play two raw files at the same time.

When i have an incoming call from my application i am creating a new Mediaplayer and play a custom ringtone. When i get shortly after also  an incoming GSM-call i create a new mediaplayer and play a knocking sound to give the user feedback that there is also a GSM-Call incoming. At the same time i want the custom ringtone to continue playing.

```<code>private fun setAudioAttributesForFile(audioUsage: Int): AudioAttributes {
    return AudioAttributes.Builder()
            .setUsage(audioUsage)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
}

private fun startRingtone(fileToPlay: Int): MediaPlayer {
    return MediaPlayer().apply {
        reset()
        if (fileToPlay == R.raw.ring {
            setAudioAttributes(setAudioAttributesForFile(AudioAttributes.USAGE_NOTIFICATION_RINGTONE))
        } else {
            setAudioAttributes(setAudioAttributesForFile(AudioAttributes.USAGE_MEDIA))
        }
        isLooping = true
        Main.get().resources.openRawResourceFd(fileToPlay).use {
            setDataSource(
                    it.fileDescriptor,
                    it.startOffset,
                    it.length
            )
        }
        setOnPreparedListener { start() }
        prepareAsync()
    }
}
</code>```

The problem that i have with this code is that as soon as the knocking sound is playing the ringtone gets muted by the system and as soon as the knocking sound is stopping the ringtone continues.

What i also tried:

Using only
AudioAttributes.USAGE_NOTIFICATION_RINGTONE. As soon as the knocking sound starts to play both mediaPlayers are getting muted.

If i leave the setAudioAttributes() call away and replace these four lines to

```<code>if (fileToPlay == R.raw.ring) {
    setAudioAttributesForFile(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
} else {
    setAudioAttributesForFile(AudioAttributes.USAGE_MEDIA)
}
</code>```

then i can play those two files at the same time. The problem then is that the ringtone file is not shown as a ringtone instead it is only shown as a media file. So when i increase and decrease the volume of the ringtone the flag does not show that it is a ringtone.

Is there a way to play one sound as a Ringtone and another sound over it as a normal Media Sound?

Thanks in advance. Any help is appreciated.

答: Use sound pool if you want to play both sounds at the same time.</p>

Body:
I'm developing a Voip-Application and i have an edge case where i want to play two raw files at the same time.

When i have an incoming call from my application i am creating a new Mediaplayer and play a custom ringtone. When i get shortly after also  an incoming GSM-call i create a new mediaplayer and play a knocking sound to give the user feedback that there is also a GSM-Call incoming. At the same time i want the custom ringtone to continue playing.

private fun setAudioAttributesForFile(audioUsage: Int): AudioAttributes {
    return AudioAttributes.Builder()
            .setUsage(audioUsage)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
}

private fun startRingtone(fileToPlay: Int): MediaPlayer {
    return MediaPlayer().apply {
        reset()
        if (fileToPlay == R.raw.ring {
            setAudioAttributes(setAudioAttributesForFile(AudioAttributes.USAGE_NOTIFICATION_RINGTONE))
        } else {
            setAudioAttributes(setAudioAttributesForFile(AudioAttributes.USAGE_MEDIA))
        }
        isLooping = true
        Main.get().resources.openRawResourceFd(fileToPlay).use {
            setDataSource(
                    it.fileDescriptor,
                    it.startOffset,
                    it.length
            )
        }
        setOnPreparedListener { start() }
        prepareAsync()
    }
}

The problem that i have with this code is that as soon as the knocking sound is playing the ringtone gets muted by the system and as soon as the knocking sound is stopping the ringtone continues.

What i also tried:

Using only
AudioAttributes.USAGE_NOTIFICATION_RINGTONE. As soon as the knocking sound starts to play both mediaPlayers are getting muted.

If i leave the setAudioAttributes() call away and replace these four lines to

if (fileToPlay == R.raw.ring) {
    setAudioAttributesForFile(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
} else {
    setAudioAttributesForFile(AudioAttributes.USAGE_MEDIA)
}

then i can play those two files at the same time. The problem then is that the ringtone file is not shown as a ringtone instead it is only shown as a media file. So when i increase and decrease the volume of the ringtone the flag does not show that it is a ringtone.

Is there a way to play one sound as a Ringtone and another sound over it as a normal Media Sound?

Thanks in advance. Any help is appreciated.


问:
Python Dictionary to CSV Issue
I put together a python script to clean CSV files.  The reformatting works, but the data rows the writer writes to the new CSV file are wrong.  I am constructing a dictionary of all rows of data before writing using writer.writerows().  When I check the dictionary using print statements, the correct data is appending to the list.  However, after appending, the incorrect values are in the dictionary.

```<code>import csv

data = []
with open(r'C:\\Data\\input.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    street_fields = []                                  # Store new field names in list
    street_fields.append("startdate")
    street_fields.append("starttime")
    street_fields.append("sitecode")
    street_fields.append("recordtime")
    street_fields.append("direction")
    street_fields.append("turnright")
    street_fields.append("wentthrough")
    street_fields.append("turnleft")
    street_fields.append("pedestrians")
    for row in csv_reader:                              # Read input rows
        if line_count == 0:
            startdate = row[1]                          # Get Start Date from B1
            line_count += 1
        elif line_count == 1:
            starttime = row[1]                          # Get Start Time from B2
            line_count += 1
        elif line_count == 2:
            sitecode = str(row[1])                      # Get Site code from B3
            line_count += 1
        elif line_count == 3:
            street_count = len(row) - 3                 # Determine number of streets in report
            streetnames = []
            i = 1
            while i < street_count:
                streetnames.append(row[i])              # Add streets to list
                i += 4
            line_count += 1
        elif line_count > 4:
            street_values = {}                          # Create dictionary to store new row values
            n = 1
            for street in streetnames:
                turnright = 0 + n
                wentthrough = 1 + n
                turnleft = 2 + n
                pedestrians = 3 + n
                street_values["startdate"] = startdate
                street_values["starttime"] = starttime
                street_values["sitecode"] = sitecode
                street_values["recordtime"] = row[0]
                street_values["direction"] =  street
                street_values["turnright"] = int(row[turnright])
                street_values["wentthrough"] = int(row[wentthrough])
                street_values["turnleft"] = int(row[turnleft])
                street_values["pedestrians"] = int(row[pedestrians])
                data.append(street_values)                                  # Append row dictionary to list
                #print(street_values)                                       ### UNCOMMENT TO SEE CORRECT ROW DATA ###
                #print(data)                                                ### UNCOMMENT TO SEE INCORRECT ROW DATA ###
                n += 4
            line_count += 1
        else:
            line_count += 1
with open(r'C:\\Data\\output.csv', 'w', newline='', encoding="utf-8") as w_scv_file:
    writer = csv.DictWriter(w_scv_file,fieldnames=street_fields)
    writer.writerow(dict((fn,fn) for fn in street_fields))                  # Write headers to new CSV
    writer.writerows(data)                                                  # Write data from list of dictionaries
</code>```

An example of the list of dictionaries created (JSON):

```<code>[
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:00",
      "direction":"Cloud Dr. From North",
      "turnright":0,
      "wentthrough":2,
      "turnleft":11,
      "pedestrians":0
   },
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:00",
      "direction":"Florida Blvd. From East",
      "turnright":4,
      "wentthrough":433,
      "turnleft":15,
      "pedestrians":0
   },
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:00",
      "direction":"Cloud Dr. From South",
      "turnright":15,
      "wentthrough":4,
      "turnleft":6,
      "pedestrians":0
   },
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:00",
      "direction":"Florida Blvd. From West",
      "turnright":2,
      "wentthrough":219,
      "turnleft":2,
      "pedestrians":0
   },
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:15",
      "direction":"Cloud Dr. From North",
      "turnright":1,
      "wentthrough":3,
      "turnleft":8,
      "pedestrians":0
   }
]
</code>```

What actually writes to the CSV:

Note the Direction field and data rows are incorrect.  For some reason when it loops through the streetnames list, the last street name and the corresponding row values persist for the individual record time.

Do I need to delete my variables before re-assigning them values?

答:
It looks like you are appending the same dictionary to the list over and over.

In general, when appending a nuber of separate dictionaries to a list, I would use mylist.append(mydict.copy()), otherwise later on when you assign new values within a dictionary of the same name you are really just updating your old dictionary, including entries in your list that point to a dictionary of the same name (see mutable vs immutable objects in python).

In short: If you want the dictionary in the list to be a separate entity from the new one, create a deep copy using dict.copy() when appending it to the list.

Title: Python Dictionary to CSV Issue

Body:
I put together a python script to clean CSV files.  The reformatting works, but the data rows the writer writes to the new CSV file are wrong.  I am constructing a dictionary of all rows of data before writing using writer.writerows().  When I check the dictionary using print statements, the correct data is appending to the list.  However, after appending, the incorrect values are in the dictionary.

import csv

data = []
with open(r'C:\\Data\\input.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    street_fields = []                                  # Store new field names in list
    street_fields.append("startdate")
    street_fields.append("starttime")
    street_fields.append("sitecode")
    street_fields.append("recordtime")
    street_fields.append("direction")
    street_fields.append("turnright")
    street_fields.append("wentthrough")
    street_fields.append("turnleft")
    street_fields.append("pedestrians")
    for row in csv_reader:                              # Read input rows
        if line_count == 0:
            startdate = row[1]                          # Get Start Date from B1
            line_count += 1
        elif line_count == 1:
            starttime = row[1]                          # Get Start Time from B2
            line_count += 1
        elif line_count == 2:
            sitecode = str(row[1])                      # Get Site code from B3
            line_count += 1
        elif line_count == 3:
            street_count = len(row) - 3                 # Determine number of streets in report
            streetnames = []
            i = 1
            while i < street_count:
                streetnames.append(row[i])              # Add streets to list
                i += 4
            line_count += 1
        elif line_count > 4:
            street_values = {}                          # Create dictionary to store new row values
            n = 1
            for street in streetnames:
                turnright = 0 + n
                wentthrough = 1 + n
                turnleft = 2 + n
                pedestrians = 3 + n
                street_values["startdate"] = startdate
                street_values["starttime"] = starttime
                street_values["sitecode"] = sitecode
                street_values["recordtime"] = row[0]
                street_values["direction"] =  street
                street_values["turnright"] = int(row[turnright])
                street_values["wentthrough"] = int(row[wentthrough])
                street_values["turnleft"] = int(row[turnleft])
                street_values["pedestrians"] = int(row[pedestrians])
                data.append(street_values)                                  # Append row dictionary to list
                #print(street_values)                                       ### UNCOMMENT TO SEE CORRECT ROW DATA ###
                #print(data)                                                ### UNCOMMENT TO SEE INCORRECT ROW DATA ###
                n += 4
            line_count += 1
        else:
            line_count += 1
with open(r'C:\\Data\\output.csv', 'w', newline='', encoding="utf-8") as w_scv_file:
    writer = csv.DictWriter(w_scv_file,fieldnames=street_fields)
    writer.writerow(dict((fn,fn) for fn in street_fields))                  # Write headers to new CSV
    writer.writerows(data)                                                  # Write data from list of dictionaries

An example of the list of dictionaries created (JSON):

[
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:00",
      "direction":"Cloud Dr. From North",
      "turnright":0,
      "wentthrough":2,
      "turnleft":11,
      "pedestrians":0
   },
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:00",
      "direction":"Florida Blvd. From East",
      "turnright":4,
      "wentthrough":433,
      "turnleft":15,
      "pedestrians":0
   },
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:00",
      "direction":"Cloud Dr. From South",
      "turnright":15,
      "wentthrough":4,
      "turnleft":6,
      "pedestrians":0
   },
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:00",
      "direction":"Florida Blvd. From West",
      "turnright":2,
      "wentthrough":219,
      "turnleft":2,
      "pedestrians":0
   },
   {
      "startdate":"11/9/2017",
      "starttime":"7:00",
      "sitecode":"012345",
      "recordtime":"7:15",
      "direction":"Cloud Dr. From North",
      "turnright":1,
      "wentthrough":3,
      "turnleft":8,
      "pedestrians":0
   }
]

What actually writes to the CSV:

Note the Direction field and data rows are incorrect.  For some reason when it loops through the streetnames list, the last street name and the corresponding row values persist for the individual record time.

Do I need to delete my variables before re-assigning them values?


问:
How to use querySelectorAll only for elements that have a specific attribute set?
I'm trying to use document.querySelectorAll for all checkboxes that have the value attribute set.

There are other checkboxes on the page that do not have value set, and the value is different for each checkbox. The ids and names are not unique though.

Example:
    <input type="checkbox" id="c2" name="c2" value="DE039230952"/>

How do I select just those checkboxes that have values set?

答:
With your example:

```<code><input type="checkbox" id="c2" name="c2" value="DE039230952"/>
</code>```

Replace $$ with document.querySelectorAll in the examples:

```<code>$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
</code>```

Use the examples above directly, without the need for additional library, just by adding:

```<code>const $$ = document.querySelectorAll.bind(document);
</code>```

Some additions:

```<code>$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()
</code>```

Body:
With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples above directly, without the need for additional library, just by adding:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()


问:
Create a query (sum from diferent tables)
I have 3 tables and I want to sum the value:

```<code>Table 1
id............value
31001.........200
31002.........100
31003.........1
31004.........0
31005.........0

Table 2
id...........value
31001.........1
31002.........1
31004.........5

Table 3
id...........value
31001.........2
31003.........2
31005.........1
</code>```

I have tried using the following code:

```<code>SELECT table1.id, Sum([table1].[Value]+[table2].[Value]+[table3].[Value])
FROM (table1 LEFT JOIN table2 ON table1.[id] = table2.[id]) LEFT JOIN table3 ON table1.[id] = table3.[id]
WHERE (((table2.id) Is not Null) and (table3.id) and (table2.id))
GROUP BY table1.id;

UNION

SELECT table1.id,Sum([table1].[Value]+[table2].[Value])
FROM table1 LEFT JOIN table2 ON table1.[id] = table2.[id]
WHERE (((table2.id) Is not Null))
GROUP BY table1.id;

UNION

SELECT table1.id,Sum([table1].[Value]+[table3].[Value])
FROM table1 LEFT JOIN table3 ON table1.[id] = table3.[id]
WHERE (((table3.id) Is not Null))
GROUP BY table1.id;
</code>```

I want a result like:

```<code>id.........value
31001.......223
31002.......111
31003.........3
31004.........5
31005.........1
</code>```

But I'm getting

```<code>id..........value
31001.......221
31001.......222
31001.......223
31002.......111
31003.........3
31004.........5
31005.........1
</code>```

How can I fix it?

答:
First use UNION ALL for all 3 tables and then sum over the column value by id:

```<code>select id, sum(value) as totalvalue from (
  select id, value from table1
  union all
  select id, value from table2
  union all
  select id, value from table3
)
group by id
order by id
</code>```

The result will be:

```<code>id  totalvalue
31001   203
31002   101
31003   3
31004   5
31005   1
</code>```

Body:
I have 3 tables and I want to sum the value:

Table 1
id............value
31001.........200
31002.........100
31003.........1
31004.........0
31005.........0

Table 2
id...........value
31001.........1
31002.........1
31004.........5

Table 3
id...........value
31001.........2
31003.........2
31005.........1

I have tried using the following code:

SELECT table1.id, Sum([table1].[Value]+[table2].[Value]+[table3].[Value])
FROM (table1 LEFT JOIN table2 ON table1.[id] = table2.[id]) LEFT JOIN table3 ON table1.[id] = table3.[id]
WHERE (((table2.id) Is not Null) and (table3.id) and (table2.id))
GROUP BY table1.id;

UNION

SELECT table1.id,Sum([table1].[Value]+[table2].[Value])
FROM table1 LEFT JOIN table2 ON table1.[id] = table2.[id]
WHERE (((table2.id) Is not Null))
GROUP BY table1.id;

UNION

SELECT table1.id,Sum([table1].[Value]+[table3].[Value])
FROM table1 LEFT JOIN table3 ON table1.[id] = table3.[id]
WHERE (((table3.id) Is not Null))
GROUP BY table1.id;

I want a result like:

id.........value
31001.......223
31002.......111
31003.........3
31004.........5
31005.........1

But I'm getting

id..........value
31001.......221
31001.......222
31001.......223
31002.......111
31003.........3
31004.........5
31005.........1

How can I fix it?

Body:
First use UNION ALL for all 3 tables and then sum over the column value by id:

select id, sum(value) as totalvalue from (
  select id, value from table1
  union all
  select id, value from table2
  union all
  select id, value from table3
)
group by id
order by id

The result will be:

id  totalvalue
31001   203
31002   101
31003   3
31004   5
31005   1


问:
How to generate a random value and its result from a list?
What I want is, generate a random value displayed in a h tag, and also, display the good value relative to the random one, in an other tag.

```<code>var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var first_value = first[Math.floor(Math.random()*first.length)];
var second_value = second[Math.floor(Math.random()*second.length)];

document.getElementById('first_value').innerHTML = first_value;
document.getElementById('second_value').innerHTML = second_value;
</code>```

At the moment, everything is generated randomly, there is no relation between the 2 values generated.

If "10+20" is randomly selected, I want to display "30" in the second html tag.

答:
Generate one random number only and use it as index for both arrays.

There's no need to generate a second random value. Both arrays just need to be the same length.

var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var index = Math.floor(Math.random()*first.length);
var first_value = first[index];
var second_value = second[index];

document.getElementById('first_value').innerHTML = first_value;
document.getElementById('second_value').innerHTML = second_value;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="first_value"></div>
<div id="second_value"></div></code>```

Body:
What I want is, generate a random value displayed in a h tag, and also, display the good value relative to the random one, in an other tag.

var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var first_value = first[Math.floor(Math.random()*first.length)];
var second_value = second[Math.floor(Math.random()*second.length)];

document.getElementById('first_value').innerHTML = first_value;
document.getElementById('second_value').innerHTML = second_value;

At the moment, everything is generated randomly, there is no relation between the 2 values generated.

If "10+20" is randomly selected, I want to display "30" in the second html tag.

Body:
Generate one random number only and use it as index for both arrays.

There's no need to generate a second random value. Both arrays just need to be the same length.

var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var index = Math.floor(Math.random()*first.length);
var first_value = first[index];
var second_value = second[index];

document.getElementById('first_value').innerHTML = first_value;
document.getElementById('second_value').innerHTML = second_value;

<div id="first_value"></div>
<div id="second_value"></div>


问:
Is it possible to OPTIMIZE FOR a specific table variable 'value'?
Let's presume I have the following query running on SQL Server 2016:

```<code>declare @Ids as table
(
    Id int
)

-- Insert some values into @Ids table

select
    *
from dbo.Foos
where FooId in (select Id from @Ids)
</code>```

Now let's presume I want to OPTIMIZE FOR a specific 'value' of @Ids table.
Is is even possible to provide such hint? I've tried option (optimize for (@Ids = (values(1), (2)))), but it does not compile

Thanks in advance

答:
No, you can't use that option such a way. Let's have a look at the documentation:

OPTIMIZE FOR ( @variable_name { UNKNOWN | = literal_constant } [ ,
  ...n ] ) Instructs the query optimizer to use a particular value for a
  local variable when the query is compiled and optimized. The value is
  used only during query optimization, and not during query execution.

@variable_name Is the name of a local variable used in a query, to which a value may be assigned for use with the OPTIMIZE FOR query
  hint.

So, that option is for a local variable but not for a table variable which is an absolutely different thing.

Hints (Transact-SQL) - Query

Body:
Let's presume I have the following query running on SQL Server 2016:

declare @Ids as table
(
    Id int
)

-- Insert some values into @Ids table

select
    *
from dbo.Foos
where FooId in (select Id from @Ids)

Now let's presume I want to OPTIMIZE FOR a specific 'value' of @Ids table.
Is is even possible to provide such hint? I've tried option (optimize for (@Ids = (values(1), (2)))), but it does not compile

Thanks in advance


问:
How to add ( integrate ) crawljax with crawler4j?
I am working on web crawler which fetch data form website using crawler4j and everything goes well but the main problem is with ajax-based events . So, I found crawljax library does this matter but I couldn't where and when to use it .

When have I use it ( I mean work sequences )?

before fetching page using crawler4j.

Or

after fetching page using crawler4j.

Or

have I use url coming using crawler4j and use it to fetch Ajax data (page) using crawljax.

答:
The library crawljax is basically a crawler for its own purpose. Integration into crawler4j requires a lot of manual effort on your side.

I recommend, that you use a combination  of Selenium and/or CasperJS and/or PhantomJS in front of crawler4j, i.e. you could run the JavaScript engine as a Proxy in front of crawler4j. However, this will slow down the performance of your web-crawleer


问:
Right click in JavaFX?
How do I detect/handle a right click in JavaFX?</p>

答:
If you are wondering about handling right-click events in JavaFX, and find the 2009 answer is somewhat outdated by now... Here is a working example in java 11 (openjfx):</p>

```<code>public class RightClickApplication extends Application
{

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        primaryStage.setTitle("Example");
        Rectangle rectangle = new Rectangle(100, 100);
        BorderPane pane = new BorderPane();
        pane.getChildren().add(rectangle);

        rectangle.setOnMouseClicked(event ->
        {
            if (event.getButton() == MouseButton.PRIMARY)
            {
                rectangle.setFill(Color.GREEN);
            } else if (event.getButton() == MouseButton.SECONDARY)
            {
                rectangle.setFill(Color.RED);
            }
        });
        primaryStage.setScene(new Scene(pane, 200, 200));
        primaryStage.show();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Right click in JavaFX?

Body:
If you are wondering about handling right-click events in JavaFX, and find the 2009 answer is somewhat outdated by now... Here is a working example in java 11 (openjfx):

public class RightClickApplication extends Application
{

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        primaryStage.setTitle("Example");
        Rectangle rectangle = new Rectangle(100, 100);
        BorderPane pane = new BorderPane();
        pane.getChildren().add(rectangle);

        rectangle.setOnMouseClicked(event ->
        {
            if (event.getButton() == MouseButton.PRIMARY)
            {
                rectangle.setFill(Color.GREEN);
            } else if (event.getButton() == MouseButton.SECONDARY)
            {
                rectangle.setFill(Color.RED);
            }
        });
        primaryStage.setScene(new Scene(pane, 200, 200));
        primaryStage.show();
    }
}


问:
BTOUCH:error BI1017:Do not know how to make a signature for System.Int32* in method get_IssueTransport
I am binding JMC objective C static library to Xamarin compatible one, currently I am trying to build my binding project now(which contains ApiDefinition.cs, StructsAndEnums.cs and libJmcSDK.a) but when I try to build this Xamarin binding project I'm getting the following error:

BTOUCH: error BI1017: btouch: Do not know how to make a signature for System.Int32* in method 'get_IssueTransport'.

When I try to search for get_IssueTransport method, their is no search results for this, trying to find the System.Int32 signature as well but not able to find in throughout solution.

Any help in resolving this issue is much appreciated in advance. Thanks.

答: Change int* (any pointer type) to IntPtr


问:
R: Calculate monthly returns by group based on daily prices
I have a large dataframe crsp that contains several columns of daily stock data. Relevant for this question are the following columns (small extract to give you an idea):

```<code>PERMNO   date         monthyear  PRC       RET
10001    1990-01-02   199001     10.1250   0.0000
10001    1990-01-03   199001     10.0000  -0.0123
...
10001    1990-02-01   199002     10.0000   0.0000
10001    1990-02-02   199002     10.0625   0.0062
...
10002    1990-01-02   199001      6.1250   0.0000
10002    1990-01-03   199001      6.2000   0.0122
...
10002    1990-02-01   199002      6.2500   0.0000
10002    1990-02-02   199002      6.5000   0.0400
...
</code>```

"PERMNO" is the stock ID, "date" the actual date, "monthyear" indicates the month, "PRC" is the price and "RET" the daily return.

I am trying to add a new column "MonthlyReturn" which shows the monthly return for each stock. The value should therefore be calculated for each month of each stock (grouped by PERMNO).

As far as my knowledge goes, there could be two possibilities to solve this:

Calculate the monthly return through dividing the last price of each month of each stock through the first price of the month (careful: due to weekends the first trading day of the month is not necessarily the actual 1st day of the month)

Convert the existing daily returns to monthly returns

Either way, I am aiming for the following output:

```<code>PERMNO   date         monthyear  PRC       RET      MonthlyReturn
10001    1990-01-02   199001     10.1250   0.0000   0.1000
10001    1990-01-03   199001     10.0000  -0.0123   0.1000
...
10001    1990-02-01   199002     10.0000   0.0000   0.0987
10001    1990-02-02   199002     10.0625   0.0062   0.0987
...
10002    1990-01-02   199001      6.1250   0.0000  -0.0034
10002    1990-01-03   199001      6.2000   0.0122  -0.0034
...
10002    1990-02-01   199002      6.2500   0.0000   0.2340
10002    1990-02-02   199002      6.5000   0.0400   0.2340
...
</code>```

Through research I came upon the monthlyReturn-function from quantmod, could this be useful?

Any help would be greatly appreciated as I just started learning R. Also feel free to add anything that could help me improve this question's suitability for SO.

答:
Using Tidyverse, you can calculate your monthly return this way :

```<code>library(tidyverse)
library(lubridate)

df <- left_join(df, df %>%
  arrange(PERMNO, date) %>% # order the data  by stock id and date
  filter(!wday(as.Date(date)) %in% c(1,7)) %>% # filter week end
  group_by(PERMNO, monthyear) %>%
  mutate(MonthlyReturn = last(PRC) / first(PRC) - 1) %>% # calculate the monthly return per stock id and month
  select(PERMNO, monthyear, MonthlyReturn)) # Keep only these 3 columns
</code>```

Hope this helps.

Body:
I have a large dataframe crsp that contains several columns of daily stock data. Relevant for this question are the following columns (small extract to give you an idea):

PERMNO   date         monthyear  PRC       RET
10001    1990-01-02   199001     10.1250   0.0000
10001    1990-01-03   199001     10.0000  -0.0123
...
10001    1990-02-01   199002     10.0000   0.0000
10001    1990-02-02   199002     10.0625   0.0062
...
10002    1990-01-02   199001      6.1250   0.0000
10002    1990-01-03   199001      6.2000   0.0122
...
10002    1990-02-01   199002      6.2500   0.0000
10002    1990-02-02   199002      6.5000   0.0400
...

"PERMNO" is the stock ID, "date" the actual date, "monthyear" indicates the month, "PRC" is the price and "RET" the daily return.

I am trying to add a new column "MonthlyReturn" which shows the monthly return for each stock. The value should therefore be calculated for each month of each stock (grouped by PERMNO).

As far as my knowledge goes, there could be two possibilities to solve this:

Calculate the monthly return through dividing the last price of each month of each stock through the first price of the month (careful: due to weekends the first trading day of the month is not necessarily the actual 1st day of the month)

Convert the existing daily returns to monthly returns

Either way, I am aiming for the following output:

PERMNO   date         monthyear  PRC       RET      MonthlyReturn
10001    1990-01-02   199001     10.1250   0.0000   0.1000
10001    1990-01-03   199001     10.0000  -0.0123   0.1000
...
10001    1990-02-01   199002     10.0000   0.0000   0.0987
10001    1990-02-02   199002     10.0625   0.0062   0.0987
...
10002    1990-01-02   199001      6.1250   0.0000  -0.0034
10002    1990-01-03   199001      6.2000   0.0122  -0.0034
...
10002    1990-02-01   199002      6.2500   0.0000   0.2340
10002    1990-02-02   199002      6.5000   0.0400   0.2340
...

Through research I came upon the monthlyReturn-function from quantmod, could this be useful?

Any help would be greatly appreciated as I just started learning R. Also feel free to add anything that could help me improve this question's suitability for SO.

Body:
Using Tidyverse, you can calculate your monthly return this way :

library(tidyverse)
library(lubridate)

df <- left_join(df, df %>%
  arrange(PERMNO, date) %>% # order the data  by stock id and date
  filter(!wday(as.Date(date)) %in% c(1,7)) %>% # filter week end
  group_by(PERMNO, monthyear) %>%
  mutate(MonthlyReturn = last(PRC) / first(PRC) - 1) %>% # calculate the monthly return per stock id and month
  select(PERMNO, monthyear, MonthlyReturn)) # Keep only these 3 columns

Hope this helps.


问:
Which is the best way to yield thread?
Program language: C++ 11

I use pipeline threads mode to deal data.

One thread generate data.

One thread process data.

While no data to deal, which is the best way to yield thread?

Now I use

```<code>std::this_thread::sleep_for(100ms);
</code>```

I wonder if there is a better way to yield?

If sleep is well enough, how long time to sleep is better?

答:
Communicate over a queue of data.  The queue can have a max size if you want.

One thread generates data and shoves it into the queue.

Another thread pops data off the queue, and processes it.

When the queue is empty, the consuming thread waits in the queue for new data to be pushed.

When the queue is full, the producing thread waits in in the queue for data to be popped.  Alternatively, you could discard and replace waiting data in the queue.  Which depends on what your data model is like (most recent is important, or everything in order is important)

Simple queue:

```<code>template<class T>
struct threadsafe_queue {
  T pop() {
    auto l = lock();
    cv.wait( l, [&]{ return !data.empty(); } );
    T r = std::move(data.front());
    data.pop_front();
    return r;
  }
  void push( T&& t ) {
    auto l = lock();
    data.push_back( std::move(t) );
    cv.notify_one();
  }
  void abandon() {
    auto l = lock();
    data = {};
  }
private:
  std::unique_lock<std::mutex> lock() { return std::unique_lock<std::mutex>(m); }

  std::mutex m;
  std::condition_variable cv;
  std::deque<T> data;
};
</code>```

one with a limit on the number of entries should have a second condition_variable to notify when someone pops, and push should see if you are at the limit.

Supporting "overwrite when full" becomes another option.  A 1-element "most recent" looks like:

```<code>template<class T>
struct mono_threadsafe_queue {
  // waits until we have data, then returns it.
  T pop() {
    auto l = lock();
    cv_hasdata.wait( l, [&]{ return (bool)data; } );
    T r = std::move(*data);
    data = boost::none;
    cv_hasroom.notify_one();
    return r;
  }
  // waits for there to be room if there is none.
  void push( T&& t ) {
    auto l = lock();
    cv_hasroom.wait( l, [&]{ return !(bool)data; } );
    data =  std::move(t);
    cv_hasdata.notify_one();
  }
  void replace( T&& t ) {
    auto l = lock();
    data =  std::move(t);
    cv_hasdata.notify_one();
  }
  // replaces data if f returns true, or if there is no data
  // imagine data with a timestamp, and we only want to replace it with
  // newer data
  template<class F>
  void replace_if( T&& t, F&& f ) {
    auto l = lock();
    if (!data || !f(*data))
    {
      data =  std::move(t);
      cv_hasdata.notify_one();
    }
  }
  void abandon() {
    auto l = lock();
    data = boost::none;
    cv_hasroom.notify_one();
  }

private:
  std::unique_lock<std::mutex> lock() { return std::unique_lock<std::mutex>(m); }

  std::mutex m;
  std::condition_variable cv_hasdata;
  std::condition_variable cv_hasroom;
  boost::optional<T> data;
};
</code>```

Title: Which is the best way to yield thread?

Body:
Program language: C++ 11

I use pipeline threads mode to deal data.

One thread generate data.

One thread process data.

While no data to deal, which is the best way to yield thread?

Now I use

std::this_thread::sleep_for(100ms);

I wonder if there is a better way to yield?

If sleep is well enough, how long time to sleep is better?

Body:
Communicate over a queue of data.  The queue can have a max size if you want.

One thread generates data and shoves it into the queue.

Another thread pops data off the queue, and processes it.

When the queue is empty, the consuming thread waits in the queue for new data to be pushed.

When the queue is full, the producing thread waits in in the queue for data to be popped.  Alternatively, you could discard and replace waiting data in the queue.  Which depends on what your data model is like (most recent is important, or everything in order is important)

Simple queue:

template<class T>
struct threadsafe_queue {
  T pop() {
    auto l = lock();
    cv.wait( l, [&]{ return !data.empty(); } );
    T r = std::move(data.front());
    data.pop_front();
    return r;
  }
  void push( T&& t ) {
    auto l = lock();
    data.push_back( std::move(t) );
    cv.notify_one();
  }
  void abandon() {
    auto l = lock();
    data = {};
  }
private:
  std::unique_lock<std::mutex> lock() { return std::unique_lock<std::mutex>(m); }

  std::mutex m;
  std::condition_variable cv;
  std::deque<T> data;
};

one with a limit on the number of entries should have a second condition_variable to notify when someone pops, and push should see if you are at the limit.

Supporting "overwrite when full" becomes another option.  A 1-element "most recent" looks like:

template<class T>
struct mono_threadsafe_queue {
  // waits until we have data, then returns it.
  T pop() {
    auto l = lock();
    cv_hasdata.wait( l, [&]{ return (bool)data; } );
    T r = std::move(*data);
    data = boost::none;
    cv_hasroom.notify_one();
    return r;
  }
  // waits for there to be room if there is none.
  void push( T&& t ) {
    auto l = lock();
    cv_hasroom.wait( l, [&]{ return !(bool)data; } );
    data =  std::move(t);
    cv_hasdata.notify_one();
  }
  void replace( T&& t ) {
    auto l = lock();
    data =  std::move(t);
    cv_hasdata.notify_one();
  }
  // replaces data if f returns true, or if there is no data
  // imagine data with a timestamp, and we only want to replace it with
  // newer data
  template<class F>
  void replace_if( T&& t, F&& f ) {
    auto l = lock();
    if (!data || !f(*data))
    {
      data =  std::move(t);
      cv_hasdata.notify_one();
    }
  }
  void abandon() {
    auto l = lock();
    data = boost::none;
    cv_hasroom.notify_one();
  }

private:
  std::unique_lock<std::mutex> lock() { return std::unique_lock<std::mutex>(m); }

  std::mutex m;
  std::condition_variable cv_hasdata;
  std::condition_variable cv_hasroom;
  boost::optional<T> data;
};


问:
Use JPA without EJB in a distributed environment
So my boss asked me to look for a way to use JPA in Spring without using EJB in a distributed environment (single DB and multiple sessions reading/writing from/on it). But I have a lot of confusion.

I've used Spring Boot and JPA using entities with @Entity annotation in simple projects, and if I understood correctly these are EJBs, right?

So now he told me that he doesn't want to use EJBs, but to find if it's possible, how hard/easy is it and what can be used to correctly manage distributed transactions on the same DB, not having the enterprise beans that, from what I understood, handle this problem easily by themselves.

I know it is confusing, but I don't know where to start or what to look for, and which is the best way to guarantee the ACID properties not using EJBs.

I've read that instead of EJBs, EntityManager and UserTransaction from JTA can be used, to manage transactions manually. Is it good in a distributed environment? What would its behaviour be? How can one guarantee correct update for all sessions?

答:
I do not understand very well your specific beacause you are saying distributed environment but then (single DB and multiple sessions reading/writing from/on it)

@Entity are not EJBs.

You can use Spring + JPA instead of EJBs.

The answer ot the part: "the best way to guarantee the ACID properties not using EJBs." is:

Using @EntityManager which handles for you the transactions.
I would use a Controller-Service-Dao approach. Something like this:

```<code>public abstract class GenericDAO  {
    protected EntityManager entityManager;

    @PersistenceContext(unitName="canvasEM") //persistence unit name defined inside persistence.xml
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}

public interface CanvasDAO {
    void newCanvas();
}

// Java map for a single DB table
@Entity
public class CanvasEntity  {

}

@Repository
public class CanvasDAOImpl extends GenericDAO implements CanvasDAO {
    @Override
    public void newCanvas()  {
        CanvasEntity e = new CanvasEntity();
        ...
        entityManager.persist(e);
    }
}

public interface CanvasService {
    CanvasDTO newCanvas(NewCanvasInputDTO in);
}

@Service
public class CanvasServiceImpl implements CanvasService {
    @Autowired
    private CanvasDAO canvasDAO;

    @Override
    public CanvasDTO newCanvas(){
        return canvasDAO.newCanvas();
    }
}

@RestController //or @Component
public class MyController{
    @Autowired
    CanvasService canvasService;

    ...
}

persistence.xml
<persistence>
    <persistence-unit name="canvasEM" ....>
</persistence>

</code>```

You can see how I configured JPA and Spring in this example here. Can give you a basic idea: https://github.com/ermalaliraj/connect4

Body:
I do not understand very well your specific beacause you are saying distributed environment but then (single DB and multiple sessions reading/writing from/on it)

@Entity are not EJBs.

You can use Spring + JPA instead of EJBs.

The answer ot the part: "the best way to guarantee the ACID properties not using EJBs." is:

Using @EntityManager which handles for you the transactions.
I would use a Controller-Service-Dao approach. Something like this:

public abstract class GenericDAO  {
    protected EntityManager entityManager;

    @PersistenceContext(unitName="canvasEM") //persistence unit name defined inside persistence.xml
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}

public interface CanvasDAO {
    void newCanvas();
}

// Java map for a single DB table
@Entity
public class CanvasEntity  {

}

@Repository
public class CanvasDAOImpl extends GenericDAO implements CanvasDAO {
    @Override
    public void newCanvas()  {
        CanvasEntity e = new CanvasEntity();
        ...
        entityManager.persist(e);
    }
}

public interface CanvasService {
    CanvasDTO newCanvas(NewCanvasInputDTO in);
}

@Service
public class CanvasServiceImpl implements CanvasService {
    @Autowired
    private CanvasDAO canvasDAO;

    @Override
    public CanvasDTO newCanvas(){
        return canvasDAO.newCanvas();
    }
}

@RestController //or @Component
public class MyController{
    @Autowired
    CanvasService canvasService;

    ...
}

persistence.xml
<persistence>
    <persistence-unit name="canvasEM" ....>
</persistence>

You can see how I configured JPA and Spring in this example here. Can give you a basic idea: https://github.com/ermalaliraj/connect4


问:
how to save mutiple values in raiseevent() python function
In pepper Robo, I would like to pass username and password as values in raiseEvent() method in python to validate user login details.

i have added below function in working project

```<code>sesson.raiseEvent("eventname", username, password)

    function login()
    {
             alert('reached login details');
             var username = document.getElementById('txtusername').value;
             var password = document.getElementById('txtpassword').value;
             //alert(username);
             //alert(password);
             loginDetails(username,password);

    }

    function loginDetails(username,password){

                session.raiseEvent("loginreq", username,password);
                //window.location = 'paybympay.html?Language='+ LANGUAGE;
    }
</code>```

.raiseEvent() has to accept multiple values such as username and password

```<code>tested in pepper robot did not accept the multiple values. how to achieve this.
</code>```

答:
I'm assuming the code you're showing is javascript on Pepper's tablet.

1) What you're doing looks very insecure. I would strongly advise against passing any raw user password as a value in ALMemory, especially for what seems to be a payment system.

2) A slightly better way of doing this would be to directly call a service of your own, e.g. from javascript you can call MyServiceOnPepper.handleLogin(username, password), for example see the service-tabletpage example here for ways of doing that.

But I would not consider this secure enough for a user password, and would add encryption (for example, use RSA, and have your service publish a public key, and have the javascript use that to encrypt the password).

3) (it's also technically possible to pass a list as an ALMemory event, but using a dedicated service is cleaner and slightly more secure)

Body:
In pepper Robo, I would like to pass username and password as values in raiseEvent() method in python to validate user login details.

i have added below function in working project

sesson.raiseEvent("eventname", username, password)

    function login()
    {
             alert('reached login details');
             var username = document.getElementById('txtusername').value;
             var password = document.getElementById('txtpassword').value;
             //alert(username);
             //alert(password);
             loginDetails(username,password);

    }

    function loginDetails(username,password){

                session.raiseEvent("loginreq", username,password);
                //window.location = 'paybympay.html?Language='+ LANGUAGE;
    }

.raiseEvent() has to accept multiple values such as username and password

tested in pepper robot did not accept the multiple values. how to achieve this.


问:
Contents of data returned by HKStatisticsQuery
I'm using following code to get burned energy for today:

```<code>    func getTodaysSummary(for type:HKQuantityType!, unit u:HKUnit!, completion: @escaping (Double) -> Void) {
        let stepsQuantityType = type

        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

        let query = HKStatisticsQuery(quantityType: stepsQuantityType!, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
            var resultCount = 0.0

            guard let result = result else {
                completion(resultCount)
                return
            }

            if let sum = result.sumQuantity() {
                resultCount = sum.doubleValue(for: u)
            }

            DispatchQueue.main.async {
                completion(resultCount)
            }
        }

        healthStore.execute(query)
    }

...

self.getTodaysSummary(for: HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned), unit: HKUnit.kilocalorie(), completion: { (energyBurned) in
  print("\(energyBurned)")
})
</code>```

Now I need to understand, what data does it return? In different sources like apple documentation I read this data should contain all activity including walking, swimming etc.

But in my case it returns only the number 680 (I added this value manually via + button on Activity Energy screen of Health app)

It definetly doesn't include steps I've made during the day.
So the question, do I need to calculate those calories separately?
Also there are iWatch rings that also seem like not returning by HKStatisticsQuery requests. Should I calculate them separately as well to calculate total burned energy?

答: The iPhone does not automatically compute Active Energy. The user must have an Apple Watch in order to get Active and Basal Energy samples automatically written to HealthKit.</p>

Body:
I'm using following code to get burned energy for today:

    func getTodaysSummary(for type:HKQuantityType!, unit u:HKUnit!, completion: @escaping (Double) -> Void) {
        let stepsQuantityType = type

        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

        let query = HKStatisticsQuery(quantityType: stepsQuantityType!, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
            var resultCount = 0.0

            guard let result = result else {
                completion(resultCount)
                return
            }

            if let sum = result.sumQuantity() {
                resultCount = sum.doubleValue(for: u)
            }

            DispatchQueue.main.async {
                completion(resultCount)
            }
        }

        healthStore.execute(query)
    }

...

self.getTodaysSummary(for: HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned), unit: HKUnit.kilocalorie(), completion: { (energyBurned) in
  print("\(energyBurned)")
})

Now I need to understand, what data does it return? In different sources like apple documentation I read this data should contain all activity including walking, swimming etc.

But in my case it returns only the number 680 (I added this value manually via + button on Activity Energy screen of Health app)

It definetly doesn't include steps I've made during the day.
So the question, do I need to calculate those calories separately?
Also there are iWatch rings that also seem like not returning by HKStatisticsQuery requests. Should I calculate them separately as well to calculate total burned energy?


问:
How should the input shape of Keras LSTM layer looks like
I've been reading for a while about training LSTM models using tf.keras, where i did use the same framework for regression problems using simple feedforward NN architectures and i highly understand how should i prepare the input data for such models,  however when it comes for training LSTM, i feel so confused about the shape of the input.

There is a lot to take care about: time steps, number of samples, batch size, number of units, etc. In addition to many parameters for the LSTM keras layer that aren't clear for me yet as what is shown in the below example:

```<code>model.add(keras.layers.LSTM(units=3, batch_input_shape=(8,2,10), return_sequence=True, stateful= True))
</code>```

So I have the following forex data structure where i don't know how to reshape it properly for an LSTM model.

```<code>open | close | high | low | volume | i1 | i2 | i3 | ... | i30 | nextClose
</code>```

These features represents the open/close/high/low prices of a certain currency pair, in addition to the volume and 30 different indicators' values from i1 -> i30, all of these features corresponds to one minuet tick. Besides the nextClose feature represents the next minuet tick close price value that I'm trying hopefully to predict.

Q1: Could anyone please explain the general concept of how the data should be shaped for input, and what are all of these required parameters (time step, batch size...)?

Q2: Where I think a simple example could be great, How should my data structure above be reshaped to look like a valid input for LSTM?

答: After a lot of search i found this excellent summary for keras LSTM in a diagram, that was so helpful. check it in the Keras_LSTM_Diagram git repository.

Body:
I've been reading for a while about training LSTM models using tf.keras, where i did use the same framework for regression problems using simple feedforward NN architectures and i highly understand how should i prepare the input data for such models,  however when it comes for training LSTM, i feel so confused about the shape of the input.

There is a lot to take care about: time steps, number of samples, batch size, number of units, etc. In addition to many parameters for the LSTM keras layer that aren't clear for me yet as what is shown in the below example:

model.add(keras.layers.LSTM(units=3, batch_input_shape=(8,2,10), return_sequence=True, stateful= True))

So I have the following forex data structure where i don't know how to reshape it properly for an LSTM model.

open | close | high | low | volume | i1 | i2 | i3 | ... | i30 | nextClose

These features represents the open/close/high/low prices of a certain currency pair, in addition to the volume and 30 different indicators' values from i1 -> i30, all of these features corresponds to one minuet tick. Besides the nextClose feature represents the next minuet tick close price value that I'm trying hopefully to predict.

Q1: Could anyone please explain the general concept of how the data should be shaped for input, and what are all of these required parameters (time step, batch size...)?

Q2: Where I think a simple example could be great, How should my data structure above be reshaped to look like a valid input for LSTM?


问:
How does Apache Ignite synchronize in cluster mode?
This information eluded me when searching through the documentation. How does Apache Ignite, if used in cluster mode, synchronize between nodes when these nodes become inactive and active again?

Assume the following scenario:

I have 2 nodes. Node A is elected Leader. Everything works until node B crashes. Node A continues to work, more transactions are executed. Before node B comes back up, node A goes down. After that, node B comes back up. What happens in this case? Does node B know it was not the master and has to wait until node A comes back up? Does it throw an exception and fails to start? Does it simply not care?

Is there any information on the docs for such scenarios?

答:
There is a rebalance process, which synchronizes data between nodes.

There is no such thing as a Leader in Ignite. All data in the cache divided by partitions and each node have its own subset of primary partitions.

Before node B comes back up, node A goes down

Do you have persistence enabled? If no, then you just lost data, since all nodes in cluster went down.


问:
Create TopoJson/GeoJson map of US South East
I need to create a TopoJson or GeoJson file of the US South East, like in this image:

I can either take the map of the whole US and extract the states I need, or take the individual states and merge them. Either way I don’t know how to approach this. Any ideas will be more than welcome.

答:
The simplest solution is to create a chart with some basic map of the USA with states and use remove methods for unwanted points.

```<code>chart: {
    map: 'countries/us/us-all',
    animation: false,
    events: {
        load: function() {
            var points = this.series[0].points;

            points.forEach(function(p) {
                if (!p.value) {
                    p.remove();

                }
            });

            this.mapZoom(0.56, 7251, -5218);
        }
    }
}
</code>```

Live demo: http://jsfiddle.net/BlackLabel/v69nsryz/

API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#mapZoom

You can also search the Highmaps map collection or create a custom map.

Map collection: https://code.highcharts.com/mapdata/

Docs: https://www.highcharts.com/docs/maps/custom-maps

Body:
The simplest solution is to create a chart with some basic map of the USA with states and use remove methods for unwanted points.

chart: {
    map: 'countries/us/us-all',
    animation: false,
    events: {
        load: function() {
            var points = this.series[0].points;

            points.forEach(function(p) {
                if (!p.value) {
                    p.remove();

                }
            });

            this.mapZoom(0.56, 7251, -5218);
        }
    }
}

Live demo: http://jsfiddle.net/BlackLabel/v69nsryz/

API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#mapZoom

You can also search the Highmaps map collection or create a custom map.

Map collection: https://code.highcharts.com/mapdata/

Docs: https://www.highcharts.com/docs/maps/custom-maps


问:
JTable displays true/false instead of a CheckBox although "getColumnClass" is implemented
I have a JTable in which I want to display Boolean-values in form of CheckBoxes, which should be able to be edited (get checked/unchecked).

In order to accomplish that, I have implemented a subclass of AbstractTableModel with all needed methods, getColumnClass and isCellEditable implemented.

The problem is, that instead of a CheckBox, true/false is displayed. Only when I click on the cell, the getColumnClass-Method is called and the CheckBox appears for a short period of time.

I have found out, that the JTable never calls "getColumnClass" in the beginning but just when I want to click in the cell.

```<code>public class OrderTableModel extends AbstractTableModel {
    private ArrayList<Orders> orders;
    private final String[] HEADER = {"Date", "isParty", "isHost"};

public OrderTableModel(ArrayList<Orders> orders)
{
    this.orders = orders;
}

public OrderTableModel(){
    orders = new ArrayList<>();
}

@Override
public String getColumnName(int column) {
    return HEADER[column];
}

@Override
public int getRowCount() {
    return orders.size() > 20 ? orders.size() : 20;
}

@Override
public int getColumnCount() {
    return HEADER.length;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
    System.out.println("in getColumnClass");
    switch(columnIndex)
    {
        case 1: return Boolean.class;
        case 2: return Boolean.class;
        default: return String.class;
    }

}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    ...
}
</code>```

答:
The problem was, that I set a DefaultCellRenderer in the GUI to center things:

```<code>    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment( SwingConstants.CENTER );

    for(int i = 0;i<table1.getColumnCount();i++)
        table1.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
</code>```

which, I think, got "asked" by the JTable for what the Cells Class is instead of the in the model implemented getColumnClass method!

Body:
I have a JTable in which I want to display Boolean-values in form of CheckBoxes, which should be able to be edited (get checked/unchecked).

In order to accomplish that, I have implemented a subclass of AbstractTableModel with all needed methods, getColumnClass and isCellEditable implemented.

The problem is, that instead of a CheckBox, true/false is displayed. Only when I click on the cell, the getColumnClass-Method is called and the CheckBox appears for a short period of time.

I have found out, that the JTable never calls "getColumnClass" in the beginning but just when I want to click in the cell.

public class OrderTableModel extends AbstractTableModel {
    private ArrayList<Orders> orders;
    private final String[] HEADER = {"Date", "isParty", "isHost"};

public OrderTableModel(ArrayList<Orders> orders)
{
    this.orders = orders;
}

public OrderTableModel(){
    orders = new ArrayList<>();
}

@Override
public String getColumnName(int column) {
    return HEADER[column];
}

@Override
public int getRowCount() {
    return orders.size() > 20 ? orders.size() : 20;
}

@Override
public int getColumnCount() {
    return HEADER.length;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
    System.out.println("in getColumnClass");
    switch(columnIndex)
    {
        case 1: return Boolean.class;
        case 2: return Boolean.class;
        default: return String.class;
    }

}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    ...
}

Body:
The problem was, that I set a DefaultCellRenderer in the GUI to center things:

    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment( SwingConstants.CENTER );

    for(int i = 0;i<table1.getColumnCount();i++)
        table1.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);

which, I think, got "asked" by the JTable for what the Cells Class is instead of the in the model implemented getColumnClass method!


问:
How to add items to dynamically created select (html) Control
Hi
  How to add items to dynamically created select (html) Control..

thanks

答:
For adding items on server side, use HtmlSelect.Items property. For example,</p>

```<code>var select = control as HtmlSelect; // may not be needed
var items = select.Items;
// Add items to the collection.
items.Add(new ListItem("apples", "1"));
items.Add(new ListItem("bananas", "2"));
items.Add(new ListItem("cherries", "3"));
</code>```

Body:
For adding items on server side, use HtmlSelect.Items property. For example,

var select = control as HtmlSelect; // may not be needed
var items = select.Items;
// Add items to the collection.
items.Add(new ListItem("apples", "1"));
items.Add(new ListItem("bananas", "2"));
items.Add(new ListItem("cherries", "3"));


问:
Google map autocomplete for IOS in ionic 2
i am using google auto complete in my IOS Ionic 2 app. When i start typing an address in a field the matching addresses appear ok in a drop down list but if I select one, the ion-input field is not populated. Could anyone help me how to fix this?

This is my template:

```<code><ion-item>
<ion-input id="journey_from" name="journey_from" type="text" placeholder="" [(ngModel)] = "location"></ion-input>
</ion-item>
</code>```

This is my component:

```<code>  ngAfterViewInit(){
    let options = {
      componentRestrictions:{
        country: 'IN'
      },
      types: ['(regions)']
    }
    let input = document.getElementById('autocomplete').getElementsByTagName('input')[0];
    let autoComplete = new google.maps.places.Autocomplete(this.autocomplete.nativeElement,options );
    google.maps.event.addListener(autoComplete,'place_changed', () => {
     this.placeSelect = autoComplete.getPlace();
 this.location= this.placeSelect.formatted_address;

     this.changeDetect.detectChanges();   });
</code>```

答:
UPDATE

You probably use the CDVUIWebViewEngine. Try to update to WKWebView to resolve your problem ;)
You can find here how to upgrade your web view engine.
If you use angularhttp, you'll need to use ionic-native@http instead for iOS (best way to resolve cors issues with angular-http and WKWebView).
Good luck guys :D

Body:
i am using google auto complete in my IOS Ionic 2 app. When i start typing an address in a field the matching addresses appear ok in a drop down list but if I select one, the ion-input field is not populated. Could anyone help me how to fix this?

This is my template:

<ion-item>
<ion-input id="journey_from" name="journey_from" type="text" placeholder="" [(ngModel)] = "location"></ion-input>
</ion-item>

This is my component:

  ngAfterViewInit(){
    let options = {
      componentRestrictions:{
        country: 'IN'
      },
      types: ['(regions)']
    }
    let input = document.getElementById('autocomplete').getElementsByTagName('input')[0];
    let autoComplete = new google.maps.places.Autocomplete(this.autocomplete.nativeElement,options );
    google.maps.event.addListener(autoComplete,'place_changed', () => {
     this.placeSelect = autoComplete.getPlace();
 this.location= this.placeSelect.formatted_address;

     this.changeDetect.detectChanges();   });


问:
Substitutions inside Sphinx code blocks aren't replaced
In this reST example meant to be rendered by Sphinx, |yaco_url| doesn't get replaced because it's in a code-block:

```<code>.. |yaco_url| replace:: http://yaco.es/

You can use wget to download it:

.. code-block:: console

    $ wget |yaco_url|package.tar.gz
</code>```

I  wonder if there is some way to force the replacement of |yaco_url| before rendering the code block.

答:
Found a better solution (in my opinion), that can be used in others directives like :samp: and might be useful for future readers.

config.py:

```<code>def ultimateReplace(app, docname, source):
    result = source[0]
    for key in app.config.ultimate_replacements:
        result = result.replace(key, app.config.ultimate_replacements[key])
    source[0] = result

ultimate_replacements = {
    "{TEST}" : "replaced"
}

def setup(app):
   app.add_config_value('ultimate_replacements', {}, True)
   app.connect('source-read', ultimateReplace)
</code>```

And this kind of markup:

```<code>.. http:get:: testing/replacement/{TEST}
</code>```

Properly generates like:

```<code>testing/replacement/replaced
</code>```

Note, that if using this to replace an argument in the :samp: directive, a double bracket { is require.

```<code>:samp:`func({{TEST}})`.
</code>```

source: https://github.com/sphinx-doc/sphinx/issues/4054

Body:
In this reST example meant to be rendered by Sphinx, |yaco_url| doesn't get replaced because it's in a code-block:

.. |yaco_url| replace:: http://yaco.es/

You can use wget to download it:

.. code-block:: console

    $ wget |yaco_url|package.tar.gz

I  wonder if there is some way to force the replacement of |yaco_url| before rendering the code block.

Body:
Found a better solution (in my opinion), that can be used in others directives like :samp: and might be useful for future readers.

config.py:

def ultimateReplace(app, docname, source):
    result = source[0]
    for key in app.config.ultimate_replacements:
        result = result.replace(key, app.config.ultimate_replacements[key])
    source[0] = result

ultimate_replacements = {
    "{TEST}" : "replaced"
}

def setup(app):
   app.add_config_value('ultimate_replacements', {}, True)
   app.connect('source-read', ultimateReplace)

And this kind of markup:

.. http:get:: testing/replacement/{TEST}

Properly generates like:

testing/replacement/replaced

Note, that if using this to replace an argument in the :samp: directive, a double bracket { is require.

:samp:`func({{TEST}})`.

source: https://github.com/sphinx-doc/sphinx/issues/4054


问:
Can not open new window in Chrome
I am trying to open a second window in my website for a popunder as assigned by my hierarchy. So I made this code:

```<code><html>
<head></head>
<body>
<script>
var popunderUrl = 'https://www.google.com';
window.open(window.location.href);
window.location.href = popunderUrl;
</script>
</body>
</html>
</code>```

As you can see, there is no extra code that can interfere with the JavaScript.

It works as intended on IE and Edge, but not in FireFox and Chrome. Do these browsers block this behaviour by default?

答:
Do these browsers block this behaviour by default?

Yes. Opening new windows on page load is routinely abused, so many browsers disallow it. If your code didn't navigate away from the page, you might see a notification from the browser saying that Page XYZ wanted to open a popup, which the user could then allow if they wanted. But because you navigate away, the user doesn't have a chance to do that.

You'll have to tell the people telling you to do this that browsers actively try to defeat it, and even if you find a way to make it work today, that's no guarantee that it'll work tomorrow. (Whereas if other people are anything like me, doing it is a great way to guarantee that people never visit your site again. ;-) )

Title: Can not open new window in Chrome

Body:
I am trying to open a second window in my website for a popunder as assigned by my hierarchy. So I made this code:

As you can see, there is no extra code that can interfere with the JavaScript.

It works as intended on IE and Edge, but not in FireFox and Chrome. Do these browsers block this behaviour by default?


问:
Class file has wrong version
When im importing the opencv library into intellij I get a compile error saying:

I have tried setting the SDK and project language level to 1.8 but it still shows the same error message.

What can I do to solve this issue?

答:
I think OpenCV libraries are compiled using java version 11 and not java 8. Please refer the link below for the class version corresponding java version. Or you can use jdk and jre 11 for the compilation and runtime.
List of Java class file format major version numbers?</p>

Title: Class file has wrong version


问:
Program not working as well - C
The following code gives me a zero value for 'count' all the time...

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}
</code>```

Thanks !

答:
This

```<code>int const count =0 ;
</code>```

and this

```<code>count++;
</code>```

conflicts , value of const variable can't be changed (that is why it is called constant)

Title: Program not working as well - C

Body:
The following code gives me a zero value for 'count' all the time...

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

Thanks !

Body:
This

int const count =0 ;

and this

count++;

conflicts , value of const variable can't be changed (that is why it is called constant)