问:
MissingResourceException: Can't find bundle for base name sun.util.logging.resources.logging, locale en_US
I am getting,

```<code>Caused by java.lang.InternalError: java.util.MissingResourceException: Can't find bundle for base name sun.util.logging.resources.logging, locale en_US
</code>```

in my application from firebase crash report.

Other details

```<code>Manufacturer: HTC
Model: HTC 10
Android API: 24
</code>```

Here is the stack trace

```<code>java.util.logging.Logger$1.run (Logger.java:1385)
java.util.logging.Logger$1.run (Logger.java:1379)
java.security.AccessController.doPrivileged (AccessController.java:41)
java.util.logging.Logger.findSystemResourceBundle (Logger.java:1378)
java.util.logging.Logger.findResourceBundle (Logger.java:1425)
java.util.logging.Logger.setupResourceInfo (Logger.java:1523)
java.util.logging.Logger.<init> (Logger.java:266)
java.util.logging.Logger.<init> (Logger.java:261)
java.util.logging.LogManager$SystemLoggerContext.demandLogger (LogManager.java:734)
java.util.logging.LogManager.demandSystemLogger (LogManager.java:399)
java.util.logging.Logger.getPlatformLogger (Logger.java:474)
java.util.logging.LoggingProxyImpl.getLogger (LoggingProxyImpl.java:41)
sun.util.logging.LoggingSupport.getLogger (LoggingSupport.java:100)
sun.util.logging.PlatformLogger$JavaLoggerProxy.<init> (PlatformLogger.java:636)
sun.util.logging.PlatformLogger$JavaLoggerProxy.<init> (PlatformLogger.java:631)
sun.util.logging.PlatformLogger.<init> (PlatformLogger.java:246)
sun.util.logging.PlatformLogger.getLogger (PlatformLogger.java:205)
java.net.CookieManager.put (CookieManager.java:262)
okhttp3.JavaNetCookieJar.saveFromResponse (JavaNetCookieJar.java:47)
okhttp3.internal.http.HttpHeaders.receiveHeaders (HttpHeaders.java:182)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:95)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:120)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.RealCall.getResponseWithInterceptorChain (RealCall.java:185)
okhttp3.RealCall.execute (RealCall.java:69)
</code>```

Here is the relevant Logger code

```<code>private static ResourceBundle findSystemResourceBundle(final Locale var0) {
        return (ResourceBundle)AccessController.doPrivileged(new PrivilegedAction() {
            public ResourceBundle run() {
                try {
                    return ResourceBundle.getBundle("sun.util.logging.resources.logging", var0, ClassLoader.getSystemClassLoader());
                } catch (MissingResourceException var2) {
                    throw new InternalError(var2.toString());
                }
            }
        });
    }
</code>```

I have got crash report for locale en_AU too.

Since the crashing code is not controlled by me, how do I prevent this crash?

答:
Analysis:

MissingResourceException: Can't find bundle for base name
  sun.util.logging.resources.logging, locale en_US

The system generates candidate bundle names

```<code>sun/util/logging/resources/logging_en_US
sun/util/logging/resources/logging_en
sun/util/logging/resources/logging
</code>```

For each candidate bundle name, it attempts to load a resource bundle:

First, it attempts to load a class using the generated class name.

If such a class can be found and loaded using the specified class
  loader, is assignment compatible with ResourceBundle, is accessible
  from ResourceBundle, and can be instantiated, getBundle creates a new
  instance of this class and uses it as the result resource bundle.

Otherwise, getBundle attempts to locate a property resource file using the generated properties file name.

It generates a path name
  from the candidate bundle name by replacing all "." characters with
  "/" and appending the string ".properties". It attempts to find a
  "resource" with this name using
  java.lang.ClassLoader.getResource(java.lang.String). (Note that a
  "resource" in the sense of getResource has nothing to do with the
  contents of a resource bundle, it is just a container of data, such as
  a file.) If it finds a "resource", it attempts to create a new
  PropertyResourceBundle instance from its contents. If successful, this
  instance becomes the result resource bundle.

Have a more detailed look here how a ressource is resolved.

Since the system is looking in the classpath for any of these files in descending order (usually there are no _en*.properties)

```<code>sun/util/logging/resources/logging_en_US.properties
sun/util/logging/resources/logging_en.properties
sun/util/logging/resources/logging.properties
</code>```

it would be a workaround to add such a file (or a class as mentioned above) to your app.
The content of the property files looks like this:

```<code># Localizations for Level names.  For the US locale
# these are the same as the non-localized level name.

# The following ALL CAPS words should be translated.
ALL=All
# The following ALL CAPS words should be translated.
SEVERE=Severe
# The following ALL CAPS words should be translated.
WARNING=Warning
# The following ALL CAPS words should be translated.
INFO=Info
# The following ALL CAPS words should be translated.
CONFIG= Config
# The following ALL CAPS words should be translated.
FINE=Fine
# The following ALL CAPS words should be translated.
FINER=Finer
# The following ALL CAPS words should be translated.
FINEST=Finest
# The following ALL CAPS words should be translated.
OFF=Off
</code>```

Body:
I am getting,

Caused by java.lang.InternalError: java.util.MissingResourceException: Can't find bundle for base name sun.util.logging.resources.logging, locale en_US

in my application from firebase crash report.

Other details

Manufacturer: HTC
Model: HTC 10
Android API: 24

Here is the stack trace

java.util.logging.Logger$1.run (Logger.java:1385)
java.util.logging.Logger$1.run (Logger.java:1379)
java.security.AccessController.doPrivileged (AccessController.java:41)
java.util.logging.Logger.findSystemResourceBundle (Logger.java:1378)
java.util.logging.Logger.findResourceBundle (Logger.java:1425)
java.util.logging.Logger.setupResourceInfo (Logger.java:1523)
java.util.logging.Logger.<init> (Logger.java:266)
java.util.logging.Logger.<init> (Logger.java:261)
java.util.logging.LogManager$SystemLoggerContext.demandLogger (LogManager.java:734)
java.util.logging.LogManager.demandSystemLogger (LogManager.java:399)
java.util.logging.Logger.getPlatformLogger (Logger.java:474)
java.util.logging.LoggingProxyImpl.getLogger (LoggingProxyImpl.java:41)
sun.util.logging.LoggingSupport.getLogger (LoggingSupport.java:100)
sun.util.logging.PlatformLogger$JavaLoggerProxy.<init> (PlatformLogger.java:636)
sun.util.logging.PlatformLogger$JavaLoggerProxy.<init> (PlatformLogger.java:631)
sun.util.logging.PlatformLogger.<init> (PlatformLogger.java:246)
sun.util.logging.PlatformLogger.getLogger (PlatformLogger.java:205)
java.net.CookieManager.put (CookieManager.java:262)
okhttp3.JavaNetCookieJar.saveFromResponse (JavaNetCookieJar.java:47)
okhttp3.internal.http.HttpHeaders.receiveHeaders (HttpHeaders.java:182)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:95)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:120)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.RealCall.getResponseWithInterceptorChain (RealCall.java:185)
okhttp3.RealCall.execute (RealCall.java:69)

Here is the relevant Logger code

private static ResourceBundle findSystemResourceBundle(final Locale var0) {
        return (ResourceBundle)AccessController.doPrivileged(new PrivilegedAction() {
            public ResourceBundle run() {
                try {
                    return ResourceBundle.getBundle("sun.util.logging.resources.logging", var0, ClassLoader.getSystemClassLoader());
                } catch (MissingResourceException var2) {
                    throw new InternalError(var2.toString());
                }
            }
        });
    }

I have got crash report for locale en_AU too.

Since the crashing code is not controlled by me, how do I prevent this crash?

Body:
Analysis:

MissingResourceException: Can't find bundle for base name
  sun.util.logging.resources.logging, locale en_US

The system generates candidate bundle names

sun/util/logging/resources/logging_en_US
sun/util/logging/resources/logging_en
sun/util/logging/resources/logging

For each candidate bundle name, it attempts to load a resource bundle:

First, it attempts to load a class using the generated class name.

If such a class can be found and loaded using the specified class
  loader, is assignment compatible with ResourceBundle, is accessible
  from ResourceBundle, and can be instantiated, getBundle creates a new
  instance of this class and uses it as the result resource bundle.

Otherwise, getBundle attempts to locate a property resource file using the generated properties file name.

It generates a path name
  from the candidate bundle name by replacing all "." characters with
  "/" and appending the string ".properties". It attempts to find a
  "resource" with this name using
  java.lang.ClassLoader.getResource(java.lang.String). (Note that a
  "resource" in the sense of getResource has nothing to do with the
  contents of a resource bundle, it is just a container of data, such as
  a file.) If it finds a "resource", it attempts to create a new
  PropertyResourceBundle instance from its contents. If successful, this
  instance becomes the result resource bundle.

Have a more detailed look here how a ressource is resolved.

Since the system is looking in the classpath for any of these files in descending order (usually there are no _en*.properties)

sun/util/logging/resources/logging_en_US.properties
sun/util/logging/resources/logging_en.properties
sun/util/logging/resources/logging.properties

it would be a workaround to add such a file (or a class as mentioned above) to your app.
The content of the property files looks like this:

# Localizations for Level names.  For the US locale
# these are the same as the non-localized level name.

