问:
Python Google Drive API file-delete() method broken
I cannot get google-drive file-delete() method to work via the Python API.

It is acting broken.

I offer some info about my setup:

Ubuntu 16.04

Python 3.5.2 (default, Nov 12 2018, 13:43:14)

google-api-python-client (1.7.9)

google-auth (1.6.3)

google-auth-httplib2 (0.0.3)

google-auth-oauthlib (0.3.0)

Below, I list a Python script which can reproduce the bug:

```<code>"""
googdrive17.py

This script should delete files named 'hello.txt'

Ref:
https://developers.google.com/drive/api/v3/quickstart/python
https://developers.google.com/drive/api/v3/reference/files

Demo (Ubuntu):
sudo apt install python3-pip
sudo pip3 install --upgrade google-api-python-client
sudo pip3 install --upgrade google-auth-httplib2
sudo pip3 install --upgrade google-auth-oauthlib

python3 googdrive17.py
"""

import pickle
import os.path
from googleapiclient.discovery      import build
from googleapiclient.http           import MediaFileUpload
from google_auth_oauthlib.flow      import InstalledAppFlow
from google.auth.transport.requests import Request

# I s.declare a very permissive scope (for training only):
SCOPES      = ['https://www.googleapis.com/auth/drive']

creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as fh:
        creds = pickle.load(fh)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server()
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

# I s.create a file so I can upload it:
with open('/tmp/hello.txt','w') as fh:
    fh.write("hello world\n")
# From my laptop, I s.upload a file named hello.txt:
drive_service = build('drive', 'v3', credentials=creds)
file_metadata = {'name': 'hello.txt'}
media = MediaFileUpload('/tmp/hello.txt', mimetype='text/plain')
create_response = drive_service.files().create(body=file_metadata,
                                     media_body=media,
                                     fields='id').execute()
file_id = create_response.get('id')
print('new /tmp/hello.txt file_id:')
print(file_id)

# Q: With googleapiclient, how to filter files list()-response?
# A1: https://developers.google.com/drive/api/v3/reference/files/list
# A2: https://developers.google.com/drive/api/v3/search-files

list_response = drive_service.files().list(
    orderBy   = "createdTime desc",
    q         = "name='hello.txt'",
    pageSize  = 22,
    fields    = "files(id, name)"
).execute()

items = list_response.get('files', [])

if items:
    for item in items:
        print('I will try to delete this file:')
        print(u'{0} ({1})'.format(item['name'], item['id']))
        del_response = drive_service.files().delete(fileId=item['id'])
        print('del_response.body:')
        print( del_response.body)
    print('I will try to emptyTrash:')
    trash_response = drive_service.files().emptyTrash()
    print('trash_response.body:')
    print( trash_response.body)
else:
    print('hello.txt not found in your google-drive account.')
</code>```

When I run the script I see output similar to that listed below:

```<code>$ python3 googdrive17.py
new /tmp/hello.txt file_id:
1m8nKOfIeB0E5t60F_-9bKwIJds8PSvYY
I will try to delete this file:
hello.txt (1m8nKOfIeB0E5t60F_-9bKwIJds8PSvYY)
del_response.body:
None
I will try to delete this file:
hello.txt (1Ow4fcUBgEYUy3ezYScDKlLSMbp-hyOLT)
del_response.body:
None
I will try to delete this file:
hello.txt (1TiUrLgQdY1Cb9w0UWHjnmj7HZBaFsKcp)
del_response.body:
None
I will try to emptyTrash:
trash_response.body:
None
$
</code>```

I see that two of the API calls work well:

files.list()

files.create()

Two calls appear broken:

files.delete()

files.emptyTrash()

Perhaps, though, I call them incorrectly?

答:
How about this modification?

At first, the official document of Files: delete method and Files: emptyTrash method says as follows.

If successful, this method returns an empty response body.

By this, when the file was deleted and the trash was cleared, the returned del_response and trash_response are empty.

Modified script:

From your question, I could understand that files.list() and files.create() works. So I would like to propose the modification points for files.delete() and files.emptyTrash(). Please modify your script as follows.

From:

```<code>for item in items:
    print('I will try to delete this file:')
    print(u'{0} ({1})'.format(item['name'], item['id']))
    del_response = drive_service.files().delete(fileId=item['id'])
    print('del_response.body:')
    print( del_response.body)
print('I will try to emptyTrash:')
trash_response = drive_service.files().emptyTrash()
print('trash_response.body:')
print( trash_response.body)
</code>```

To:

```<code>for item in items:
    print('I will try to delete this file:')
    print(u'{0} ({1})'.format(item['name'], item['id']))
    del_response = drive_service.files().delete(fileId=item['id']).execute()  # Modified
    print('del_response.body:')
    print(del_response)
print('I will try to emptyTrash:')
trash_response = drive_service.files().emptyTrash().execute()  # Modified
print('trash_response.body:')
print(trash_response)
</code>```

execute() was added for drive_service.files().delete() and drive_service.files().emptyTrash().

References:

Files: delete

Files: emptyTrash

If this was not the result you want, I apologize.

Body:
I cannot get google-drive file-delete() method to work via the Python API.

It is acting broken.

I offer some info about my setup:

Ubuntu 16.04

Python 3.5.2 (default, Nov 12 2018, 13:43:14)

google-api-python-client (1.7.9)

google-auth (1.6.3)

google-auth-httplib2 (0.0.3)

google-auth-oauthlib (0.3.0)

Below, I list a Python script which can reproduce the bug:

"""
googdrive17.py

This script should delete files named 'hello.txt'

Ref:
https://developers.google.com/drive/api/v3/quickstart/python
https://developers.google.com/drive/api/v3/reference/files

Demo (Ubuntu):
sudo apt install python3-pip
sudo pip3 install --upgrade google-api-python-client
sudo pip3 install --upgrade google-auth-httplib2
sudo pip3 install --upgrade google-auth-oauthlib

python3 googdrive17.py
"""

import pickle
import os.path
from googleapiclient.discovery      import build
from googleapiclient.http           import MediaFileUpload
from google_auth_oauthlib.flow      import InstalledAppFlow
from google.auth.transport.requests import Request

# I s.declare a very permissive scope (for training only):
SCOPES      = ['https://www.googleapis.com/auth/drive']

creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as fh:
        creds = pickle.load(fh)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server()
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

# I s.create a file so I can upload it:
with open('/tmp/hello.txt','w') as fh:
    fh.write("hello world\n")
# From my laptop, I s.upload a file named hello.txt:
drive_service = build('drive', 'v3', credentials=creds)
file_metadata = {'name': 'hello.txt'}
media = MediaFileUpload('/tmp/hello.txt', mimetype='text/plain')
create_response = drive_service.files().create(body=file_metadata,
                                     media_body=media,
                                     fields='id').execute()
file_id = create_response.get('id')
print('new /tmp/hello.txt file_id:')
print(file_id)

# Q: With googleapiclient, how to filter files list()-response?
# A1: https://developers.google.com/drive/api/v3/reference/files/list
# A2: https://developers.google.com/drive/api/v3/search-files

list_response = drive_service.files().list(
    orderBy   = "createdTime desc",
    q         = "name='hello.txt'",
    pageSize  = 22,
    fields    = "files(id, name)"
).execute()

items = list_response.get('files', [])

if items:
    for item in items:
        print('I will try to delete this file:')
        print(u'{0} ({1})'.format(item['name'], item['id']))
        del_response = drive_service.files().delete(fileId=item['id'])
        print('del_response.body:')
        print( del_response.body)
    print('I will try to emptyTrash:')
    trash_response = drive_service.files().emptyTrash()
    print('trash_response.body:')
    print( trash_response.body)
else:
    print('hello.txt not found in your google-drive account.')

When I run the script I see output similar to that listed below:

$ python3 googdrive17.py
new /tmp/hello.txt file_id:
1m8nKOfIeB0E5t60F_-9bKwIJds8PSvYY
I will try to delete this file:
hello.txt (1m8nKOfIeB0E5t60F_-9bKwIJds8PSvYY)
del_response.body:
None
I will try to delete this file:
hello.txt (1Ow4fcUBgEYUy3ezYScDKlLSMbp-hyOLT)
del_response.body:
None
I will try to delete this file:
hello.txt (1TiUrLgQdY1Cb9w0UWHjnmj7HZBaFsKcp)
del_response.body:
None
I will try to emptyTrash:
trash_response.body:
None
$

I see that two of the API calls work well:

files.list()

files.create()

Two calls appear broken:

files.delete()

files.emptyTrash()

Perhaps, though, I call them incorrectly?

Body:
How about this modification?

At first, the official document of Files: delete method and Files: emptyTrash method says as follows.

If successful, this method returns an empty response body.

By this, when the file was deleted and the trash was cleared, the returned del_response and trash_response are empty.

Modified script:

From your question, I could understand that files.list() and files.create() works. So I would like to propose the modification points for files.delete() and files.emptyTrash(). Please modify your script as follows.

From:

for item in items:
    print('I will try to delete this file:')
    print(u'{0} ({1})'.format(item['name'], item['id']))
    del_response = drive_service.files().delete(fileId=item['id'])
    print('del_response.body:')
    print( del_response.body)
print('I will try to emptyTrash:')
trash_response = drive_service.files().emptyTrash()
print('trash_response.body:')
print( trash_response.body)

To:

for item in items:
    print('I will try to delete this file:')
    print(u'{0} ({1})'.format(item['name'], item['id']))
    del_response = drive_service.files().delete(fileId=item['id']).execute()  # Modified
    print('del_response.body:')
    print(del_response)
print('I will try to emptyTrash:')
trash_response = drive_service.files().emptyTrash().execute()  # Modified
print('trash_response.body:')
print(trash_response)

execute() was added for drive_service.files().delete() and drive_service.files().emptyTrash().

References:

Files: delete

Files: emptyTrash

If this was not the result you want, I apologize.


来源: stackexchange

问:
Is there an R function that resolve a second order linear model?
I´m a begginer in R and programming and struggling in doing  problably a simple task.
I've made a code that creates a second model order and i want to input variables in this model and find the "Y value"

I´ve tried to use the predict function, but is actually pretty complex and I can't got anywhere.

I did this so far:

