问:
T-SQL Get percentage of characters matching between 2 columns
Trying to find the percentage of characters that are matching between 2 columns.

Table A

```<code>ID  Name
1   RICK
2   PATRICK
3   MARK.HI
</code>```

Table B

```<code>ID  Name
1   RICK
2   PATRCIK
3   MARK-HI
</code>```

when i join both the tables (A and B), If column 'Name' matches
('RICK' in Table A = 'RICK' in Table B), then a new column called percentage should show as 100%.

If the column 'Name' does not match when I join both the tables
 ('PATRICK' in Table A <> 'PATRCIK' in Table B) it should show approximately by what percentage the column is not matching.

I am trying to figure out the messy data.

答:
The question isn't overly clear, however I've made the assumption that a match is where the names are in both tables and there can be names in either table that are not in the other:

DDL

```<code>CREATE TABLE MyTab1
(
    MyVAL NVARCHAR(20)
);

INSERT INTO MyTab1 VALUES ('Rick'),('Patrick'),('John'),('Jhon');

CREATE TABLE MyTab2
(
    MyVAL NVARCHAR(20)
);

INSERT INTO MyTab2 VALUES ('Rick'),('Patrikc'),('Fred');
</code>```

Query

```<code>DECLARE @TotalRecords DECIMAL= (
                                   SELECT COUNT(*)
                                   FROM (
                                           SELECT b.MyVal AS Val1,
                                                  a.MyVAL AS Val2
                                           FROM   MyTab1 a
                                                  FULL JOIN Mytab2 b
                                                      ON a.MyVal = b.MyVal
                                         ) a
                                 );

DECLARE @Matches DECIMAL  = (
                                 SELECT COUNT(*)
                                 FROM (
                                           SELECT b.MyVal AS Val1,
                                                  a.MyVAL AS Val2
                                           FROM   MyTab1 a
                                                  FULL JOIN Mytab2 b
                                                      ON a.MyVal = b.MyVal
                                      ) a
                                 WHERE Val1 IS NOT NULL AND Val2 IS NOT NULL
                            );

SELECT (@Matches / @TotalRecords) * 100
</code>```

In this example, the value returned is 16.6% as there are 6 unique values across the two tables of which 1 is common across the two - (1 / 6) * 100 = 16.6

Body:
Trying to find the percentage of characters that are matching between 2 columns.

Table A

ID  Name
1   RICK
2   PATRICK
3   MARK.HI

Table B

ID  Name
1   RICK
2   PATRCIK
3   MARK-HI

when i join both the tables (A and B), If column 'Name' matches
('RICK' in Table A = 'RICK' in Table B), then a new column called percentage should show as 100%.

If the column 'Name' does not match when I join both the tables
 ('PATRICK' in Table A <> 'PATRCIK' in Table B) it should show approximately by what percentage the column is not matching.

I am trying to figure out the messy data.

Body:
The question isn't overly clear, however I've made the assumption that a match is where the names are in both tables and there can be names in either table that are not in the other:

DDL

CREATE TABLE MyTab1
(
    MyVAL NVARCHAR(20)
);

INSERT INTO MyTab1 VALUES ('Rick'),('Patrick'),('John'),('Jhon');

CREATE TABLE MyTab2
(
    MyVAL NVARCHAR(20)
);

INSERT INTO MyTab2 VALUES ('Rick'),('Patrikc'),('Fred');

Query

DECLARE @TotalRecords DECIMAL= (
                                   SELECT COUNT(*)
                                   FROM (
                                           SELECT b.MyVal AS Val1,
                                                  a.MyVAL AS Val2
                                           FROM   MyTab1 a
                                                  FULL JOIN Mytab2 b
                                                      ON a.MyVal = b.MyVal
                                         ) a
                                 );

DECLARE @Matches DECIMAL  = (
                                 SELECT COUNT(*)
                                 FROM (
                                           SELECT b.MyVal AS Val1,
                                                  a.MyVAL AS Val2
                                           FROM   MyTab1 a
                                                  FULL JOIN Mytab2 b
                                                      ON a.MyVal = b.MyVal
                                      ) a
                                 WHERE Val1 IS NOT NULL AND Val2 IS NOT NULL
                            );

SELECT (@Matches / @TotalRecords) * 100

In this example, the value returned is 16.6% as there are 6 unique values across the two tables of which 1 is common across the two - (1 / 6) * 100 = 16.6


来源: stackexchange

问:
Change namespace in XSLT with unknown prefix
I would like to change namespace in XML file with XSLT based only on namespace-uri without knowing what prefix this namespace has defined. Is it possible?

I get some solution but they work only with small files when I know the input and can setup xsl file kinda manualy.

What I would like to achieve:

INPUT XML:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <re:rootElement xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:re="http://something.com/root"
xmlns:ns1="http://something.com/some/schema"
xmlns:cs2="http://something.com/another/schema"
xmlns:ns3="http://something.com/different/schema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:import namespace="http://something.com/another/schema" schemaLocation="/schema/location"/>
</code>```

(multiple nodes below)

XSLT that takes 2 parameters:

```<code><xsl:param name="old_namespace" select="'http://something.com/another/schema'"/>
<xsl:param name="new_namespace" select="'http://something.com/another/schemaNEW'"/>
</code>```

And output as xml:

```<code>    <re:rootElement xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:re="http://something.com/root"
xmlns:ns1="http://something.com/some/schema"
xmlns:cs2="http://something.com/another/schemaNEW"
xmlns:ns3="http://something.com/different/schema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
 <xsd:import namespace="http://something.com/another/schemaNEW" schemaLocation="/schema/location"/>
(multiple nodes below)
</code>```

答:
It's not difficult to change the namespace URI used in namespace nodes and in the names of elements and attributes. In a schema-aware stylesheet, it's also possible (but perhaps harder) to change the namespace URI used in values of type QName. It's rather harder, I suspect, to change namespace URIs that appear:

directly in attributes such as xsi:schemaLocation or xs:import (unless you enumerate such attributes)

in the names of NOTATIONs

in content with a micro-syntax, e.g. consider

<xsl:if test="namespace-uri() = 'http://old-namespace.com/'>

If it's just namespaces used in element and attributes that you're after, then you can use

```<code><xsl:template match="*[namespace-uri()=$old-namespace]">
  <xsl:element name="{name()}" namespace="{$new-namespace}">
    <xsl:apply-templates select="@*, node()"/>
  </xsl:element>
</xsl:template>

<xsl:template match="@*[namespace-uri()='$old-namespace']">
  <xsl:attribute name="{name()}" namespace="{$new-namespace}" select="."/>
</xsl:template>
</code>```

along with the identity template (or in 3.0, <xsl:mode on-no-match="shallow-copy"/>) to make sure that other elements and attributes are copied unchanged.

(This is XSLT 2.0 but could easily be rewritten in 1.0).

ContentLicense: CC BY-SA 4.0

Body:
I would like to change namespace in XML file with XSLT based only on namespace-uri without knowing what prefix this namespace has defined. Is it possible?

I get some solution but they work only with small files when I know the input and can setup xsl file kinda manualy.

What I would like to achieve:

INPUT XML:

    <?xml version="1.0" encoding="UTF-8"?>
    <re:rootElement xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:re="http://something.com/root"
xmlns:ns1="http://something.com/some/schema"
xmlns:cs2="http://something.com/another/schema"
xmlns:ns3="http://something.com/different/schema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:import namespace="http://something.com/another/schema" schemaLocation="/schema/location"/>

(multiple nodes below)

XSLT that takes 2 parameters:

<xsl:param name="old_namespace" select="'http://something.com/another/schema'"/>
<xsl:param name="new_namespace" select="'http://something.com/another/schemaNEW'"/>

And output as xml:

    <re:rootElement xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:re="http://something.com/root"
xmlns:ns1="http://something.com/some/schema"
xmlns:cs2="http://something.com/another/schemaNEW"
xmlns:ns3="http://something.com/different/schema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
 <xsd:import namespace="http://something.com/another/schemaNEW" schemaLocation="/schema/location"/>
(multiple nodes below)

Body:
It's not difficult to change the namespace URI used in namespace nodes and in the names of elements and attributes. In a schema-aware stylesheet, it's also possible (but perhaps harder) to change the namespace URI used in values of type QName. It's rather harder, I suspect, to change namespace URIs that appear:

directly in attributes such as xsi:schemaLocation or xs:import (unless you enumerate such attributes)

in the names of NOTATIONs

in content with a micro-syntax, e.g. consider

<xsl:if test="namespace-uri() = 'http://old-namespace.com/'>

If it's just namespaces used in element and attributes that you're after, then you can use

<xsl:template match="*[namespace-uri()=$old-namespace]">
  <xsl:element name="{name()}" namespace="{$new-namespace}">
    <xsl:apply-templates select="@*, node()"/>
  </xsl:element>
</xsl:template>

<xsl:template match="@*[namespace-uri()='$old-namespace']">
  <xsl:attribute name="{name()}" namespace="{$new-namespace}" select="."/>
</xsl:template>

along with the identity template (or in 3.0, <xsl:mode on-no-match="shallow-copy"/>) to make sure that other elements and attributes are copied unchanged.

(This is XSLT 2.0 but could easily be rewritten in 1.0).


问:
Why these variables not getting recognized?
I have a class called as movie Catalog and trying to return the list of this class from another class however the variables, name, desc and rating is not getting recognized.

@RestController
   @RequestMapping("/catalog")
   public class MovieCatalogResource {

```<code>@RequestMapping("/{userId}")
public List<CatalogItem> getCatalog(@PathVariable("userId") String
userId){

return Collections.singletonList(
            new CatalogItem(name: "Transformer", desc:"Test", rating:4)
            );
  }
}
</code>```

Following is an error.

Multiple markers at this line
    - Syntax error on token ":", invalid
     AssignmentOperator
    - desc cannot be resolved to a variable

I have got all the packages correctly imported and they have the references

I am looking for the code compilation however because these variables are not getting recognized it is failing.

答:
It looks like you're trying to use named parameters, which Java does not support.

If the constructor for CatalogItem looks like this: CatalogItem(String name, String desc, int rating) you call it like this: new CatalogItem("Transformer", "Test", 4);

Body:
I have a class called as movie Catalog and trying to return the list of this class from another class however the variables, name, desc and rating is not getting recognized.

@RestController
   @RequestMapping("/catalog")
   public class MovieCatalogResource {

@RequestMapping("/{userId}")
public List<CatalogItem> getCatalog(@PathVariable("userId") String
userId){

return Collections.singletonList(
            new CatalogItem(name: "Transformer", desc:"Test", rating:4)
            );
  }
}

Following is an error.

Multiple markers at this line
    - Syntax error on token ":", invalid
     AssignmentOperator
    - desc cannot be resolved to a variable

I have got all the packages correctly imported and they have the references

I am looking for the code compilation however because these variables are not getting recognized it is failing.


问:
Regex for picking a Value After “=”
How i can select RQR-1BN6Q360090-0001 (without quotes) using Regex in below - </p>

```<code><html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/gaits/CreateReport.aspx?RptNum=RQR-1BN6Q360090-0001">here</a>.</h2>
</body></html>