# The following ALL CAPS words should be translated.
ALL=All
# The following ALL CAPS words should be translated.
SEVERE=Severe
# The following ALL CAPS words should be translated.
WARNING=Warning
# The following ALL CAPS words should be translated.
INFO=Info
# The following ALL CAPS words should be translated.
CONFIG= Config
# The following ALL CAPS words should be translated.
FINE=Fine
# The following ALL CAPS words should be translated.
FINER=Finer
# The following ALL CAPS words should be translated.
FINEST=Finest
# The following ALL CAPS words should be translated.
OFF=Off


来源: stackexchange

问:
Why does flexbox not center my image?
```<code>section
{
background-color: #EEEEEE;
margin: 10vmin 5vmin;
padding: 2vmin;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
}

img
{
height: 30vmax;
border: 1vmin solid black;
border-radius: 30vmax;
margin: 1vmin;
}
</code>```

Entire source code available here : https://codepen.io/de_arth/pen/dvLoyO/

Basically, I'm able to center everything BUT an image, (and a link in the very last section) with flexbox, even though it should be in a single straight line on mobile and desktop displays. What am I doing wrong?

答:
Add text-align:center

```<code>section {
    background-color: #eeeeee;
    flex-flow: column wrap;
    margin: 10vmin 5vmin;
    padding: 2vmin;
    text-align: center;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why does flexbox not center my image?

Body:
section
{
background-color: #EEEEEE;
margin: 10vmin 5vmin;
padding: 2vmin;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
}

img
{
height: 30vmax;
border: 1vmin solid black;
border-radius: 30vmax;
margin: 1vmin;
}

Entire source code available here : https://codepen.io/de_arth/pen/dvLoyO/

Basically, I'm able to center everything BUT an image, (and a link in the very last section) with flexbox, even though it should be in a single straight line on mobile and desktop displays. What am I doing wrong?

Body:
Add text-align:center

section {
    background-color: #eeeeee;
    flex-flow: column wrap;
    margin: 10vmin 5vmin;
    padding: 2vmin;
    text-align: center;
}


问:
Nested array error
I know this is a really newbie question but it has thrown me for days and I can't seem to find a solution that I actually understand.

I am trying to make a nested array to store latitude and longitude, however it Xcode/playground throws a EXC_BAD_INSTRUCTION error.

I want to declare, initialise and print the contents of an array. What am I doing wrong?

```<code>var arrayLocations:[[Float]] = []

arrayLocations[0] = [27.1750199, 78.0399665]

print("\(arrayLocations[0][0]) and \(arrayLocations[0][1])")
</code>```

答:
As vadian said on his answer

You cannot assign a value to index 0 because there is no index 0 if
the array is empty.

You have to append or insert the item:

arrayLocations.append([27.1750199, 78.0399665])

I suggest that you make use of this Collection extension so that your code won't crash often

```<code>extension Collection where Indices.Iterator.Element == Index {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}
</code>```

By using this you could just use if let blocks

Sample:

```<code>if let aLocation = arrayLocations[safe: 0] {
    aLocation = [27.1750199, 78.0399665]
}
</code>```

This ensures that even if you try to access an object of index 0 your code won't crash.

Suggestion:

Note: This suggestion is not part of the answer, but rather something to improve your code.

It looks like you're trying to create an array of latitude and longitude. Using an array for the latitude and longitude object isn't very wise. I suggest that you create an object instead, it can be a struct or a typeAlias

For example:

```<code>struct CoordinateStruct {
    var longitude: Float
    var latitude: Float
}

/* or */

typealias CoordinateTypeAlias = (latitude: Float, longitude: Float)

/************************* */

// Your code would then look like this
var arrayLocations:[CoordinateStruct] = []
arrayLocations.append(CoordinateStruct(longitude: 27.12312312, latitude: 78.123123))

/* or */

var arrayLocations:[CoordinateTypeAlias] = []
arrayLocations.append((27.12312312, 78.123123))

// Which would make accessing them very easy and readable, like this.

if let aLocation = arrayLocations[safe: 0] {
    print(aLocation.longitude)
    print(aLocation.latitude)

    // instead of this
    print(aLocation[0]) // a person who reads your code won't understand this
    print(aLocation[1]) // a person who reads your code won't understand this
}
</code>```

Title: Nested array error

Body:
I know this is a really newbie question but it has thrown me for days and I can't seem to find a solution that I actually understand.

I am trying to make a nested array to store latitude and longitude, however it Xcode/playground throws a EXC_BAD_INSTRUCTION error.

I want to declare, initialise and print the contents of an array. What am I doing wrong?

var arrayLocations:[[Float]] = []

arrayLocations[0] = [27.1750199, 78.0399665]

print("\(arrayLocations[0][0]) and \(arrayLocations[0][1])")

Body:
As vadian said on his answer

You cannot assign a value to index 0 because there is no index 0 if
the array is empty.

You have to append or insert the item:

arrayLocations.append([27.1750199, 78.0399665])

I suggest that you make use of this Collection extension so that your code won't crash often

extension Collection where Indices.Iterator.Element == Index {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

By using this you could just use if let blocks

Sample:

if let aLocation = arrayLocations[safe: 0] {
    aLocation = [27.1750199, 78.0399665]
}

This ensures that even if you try to access an object of index 0 your code won't crash.

Suggestion:

Note: This suggestion is not part of the answer, but rather something to improve your code.

It looks like you're trying to create an array of latitude and longitude. Using an array for the latitude and longitude object isn't very wise. I suggest that you create an object instead, it can be a struct or a typeAlias

For example:

struct CoordinateStruct {
    var longitude: Float
    var latitude: Float
}

/* or */

typealias CoordinateTypeAlias = (latitude: Float, longitude: Float)

/************************* */

// Your code would then look like this
var arrayLocations:[CoordinateStruct] = []
arrayLocations.append(CoordinateStruct(longitude: 27.12312312, latitude: 78.123123))

/* or */

var arrayLocations:[CoordinateTypeAlias] = []
arrayLocations.append((27.12312312, 78.123123))

// Which would make accessing them very easy and readable, like this.

if let aLocation = arrayLocations[safe: 0] {
    print(aLocation.longitude)
    print(aLocation.latitude)

    // instead of this
    print(aLocation[0]) // a person who reads your code won't understand this
    print(aLocation[1]) // a person who reads your code won't understand this
}


问:
How to redirect HTTP traffic to HTTPS using an .htaccess file in WordPress
I need to redirect my WordPress site to HTTP to HTTPS through .htaccess file.
(e.g. http://www.example.com) to (e.g. https://www.example.com)
Please help me out to do that.</p>

答:
Redirect to the https in wordpress. And wordpress ttake over your all requests.</p>

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
</code>```

Body:
Redirect to the https in wordpress. And wordpress ttake over your all requests.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>


问:
Difference among the Azure CosmosDB Query Explorer's results and the Azure Functions results
I executed a following query on the CosmosDB Query Explorer.

```<code>SELECT c.id, c.created_at FROM c
WHERE c.created_at_epoch <= 1499871600 - 86400*31
AND (CEILING(1499871600/86400) - CEILING(c.created_at_epoch / 86400)) % 31 = 0
</code>```

That's result is followings.

```<code>[
  {
    "id": "70251cbf-44b3-4cd9-991f-81127ad78bca",
    "created_at": "2017-05-11 18:46:16"
  },
  {
    "id": "0fa31de2-4832-49ea-a0c6-b517d64ede85",
    "created_at": "2017-05-11 18:48:22"
  },
  {
    "id": "b9959d15-92e7-41c3-8eff-718c4ab2be6e",
    "created_at": "2017-05-11 19:01:43"
  }
]
</code>```

It looks that problem does not exist.

Next, I replaced epoch values that defined statically to placeholders for using it as sqlQuery of the Azure Functions DocumentDB input bindings. Then, I replaced a modulations symbol to %modulationsymbol% for avoiding this issue

```<code>SELECT c.id, c.created_at FROM c
WHERE c.created_at_epoch <= {epoch} - 86400*31
AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400))  %modulationsymbol% 31 = 0
</code>```

And I defined modulationsymbol = % as an application setting.

Then, I specified the function as follows.

```<code>// index.js
module.exports = function (context, myQueueItem) {
    context.log(context.bindings.members, myQueueItem);
    context.done();
};

// function.json
{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "myqueue",
      "connection": "MYSTORAGE"
    },
    {
      "type": "documentDB",
      "name": "members",
      "databaseName": "myproject-db",
      "collectionName": "member",
      "sqlQuery": "SELECT c.id, c.created_at FROM c  WHERE {epoch} - c.created_at_epoch >= 86400*31  AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) %modulationsymbol% 31 = 0",
      "connection": "MYCOSMOSDB",
      "direction": "in"
    }
  ],
  "disabled": true
}
</code>```

Afterward, I triggered the function and this result is followings.

```<code>2017-07-05T03:57:29.640 Function started (Id=d980521e-d23a-4bda-a730-57a236bcd011)
2017-07-05T03:57:30.594 [] { epoch: 1499871600 }
2017-07-05T03:57:30.594 Function completed (Success, Id=d980521e-d23a-4bda-a730-57a236bcd011, Duration=951ms)
</code>```

It looks context.bindings.members is a empty list. It differenced from the  CosmosDB Query Explorer's result.

Why appeared this differences?

答:
After print out the {epoch}, I found its type is string and the expected type is number instead of string. That is the reason of getting empty list when use the same query.

To fix this issue, you could convert the type to number before using it to filter your query result. Steps below for your reference.

Step 1, Create a UDF which could convert string to number. Script Explorer->Create User Defined Function

```<code>function toNumber(ts) {
   return parseInt(ts);
}
</code>```

