问:
How to call a page from custom AppBar using onPressed?
I have created a custom appBar in flutter MyApplicationBar.dart
I am including every page? now how to call Login Page   onPressed: () function</p>

```<code>  class MyApplicationBar extends AppBar {
  MyApplicationBar({Key key, Widget title})
    : super(key: key, title:title, actions:<Widget>[
    IconButton(
        icon: new Icon(Icons.lock),
        tooltip: 'Login',
        onPressed: () {
          print('sssss');

        },
      ),
    IconButton(
              icon: const Icon(Icons.supervised_user_circle),
              tooltip: 'Accounts',
              onPressed: () {

              },
            ),
  ]);

}
</code>```

答:
There are more than one methods to navigate to new page
1. Easy way is Navigator.of(context).pushNamed(routeName, arguments: arguments)

but the best approach is to use because it is very clean and increase code readability.
And this is how professional do Navigation.
2. using  onGenerateRoute in your MaterialApp Widget

```<code>return MaterialApp(
      // remove debug banner
      debugShowCheckedModeBanner: false,
      title: APP_NAME,
      home: Home(),
      onGenerateRoute: (RouteSettings settings) {
        switch (settings.name) {
        case "abc":
              return CupertinoPageRoute(
                builder: (BuildContext context) {
                  return VideoTopics();
                },
                settings: settings);
        break;
}});

</code>```

Now to navigate from any page to abc page just use this line of code

```<code>   Navigator.of(context).pushNamed("abc");
</code>```

make sure the text you are passing in Navigator is same to as in onGeneratedRoute
so it is advisiable to use constants for such things

Body:
I have created a custom appBar in flutter MyApplicationBar.dart
I am including every page? now how to call Login Page   onPressed: () function

  class MyApplicationBar extends AppBar {
  MyApplicationBar({Key key, Widget title})
    : super(key: key, title:title, actions:<Widget>[
    IconButton(
        icon: new Icon(Icons.lock),
        tooltip: 'Login',
        onPressed: () {
          print('sssss');

        },
      ),
    IconButton(
              icon: const Icon(Icons.supervised_user_circle),
              tooltip: 'Accounts',
              onPressed: () {

              },
            ),
  ]);

}

Body:
There are more than one methods to navigate to new page
1. Easy way is Navigator.of(context).pushNamed(routeName, arguments: arguments)

but the best approach is to use because it is very clean and increase code readability.
And this is how professional do Navigation.
2. using  onGenerateRoute in your MaterialApp Widget

return MaterialApp(
      // remove debug banner
      debugShowCheckedModeBanner: false,
      title: APP_NAME,
      home: Home(),
      onGenerateRoute: (RouteSettings settings) {
        switch (settings.name) {
        case "abc":
              return CupertinoPageRoute(
                builder: (BuildContext context) {
                  return VideoTopics();
                },
                settings: settings);
        break;
}});

Now to navigate from any page to abc page just use this line of code

   Navigator.of(context).pushNamed("abc");

make sure the text you are passing in Navigator is same to as in onGeneratedRoute
so it is advisiable to use constants for such things


来源: stackexchange

问:
maven plug-ins specified in pom.xml don't execute
I'm building my Java project and have specified 2 maven plug-ins, maven-jar-plugin and maven-dependency-plugin. I execute mvn clean package from the command line. The source code is compiled successfully; however, I never see the dependency plugin executing. In addition, when doing mvn --debug clean package I don't see the jar-plugin executing with my specified parameters.

I'm looking for some assistance as to why these plugins are not running when doing mvn clean package.

A snippet of the pom.xml:

FYI, I did not include all of the dependencies and the groupId, main class information was changed to protect the innocent. However, the structure of the pom.xml is intact.

```<code>`<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mygroupId</groupId>
  <artifactId>ssmgr</artifactId>
  <version>0.1</version>

  <name>ssmgr</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <mainClass>com.myclass.App</mainClass>
    <dependenciesDirectory>libs</dependenciesDirectory>
  </properties>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>3.1.1</version>
          <executions>
            <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                <outputDirectory>${project.build.directory}/${dependenciesDirectory}</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>
                <!-- <overWriteIfNewer>true</overWriteIfNewer> -->
                <!--<includeScope>runtime</includeScope>
                <excludeScope>test</excludeScope>
                <useBaseVersion>false</useBaseVersion> -->
              </configuration>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.2.0</version>
          <executions>
            <execution>
              <id>create-jar</id>
              <configuration>
                <archive>
                  <manifest>
                    <addClasspath>true</addClasspath>
                    <classpathPrefix>${dependenciesDirectory}</classpathPrefix>
                    <mainClass>com.myclass.App</mainClass>
                  </manifest>
                </archive>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
  <dependencies>
    <dependency>
    </dependency>
  </dependencies>
</project>
</code>```

答: I was able to resolve this issue. I removed the plugins out from under the  stanza. In addition, for the jar-plugin I removed the  and  stanzas. With these removed the jar was created properly and the manifest file was generated properly.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm building my Java project and have specified 2 maven plug-ins, maven-jar-plugin and maven-dependency-plugin. I execute mvn clean package from the command line. The source code is compiled successfully; however, I never see the dependency plugin executing. In addition, when doing mvn --debug clean package I don't see the jar-plugin executing with my specified parameters.

I'm looking for some assistance as to why these plugins are not running when doing mvn clean package.

A snippet of the pom.xml:

FYI, I did not include all of the dependencies and the groupId, main class information was changed to protect the innocent. However, the structure of the pom.xml is intact.

`<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mygroupId</groupId>
  <artifactId>ssmgr</artifactId>
  <version>0.1</version>

  <name>ssmgr</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <mainClass>com.myclass.App</mainClass>
    <dependenciesDirectory>libs</dependenciesDirectory>
  </properties>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>3.1.1</version>
          <executions>
            <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                <outputDirectory>${project.build.directory}/${dependenciesDirectory}</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>

              </configuration>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.2.0</version>
          <executions>
            <execution>
              <id>create-jar</id>
              <configuration>
                <archive>
                  <manifest>
                    <addClasspath>true</addClasspath>
                    <classpathPrefix>${dependenciesDirectory}</classpathPrefix>
                    <mainClass>com.myclass.App</mainClass>
                  </manifest>
                </archive>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
  <dependencies>
    <dependency>
    </dependency>
  </dependencies>
</project>


问:
SQL Query between two dates from sub query
I have to filter my result by two columns from sub query,so I have join them like below which works fine.

```<code>select * from EDM_STATUS_REPORT_DATA LEFT JOIN
(
   Select DocumentID, LogDate
   From [LM_StateEvents]
   Where 1=1

) table2
ON
   EDM_STATUS_REPORT_DATA.LLObjID=table2.DocumentID
   AND EDM_STATUS_REPORT_DATA.StatusDate = table2.LogDate
WHERE table2.DocumentID IS NOT NULL
</code>```

However the EDM_STATUS_REPORT_DATA.StatusDate in main query is not going to be the same value from sub query.It would have maximum of +5 seconds difference.  So I have to search like using between table2.LogDate and table2.LogDate + 5 seconds.

How can I achieve this.

Below is the sample data and Expected output.

答:
I think you want cross apply:

```<code>select srd.*, le.*
from EDM_STATUS_REPORT_DATA src cross apply
     (Select DocumentID, LogDate
      From LM_StateEvents le
      where le.LLObjID = srd.DocumentID and
            le.LogDate  = src.StatusDate
     ) le
where le.DocumentID is not null;
</code>```

Note:  Your outer where clause suggests that you need a match.  I wonder why you are using an outer join in that case.

Body:
I have to filter my result by two columns from sub query,so I have join them like below which works fine.

select * from EDM_STATUS_REPORT_DATA LEFT JOIN
(
   Select DocumentID, LogDate
   From [LM_StateEvents]
   Where 1=1

) table2
ON
   EDM_STATUS_REPORT_DATA.LLObjID=table2.DocumentID
   AND EDM_STATUS_REPORT_DATA.StatusDate = table2.LogDate
WHERE table2.DocumentID IS NOT NULL

However the EDM_STATUS_REPORT_DATA.StatusDate in main query is not going to be the same value from sub query.It would have maximum of +5 seconds difference.  So I have to search like using between table2.LogDate and table2.LogDate + 5 seconds.

How can I achieve this.

Below is the sample data and Expected output.

Body:
I think you want cross apply:

select srd.*, le.*
from EDM_STATUS_REPORT_DATA src cross apply
     (Select DocumentID, LogDate
      From LM_StateEvents le
      where le.LLObjID = srd.DocumentID and
            le.LogDate  = src.StatusDate
     ) le
where le.DocumentID is not null;

Note:  Your outer where clause suggests that you need a match.  I wonder why you are using an outer join in that case.


问:
If a browser can shows Accept-Encoding of deflate, can it handle .NET gzipped responses?
I'm looking at this method in this HTTPCombiner:

```<code>private bool CanGZip(HttpRequest request)
{
    string acceptEncoding = request.Headers["Accept-Encoding"];
    if (!string.IsNullOrEmpty(acceptEncoding) &&
         (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
        return true;
    return false;
}
</code>```

If this returns true then the response is compressed using a GZipStream. Is this right?

答:
Those are two different algorithms :

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3

http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5

Some code here :

http://www.singular.co.nz/blog/archive/2008/07/06/finding-preferred-accept-encoding-header-in-csharp.aspx

So, according to the protocol, it is not right, as if the browser says "give me the content using deflate", you shouldn't send it back gzipped.

ContentLicense: CC BY-SA 3.0

Body:
I'm looking at this method in this HTTPCombiner:

private bool CanGZip(HttpRequest request)
{
    string acceptEncoding = request.Headers["Accept-Encoding"];
    if (!string.IsNullOrEmpty(acceptEncoding) &&
         (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
        return true;
    return false;
}

If this returns true then the response is compressed using a GZipStream. Is this right?


问:
Why does this work under Microsoft SQL Server Management Studio but not under R?
I received this SQL statement:

use MYDATABASE;
if object_id('tempdb..#mapDT') is not null drop table #mapDT;
create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
insert into #mapDT SELECT 'varchar','type text' UNION ALL SELECT 'datetime','type datetime'UNION ALL SELECT 'tinyint','int64.Type' UNION ALL SELECT 'int','int64.Type' UNION ALL SELECT 'float','type number';
SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
```

<p>and it runs nicely under MS SSMS. The relevant part of the result is:</p>

<pre class="lang-none prettyprint-override"><code>MyString1COLUMN01MyString2type textMyString3
MyString1COLUMN02MyString2type datetimeMyString3
MyString1COLUMN03MyString2type textMyString3
MyString1COLUMN04MyString2type textMyString3
MyString1COLUMN05MyString2int64.TypeMyString3
MyString1COLUMN06MyString2type datetimeMyString3
MyString1COLUMN07MyString2type datetimeMyString3
    ...     ...    ...
</code>```

When I run it under R I must leave out use MYDATABASE; and be sure I am connected at the right database, which is the case. But the SQL-statement is problematic. The output of:

> library(odbc)
> conn <- dbConnect(odbc(), Driver = "SQL Server", Server = "MYSERVER\\MYINSTANCE", Database = "MYDATABASE", Trusted_Connection = "True")
> dbGetQuery(conn, "
+                   if object_id('tempdb..#mapDT') is not null drop table #mapDT; create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
+                   insert into #mapDT SELECT 'varchar', 'type text' UNION ALL SELECT 'datetime', 'type datetime' UNION ALL SELECT 'tinyint', 'int64.Type' UNION ALL SELECT 'int', 'int64.Type' UNION ALL SELECT 'float', 'type number';
+                   SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
+                  ")
```

is data frame with 0 columns and 0 rows.

Is it the use of "temporal tables" (i.e. #mapDT) the cause of the empty data frame? If so, is there a way to get R and/or Python to understand/use them?

答:
Nonetheless, consider avoiding any DML statement that triggers NOCOUNT as your temp table is unnecessary. Simply run a subquery JOIN for a simpler, readable, maintainable query. Below CONCAT replaces the + on varchar fields and names calculated column with alias, OUTPUT:

SELECT COLUMN_NAME, DATA_TYPE,
       CONCAT('MyString1', COLUMN_NAME,
              'MyString2', m.MyNewDataType,
              'MyString3') AS OUTPUT
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN
   ( SELECT 'varchar' AS SqlDatatype, 'type text' AS MyNewDataType
     UNION ALL SELECT 'datetime', 'type datetime'
     UNION ALL SELECT 'tinyint', 'int64.Type'
     UNION ALL SELECT 'int', 'int64.Type'
     UNION ALL SELECT 'float', 'type number'
   ) m

ON m.SqlDatatype = C.DATA_TYPE
WHERE TABLE_NAME = 'MYTABLE';
```

Body:
I received this SQL statement:

use MYDATABASE;
if object_id('tempdb..#mapDT') is not null drop table #mapDT;
create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
insert into #mapDT SELECT 'varchar','type text' UNION ALL SELECT 'datetime','type datetime'UNION ALL SELECT 'tinyint','int64.Type' UNION ALL SELECT 'int','int64.Type' UNION ALL SELECT 'float','type number';
SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';

and it runs nicely under MS SSMS. The relevant part of the result is:

MyString1COLUMN01MyString2type textMyString3
MyString1COLUMN02MyString2type datetimeMyString3
MyString1COLUMN03MyString2type textMyString3
MyString1COLUMN04MyString2type textMyString3
MyString1COLUMN05MyString2int64.TypeMyString3
MyString1COLUMN06MyString2type datetimeMyString3
MyString1COLUMN07MyString2type datetimeMyString3
    ...     ...    ...

When I run it under R I must leave out use MYDATABASE; and be sure I am connected at the right database, which is the case. But the SQL-statement is problematic. The output of:

> library(odbc)
> conn <- dbConnect(odbc(), Driver = "SQL Server", Server = "MYSERVER\\MYINSTANCE", Database = "MYDATABASE", Trusted_Connection = "True")
> dbGetQuery(conn, "
+                   if object_id('tempdb..#mapDT') is not null drop table #mapDT; create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
+                   insert into #mapDT SELECT 'varchar', 'type text' UNION ALL SELECT 'datetime', 'type datetime' UNION ALL SELECT 'tinyint', 'int64.Type' UNION ALL SELECT 'int', 'int64.Type' UNION ALL SELECT 'float', 'type number';
+                   SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
+                  ")

is data frame with 0 columns and 0 rows.

Is it the use of "temporal tables" (i.e. #mapDT) the cause of the empty data frame? If so, is there a way to get R and/or Python to understand/use them?


问:
Laravel Mix one sass to multiple css
When trying this:

```<code>mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css/app_blue.css', {
        data: '$theme-bg-primary: #1450d9;'
    })
    .sass('resources/sass/app.scss', 'public/css/app_red.css', {
        data: '$theme-bg-primary: #ba0000;'
    });
</code>```

the output from npm is should not contain the item '[...]/app.scss' twice.

How to ouput 2 distincts css from one source as app.scss ?

答:
Since you are using a different variable values for both css files. You have to call .sass twice but to optimize it further i would suggest you to use variables.

e.g.

```<code>const cssSourceDir = 'resources/sass/';
const cssPublicDir = 'public/css/';
const commonSassFile = `${cssSourceDir}/app.scss`;
</code>```

duplication can be removed like this

```<code>mix.js('resources/js/app.js', 'public/js')
.sass(commonSassFile, cssPublicDir+'/app_blue.css', {
    data: '$theme-bg-primary: #1450d9;'
})
.sass(commonSassFile, cssPublicDir+'/app_red.css', {
    data: '$theme-bg-primary: #ba0000;'
});
</code>```

Title: Laravel Mix one sass to multiple css

Body:
When trying this:

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css/app_blue.css', {
        data: '$theme-bg-primary: #1450d9;'
    })
    .sass('resources/sass/app.scss', 'public/css/app_red.css', {
        data: '$theme-bg-primary: #ba0000;'
    });

the output from npm is should not contain the item '[...]/app.scss' twice.

How to ouput 2 distincts css from one source as app.scss ?

Body:
Since you are using a different variable values for both css files. You have to call .sass twice but to optimize it further i would suggest you to use variables.

e.g.

const cssSourceDir = 'resources/sass/';
const cssPublicDir = 'public/css/';
const commonSassFile = `${cssSourceDir}/app.scss`;

duplication can be removed like this

mix.js('resources/js/app.js', 'public/js')
.sass(commonSassFile, cssPublicDir+'/app_blue.css', {
    data: '$theme-bg-primary: #1450d9;'
})
.sass(commonSassFile, cssPublicDir+'/app_red.css', {
    data: '$theme-bg-primary: #ba0000;'
});


问:
Azure storage SAS token generation - signature mismatch
I am struggling with this issue for 3 days now.. I would really appreciate the help.

I am trying to create SAS tokens for accessing Azure storage blobs dynamically, the token generates but I keep getting this error:
Signature did not match. String to sign used was ...

Creating the SAS token from azure portal works fine, but I have tried generating it in the code using many different ways, Micrtosoft.Azure.Storage library:

```<code>private static string GetBlobSasUri(CloudBlobContainer container, string blobName)
{
    string sasBlobToken;

    // Get a reference to a blob within the container.
    // Note that the blob may not exist yet, but a SAS can still be created for it.
    CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

    // Create a new access policy and define its constraints.
    // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
    // to construct a shared access policy that is saved to the container's shared access policies.
    SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
    {
        // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
        // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
        SharedAccessStartTime = DateTime.UtcNow.AddHours(-24),
        SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
        Permissions = SharedAccessBlobPermissions.Read //| SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create
    };

    // Generate the shared access signature on the blob, setting the constraints directly on the signature.
    sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);

    Console.WriteLine("SAS for blob (ad hoc): {0}", sasBlobToken);
    Console.WriteLine();

    // Return the URI string for the container, including the SAS token.
    return blob.Uri + sasBlobToken;
}

</code>```

This has worked for a for few tries, the next day is stopped functioning.. I tested it on my local IIS and on azure as well, locally it never worked.

I have also tried creating the token myself, both generating and signing the token, but the same issue persists.. here is the code for the signing:

```<code> public static string generateSAS(Uri resourceUri, string accountKey, string accountName, StorageFile f)
        {

            string
                sr = "b",
                sp = "r",
                st = DateTime.Now.AddHours(-50).ToString("yyyy-MM-ddTH:MM:ssZ"),
                se = DateTime.Now.AddHours(50).ToString("yyyy-MM-ddTH:MM:ssZ"),
                sv = "2016-05-31"; //"2019-07-07"

            string blobUri = $"https://{accountName}.blob.core.windows.net/{f.Model.Container}/{f.Model.FileName}";

            string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}", new object[]
            {
                "r",
                st,
                se,
                GetCanonicalizedResource(new Uri(blobUri), accountName),
                string.Empty,
                string.Empty,
                string.Empty,
                sv,
                sr,
                string.Empty,
                string.Empty,
                string.Empty,
                string.Empty
            });

            var sas = GetHash(stringToSign, accountKey);

            var token =
                $"?sv={sv}&sr=b&sig={HttpUtility.UrlEncode(sas)}&st={HttpUtility.UrlEncode(st)}&se={HttpUtility.UrlEncode(se)}&sp=r";

            return blobUri + token;
        }

        private static string GetHash(string stringToSign, string key)
        {
            byte[] keyValue = Convert.FromBase64String(key);

            using (HMACSHA256 hmac = new HMACSHA256(keyValue))
            {
                return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
            }
        }

private static string GetCanonicalizedResource(Uri address, string storageAccountName)
        {
             // The absolute path is "/" because for we're getting a list of containers.
            StringBuilder sb = new StringBuilder("/").Append("blob").Append("/").Append(storageAccountName).Append(address.AbsolutePath);
            return sb.ToString();

        }
</code>```

I have read the documentation and thought the issue might be a version issue, so I tried using the latest build and some versions prior to it, but to no avail.

I have tried not using and adding other parameters, nothing worked at all..

I also have been lead  to believe that the issue might be due to clock, but I have adjusted my clock to every hour of the day so far, also it has been tested on an app service on Azure which is located in "UK South", in there the C# code worked for less than a single day.

I would appreciate you help very much! thank you

EDIT
Using the RESTful version of the code where I self sign it manually, this is the "toSignString":

```<code>r
2020-02-17T14:02:56Z
2020-02-21T18:02:56Z
/blob/<accountName>/<contaioner1>/<subContainer2>/<subContainer3>/file.v

2016-05-31
b

</code>```

and this is the full Uri:

```<code>https://<account>.blob.core.windows.net/<contaioner1>/<subContainer2>/<subContainer3>/file.v?
sv=2016-05-31&sr=b&sig=hI7MH0pT05cDpga2bMkanR%2b77CeocgttygDJbkRw6EM%3d&st=2020-02-17T14%3a02%3a56Z&se=2020-02-21T18%3a02%3a56Z&sp=r
</code>```

答:
This has worked for a single day, then it stopped working.. I tested
  it on my local IIS and on azure as well, locally it never worked.

This is expected behavior because you're setting the SAS Token expiry to be 24 hours from the current date/time (in UTC):

```<code>SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
</code>```

If you want your SAS URL to work for a longer duration, you will need to specify an expiry date much out in future.

Regarding the 2nd issue (manual creation of SAS Token), I believe there's an issue with your GetCanonicalizedResource method. Per the documentation, it should be in the following format:

```<code>/blob/<account-name>/<container-name>/<blob-name>
</code>```

The canonicalizedresource portion of the string is a canonical path to
  the signed resource. It must include the service name (blob, table,
  queue or file) for version 2015-02-21 or later, the storage account
  name, and the resource name, and must be URL-decoded.

Based on this, please try the following code:

```<code>private static string GetCanonicalizedResource(Uri address, string storageAccountName)
{
    // The absolute path is "/" because for we're getting a list of containers.
    StringBuilder sb = new StringBuilder("/").Append("blob").Append("/").Append(storageAccountName).Append("/").Append(address.AbsolutePath);
    return sb.ToString();
}
</code>```

UPDATE

Took me a while to figure out what's wrong :) but finally was able to do so. There are a number of issues I found:

You're formatting dates incorrectly. It should be in yyyy-MM-ddTHH:MM:ssZ but you're formatting it in yyyy-MM-ddTH:MM:ssZ format. If you notice, it's missing an extra H.

You're using 2016-05-31 signed version and that does not include the signed resource (b in your case) in stringToSign but you're including that. It should be included in your SAS URL though.

Your string to sign is missing content-language (rscl) parameter.

According to the documentation, this is how you should construct your stringToSign:

```<code>StringToSign = signedpermissions + "\n" +
               signedstart + "\n" +
               signedexpiry + "\n" +
               canonicalizedresource + "\n" +
               signedidentifier + "\n" +
               signedIP + "\n" +
               signedProtocol + "\n" +
               signedversion + "\n" +
               rscc + "\n" +
               rscd + "\n" +
               rsce + "\n" +
               rscl + "\n" +
               rsct
</code>```

Based on this, here should be your code:

```<code>    string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}", new object[]
    {
        "r",//permission
        st,//start
        se,//end
        GetCanonicalizedResource(new Uri(blobUri), accountName),//canonical resource
        string.Empty,//signed identifier
        string.Empty,//signed ip
        string.Empty,//signed protocol
        sv,//signed version
        string.Empty,//cache control
        string.Empty,//content disposition
        string.Empty,//content encoding
        string.Empty,//content language
        string.Empty//content type
    });
</code>```

Give it a try and it should work.

Body:
I am struggling with this issue for 3 days now.. I would really appreciate the help.

I am trying to create SAS tokens for accessing Azure storage blobs dynamically, the token generates but I keep getting this error:
Signature did not match. String to sign used was ...

Creating the SAS token from azure portal works fine, but I have tried generating it in the code using many different ways, Micrtosoft.Azure.Storage library:

private static string GetBlobSasUri(CloudBlobContainer container, string blobName)
{
    string sasBlobToken;

    // Get a reference to a blob within the container.
    // Note that the blob may not exist yet, but a SAS can still be created for it.
    CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

    // Create a new access policy and define its constraints.
    // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
    // to construct a shared access policy that is saved to the container's shared access policies.
    SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
    {
        // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
        // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
        SharedAccessStartTime = DateTime.UtcNow.AddHours(-24),
        SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
        Permissions = SharedAccessBlobPermissions.Read //| SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create
    };

    // Generate the shared access signature on the blob, setting the constraints directly on the signature.
    sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);

    Console.WriteLine("SAS for blob (ad hoc): {0}", sasBlobToken);
    Console.WriteLine();

    // Return the URI string for the container, including the SAS token.
    return blob.Uri + sasBlobToken;
}

This has worked for a for few tries, the next day is stopped functioning.. I tested it on my local IIS and on azure as well, locally it never worked.

I have also tried creating the token myself, both generating and signing the token, but the same issue persists.. here is the code for the signing:

 public static string generateSAS(Uri resourceUri, string accountKey, string accountName, StorageFile f)
        {

            string
                sr = "b",
                sp = "r",
                st = DateTime.Now.AddHours(-50).ToString("yyyy-MM-ddTH:MM:ssZ"),
                se = DateTime.Now.AddHours(50).ToString("yyyy-MM-ddTH:MM:ssZ"),
                sv = "2016-05-31"; //"2019-07-07"

            string blobUri = $"https://{accountName}.blob.core.windows.net/{f.Model.Container}/{f.Model.FileName}";

            string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}", new object[]
            {
                "r",
                st,
                se,
                GetCanonicalizedResource(new Uri(blobUri), accountName),
                string.Empty,
                string.Empty,
                string.Empty,
                sv,
                sr,
                string.Empty,
                string.Empty,
                string.Empty,
                string.Empty
            });

            var sas = GetHash(stringToSign, accountKey);

            var token =
                $"?sv={sv}&sr=b&sig={HttpUtility.UrlEncode(sas)}&st={HttpUtility.UrlEncode(st)}&se={HttpUtility.UrlEncode(se)}&sp=r";

            return blobUri + token;
        }

        private static string GetHash(string stringToSign, string key)
        {
            byte[] keyValue = Convert.FromBase64String(key);

            using (HMACSHA256 hmac = new HMACSHA256(keyValue))
            {
                return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
            }
        }