```<code>modFOI <- rsm(Rendimento~FO(x1,x2,x3,x4)+TWI(x1,x2,x3,x4)+PQ(x1,x2,x3,x4),data=CR) # com interações
summary(modFOI)
print(modFOI)
</code>```

With that, i found the SO model, but now i want to create variables like x1,x2,x3 and input that in the model and find the Y. I also woud like to find the optimum Y

答:
Simplest way to create a polynomial (2nd order) that I can think of is the following:

```<code>DF <- data.frame(x = runif(10,0,1),
                 y = runif(10,0,1) )
mod <- lm(DF$y ~ DF$x + I(DF$x^2))

predict(mod, new.data=data.frame(x=c(1,2,3,4,5)))
</code>```

NB. when using predict the new.data must be in a data.frame format, and the variable must have the same name as the variable in the model (here, x)

Hope this helps

ContentLicense: CC BY-SA 4.0

Body:
I´m a begginer in R and programming and struggling in doing  problably a simple task.
I've made a code that creates a second model order and i want to input variables in this model and find the "Y value"

I´ve tried to use the predict function, but is actually pretty complex and I can't got anywhere.

I did this so far:

modFOI <- rsm(Rendimento~FO(x1,x2,x3,x4)+TWI(x1,x2,x3,x4)+PQ(x1,x2,x3,x4),data=CR) # com interações
summary(modFOI)
print(modFOI)

With that, i found the SO model, but now i want to create variables like x1,x2,x3 and input that in the model and find the Y. I also woud like to find the optimum Y

Body:
Simplest way to create a polynomial (2nd order) that I can think of is the following:

DF <- data.frame(x = runif(10,0,1),
                 y = runif(10,0,1) )
mod <- lm(DF$y ~ DF$x + I(DF$x^2))

predict(mod, new.data=data.frame(x=c(1,2,3,4,5)))

NB. when using predict the new.data must be in a data.frame format, and the variable must have the same name as the variable in the model (here, x)

Hope this helps


问:
Why does jQuery has a "window=this" at the very begining and say it would speed up references to window?
When I open jQuery's source code I find this line.

```<code>var
// Will speed up references to window, and allows munging its name.
window = this
</code>```

Why and how this line will speed up?

答: this would be faster for javascript to reference to, as compared to window which would have to be resolved to the window object.

OwnerDisplayName: David

ContentLicense: CC BY-SA 2.5

Body:
When I open jQuery's source code I find this line.

var
// Will speed up references to window, and allows munging its name.
window = this

Why and how this line will speed up?

OwnerDisplayName: Click Upvote


问:
Easily strip alpha channel from images in Mathematica
What is the simplest way to strip the alpha channel (and possible convert images to greyscale) in Mathematica?

I would like to use ImageAssemble, but some of the images come with and some without an alpha channel.  Is there a simpler built-in way than manipulating the ImageData directly?

答:
For Mathematica 7, I believe this works:

```<code>ColorCombine@Most@ColorSeparate@# &
</code>```

It's not robust at this point, but type checking could be added.

ContentLicense: CC BY-SA 3.0

Body:
For Mathematica 7, I believe this works:

ColorCombine@Most@ColorSeparate@# &

It's not robust at this point, but type checking could be added.


问:
Counting number of sequences of particular value for multiple columns in a data frame
I would like to create a table or a new data frame that displays, for each column in the original data frame (of which there are many), how many times a sequence of a specific value occurs. For example, if I have the following data frame:

```<code>x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "a", "a", "a", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))
</code>```

and I want to know, for each color (Red, Blue, and Green) how many times a run of the value "a" occurs (i.e., before it is interrupted by another value like b or c)

The correct answer would look something like this:

```<code>     Color a_sequences
1   Red  2
2  Blue  1
3 Green  3
</code>```

I have found solutions on this site using the rle function on single vectors but I don't know how to scale this up for an entire data frame with multiple columns and obtain a new table or data frame with the sequence counts, as in the above table. Thank you!

答:
Here is an option with tidyverse where we gather into 'long' format, grouped by 'color', and the run-length-id (rleid) of 'value', filter the 'value' elements that are 'a', then grouped by 'color', get the number of distinct 'grp' elements

```<code>library(tidyverse)
library(data.table)
gather(x, color, value) %>%
   group_by(color, grp = rleid(value)) %>%
   filter(value == "a") %>%
   group_by(color) %>%
   summarise(n = n_distinct(grp))
# A tibble: 3 x 2
#  color     n
#  <chr> <int>
#1 Blue      1
#2 Green     3
#3 Red       2
</code>```

Or an option with summarise_all

```<code>x %>%
   summarise_all(list(~ n_distinct(setdiff((. == 'a') * rleid(.), 0)))) %>%
   as.list %>%
   enframe %>%
   unnest
# A tibble: 3 x 2
#  name  value
#  <chr> <int>
#1 Red       2
#2 Blue      1
#3 Green     3
</code>```

Body:
I would like to create a table or a new data frame that displays, for each column in the original data frame (of which there are many), how many times a sequence of a specific value occurs. For example, if I have the following data frame:

x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "a", "a", "a", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))

and I want to know, for each color (Red, Blue, and Green) how many times a run of the value "a" occurs (i.e., before it is interrupted by another value like b or c)

The correct answer would look something like this:

     Color a_sequences
1   Red  2
2  Blue  1
3 Green  3

I have found solutions on this site using the rle function on single vectors but I don't know how to scale this up for an entire data frame with multiple columns and obtain a new table or data frame with the sequence counts, as in the above table. Thank you!

Body:
Here is an option with tidyverse where we gather into 'long' format, grouped by 'color', and the run-length-id (rleid) of 'value', filter the 'value' elements that are 'a', then grouped by 'color', get the number of distinct 'grp' elements

library(tidyverse)
library(data.table)
gather(x, color, value) %>%
   group_by(color, grp = rleid(value)) %>%
   filter(value == "a") %>%
   group_by(color) %>%
   summarise(n = n_distinct(grp))
# A tibble: 3 x 2
#  color     n
#  <chr> <int>
#1 Blue      1
#2 Green     3
#3 Red       2

Or an option with summarise_all

x %>%
   summarise_all(list(~ n_distinct(setdiff((. == 'a') * rleid(.), 0)))) %>%
   as.list %>%
   enframe %>%
   unnest
# A tibble: 3 x 2
#  name  value
#  <chr> <int>
#1 Red       2
#2 Blue      1
#3 Green     3


问:
How to combine two arrays of integers and return average?
Ok so I have two arrays of integers, and I have to return the average rating of the two days. This is the code that I have come up with thus far, but apparently it does not meet the expectations. Result:

Message:   Expected: 5.0d
    But was:  3.0d

Unit:

```<code>public double WeekendAverage(int[] saturday, int[] sunday)
    {
        int[] n = { saturday.Length, sunday.Length };
        int sum = 0;

        for (int i = 0; i < n.Length; i++)
        {
            sum = saturday[i] + sunday[i];
            return sum / n.Length;
        }
        return sum;
        }
</code>```

UnitTest:

```<code>[TestCase(new[] { 1, 2, 3, 4, 5, 7, 8, 5, 10 }, new[] { 9, 9, 9, 8, 9, 8, 9, 9, 9, 10, 10 }, 7)]

public void WeekendAverage(int[] saturday, int[] sunday, double expected)
    {
        var actual = warmups.WeekendAverage(saturday, sunday);
        Assert.AreEqual(expected, actual);
    }
</code>```

答:
The length of n is 2 as an array. You want an int that stores the total of the two array lengths, not an array of integers representing the lengths of your parameters.

Change that to n = saturday.length + sunday.length and i < n in your loop.

Body:
Ok so I have two arrays of integers, and I have to return the average rating of the two days. This is the code that I have come up with thus far, but apparently it does not meet the expectations. Result:

Message:   Expected: 5.0d
    But was:  3.0d

Unit:

public double WeekendAverage(int[] saturday, int[] sunday)
    {
        int[] n = { saturday.Length, sunday.Length };
        int sum = 0;

        for (int i = 0; i < n.Length; i++)
        {
            sum = saturday[i] + sunday[i];
            return sum / n.Length;
        }
        return sum;
        }

UnitTest:

[TestCase(new[] { 1, 2, 3, 4, 5, 7, 8, 5, 10 }, new[] { 9, 9, 9, 8, 9, 8, 9, 9, 9, 10, 10 }, 7)]

public void WeekendAverage(int[] saturday, int[] sunday, double expected)
    {
        var actual = warmups.WeekendAverage(saturday, sunday);
        Assert.AreEqual(expected, actual);
    }


问:
Spring Boot with Hibernate generating drop constraint errors on startup with H2 database
I am using spring-boot and have an H2 database configured like so (in the application.properties).

```<code>spring.datasource.url=jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
</code>```

In the logs I am seeing the following errors:

```<code>o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
        name: default
        ...]
org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.5.Final}
org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table key_request drop constraint FK_53shrbc21c25inskpp1yoxxss if exists
org.hibernate.tool.hbm2ddl.SchemaExport  : Table "KEY_REQUEST" not found; SQL statement:
    alter table key_request drop constraint FK_53shrbc21c25inskpp1yoxxss if exists [42102-178]
</code>```

Even though hibernate reports these as errors, I can then login to the H2 console and see the constraints and they appear to be just fine.

```<code>SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, INDEX_TYPE_NAME FROM information_schema.indexes WHERE TABLE_NAME='KEY_REQUEST';
TABLE_NAME    INDEX_NAME                            COLUMN_NAME  INDEX_TYPE_NAME
KEY_REQUEST   PRIMARY_KEY_F                         REQUEST_ID   PRIMARY KEY
KEY_REQUEST   FK_53SHRBC21C25INSKPP1YOXXSS_INDEX_F  USER_ID      INDEX
</code>```

If really looks like hibernate is trying to drop these constraints before it actually creates the database (i.e. some kind of bug in hibernate).
Is there any way to avoid these errors clogging up the logs or are the indicative of a real failure somewhere?

UPDATE 1

Trying to force the application to only do updates using this setting:

```<code>spring.jpa.hibernate.ddl-auto=update
</code>```

Results in the following errors (all the other errors disappear):