Step 2, After created the ConvertToNumber function, you could use it to convert the type of {epoch} to number.

```<code>SELECT c.id, c.created_at FROM c
WHERE c.created_at_epoch <= udf.ConvertToNumber({epoch}) - 86400*31
AND (CEILING(udf.ConvertToNumber({epoch})/86400) - CEILING(c.created_at_epoch / 86400))  %modulationsymbol% 31 = 0
</code>```

If you are familiar with C#, you could create the function with C#. Since C# is a strongly typed language. We can define a class which is used to deserialize the message from queue. It will convert the type in language layer.

```<code>public class EpochMessage
{
    public int epoch { get; set; }
}
</code>```

The whole function could be like this.

```<code>using System;

public static void Run(EpochMessage myQueueItem, TraceWriter log, IEnumerable<dynamic> members)
{
    log.Info(context.bindings.members, myQueueItem);
}

public class EpochMessage
{
    public int epoch { get; set; }
}
</code>```

Body:
I executed a following query on the CosmosDB Query Explorer.

SELECT c.id, c.created_at FROM c
WHERE c.created_at_epoch <= 1499871600 - 86400*31
AND (CEILING(1499871600/86400) - CEILING(c.created_at_epoch / 86400)) % 31 = 0

That's result is followings.

[
  {
    "id": "70251cbf-44b3-4cd9-991f-81127ad78bca",
    "created_at": "2017-05-11 18:46:16"
  },
  {
    "id": "0fa31de2-4832-49ea-a0c6-b517d64ede85",
    "created_at": "2017-05-11 18:48:22"
  },
  {
    "id": "b9959d15-92e7-41c3-8eff-718c4ab2be6e",
    "created_at": "2017-05-11 19:01:43"
  }
]

It looks that problem does not exist.

Next, I replaced epoch values that defined statically to placeholders for using it as sqlQuery of the Azure Functions DocumentDB input bindings. Then, I replaced a modulations symbol to %modulationsymbol% for avoiding this issue

SELECT c.id, c.created_at FROM c
WHERE c.created_at_epoch <= {epoch} - 86400*31
AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400))  %modulationsymbol% 31 = 0

And I defined modulationsymbol = % as an application setting.

Then, I specified the function as follows.

// index.js
module.exports = function (context, myQueueItem) {
    context.log(context.bindings.members, myQueueItem);
    context.done();
};

// function.json
{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "myqueue",
      "connection": "MYSTORAGE"
    },
    {
      "type": "documentDB",
      "name": "members",
      "databaseName": "myproject-db",
      "collectionName": "member",
      "sqlQuery": "SELECT c.id, c.created_at FROM c  WHERE {epoch} - c.created_at_epoch >= 86400*31  AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) %modulationsymbol% 31 = 0",
      "connection": "MYCOSMOSDB",
      "direction": "in"
    }
  ],
  "disabled": true
}

Afterward, I triggered the function and this result is followings.

2017-07-05T03:57:29.640 Function started (Id=d980521e-d23a-4bda-a730-57a236bcd011)
2017-07-05T03:57:30.594 [] { epoch: 1499871600 }
2017-07-05T03:57:30.594 Function completed (Success, Id=d980521e-d23a-4bda-a730-57a236bcd011, Duration=951ms)

It looks context.bindings.members is a empty list. It differenced from the  CosmosDB Query Explorer's result.

Why appeared this differences?

Body:
After print out the {epoch}, I found its type is string and the expected type is number instead of string. That is the reason of getting empty list when use the same query.

To fix this issue, you could convert the type to number before using it to filter your query result. Steps below for your reference.

Step 1, Create a UDF which could convert string to number. Script Explorer->Create User Defined Function

function toNumber(ts) {
   return parseInt(ts);
}

Step 2, After created the ConvertToNumber function, you could use it to convert the type of {epoch} to number.

SELECT c.id, c.created_at FROM c
WHERE c.created_at_epoch <= udf.ConvertToNumber({epoch}) - 86400*31
AND (CEILING(udf.ConvertToNumber({epoch})/86400) - CEILING(c.created_at_epoch / 86400))  %modulationsymbol% 31 = 0

If you are familiar with C#, you could create the function with C#. Since C# is a strongly typed language. We can define a class which is used to deserialize the message from queue. It will convert the type in language layer.

public class EpochMessage
{
    public int epoch { get; set; }
}

The whole function could be like this.

using System;

public static void Run(EpochMessage myQueueItem, TraceWriter log, IEnumerable<dynamic> members)
{
    log.Info(context.bindings.members, myQueueItem);
}

public class EpochMessage
{
    public int epoch { get; set; }
}


问:
How to prevent an image size from changing when I resize the browser
How can i prevent an image from resizing when i try to change the browser's size? Here's an example of what I am talking about. Try to resize your browser and you'll see the image not changing. It seems simple but I've tried everything I know without success.

Thanks

答:
There are many ways you can ensure that the image size doesn't change.

```<code><!DOCTYPE html>
<html>
    <style>
    img {
        width = 100px;//or any size you want but not in '%'
        height = auto;//or in px or in em
    }
    </style>
    <body>
        <img src="imgsrc" alt='img'>
    </body>
</html>
</code>```

the width can be any size you want but make sure the length unit that use should be an absolute unit. In css following are the absolute units:

cm (centimeters)

mm (millimeters)

in (inches)

px (pixels)

pt (points, 1 point is 72nd part of an inch)

pc (picas, 1picas is 12th part of a point)

You can, if you want use 'em' as essential 1em is means the current font size and you can then sent the current font size in px which is absolute and isn't affected by browser re-size.

Same goes with height but you should set the height to auto as in that case you are preserving the aspect ratio of the original image.

For more information on CSS units of length refer this w3-school reference.

Body:
There are many ways you can ensure that the image size doesn't change.

<!DOCTYPE html>
<html>
    <style>
    img {
        width = 100px;//or any size you want but not in '%'
        height = auto;//or in px or in em
    }
    </style>
    <body>
        <img src="imgsrc" alt='img'>
    </body>
</html>

the width can be any size you want but make sure the length unit that use should be an absolute unit. In css following are the absolute units:

cm (centimeters)

mm (millimeters)

in (inches)

px (pixels)

pt (points, 1 point is 72nd part of an inch)

pc (picas, 1picas is 12th part of a point)

You can, if you want use 'em' as essential 1em is means the current font size and you can then sent the current font size in px which is absolute and isn't affected by browser re-size.

Same goes with height but you should set the height to auto as in that case you are preserving the aspect ratio of the original image.

For more information on CSS units of length refer this w3-school reference.


问:
How to populate Dropdown with jQuery each() Loop
i want to to exactly the same like this:

```<code>window.onload = function populateDropdown(){
    console.log('Hallo i bims, ein Method')
    for(var i = 0; i < 100; i++){
        var select = document.getElementById('age');
        select.options[select.options.length] = new Option(i, i);
    }
};
</code>```

in jQuery.. i already tried it with $.each(), but i don't understand how i can do the the step:

```<code>(;i < 99; i++)
</code>```

Can u give me some hints pls ?

答:
Here is simple example of for loop in JQuery:

```<code>var totalNumbers = 99;
for (var i = 0; i < totalNumbers; i++) {
  //creates option tag
  jQuery('<option/>', {
    value: i,
    html: i
  }).appendTo('#ID_OF_SELECT');
}
</code>```

Body:
i want to to exactly the same like this:

window.onload = function populateDropdown(){
    console.log('Hallo i bims, ein Method')
    for(var i = 0; i < 100; i++){
        var select = document.getElementById('age');
        select.options[select.options.length] = new Option(i, i);
    }
};

in jQuery.. i already tried it with $.each(), but i don't understand how i can do the the step:

(;i < 99; i++)

Can u give me some hints pls ?

Body:
Here is simple example of for loop in JQuery:

var totalNumbers = 99;
for (var i = 0; i < totalNumbers; i++) {
  //creates option tag
  jQuery('<option/>', {
    value: i,
    html: i
  }).appendTo('#ID_OF_SELECT');
}


问:
how to refresh bindings in textBox?
How can I refresh bindings I mean run Property Get of the field which is Bound to the text manually :/ I cant find solution. My textBox is bound to bindingSource. I want to refresh this bindingSource manually</p>

答:
```<code>bindingSource.ResetCurrentItem();
</code>```

Causes a control bound to the BindingSource to reread the currently selected item and refresh its displayed value.

```<code>bindingSource.ResetBindings();
</code>```

Causes a control bound to the BindingSource to reread all the items in the list and refresh their displayed values.

ContentLicense: CC BY-SA 2.5

Title: how to refresh bindings in textBox?

Body:
bindingSource.ResetCurrentItem();

Causes a control bound to the BindingSource to reread the currently selected item and refresh its displayed value.

bindingSource.ResetBindings();

Causes a control bound to the BindingSource to reread all the items in the list and refresh their displayed values.


问:
How to Setup Jenkins for IOS simulator using Appium Server from Mac
I've designed a framework using BDD in Java and using Appium Maven, for iOS Simulator and real Device which works totally fine in local machine.

but When I configure to Jenkins, Its working fine for Real device but for Simulator, Jenkins to not talking appium server.

Is there any plugins or configs changes i need to follow.

PS: As of now, I'm running Jenkins in my local machine

答:
We should allow Jenkins to Run GUI Applications:

Follow this link for configuration steps on Mac:

Jenkins Mac Setup to Open iOS Simulator