private static string GetCanonicalizedResource(Uri address, string storageAccountName)
        {
             // The absolute path is "/" because for we're getting a list of containers.
            StringBuilder sb = new StringBuilder("/").Append("blob").Append("/").Append(storageAccountName).Append(address.AbsolutePath);
            return sb.ToString();

        }

I have read the documentation and thought the issue might be a version issue, so I tried using the latest build and some versions prior to it, but to no avail.

I have tried not using and adding other parameters, nothing worked at all..

I also have been lead  to believe that the issue might be due to clock, but I have adjusted my clock to every hour of the day so far, also it has been tested on an app service on Azure which is located in "UK South", in there the C# code worked for less than a single day.

I would appreciate you help very much! thank you

EDIT
Using the RESTful version of the code where I self sign it manually, this is the "toSignString":

r
2020-02-17T14:02:56Z
2020-02-21T18:02:56Z
/blob/<accountName>/<contaioner1>/<subContainer2>/<subContainer3>/file.v

2016-05-31
b

and this is the full Uri:

https://<account>.blob.core.windows.net/<contaioner1>/<subContainer2>/<subContainer3>/file.v?
sv=2016-05-31&sr=b&sig=hI7MH0pT05cDpga2bMkanR%2b77CeocgttygDJbkRw6EM%3d&st=2020-02-17T14%3a02%3a56Z&se=2020-02-21T18%3a02%3a56Z&sp=r

Body:
This has worked for a single day, then it stopped working.. I tested
  it on my local IIS and on azure as well, locally it never worked.

This is expected behavior because you're setting the SAS Token expiry to be 24 hours from the current date/time (in UTC):

SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),

If you want your SAS URL to work for a longer duration, you will need to specify an expiry date much out in future.

Regarding the 2nd issue (manual creation of SAS Token), I believe there's an issue with your GetCanonicalizedResource method. Per the documentation, it should be in the following format:

/blob/<account-name>/<container-name>/<blob-name>

The canonicalizedresource portion of the string is a canonical path to
  the signed resource. It must include the service name (blob, table,
  queue or file) for version 2015-02-21 or later, the storage account
  name, and the resource name, and must be URL-decoded.

Based on this, please try the following code:

private static string GetCanonicalizedResource(Uri address, string storageAccountName)
{
    // The absolute path is "/" because for we're getting a list of containers.
    StringBuilder sb = new StringBuilder("/").Append("blob").Append("/").Append(storageAccountName).Append("/").Append(address.AbsolutePath);
    return sb.ToString();
}