I tried this but it does  not work
RptNum=([A-Za-z]+)$
</code>```

答:
Here, we can also use an expression that collects the new lines, such as:

```<code>[\s\S]*RptNum=(.+?)"[\s\S]*
[\w\W]*RptNum=(.+?)"[\w\W]*
[\d\D]*RptNum=(.+?)"[\d\D]*
</code>```

and our desired output is saved in (.+?).

Test

const regex = /[\s\S]*RptNum=(.+?)"[\s\S]*/gm;
const str = `<title>Object moved</title>

Object moved to here.

`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);```

Demo

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Title: Regex for picking a Value After “=”

Body:
How i can select RQR-1BN6Q360090-0001 (without quotes) using Regex in below -

<title>Object moved</title>

Object moved to here.

I tried this but it does  not work
RptNum=([A-Za-z]+)$

Body:
Here, we can also use an expression that collects the new lines, such as:

[\s\S]*RptNum=(.+?)"[\s\S]*
[\w\W]*RptNum=(.+?)"[\w\W]*
[\d\D]*RptNum=(.+?)"[\d\D]*

and our desired output is saved in (.+?).

Test

const regex = /[\s\S]*RptNum=(.+?)"[\s\S]*/gm;
const str = `<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/gaits/CreateReport.aspx?RptNum=RQR-1BN6Q360090-0001">here</a>.</h2>
</body></html>`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

Demo

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


答:
You may use

```<code>/RptNum=([\w-]+)/
</code>```

The pattern will match RptNum= and then capture 1 or more occurrences of word chars (letters, digits and _) or hyphens. See the regex demo and the regex graph:

Note that

```<code>/RptNum=([A-Z0-9-]+)/
</code>```

might be a more restrictive pattern that should work, too. It does not match _ and lowercase letters.

In JS, use it with String#match() and grab the second array item upon a match:

var s = 'Object moved to here';
var m = s.match(/RptNum=([\w-]+)/);
if (m) {
  console.log(m[1]);
}```

Title: Regex for picking a Value After “=”

Body:
You may use

/RptNum=([\w-]+)/

The pattern will match RptNum= and then capture 1 or more occurrences of word chars (letters, digits and _) or hyphens. See the regex demo and the regex graph:

Note that

/RptNum=([A-Z0-9-]+)/

might be a more restrictive pattern that should work, too. It does not match _ and lowercase letters.

In JS, use it with String#match() and grab the second array item upon a match:

var s = 'Object moved to <a href="/gaits/CreateReport.aspx?RptNum=RQR-1BN6Q360090-0001">here</a>';
var m = s.match(/RptNum=([\w-]+)/);
if (m) {
  console.log(m[1]);
}


问:
How can I connect to the Azure AD B2C from Microsoft Graph Explorer
I have a Azure AD B2C Tenant and a few users in it.

How can I use the Microsoft Graph Explorer to update those users properties (default as well as custom)?

What endpoint I need to use and what credentials to be used to login to the Microsoft Graph Explorer?

答:
Currently, you must use Azure AD Graph API and Azure AD Graph Explorer to manage users in an Azure AD B2C tenant, since Microsoft Graph doesn't support some of the user properties that are used by Azure AD B2C.

You can sign in as either a Company/Global Administrator or User Administrator user to Azure AD Graph Explorer.


问:
Why does Thread.Sleep(0) fix my problems, and how to avoid it?
I'm working on a client server application.  At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock.  If I step in to debug the problem, then the program appears to be processing.  Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem.  The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code.  If I don't call it enough, the code seems to be in deadlock.  Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread.

Is there a good way to track down exactly what is causing this.  It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP.  However, it's impossible to debug, because simply stepping into the code causes the problem to go away.  I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there.  Any pointers would be greatly appreciated.

[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher.  I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode.  The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.

[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely.  Still the problem persists.  There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there.  And it's not deadlocked.  It runs, albeit very slowly, even though it's eating up all the processor resources.

答: You definately have threading issues that need to be addressed.  Calling thread.Sleep(0) causes the scheduler to kick in. This probably gives each thread an opportunity to run enough to make things work. I wouldn't just leave the sleep in there and leave it at that because those are the type of things that work for a while and then a totally unrelated change ends up breaking things.</p>

OwnerDisplayName: Kibbee

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kibbee

OwnerDisplayName: Dunk


问:
UICollectionView Header Dynamic Size according to its contents and margins
I have a UICollectionView where my header is of type UICollectionReusableView. Now I have multiple items in the header which may lead to variability in the size of the header. These items also do have padding/contraints. How exactly should I address this?

答:
There is no magic bullet. There is no such thing as a self-sizing header view. You just have to measure / calculate the desired size of the header view based on its contents, yourself, and use that as the result of referenceSizeForHeaderInSection.

The typical approach, if you're configuring the contents of the header view with constraints, is to set up a model header view with the desired contents and constraints and call systemLayoutSizeFittingSize to get the autolayout engine to tell you the resulting size.


问:
Can we use the same signer object to sign all the requests?
I need to make mutiple rest api calls for fetching instance, volume and vnic details. Can i reuse the same signer object created for signing the other calls?

Signer object method

```<code>   public RequestSigner getSigner(Properties properties, String pemFilePath, String apiKey) {
    InputStream privateKeyStream;
    PrivateKey privateKey = null;
    try {
        privateKeyStream = Files.newInputStream(Paths.get(pemFilePath));
        privateKey = PEM.readPrivateKey(privateKeyStream);
    } catch (InvalidKeySpecException e) {
        // throw new RuntimeException("Invalid format for private key");
        properties.setProperty(OracleCloudConstants.CUSTOM_DC_ERROR,
                FormatUtil.getString("am.webclient.oraclecloud.customdc.invalidformat"));
        AMLog.debug("OracleCloudDataCollector::CheckAuthentication()::Invalid format for private key::"
                + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        properties.setProperty(OracleCloudConstants.CUSTOM_DC_ERROR,
                FormatUtil.getString("am.webclient.oraclecloud.customdc.failedload"));
        AMLog.debug(
                "OracleCloudDataCollector::CheckAuthentication()::Failed to load private key::" + e.getMessage());  //No I18N
        e.printStackTrace();
        // throw new RuntimeException("Failed to load private key");
    }
    RequestSigner signer = null;
    if (privateKey != null) {
        signer = new RequestSigner(apiKey, privateKey);
    }
    return signer;
}
</code>```

答:
One signer object may be used to sign multiple requests. In fact, the SDK implementation does this too.

It is not clear what version of the SDK you are using. In version 1.5.7 (the most recent at the time of writing), com.oracle.bmc.http.signing.RequestSigner (https://github.com/oracle/oci-java-sdk/blob/master/bmc-common/src/main/java/com/oracle/bmc/http/signing/RequestSigner.java#L16) is an interface which cannot be new’ed as per the snippet above.

Body:
I need to make mutiple rest api calls for fetching instance, volume and vnic details. Can i reuse the same signer object created for signing the other calls?

Signer object method

   public RequestSigner getSigner(Properties properties, String pemFilePath, String apiKey) {
    InputStream privateKeyStream;
    PrivateKey privateKey = null;
    try {
        privateKeyStream = Files.newInputStream(Paths.get(pemFilePath));
        privateKey = PEM.readPrivateKey(privateKeyStream);
    } catch (InvalidKeySpecException e) {
        // throw new RuntimeException("Invalid format for private key");
        properties.setProperty(OracleCloudConstants.CUSTOM_DC_ERROR,
                FormatUtil.getString("am.webclient.oraclecloud.customdc.invalidformat"));
        AMLog.debug("OracleCloudDataCollector::CheckAuthentication()::Invalid format for private key::"
                + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        properties.setProperty(OracleCloudConstants.CUSTOM_DC_ERROR,
                FormatUtil.getString("am.webclient.oraclecloud.customdc.failedload"));
        AMLog.debug(
                "OracleCloudDataCollector::CheckAuthentication()::Failed to load private key::" + e.getMessage());  //No I18N
        e.printStackTrace();
        // throw new RuntimeException("Failed to load private key");
    }
    RequestSigner signer = null;
    if (privateKey != null) {
        signer = new RequestSigner(apiKey, privateKey);
    }
    return signer;
}


问:
Node JS and mysql not connecting (client does not support authentication protocol requested by server consider upgrading mysql client)
I'm trying to connect my NodeJs application with a mysql database but its not connecting for some reason.

I did install the mysql npm like this (typed this in commandline):

```<code>npm install mysql
</code>```

After I installed the mysql npm I made an index.js file and in that file I tried to make the connection with my database.

This is the code inside my index.js file to make a connection with mysql:

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

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    port     : '3306',
    password : 'test12310',
    database : 'fys'
});

connection.connect((err) => {
    if(!err)
        console.log('Database is geconnect!');
    else
        console.log('Database connectie niet gelukt!  : '+ JSON.stringify(err, undefined,2));
});
</code>```

Then I tried to run the code and see if the connection with mysql worked. I typed this in the command line:

```<code>node index.js
</code>```

This is the error message I got in the command prompt :

error image

Does anyone know how I can fix this error and get a connection with my mysqldatabase in nodejs ?

Any kind of help is appreciated

答:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YourRootPassword';
-- or
CREATE USER 'foo'@'%' IDENTIFIED WITH mysql_native_password BY 'bar';
-- then
FLUSH PRIVILEGES;
```

Body:
I'm trying to connect my NodeJs application with a mysql database but its not connecting for some reason.

I did install the mysql npm like this (typed this in commandline):

npm install mysql

After I installed the mysql npm I made an index.js file and in that file I tried to make the connection with my database.

This is the code inside my index.js file to make a connection with mysql:

const mysql      = require('mysql');

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    port     : '3306',
    password : 'test12310',
    database : 'fys'
});

connection.connect((err) => {
    if(!err)
        console.log('Database is geconnect!');
    else
        console.log('Database connectie niet gelukt!  : '+ JSON.stringify(err, undefined,2));
});

Then I tried to run the code and see if the connection with mysql worked. I typed this in the command line:

node index.js

This is the error message I got in the command prompt :

error image

Does anyone know how I can fix this error and get a connection with my mysqldatabase in nodejs ?

Any kind of help is appreciated


问:
Help shortening my code in didSelectRowAtIndexPath into a much easier code
Hey developers!
I built a Table View, populated it with array objects and I implemented a code when a user clicks an object inside my Table View, it loads that object's own nib file, and I am using an if statement. (just a little note, I populated my Table View with 40 objects because that's how much things I have and need), so I'll show only the first two if statements I created at the beginning of my if statement code since I have way too many if statements for all 40 objects in my Table View:

```<code>if ([[glossaryArray objectAtIndex:indexPath.row] isEqual:@"Title"]) {
    Title *titleLoad = [[Title alloc] initWithNibName:@"Title" bundle:nil];
    [self.navigationController pushViewController:titleLoad animated:YES];
    [titleLoad release];
    }
    else if ([[glossaryArray objectAtIndex:indexPath.row] isEqual:@"Meta Description Tag"]) {
        MetaDescriptionTag *metaDescriptionTagLoad = [[MetaDescriptionTag alloc] initWithNibName:@"MetaDescriptionTag" bundle:nil];
        [self.navigationController pushViewController:metaDescriptionTagLoad animated:YES];
        [metaDescriptionTagLoad release];
    }
...
</code>```

So that's it, I don't want to be cocky showing all of my if statements, so yep this code works, each array objects loading it's own separate nib file (40 nib file 1 for each array objects) and each of these nib files are like Web Views, Image Views, Text Fields and other objects. Call me crazy, but this is the only code I can think of right now, so hopefully someone can help me edit this code into a much easier code, thanks

答:
If your values in glossaryArray can be mechanically transformed into the corresponding class/nib name (e.g. by removing all spaces), you could do something like this:

```<code>NSString *className = [self classNameFromString:[glossaryArray objectAtIndex:indexPath.row]];
UIViewController *viewController = [[NSClassFromString(className) alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
</code>```

If they can't be mechanically transformed, you could always construct an NSDictionary mapping from one to the other, or special-case the few that are different. Or rename the classes and nibs.

ContentLicense: CC BY-SA 3.0

Body:
Hey developers!
I built a Table View, populated it with array objects and I implemented a code when a user clicks an object inside my Table View, it loads that object's own nib file, and I am using an if statement. (just a little note, I populated my Table View with 40 objects because that's how much things I have and need), so I'll show only the first two if statements I created at the beginning of my if statement code since I have way too many if statements for all 40 objects in my Table View:

if ([[glossaryArray objectAtIndex:indexPath.row] isEqual:@"Title"]) {
    Title *titleLoad = [[Title alloc] initWithNibName:@"Title" bundle:nil];
    [self.navigationController pushViewController:titleLoad animated:YES];
    [titleLoad release];
    }
    else if ([[glossaryArray objectAtIndex:indexPath.row] isEqual:@"Meta Description Tag"]) {
        MetaDescriptionTag *metaDescriptionTagLoad = [[MetaDescriptionTag alloc] initWithNibName:@"MetaDescriptionTag" bundle:nil];
        [self.navigationController pushViewController:metaDescriptionTagLoad animated:YES];
        [metaDescriptionTagLoad release];
    }
...

So that's it, I don't want to be cocky showing all of my if statements, so yep this code works, each array objects loading it's own separate nib file (40 nib file 1 for each array objects) and each of these nib files are like Web Views, Image Views, Text Fields and other objects. Call me crazy, but this is the only code I can think of right now, so hopefully someone can help me edit this code into a much easier code, thanks

Body:
If your values in glossaryArray can be mechanically transformed into the corresponding class/nib name (e.g. by removing all spaces), you could do something like this:

NSString *className = [self classNameFromString:[glossaryArray objectAtIndex:indexPath.row]];
UIViewController *viewController = [[NSClassFromString(className) alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];

If they can't be mechanically transformed, you could always construct an NSDictionary mapping from one to the other, or special-case the few that are different. Or rename the classes and nibs.


问:
Too many simultaneous invocations Google Script
I set up some code to copy and paste a certain value from the formula using form submissions as a trigger.  It worked!  But now it's giving me a "too many simultaneous invocations" error with reference to line 3.

It has not been called in excess of 20 times a day (as I know is the set limit) so I'm imagining I did something off with my code... (I'm NOT a JS guy.)

```<code>function pasteValue(){
var sheet =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('INVOICES')
var lastRow = sheet.getDataRange().getValues();

lastRow.forEach(function (row,index) {
    if (row[1] == "") {
        lastRow.length = index;
    }
});

var newRange = sheet.getRange(lastRow.length,13);
newRange.copyTo(newRange, {contentsOnly: true})
sheet.setActiveRange(newRange);
}
</code>```

答:
If what you want is to remove the formulas, its more straightforward to do something like this with "display values":</p>

```<code>function pasteValue(){
var sheet =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('INVOICES')
var data = sheet.getDataRange().getDisplayValues();
sheet.getRange(1, 1,data.length, data[0].length).setValues(data);
}
</code>```

Body:
I set up some code to copy and paste a certain value from the formula using form submissions as a trigger.  It worked!  But now it's giving me a "too many simultaneous invocations" error with reference to line 3.

It has not been called in excess of 20 times a day (as I know is the set limit) so I'm imagining I did something off with my code... (I'm NOT a JS guy.)

function pasteValue(){
var sheet =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('INVOICES')
var lastRow = sheet.getDataRange().getValues();

lastRow.forEach(function (row,index) {
    if (row[1] == "") {
        lastRow.length = index;
    }
});

var newRange = sheet.getRange(lastRow.length,13);
newRange.copyTo(newRange, {contentsOnly: true})
sheet.setActiveRange(newRange);
}

Body:
If what you want is to remove the formulas, its more straightforward to do something like this with "display values":

function pasteValue(){
var sheet =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('INVOICES')
var data = sheet.getDataRange().getDisplayValues();
sheet.getRange(1, 1,data.length, data[0].length).setValues(data);
}


问:
Use GIT LFS to track a large binary file without a file extension
Inside iOS frameworks is a binary that has no extension. My binary exceeds github's size limit of 100MB.

I've set up LFS as indicated here

I've tried to tell LFS to track my binary by name: git lfs track 'MyFramework'

I've tried to tell LFS to track my binary by path: git lfs track 'path/to/MyFramework'

No deal either way! Github server still responds by telling me that the file is too large.

Any ideas?

答:
I've been trying to find the solution to this for a while and every answer was to use git lfs track .. Which is great for single files, but doesn't handle new files being added.

Adding this to the .gitattributes file worked for finding everything that doesn't have an extension in a Repo:

```<code>* filter=lfs diff=lfs merge=lfs -text # Include everything
/**/ -filter=lfs -diff=lfs -merge=lfs -text # Exclude directories
*.* -filter=lfs -diff=lfs -merge=lfs -text # Exclude anything with an extension
</code>```

Body:
I've been trying to find the solution to this for a while and every answer was to use git lfs track .. Which is great for single files, but doesn't handle new files being added.

Adding this to the .gitattributes file worked for finding everything that doesn't have an extension in a Repo:

* filter=lfs diff=lfs merge=lfs -text # Include everything
/**/ -filter=lfs -diff=lfs -merge=lfs -text # Exclude directories
*.* -filter=lfs -diff=lfs -merge=lfs -text # Exclude anything with an extension


问:
Div with Background Image Not Showing
I am sure I am missing something simple here: I am creating a map with different image overlays. I got the map to work but the map doesn't show up until you push a button. I need it to show up always. Currently the map is set as a background image. If I set it as an image none of the buttons work. Does anyone know what I'm missing?

var alertName = document.getElementsByClassName("alertName");

var myFunction = function() {

  var hide = document.getElementsByClassName("hide");

  for (var i = 0; i < hide.length; i++) {

    hide[i].style.display = "none";

  }

  var name = this.getAttribute("name");

  var show = document.querySelector('.' + name);

  if (show.style.display = "none") {

    show.style.display = "block";

  } else {

    show.style.display = "none";

  }

};

for (var i = 0; i < alertName.length; i++) {

  alertName[i].addEventListener('click', myFunction);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  z-index: 2;
  display: none;
}

.hidingsection {
  background-image: url("https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077777/elke/map_base_1_gv6ehh.png");
  background-repeat: no-repeat;
}

.container {
  display: flex;
  flex-flow: row
}

.hidingsection {
  z-index: 0;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />

          <button class="alertName" name="schoolContent">Schools</button>

          <button class="alertName" name="recreationContent">Recreation</button>

          <button class="alertName" name="restaurantsContent">Restaurants</button>

          <button class="alertName" name="banksContent">Banks</button>

          <button class="alertName" name="groceriesContent">Groceries</button>

          <button class="alertName" name="transportationContent"> Transportation</button>

          <button class="alertName" name="libraryContent">Library</button>

```

答:
Since all inner divs are hidden (thus no-content), the parent (outer) div does not have an initial height.

Add a size to the section and you'll see the bg image

i.e.

```<code>.hidingsection {
    z-index: 0;
    width: 1280px;
    height: 800px;
    background-image: url("https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077777/elke/map_base_1_gv6ehh.png");
}
</code>```

(of course, you'll need to adjust the values given above to suit your needs)

See demo below

var alertName = document.getElementsByClassName("alertName");

var myFunction = function() {

  var hide = document.getElementsByClassName("hide");

  for (var i = 0; i < hide.length; i++) {

    hide[i].style.display = "none";

  }

  var name = this.getAttribute("name");

  var show = document.querySelector('.' + name);

  if (show.style.display = "none") {

    show.style.display = "block";

  } else {

    show.style.display = "none";

  }

};

for (var i = 0; i < alertName.length; i++) {

  alertName[i].addEventListener('click', myFunction);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  z-index: 2;
  display: none;
}

.hidingsection {
    z-index: 0;
    width: 1280px;
    height: 800px;
    background-image: url("https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077777/elke/map_base_1_gv6ehh.png");
}

.container {
  display: flex;
  flex-flow: row
}

.hidingsection {

}</code>```

        <button class="alertName" name="schoolContent">Schools</button>

        <button class="alertName" name="recreationContent">Recreation</button>

        <button class="alertName" name="restaurantsContent">Restaurants</button>

        <button class="alertName" name="banksContent">Banks</button>

        <button class="alertName" name="groceriesContent">Groceries</button>

        <button class="alertName" name="transportationContent"> Transportation</button>

        <button class="alertName" name="libraryContent">Library</button>

```

Title: Div with Background Image Not Showing

Body:
I am sure I am missing something simple here: I am creating a map with different image overlays. I got the map to work but the map doesn't show up until you push a button. I need it to show up always. Currently the map is set as a background image. If I set it as an image none of the buttons work. Does anyone know what I'm missing?

var alertName = document.getElementsByClassName("alertName");

var myFunction = function() {

  var hide = document.getElementsByClassName("hide");

  for (var i = 0; i < hide.length; i++) {

    hide[i].style.display = "none";

  }

  var name = this.getAttribute("name");

  var show = document.querySelector('.' + name);

  if (show.style.display = "none") {

    show.style.display = "block";

  } else {

    show.style.display = "none";

  }

};

for (var i = 0; i < alertName.length; i++) {

  alertName[i].addEventListener('click', myFunction);

}

.hide {
  z-index: 2;
  display: none;
}

.hidingsection {
  background-image: url("https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077777/elke/map_base_1_gv6ehh.png");
  background-repeat: no-repeat;
}

.container {
  display: flex;
  flex-flow: row
}

.hidingsection {
  z-index: 0;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />

          <button class="alertName" name="schoolContent">Schools</button>

          <button class="alertName" name="recreationContent">Recreation</button>

          <button class="alertName" name="restaurantsContent">Restaurants</button>

          <button class="alertName" name="banksContent">Banks</button>

          <button class="alertName" name="groceriesContent">Groceries</button>

          <button class="alertName" name="transportationContent"> Transportation</button>

          <button class="alertName" name="libraryContent">Library</button>

Body:
Since all inner divs are hidden (thus no-content), the parent (outer) div does not have an initial height.

Add a size to the section and you'll see the bg image

i.e.

.hidingsection {
    z-index: 0;
    width: 1280px;
    height: 800px;
    background-image: url("https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077777/elke/map_base_1_gv6ehh.png");
}

(of course, you'll need to adjust the values given above to suit your needs)

See demo below

var alertName = document.getElementsByClassName("alertName");

var myFunction = function() {

  var hide = document.getElementsByClassName("hide");

  for (var i = 0; i < hide.length; i++) {

    hide[i].style.display = "none";

  }

  var name = this.getAttribute("name");

  var show = document.querySelector('.' + name);

  if (show.style.display = "none") {

    show.style.display = "block";

  } else {

    show.style.display = "none";

  }

};

for (var i = 0; i < alertName.length; i++) {

  alertName[i].addEventListener('click', myFunction);

}

.hide {
  z-index: 2;
  display: none;
}

.hidingsection {
    z-index: 0;
    width: 1280px;
    height: 800px;
    background-image: url("https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077777/elke/map_base_1_gv6ehh.png");
}

.container {
  display: flex;
  flex-flow: row
}

.hidingsection {

}

<div class="container">
  <div class="buttons">
    <section>
      <div>

        <button class="alertName" name="schoolContent">Schools</button>

        <button class="alertName" name="recreationContent">Recreation</button>

        <button class="alertName" name="restaurantsContent">Restaurants</button>

        <button class="alertName" name="banksContent">Banks</button>

        <button class="alertName" name="groceriesContent">Groceries</button>

        <button class="alertName" name="transportationContent"> Transportation</button>

        <button class="alertName" name="libraryContent">Library</button>

      </div>
    </section>
  </div>
  <br/>
  <div class="map">
    <section class="hidingsection">

      <div class="hide schoolContent">

        <img src="https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077188/elke/schools_pyqexw.png" />

      </div>
      <div class="hide recreationContent">
        <img src="https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077189/elke/recreation_psbfyp.png" />

      </div>

      <div class="hide restaurantsContent">

        <img src="https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077188/elke/restaurants_xjbtbd.png" />

      </div>

      <div class="hide banksContent">

        <img src="https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077188/elke/banks_zohw39.png" />

      </div>

      <div class="hide groceriesContent">

        <img src="https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077188/elke/groceries_xjaddd.png" />

      </div>

      <div class="hide transportationContent">

        <img src="https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077188/elke/transportation_mzzclu.png" />

      </div>

      <div class="hide libraryContent">

        <img src="https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077188/elke/library_pbesf1.png" />

      </div>

    </section>
  </div>


问:
Fastest method to find a complex type in a list (Vector, Array, Dictionary, whatever is faster)
Hail, Stack!

I need to know the best method to find an item inside a list (Vector, Array, Dictionary, whatever is faster) of complex type (extensions of Objects and Sprites).

I've used "Needle in Haystack" method, but it seems that it isn't fast enough.

E.g.
Suppose that I have a collection of Sprites (a pool, in fact).

Each sprite will be added to the stage and perform some action. After that, it will die.

I don't want to pay the cost to dispose it (garbage collect) and create another (new) one every time so I'll keep the dead sprites in a collection.

Sometimes times I'll call a method that will add a sprite to the stage.

This sprite can be a old one, if it is already dead, or a new one, if the pool don't have any free sprite.

One of the scenarios that pushed me to this question was a Particle System.

A "head" particle leaving a "trail" of particles every frame and exploding into a flashy multitude of particles... Every frame...

Some times this counts up to 50.000 PNGs with motion, rotation, alpha, event dispatching, scale, etc...

But, this is JUST ONE scenario...

At the moment I'm trying to use a Object Pool with a Linked List...

Hopes that it will be faster that running a whole Array/Vector or create new instances every frame an let them dye with Garbage Collection.

Someone knows a better/faster way to do it?

答:
I'm not sure about what you are searching and what you want to do with it.
If you are trying to determine if a string is in a list, the fastest solution is the Dictionnary. I've done a little benchmark.

```<code>/**
* Determine which is the fastest to find a key between array, object, vector and dictionnary
**/
public class FlashTest extends Sprite {
    public function FlashTest() {
        var array:Array = new Array();
        var object:Object = new Object();
        var dictionary:Dictionary = new Dictionary();
        var vector:Vector.<String> = new Vector.<String>();

        for (var i:int=0; i < 10000; i++)
        {
            array.push(i.toString());
            object[i.toString()] = 1;
            vector.push(i.toString());
            dictionary[i.toString()] = 1;
        }

        var time:uint = getTimer();
        for (i=0; i < 10000; i++)
        {
            array.indexOf(i.toString());
        }

        trace("array"+(getTimer()-time)); //2855

        time = getTimer();
        for (i=0; i < 10000; i++)
        {
            vector.indexOf(i.toString());
        }

        trace("vector"+(getTimer()-time)); //3644

        time = getTimer();
        for (i=0; i < 10000; i++)
        {
            object.hasOwnProperty(i.toString());
        }

        trace("object"+(getTimer()-time)); //48

        time = getTimer();
        for (i=0; i < 10000; i++)
        {
            dictionary.hasOwnProperty(i.toString());
        }

        trace("dictionary"+(getTimer()-time)); //35

    }
}
</code>```

Cheers!

Body:
I'm not sure about what you are searching and what you want to do with it.
If you are trying to determine if a string is in a list, the fastest solution is the Dictionnary. I've done a little benchmark.

/**
* Determine which is the fastest to find a key between array, object, vector and dictionnary
**/
public class FlashTest extends Sprite {
    public function FlashTest() {
        var array:Array = new Array();
        var object:Object = new Object();
        var dictionary:Dictionary = new Dictionary();
        var vector:Vector.<String> = new Vector.<String>();

        for (var i:int=0; i < 10000; i++)
        {
            array.push(i.toString());
            object[i.toString()] = 1;
            vector.push(i.toString());
            dictionary[i.toString()] = 1;
        }

        var time:uint = getTimer();
        for (i=0; i < 10000; i++)
        {
            array.indexOf(i.toString());
        }

        trace("array"+(getTimer()-time)); //2855

        time = getTimer();
        for (i=0; i < 10000; i++)
        {
            vector.indexOf(i.toString());
        }

        trace("vector"+(getTimer()-time)); //3644

        time = getTimer();
        for (i=0; i < 10000; i++)
        {
            object.hasOwnProperty(i.toString());
        }

        trace("object"+(getTimer()-time)); //48

        time = getTimer();
        for (i=0; i < 10000; i++)
        {
            dictionary.hasOwnProperty(i.toString());
        }

        trace("dictionary"+(getTimer()-time)); //35

    }
}

Cheers!


问:
What does validity of a templated code mean?
Validity of a non-template code is more or less clear to everyone - a compiler checks the syntax, types, and rules. The compiler has everything it needs to perform these checks.

But when the compiler has to compile a templated code (for example STL, or Boost) it does't have enough information.
While the templated code isn't instantiated the compiler doesn't know what operations mean, whether or not they are defined for the types that will be used to instantiate this templated code, etc. Templated code can't be compiled untill instantiated.

Is there such a thing as a validity of a templated code? Would it require us to compile every instantiation of a templated code to verify its validity?

答:
The standard talks about such validity:

The validity of a template may be checked prior to any instantiation. [ Note: Knowing which names are type names allows the syntax of every template to be checked in this way. — end note ]

As the note says, the reliable check is merely syntactic (or grammar-based).  Even rules like looking up non-dependent names are covered by the rule that any template that cannot be instantiated is ill-formed, no diagnostic required.  The implementation may then do anything at all, including compiling a program that does… something.  (This is really too much implementation freedom; some of these rules could just be “may be ill-formed (with a diagnostic) at the implementation’s discretion”.)


问:
Modify grid-template-columns using javascript
I am trying to change the size of grid-template-columns upon the click of a button (https://jsfiddle.net/3ft6svgk/2/).

html:

```<code><div class="grid-squares">
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
    <button id="firstButton">Learn More</button>
  </div>
   <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
   <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
   <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
</div>
</code>```

css:

```<code>.grid-squares{
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 300px;
}
</code>```

javscript:

```<code>firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
  squaresGrid = document.getElementsByClassName("grid-squares");
  squaresGrid.style.gridTemplateColumns = "1000px";
}
</code>```

With this code I am getting

```<code>"Uncaught TypeError: Cannot set property 'gridTemplateColumns' of undefined
    at HTMLButtonElement.repairsAndUpgradesButton.onclick"
</code>```

in the console. How can I properly change the value of grid-template-columns?

答:
.getElementsByClassName() returns a NodeList collection of elements.

You either need to loop over your .gridSquares:

```<code>squaresGrid = document.getElementsByClassName("grid-squares");
for (let i = 0; i < squaresGrid.length; i++) {
   squaresGrid[i].style.gridTemplateColumns = "1000px";
}
</code>```

Or access them by index (you only have one, at index 0):

```<code>squaresGrid = document.getElementsByClassName("grid-squares")[0];
squaresGrid.style.gridTemplateColumns = "1000px";
</code>```

You will also want to make use of Unobtrusive JavaScript, and add an event listener to your button rather than make use of .onclick.

This can be seen in the following working example:

firstButton = document.getElementById("firstButton")
firstButton.addEventListener('click', function() {
  squaresGrid = document.getElementsByClassName("grid-squares")[0];
  squaresGrid.style.gridTemplateColumns = "1000px";
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.grid-squares {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 300px;
}</code>```

Lorem Ipsum

    <button id="firstButton">Learn More</button>

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

```

Body:
I am trying to change the size of grid-template-columns upon the click of a button (https://jsfiddle.net/3ft6svgk/2/).

html:

Lorem Ipsum

    <button id="firstButton">Learn More</button>

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

css:

.grid-squares{
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 300px;
}

javscript:

firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
  squaresGrid = document.getElementsByClassName("grid-squares");
  squaresGrid.style.gridTemplateColumns = "1000px";
}

With this code I am getting

"Uncaught TypeError: Cannot set property 'gridTemplateColumns' of undefined
    at HTMLButtonElement.repairsAndUpgradesButton.onclick"

in the console. How can I properly change the value of grid-template-columns?

Body:
.getElementsByClassName() returns a NodeList collection of elements.

You either need to loop over your .gridSquares:

squaresGrid = document.getElementsByClassName("grid-squares");
for (let i = 0; i < squaresGrid.length; i++) {
   squaresGrid[i].style.gridTemplateColumns = "1000px";
}

Or access them by index (you only have one, at index 0):

squaresGrid = document.getElementsByClassName("grid-squares")[0];
squaresGrid.style.gridTemplateColumns = "1000px";

You will also want to make use of Unobtrusive JavaScript, and add an event listener to your button rather than make use of .onclick.

This can be seen in the following working example:

firstButton = document.getElementById("firstButton")
firstButton.addEventListener('click', function() {
  squaresGrid = document.getElementsByClassName("grid-squares")[0];
  squaresGrid.style.gridTemplateColumns = "1000px";
});

.grid-squares {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 300px;
}

<div class="grid-squares">
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
    <button id="firstButton">Learn More</button>
  </div>
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
</div>


问:
noble BLE module - characteristic.subscribe() hitting error
I'm on windows 10, using the asus BT-400.

I've successfully connected to my device, read all characteristics/properties, and written to a characteristic. However, I have a characteristic that I'd like to subscribe to for notifications (I have verified that this characteristic has the notify property), and I'm running into an error.

When I follow the code execution, it looks like within gatt.js at the notify function, I'm getting an op code associated with an error.

```<code>Gatt.prototype.notify = function(serviceUuid, characteristicUuid, notify) {
  var characteristic = this._characteristics[serviceUuid][characteristicUuid];

  this._queueCommand(this.readByTypeRequest(characteristic.startHandle, characteristic.endHandle, GATT_CLIENT_CHARAC_CFG_UUID), function(data) {
    var opcode = data[0];

    if (opcode === ATT_OP_READ_BY_TYPE_RESP) {
      var type = data[1];
      var handle = data.readUInt16LE(2);
      var value = data.readUInt16LE(4);

      var useNotify = characteristic.properties & 0x10;
      var useIndicate = characteristic.properties & 0x20;

      if (notify) {
        if (useNotify) {
          value |= 0x0001;
        } else if (useIndicate) {
          value |= 0x0002;
        }
      } else {
        if (useNotify) {
          value &= 0xfffe;
        } else if (useIndicate) {
          value &= 0xfffd;
        }
      }

      var valueBuffer = new Buffer(2);
      valueBuffer.writeUInt16LE(value, 0);

      this._queueCommand(this.writeRequest(handle, valueBuffer, false), function(data) {
        var opcode = data[0];

        if (opcode === ATT_OP_WRITE_RESP) {
          this.emit('notify', this._address, serviceUuid, characteristicUuid, notify);
        }
      }.bind(this));
    }
  }.bind(this));
};
</code>```

The value of "data" in the callback is: { 1, 8, 54, 0, 10 }.

Also, here is the characteristic I'm calling this on:

```<code>Characteristic
descriptors: null
name: null
properties: (5) ["read", "writeWithoutResponse", "write", "notify", "indicate"]
type: null
uuid: "495353431e4d4bd9ba6123c647249616"
_events: {data: ƒ}
_eventsCount: 1
_noble: Noble {initialized: true, address: "5c:f3:70:94:4b:01", _state: "poweredOn", _bindings: NobleBindings, _peripherals: {…}, …}
_peripheralId: "3481f4141bf0"
_serviceUuid: "49535343fe7d4ae58fa99fafd205e455"
__proto__: EventEmitter
</code>```

And when I call discoverDescriptors on this characteristic:

```<code>Descriptor {
  _noble:
   Noble {
     initialized: true,
     address: '5c:f3:70:94:4b:01',
     _state: 'poweredOn',
     _bindings:
      NobleBindings {
        _state: 'poweredOn',
        _addresses: [Object],
        _addresseTypes: [Object],
        _connectable: [Object],
        _pendingConnectionUuid: null,
        _connectionQueue: [],
        _handles: [Object],
        _gatts: [Object],
        _aclStreams: [Object],
        _signalings: [Object],
        _hci: [Hci],
        _gap: [Gap],
        _events: [Object],
        _eventsCount: 21,
        onSigIntBinded: [Function: bound ],
        _scanServiceUuids: [] },
     _peripherals:
      { '574d3263441d': [Peripheral], '3481f4141bf0': [Peripheral] },
     _services: { '574d3263441d': {}, '3481f4141bf0': [Object] },
     _characteristics: { '574d3263441d': {}, '3481f4141bf0': [Object] },
     _descriptors: { '574d3263441d': {}, '3481f4141bf0': [Object] },
     _discoveredPeripheralUUids: [ '574d3263441d', '3481f4141bf0' ],
     _events:
      [Object: null prototype] {
        warning: [Function: bound ],
        newListener: [Function: bound ],
        stateChange: [Function],
        discover: [Function] },
     _eventsCount: 4,
     _allowDuplicates: undefined },
  _peripheralId: '3481f4141bf0',
  _serviceUuid: '49535343fe7d4ae58fa99fafd205e455',
  _characteristicUuid: '495353431e4d4bd9ba6123c647249616',
  uuid: '2902',
  name: 'Client Characteristic Configuration',
  type:
   'org.bluetooth.descriptor.gatt.client_characteristic_configuration' }
</code>```

I'm not sure how to interpret the data that's passed back in order to debug this issue further.

答:
Your data is an ATT Response.
1: opcode for Error Response
8: opcode for the request that failed (Read By Type Request with the CCCD uuid)
54 00: search from handle
10: the error code "Attribute Not Found"

So I guess the Client Characteristic Configuration Descriptor is missing for the characteristic.

Body:
I'm on windows 10, using the asus BT-400.

I've successfully connected to my device, read all characteristics/properties, and written to a characteristic. However, I have a characteristic that I'd like to subscribe to for notifications (I have verified that this characteristic has the notify property), and I'm running into an error.

When I follow the code execution, it looks like within gatt.js at the notify function, I'm getting an op code associated with an error.

Gatt.prototype.notify = function(serviceUuid, characteristicUuid, notify) {
  var characteristic = this._characteristics[serviceUuid][characteristicUuid];

  this._queueCommand(this.readByTypeRequest(characteristic.startHandle, characteristic.endHandle, GATT_CLIENT_CHARAC_CFG_UUID), function(data) {
    var opcode = data[0];

    if (opcode === ATT_OP_READ_BY_TYPE_RESP) {
      var type = data[1];
      var handle = data.readUInt16LE(2);
      var value = data.readUInt16LE(4);

      var useNotify = characteristic.properties & 0x10;
      var useIndicate = characteristic.properties & 0x20;

      if (notify) {
        if (useNotify) {
          value |= 0x0001;
        } else if (useIndicate) {
          value |= 0x0002;
        }
      } else {
        if (useNotify) {
          value &= 0xfffe;
        } else if (useIndicate) {
          value &= 0xfffd;
        }
      }

      var valueBuffer = new Buffer(2);
      valueBuffer.writeUInt16LE(value, 0);

      this._queueCommand(this.writeRequest(handle, valueBuffer, false), function(data) {
        var opcode = data[0];

        if (opcode === ATT_OP_WRITE_RESP) {
          this.emit('notify', this._address, serviceUuid, characteristicUuid, notify);
        }
      }.bind(this));
    }
  }.bind(this));
};

The value of "data" in the callback is: { 1, 8, 54, 0, 10 }.

Also, here is the characteristic I'm calling this on:

Characteristic
descriptors: null
name: null
properties: (5) ["read", "writeWithoutResponse", "write", "notify", "indicate"]
type: null
uuid: "495353431e4d4bd9ba6123c647249616"
_events: {data: ƒ}
_eventsCount: 1
_noble: Noble {initialized: true, address: "5c:f3:70:94:4b:01", _state: "poweredOn", _bindings: NobleBindings, _peripherals: {…}, …}
_peripheralId: "3481f4141bf0"
_serviceUuid: "49535343fe7d4ae58fa99fafd205e455"
__proto__: EventEmitter

And when I call discoverDescriptors on this characteristic:

Descriptor {
  _noble:
   Noble {
     initialized: true,
     address: '5c:f3:70:94:4b:01',
     _state: 'poweredOn',
     _bindings:
      NobleBindings {
        _state: 'poweredOn',
        _addresses: [Object],
        _addresseTypes: [Object],
        _connectable: [Object],
        _pendingConnectionUuid: null,
        _connectionQueue: [],
        _handles: [Object],
        _gatts: [Object],
        _aclStreams: [Object],
        _signalings: [Object],
        _hci: [Hci],
        _gap: [Gap],
        _events: [Object],
        _eventsCount: 21,
        onSigIntBinded: [Function: bound ],
        _scanServiceUuids: [] },
     _peripherals:
      { '574d3263441d': [Peripheral], '3481f4141bf0': [Peripheral] },
     _services: { '574d3263441d': {}, '3481f4141bf0': [Object] },
     _characteristics: { '574d3263441d': {}, '3481f4141bf0': [Object] },
     _descriptors: { '574d3263441d': {}, '3481f4141bf0': [Object] },
     _discoveredPeripheralUUids: [ '574d3263441d', '3481f4141bf0' ],
     _events:
      [Object: null prototype] {
        warning: [Function: bound ],
        newListener: [Function: bound ],
        stateChange: [Function],
        discover: [Function] },
     _eventsCount: 4,
     _allowDuplicates: undefined },
  _peripheralId: '3481f4141bf0',
  _serviceUuid: '49535343fe7d4ae58fa99fafd205e455',
  _characteristicUuid: '495353431e4d4bd9ba6123c647249616',
  uuid: '2902',
  name: 'Client Characteristic Configuration',
  type:
   'org.bluetooth.descriptor.gatt.client_characteristic_configuration' }

I'm not sure how to interpret the data that's passed back in order to debug this issue further.


问:
How to deploy two projects into one Web app - Deploy using sub directory
I have two projects, JavaScript and Angular. I want to have both on the same web app on azure.

The URL will be like:

First Project: www.wholeproject.com

Second Project: ww.wwholeproject.com/secondproject

The projects are on the same git repository.

I created Azure web app and linked it to the first project, so deploying the first one is working and I can see it online. However, I can't manage to publish the second (angular) project having the subdirectory ../secondproject.

I tried adding the .deployment file to the main project, but I couldn't figure out how to proceed.

答:
You should be able to accomplish this on your web app by using virtual directories.

The below two blogs highlight how to setup virtual directories with different URLs and how to deploy to each directory.

http://jaliyaudagedara.blogspot.com/2016/07/deploy-aspnet-core-10-web-application.html

http://chamindac.blogspot.com/2017/06/deploying-web-apps-to-azure-virtual.html

Please let us know if you have any questions or concerns regarding this topic.


问:
Java threadpool oversubscription
I have mainly CPU intensive operation which is running on a thread pool.
Operation however has certain amount of waiting foe external events which doesn't happen uniformly in time.
Since in Java, as far as I know, there is not a thread pool implementation which automatically sizes its number of threads based on observed task throughput (as in Microsoft's CLR 4), is there at least a way to manually tell to thread pool to increase its size when a blocking operation starts and to decrease when it ends?

For example with 8 cores, pool size is 8.
  If operation is 100% CPU bound, just use this fixed pool.
  If there is some blocking operation, one should be able to do this:

```<code>pool.increase();
waitForSpecialKeyPress();
pool.decrease();
</code>```

Here is how it is being done in Microsoft's C++ Async library: Use Oversubscription to Offset Latency

答:
Java 7's ForkJoinPool has a ManagedBlocker, which can be used to keep the pool informed about blocked threads, so that it can schedule more threads if necessary.

EDIT: I forgot to mention, the classes are also available for Java 6 as jsr166y.

Title: Java threadpool oversubscription

Body:
I have mainly CPU intensive operation which is running on a thread pool.
Operation however has certain amount of waiting foe external events which doesn't happen uniformly in time.
Since in Java, as far as I know, there is not a thread pool implementation which automatically sizes its number of threads based on observed task throughput (as in Microsoft's CLR 4), is there at least a way to manually tell to thread pool to increase its size when a blocking operation starts and to decrease when it ends?

For example with 8 cores, pool size is 8.
  If operation is 100% CPU bound, just use this fixed pool.
  If there is some blocking operation, one should be able to do this:

pool.increase();
waitForSpecialKeyPress();
pool.decrease();

Here is how it is being done in Microsoft's C++ Async library: Use Oversubscription to Offset Latency


问:
Simulate a time interval
I am working on a homework project where I need to simulate a time interval (4 minutes specifically) with the python time library.

I have to use the time.time() function, so I tried with that function but It only returns the seconds since the epoch.

答: You can use time.sleep(), which sleeps for the given amount of seconds. So time.sleep(5) would create a 5 second pause.</p>

Title: Simulate a time interval


问:
How to use COUNT with a GROUP BY on two fields
I am trying to write a query where all buildings will show up for each date, and zeros are listed for the ones that do not exist. Below are an example table and data for my example.

```<code>CREATE TABLE IF NOT EXISTS `table1` (
  `id` int(6) unsigned NOT NULL,
  `buildings` char(3) NOT NULL,
  `date` varchar(50) NOT NULL,
  `sold` char(1) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `table1` (`id`, `buildings`, `date`, `sold`) VALUES
  ('1', '1', '2019-04-22 07:40:08','X'),
  ('2', '1', '2019-04-22 07:41:15',''),
  ('3', '1', '2019-04-22 07:42:10','X'),
  ('4', '3', '2019-04-22 07:43:50','X'),
  ('5', '1', '2019-04-22 07:44:27',''),
  ('6', '2', '2019-05-21 06:43:17','X'),
  ('7', '2', '2019-05-21 07:36:17',''),
  ('8', '1', '2019-05-21 06:32:22','X'),
  ('9', '3', '2019-05-21 07:43:50',''),
  ('10', '2', '2019-05-21 07:44:27','X');
</code>```

And the SQL query that I am using as of now is listed below. The CONCAT and MID that is used to build the first column are getting the year and week of the year to create a 4 digit code per week.

```<code>SELECT CONCAT(MID(date,3,2),
           LPAD(WEEK(CONCAT(MID(date,1,4),'-',
           MID(date,6,2),'-',
           MID(date,10,2))),2,0)) AS YearWeek,
       buildings,
       COUNT(sold) AS count
FROM table1
WHERE sold = 'X'
GROUP BY CONCAT(MID(date,3,2),
           LPAD(WEEK(CONCAT(MID(date,1,4),'-',
           MID(date,6,2),'-',
           MID(date,10,2))),2,0)),
         buildings
</code>```

My issue with this is I get the data as below

```<code>YearWeek    buildings   count
1913        1           2
1913        3           1
1917        1           1
1917        2           2
</code>```

When in fact I would like the data to look like the below so I can graph it.

```<code>YearWeek    buildings   count
1913        1           2
1913        2           0
1913        3           1
1917        1           1
1917        2           2
1917        3           0
</code>```

To achieve this I have tried to do a left join to a subquery
(select distinct building as buildings from table1) but this is not working, and I think it is due to the fact that I am grouping by YearWeek and then building instead of the other way around.'

Any help on this query would be much appreciated!

答:
You can get the results you want by taking a CROSS JOIN of the distinct YearWeek and buildings values to get all the possible combinations of each, and then using a LEFT JOIN to the table to get the count of each type of buildings sold that week. For example:

```<code>SELECT yw.YearWeek,
       b.buildings,
       COALESCE(SUM(t.sold = 'X'), 0) AS count
FROM (SELECT DISTINCT buildings
      FROM table1) b
CROSS JOIN (SELECT DISTINCT RIGHT(YEARWEEK(date),4) AS YearWeek
            FROM table1) yw
LEFT JOIN table1 t ON t.buildings = b.buildings AND RIGHT(YEARWEEK(t.date),4) = yw.YearWeek
GROUP BY yw.YearWeek, b.buildings
</code>```

Output:

```<code>YearWeek    buildings   count
1916        1           2
1916        2           0
1916        3           1
1920        1           1
1920        2           2
1920        3           0
</code>```

Demo on dbfiddle

Note I have used MySQL's inbuilt YEARWEEK function to simplify the query, you can simply substitute your formula if that is not suitable.

Body:
I am trying to write a query where all buildings will show up for each date, and zeros are listed for the ones that do not exist. Below are an example table and data for my example.

CREATE TABLE IF NOT EXISTS `table1` (
  `id` int(6) unsigned NOT NULL,
  `buildings` char(3) NOT NULL,
  `date` varchar(50) NOT NULL,
  `sold` char(1) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `table1` (`id`, `buildings`, `date`, `sold`) VALUES
  ('1', '1', '2019-04-22 07:40:08','X'),
  ('2', '1', '2019-04-22 07:41:15',''),
  ('3', '1', '2019-04-22 07:42:10','X'),
  ('4', '3', '2019-04-22 07:43:50','X'),
  ('5', '1', '2019-04-22 07:44:27',''),
  ('6', '2', '2019-05-21 06:43:17','X'),
  ('7', '2', '2019-05-21 07:36:17',''),
  ('8', '1', '2019-05-21 06:32:22','X'),
  ('9', '3', '2019-05-21 07:43:50',''),
  ('10', '2', '2019-05-21 07:44:27','X');

And the SQL query that I am using as of now is listed below. The CONCAT and MID that is used to build the first column are getting the year and week of the year to create a 4 digit code per week.

SELECT CONCAT(MID(date,3,2),
           LPAD(WEEK(CONCAT(MID(date,1,4),'-',
           MID(date,6,2),'-',
           MID(date,10,2))),2,0)) AS YearWeek,
       buildings,
       COUNT(sold) AS count
FROM table1
WHERE sold = 'X'
GROUP BY CONCAT(MID(date,3,2),
           LPAD(WEEK(CONCAT(MID(date,1,4),'-',
           MID(date,6,2),'-',
           MID(date,10,2))),2,0)),
         buildings

My issue with this is I get the data as below

YearWeek    buildings   count
1913        1           2
1913        3           1
1917        1           1
1917        2           2

When in fact I would like the data to look like the below so I can graph it.

YearWeek    buildings   count
1913        1           2
1913        2           0
1913        3           1
1917        1           1
1917        2           2
1917        3           0

To achieve this I have tried to do a left join to a subquery
(select distinct building as buildings from table1) but this is not working, and I think it is due to the fact that I am grouping by YearWeek and then building instead of the other way around.'

Any help on this query would be much appreciated!

Body:
You can get the results you want by taking a CROSS JOIN of the distinct YearWeek and buildings values to get all the possible combinations of each, and then using a LEFT JOIN to the table to get the count of each type of buildings sold that week. For example:

SELECT yw.YearWeek,
       b.buildings,
       COALESCE(SUM(t.sold = 'X'), 0) AS count
FROM (SELECT DISTINCT buildings
      FROM table1) b
CROSS JOIN (SELECT DISTINCT RIGHT(YEARWEEK(date),4) AS YearWeek
            FROM table1) yw
LEFT JOIN table1 t ON t.buildings = b.buildings AND RIGHT(YEARWEEK(t.date),4) = yw.YearWeek
GROUP BY yw.YearWeek, b.buildings

Output:

YearWeek    buildings   count
1916        1           2
1916        2           0
1916        3           1
1920        1           1
1920        2           2
1920        3           0

Demo on dbfiddle

Note I have used MySQL's inbuilt YEARWEEK function to simplify the query, you can simply substitute your formula if that is not suitable.


问:
Function for getting the ordinal of a number?
I was about to write a C++ function doing the following:

```<code>1 ---> "1st"
2 ---> "1nd"
3 ---> "3rd"
...
17657 --> "17657th"
...
</code>```

i.e. produces the ordinal extension string for that number (it doesn't have to do an itoa() of the number itself). But then I thought "surely something in the standard library or boost does this already?"

Notes:

I know it's not hard to write this, there's an implementation in Python right here on SO, I just don't want to duplicate code.

I need this in English, obviously. A multi-language version would be nice for political-correctness considerations, not more than that...

答:
```<code>// Returns numbers with ordinal suffix as string
// Based on https://stackoverflow.com/questions/3109978/display-numbers-with-ordinal-suffix-in-php
std::string NumberToOrdinal(size_t number) {
  std::string suffix = "th";
  if (number % 100 < 11 || number % 100 > 13) {
    switch (number % 10) {
      case 1:
        suffix = "st";
        break;
      case 2:
        suffix = "nd";
        break;
      case 3:
        suffix = "rd";
        break;
    }
  }
  return std::to_string(number) + suffix;
}
</code>```

Body:
I was about to write a C++ function doing the following:

1 ---> "1st"
2 ---> "1nd"
3 ---> "3rd"
...
17657 --> "17657th"
...

i.e. produces the ordinal extension string for that number (it doesn't have to do an itoa() of the number itself). But then I thought "surely something in the standard library or boost does this already?"

Notes:

I know it's not hard to write this, there's an implementation in Python right here on SO, I just don't want to duplicate code.

I need this in English, obviously. A multi-language version would be nice for political-correctness considerations, not more than that...


问:
I need to do validations for a form in angular

import {  FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
   ngOnInit() {

    this.createFormControls();
    this.createForm();
  }
  createFormControls(){

    this.firstName = new FormControl('',Validators.required);
    this.lastName= new FormControl('',Validators.required);
    this.Address= new FormControl('',Validators.required);
    this.age = new FormControl('',Validators.required);
    this.phnumer= new FormControl('',Validators.required);
  }
  createForm(){
    this.form = new FormGroup({
      name: new FormGroup({
      firstName:this.firstName,
      lastName: this.lastName,
      Address:this.Address,
      age:this.age,
      phnumer:this.phnumer
      }),
    });
  }```

I need to validate a form in angular6, I have 5 fields but and need to validate without submit button, I have to validate them in same inline. this is my code in ts file now i have implement validation in html page but validation  should be shown error msg in same line instead of clicking submit button

答:
You can use the built in validators in Angular to achieve this (https://angular.io/guide/form-validation#built-in-validators)

In your component, create a form group and a getter method to access the form control through the get method in the parent group. I'll provide an example for a single field.

```<code>createForm(){
    this.form = new FormGroup({
        firstName:  new FormControl('', Validators.required)
    });
}

get firstName() {
    return this.form.get('firstName');
}
</code>```

In your HTML you can use conditional expressions along with the validation attributes in order to display the errors.

```<code><form [formGroup]="form">
    <label for="firstName">First Name
        <input id="firstName" formControlName="firstName">
        <div *ngIf="firstName.invalid && (firstName.dirty || firstName.touched)">
            <div *ngIf="firstName.errors.required">
                First Name is required.
            </div>
        </div>
    </label>
</form>
</code>```

Body:
import {  FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
   ngOnInit() {

    this.createFormControls();
    this.createForm();
  }
  createFormControls(){

    this.firstName = new FormControl('',Validators.required);
    this.lastName= new FormControl('',Validators.required);
    this.Address= new FormControl('',Validators.required);
    this.age = new FormControl('',Validators.required);
    this.phnumer= new FormControl('',Validators.required);
  }
  createForm(){
    this.form = new FormGroup({
      name: new FormGroup({
      firstName:this.firstName,
      lastName: this.lastName,
      Address:this.Address,
      age:this.age,
      phnumer:this.phnumer
      }),
    });
  }

I need to validate a form in angular6, I have 5 fields but and need to validate without submit button, I have to validate them in same inline. this is my code in ts file now i have implement validation in html page but validation  should be shown error msg in same line instead of clicking submit button

Body:
You can use the built in validators in Angular to achieve this (https://angular.io/guide/form-validation#built-in-validators)

In your component, create a form group and a getter method to access the form control through the get method in the parent group. I'll provide an example for a single field.

createForm(){
    this.form = new FormGroup({
        firstName:  new FormControl('', Validators.required)
    });
}

get firstName() {
    return this.form.get('firstName');
}

In your HTML you can use conditional expressions along with the validation attributes in order to display the errors.

<form [formGroup]="form">
    <label for="firstName">First Name
        <input id="firstName" formControlName="firstName">
        <div *ngIf="firstName.invalid && (firstName.dirty || firstName.touched)">
            <div *ngIf="firstName.errors.required">
                First Name is required.
            </div>
        </div>
    </label>
</form>


问:
How to fix background image with drawable xml file on Android?
How do I make this picture in android drawable.xml format?</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap android:src="@drawable/wallpaper"></bitmap>
    </item>
</layer-list>
</code>```

答:
The drawable will expand to fit your container. Notice that I didn't modify the bottom inset (android:bottom) so that the curve remains flush with the bottom of your container. You can modify the left, right, top and bottom attributes to get your desired curve.

rounded_header.xml

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:top="-100dp"
        android:left="-400dp"
        android:right="-400dp">
        <shape android:shape="oval">
            <gradient
                android:startColor="#F07B26"
                android:endColor="#F8BA4C"/>
        </shape>
    </item>
</layer-list>
</code>```

layout.xml

```<code><View
    android:id="@+id/header"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/rounded_header"/>
</code>```

Result

Body:
How do I make this picture in android drawable.xml format?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap android:src="@drawable/wallpaper"></bitmap>
    </item>
</layer-list>

Body:
The drawable will expand to fit your container. Notice that I didn't modify the bottom inset (android:bottom) so that the curve remains flush with the bottom of your container. You can modify the left, right, top and bottom attributes to get your desired curve.

rounded_header.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:top="-100dp"
        android:left="-400dp"
        android:right="-400dp">
        <shape android:shape="oval">
            <gradient
                android:startColor="#F07B26"
                android:endColor="#F8BA4C"/>
        </shape>
    </item>
</layer-list>

layout.xml

<View
    android:id="@+id/header"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/rounded_header"/>

Result


答:
Are you trying to simulate time.sleep()?

Without giving the answer away completely, consider the following usage of time.time():

```<code>>>> import time
>>> start = time.time()
>>> time.time() - start
12.311654090881348
</code>```

Between the time when the second and third commands were executed, it took me ~12.3 seconds.

Title: Simulate a time interval

Body:
I am working on a homework project where I need to simulate a time interval (4 minutes specifically) with the python time library.

I have to use the time.time() function, so I tried with that function but It only returns the seconds since the epoch.

Body:
Are you trying to simulate time.sleep()?

Without giving the answer away completely, consider the following usage of time.time():

>>> import time
>>> start = time.time()
>>> time.time() - start
12.311654090881348

Between the time when the second and third commands were executed, it took me ~12.3 seconds.


问:
jquery change() binding doesn't trigger on first change (ASP.NET Validation)
I have a form with a number of different elements.  In the Ready function I'm binding the "change" for these like this:

```<code>$(function(){
    $('#someControlID').change(nameOfHandlerFunction);
    .... (similar code for all controls)
}
</code>```

It works as expected for drop-down lists, but for textboxes, textareas, and checkboxes, the handler function doesn't get called until the second time I change the value.  I've placed a debugger statement in the handler to double check. If I focus a textbox, modify text, and leave focus, I'll have to do that a second time to get the handler to run.  Any idea what might cause this behaviour?

Edit: this was observed in IE 8.

Thanks!

答:
ASP.NET was the culprit.  I didn't mention it in my question because I didn't think it was relevant, but there you go.  The controls in question had associated ASP.NET Validator controls linked to them.  On examination, the control elements' "onchange" was set to a function called "ValidatorOnChange".  Somehow, invoking jQuery's "change()" on these controls was causing the undesirable behaviour described above.

I worked around the problem by using my own event handler - this is probably not an option for everybody but I had this function available in a loaded library so I used it and the page works now.

The new code looks like:

```<code>var el = document.getElementById('someControlId');
el.onchange = appendFunction(el.onchange, nameOfHandlerFunction);
</code>```

Here's the method itself in case this helps anybody else.

```<code>function appendFunction(fn1, fn2) {
    var result;

    // if neither arguments are functions,  return an empty function.
    // if only one argument is a function, return that.
    if (typeof (fn1) !== 'function' && typeof (fn2) !== 'function') {
        result = function () { return; };
    }
    else if (typeof (fn1) === 'function' && typeof (fn2) !== 'function') {
        result = fn1;
    }
    else if (typeof (fn1) !== 'function' && typeof (fn2) === 'function') {
        result = fn2;
    }
    else {
        result = function () {
            fn1();
            fn2();
        }
    }
    return result;
}
</code>```

Body:
I have a form with a number of different elements.  In the Ready function I'm binding the "change" for these like this:

$(function(){
    $('#someControlID').change(nameOfHandlerFunction);
    .... (similar code for all controls)
}

It works as expected for drop-down lists, but for textboxes, textareas, and checkboxes, the handler function doesn't get called until the second time I change the value.  I've placed a debugger statement in the handler to double check. If I focus a textbox, modify text, and leave focus, I'll have to do that a second time to get the handler to run.  Any idea what might cause this behaviour?

Edit: this was observed in IE 8.

Thanks!

Body:
ASP.NET was the culprit.  I didn't mention it in my question because I didn't think it was relevant, but there you go.  The controls in question had associated ASP.NET Validator controls linked to them.  On examination, the control elements' "onchange" was set to a function called "ValidatorOnChange".  Somehow, invoking jQuery's "change()" on these controls was causing the undesirable behaviour described above.

I worked around the problem by using my own event handler - this is probably not an option for everybody but I had this function available in a loaded library so I used it and the page works now.

The new code looks like:

var el = document.getElementById('someControlId');
el.onchange = appendFunction(el.onchange, nameOfHandlerFunction);

Here's the method itself in case this helps anybody else.

function appendFunction(fn1, fn2) {
    var result;

    // if neither arguments are functions,  return an empty function.
    // if only one argument is a function, return that.
    if (typeof (fn1) !== 'function' && typeof (fn2) !== 'function') {
        result = function () { return; };
    }
    else if (typeof (fn1) === 'function' && typeof (fn2) !== 'function') {
        result = fn1;
    }
    else if (typeof (fn1) !== 'function' && typeof (fn2) === 'function') {
        result = fn2;
    }
    else {
        result = function () {
            fn1();
            fn2();
        }
    }
    return result;
}


问:
lineChartView findViewById in fragment
i have some errors when i try to add chart in fragment.
i'm trying to make a chart in a fragment which will refer to the LineChartView element which I have created in XML for the Fragment.

I use hellochart and I read the tutorial. explained there using activity to implement it. how do i implement it to fragment?

LineChartView lineChartView;
String[] axisData = {"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept",
            "Oct", "Nov", "Dec"};
int[] yAxisData = {50, 20, 15, 30, 20, 60, 15, 40, 45, 10, 90, 18};
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        lineChartView = findViewById(R.id.chart);
        List yAxisValues = new ArrayList();
        List axisValues = new ArrayList();
        Line line = new Line(yAxisValues).setColor(Color.parseColor("#9C27B0"));
        for (int i = 0; i < axisData.length; i++) {
            axisValues.add(i, new AxisValue(i).setLabel(axisData[i]));
        }
        for (int i = 0; i < yAxisData.length; i++) {
            yAxisValues.add(new PointValue(i, yAxisData[i]));
        }
        List lines = new ArrayList();
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);
        Axis axis = new Axis();
        axis.setValues(axisValues);
        axis.setTextSize(16);
        axis.setTextColor(Color.parseColor("#03A9F4"));
        data.setAxisXBottom(axis);
        Axis yAxis = new Axis();
        yAxis.setName("Sales in millions");
        yAxis.setTextColor(Color.parseColor("#03A9F4"));
        yAxis.setTextSize(16);
        data.setAxisYLeft(yAxis);
        lineChartView.setLineChartData(data);
        Viewport viewport = new Viewport(lineChartView.getMaximumViewport());
        viewport.top = 110;
        lineChartView.setMaximumViewport(viewport);
        lineChartView.setCurrentViewport(viewport);
        return inflater.inflate(R.layout.fragment_events, container, false);
    }
```

The findViewById method has an error on it which states that the method is cannot resolve.

答:
Change onCreateView on this and tell me if it works.
First declare View

```<code>private View paramView;

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {

  paramView = inflater.inflate(R.layout.fragment_events, container, false);
  lineChartView = paramView.findViewById(R.id.chart);
  // Here comes all your code
  return paramView;
}
</code>```

Title: lineChartView findViewById in fragment

Body:
i have some errors when i try to add chart in fragment.
i'm trying to make a chart in a fragment which will refer to the LineChartView element which I have created in XML for the Fragment.

I use hellochart and I read the tutorial. explained there using activity to implement it. how do i implement it to fragment?

LineChartView lineChartView;
String[] axisData = {"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept",
            "Oct", "Nov", "Dec"};
int[] yAxisData = {50, 20, 15, 30, 20, 60, 15, 40, 45, 10, 90, 18};
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        lineChartView = findViewById(R.id.chart);
        List yAxisValues = new ArrayList();
        List axisValues = new ArrayList();
        Line line = new Line(yAxisValues).setColor(Color.parseColor("#9C27B0"));
        for (int i = 0; i < axisData.length; i++) {
            axisValues.add(i, new AxisValue(i).setLabel(axisData[i]));
        }
        for (int i = 0; i < yAxisData.length; i++) {
            yAxisValues.add(new PointValue(i, yAxisData[i]));
        }
        List lines = new ArrayList();
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);
        Axis axis = new Axis();
        axis.setValues(axisValues);
        axis.setTextSize(16);
        axis.setTextColor(Color.parseColor("#03A9F4"));
        data.setAxisXBottom(axis);
        Axis yAxis = new Axis();
        yAxis.setName("Sales in millions");
        yAxis.setTextColor(Color.parseColor("#03A9F4"));
        yAxis.setTextSize(16);
        data.setAxisYLeft(yAxis);
        lineChartView.setLineChartData(data);
        Viewport viewport = new Viewport(lineChartView.getMaximumViewport());
        viewport.top = 110;
        lineChartView.setMaximumViewport(viewport);
        lineChartView.setCurrentViewport(viewport);
        return inflater.inflate(R.layout.fragment_events, container, false);
    }

The findViewById method has an error on it which states that the method is cannot resolve.

Body:
Change onCreateView on this and tell me if it works.
First declare View

private View paramView;

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {

  paramView = inflater.inflate(R.layout.fragment_events, container, false);
  lineChartView = paramView.findViewById(R.id.chart);
  // Here comes all your code
  return paramView;
}


问:
Merge Overlapping Time Intervals based on Hierarchy in SQL
I am trying to solve a problem where i want to merge overlapping intervals for a given column id, but i also want to merge them based on hierarchy/priority. I have start_time and stop_time for each interval and each interval has a hierarchy/priority associated with it.

These are the following columns in the table:

```<code>id, start_time, stop_time, priority
</code>```

I was able to solve the problem where i do not have take into account the priority, but i am struggling with this one.

```<code>Red colour: p1 (priority 1)
Blue Colour: p2 (priority 2)
Green colour: p3 (priority 3)
</code>```

Note that in the example input below we will have 9 rows having same id, and the output will have 6 rows. Please note that for some id's might have only some of the priority values or just one, the solution should take care of that.

expected input and output:

答:
Below is for BigQuery Standard SQL

```<code>#standardSQL
WITH check_times AS (
  SELECT id, start_time AS time FROM `project.dataset.table` UNION DISTINCT
  SELECT id, stop_time AS time FROM `project.dataset.table`
), distinct_intervals AS (
  SELECT id, time AS start_time, LEAD(time) OVER(PARTITION BY id ORDER BY time) stop_time
  FROM check_times
), deduped_intervals AS (
  SELECT a.id, a.start_time, a.stop_time, MIN(priority) priority
  FROM distinct_intervals a
  JOIN `project.dataset.table` b
  ON a.id = b.id
  AND a.start_time BETWEEN b.start_time AND b.stop_time
  AND a.stop_time BETWEEN b.start_time AND b.stop_time
  GROUP BY a.id, a.start_time, a.stop_time
), combined_intervals AS (
  SELECT id, MIN(start_time) start_time, MAX(stop_time) stop_time, ANY_VALUE(priority) priority
  FROM (
    SELECT id, start_time, stop_time, priority, COUNTIF(flag) OVER(PARTITION BY id ORDER BY start_time) grp
    FROM (
      SELECT id, start_time, stop_time, priority,
        start_time != IFNULL(LAG(stop_time) OVER(PARTITION BY id ORDER BY start_time), start_time) OR
        priority != IFNULL(LAG(priority) OVER(PARTITION BY id ORDER BY start_time), -1) flag
      FROM deduped_intervals
    )
  )
  GROUP BY id, grp
)
SELECT *
FROM combined_intervals
-- ORDER BY id, start_time
</code>```

If to apply to sample data from your question  - result is

Can you also share a solution where we merge intervals based on just id and no priority column

I just simply slightly adjusted above query to ignore priority

```<code>#standardSQL
WITH check_times AS (
  SELECT id, start_time AS TIME FROM `project.dataset.table` UNION DISTINCT
  SELECT id, stop_time AS TIME FROM `project.dataset.table`
), distinct_intervals AS (
  SELECT id, TIME AS start_time, LEAD(TIME) OVER(PARTITION BY id ORDER BY TIME) stop_time
  FROM check_times
), deduped_intervals AS (
  SELECT a.id, a.start_time, a.stop_time
  FROM distinct_intervals a
  JOIN `project.dataset.table` b
  ON a.id = b.id
  AND a.start_time BETWEEN b.start_time AND b.stop_time
  AND a.stop_time BETWEEN b.start_time AND b.stop_time
  GROUP BY a.id, a.start_time, a.stop_time
), combined_intervals AS (
  SELECT id, MIN(start_time) start_time, MAX(stop_time) stop_time
  FROM (
    SELECT id, start_time, stop_time, COUNTIF(flag) OVER(PARTITION BY id ORDER BY start_time) grp
    FROM (
      SELECT id, start_time, stop_time,
        start_time != IFNULL(LAG(stop_time) OVER(PARTITION BY id ORDER BY start_time), start_time) flag
      FROM deduped_intervals
    )
  )
  GROUP BY id, grp
)
SELECT *
FROM combined_intervals
-- ORDER BY id, start_time
</code>```

with result

```<code>Row id  start_time  stop_time
1   1   0           36
2   1   41          47
</code>```

Body:
I am trying to solve a problem where i want to merge overlapping intervals for a given column id, but i also want to merge them based on hierarchy/priority. I have start_time and stop_time for each interval and each interval has a hierarchy/priority associated with it.

These are the following columns in the table:

id, start_time, stop_time, priority

I was able to solve the problem where i do not have take into account the priority, but i am struggling with this one.

Red colour: p1 (priority 1)
Blue Colour: p2 (priority 2)
Green colour: p3 (priority 3)

Note that in the example input below we will have 9 rows having same id, and the output will have 6 rows. Please note that for some id's might have only some of the priority values or just one, the solution should take care of that.

expected input and output:

Body:
Below is for BigQuery Standard SQL

#standardSQL
WITH check_times AS (
  SELECT id, start_time AS time FROM `project.dataset.table` UNION DISTINCT
  SELECT id, stop_time AS time FROM `project.dataset.table`
), distinct_intervals AS (
  SELECT id, time AS start_time, LEAD(time) OVER(PARTITION BY id ORDER BY time) stop_time
  FROM check_times
), deduped_intervals AS (
  SELECT a.id, a.start_time, a.stop_time, MIN(priority) priority
  FROM distinct_intervals a
  JOIN `project.dataset.table` b
  ON a.id = b.id
  AND a.start_time BETWEEN b.start_time AND b.stop_time
  AND a.stop_time BETWEEN b.start_time AND b.stop_time
  GROUP BY a.id, a.start_time, a.stop_time
), combined_intervals AS (
  SELECT id, MIN(start_time) start_time, MAX(stop_time) stop_time, ANY_VALUE(priority) priority
  FROM (
    SELECT id, start_time, stop_time, priority, COUNTIF(flag) OVER(PARTITION BY id ORDER BY start_time) grp
    FROM (
      SELECT id, start_time, stop_time, priority,
        start_time != IFNULL(LAG(stop_time) OVER(PARTITION BY id ORDER BY start_time), start_time) OR
        priority != IFNULL(LAG(priority) OVER(PARTITION BY id ORDER BY start_time), -1) flag
      FROM deduped_intervals
    )
  )
  GROUP BY id, grp
)
SELECT *
FROM combined_intervals
-- ORDER BY id, start_time

If to apply to sample data from your question  - result is

Can you also share a solution where we merge intervals based on just id and no priority column

I just simply slightly adjusted above query to ignore priority

#standardSQL
WITH check_times AS (
  SELECT id, start_time AS TIME FROM `project.dataset.table` UNION DISTINCT
  SELECT id, stop_time AS TIME FROM `project.dataset.table`
), distinct_intervals AS (
  SELECT id, TIME AS start_time, LEAD(TIME) OVER(PARTITION BY id ORDER BY TIME) stop_time
  FROM check_times
), deduped_intervals AS (
  SELECT a.id, a.start_time, a.stop_time
  FROM distinct_intervals a
  JOIN `project.dataset.table` b
  ON a.id = b.id
  AND a.start_time BETWEEN b.start_time AND b.stop_time
  AND a.stop_time BETWEEN b.start_time AND b.stop_time
  GROUP BY a.id, a.start_time, a.stop_time
), combined_intervals AS (
  SELECT id, MIN(start_time) start_time, MAX(stop_time) stop_time
  FROM (
    SELECT id, start_time, stop_time, COUNTIF(flag) OVER(PARTITION BY id ORDER BY start_time) grp
    FROM (
      SELECT id, start_time, stop_time,
        start_time != IFNULL(LAG(stop_time) OVER(PARTITION BY id ORDER BY start_time), start_time) flag
      FROM deduped_intervals
    )
  )
  GROUP BY id, grp
)
SELECT *
FROM combined_intervals
-- ORDER BY id, start_time

with result

Row id  start_time  stop_time
1   1   0           36
2   1   41          47