答:
You can do it like this. In each iteration we're creating a new option element and setting both its text and value to i. Then we append it to the select with .appendChild().

window.onload = function populateDropdown(){
  var select = document.getElementById('age');

  for (var i = 0; i < 100; i++) {
    var option = document.createElement("option");
    option.text = i;
    option.value = i;
    select.appendChild(option);
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="age"></select></code>```

Title: How to populate Dropdown with jQuery each() Loop

Body:
You can do it like this. In each iteration we're creating a new option element and setting both its text and value to i. Then we append it to the select with .appendChild().

window.onload = function populateDropdown(){
  var select = document.getElementById('age');

  for (var i = 0; i < 100; i++) {
    var option = document.createElement("option");
    option.text = i;
    option.value = i;
    select.appendChild(option);
  }
};

<select id="age"></select>


问:
iOS - Cannot call value of non-function type 'NSProgress'
I'm trying to download a file using Alamofire, with progress. But I get this error at the progress line.

Cannot call value of non-function type 'NSProgress'

What's the problem? All the examples I've seen, namely the official one, do the exact same thing!

```<code>Alamofire.download(.GET, nsurl!.absoluteString,     destination: { (temporaryURL, response) in
    return filepath
})
    .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in // <------ ERROR HERE
        dispatch_async(dispatch_get_main_queue(), {
            self.progressBar?.progress = totalBytesRead / totalBytesExpectedToRead
        })
    }
    .response { (request, response, _, error) in
        self.loadImageFromFile(filepath.absoluteString)
}
</code>```

EDIT:

After @mvoelkl's suggestion, I added parenthesis to the progress function. But the result stayed the same:

答:
For me the solution was to add Float around progress.fractionCompleted, so use it like this:

```<code>.uploadProgress{ progress in
    self.updateProgressBar(imagesToDo: images.count, prog: Float(progress.fractionCompleted))
}
</code>```

thanks to:
https://github.com/Alamofire/Alamofire/issues/1652#issuecomment-259020449

Body:
I'm trying to download a file using Alamofire, with progress. But I get this error at the progress line.

Cannot call value of non-function type 'NSProgress'

What's the problem? All the examples I've seen, namely the official one, do the exact same thing!

Alamofire.download(.GET, nsurl!.absoluteString,     destination: { (temporaryURL, response) in
    return filepath
})
    .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in // <------ ERROR HERE
        dispatch_async(dispatch_get_main_queue(), {
            self.progressBar?.progress = totalBytesRead / totalBytesExpectedToRead
        })
    }
    .response { (request, response, _, error) in
        self.loadImageFromFile(filepath.absoluteString)
}

EDIT:

After @mvoelkl's suggestion, I added parenthesis to the progress function. But the result stayed the same:

Body:
For me the solution was to add Float around progress.fractionCompleted, so use it like this:

.uploadProgress{ progress in
    self.updateProgressBar(imagesToDo: images.count, prog: Float(progress.fractionCompleted))
}

thanks to:
https://github.com/Alamofire/Alamofire/issues/1652#issuecomment-259020449


问:
Counting number of words in Python file
I'm trying to count the number of instances several words appear in a file.

Here is my code:

```<code>#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))
</code>```

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

答:
Short solution using collections.Counter object:

```<code>import collections

with open('my_output', 'r') as f:
    wordnames = ('wordA', 'wordB', 'wordC')
    counts = (i for i in collections.Counter(f.read().split()).items() if i[0] in wordnames)
    for c in counts:
        print(c[0], c[1])
</code>```

For the following sample text line:

```<code>'wordA some dfasd asdasdword B wordA sdfsd sdasdasdddasd wordB wordC wordC sdfsdfsdf wordA'
</code>```

we would obtain the output:

```<code>wordB 1
wordC 2
wordA 3
</code>```

Title: Counting number of words in Python file

Body:
I'm trying to count the number of instances several words appear in a file.

Here is my code:

#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

Body:
Short solution using collections.Counter object:

import collections

with open('my_output', 'r') as f:
    wordnames = ('wordA', 'wordB', 'wordC')
    counts = (i for i in collections.Counter(f.read().split()).items() if i[0] in wordnames)
    for c in counts:
        print(c[0], c[1])

For the following sample text line:

'wordA some dfasd asdasdword B wordA sdfsd sdasdasdddasd wordB wordC wordC sdfsdfsdf wordA'

we would obtain the output:

wordB 1
wordC 2
wordA 3


问:
Detecting Chrome browser with AJAX
I use Sys.Browser.name for borwser detection, but Chrome detected as safari.

答:
That is because you're checking for "webkit", which happens to exist in both safari and chrome.

Chrome

5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10

Safari

5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4

Ensure that it is webkit (as I guess you're doing already) and also check for "Chrome".

Edit: What exactly is your code platform? Sys.Browser.Name doesn't sound familiar to me. Also, what is the exact code you're using?

Edit 2: You still didn't mention what code you are using. 1. I don't have .NET here. 2. I can't code it up for you right now. 3. I need to see you doing the comparison. 4. I largely forgot how C#/VB works, so seeing your code will great help out.

Without more info, I can't help more than that, sorry.

Title: Detecting Chrome browser with AJAX


问:
Does HTML5 allow drag-drop upload of folders or a folder tree?
I haven't seen any examples that do this. Is this not allowed in the API spec?

I am searching for an easy drag-drop solution for uploading an entire folder tree of photos.

答:
This function will give you a promise for array of all dropped files, like <input type="file"/>.files:

function getFilesWebkitDataTransferItems(dataTransferItems) {
  function traverseFileTreePromise(item, path='') {
    return new Promise( resolve => {
      if (item.isFile) {
        item.file(file => {
          file.filepath = path + file.name //save full path
          files.push(file)
          resolve(file)
        })
      } else if (item.isDirectory) {
        let dirReader = item.createReader()
        dirReader.readEntries(entries => {
          let entriesPromises = []
          for (let entr of entries)
            entriesPromises.push(traverseFileTreePromise(entr, path + item.name + "/"))
          resolve(Promise.all(entriesPromises))
        })
      }
    })
  }

  let files = []
  return new Promise((resolve, reject) => {
    let entriesPromises = []
    for (let it of dataTransferItems)
      entriesPromises.push(traverseFileTreePromise(it.webkitGetAsEntry()))
    Promise.all(entriesPromises)
      .then(entries => {
        //console.log(entries)
        resolve(files)
      })
  })
}
```
<p>Usage:</p>
<pre class="lang-js prettyprint-override"><code>dropArea.addEventListener("drop", function(event) {
  event.preventDefault();

  var items = event.dataTransfer.items;
  getFilesFromWebkitDataTransferItems(items)
    .then(files => {
      ...
    })
}, false);
</code>```

NPM package:
https://www.npmjs.com/package/datatransfer-files-promise

Usage example:
https://github.com/grabantot/datatransfer-files-promise/blob/master/index.html

ContentLicense: CC BY-SA 4.0

Body:
This function will give you a promise for array of all dropped files, like <input type="file"/>.files:

function getFilesWebkitDataTransferItems(dataTransferItems) {
  function traverseFileTreePromise(item, path='') {
    return new Promise( resolve => {
      if (item.isFile) {
        item.file(file => {
          file.filepath = path + file.name //save full path
          files.push(file)
          resolve(file)
        })
      } else if (item.isDirectory) {
        let dirReader = item.createReader()
        dirReader.readEntries(entries => {
          let entriesPromises = []
          for (let entr of entries)
            entriesPromises.push(traverseFileTreePromise(entr, path + item.name + "/"))
          resolve(Promise.all(entriesPromises))
        })
      }
    })
  }

  let files = []
  return new Promise((resolve, reject) => {
    let entriesPromises = []
    for (let it of dataTransferItems)
      entriesPromises.push(traverseFileTreePromise(it.webkitGetAsEntry()))
    Promise.all(entriesPromises)
      .then(entries => {
        //console.log(entries)
        resolve(files)
      })
  })
}

Usage:

dropArea.addEventListener("drop", function(event) {
  event.preventDefault();

  var items = event.dataTransfer.items;
  getFilesFromWebkitDataTransferItems(items)
    .then(files => {
      ...
    })
}, false);

NPM package:
https://www.npmjs.com/package/datatransfer-files-promise

Usage example:
https://github.com/grabantot/datatransfer-files-promise/blob/master/index.html


问:
How to solve expected of type 'a Conduit_async.io in OCaml?
I want to get the headers of http response by cohttp

```<code>open Core
open Async
open Cohttp
open Cohttp_async

let cli_hdr url =
  let uri = Uri.of_string url in
  let%bind resp_head = Cohttp_async.Client.head uri in
  resp_head |> Response.headers |> Header.to_string >>| fun hdrs ->
  print_endline hdrs

let () =
  Command.async_basic
    ~summary:"Retrieve definitions from dudugo search engine"
    Command.Spec.(
      empty
      +> anon ("link" %: string)
    )
    (fun link () -> cli_hdr link)
  |> Command.run
</code>```

But there's an type error when compiling the programming:

```<code>$ corebuild -pkg async,cohttp,cohttp.async test.native
+ ocamlfind ocamlc -c -w A-4-33-40-41-42-43-34-44 -strict-sequence -g -bin-annot -short-paths -thread -package async,cohttp,cohttp.async -package core -ppx 'ppx-jane -as-ppx' -o test.cmo test.ml
File "test.ml", line 17, characters 2-51:
Error: This expression has type string but an expression was expected of type 'a Conduit_async.io
Command exited with code 2.
</code>```

I was wondering how to make it work?

答:
Using let%map instead of let%bind as follows

```<code>let cli_hdr url =
  let uri = Uri.of_string url in
  let%map resp_head = Cohttp_async.Client.head uri in
  resp_head
  |> Response.headers
  |> Header.to_string
  |> print_endline
</code>```

Body:
I want to get the headers of http response by cohttp

open Core
open Async
open Cohttp
open Cohttp_async

let cli_hdr url =
  let uri = Uri.of_string url in
  let%bind resp_head = Cohttp_async.Client.head uri in
  resp_head |> Response.headers |> Header.to_string >>| fun hdrs ->
  print_endline hdrs

let () =
  Command.async_basic
    ~summary:"Retrieve definitions from dudugo search engine"
    Command.Spec.(
      empty
      +> anon ("link" %: string)
    )
    (fun link () -> cli_hdr link)
  |> Command.run

But there's an type error when compiling the programming:

$ corebuild -pkg async,cohttp,cohttp.async test.native
+ ocamlfind ocamlc -c -w A-4-33-40-41-42-43-34-44 -strict-sequence -g -bin-annot -short-paths -thread -package async,cohttp,cohttp.async -package core -ppx 'ppx-jane -as-ppx' -o test.cmo test.ml
File "test.ml", line 17, characters 2-51:
Error: This expression has type string but an expression was expected of type 'a Conduit_async.io
Command exited with code 2.

I was wondering how to make it work?

Body:
Using let%map instead of let%bind as follows

let cli_hdr url =
  let uri = Uri.of_string url in
  let%map resp_head = Cohttp_async.Client.head uri in
  resp_head
  |> Response.headers
  |> Header.to_string
  |> print_endline


问:
Facebook Graph API : possible values for category and categories_list fields of a place
Facebook has not provided with any list of possible values for these fields.

here They have stated some categories for searching but these are not the values that are returned, Instead following values are returned for every place. I'm okay with that but where do I get a list of possible values for fields category and categories_list.

Thank you very much.

{
      "checkins": 78,
      "name": "SODA SHOTS & CAFE",
      "location": {
        "city": "Sangli",
        "country": "India",
        "latitude": 16.85507,
        "longitude": 74.59768,
        "street": "SIDE GATE OF WILLINGDON COLLEGE,NEAR BANK OF MAHARASTRA ,JAYHIND COLONY ,VISHRAMBAGH",
        "zip": "416416"
      },
      "category": "Coffee Shop",
      "category_list": [
        {
          "id": "128673187201735",
          "name": "Coffee Shop"
        },
        {
          "id": "273819889375819",
          "name": "Restaurant"
        }
      ],
      "id": "246105402415302"
    }```

答:
After a few more searches I found an answer

Authoritative List of all Facebook Subcategories

I'm beginner here and don't know what do now about the thread, someone please mark this as duplicate or please take appropriate action.
Thanks, all.


问:
combining two php variables
```<code>    $current_month  = date('M');
    for($m=1; $m<=$current_month; ++$m)
    {
        $monthNamelower=strtolower(date('M', mktime(0, 0, 0, $m, 1))).'';

            if ($jandata!='')
            {
              echo $jandata;
            }

        echo $data2jan;
    }
</code>```

can i replace the month jan with the variable $monthNamelower?

I tried something like this but not working

```<code>    if ('$'.$monthNamelower.'data'!='')
    {
            echo '$'.$monthNamelower.'data';

    }
    echo '$data2'.$monthNamelower;
</code>```

答:
Yes, you can do it.

```<code>if (${$monthNamelower . 'data'} != '') {
    echo ${$monthNamelower . 'data'};
}
</code>```

If your value stored in $monthNamelower is j, it will check for variable name jdata and will print it.

You can test this code directly to see effect:

```<code>$monthNamelower = 'j';
$jdata = 'January';
if (${$monthNamelower . 'data'} != '') {
    echo ${$monthNamelower . 'data'};  //Prints 'January'
}
</code>```

Title: combining two php variables

Body:
    $current_month  = date('M');
    for($m=1; $m<=$current_month; ++$m)
    {
        $monthNamelower=strtolower(date('M', mktime(0, 0, 0, $m, 1))).'';

            if ($jandata!='')
            {
              echo $jandata;
            }

        echo $data2jan;
    }

can i replace the month jan with the variable $monthNamelower?

I tried something like this but not working

    if ('$'.$monthNamelower.'data'!='')
    {
            echo '$'.$monthNamelower.'data';

    }
    echo '$data2'.$monthNamelower;

Body:
Yes, you can do it.

if (${$monthNamelower . 'data'} != '') {
    echo ${$monthNamelower . 'data'};
}

If your value stored in $monthNamelower is j, it will check for variable name jdata and will print it.

You can test this code directly to see effect:

$monthNamelower = 'j';
$jdata = 'January';
if (${$monthNamelower . 'data'} != '') {
    echo ${$monthNamelower . 'data'};  //Prints 'January'
}


问:
How to call MongoDB commands using .bat file
I'm trying to execute MongoDB command (for create DB) using .bat file.

For that I've tried:

```<code>cd C:\Program Files\MongoDB\Server\3.4\bin
mongo
mongo --eval "use MyDatabase"
pause
</code>```

But it gives an error missing ; before statement @(shell eval):1:4

How can I solve this issue?

Side: I've already gone through MongoDB SyntaxError: missing ; before statement @(shell)

答:
Put this code in your bat file.

It'll start and activate the mongodb in 2 different admin privileged cmd windows.

Please check the paths before to adjust to your environment.

START "runas /user:administrator" cmd /K "cd C:\Program
Files\MongoDB\Server\3.4\bin &  mongod.exe --dbpath c:\data\db"

TIMEOUT /T 10 START

START "runas /user:administrator" cmd /K "cd C:\Program
Files\MongoDB\Server\3.4\bin &  mongo.exe "

Body:
I'm trying to execute MongoDB command (for create DB) using .bat file.

For that I've tried:

cd C:\Program Files\MongoDB\Server\3.4\bin
mongo
mongo --eval "use MyDatabase"
pause

But it gives an error missing ; before statement @(shell eval):1:4

How can I solve this issue?

Side: I've already gone through MongoDB SyntaxError: missing ; before statement @(shell)


问:
why I can't use var value in my button action?
I want value send to my button...

why I can't use quizWord in my button action??

it occurs "use of unsolved identifier..." error...

```<code>    import UIKit

extension Array
{
    /** Randomizes the order of an array's elements. */
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}
// random

class QuizViewController: UIViewController {

    var tasks : [Task] = []
    var limitRe:Int = 0
    var cards: [Character] = []
    var quizName = [String]()
    var quizfileName = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        //get the data from core data
        getData()

        for q in 0...tasks.count-1 {
            let quiz = tasks[q]
            quizName.append(quiz.name!)
            quizfileName.append(quiz.filename!)
            print(quizName, quizfileName)
        }
        var quizWord = quizName[0]
        var countText: Int = (quizWord.characters.count) - 1

        for _ in 0...countText
        {let index1 = quizWord.index(quizWord.startIndex, offsetBy: limitRe)

            cards.append(quizWord[index1])
            limitRe = limitRe + 1
        }
        cards.shuffle()
        quizPhotoView.image = UIImage(named: "1.jpg")

        if countText >= 0 {lblChar1.text = "\(cards[0])"} else {lblChar1.text = ""}
        if countText >= 1 {lblChar2.text = "\(cards[1])"} else {lblChar2.text = ""}
        if countText >= 2 {lblChar3.text = "\(cards[2])"} else {lblChar3.text = ""}
        if countText >= 3 {lblChar4.text = "\(cards[3])"} else {lblChar4.text = ""}
        if countText >= 4 {lblChar5.text = "\(cards[4])"} else {lblChar5.text = ""}
        if countText >= 5 {lblChar6.text = "\(cards[5])"} else {lblChar6.text = ""}
        if countText >= 6 {lblChar7.text = "\(cards[6])"} else {lblChar7.text = ""}
        if countText >= 7 {lblChar8.text = "\(cards[7])"} else {lblChar8.text = ""}

    }

    @IBOutlet weak var lblChar1: UILabel!
    @IBOutlet weak var lblChar2: UILabel!
    @IBOutlet weak var lblChar3: UILabel!
    @IBOutlet weak var lblChar4: UILabel!
    @IBOutlet weak var lblChar5: UILabel!
    @IBOutlet weak var lblChar6: UILabel!
    @IBOutlet weak var lblChar7: UILabel!
    @IBOutlet weak var lblChar8: UILabel!
    @IBOutlet weak var lblTyped: UILabel!
    @IBOutlet weak var quizPhotoView: UIImageView!

    func getData() {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do {
            tasks = try context.fetch(Task.fetchRequest())
        }
        catch {
            print("Failed")
        }
    }

    @IBAction func butChar1(_ sender: UIButton) {
    if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar1.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar2(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar2.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}
    }
    @IBAction func butChar3(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar3.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar4(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar4.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar5(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar5.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar6(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar6.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar7(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar7.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar8(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar8.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}

}
</code>```

答:
Overview your code there is problem with you quizWord string variable just declare the variable outside viewDidLoad() function

eg.

```<code>var tasks : [Task] = []
var limitRe:Int = 0
var cards: [Character] = []
var quizName = [String]()
var quizfileName = [String]()
**var quizWord  : String = ""**
</code>```

and you good to go
Thanks

Body:
I want value send to my button...

why I can't use quizWord in my button action??

it occurs "use of unsolved identifier..." error...

    import UIKit

extension Array
{
    /** Randomizes the order of an array's elements. */
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}
// random

class QuizViewController: UIViewController {

    var tasks : [Task] = []
    var limitRe:Int = 0
    var cards: [Character] = []
    var quizName = [String]()
    var quizfileName = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        //get the data from core data
        getData()

        for q in 0...tasks.count-1 {
            let quiz = tasks[q]
            quizName.append(quiz.name!)
            quizfileName.append(quiz.filename!)
            print(quizName, quizfileName)
        }
        var quizWord = quizName[0]
        var countText: Int = (quizWord.characters.count) - 1

        for _ in 0...countText
        {let index1 = quizWord.index(quizWord.startIndex, offsetBy: limitRe)

            cards.append(quizWord[index1])
            limitRe = limitRe + 1
        }
        cards.shuffle()
        quizPhotoView.image = UIImage(named: "1.jpg")

        if countText >= 0 {lblChar1.text = "\(cards[0])"} else {lblChar1.text = ""}
        if countText >= 1 {lblChar2.text = "\(cards[1])"} else {lblChar2.text = ""}
        if countText >= 2 {lblChar3.text = "\(cards[2])"} else {lblChar3.text = ""}
        if countText >= 3 {lblChar4.text = "\(cards[3])"} else {lblChar4.text = ""}
        if countText >= 4 {lblChar5.text = "\(cards[4])"} else {lblChar5.text = ""}
        if countText >= 5 {lblChar6.text = "\(cards[5])"} else {lblChar6.text = ""}
        if countText >= 6 {lblChar7.text = "\(cards[6])"} else {lblChar7.text = ""}
        if countText >= 7 {lblChar8.text = "\(cards[7])"} else {lblChar8.text = ""}

    }

    @IBOutlet weak var lblChar1: UILabel!
    @IBOutlet weak var lblChar2: UILabel!
    @IBOutlet weak var lblChar3: UILabel!
    @IBOutlet weak var lblChar4: UILabel!
    @IBOutlet weak var lblChar5: UILabel!
    @IBOutlet weak var lblChar6: UILabel!
    @IBOutlet weak var lblChar7: UILabel!
    @IBOutlet weak var lblChar8: UILabel!
    @IBOutlet weak var lblTyped: UILabel!
    @IBOutlet weak var quizPhotoView: UIImageView!

    func getData() {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do {
            tasks = try context.fetch(Task.fetchRequest())
        }
        catch {
            print("Failed")
        }
    }

    @IBAction func butChar1(_ sender: UIButton) {
    if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar1.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar2(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar2.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}
    }
    @IBAction func butChar3(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar3.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar4(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar4.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar5(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar5.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar6(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar6.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar7(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar7.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar8(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar8.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}

}

Body:
Overview your code there is problem with you quizWord string variable just declare the variable outside viewDidLoad() function

eg.

var tasks : [Task] = []
var limitRe:Int = 0
var cards: [Character] = []
var quizName = [String]()
var quizfileName = [String]()
**var quizWord  : String = ""**

and you good to go
Thanks


问:
Android AccessibilityNodeInfo get image content
If AccessibilityNodeInfo.getClassName() invocation return "android.widget.ImageView", is it possible to get the image content (byte array, bitmap or drawable) from the AccessibilityNodeInfo object?

Note: The viewIdResourceName of the said AccessibilityNodeInfo is null. I have no way to identify the image except performing a checksum on image content.

答: I am not sure if AccessinbilityNodeInfo allows you to get the imageView, but have you considered using getItemCount() to get a list of indexes for your imageViews and attaching them to each imageView using setTag(). You could iterate through the list and get the object needed once the AccessibilityEvent is fired.</p>


问:
Elastic search bool query
My objective is to find out most recent 10 documents which match message id as MSG-1013 and Severity field must be info. Both conditions should satisfied and match text should be exact. I have tried with search query below but it does not give me expected results. What am I doing wrong here ?</p>

```<code>{
    "size": 10,
    "query": {
        "bool": {
            "must": [
                {
                    "match": { "messageId": "MSG-1013" }
                },
                {
                    "match": { "Severity": "Info" }
                }
            ]
        }
    }
}
</code>```

答:
If I have understood you correctly, you want to find the top 10 (recent) documents having exactly fields "messageId" and "Severity". I assume, you don't need a score because your score seems to be the the document timestamp or something else like a date field. For this purpose, you could use the bool filter in combination with a sort query.</p>

```<code>{
    "query": {
        "bool": {
            "filter": [
                { "term": { "messageId": "MSG-1013" } },
                { "term": { "Severity": "Info" } }
            ]
        }
    },
    "sort" : [
        { "documentTimestamp" : {"order" : "desc"}}
    ],
    "size": 10
}
</code>```

Title: Elastic search bool query

Body:
My objective is to find out most recent 10 documents which match message id as MSG-1013 and Severity field must be info. Both conditions should satisfied and match text should be exact. I have tried with search query below but it does not give me expected results. What am I doing wrong here ?

{
    "size": 10,
    "query": {
        "bool": {
            "must": [
                {
                    "match": { "messageId": "MSG-1013" }
                },
                {
                    "match": { "Severity": "Info" }
                }
            ]
        }
    }
}

Body:
If I have understood you correctly, you want to find the top 10 (recent) documents having exactly fields "messageId" and "Severity". I assume, you don't need a score because your score seems to be the the document timestamp or something else like a date field. For this purpose, you could use the bool filter in combination with a sort query.

{
    "query": {
        "bool": {
            "filter": [
                { "term": { "messageId": "MSG-1013" } },
                { "term": { "Severity": "Info" } }
            ]
        }
    },
    "sort" : [
        { "documentTimestamp" : {"order" : "desc"}}
    ],
    "size": 10
}


问:
how to stable hover effect even after mouse out
how to set my hover effect stable even after mouse out ???
    code is working fine but after mouse out div element comes to its
    original state ??

html

```<code><div id="sme"></div>
</code>```

css

```<code>#sme{
    width: 400px;
    height: 400px;
    border: 20px solid #06c999;
/* Rotate */
}
#sme:hover{
transition: all 1.9s ease;
 -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);

}
</code>```

答:
You must have to use animations and add a class when you hover the element like

function hasClass(element, cls) {
  return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

document.getElementById('sme').addEventListener('mouseover', function() {
  if (!hasClass(this, 'animated')) {
    this.className = 'animated';
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sme {
  width: 400px;
  height: 400px;
  border: 20px solid #06c999;
  transition-property: transform;
  transition-duration: 1.9s;
}

#sme:hover,
.animated {
  animation-name: rotate;
  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}</code>```

```

Body:
how to set my hover effect stable even after mouse out ???
    code is working fine but after mouse out div element comes to its
    original state ??

html

css

#sme{
    width: 400px;
    height: 400px;
    border: 20px solid #06c999;
/* Rotate */
}
#sme:hover{
transition: all 1.9s ease;
 -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);

}

Body:
You must have to use animations and add a class when you hover the element like

function hasClass(element, cls) {
  return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

document.getElementById('sme').addEventListener('mouseover', function() {
  if (!hasClass(this, 'animated')) {
    this.className = 'animated';
  }
});

#sme {
  width: 400px;
  height: 400px;
  border: 20px solid #06c999;
  transition-property: transform;
  transition-duration: 1.9s;
}

#sme:hover,
.animated {
  animation-name: rotate;
  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

<div id="sme"></div>


问:
How do i get alt-text for an image from Google Custom Search API
I want to use Google's Custom Search API to get a list of images. How do i get alt-text for each image?</p>

答: I figured it out myself. There is a HTMLsnippet parameter in the response which is what I required.</p>


问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答:
If you are doing Java and desperately need something to get you out of the ohfock-it's-2am-and-I-am-still-coding-this-sql-shite, then please look no further than Grails http://grails.org.

It's everything like Ruby on Rails except that it:

Should be way cooler than Rails

Better performance

Wealth of Java libraries

You get some peace Rails disco noise and get things done.

OwnerDisplayName: nagul

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic

OwnerDisplayName: Seymour Cakes


问:
Android:: Set max-length of EditText programmatically with other InputFilter
I'm using InputFilter like this to allow only alpha and numbers

```<code>private InputFilter[] inputFilters = new InputFilter[] { new InputFilter()
{
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
    {
        for (int i = start; i < end; ++i)
        {
            if (!Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890]*").matcher(String.valueOf(source.charAt(i))).matches())
            {
                return "";
            }
        }

        return null;
    }
} };
</code>```

But problem is "android:maxLength" value in xml file is not working with this InputFilter

I think I need code in InputFilter to set max-length of EditText

Anyone has good idea for this?

Thanks

答:
A simple one-liner would be:

Java:

```<code>myEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) });
</code>```

Kotlin:

```<code>myEditText.filters = arrayOf(InputFilter.LengthFilter(10))
</code>```

Body:
I'm using InputFilter like this to allow only alpha and numbers

private InputFilter[] inputFilters = new InputFilter[] { new InputFilter()
{
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
    {
        for (int i = start; i < end; ++i)
        {
            if (!Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890]*").matcher(String.valueOf(source.charAt(i))).matches())
            {
                return "";
            }
        }

        return null;
    }
} };

But problem is "android:maxLength" value in xml file is not working with this InputFilter

I think I need code in InputFilter to set max-length of EditText

Anyone has good idea for this?

Thanks

Body:
A simple one-liner would be:

Java:

myEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) });

Kotlin:

myEditText.filters = arrayOf(InputFilter.LengthFilter(10))


问:
Html.ValidationMessageFor Text Color
Probably a simple question, but i cant seem to find the answer.

using MVC 2 i have a series of Html.ValidationFor controls. I want to assign a CSS class to the text and cant seem to do it.

```<code><%= Html.TextBoxFor(Model => Model.Chest, new { @class = "textBoxMeasure" })%>
<%= Html.ValidationMessageFor(Model => Model.Chest) %>
</code>```

if i try the same method as textboxfor i get errors because it requires a string, when i put a string in it still wont  work!

thanks

答:
simplest way to do this to put @Html.ValidationMessageFor in div tag and apply css to div tag</p>

```<code>    <div style="font-size:15px !important;">
             @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
    </div>
</code>```

Title: Html.ValidationMessageFor Text Color

Body:
Probably a simple question, but i cant seem to find the answer.

using MVC 2 i have a series of Html.ValidationFor controls. I want to assign a CSS class to the text and cant seem to do it.

<%= Html.TextBoxFor(Model => Model.Chest, new { @class = "textBoxMeasure" })%>
<%= Html.ValidationMessageFor(Model => Model.Chest) %>

if i try the same method as textboxfor i get errors because it requires a string, when i put a string in it still wont  work!

thanks

Body:
simplest way to do this to put @Html.ValidationMessageFor in div tag and apply css to div tag

    <div style="font-size:15px !important;">
             @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
    </div>


问:
Use contains() to check if back button pressed in Swift
I need to check if the back button is pressed in Swift. The action does not fire programmatically, so the approach appears to be to check if self is in the viewcontroller stack. I think the solution is here:

How to check for self with contains() in Swift?

However for each of the answers Swift tells me that contains is an unresolved identifier. I understand that is it in the Swift standard library so I assume I don't know how to use it.

Therefore what is the proper form of the following function?

```<code>override func viewDidDisappear(_ animated: Bool) {
    if let viewControllers = self.navigationController?.viewControllers as? [UIViewController] {
        if (contains(viewControllers, self)) {
            print("Back button not pressed")
        } else {
                print ("Back button pressed")
        }
    }
}
</code>```

答:
Similar to RAJAMOHAN-S I look at where I'm transitioning from. However, the function

```<code>override func willMove(toParentViewController parent: UIViewController?)
</code>```

provides a nice way of doing that; I combined with a simple bool variable to differentiate if the back button was really used or whether another programmatic method meant a transition event.

```<code>override func willMove(toParentViewController parent: UIViewController?) {
    super.willMove(toParentViewController: parent)
    if parent == nil {
        // The back button was pressed, can be acted on
        }
    }
    else{
        print ("Coming here from a child view")
    }
}
</code>```

Body:
I need to check if the back button is pressed in Swift. The action does not fire programmatically, so the approach appears to be to check if self is in the viewcontroller stack. I think the solution is here:

How to check for self with contains() in Swift?

However for each of the answers Swift tells me that contains is an unresolved identifier. I understand that is it in the Swift standard library so I assume I don't know how to use it.

Therefore what is the proper form of the following function?

override func viewDidDisappear(_ animated: Bool) {
    if let viewControllers = self.navigationController?.viewControllers as? [UIViewController] {
        if (contains(viewControllers, self)) {
            print("Back button not pressed")
        } else {
                print ("Back button pressed")
        }
    }
}

Body:
Similar to RAJAMOHAN-S I look at where I'm transitioning from. However, the function

override func willMove(toParentViewController parent: UIViewController?)

provides a nice way of doing that; I combined with a simple bool variable to differentiate if the back button was really used or whether another programmatic method meant a transition event.

override func willMove(toParentViewController parent: UIViewController?) {
    super.willMove(toParentViewController: parent)
    if parent == nil {
        // The back button was pressed, can be acted on
        }
    }
    else{
        print ("Coming here from a child view")
    }
}


问:
Image not acting "responsive" using flexbox?
I am pretty new to HTML/CSS and have begun trying to learn CSS flexbox layout. Just working on a simple site recreation from scratch using flexbox.

In full screen, the image positioning on the logo looks good. However, when shifting around the screen size, my nav bar on the right side responds but the logo image on the left does not. I believe I have set it up correctly though.

```<code>.header-container {
 display: flex;
 width: 100%;
 height: 150px;
 align-items: center;
 justify-content: space-between;
 }

.header-container .logo .sb{
 display: flex;
 justify-content: flex-start;
 width: 60%;
 position: relative;
 left: 50px;
 padding: 20px;
 }
</code>```

Here's a link to my work as well: https://codepen.io/gkunthara/pen/VWdrYj

What exactly am I doing wrong? Any tips on the type of positioning I'm doing with flexbox or with flexbox, in general, are appreciated!

答:
Remove position on nav & set max-width: 100% on logo image.

https://codepen.io/thesumit67/pen/bRKYLx?editors=1100

Body:
I am pretty new to HTML/CSS and have begun trying to learn CSS flexbox layout. Just working on a simple site recreation from scratch using flexbox.

In full screen, the image positioning on the logo looks good. However, when shifting around the screen size, my nav bar on the right side responds but the logo image on the left does not. I believe I have set it up correctly though.

.header-container {
 display: flex;
 width: 100%;
 height: 150px;
 align-items: center;
 justify-content: space-between;
 }

.header-container .logo .sb{
 display: flex;
 justify-content: flex-start;
 width: 60%;
 position: relative;
 left: 50px;
 padding: 20px;
 }

Here's a link to my work as well: https://codepen.io/gkunthara/pen/VWdrYj

What exactly am I doing wrong? Any tips on the type of positioning I'm doing with flexbox or with flexbox, in general, are appreciated!


问:
Getting the user's "Favorites" playlist: contentDetails.relatedPlaylists.favorites is an invalid ID
The Google documentation on this feature is quite clear, except this doesn't work (I'm using C#, but since the API itself is the same across languages, this will hopefully be comprehensible

```<code>private async Task FetchYtUploads()
        {
            UserCredential credential;
            var credentialsPath = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), @"..\..\..\..\client_id.json").Replace("file:\\", "");
            using (var stream = new FileStream(credentialsPath, FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows for read-only access to the authenticated
                    // user's account, but not other types of account access.
                    new[] { YouTubeService.Scope.YoutubeReadonly },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(this.GetType().ToString())
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = this.GetType().ToString()
            });

            var channelsListRequest = youtubeService.Channels.List("contentDetails");
            channelsListRequest.Mine = true;
            var channels = await channelsListRequest.ExecuteAsync(); // A list with just one item is returned

            if (channels.Items.Count <= 0)
            {
                Console.Write("ERROR: no YT channels found.");
                return;
            }

            var favoritesListId = channels.Items[0].ContentDetails.RelatedPlaylists.Favorites;
</code>```

channels.Items is a list of just one item. And channels.Items[0].ContentDetails.RelatedPlaylists.Favorites has an ID alright, but it is NOT the same as the ID from the URL link of my "Favorites". The following request fails with RelatedPlaylists.Favorites for ID but works if I hard-code the ID that I looked up in the URL of my list:

```<code>var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = favoritesListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;

var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
</code>```

What's going on? Am I missing something? How can I get the correct ID for my "Favorites" playlist, and what is ContentDetails.RelatedPlaylists.Favorites if it can't be used in playlistItemsListRequest.PlaylistId?

答:
You need to remember that the YouTube API is channel based.  When you authenticate to the API using your application you are asked to pick a channel.  The authentication you have will only give you access to this one channel.

If you want to access a different channel then you will have to re-authenticate your application and pick a different channel.

Tip: Change "user" to something else and it will request auth again.  user is the name of the user your credentials have been stored under in %appData%

Body:
The Google documentation on this feature is quite clear, except this doesn't work (I'm using C#, but since the API itself is the same across languages, this will hopefully be comprehensible

private async Task FetchYtUploads()
        {
            UserCredential credential;
            var credentialsPath = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), @"..\..\..\..\client_id.json").Replace("file:\\", "");
            using (var stream = new FileStream(credentialsPath, FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows for read-only access to the authenticated
                    // user's account, but not other types of account access.
                    new[] { YouTubeService.Scope.YoutubeReadonly },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(this.GetType().ToString())
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = this.GetType().ToString()
            });

            var channelsListRequest = youtubeService.Channels.List("contentDetails");
            channelsListRequest.Mine = true;
            var channels = await channelsListRequest.ExecuteAsync(); // A list with just one item is returned

            if (channels.Items.Count <= 0)
            {
                Console.Write("ERROR: no YT channels found.");
                return;
            }

            var favoritesListId = channels.Items[0].ContentDetails.RelatedPlaylists.Favorites;

channels.Items is a list of just one item. And channels.Items[0].ContentDetails.RelatedPlaylists.Favorites has an ID alright, but it is NOT the same as the ID from the URL link of my "Favorites". The following request fails with RelatedPlaylists.Favorites for ID but works if I hard-code the ID that I looked up in the URL of my list:

var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = favoritesListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;

var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();

What's going on? Am I missing something? How can I get the correct ID for my "Favorites" playlist, and what is ContentDetails.RelatedPlaylists.Favorites if it can't be used in playlistItemsListRequest.PlaylistId?


问:
Can't display the proper value
I have these classes:

```<code>interface Shape
{
    public double getPerimeter();
    public double getArea();
    public void getDetails();
}
</code>```

and

```<code>class Circle implements Shape
{
    private double PI = 3.14;
    private int radius;
    double perimeter, area;

    //constructor
    public Circle(int radius)
    {
        perimeter = 2.0 * (PI * radius);
        area = PI * (radius * radius);
    }

    public int getRadius()
    {
        return radius;
    }

    public double getPerimeter()
    {
        return perimeter;
    }

    public double getArea()
    {
        return area;
    }

    public void getDetails()
    {
        System.out.println("Shape Type: Circle " + "\n"
                         + "Radius: " + getRadius() + "\n"
                         + "Perimeter: " + getPerimeter() + "\n"
                         + "Area: "  + getArea() + "\n"         );
    }
}
</code>```

and finally

```<code>public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.print("wrong");
            }

            catch(IllegalArgumentException iae)
            {
                System.err.print("wrong");
            }

            if(args.length==1)
            {
                i = Integer.parseInt(args[0]);
                Circle r1 = new Circle(i);
                r1.getDetails();
            }
        }

    }

}
</code>```

We were assigned to input 1,2 or 3 numbers on the command line of the terminal and the output would display what kind of shape it is depending on the array size. I managed to get the proper parameter and area when I input a number but the radius keeps displaying 0 instead of the actual number I inputted.

This is what the output looks like

So what do you guys think?

答:
In your constructor:

```<code>public Circle(int radius)
{
    perimeter = 2.0 * (PI * radius);
    area = PI * (radius * radius);
}
</code>```

radius refers to the parameter radius, not the radius field declared in Circle. You need to make them the same by assigning the radius parameter to the radius field. To refer to the radius field, use this.radius.

```<code>this.radius = radius;
</code>```

Because you did not do this in your code, the radius returned by getRadius is 0, which is the default value of an unassigned int.

Title: Can't display the proper value

Body:
I have these classes:

interface Shape
{
    public double getPerimeter();
    public double getArea();
    public void getDetails();
}

and

class Circle implements Shape
{
    private double PI = 3.14;
    private int radius;
    double perimeter, area;

    //constructor
    public Circle(int radius)
    {
        perimeter = 2.0 * (PI * radius);
        area = PI * (radius * radius);
    }

    public int getRadius()
    {
        return radius;
    }

    public double getPerimeter()
    {
        return perimeter;
    }

    public double getArea()
    {
        return area;
    }

    public void getDetails()
    {
        System.out.println("Shape Type: Circle " + "\n"
                         + "Radius: " + getRadius() + "\n"
                         + "Perimeter: " + getPerimeter() + "\n"
                         + "Area: "  + getArea() + "\n"         );
    }
}

and finally

public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.print("wrong");
            }

            catch(IllegalArgumentException iae)
            {
                System.err.print("wrong");
            }

            if(args.length==1)
            {
                i = Integer.parseInt(args[0]);
                Circle r1 = new Circle(i);
                r1.getDetails();
            }
        }

    }

}