UPDATE

Took me a while to figure out what's wrong :) but finally was able to do so. There are a number of issues I found:

You're formatting dates incorrectly. It should be in yyyy-MM-ddTHH:MM:ssZ but you're formatting it in yyyy-MM-ddTH:MM:ssZ format. If you notice, it's missing an extra H.

You're using 2016-05-31 signed version and that does not include the signed resource (b in your case) in stringToSign but you're including that. It should be included in your SAS URL though.

Your string to sign is missing content-language (rscl) parameter.

According to the documentation, this is how you should construct your stringToSign:

StringToSign = signedpermissions + "\n" +
               signedstart + "\n" +
               signedexpiry + "\n" +
               canonicalizedresource + "\n" +
               signedidentifier + "\n" +
               signedIP + "\n" +
               signedProtocol + "\n" +
               signedversion + "\n" +
               rscc + "\n" +
               rscd + "\n" +
               rsce + "\n" +
               rscl + "\n" +
               rsct

Based on this, here should be your code:

    string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}", new object[]
    {
        "r",//permission
        st,//start
        se,//end
        GetCanonicalizedResource(new Uri(blobUri), accountName),//canonical resource
        string.Empty,//signed identifier
        string.Empty,//signed ip
        string.Empty,//signed protocol
        sv,//signed version
        string.Empty,//cache control
        string.Empty,//content disposition
        string.Empty,//content encoding
        string.Empty,//content language
        string.Empty//content type
    });

Give it a try and it should work.


答: You can see this answer here to add seconds to a date (use DateADD function): https://stackoverflow.com/a/3480794/6601237 </p>

Title: SQL Query between two dates from sub query


问:
No metadata registered for captured table ORCLCDB.ROOT.TEST
After inserting something on TEST table this error occurs.

```<code>[2020-02-15 15:20:03,996] ERROR Producer failure (io.debezium.pipeline.ErrorHandler:36)
**java.lang.IllegalArgumentException: No metadata registered for captured table ORCLCDB.ROOT.TEST**
    at io.debezium.pipeline.EventDispatcher.errorOnMissingSchema(EventDispatcher.java:168)
    at io.debezium.pipeline.EventDispatcher.dispatchDataChangeEvent(EventDispatcher.java:138)
    at io.debezium.connector.oracle.LcrEventHandler.dispatchDataChangeEvent(LcrEventHandler.java:102)
    at io.debezium.connector.oracle.LcrEventHandler.processLCR(LcrEventHandler.java:76)
    at oracle.streams.XStreamOut.XStreamOutReceiveLCRCallbackNative(Native Method)
    at oracle.streams.XStreamOut.receiveLCRCallback(XStreamOut.java:465)
    at io.debezium.connector.oracle.OracleStreamingChangeEventSource.execute(OracleStreamingChangeEventSource.java:74)
    at io.debezium.pipeline.ChangeEventSourceCoordinator.lambda$start$0(ChangeEventSourceCoordinator.java:99)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

connector-oracle-source.properties:

```<code>name=oracle-connector
connector.class=io.debezium.connector.oracle.OracleConnector
tasks.max=1
database.hostname=192.168.6.36
database.port=1521
database.user=c##xstrm
database.password=xs
database.server.name=osTomates
database.out.server.name=teucude4
database.dbname=ORCLCDB
#database.pdb.name=ORCLPDB1
database.history.kafka.bootstrap.servers=192.168.6.36:9092
database.history.kafka.topic=test
</code>```

Please let me know if you need additional information?

Oracle 19 version
Standalone configuration

答:
The user c##xstrm should get permission to see the root.test table (on my case).

GRANT SELECT ON root.test TO c##xstrm;

This solved my problem.

If next you after restart the kafka connect and you get this error ORA-31603, this worked for me:

GRANT select_catalog_role TO c##xstrm;

Hope this helps someone out there.

Body:
After inserting something on TEST table this error occurs.

[2020-02-15 15:20:03,996] ERROR Producer failure (io.debezium.pipeline.ErrorHandler:36)
**java.lang.IllegalArgumentException: No metadata registered for captured table ORCLCDB.ROOT.TEST**
    at io.debezium.pipeline.EventDispatcher.errorOnMissingSchema(EventDispatcher.java:168)
    at io.debezium.pipeline.EventDispatcher.dispatchDataChangeEvent(EventDispatcher.java:138)
    at io.debezium.connector.oracle.LcrEventHandler.dispatchDataChangeEvent(LcrEventHandler.java:102)
    at io.debezium.connector.oracle.LcrEventHandler.processLCR(LcrEventHandler.java:76)
    at oracle.streams.XStreamOut.XStreamOutReceiveLCRCallbackNative(Native Method)
    at oracle.streams.XStreamOut.receiveLCRCallback(XStreamOut.java:465)
    at io.debezium.connector.oracle.OracleStreamingChangeEventSource.execute(OracleStreamingChangeEventSource.java:74)
    at io.debezium.pipeline.ChangeEventSourceCoordinator.lambda$start$0(ChangeEventSourceCoordinator.java:99)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

connector-oracle-source.properties:

name=oracle-connector
connector.class=io.debezium.connector.oracle.OracleConnector
tasks.max=1
database.hostname=192.168.6.36
database.port=1521
database.user=c##xstrm
database.password=xs
database.server.name=osTomates
database.out.server.name=teucude4
database.dbname=ORCLCDB
#database.pdb.name=ORCLPDB1
database.history.kafka.bootstrap.servers=192.168.6.36:9092
database.history.kafka.topic=test

Please let me know if you need additional information?

Oracle 19 version
Standalone configuration


问:
run button in xcode 4
Whenever I re-run my application by selecting the run button in xcode for, it says simulator already in use. So I have to stop it every time before re-running.
So my question is, is there any option or setting to avoid this. I want to run the application without stopping it like we used to do in xcode 3.</p>

答: This is a bug in Xcode 4 which occurs sometimes. Usually you can make it go away by quitting the Simulator and restarting Xcode. If that still doesn't fix the problem, I would report the issue at bugreport.apple.com and see if the engineers at Apple can help.</p>

Title: run button in xcode 4


答:
Instead of injecting your data into the mix call, you need to create a stub scss file for each theme you are creating.

```<code>mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app_red.scss', 'public/css')
   .sass('resources/assets/sass/app_blue.scss', 'public/css')
</code>```

Where those scss files include the base app.scss and overrides that you are injecting with your data value.

Title: Laravel Mix one sass to multiple css

Body:
Instead of injecting your data into the mix call, you need to create a stub scss file for each theme you are creating.

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app_red.scss', 'public/css')
   .sass('resources/assets/sass/app_blue.scss', 'public/css')

Where those scss files include the base app.scss and overrides that you are injecting with your data value.


问:
TestNG - Implementation of sequential and parallel test scripts
I was creating a demo framework for Open MRS Application using POM design. The credentials for the Application are "admin/Admin123"

I created the following 3 Classes:

1) Login tests: Which contains all the Login (1 +ve and 2 -ve scenarios) and Logout test (Total 4 @Tests)

2) Register Patient test: Which will register a patient and also verify if the patient has been registered successfully (Total 3 +ve @Tests)

3) Capture Vitals test: Which will Capture Vitals of the patient registered above and verify if the details captured are correct. (Total 2 +ve @Tests)

I'm planning to add a few more Classes which will contain tests related to Adding Visits, adding Allergies etc.

There is a dependency between the classes i.e. only execute the Register patient test if the @Test for Login passes. Similarly, execute the remaining tests like capture vitals, adding visits, adding allergies only if the Register patient test passes. However, there is no dependency between the capture vitals, adding visits and adding allergies and can run in parallel.

This is how it looks from a top-level:

```<code>class Login
    @Test T_001_LoginTest
    @Test T_002_LogoutTest
class RegisterPatient
    @Test T_003_RegisterNewPatient
    @Test T_004_ConfirmPatientRegisteredUsingPatientID (dependent on T_003)
    @Test T_005_ConfirmPatientRegisteredUsingPatientName (dependent on T_003)
class CaptureVitalsTest
    @Test T_006_CreateAVisitAndCaptureVitals (dependent on T_001 and T_003)
    @Test T_007_VerifyVitals (dependent on T_006)
</code>```

What I have done so far is added defined group "login" for class Login and group "registerpatient" for class Register. For class RegisterPatient, I've added dependsOnGroup "login". Similarly, for class CaptureVitals, I've added dependsOnGroups for both "login" and "registerpatient". I've also set alwaysRun = true for the @Test Methods which have "dependsOnMethods" dependency.

Below is my testng.xml file

```<code><suite name="Open MRS Automation" parallel="tests">

    <listeners>
        <listener class-name="com.utils.CustomListener" />
    </listeners>

    <test thread-count="5" name="Login Test">
        <classes>
            <class name="com.testcases.LoginTest" />
        </classes>
    </test> <!-- Test -->

    <test thread-count="5" name="Register Patient Tests">
        <classes>
            <class name="com.testcases.RegisterPatientTest" />
        </classes>
    </test>

    <test thread-count="5" name="Capture Vitals Tests">
        <classes>
            <class name="com.testcases.CaptureVitalsTest" />
        </classes>
    </test>

</suite>