```<code>org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000388: Unsuccessful: alter table lti_result add constraint FK_1cnh9amy5br8owkmafsrth3as foreign key (result_id) references lti_link
org.hibernate.tool.hbm2ddl.SchemaUpdate  : Constraint "FK_1CNH9AMY5BR8OWKMAFSRTH3AS" already exists; SQL statement:
    alter table lti_result add constraint FK_1cnh9amy5br8owkmafsrth3as foreign key (result_id) references lti_link [90045-178]
</code>```

NOTE: the source is here: https://github.com/azeckoski/lti_starter

Specifically the config:
https://github.com/azeckoski/lti_starter/blob/master/src/main/resources/application.properties

and the model:
https://github.com/azeckoski/lti_starter/tree/master/src/main/java/ltistarter/model

答:
thanks, this work for  me .

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=create
logging.level.org.hibernate.SQL= DEBUG
hibernate.hbm2ddl.auto=update

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
# Enable response compression
server.compression.enabled=true
# The comma-separated list of mime types that should be compressed
server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json
# Compress the response only if the response size is at least 1KB
server.compression.min-response-size=1024
server.http2.enabled=true
# Maximum time the response should be cached (in seconds)
spring.resources.cache.cachecontrol.max-age=120
# The cache must re-validate stale resources with the server. Any expired resources must not be used without re-validating.
spring.resources.cache.cachecontrol.must-revalidate=true
#https://www.callicoder.com/configuring-spring-boot-application/
server.port=8080```

Body:
I am using spring-boot and have an H2 database configured like so (in the application.properties).

spring.datasource.url=jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

In the logs I am seeing the following errors:

o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
        name: default
        ...]
org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.5.Final}
org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table key_request drop constraint FK_53shrbc21c25inskpp1yoxxss if exists
org.hibernate.tool.hbm2ddl.SchemaExport  : Table "KEY_REQUEST" not found; SQL statement:
    alter table key_request drop constraint FK_53shrbc21c25inskpp1yoxxss if exists [42102-178]

Even though hibernate reports these as errors, I can then login to the H2 console and see the constraints and they appear to be just fine.

SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, INDEX_TYPE_NAME FROM information_schema.indexes WHERE TABLE_NAME='KEY_REQUEST';
TABLE_NAME    INDEX_NAME                            COLUMN_NAME  INDEX_TYPE_NAME
KEY_REQUEST   PRIMARY_KEY_F                         REQUEST_ID   PRIMARY KEY
KEY_REQUEST   FK_53SHRBC21C25INSKPP1YOXXSS_INDEX_F  USER_ID      INDEX

If really looks like hibernate is trying to drop these constraints before it actually creates the database (i.e. some kind of bug in hibernate).
Is there any way to avoid these errors clogging up the logs or are the indicative of a real failure somewhere?

UPDATE 1

Trying to force the application to only do updates using this setting:

spring.jpa.hibernate.ddl-auto=update

Results in the following errors (all the other errors disappear):

org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000388: Unsuccessful: alter table lti_result add constraint FK_1cnh9amy5br8owkmafsrth3as foreign key (result_id) references lti_link
org.hibernate.tool.hbm2ddl.SchemaUpdate  : Constraint "FK_1CNH9AMY5BR8OWKMAFSRTH3AS" already exists; SQL statement:
    alter table lti_result add constraint FK_1cnh9amy5br8owkmafsrth3as foreign key (result_id) references lti_link [90045-178]

NOTE: the source is here: https://github.com/azeckoski/lti_starter

Specifically the config:
https://github.com/azeckoski/lti_starter/blob/master/src/main/resources/application.properties

and the model:
https://github.com/azeckoski/lti_starter/tree/master/src/main/java/ltistarter/model


问:
How can I generate signal and record with NAudio at the same time?
I want to make a sine signal, play it with speaker, receive it using MIC, and then record it.

I tried to make some programs to achieve that as below, but some problems occur.

Generate Sine Signal -> Speaker -> MIC -> Record (wave)

1) WaveOut :
 I used two WaveOut.

a) To Generate Signal

b) To Record a wave file.
 Does it make a problem?

2) Echo Sound :

a) Earphone :

If I use earphone, I can hear pure sine sweep sound. But MIC can't heard this sound. and then it will just record environment sound.

b) Speaker :

If I use speaker (same earphone line, I just add amplifier and speaker), I can hear echo sound as below picture. And MIC also record this echo sound.
  I can guess MIC received this sound and after some millisecond Speaker add this sound on Original sound. But I can't understand why Speaker add this received sound. How can I record without echo sound?

3) Recording Time :

I want to record 2 sec. Then I used timer and defined timer.Interval = 2 sec.
  But real record time is over 2 sec. some delay?

4) Sweep Time :

I defined 2 sec sweep time. But during over 2 sec, sine sweep is not finished. At finish time (about 2.2 sec) frequency is 1.5kHz. (I defined End frequency
 =2kHz).

Recorded Echo Wave file

```<code>public partial class Form1 : Form
{
    private WaveIn recorder;
    private BufferedWaveProvider bufferedWaveProvider;
    private SavingWaveProvider savingWaveProvider;
    private WaveOut player;

    private WaveOut player_sweep;   // 190305

    public Form1()
    {
        InitializeComponent();
    }

    private void OnStartRecording_Click(object sender, EventArgs e)
    {
        // set up the recorder
        recorder = new WaveIn();
        recorder.DataAvailable += RecorderOnDataAvailable;

        // set up our signal chain
        bufferedWaveProvider = new BufferedWaveProvider(recorder.WaveFormat);
        savingWaveProvider = new SavingWaveProvider(bufferedWaveProvider, "temp.wav");

        // set up playback
        player = new WaveOut();
        player.Init(savingWaveProvider);

        // 190305   / Signal Generator : Sine 50~2000 Hz, 2 sec
        SignalGenerator sweep_out = new SignalGenerator();
        sweep_out.Gain = 1;
        sweep_out.Frequency = 50;
        sweep_out.FrequencyEnd = 2000;
        sweep_out.SweepLengthSecs = 2;
        sweep_out.Type = SignalGeneratorType.Sweep;

        player_sweep = new WaveOut();   // 190305
        player_sweep.Init(sweep_out); // 190305

        // begin playback & record
        recorder.StartRecording();

        timer1.Enabled = true;

        // begin playback & record
        player.Play();      // Start Recording

        player_sweep.Play();    // 190305
    }

    private void RecorderOnDataAvailable(object sender, WaveInEventArgs waveInEventArgs)
    {
        bufferedWaveProvider.AddSamples(waveInEventArgs.Buffer, 0, waveInEventArgs.BytesRecorded);
    }

    private void timer1_Tick(object sender, EventArgs e)    // 190305
    {
        timer1.Enabled = false;

        player_sweep.Stop();    // 190305

        // stop playback
        player.Stop();

        // stop recording
        recorder.StopRecording();

        // finalise the WAV file
        savingWaveProvider.Dispose();

    }
}
</code>```

答:
I studied again NAudio. ( https://www.pluralsight.com/courses/audio-programming-naudio/ )
And I got the solution as below.

My Target : Generate Sine Signal -> Speaker -> MIC -> Record (wave)

using this, I want to analyze the speaker conditions additionally using FFT.

Generate Sine Signal :NAudio.Wave.SamplePrividers.SignalGenerator

Speaker Output :NAudio.Wave.WaveOut

Microphone : NAudio.Wave.WaveIn

Record(wave) : NAudio.Wave.WaveFileWriter

// Source Code

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Diagnostics;   // for Process, Stopwatch
using NAudio.Wave;    // for WaveOut, WaveIn
using NAudio.Wave.SampleProviders;  // for SignalGenerator

namespace Speaker_Record-Wave
{
    public partial class Form1 : Form
    {
        // 0) StopWatch
        Stopwatch stopWatch;

        // 1) Signal Gen -> Speaker
        WaveOut waveOut;
        SignalGenerator signalGenerator;

        // 2) MIC -> Wave
        WaveIn waveIn;
        WaveFileWriter waveFileWriter;

        public Form1()
        {
            InitializeComponent();
        }

        private void bt_Start_Click(object sender, EventArgs e)
        {
            // 0) StopWatch
            stopWatch = new Stopwatch();
            stopWatch.Start();

            // 1) Signal Gen -> Speaker
            Start_Signal();

            // 3) Timer_Sweep
            timer_Sweep.Interval = 1500;
            timer_Sweep.Enabled = true;

            // 2) MIC -> Wave
            Start_Record();
        }

        private void timer_Sweep_Tick(object sender, EventArgs e)
        {
            // 3) Timer_Sweep
            timer_Sweep.Enabled = false;

            // 1) Signal Gen -> Speaker
            waveOut.Stop();

            // 2) MIC -> Wave
            waveIn.StopRecording();

            // 4) 공통
            waveOut.Dispose();
            waveIn.Dispose();
            waveFileWriter.Dispose();

            // 0) StopWatch
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            string es = String.Format("{0:00}:{1:00}:{2:00}:{3:00}",ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            tb_Result.AppendText(es + "\n");
        }

        private void bt_Open_Folder_Click(object sender, EventArgs e)
        {
            Process.Start(".\\");   // Open Folder
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////

        // 1) Signal Gen -> Speaker
        private void Start_Signal()
        {
            signalGenerator = new SignalGenerator();
            signalGenerator.Type = SignalGeneratorType.Sweep;
            signalGenerator.Frequency = 50;
            signalGenerator.FrequencyEnd = 5000;
            signalGenerator.SweepLengthSecs = 1.5;

            waveOut = new WaveOut();
            waveOut.DeviceNumber = 0;
            waveOut.Init(signalGenerator);
            waveOut.Play();
        }

        // 2) MIC -> Wave
        private void Start_Record()
        {
            waveIn = new WaveIn();
            waveIn.DeviceNumber = 0;
            waveIn.WaveFormat = new WaveFormat(44100, 16, 1);

            waveIn.DataAvailable += OnDataAvailable;
            waveIn.RecordingStopped += OnRecordingStopped;

            waveFileWriter = new WaveFileWriter("1_Recorded.wav", waveIn.WaveFormat);

            waveIn.StartRecording();
        }

        // 2) MIC -> Wave
        private void OnDataAvailable(object sender, WaveInEventArgs e)
        {
            if (waveFileWriter != null)
            {
                waveFileWriter.Write(e.Buffer, 0, e.BytesRecorded);
            }
        }

        // 2) MIC -> Wave
        private void OnRecordingStopped(object sender, StoppedEventArgs e)
        {
            waveIn.Dispose();
            waveFileWriter.Dispose();
        }
    }
}
</code>```