We were assigned to input 1,2 or 3 numbers on the command line of the terminal and the output would display what kind of shape it is depending on the array size. I managed to get the proper parameter and area when I input a number but the radius keeps displaying 0 instead of the actual number I inputted.

This is what the output looks like

So what do you guys think?

Body:
In your constructor:

public Circle(int radius)
{
    perimeter = 2.0 * (PI * radius);
    area = PI * (radius * radius);
}

radius refers to the parameter radius, not the radius field declared in Circle. You need to make them the same by assigning the radius parameter to the radius field. To refer to the radius field, use this.radius.

this.radius = radius;

Because you did not do this in your code, the radius returned by getRadius is 0, which is the default value of an unassigned int.


问:
PSI and index do not match / Error:Execution failed for task ':processArmv7DebugManifest'
I work on an app with the framework Ionic and when I run my app thanks to Android Studio these errors appear :

On the Event log :

PSI and index do not match: PSI and index do not match

On the message gradle build :

Error:Execution failed for task ':processArmv7DebugManifest'.
  Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.1) from [com.android.support:appcompat-v7:25.3.1] AndroidManifest.xml:27:9-31
      is also present at [com.android.support:support-v4:26.0.0-alpha1] AndroidManifest.xml:27:9-38 value=(26.0.0-alpha1).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:25:5-27:34 to override.