</code>```

What would be the right approach in setting initial sequential and then parallel execution of the tests? Any help would be appreciated! Thanks.

答:
You should give Testcases method name by numbers.
you must be using excel sheet for data provider format that will help you run test cases according to Testcases number </p>

Body:
I was creating a demo framework for Open MRS Application using POM design. The credentials for the Application are "admin/Admin123"

I created the following 3 Classes:

1) Login tests: Which contains all the Login (1 +ve and 2 -ve scenarios) and Logout test (Total 4 @Tests)

2) Register Patient test: Which will register a patient and also verify if the patient has been registered successfully (Total 3 +ve @Tests)

3) Capture Vitals test: Which will Capture Vitals of the patient registered above and verify if the details captured are correct. (Total 2 +ve @Tests)

I'm planning to add a few more Classes which will contain tests related to Adding Visits, adding Allergies etc.

There is a dependency between the classes i.e. only execute the Register patient test if the @Test for Login passes. Similarly, execute the remaining tests like capture vitals, adding visits, adding allergies only if the Register patient test passes. However, there is no dependency between the capture vitals, adding visits and adding allergies and can run in parallel.

This is how it looks from a top-level:

class Login
    @Test T_001_LoginTest
    @Test T_002_LogoutTest
class RegisterPatient
    @Test T_003_RegisterNewPatient
    @Test T_004_ConfirmPatientRegisteredUsingPatientID (dependent on T_003)
    @Test T_005_ConfirmPatientRegisteredUsingPatientName (dependent on T_003)
class CaptureVitalsTest
    @Test T_006_CreateAVisitAndCaptureVitals (dependent on T_001 and T_003)
    @Test T_007_VerifyVitals (dependent on T_006)

What I have done so far is added defined group "login" for class Login and group "registerpatient" for class Register. For class RegisterPatient, I've added dependsOnGroup "login". Similarly, for class CaptureVitals, I've added dependsOnGroups for both "login" and "registerpatient". I've also set alwaysRun = true for the @Test Methods which have "dependsOnMethods" dependency.

Below is my testng.xml file

<suite name="Open MRS Automation" parallel="tests">

    <listeners>
        <listener class-name="com.utils.CustomListener" />
    </listeners>

    <test thread-count="5" name="Login Test">
        <classes>
            <class name="com.testcases.LoginTest" />
        </classes>
    </test>

    <test thread-count="5" name="Register Patient Tests">
        <classes>
            <class name="com.testcases.RegisterPatientTest" />
        </classes>
    </test>

    <test thread-count="5" name="Capture Vitals Tests">
        <classes>
            <class name="com.testcases.CaptureVitalsTest" />
        </classes>
    </test>

</suite>

What would be the right approach in setting initial sequential and then parallel execution of the tests? Any help would be appreciated! Thanks.


问:
ImageJ- how to get the slicename from the actually processed image in an imagestack
i have a problem getting the filename from an image stack in ImageJ.
I wrote a plugin that can be used on image stacks and gives an output result for every image in the stack with:

```<code>if (mfpc == true) {
            IJ.log(fileName+": Good");
        } else {
            IJ.log(fileName+": Bad");
        }
</code>```

getTitle() works for single images, but only shows the Stack-Name for stacks, not the name of the actual slice.

i also tried to get the slice name with the following code

```<code>fileName = imp.getImageStack().getShortSliceLabel(imp.getCurrentSlice());
</code>```

but it only shows the currently chosen picture, not the picture which is handled by the plugin. My wishful thinking is the following output (while the filename is Imagex.png):

Image1.png: Good

Image2.png: Bad

Image3.png: Good

Is that possible and if so, how? :)

答: You can get the slice name by using the command getInfo("slice.label");

Body:
i have a problem getting the filename from an image stack in ImageJ.
I wrote a plugin that can be used on image stacks and gives an output result for every image in the stack with:

if (mfpc == true) {
            IJ.log(fileName+": Good");
        } else {
            IJ.log(fileName+": Bad");
        }

getTitle() works for single images, but only shows the Stack-Name for stacks, not the name of the actual slice.

i also tried to get the slice name with the following code

fileName = imp.getImageStack().getShortSliceLabel(imp.getCurrentSlice());

but it only shows the currently chosen picture, not the picture which is handled by the plugin. My wishful thinking is the following output (while the filename is Imagex.png):

Image1.png: Good

Image2.png: Bad

Image3.png: Good

Is that possible and if so, how? :)


问:
Is Alexa still sending the Viewport data in the Request?
I don't see the Viewport data neither from a Show or a Spot... (context.Viewport) What happened?

There used to be a section to describe the display capabilites, like this from a Spot:

```<code>"Viewport": {
  "currentPixelHeight": 480,
  "currentPixelWidth": 480,
  "dpi": 160,
  "experiences": [
    {
      "arcMinuteHeight": 144,
      "arcMinuteWidth": 144,
      "canResize": false,
      "canRotate": false
    }
  ],
  "keyboard": [],
  "pixelHeight": 480,
  "pixelWidth": 480,
  "shape": "ROUND",
  "touch": [
    "SINGLE"
  ]
}
</code>```

答:
I have been scouring documentation for days looking for a way to get the display characteristics.  This post gave me a tiny clue, thank you very much.  I finally found out how to get them with this.  I know it seems a simple task to get the variable but I'm just beginning and the documentation isn't that friendly (or I was looking in the wrong places).  So if one prints event['context']['Viewport'] then one can get the display characteristics when the test skill is run.

Here's my example for getting the screen width:

```<code>def get_display_width(event):
    try:
        width = event['context']['Viewport']['currentPixelWidth']
    except:
        width = 1
    if width < 481:
            return 1 #small hub round 480 x 480
    elif width < 962:
        return 2 #small hub 960 x 480
    elif width < 1026:
        return 3 #medium hub 1024 x 600
    else:
        return 4 #large hubs and tv's
</code>```

Body:
I don't see the Viewport data neither from a Show or a Spot... (context.Viewport) What happened?

There used to be a section to describe the display capabilites, like this from a Spot:

"Viewport": {
  "currentPixelHeight": 480,
  "currentPixelWidth": 480,
  "dpi": 160,
  "experiences": [
    {
      "arcMinuteHeight": 144,
      "arcMinuteWidth": 144,
      "canResize": false,
      "canRotate": false
    }
  ],
  "keyboard": [],
  "pixelHeight": 480,
  "pixelWidth": 480,
  "shape": "ROUND",
  "touch": [
    "SINGLE"
  ]
}

Body:
I have been scouring documentation for days looking for a way to get the display characteristics.  This post gave me a tiny clue, thank you very much.  I finally found out how to get them with this.  I know it seems a simple task to get the variable but I'm just beginning and the documentation isn't that friendly (or I was looking in the wrong places).  So if one prints event['context']['Viewport'] then one can get the display characteristics when the test skill is run.

Here's my example for getting the screen width:

def get_display_width(event):
    try:
        width = event['context']['Viewport']['currentPixelWidth']
    except:
        width = 1
    if width < 481:
            return 1 #small hub round 480 x 480
    elif width < 962:
        return 2 #small hub 960 x 480
    elif width < 1026:
        return 3 #medium hub 1024 x 600
    else:
        return 4 #large hubs and tv's


问:
terraform cyclic dependeny for aws api gateway with resource policy
Problem statement
i am trying to automate aws api gateway with terraform follwing is part of my code

for api gateway

```<code>resource "aws_api_gateway_rest_api" "rest_api" {
  #some code
policy = "${data.template_file.init.rendered}"
}

output "id" {
  value = "${aws_api_gateway_rest_api.rest_api.id}"
}

output "execution_arn" {
  value = "${aws_api_gateway_rest_api.rest_api.execution_arn}"
}

output "arn" {
  value = "${aws_api_gateway_rest_api.rest_api.arn}"
}
</code>```

for resource policy
please note i want to automate insertion of api id in json policy document

```<code>data "aws_region" "current" {}
data "aws_caller_identity" "current" {}
data "template_file" "init" {
  template = "${file("${path.root}/${var.policy_file_location}")}"
  vars = {
    current_region      = "${data.aws_region.current.name}"
    current_aws_account = "${data.aws_caller_identity.current.account_id}"
    current_api_id              = "${aws_api_gateway_rest_api.rest_api.id}"
  }
}
</code>```

json policy

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:${current_region}:${current_aws_account}:${current_api_id}/*"
        }
    ]
}
</code>```

when i try to provide resource policy similar to following i am getting

Error: Cycle: module.simple-api-gw.data.template_file.init,
  module.simple-api-gw.aws_api_gateway_rest_api.rest_api

how can I resolve this error? I want to provide api id dynamically in json file.

答:
The policy you are generating would be appropriate to assign to an IAM role or IAM user, to allow them to invoke the API. Assigning that specific policy directly to the API Gateway doesn't make sense. In essence you are saying "anyone with permission to invoke the API can have permission to invoke the API" which is a circular statement.

A policy appropriate for assigning to an API Gateway would do something like limit requests to specific Principals, or specific IP addresses.

Please see the documentation that I have linked above. It outlines two separate methods for controlling access to your API Gateway, via IAM permissions or via resource policies. You are trying to assign an IAM permission as a resource policy, which isn't going to work.

Body:
Problem statement
i am trying to automate aws api gateway with terraform follwing is part of my code

for api gateway

resource "aws_api_gateway_rest_api" "rest_api" {
  #some code
policy = "${data.template_file.init.rendered}"
}

output "id" {
  value = "${aws_api_gateway_rest_api.rest_api.id}"
}

output "execution_arn" {
  value = "${aws_api_gateway_rest_api.rest_api.execution_arn}"
}

output "arn" {
  value = "${aws_api_gateway_rest_api.rest_api.arn}"
}

for resource policy
please note i want to automate insertion of api id in json policy document

data "aws_region" "current" {}
data "aws_caller_identity" "current" {}
data "template_file" "init" {
  template = "${file("${path.root}/${var.policy_file_location}")}"
  vars = {
    current_region      = "${data.aws_region.current.name}"
    current_aws_account = "${data.aws_caller_identity.current.account_id}"
    current_api_id              = "${aws_api_gateway_rest_api.rest_api.id}"
  }
}

json policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:${current_region}:${current_aws_account}:${current_api_id}/*"
        }
    ]
}

when i try to provide resource policy similar to following i am getting

Error: Cycle: module.simple-api-gw.data.template_file.init,
  module.simple-api-gw.aws_api_gateway_rest_api.rest_api

how can I resolve this error? I want to provide api id dynamically in json file.


问:
Cull off parts above the mesh
So, I want to make scene same to this Sphere Scene

Now I have mesh with random generation as a ground and a sphere. But I dont't know how to cull off spheres geometry above mesh. Tried to use Stencil, and hightmap. Stencil rendered ground in front, but sphere above ground is still rendered. Using heightmap, to get know if it needs to render (I compared height map and worldPos) is problematic, because the texture is superimposed over the all sphere, and not projected onto it. Can you help. Is there any shader function to cull off all above mesh.

答:
I did something similar for an Asteroids demo a few years ago. Whenever an asteroid was hit, I used a height map - really, just a noise map - to offset half of the vertices on the asteroid model to give it a broken-in-half look. For the other half, I just duplicated the asteroid model and offset the other half using the same noise map. The effect is that the two "halves" matched perfectly.

Here's what I'd try:

Your sphere model should be a complete sphere.

You'll need a height map for the terrain.

In your sphere's vertex shader, for any vertex north of the equator:

Sample the height map.

Set the vertex's Y coordinate to the height from the height map. This will effectively flatten the top of the sphere, and then offset it based on your height map. You will likely have to scale the height value here to get something rational.

Transform the new x,y,z as usual.

Note that you are not texturing the sphere. You're modifying the geometry. This needs to happen in the geometry part of the pipeline, not in the fragment shader.

The other thing you'll need to consider is how to add the debris - rocks, etc. - so that it matches the geometry offset on the sphere. Since you've got a height map, that should be straightforward.

To start with, I'd just get your vertex shader to flatten the top half of the sphere. Once that works, add in the height map.

For this to look convincing, you'll need a fairly high-resolution sphere and height map. To cut down on geometry, you could use a plane for the terrain and a hemisphere for the bottom part. Just discard any fragment for the plane that is not within the spherical volume you're interested in. (You could also use a circular "plane" rather than a rectangular plane, but getting the vertices to line up with the sphere and filling in holes at the border can be tricky.)

Title: Cull off parts above the mesh


问:
Extract the factor's values positions in level
I'm returning to R after some time, and the following has me stumped:

I'd like to build a list of the positions factor values have in the facor levels list.
Example:

```<code>> data = c("a", "b", "a","a","c")
> fdata = factor(data)
> fdata
[1] a b a a c
Levels: a b c
> fdata$lvl_idx <- ????
</code>```

Such that:

```<code>> fdata$lvl_idx
[1] 1 2 1 1 3
</code>```

Appreciate any hints or tips.

答:
The solution provided years ago by Matthew Lundberg is not robust. It could be that the as.integer() function was defined for a specific S3 type of factors. Imagine someone would create a new factor class to keep operators like >=.

```<code>as.myfactor <- function(x, ...) {
  structure(as.factor(x), class = c("myfactor", "factor"))
}

# and that someone would create an S3 method for integers - it should
# only remove the operators, which makes sense...
as.integer.myfactor <- function(x, ...) {
  as.integer(gsub("(<|=|>)+", "", as.character(x)))
}
</code>```

Now this is not working anymore, - it just removes operators:

```<code>f <- as.myfactor(">=2")
as.integer(f)
#> [1] 2
</code>```

But this is robust with any factor you want to know the index of the level of, using which():

```<code>f <- factor(2:4)
which(levels(f) == 2)
#> [1] 1
</code>```

Body:
I'm returning to R after some time, and the following has me stumped:

I'd like to build a list of the positions factor values have in the facor levels list.
Example:

> data = c("a", "b", "a","a","c")
> fdata = factor(data)
> fdata
[1] a b a a c
Levels: a b c
> fdata$lvl_idx <- ????

Such that:

> fdata$lvl_idx
[1] 1 2 1 1 3

Appreciate any hints or tips.

Body:
The solution provided years ago by Matthew Lundberg is not robust. It could be that the as.integer() function was defined for a specific S3 type of factors. Imagine someone would create a new factor class to keep operators like >=.

as.myfactor <- function(x, ...) {
  structure(as.factor(x), class = c("myfactor", "factor"))
}

# and that someone would create an S3 method for integers - it should
# only remove the operators, which makes sense...
as.integer.myfactor <- function(x, ...) {
  as.integer(gsub("(<|=|>)+", "", as.character(x)))
}

Now this is not working anymore, - it just removes operators:

f <- as.myfactor(">=2")
as.integer(f)
#> [1] 2

But this is robust with any factor you want to know the index of the level of, using which():

f <- factor(2:4)
which(levels(f) == 2)
#> [1] 1


问:
Rendering a partial view in Layout and declare a controller for it in asp.net core
I have the following scenario

```<code> @model CashUnited.Models.HomeViewModel
 <html lang="en">
 <head>
   <title>@ViewData["Title"] - test</title>
 </head>
 <body>
   <partial name="_Header" model="@Html.DisplayNameFor(model=>model)"/>
 </body>
</html>
</code>```

my partial view Code

```<code><select>
@{
   foreach (string item in Model.companiesLst)
   {
      <option value="@item">@item</option>
   }
}
</code>```

How and where I can Fill Model.companiesLst from the controller? I can't seem to figure it out in asp.net Core

答:
You have to create/get instances of your model and then pass it to the main view like this:

```<code>public ActionResult GetItems() {
    var items = this.itemsService.GetItems();

    return this.View(items);
}
</code>```

Where variable with name items is your model which contains the property companiesList.

The parent view:

```<code>@model CashUnited.Models.HomeViewModel
 <html lang="en">
 <head>
   <title>@ViewData["Title"] - test</title>
 </head>
 <body>
   @await Html.PartialAsync("_Header", Model)
 </body>
</html>
</code>```

The partial view:

```<code>@model CashUnited.Models.HomeViewModel

<select>
@{
   foreach (string item in Model.companiesLst)
   {
      <option value="@item">@item</option>
   }
}
</select>
</code>```

Body:
I have the following scenario

 @model CashUnited.Models.HomeViewModel

   <title>@ViewData["Title"] - test</title>

   <partial name="_Header" model="@Html.DisplayNameFor(model=>model)"/>

my partial view Code

<select>
@{
   foreach (string item in Model.companiesLst)
   {
      <option value="@item">@item</option>
   }
}

How and where I can Fill Model.companiesLst from the controller? I can't seem to figure it out in asp.net Core

Body:
You have to create/get instances of your model and then pass it to the main view like this:

public ActionResult GetItems() {
    var items = this.itemsService.GetItems();

    return this.View(items);
}

Where variable with name items is your model which contains the property companiesList.

The parent view:

@model CashUnited.Models.HomeViewModel
 <html lang="en">
 <head>
   <title>@ViewData["Title"] - test</title>
 </head>
 <body>
   @await Html.PartialAsync("_Header", Model)
 </body>
</html>

The partial view:

@model CashUnited.Models.HomeViewModel

<select>
@{
   foreach (string item in Model.companiesLst)
   {
      <option value="@item">@item</option>
   }
}
</select>


问:
MySql.Data.MySqlClient.MySqlException: in C# but works fine in MySQL Workbench
Goal:

I am trying to put a query into C# to update MySQL record for specific id. But it is coming with an error message whenever I run it.

This is the Error message:

MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\', ''))), '\Archive\', SUBSTRING_INDEX(file_attachment, '\', -1)) where id = 2' at line 1'

C# code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string query = "UPDATE document_control SET newIssueNo = 2, file_attachment = CONCAT(SUBSTRING_INDEX(file_attachment, '\\', LENGTH(file_attachment) - LENGTH(REPLACE(file_attachment, '\\', ''))), '\\Archive\\', SUBSTRING_INDEX(file_attachment, '\\', -1)) where id = 2";
            MySqlConnection conn = new MySqlConnection("credentials");
            conn.Open(); //Open the connection
            MySqlCommand cmd = new MySqlCommand(query, conn);

            cmd.ExecuteNonQuery();

            conn.Close(); //don't forget to close it after you're done

        }
    }
}
</code>```

But when I run it in MySQL workbench:

```<code>UPDATE document_control SET newIssueNo = 2, file_attachment = CONCAT(SUBSTRING_INDEX(file_attachment, '\\',  LENGTH(file_attachment) - LENGTH(REPLACE(file_attachment, '\\', ''))), '\\Archive\\', SUBSTRING_INDEX(file_attachment, '\\', -1)) where id = 2

1 row(s) affected Rows matched: 1  Changed: 1  Warnings: 0
</code>```

答:
Use @ before string value because in regular declaration \ is escape character.

string query = @"UPDATE document_control SET newIssueNo = 2, file_attachment = CONCAT(SUBSTRING_INDEX(file_attachment, '\\', LENGTH(file_attachment) - LENGTH(REPLACE(file_attachment, '\\', ''))), '\\Archive\\', SUBSTRING_INDEX(file_attachment, '\\', -1)) where id = 2";
```

Body:
Goal:

I am trying to put a query into C# to update MySQL record for specific id. But it is coming with an error message whenever I run it.

This is the Error message:

MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\', ''))), '\Archive\', SUBSTRING_INDEX(file_attachment, '\', -1)) where id = 2' at line 1'

C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string query = "UPDATE document_control SET newIssueNo = 2, file_attachment = CONCAT(SUBSTRING_INDEX(file_attachment, '\\', LENGTH(file_attachment) - LENGTH(REPLACE(file_attachment, '\\', ''))), '\\Archive\\', SUBSTRING_INDEX(file_attachment, '\\', -1)) where id = 2";
            MySqlConnection conn = new MySqlConnection("credentials");
            conn.Open(); //Open the connection
            MySqlCommand cmd = new MySqlCommand(query, conn);

            cmd.ExecuteNonQuery();

            conn.Close(); //don't forget to close it after you're done

        }
    }
}

But when I run it in MySQL workbench:

UPDATE document_control SET newIssueNo = 2, file_attachment = CONCAT(SUBSTRING_INDEX(file_attachment, '\\',  LENGTH(file_attachment) - LENGTH(REPLACE(file_attachment, '\\', ''))), '\\Archive\\', SUBSTRING_INDEX(file_attachment, '\\', -1)) where id = 2

1 row(s) affected Rows matched: 1  Changed: 1  Warnings: 0


问:
Why am I getting invalid data from my QTouchPoint?
I have a QGraphicsScene with QGraphicsItems.  I have reimplemented the sceneEvent function and handle multi-touch.

The problem is that randomly I get invalid values out of this section:

```<code>    QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
    QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
    const QTouchEvent::TouchPoint &p0 = touchPoints.first();
</code>```

Gives the following debug information (not all the time):

```<code>Debug: TouchUpdate: p0.scenePos(): QPointF(489.76, 160.71) :
Debug: TouchUpdate: p0.startPos(): QPointF(-8.62078e+14, 1.83351e+15)
</code>```

I have no idea why startPos() should be a random value like that.  Any suggestions?

答:
Are you blindly casting events or using a switch-case statement as below ?</p>

```<code>    bool MyItem::sceneEvent(QEvent *event)
    {
        case QEvent::TouchBegin:
        case QEvent::TouchUpdate:
        case QEvent::TouchEnd:
        {
            QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
            QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();

            //Remember to accept the event too
            event->accept();
            break;
        }
    }
</code>```

Body:
I have a QGraphicsScene with QGraphicsItems.  I have reimplemented the sceneEvent function and handle multi-touch.

The problem is that randomly I get invalid values out of this section:

    QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
    QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
    const QTouchEvent::TouchPoint &p0 = touchPoints.first();

Gives the following debug information (not all the time):

Debug: TouchUpdate: p0.scenePos(): QPointF(489.76, 160.71) :
Debug: TouchUpdate: p0.startPos(): QPointF(-8.62078e+14, 1.83351e+15)

I have no idea why startPos() should be a random value like that.  Any suggestions?

Body:
Are you blindly casting events or using a switch-case statement as below ?

    bool MyItem::sceneEvent(QEvent *event)
    {
        case QEvent::TouchBegin:
        case QEvent::TouchUpdate:
        case QEvent::TouchEnd:
        {
            QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
            QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();

            //Remember to accept the event too
            event->accept();
            break;
        }
    }


问:
Why do tweets that I know have likes have 0 return for their favorite count using the tweepy api?
Basically when I loop up tweets that I know have been "liked" by seeing them on Twitter, and print their favorite count attribute, the count is always 0. Is favorite count not the same as the number of likes/why is favorite count always 0/how do I get the number of likes of a tweet?

Right now I am doing the following:

```<code>print(the_tweet.favorite_count)
</code>```

When I print:

```<code>print(dir(the_tweet))
</code>```

I see a lot of stuff to do with a tweet, including retweet_count and favorite_count but nothing that looks like a "like_count".

答:
I had the same issue, favorite_count shows the likes of your own tweet, while the_tweet object is your user_timeline object which is a mixture of tweets and retweets. Therefore you need to check to see if retweeted_status exist and if so favorite_count for the retweeted tweets are under this list. Please check my example below:

def user_tweets(count):
    '''
    This function uses tweepy to read the user's twitter feed.
    '''
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    # user = api.get_user(twitter_user_name)

    user_tweets = api.user_timeline(twitter_user_name, count=count)
    return user_tweets

user_tweets(4)# returns your latest 4 tweets and retweets

#to list the number of likes for each tweet and retweet:
for tweet in user_tweets:
    try:
        print(tweet.retweeted_status.favorite_count)
    except:
        print(tweet.favorite_count)

```

<p>Also if you are using Django template tags you can use the following:</p>

<pre class="lang-html prettyprint-override"><code>            {% if tweet.retweeted_status %}
            <small>{{ tweet.retweeted_status.favorite_count }}</small>
            {% else %}
            <small>{{ tweet.favorite_count }}</small>
            {% endif %}
</code>```

Body:
Basically when I loop up tweets that I know have been "liked" by seeing them on Twitter, and print their favorite count attribute, the count is always 0. Is favorite count not the same as the number of likes/why is favorite count always 0/how do I get the number of likes of a tweet?

Right now I am doing the following:

print(the_tweet.favorite_count)

When I print:

print(dir(the_tweet))

I see a lot of stuff to do with a tweet, including retweet_count and favorite_count but nothing that looks like a "like_count".

Body:
I had the same issue, favorite_count shows the likes of your own tweet, while the_tweet object is your user_timeline object which is a mixture of tweets and retweets. Therefore you need to check to see if retweeted_status exist and if so favorite_count for the retweeted tweets are under this list. Please check my example below:

def user_tweets(count):
    '''
    This function uses tweepy to read the user's twitter feed.
    '''
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    # user = api.get_user(twitter_user_name)

    user_tweets = api.user_timeline(twitter_user_name, count=count)
    return user_tweets

user_tweets(4)# returns your latest 4 tweets and retweets

#to list the number of likes for each tweet and retweet:
for tweet in user_tweets:
    try:
        print(tweet.retweeted_status.favorite_count)
    except:
        print(tweet.favorite_count)

Also if you are using Django template tags you can use the following:

            {% if tweet.retweeted_status %}
            <small>{{ tweet.retweeted_status.favorite_count }}</small>
            {% else %}
            <small>{{ tweet.favorite_count }}</small>
            {% endif %}


问:
Firebase cookie issue for Twitter Authentication
I am currently trying to allow users to login to my Vue.js application via Twitter authentication. This is essentially the code I am using. Every time I click the Twitter sign in button I get this issue:

A cookie associated with a cross-site resource at http://google.com/ was set without the SameSite attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.

Any idea as to how I can resolve this? Any help would be greatly appreciated. I feel like these two pieces of code could be the issue but I am not so sure.

store.js

```<code>import Vue from 'vue'
import Vuex from 'vuex'
import * as firebase from 'firebase/app'

Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        user: null
    },
    getters: {
        user (state) {
            return state.user
        }
    },
    mutations: {
        SET_USER (state, payload) {
            state.user = payload
        },
        LOGOUT (state, payload) {
            state.user = null
        }
    },
    actions: {
        autoSignIn({ commit }, payload) {
            const newUser = {
                userDetails: payload.providerData
            }
            commit('SET_USER', newUser)
        },

        signIn({ commit }) {
            var provider = new firebase.auth.TwitterAuthProvider();
            firebase.auth().signInWithRedirect(provider);
            firebase.auth().getRedirectResult().then(result => {

                // The signed-in user info.
                var user = result.user;
                commit('SET_USER', user)
            }).catch(error => {
                alert(error)
                return
            })
        },
        logout({ commit }) {
            firebase.auth().signOut().then(function () {
                commit('LOGOUT')
            }).catch(function (error) {
                alert(error)
                return
            });

        }
    }
})
</code>```

main.js

```<code>import Vue from 'vue'
import App from './App'
import router from './router'
import {store} from './vuex/store'
import * as firebase from 'firebase/app'
import Vuex from 'vuex'
import {config} from './firebaseConfig'
// Firebase App (the core Firebase SDK) is always required and must be listed first

// If you enabled Analytics in your project, add the Firebase SDK for Analytics
import "firebase/analytics"

// Add the Firebase products that you want to use
import "firebase/auth"
import "firebase/firestore"

Vue.use(Vuex)

Vue.config.productionTip = false

/* eslint-disable no-new */