Body:
I want to make a sine signal, play it with speaker, receive it using MIC, and then record it.

I tried to make some programs to achieve that as below, but some problems occur.

Generate Sine Signal -> Speaker -> MIC -> Record (wave)

1) WaveOut :
 I used two WaveOut.

a) To Generate Signal

b) To Record a wave file.
 Does it make a problem?

2) Echo Sound :

a) Earphone :

If I use earphone, I can hear pure sine sweep sound. But MIC can't heard this sound. and then it will just record environment sound.

b) Speaker :

If I use speaker (same earphone line, I just add amplifier and speaker), I can hear echo sound as below picture. And MIC also record this echo sound.
  I can guess MIC received this sound and after some millisecond Speaker add this sound on Original sound. But I can't understand why Speaker add this received sound. How can I record without echo sound?

3) Recording Time :

I want to record 2 sec. Then I used timer and defined timer.Interval = 2 sec.
  But real record time is over 2 sec. some delay?

4) Sweep Time :

I defined 2 sec sweep time. But during over 2 sec, sine sweep is not finished. At finish time (about 2.2 sec) frequency is 1.5kHz. (I defined End frequency
 =2kHz).

Recorded Echo Wave file

public partial class Form1 : Form
{
    private WaveIn recorder;
    private BufferedWaveProvider bufferedWaveProvider;
    private SavingWaveProvider savingWaveProvider;
    private WaveOut player;

    private WaveOut player_sweep;   // 190305

    public Form1()
    {
        InitializeComponent();
    }

    private void OnStartRecording_Click(object sender, EventArgs e)
    {
        // set up the recorder
        recorder = new WaveIn();
        recorder.DataAvailable += RecorderOnDataAvailable;

        // set up our signal chain
        bufferedWaveProvider = new BufferedWaveProvider(recorder.WaveFormat);
        savingWaveProvider = new SavingWaveProvider(bufferedWaveProvider, "temp.wav");

        // set up playback
        player = new WaveOut();
        player.Init(savingWaveProvider);

        // 190305   / Signal Generator : Sine 50~2000 Hz, 2 sec
        SignalGenerator sweep_out = new SignalGenerator();
        sweep_out.Gain = 1;
        sweep_out.Frequency = 50;
        sweep_out.FrequencyEnd = 2000;
        sweep_out.SweepLengthSecs = 2;
        sweep_out.Type = SignalGeneratorType.Sweep;

        player_sweep = new WaveOut();   // 190305
        player_sweep.Init(sweep_out); // 190305

        // begin playback & record
        recorder.StartRecording();

        timer1.Enabled = true;

        // begin playback & record
        player.Play();      // Start Recording

        player_sweep.Play();    // 190305
    }

    private void RecorderOnDataAvailable(object sender, WaveInEventArgs waveInEventArgs)
    {
        bufferedWaveProvider.AddSamples(waveInEventArgs.Buffer, 0, waveInEventArgs.BytesRecorded);
    }

    private void timer1_Tick(object sender, EventArgs e)    // 190305
    {
        timer1.Enabled = false;

        player_sweep.Stop();    // 190305

        // stop playback
        player.Stop();

        // stop recording
        recorder.StopRecording();

        // finalise the WAV file
        savingWaveProvider.Dispose();

    }
}