AndroidManifest.xml

```<code><?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="io.ionic.starter" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="android.support.v4.content.FileProvider">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
        </provider>
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/fb_app_id" />
        <meta-data android:name="com.facebook.sdk.ApplicationName" android:value="@string/fb_app_name" />
        <activity android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/fb_app_name" android:name="com.facebook.FacebookActivity" />
        <service android:name="org.apache.cordova.firebase.FirebasePluginMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="org.apache.cordova.firebase.FirebasePluginInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <receiver android:name="org.apache.cordova.firebase.OnNotificationOpenReceiver" />
    </application>
    <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>
</code>```

Someone know how to solve this problem?

Thanks in advance,
Caroline

答: I have faced the same problem. I am fixed the issue by changing the  gradle both (v7 and v4) compile "com.android.support:appcompat-v7:25.0.0+" to "com.android.support:appcompat-v7:26.0.0+"</p>

Body:
I work on an app with the framework Ionic and when I run my app thanks to Android Studio these errors appear :

On the Event log :

PSI and index do not match: PSI and index do not match

On the message gradle build :

Error:Execution failed for task ':processArmv7DebugManifest'.
  Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.1) from [com.android.support:appcompat-v7:25.3.1] AndroidManifest.xml:27:9-31
      is also present at [com.android.support:support-v4:26.0.0-alpha1] AndroidManifest.xml:27:9-38 value=(26.0.0-alpha1).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:25:5-27:34 to override.