firebase.initializeApp(config)

const check = firebase.auth().onAuthStateChanged((user) => {
  new Vue({
    el: '#app',
    router,
    components: { App },
    template: '<App/>',
    store,
    created() {
      if (user) {
        store.dispatch('autoSignIn', user)
      }
    }
  })
  check()
})
</code>```

答: I had the wrong callback url in my Twitter app. Didn't realise firebase gave you a callback URL once you insert the API/secret API key in firebase.</p>

Body:
I am currently trying to allow users to login to my Vue.js application via Twitter authentication. This is essentially the code I am using. Every time I click the Twitter sign in button I get this issue:

A cookie associated with a cross-site resource at http://google.com/ was set without the SameSite attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.

Any idea as to how I can resolve this? Any help would be greatly appreciated. I feel like these two pieces of code could be the issue but I am not so sure.

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import * as firebase from 'firebase/app'

Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        user: null
    },
    getters: {
        user (state) {
            return state.user
        }
    },
    mutations: {
        SET_USER (state, payload) {
            state.user = payload
        },
        LOGOUT (state, payload) {
            state.user = null
        }
    },
    actions: {
        autoSignIn({ commit }, payload) {
            const newUser = {
                userDetails: payload.providerData
            }
            commit('SET_USER', newUser)
        },

        signIn({ commit }) {
            var provider = new firebase.auth.TwitterAuthProvider();
            firebase.auth().signInWithRedirect(provider);
            firebase.auth().getRedirectResult().then(result => {

                // The signed-in user info.
                var user = result.user;
                commit('SET_USER', user)
            }).catch(error => {
                alert(error)
                return
            })
        },
        logout({ commit }) {
            firebase.auth().signOut().then(function () {
                commit('LOGOUT')
            }).catch(function (error) {
                alert(error)
                return
            });

        }
    }
})

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import {store} from './vuex/store'
import * as firebase from 'firebase/app'
import Vuex from 'vuex'
import {config} from './firebaseConfig'
// Firebase App (the core Firebase SDK) is always required and must be listed first

// If you enabled Analytics in your project, add the Firebase SDK for Analytics
import "firebase/analytics"

// Add the Firebase products that you want to use
import "firebase/auth"
import "firebase/firestore"

Vue.use(Vuex)

Vue.config.productionTip = false

/* eslint-disable no-new */

firebase.initializeApp(config)

const check = firebase.auth().onAuthStateChanged((user) => {
  new Vue({
    el: '#app',
    router,
    components: { App },
    template: '<App/>',
    store,
    created() {
      if (user) {
        store.dispatch('autoSignIn', user)
      }
    }
  })
  check()
})


问:
Resizing images to fit inside a container
I'm trying to make a 4 panel screen which would fit the screen of any user who accesses it. The images push everything else out of the div that envolves them. I don't want it to overflow.

My code:

```