Body:
I studied again NAudio. ( https://www.pluralsight.com/courses/audio-programming-naudio/ )
And I got the solution as below.

My Target : Generate Sine Signal -> Speaker -> MIC -> Record (wave)

using this, I want to analyze the speaker conditions additionally using FFT.

Generate Sine Signal :NAudio.Wave.SamplePrividers.SignalGenerator

Speaker Output :NAudio.Wave.WaveOut

Microphone : NAudio.Wave.WaveIn

Record(wave) : NAudio.Wave.WaveFileWriter

// Source Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Diagnostics;   // for Process, Stopwatch
using NAudio.Wave;    // for WaveOut, WaveIn
using NAudio.Wave.SampleProviders;  // for SignalGenerator

namespace Speaker_Record-Wave
{
    public partial class Form1 : Form
    {
        // 0) StopWatch
        Stopwatch stopWatch;

        // 1) Signal Gen -> Speaker
        WaveOut waveOut;
        SignalGenerator signalGenerator;

        // 2) MIC -> Wave
        WaveIn waveIn;
        WaveFileWriter waveFileWriter;

        public Form1()
        {
            InitializeComponent();
        }

        private void bt_Start_Click(object sender, EventArgs e)
        {
            // 0) StopWatch
            stopWatch = new Stopwatch();
            stopWatch.Start();

            // 1) Signal Gen -> Speaker
            Start_Signal();

            // 3) Timer_Sweep
            timer_Sweep.Interval = 1500;
            timer_Sweep.Enabled = true;

            // 2) MIC -> Wave
            Start_Record();
        }

        private void timer_Sweep_Tick(object sender, EventArgs e)
        {
            // 3) Timer_Sweep
            timer_Sweep.Enabled = false;

            // 1) Signal Gen -> Speaker
            waveOut.Stop();

            // 2) MIC -> Wave
            waveIn.StopRecording();

            // 4) 공통
            waveOut.Dispose();
            waveIn.Dispose();
            waveFileWriter.Dispose();

            // 0) StopWatch
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            string es = String.Format("{0:00}:{1:00}:{2:00}:{3:00}",ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            tb_Result.AppendText(es + "\n");
        }

        private void bt_Open_Folder_Click(object sender, EventArgs e)
        {
            Process.Start(".\\");   // Open Folder
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////

        // 1) Signal Gen -> Speaker
        private void Start_Signal()
        {
            signalGenerator = new SignalGenerator();
            signalGenerator.Type = SignalGeneratorType.Sweep;
            signalGenerator.Frequency = 50;
            signalGenerator.FrequencyEnd = 5000;
            signalGenerator.SweepLengthSecs = 1.5;

            waveOut = new WaveOut();
            waveOut.DeviceNumber = 0;
            waveOut.Init(signalGenerator);
            waveOut.Play();
        }

        // 2) MIC -> Wave
        private void Start_Record()
        {
            waveIn = new WaveIn();
            waveIn.DeviceNumber = 0;
            waveIn.WaveFormat = new WaveFormat(44100, 16, 1);

            waveIn.DataAvailable += OnDataAvailable;
            waveIn.RecordingStopped += OnRecordingStopped;

            waveFileWriter = new WaveFileWriter("1_Recorded.wav", waveIn.WaveFormat);

            waveIn.StartRecording();
        }

        // 2) MIC -> Wave
        private void OnDataAvailable(object sender, WaveInEventArgs e)
        {
            if (waveFileWriter != null)
            {
                waveFileWriter.Write(e.Buffer, 0, e.BytesRecorded);
            }
        }

        // 2) MIC -> Wave
        private void OnRecordingStopped(object sender, StoppedEventArgs e)
        {
            waveIn.Dispose();
            waveFileWriter.Dispose();
        }
    }
}


问:
Fuzzy match portions of an image
I need to determine the existance of a smaller image inside a larger image.

The match must be fuzzy and preferrably I should know how well it matched (%), but I can calculate the accuracy my self after the match is done if required.

My goal is to match a FFT (Fast Fourier Transfrom) spectrogram (visualization of frequencies in music) with the original music track. The small image I'm matching with is only a subset (both in time and frequency range) of the original track (like a cutout of the image below).

Where should I start? Are the same algorithms used for object recognition suitable for this task?

I am primarily looking for C#/.Net libraries/samples, but also information on implementations and problems/pitfalls.

I am considering using artificual neural networks for training the recognition. Any thoughts?

Example of what the images I want to match may look like:

答:
I think that treating this problem as an image recognition problem is ignoring the underlying structure of the problem.   Specifically you may want to look at how Shazam addresses the problem.  This question on Quora has a couple of interesting links:

http://www.quora.com/How-does-Shazam-work

First, an academic paper describing the algorithm.  You will notice that they also start with a spectrogram, but from there pick a small number of landmarks using an algorithm tailored to the problem.  They then essentially use that as a fingerprint id into a database.

Second, an article on Slate that is understandably at a higher level, but may still be helpful.

Title: Fuzzy match portions of an image


问:
Deploy JHipster app to Heroku cases JHipster Admin menus "AP"I and "Database" to disappear
I can run my JHipster app locally and I have access to the API and Database menus when logged in as Admin. When I deploy to Heroku these menus are not available in my app. I know the database is configured and I can add entities. I am also not able to access the Swagger API definition page.

I am using tokens for authentication and deploying to Heroku with 'jhipster heroku' command.

答: I realize now after understanding more about how jHipster manages databases, that the issue was liquibase did not run, which means the database was not populated with the initial set of users. The solution would be to configure the prod setting to allow liqubase to run.</p>


问:
Using an Alias in PostgreSQL query returns "column does not exist"
I'm trying to get the result of a calculated column in PostgreSQL using aliases from other select queries. I want to divide totalScore by totalEmployee to get the average for the section. But when I try to perform the calculation I get an error.

```<code>SELECT
    cast( sum( empskills.score ) as dec( 2 , 1 ) ) AS totalScore,
    skills.skill_name,
    (SELECT
        count(employees.first_name)
        FROM
        sections
        INNER JOIN employees
        ON sections.id = employees.section_id
        WHERE
        sections.id = 2) as totalEmployees,
    (SELECT totalScore / totalEmployees) as finalResult
FROM
    employees
    INNER JOIN empskills
     ON employees.id = empskills.empid
    INNER JOIN skills
     ON empskills.skillid = skills.id
    INNER JOIN sections
     ON employees.section_id = sections.id
WHERE
    sections.id = 2
GROUP BY
    skills.skill_name
</code>```

```<code>ERROR:  column "totalscore" does not exist
LINE 17:  (SELECT totalScore / totalEmployees)
</code>```

I expected to have the results of the division equation.

答:
According to your SQL above, I think you just want to get the average score for every skill of each employee, I tried to write a more concise SQL as below according to your SQL above:</p>

```<code>select
    s.skill_name,
    sum(k.score) as totalScore,
    count(distinct e.id) as totalEmployees,
    sum(k.score*1.0)/count(distinct e.id) as finalResult
from
    employees e
join
    empskills k on e.id = k.empid
join
    skills s on k.skillid = s.id
where
    e.section_id = 2
group by
    s.skill_name
</code>```

Body:
I'm trying to get the result of a calculated column in PostgreSQL using aliases from other select queries. I want to divide totalScore by totalEmployee to get the average for the section. But when I try to perform the calculation I get an error.

SELECT
    cast( sum( empskills.score ) as dec( 2 , 1 ) ) AS totalScore,
    skills.skill_name,
    (SELECT
        count(employees.first_name)
        FROM
        sections
        INNER JOIN employees
        ON sections.id = employees.section_id
        WHERE
        sections.id = 2) as totalEmployees,
    (SELECT totalScore / totalEmployees) as finalResult
FROM
    employees
    INNER JOIN empskills
     ON employees.id = empskills.empid
    INNER JOIN skills
     ON empskills.skillid = skills.id
    INNER JOIN sections
     ON employees.section_id = sections.id
WHERE
    sections.id = 2
GROUP BY
    skills.skill_name

ERROR:  column "totalscore" does not exist
LINE 17:  (SELECT totalScore / totalEmployees)

I expected to have the results of the division equation.

Body:
According to your SQL above, I think you just want to get the average score for every skill of each employee, I tried to write a more concise SQL as below according to your SQL above:

select
    s.skill_name,
    sum(k.score) as totalScore,
    count(distinct e.id) as totalEmployees,
    sum(k.score*1.0)/count(distinct e.id) as finalResult
from
    employees e
join
    empskills k on e.id = k.empid
join
    skills s on k.skillid = s.id
where
    e.section_id = 2
group by
    s.skill_name


问:
Can I obtain the content rect of a NSTabViewItem witihin its tab bar?
Is there a way to get the content rect of a NSTabViewItem in the bar of a NSTabView?

The view property is just the view to be displayed, when the item is active.

The tabView property gives me the tab view but its frame is the entire area used by the tab view (including the currently displayed content view).

I would like to align a NSPopover exactly below a specific NSTabViewItem but therefor I require the content rect of it.

答:
Not directly. There is no typical API to get the frame of the actual tab control's segments. You can roughly do it if you swap your tab view's switch for an NSSegmentedControl by estimating the frame using the width of each segment, but there's still no explicit way to get the actual frame of a given segment (until the moment that segment is drawn by the NSSegmentedCell).

However, you can get a rect for the segment in a tab view by using the Accessibility APIs. That's a really obtuse way of doing it, but it's possible.

NSTabViewItem doesn't conform to NSAccessibility for some reason, but you can use the older deprecated APIs:

```<code>[tabViewItem accessibilityAttributeValue:NSAccessibilityPositionAttribute];
[tabViewItem accessibilityAttributeValue:NSAccessibilitySizeAttribute];
</code>```

These give you coordinates in screen space, so then you need to convert those to the window (convertRectFromScreen) and the tab view's own frame (convertRect:fromView:). Tedious but doable.

Body:
Not directly. There is no typical API to get the frame of the actual tab control's segments. You can roughly do it if you swap your tab view's switch for an NSSegmentedControl by estimating the frame using the width of each segment, but there's still no explicit way to get the actual frame of a given segment (until the moment that segment is drawn by the NSSegmentedCell).

However, you can get a rect for the segment in a tab view by using the Accessibility APIs. That's a really obtuse way of doing it, but it's possible.

NSTabViewItem doesn't conform to NSAccessibility for some reason, but you can use the older deprecated APIs:

[tabViewItem accessibilityAttributeValue:NSAccessibilityPositionAttribute];
[tabViewItem accessibilityAttributeValue:NSAccessibilitySizeAttribute];

These give you coordinates in screen space, so then you need to convert those to the window (convertRectFromScreen) and the tab view's own frame (convertRect:fromView:). Tedious but doable.


问:
mysql Nodejs connection.query like operator error
I am trying to fetch a bunch of values entered by the user using mysql like operator

In my get route in Nodejs I have

```<code> console.log(req.query.key)
 pool.query("select FirstName from users where FirstName like %'" + req.query.key +"%'"
</code>```

In my debug console I get

dav

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '%'dav%'

I just ran this query in mysql workbench and it is working properly over there

```<code>select FirstName from users where FirstName like '%dav%'
</code>```

MySQL Workbench returns

David

I am not sure why I get the error in Nodejs

Edit 1:

```<code>I am using the `mysql` package
</code>```

app.js

```<code>    const mysql= require('mysql');

    const pool = mysql.createPool({
    connectionLimit : 10,
    host: keys.connection.host,
    user: keys.connection.user,
    password:keys.connection.password,
    database:keys.connection.database,
})
</code>```

I am sure there is not issues with my connection because my other routes are working properly without error

答:
You need to put the quote character before the first %, not after it.

```<code>pool.query("select FirstName from users where FirstName like '%" + req.query.key +"%'"
</code>```

Body:
I am trying to fetch a bunch of values entered by the user using mysql like operator

In my get route in Nodejs I have

 console.log(req.query.key)
 pool.query("select FirstName from users where FirstName like %'" + req.query.key +"%'"

In my debug console I get

dav

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '%'dav%'

I just ran this query in mysql workbench and it is working properly over there

select FirstName from users where FirstName like '%dav%'

MySQL Workbench returns

David

I am not sure why I get the error in Nodejs

Edit 1:

I am using the `mysql` package

app.js

    const mysql= require('mysql');

    const pool = mysql.createPool({
    connectionLimit : 10,
    host: keys.connection.host,
    user: keys.connection.user,
    password:keys.connection.password,
    database:keys.connection.database,
})

I am sure there is not issues with my connection because my other routes are working properly without error

Body:
You need to put the quote character before the first %, not after it.

pool.query("select FirstName from users where FirstName like '%" + req.query.key +"%'"


问:
Java Collections - Effienct search for DateTime ranges
I have a case where I have a table (t1) which contains items like

```<code> | id | timestamp | att1 | att2 |
</code>```

Now I have to iterate over a collection of elements of type att1 and get all records from t1 which are between two certain timestamps for this att1. I have to do this operation several times for a single att1.

So in order to go easy on the database queries, I intended to load every entry from t1 which has a certain att1 attribute once into a collection and perform the subsequent searches on this collection.

Is there a collection that could handle a search like between '2011-02-06 09:00:00' and '2011-02-06 09:00:30'? It's not guaranteed to contain entries for those two timestamps.

Before writing an implementation for that (most likely a very slow implementation ^^) I wanted to ask you guys if there might be some existing collections already or how I could tackle this problem.

Thanks!

答:
The closest I can think of, and this isn't really what I would consider ideal, is to write a comparator that will sort dates so that those within the range count as less than those outside the range (always return -1 when comparing in to out, 0 when comparing in to in or out to out, and always return +1 when comparing out to in.

Then, use this comparator to sort a collection (I suggest an ArrayList). The values within the range will appear first.

You might just be better off writing your own filter, though. Input a collection (I recommend a LinkedList), iterate over it, and remove anything not in the range. Keep a master copy around for spawning new ones to pass into the filter, if you need to.

Body:
I have a case where I have a table (t1) which contains items like

 | id | timestamp | att1 | att2 |

Now I have to iterate over a collection of elements of type att1 and get all records from t1 which are between two certain timestamps for this att1. I have to do this operation several times for a single att1.

So in order to go easy on the database queries, I intended to load every entry from t1 which has a certain att1 attribute once into a collection and perform the subsequent searches on this collection.

Is there a collection that could handle a search like between '2011-02-06 09:00:00' and '2011-02-06 09:00:30'? It's not guaranteed to contain entries for those two timestamps.

Before writing an implementation for that (most likely a very slow implementation ^^) I wanted to ask you guys if there might be some existing collections already or how I could tackle this problem.

Thanks!


问:
conditionally setting style attribute depending on an image's size, fetched through url
My goal is to be able to pass in an image url and decide, depending on its dimensions, whether or not I want to use it. In order to accomplish this, I am using a function I found on stack overflow that is supposed to be able to return dimensions of an image using just the url.

This was the exact code they answered:

```<code>function getMeta(url){
    var img = new Image();
    img.onload = function(){
        alert(this.width + " " + this.height)
    };
    img.src = url;
}
</code>```

For my purposes, I need to be able to evaluate the width and height, so I modified as such, and let me know if I broke some major rule of js:

```<code>function getMeta(url){
    var img = new Image();
    img.onload = function(){
        return [this.width, this.height]
    };
    img.src = url;
}
</code>```

With this function, I am able to call it with another function that I cooked up:

```<code>function backgroundCss(url){
    const dims = getMeta(url);
    return (dims[0] >= 1000 && dims[1] >= 300) ? `url(${url})` : "none"
}
</code>```

and call it in my style attribute:

```<code><Grid item xs={15} md={6} style={{
      backgroundImage: backgroundCss(url)
}}>
</code>```

To my untrained eye, my approach seems pretty reasonable and error-free, but I keep getting this error saying Image() is not defined. (for what it's worth, I tried simply copy pasting the unchanged version of the function and calling it with a button, and it worked fine, alerting me onload with the dimensions)

I got the same error when trying a slightly different approach:

```<code>const [imageText, setImageText] = React.useState(null);
function getMeta(url){
    var img = new Image();
    img.src = url;
    if(imageText == null){
        img.onload = () => setImageText((img.width >= 1000 && img.height >= 300) ? `url(${url})` : "none");
        getMeta(url);
        return false;
    }
    return imageText;
}
...
<Grid item xs={15} md={6} style={{
      backgroundImage: getMeta(url)
}}>
</code>```

Is what I'm trying to do even possible? Where did I go wrong here?

Edit: is this the right direction?

```<code>function getMeta(url){
    return new Promise((resolve) => {
        var img = new Image();
        img.onload = function(){
            resolve([this.width, this.height]);
        };
        img.src = url;
    })
}

function backgroundCss(url) {
    getMeta(url).then((dims) => {
        return (dims[0] >= 1000 && dims[1] >= 300) ? `url(${url})` : "none"
    })
}
</code>```

答:
Problem #1, asynchronous code

Your return statement inside the onload handler isn't doing what you think:

function getMeta(url){
    var img = new Image();
    img.onload = function(){
        return [this.width, this.height]
        // ^^^ this returns for the `onload` handler, not `getMeta`
    };
    img.src = url;
}
```

<p>In order to fix this, you'd need to either use a "callback" or a <code>Promise</code> so you can asynchronously provide the return value once it's available.</p>

<h3>Callback</h3>

<pre class="lang-js prettyprint-override"><code>function getMeta(url, callback){
    var img = new Image();
    img.onload = function(){
        // trigger the provided callback with the return value
        callback([this.width, this.height]);
    };
    img.src = url;
}

// used like so
getMeta('...', (dims) => {
    console.log(dims);
});
</code>```

Promise

function getMeta(url, callback){
    return new Promise((resolve) => {
        var img = new Image();
        img.onload = function(){
            // resolve the promise with the return value
            resolve([this.width, this.height]);
        };
        img.src = url;
    })
}

// used like so
getMeta('...').then((dims) => {
    console.log(dims);
});
```

<h1>Problem #2, react asynchronous rendering</h1>

<p>Since react component render functions are synchronous, I believe you'll need to add some state for this. You could use  another <code>useState</code> hook like the one you already have. Something like:</p>

<pre class="lang-js prettyprint-override"><code>const [imageUrl, setImageUrl] = React.useState(null);

//...

// update the state once it's available
getMeta('...').then((dims) => {
    setImageUrl('...');
});
</code>```

Body:
My goal is to be able to pass in an image url and decide, depending on its dimensions, whether or not I want to use it. In order to accomplish this, I am using a function I found on stack overflow that is supposed to be able to return dimensions of an image using just the url.

This was the exact code they answered:

function getMeta(url){
    var img = new Image();
    img.onload = function(){
        alert(this.width + " " + this.height)
    };
    img.src = url;
}

For my purposes, I need to be able to evaluate the width and height, so I modified as such, and let me know if I broke some major rule of js:

function getMeta(url){
    var img = new Image();
    img.onload = function(){
        return [this.width, this.height]
    };
    img.src = url;
}

With this function, I am able to call it with another function that I cooked up:

function backgroundCss(url){
    const dims = getMeta(url);
    return (dims[0] >= 1000 && dims[1] >= 300) ? `url(${url})` : "none"
}

and call it in my style attribute:

<Grid item xs={15} md={6} style={{
      backgroundImage: backgroundCss(url)
}}>

To my untrained eye, my approach seems pretty reasonable and error-free, but I keep getting this error saying Image() is not defined. (for what it's worth, I tried simply copy pasting the unchanged version of the function and calling it with a button, and it worked fine, alerting me onload with the dimensions)

I got the same error when trying a slightly different approach:

const [imageText, setImageText] = React.useState(null);
function getMeta(url){
    var img = new Image();
    img.src = url;
    if(imageText == null){
        img.onload = () => setImageText((img.width >= 1000 && img.height >= 300) ? `url(${url})` : "none");
        getMeta(url);
        return false;
    }
    return imageText;
}
...
<Grid item xs={15} md={6} style={{
      backgroundImage: getMeta(url)
}}>

Is what I'm trying to do even possible? Where did I go wrong here?

Edit: is this the right direction?

function getMeta(url){
    return new Promise((resolve) => {
        var img = new Image();
        img.onload = function(){
            resolve([this.width, this.height]);
        };
        img.src = url;
    })
}

function backgroundCss(url) {
    getMeta(url).then((dims) => {
        return (dims[0] >= 1000 && dims[1] >= 300) ? `url(${url})` : "none"
    })
}

Body:
Problem #1, asynchronous code

Your return statement inside the onload handler isn't doing what you think:

function getMeta(url){
    var img = new Image();
    img.onload = function(){
        return [this.width, this.height]
        // ^^^ this returns for the `onload` handler, not `getMeta`
    };
    img.src = url;
}

In order to fix this, you'd need to either use a "callback" or a Promise so you can asynchronously provide the return value once it's available.

Callback

function getMeta(url, callback){
    var img = new Image();
    img.onload = function(){
        // trigger the provided callback with the return value
        callback([this.width, this.height]);
    };
    img.src = url;
}

// used like so
getMeta('...', (dims) => {
    console.log(dims);
});

Promise

function getMeta(url, callback){
    return new Promise((resolve) => {
        var img = new Image();
        img.onload = function(){
            // resolve the promise with the return value
            resolve([this.width, this.height]);
        };
        img.src = url;
    })
}

// used like so
getMeta('...').then((dims) => {
    console.log(dims);
});

Problem #2, react asynchronous rendering

Since react component render functions are synchronous, I believe you'll need to add some state for this. You could use  another useState hook like the one you already have. Something like:

const [imageUrl, setImageUrl] = React.useState(null);

//...

// update the state once it's available
getMeta('...').then((dims) => {
    setImageUrl('...');
});


问:
Why is my event handler not allowing me to access event.target?
I'm setting up an inventory management system in a new Corona game. I'm testing the initial setup by creating a sample displayObject in a scene and then changing the visibility of that object on tap. The simulator throws me an error when I try, it says "Attempt to index local 'event' (a nil value)."

I tried changing the listener from a function listener to a table listener, but the same error persists. I've read the relevant Corona documentation as well as all of the Corona-related results I could find on the site, but none of the solutions seemed to apply to my particular situation (my setup already appears to be in line with what the other solutions suggest).

The game has several files, but the relevant parts here are:

inventory.lua

local composer = require( "composer" )

local I = {}

--Identifies what to do when an object is clicked
function I:clickRouter( event )
  event.target.isVisible = false --this is the line that prompts the error
return true
end

return I
```

<p>sceneOne.lua</p>

<pre class="lang-lua prettyprint-override"><code>local composer = require( "composer" )
local inventoryManager = require( "inventory" )

local scene = composer.newScene()

function scene:create( event )

    local sceneGroup = self.view

        local obj = display.newImageRect(sceneGroup, "images.xcassets/scObj.png", 32, 32)
        obj.num = 1
        obj:addEventListener("tap", inventoryManager.clickRouter)

end

--...other irrelevant code omitted here
</code>```

I expect, on tap, for the image to disappear. Instead, it throws the aforementioned error message. I think the error may have to do with how the files are interacting with each other, but I can't figure out what it is.

答:
Okay, figured this out:

As per this answer and this conversation, I'd been declaring the clickRouter function as a method instead of a regular function, so there was an implicit "self" parameter that was causing what I'd attempted to call the "event" to instead just be null.

Changing the function from:

```<code>function I:clickRouter(event)
</code>```

to

```<code>function I.clickRouter(event)
</code>```

resolved my issue.

Body:
I'm setting up an inventory management system in a new Corona game. I'm testing the initial setup by creating a sample displayObject in a scene and then changing the visibility of that object on tap. The simulator throws me an error when I try, it says "Attempt to index local 'event' (a nil value)."

I tried changing the listener from a function listener to a table listener, but the same error persists. I've read the relevant Corona documentation as well as all of the Corona-related results I could find on the site, but none of the solutions seemed to apply to my particular situation (my setup already appears to be in line with what the other solutions suggest).

The game has several files, but the relevant parts here are:

inventory.lua

local composer = require( "composer" )

local I = {}

--Identifies what to do when an object is clicked
function I:clickRouter( event )
  event.target.isVisible = false --this is the line that prompts the error
return true
end

return I

sceneOne.lua

local composer = require( "composer" )
local inventoryManager = require( "inventory" )

local scene = composer.newScene()

function scene:create( event )

    local sceneGroup = self.view

        local obj = display.newImageRect(sceneGroup, "images.xcassets/scObj.png", 32, 32)
        obj.num = 1
        obj:addEventListener("tap", inventoryManager.clickRouter)

end

--...other irrelevant code omitted here

I expect, on tap, for the image to disappear. Instead, it throws the aforementioned error message. I think the error may have to do with how the files are interacting with each other, but I can't figure out what it is.

Body:
Okay, figured this out:

As per this answer and this conversation, I'd been declaring the clickRouter function as a method instead of a regular function, so there was an implicit "self" parameter that was causing what I'd attempted to call the "event" to instead just be null.

Changing the function from:

function I:clickRouter(event)

to

function I.clickRouter(event)

resolved my issue.


问:
Heroku send error time out and multiply files at the moment of deploy
I had to replicate a site that was very outdated, is created by Themosis. What I want is to deploy it in Heroku, the file compilation process happens successfully but at the moment of entering the site the logs are of an error when not finding the .env file, after creating it through SSH the error it throws is that there are repeated parameters. Not finding the .env file throws a time out error, I know it's a configuration problem but the truth is that my knowledge does not go beyond what I've done.

答: .ENV file is not uploaded. You can change it in the Configurations tab, I guess in Heroku it's in the last tab. Edit the configuration variables or environment variables there one by one.</p>


问:
SugarCRM Javascript/JQuery phone mask not fully working like I want it to work
The mask works perfectly I got it working to the point that it will remove everything except the country code from the front of the number when I copy and paste it. So my problem now is that when I copy and paste like for example a number like this +1(999)999-9999 the output is coming out like 199-999-999 and I need it to come out like 999-999-9999. Don't know what exactly I'm missing if anyone can help me with this it would be great.

Tried everything I could think of.

```<code>_render: function() {
    this._super('_render');

    var SPMaskBehavior = function (val) {
        return '000-000-00009';
    },
    spOptions = {
        onKeyPress: function(val, e, field, options) {
            var value = e.target.value;
            if(value.length > 11) {

                if(value[0] == '1' || value[0] == 1) {
                    var res=value.slice(1, 13);
                    $('.republic_phone').val(res);
                }
                else {
                    var res =value.slice(0, 12);
                    $('.republic_phone').val(res);
                }
            }
            field.mask(SPMaskBehavior.apply({}, arguments), options);
            }
    };

    $('.republic_phone').mask(SPMaskBehavior, spOptions);
},
</code>```

I expect when I copy and paste any phone number like +1(999)999-9999 or even +1999999999 well really anything that looks like a phone I want to display it as 999-999-9999 Thank you in advance.

答:
999-999-9999 is 12 characters long, not 11.

Therefore I believe your entire code is off-by-one.

```<code>        if(value.length > 12) {

            if(value[0] == '1' || value[0] == 1) {
                var res=value.slice(1, 14);
                $('.republic_phone').val(res);
            }
            else {
                var res =value.slice(0, 13);
                $('.republic_phone').val(res);
            }
        }
</code>```

Also it's weird you're using $('.republic_phone'). in there to address the field.
 Shouldn't field. be the correct way to address the very field the function gets triggered for?

Body:
The mask works perfectly I got it working to the point that it will remove everything except the country code from the front of the number when I copy and paste it. So my problem now is that when I copy and paste like for example a number like this +1(999)999-9999 the output is coming out like 199-999-999 and I need it to come out like 999-999-9999. Don't know what exactly I'm missing if anyone can help me with this it would be great.

Tried everything I could think of.

_render: function() {
    this._super('_render');

    var SPMaskBehavior = function (val) {
        return '000-000-00009';
    },
    spOptions = {
        onKeyPress: function(val, e, field, options) {
            var value = e.target.value;
            if(value.length > 11) {

                if(value[0] == '1' || value[0] == 1) {
                    var res=value.slice(1, 13);
                    $('.republic_phone').val(res);
                }
                else {
                    var res =value.slice(0, 12);
                    $('.republic_phone').val(res);
                }
            }
            field.mask(SPMaskBehavior.apply({}, arguments), options);
            }
    };

    $('.republic_phone').mask(SPMaskBehavior, spOptions);
},

I expect when I copy and paste any phone number like +1(999)999-9999 or even +1999999999 well really anything that looks like a phone I want to display it as 999-999-9999 Thank you in advance.

Body:
999-999-9999 is 12 characters long, not 11.

Therefore I believe your entire code is off-by-one.

        if(value.length > 12) {

            if(value[0] == '1' || value[0] == 1) {
                var res=value.slice(1, 14);
                $('.republic_phone').val(res);
            }
            else {
                var res =value.slice(0, 13);
                $('.republic_phone').val(res);
            }
        }

Also it's weird you're using $('.republic_phone'). in there to address the field.
 Shouldn't field. be the correct way to address the very field the function gets triggered for?


问:
Turn a table row in a css grid layout independent from other rows
I've to rearrange a table like this one using only CSS.

        H1
 H2
 H3
        H4
 H5
 H6
 H7
 H8
 H9
 H10

 A1
        A2
 A3
 A4
 A5
 A6
 A7
 A8
 A9
 A10

 B1
 B2
 B3
 B4
        B5
 B6
 B7
 B8
 B9
 B10

```

How can I get a layout like this?
My initial idea would have been using CSS flexbox but I didn't know how to rearrange the row into this layout, especially the A2 to A7 part in which there are two columns.

So as suggested by comments to original post, I would opt for a CSS grid layout.

答:
This is not possible with tables even if you rearrange the rows because col-A9 and col-A10 occupy 2.5 columns each. And with flexbox you would find difficulty spanning the rows (eg col-A2) and can be solved only if you nest more containers.

But with css grids this is actually easy - you can use a 20-column layout here. See demo with explanations inline:

.wrapper {
  display: grid; /* establish a grid container */
  grid-template-columns: repeat(20, 1fr); /* 20 columns */
  grid-auto-rows: 50px; /* row height for illustration */
}

.wrapper div {
  border: 1px solid;
  grid-column: span 2; /* span two columns */
  /* flexbox to center content*/
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .a {
  grid-column: span 10;  /* span ten columns */
}

.wrapper .a1 {
  grid-column: span 20; /* span all 20 columns */
}

.wrapper .a2 {
  grid-row: span 5; /* span five rows */
}

.wrapper .a9,.wrapper .a10{
  grid-column: span 5; /* span five columns */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="h">H1</div>
  <div class="h">H2</div>
  <div class="h">H3</div>
  <div class="h">H4</div>
  <div class="h">H5</div>
  <div class="h">H6</div>
  <div class="h">H7</div>
  <div class="h">H8</div>
  <div class="h">H9</div>
  <div class="h">H10</div>

  <div class="a a1">A1</div>
  <div class="a a2">A2</div>
  <div class="a a3">A3</div>
  <div class="a a4">A4</div>
  <div class="a a5">A5</div>
  <div class="a a6">A6</div>
  <div class="a a7">A7</div>
  <div class="a a8">A8</div>
  <div class="a a9">A9</div>
  <div class="a a10">A10</div>

  <div class="b">B1</div>
  <div class="b">B2</div>
  <div class="b">B3</div>
  <div class="b">B4</div>
  <div class="b">B5</div>
  <div class="b">B6</div>
  <div class="b">B7</div>
  <div class="b">B8</div>
  <div class="b">B9</div>
  <div class="b">B10</div>

</div></code>```

Body:
I've to rearrange a table like this one using only CSS.

        H1
 H2
 H3
        H4
 H5
 H6
 H7
 H8
 H9
 H10

 A1
        A2
 A3
 A4
 A5
 A6
 A7
 A8
 A9
 A10

 B1
 B2
 B3
 B4
        B5
 B6
 B7
 B8
 B9
 B10

How can I get a layout like this?
My initial idea would have been using CSS flexbox but I didn't know how to rearrange the row into this layout, especially the A2 to A7 part in which there are two columns.

So as suggested by comments to original post, I would opt for a CSS grid layout.

Body:
This is not possible with tables even if you rearrange the rows because col-A9 and col-A10 occupy 2.5 columns each. And with flexbox you would find difficulty spanning the rows (eg col-A2) and can be solved only if you nest more containers.

But with css grids this is actually easy - you can use a 20-column layout here. See demo with explanations inline:

.wrapper {
  display: grid; /* establish a grid container */
  grid-template-columns: repeat(20, 1fr); /* 20 columns */
  grid-auto-rows: 50px; /* row height for illustration */
}

.wrapper div {
  border: 1px solid;
  grid-column: span 2; /* span two columns */
  /* flexbox to center content*/
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .a {
  grid-column: span 10;  /* span ten columns */
}

.wrapper .a1 {
  grid-column: span 20; /* span all 20 columns */
}

.wrapper .a2 {
  grid-row: span 5; /* span five rows */
}

.wrapper .a9,.wrapper .a10{
  grid-column: span 5; /* span five columns */
}

<div class="wrapper">
  <div class="h">H1</div>
  <div class="h">H2</div>
  <div class="h">H3</div>
  <div class="h">H4</div>
  <div class="h">H5</div>
  <div class="h">H6</div>
  <div class="h">H7</div>
  <div class="h">H8</div>
  <div class="h">H9</div>
  <div class="h">H10</div>

  <div class="a a1">A1</div>
  <div class="a a2">A2</div>
  <div class="a a3">A3</div>
  <div class="a a4">A4</div>
  <div class="a a5">A5</div>
  <div class="a a6">A6</div>
  <div class="a a7">A7</div>
  <div class="a a8">A8</div>
  <div class="a a9">A9</div>
  <div class="a a10">A10</div>

  <div class="b">B1</div>
  <div class="b">B2</div>
  <div class="b">B3</div>
  <div class="b">B4</div>
  <div class="b">B5</div>
  <div class="b">B6</div>
  <div class="b">B7</div>
  <div class="b">B8</div>
  <div class="b">B9</div>
  <div class="b">B10</div>

</div>


问:
How to determine if a nested list structure is the same as another, but with elements exchanged for new ones
Let's say we have two nested lists: L1 = [[0, 1], [0, 2]] and L2 = [[1, 2], [1, 3]]

The question is, does there exist a bijection between the integers in one list and the integers in the other list which transforms L1 into L2?  For L1 and L2 given above, the answer is yes.

BIJECTION:

old 0 becomes new 1

old 1 becomes new 2

old 2becomes new 3

Recall our nested list L1 = [[0, 1], [0, 2]]. If we apply the mapping described above, then we get L2 = [[1, 2], [1, 3]] Therefore, foo(L1, L2) should return True. foo is the name of the equality operator we are trying to implement.

Also, order does not matter. Each list should be treated as a mathematical "set."

Some examples are shown below:

Left list: [[2, 1], [3, 1]]

Right list: [[1, 2], [1, 3]] : True
foo(left,right) returns True

why?

order doesn't matter

Left list: [[2, 1], [3, 1]]

Right list: [[1, 2], [3, 4]]

foo(left,right) returns False

why?

Two integers inside of the left list are the same, but all integers inside of the right list are different from each-other.

left= [[2, 1], [3, 1]]

right = [[0, 1], [0, 1]]

foo(left, right) returns False

why?

the right list contains only 2 distinct integers (0 and 1). The left list contains 3 distinct integers (1, 2, 3)

Some longer examples are shown below:

Original list: [[0, 1], [0, 2], [1, 2], [1, 3], [0, 1, 2]]

A1: [[4, 1], [4, 0], [1, 0], [1, 3], [4, 1, 0]] : True

A2: [[4, 1], [4, 0], [1, 3], [1, 0], [4, 0, 1]] : True

B: [[1, 2], [3, 1], [2, 4], [1, 4], [2, 4, 1]] : True

C: [[3, 2], [5, 2], [5, 0], [0, 2], [5, 0, 2]] : True

D: [[5, 2], [5, 2], [3, 0], [0, 2], [5, 0, 2]] : False

E: [[3, 0], [0, 3], [5, 0], [0, 2], [5, 0, 2]] : False

Bijection for Example A1:

```<code>ORIGINAL  A
 0        4
 1        1
 2        0
 3        3
</code>```

A2 is simply a reordering of A1

In example B, 2 and 4 are playing the same role as 0 and 2 in the original list. 1 is in the same role in both lists, as is 3.

In example C, 0 and 5 are playing the same role as 0 and 2 in the original list, 2 is playing the same role as 1 in the original list, and 3 is playing the same role in both lists.
In example D, there are two sub-lists which are the same ([5, 2]), while the original list has no repeating sub-lists.
In example E, 0 is in all four length-2 sub-lists, while in the original list, no number is in all four length-2 sub-lists.

Here is the code I have from my attempt, however it does not work when a low number (like 0) is exchanged for one of the largest numbers in the lists (like say 4). When it does the sorting, it fails to recognize that the 4 is playing the same role as the 0. Since low numbers can be exchanged for high numbers, sorting will not work.

def CheckUnique(configs, newconfig):
    sortednewconfig = sorted([sorted(i) for i in newconfig])
    presentnumbers = []
    canonicalnewconfig = []
    for sub in sortednewconfig:
        for i in sub:
            if i not in presentnumbers:
                presentnumbers.append(i)
    for sub in sortednewconfig:
        cansub = []
        for i in sub:
            cansub.append(presentnumbers.index(i))
        canonicalnewconfig.append(cansub)
    if canonicalnewconfig not in configs:
        return True
    else:
        return False

```

Body:
Let's say we have two nested lists: L1 = [[0, 1], [0, 2]] and L2 = [[1, 2], [1, 3]]

The question is, does there exist a bijection between the integers in one list and the integers in the other list which transforms L1 into L2?  For L1 and L2 given above, the answer is yes.

BIJECTION:

old 0 becomes new 1

old 1 becomes new 2

old 2becomes new 3

Recall our nested list L1 = [[0, 1], [0, 2]]. If we apply the mapping described above, then we get L2 = [[1, 2], [1, 3]] Therefore, foo(L1, L2) should return True. foo is the name of the equality operator we are trying to implement.

Also, order does not matter. Each list should be treated as a mathematical "set."

Some examples are shown below:

Left list: [[2, 1], [3, 1]]

Right list: [[1, 2], [1, 3]] : True
foo(left,right) returns True

why?

order doesn't matter

Left list: [[2, 1], [3, 1]]

Right list: [[1, 2], [3, 4]]

foo(left,right) returns False

why?

Two integers inside of the left list are the same, but all integers inside of the right list are different from each-other.

left= [[2, 1], [3, 1]]

right = [[0, 1], [0, 1]]

foo(left, right) returns False

why?

the right list contains only 2 distinct integers (0 and 1). The left list contains 3 distinct integers (1, 2, 3)

Some longer examples are shown below:

Original list: [[0, 1], [0, 2], [1, 2], [1, 3], [0, 1, 2]]

A1: [[4, 1], [4, 0], [1, 0], [1, 3], [4, 1, 0]] : True

A2: [[4, 1], [4, 0], [1, 3], [1, 0], [4, 0, 1]] : True

B: [[1, 2], [3, 1], [2, 4], [1, 4], [2, 4, 1]] : True

C: [[3, 2], [5, 2], [5, 0], [0, 2], [5, 0, 2]] : True

D: [[5, 2], [5, 2], [3, 0], [0, 2], [5, 0, 2]] : False

E: [[3, 0], [0, 3], [5, 0], [0, 2], [5, 0, 2]] : False

Bijection for Example A1:

ORIGINAL  A
 0        4
 1        1
 2        0
 3        3

A2 is simply a reordering of A1

In example B, 2 and 4 are playing the same role as 0 and 2 in the original list. 1 is in the same role in both lists, as is 3.

In example C, 0 and 5 are playing the same role as 0 and 2 in the original list, 2 is playing the same role as 1 in the original list, and 3 is playing the same role in both lists.
In example D, there are two sub-lists which are the same ([5, 2]), while the original list has no repeating sub-lists.
In example E, 0 is in all four length-2 sub-lists, while in the original list, no number is in all four length-2 sub-lists.

Here is the code I have from my attempt, however it does not work when a low number (like 0) is exchanged for one of the largest numbers in the lists (like say 4). When it does the sorting, it fails to recognize that the 4 is playing the same role as the 0. Since low numbers can be exchanged for high numbers, sorting will not work.

def CheckUnique(configs, newconfig):
    sortednewconfig = sorted([sorted(i) for i in newconfig])
    presentnumbers = []
    canonicalnewconfig = []
    for sub in sortednewconfig:
        for i in sub:
            if i not in presentnumbers:
                presentnumbers.append(i)
    for sub in sortednewconfig:
        cansub = []
        for i in sub:
            cansub.append(presentnumbers.index(i))
        canonicalnewconfig.append(cansub)
    if canonicalnewconfig not in configs:
        return True
    else:
        return False

Body:
Use a all and any with a zip with it:

>>> l = [[0, 1], [0, 2], [1, 2], [1, 3], [0, 1, 2]]
>>> l2 = [[4, 1], [4, 0], [1, 3], [1, 0], [4, 0, 1]]
>>> all([any(i in x for i in y) for x, y in zip(l, l2)])
True
>>> l3 = [[5, 2], [5, 2], [3, 0], [0, 2], [5, 0, 2]]
>>> all([any(i in x for i in y) for x, y in zip(l, l3)])
False
>>>


问:
android data binding: how to get useful error messages
In android studio 2.1, the compile time error messages from xml mistakes are entirely non-helpful:

```<code>Error:(11, 41) error: package mypackage.databinding does not exist
Error:(15, 13) error: cannot find symbol class MyActivityBinding
</code>```

The real error would usually be something like "there's no such attribute android:adapter", or "variable foo doesn't contain property bar" or something like that. But instead of actually showing such errors, it shows the above unhelpful ones, which only tell you that the bindings weren't generated because of some unknown error.

答: Clink on Toogle View, under the 'Build' icon will give you details logs

Body:
In android studio 2.1, the compile time error messages from xml mistakes are entirely non-helpful:

Error:(11, 41) error: package mypackage.databinding does not exist
Error:(15, 13) error: cannot find symbol class MyActivityBinding

The real error would usually be something like "there's no such attribute android:adapter", or "variable foo doesn't contain property bar" or something like that. But instead of actually showing such errors, it shows the above unhelpful ones, which only tell you that the bindings weren't generated because of some unknown error.


问:
How to print HTML geolocation?
I'm using HTML5 Geolocation and wants to print the returned user location in the input field.

Is this possible? If so how?

    var x = document.getElementById("demo");

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }

    function showPosition(position) {
      x.innerHTML = "Latitude: " + position.coords.latitude +
      "
Longitude: " + position.coords.longitude;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text">
<button onclick="getLocation()">Try It</button>
<p id="demo"></p></code>```

答:
```<code>I have edited the answer. the problem in your code was that the variable x was coming null since you were trying to do getElemntById for the p tag not defined in the code yet.so I have put the HTML part above the javascript code.

 <input type="text">
    <button onclick="getLocation()">Try It</button>
    <p id="demo"></p>
    <script>
    var x = document.getElementById("demo");
    console.log(x);
       function getLocation() {
         if (navigator.geolocation) {
           navigator.geolocation.getCurrentPosition(showPosition);
         } else {
           x.innerHTML = "Geolocation is not supported by this browser.";
         }
       }

       function showPosition(position) {
         x.innerHTML = "Latitude: " + position.coords.latitude +
         "<br>Longitude: " + position.coords.longitude;
       }
       </script>
</code>```

Title: How to print HTML geolocation?

Body:
I'm using HTML5 Geolocation and wants to print the returned user location in the input field.

Is this possible? If so how?

    var x = document.getElementById("demo");

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }

    function showPosition(position) {
      x.innerHTML = "Latitude: " + position.coords.latitude +
      "
Longitude: " + position.coords.longitude;
    }

<input type="text">
<button onclick="getLocation()">Try It</button>


问:
I'm trying to make a GET request to a public API, however, I get No 'Access-Control-Allow-Origin' header is present on the requested resource
I've literally just created a new project and made a single route:

```<code>Route::get('/getSummoner', 'RiotController@getSummoner');
</code>```

That executes this function:

```<code>public function getSummoner(){

$get = file_get_contents("https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/RiotSchmick?api_key=");
$result = json_decode($get);

return response()->json([
    'result' => $result,
], 201);

}
</code>```

and on the front-end, I get the following error:

```<code>Access to XMLHttpRequest at 'url' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I understand this happens when the I make a request to a different domain than what my page is on but since the API is not mine, I can't really make a request from the same domain, can I?

答:
CORS is disabled by default in any sites for security purposes. You need to install barryvdh/laravel-cors to allow CORS.

```<code>composer require barryvdh/laravel-cors
</code>```

once installed you need to run this in terminal/command prompt

```<code>php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
</code>```

then add the HandleCors in your middleware groups, in your case add it in api middleware

```<code>    protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        // ...
        \Barryvdh\Cors\HandleCors::class,
    ],
];
</code>```

Body:
I've literally just created a new project and made a single route:

Route::get('/getSummoner', 'RiotController@getSummoner');

That executes this function:

public function getSummoner(){

$get = file_get_contents("https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/RiotSchmick?api_key=");
$result = json_decode($get);

return response()->json([
    'result' => $result,
], 201);

}

and on the front-end, I get the following error:

Access to XMLHttpRequest at 'url' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I understand this happens when the I make a request to a different domain than what my page is on but since the API is not mine, I can't really make a request from the same domain, can I?

Body:
CORS is disabled by default in any sites for security purposes. You need to install barryvdh/laravel-cors to allow CORS.

composer require barryvdh/laravel-cors

once installed you need to run this in terminal/command prompt

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

then add the HandleCors in your middleware groups, in your case add it in api middleware

    protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        // ...
        \Barryvdh\Cors\HandleCors::class,
    ],
];


问:
Cypher Traverse tree in single query
Assume you have following layout.  A root node known as a "group" that can be found by the following:

```<code>MATCH (g: Group {key: $groupKey}) RETURN g;
</code>```

And a series of Messages owned by the group:

```<code>MATCH (g: Group {key: $groupKey})-[r: Owns]->(m: Message) RETURN m;
</code>```

And each message can have many replies also represented as messages

```<code>MATCH (m: Message {key: $messageKey})-[r: Owns]->(reply: Message) RETURN reply;
</code>```

The question is how in a single query do you traverse from g to retrieve the graph of all messages and their replies.  Assume no circular paths exist.

答:
This query will return every Message in the tree rooted at g.

```<code>MATCH (g:Group {key: $groupKey})-[:Owns*]->(m:Message)
RETURN g, COLLECT(DISTINCT m) AS messages;
</code>```

Title: Cypher Traverse tree in single query

Body:
Assume you have following layout.  A root node known as a "group" that can be found by the following:

MATCH (g: Group {key: $groupKey}) RETURN g;

And a series of Messages owned by the group:

MATCH (g: Group {key: $groupKey})-[r: Owns]->(m: Message) RETURN m;

And each message can have many replies also represented as messages

MATCH (m: Message {key: $messageKey})-[r: Owns]->(reply: Message) RETURN reply;

The question is how in a single query do you traverse from g to retrieve the graph of all messages and their replies.  Assume no circular paths exist.

Body:
This query will return every Message in the tree rooted at g.

MATCH (g:Group {key: $groupKey})-[:Owns*]->(m:Message)
RETURN g, COLLECT(DISTINCT m) AS messages;