AndroidManifest.xml

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="io.ionic.starter" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="android.support.v4.content.FileProvider">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
        </provider>
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/fb_app_id" />
        <meta-data android:name="com.facebook.sdk.ApplicationName" android:value="@string/fb_app_name" />
        <activity android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/fb_app_name" android:name="com.facebook.FacebookActivity" />
        <service android:name="org.apache.cordova.firebase.FirebasePluginMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="org.apache.cordova.firebase.FirebasePluginInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <receiver android:name="org.apache.cordova.firebase.OnNotificationOpenReceiver" />
    </application>
    <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>

Someone know how to solve this problem?

Thanks in advance,
Caroline


问:
ViewBox vs Grid
Whats the difference between these two, and which is the better approach.</p>

答:
They are completely different control!

A Grid allows you to arrange its multiple children according to a a pre-defined set of rows / columns.

A ViewBox scales its single child to fill a certain area on the screen.

Title: ViewBox vs Grid


问:
Importing Project-Swift.h into a Objective-C class...file not found
I have a project that was started in Objective-C, and I am trying to import some Swift code into the same class files that I have previously written Objective-C in.

I have consulted the Apple docs on using Swift and Objective-C in the same project, as well as SO question like this, but still no avail: I continue to get the file not found error after putting in #import "NewTestApp-Swift.h" (NewTestApp is the name of the Product and module).