How I would like it to look:

答:
Use CSS grid for this:

.container{
  display: grid;
  grid-template-columns: auto minmax(0, 1fr);
}

img{
  height: 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="">
    <img class="" src="https://docplayer.org/docs-images/22/1321497/images/61-0.png">
  </div>
  <div class="">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
  <div class="">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
  <div class="">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
</div></code>```

Body:
I'm trying to make a 4 panel screen which would fit the screen of any user who accesses it. The images push everything else out of the div that envolves them. I don't want it to overflow.

My code:

How I would like it to look:

Body:
Use CSS grid for this:

.container{
  display: grid;
  grid-template-columns: auto minmax(0, 1fr);
}

img{
  height: 300px;
}

<div class="container">
  <div class="">
    <img class="" src="https://docplayer.org/docs-images/22/1321497/images/61-0.png">
  </div>
  <div class="">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
  <div class="">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
  <div class="">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
</div>


问:
how can i add boot sector in ms dos image file when we are using windows os?
i found that there is a command in linux for adding boot sector to disk image as given:

```<code>dd count=2 seek=0 bs=512 if=..\source\bootload\bootload.bin of=.\mikeos.flp
</code>```

but what is the similar command for windows option.

答: You can install GNU core utils for Windows, you will get the original dd command but compiled for windows.</p>

Body:
i found that there is a command in linux for adding boot sector to disk image as given:

dd count=2 seek=0 bs=512 if=..\source\bootload\bootload.bin of=.\mikeos.flp

but what is the similar command for windows option.


问:
testing select element in react with Jest
I am trying to test functionality of a select element in a React component.

Note: This is not a duplicate of this question because I am not using enzyme, but rather trying to do things simply using act() from React's Test Utilities and running tests with Jest.

Given a component with a select element like this:

class TestSelect extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            choice: "apples",
        };
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(event) {
        this.setState({choice: event.target.value});
    }
    render() {
        return (

                <select value={this.state.choice} onChange={this.handleChange}>
                    <option value="apples">apples</option>
                    <option value="oranges">oranges</option>
                </select>

You like {this.state.choice}

        );
    }
}
```

<p>I would like to be able to test it like this:</p>

<pre class="lang-js prettyprint-override"><code>import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";

test("Should change preference", () => {
    act(() => {
        render(<TestSelect/>, container);
    });
    let message = container.querySelector("h4");
    expect(message.innerHTML).toContain("apples");
    const selectElement = container.querySelector("select");
    act(() => {
        selectElement.dispatchEvent(new Event("change"), {
            target: { value: "oranges"},
            bubbles: true,
        });
    });
    message = container.querySelector("h4");
    // Test fails here: Value does not change
    expect(message.innerHTML).toContain("oranges");
});
</code>```

After a lot of fiddling and trying different options I am not able to simulate an event that ends up changing the selected value in the select element.

答:
I suggest you to use the userEvent from the React Testing Library.

It's very straightforward and simple to use.
Here is the provided example:

```<code>import React from "react";
import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

test("select values", () => {
    const { getByTestId } = render(
        <select multiple data-testid="select-multiple">
            <option data-testid="val1" value="1">
                1
            </option>
            <option data-testid="val2" value="2">
                2
            </option>
            <option data-testid="val3" value="3">
                3
            </option>
        </select>
    );

    userEvent.selectOptions(getByTestId("select-multiple"), ["1", "3"]);

    expect(getByTestId("val1").selected).toBe(true);
    expect(getByTestId("val2").selected).toBe(false);
    expect(getByTestId("val3").selected).toBe(true);
});
</code>```

Body:
I am trying to test functionality of a select element in a React component.

Note: This is not a duplicate of this question because I am not using enzyme, but rather trying to do things simply using act() from React's Test Utilities and running tests with Jest.

Given a component with a select element like this:

class TestSelect extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            choice: "apples",
        };
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(event) {
        this.setState({choice: event.target.value});
    }
    render() {
        return (

                <select value={this.state.choice} onChange={this.handleChange}>
                    <option value="apples">apples</option>
                    <option value="oranges">oranges</option>
                </select>

You like {this.state.choice}

        );
    }
}

I would like to be able to test it like this:

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";

test("Should change preference", () => {
    act(() => {
        render(<TestSelect/>, container);
    });
    let message = container.querySelector("h4");
    expect(message.innerHTML).toContain("apples");
    const selectElement = container.querySelector("select");
    act(() => {
        selectElement.dispatchEvent(new Event("change"), {
            target: { value: "oranges"},
            bubbles: true,
        });
    });
    message = container.querySelector("h4");
    // Test fails here: Value does not change
    expect(message.innerHTML).toContain("oranges");
});

After a lot of fiddling and trying different options I am not able to simulate an event that ends up changing the selected value in the select element.

Body:
I suggest you to use the userEvent from the React Testing Library.

It's very straightforward and simple to use.
Here is the provided example:

import React from "react";
import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

test("select values", () => {
    const { getByTestId } = render(
        <select multiple data-testid="select-multiple">
            <option data-testid="val1" value="1">
                1
            </option>
            <option data-testid="val2" value="2">
                2
            </option>
            <option data-testid="val3" value="3">
                3
            </option>
        </select>
    );

    userEvent.selectOptions(getByTestId("select-multiple"), ["1", "3"]);

    expect(getByTestId("val1").selected).toBe(true);
    expect(getByTestId("val2").selected).toBe(false);
    expect(getByTestId("val3").selected).toBe(true);
});


问:
How to get Twitter direct_messages/events/new rate limit
Using the API "https://api.twitter.com/1.1/application/rate_limit_status.json" doesn't retrieve any info about posting direct message API (https://api.twitter.com/1.1/direct_messages/events/new.json) rate limit, even when using this (https://api.twitter.com/1.1/direct_messages/events/new.json) none of the twitter rate limit headers exists (x-rate-limit-limit, x-rate-limit-remaining, x-rate-limit-reset)
So how we can retrieve this API rate limit????

答:
Those headers only apply to read-only endpoints, not for HTTP POST calls. This is not an API rate limit, it is an account limit. Twitter accounts have a maximum number of Direct Messages they can send each day.

The current technical limits for accounts are:

Direct Messages (daily): The limit is 1,000 messages sent per day.

Additionally, there are adaptive limits to enable conversations to occur more easily that do not count to these limits, but are on a per-message basis:

Accounts may send up to 5 messages via the API in reply to a message they have received within 24 hours. Each message received resets this threshold.

So, this is not something that you can get from the API, you have to keep track of these yourself in your code.


问:
having trouble writing a dataframe to an sqlite database
sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.

Here is the exact code to reproduce the error

go to this page with dev tools open

https://stats.nba.com/teams/boxscores-traditional/

on teamgamelogs endpoint right click -> Copy -> copy as curl(bash)

convert to python requests
https://curl.trillworks.com/

```<code>import pandas as pd
import requests
import sqlite3

response = requests.get('https://stats.nba.com/stats/teamgamelogs?DateFrom=&DateTo=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=Totals&Period=0&PlusMinus=N&Rank=N&Season=2019-20&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&VsConference=&VsDivision=', headers=headers, cookies=cookies)

conn = sqlite3.connect('nbastats.db')
stats = response.json()

df = pd.DataFrame(stats["resultSets"])

df.to_sql('Team_stats', conn, if_exists='append')
</code>```

I dont understand why I am getting this error.

```<code>sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.
</code>```

答:
I ended up figuring it out.

my different way of doing things was to use the .get_data_frames()[0] function provided by the API and then I was able to get a data frame by selecting the 0 position in the list. This was able to be inserted into the database.

Body:
sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.

Here is the exact code to reproduce the error

go to this page with dev tools open

https://stats.nba.com/teams/boxscores-traditional/

on teamgamelogs endpoint right click -> Copy -> copy as curl(bash)

convert to python requests
https://curl.trillworks.com/

import pandas as pd
import requests
import sqlite3

response = requests.get('https://stats.nba.com/stats/teamgamelogs?DateFrom=&DateTo=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=Totals&Period=0&PlusMinus=N&Rank=N&Season=2019-20&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&VsConference=&VsDivision=', headers=headers, cookies=cookies)

conn = sqlite3.connect('nbastats.db')
stats = response.json()

df = pd.DataFrame(stats["resultSets"])

df.to_sql('Team_stats', conn, if_exists='append')

I dont understand why I am getting this error.

sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.