Here is what I have done so far:

In Define Modules, selected YES for the app.

Ensured that the Product Module name did not have any space in it (see screenshot below question)

I have tried using #import "NewTestApp-Swift.h" inside ViewController.m, ViewController.h and AppDelegate.m but none of them has worked.

What else am I doing incorrectly? Thanks for your help.

Screenshot of settings:

Errors that I am presently encountering:

答:
DEFINE MODULES: YES
and import "ProjectName-Swift.h" in .m file of Obj-C class

This worked for me to access Swift classes in Obj-c.


问:
How can I give data from my webworker to highchart
I am working with highcharts, I want to update highcharts series from my web-worker. My web-worker is receiving data from my api via xmlhttprequest now I want to update my chart without refreshing the web page , and how can I  pass that data to highcharts series? </p>

答:
You need to use the onMessage event, and post messages from the worker to the client. Messages should be stringyfied object or arrays.

In your main code:

```<code>var worker = new Worker('w/main-worker.js');
worker.postMessage('message to worker');

worker.onmessage = function(e) {
    console.log(e.data);
    // do stuff with data from worker
};
</code>```

In your worker:

```<code>// do stuff
// when stuff is ready
postMessage(myStuff);

// handle messages from the main thread
onmessage = function(e) {
    console.log(e.data);
    // do stuff with message from main thread
};
</code>```

I have few demos here: https://github.com/mchaov/WebWorkers There are demos for similar use case like yours.

Body:
You need to use the onMessage event, and post messages from the worker to the client. Messages should be stringyfied object or arrays.

In your main code:

var worker = new Worker('w/main-worker.js');
worker.postMessage('message to worker');

worker.onmessage = function(e) {
    console.log(e.data);
    // do stuff with data from worker
};

In your worker:

// do stuff
// when stuff is ready
postMessage(myStuff);

// handle messages from the main thread
onmessage = function(e) {
    console.log(e.data);
    // do stuff with message from main thread
};

I have few demos here: https://github.com/mchaov/WebWorkers There are demos for similar use case like yours.


问:
Upload Alexa Slot Types via API
Is there anyway of uploading Custom Slot Types values via an API, so that you do not need to type them in manually using the new Alexa Skill Builder interface (if you have many of them):

I haven't found anything.

答:
It seems not (after searching). There is a feature request logged here with Amazon:

https://forums.developer.amazon.com/questions/9640/api-to-upload-intent-schema-and-sample-utterances.html#answer-77902

Title: Upload Alexa Slot Types via API