问:
Why are jagged arrays in C# defined in the opposite way?
Let's say I have a type called T. Now let's say I make an array of type T, it gives me T[]. In code, it gives:

```<code>var myArray = new T[10];
</code>```

With a length of 10. So, we can see that this makes an array that contains 10 items of type T. This works if T is int, string, BinaryWriter or anything standard. But let's say T is an array type, like int[] or string[].

Then, if we want to define an array of 10 items of type T (int[]), it should give something like this:

```<code>var myArray = new int[][10];
</code>```

By replacing T by int[] in the previous example. But this gives a syntax error, because the correct syntax in C# is:

```<code>var myArray = new int[10][];
</code>```

Which, if we followed the logic of the first example, should give an array containing an undefined amount of arrays containing 10 integers.

The same applies for any dimension of jagged arrays:

```<code>var myArray = new int[][][10];
</code>```

Is wrong because the syntactically correct way is:

```<code>var myArray = new int[10][][];
</code>```

This isn't a personal preference or a code style debate, but simply logic: why is the syntax different when we define arrays of array types, than when we define arrays of anything else?

答:
new T[10] says you want an array of 10 items of type T.  It is not the same as new int[][10] because it does not behave like a preprocessor macro in other languages.  It doesn't just swap T with whatever the type is to create new int[][10].  Instead it is being consistent with the fact that T is always the inner type and new T[10] defines the size of the outer array.

So if T was DateTime then you'd expect to have 10 date times and access them such as myArray[9].Day

If each item T is an int[] then you'd still always index into the array of 10 items and then access the item T, which is an array: myarray[9][2465] assuming the inner array at index 9 had at least 2466 items.

So the index of the outer array always comes first.

A T[10] is a size 10 array of items T.  Whatever T is the inner item.

You state your expectation is that new T[10] would produce  var myArray = new int[][10];.  However even in C++ when declaring a multidimensional array, the outer dimension comes first in the declaration:

https://www.tutorialspoint.com/cplusplus/cpp_multi_dimensional_arrays.htm

Declaring a jagged array is similar in C++ except you must use pointer syntax and first declare the outer array then initialize each inner array separately.

Let's think about it in terms of the semantics of what each statement is saying:

A) new T[10]: I want an array of outer dimension 10, with each element containing a type T

B) new T[10] where T is int[]: I want an array of outer dimension 10, with each element containing an int array of unknown length.

C) new int[][10]: I want an array of outer dimension unknown, with each element containing an array of 10 integers.

D) new int[10][]: I want an array of outer dimension 10, with each element containing an int array of unknown length.

Notice that B and D match, but B and C do not match.

Body:
Let's say I have a type called T. Now let's say I make an array of type T, it gives me T[]. In code, it gives:

var myArray = new T[10];

With a length of 10. So, we can see that this makes an array that contains 10 items of type T. This works if T is int, string, BinaryWriter or anything standard. But let's say T is an array type, like int[] or string[].

Then, if we want to define an array of 10 items of type T (int[]), it should give something like this:

var myArray = new int[][10];

By replacing T by int[] in the previous example. But this gives a syntax error, because the correct syntax in C# is:

var myArray = new int[10][];

Which, if we followed the logic of the first example, should give an array containing an undefined amount of arrays containing 10 integers.

The same applies for any dimension of jagged arrays:

var myArray = new int[][][10];

Is wrong because the syntactically correct way is:

var myArray = new int[10][][];

This isn't a personal preference or a code style debate, but simply logic: why is the syntax different when we define arrays of array types, than when we define arrays of anything else?


来源: stackexchange

问:
NSFastEnumeration message sent to deallocated instance
I am trying to implement the NSFastEnumeration protocol for a sqlite query.

I am running into:
message sent to deallocated instance

```<code>- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained *)stackbuf count:(NSUInteger)len {

    // First call
    if(state->state == 0) {
        state->mutationsPtr = &state->extra[0];
        state->state = 1;
        sqlite3_reset(self.statement);
    }

    state->itemsPtr = stackbuf;

    NSUInteger count = 0;
    while (count < len) {
        int result = sqlite3_step(self.statement);

        if (result == SQLITE_DONE) {
            break;
        }

        MyRow *row = [self queryRow];
        stackbuf[count] = row;
        count += 1;
    }

    return count;
}

-(MyRow *) queryRow {
    MyRow * row = // query sqlite for row
    return row;
}
</code>```

It seems as if the 'row' object is not being retained, so when it needs to be accessed in loop its already been deallocated.

Do I need to save the results when iterating in 'countByEnumeratingWithState' in a'strong' dataset, so that it is retained?

IE:

```<code>@property (nonatomic, strong) NSMutableArray *resultList;
</code>```

Then inside the while loop:

```<code>while (count < len) {
    int result = sqlite3_step(self.statement);

    if (result == SQLITE_DONE) {
        break;
    }

    MyRow *row = [self queryRow];
    [self.resultList addObject:row];  // throw into a strong array so its retained
    stackbuf[count] = row;
    count += 1;
}
</code>```

EDIT:

A little more research reveals that maybe I can just use __autoreleasing:

```<code>MyRow * __autoreleasing row = [self queryRow];
</code>```

Without having to maintain a strong array of objects.  Is this the right solution?

答:
The fast enumeration protocol relies on the collection it is enumerating retaining its contained items. The caller (the compiler) ensures that the collection is itself is retained during the enumeration.

The array used by countByEnumeratingWithState: contains __unsafe_unretained references. This is safe as the compiler retains the collection, the collection retains the items, and so the references in the array will remain valid.

At the language level an object reference returned by fast enumeration is unowned by the caller and must be retained if need, which is of course handled automatically by ARC. This is no different to how items returned from any other collection (arrays, dictionaries, etc.) are handled.

Now your "collection" is different, it does not contain items but obtains them from an SQL query on demand. Those items are not owned by your "collection" and so are deallocated by ARC when there is no longer any strong references to them. Therefore the __unsafe_unretained references you store in fast enumerations C array really are unsafe - ARC deallocates what they reference.

The solution is to add (i.e. instance variable) a standard collection, say an NSMutableArray, to your "collection". On each call to countByEnumeratingWithState: first empty out this collection, thereby discarding any references you hold to previous query results (which will also deallocated them if the calling code has not retained them), and then fill it with the query results that will be return for this call.

When your "collection" is itself finally deallocated by ARC any references to query results it still holds will also be discarded.

It is worthwhile reading Apple's Enumeration Sample as its comments contain details of the memory management required to implement fast enumeration.

HTH

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement the NSFastEnumeration protocol for a sqlite query.

I am running into:
message sent to deallocated instance

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained *)stackbuf count:(NSUInteger)len {

    // First call
    if(state->state == 0) {
        state->mutationsPtr = &state->extra[0];
        state->state = 1;
        sqlite3_reset(self.statement);
    }

    state->itemsPtr = stackbuf;

    NSUInteger count = 0;
    while (count < len) {
        int result = sqlite3_step(self.statement);

        if (result == SQLITE_DONE) {
            break;
        }

        MyRow *row = [self queryRow];
        stackbuf[count] = row;
        count += 1;
    }

    return count;
}

-(MyRow *) queryRow {
    MyRow * row = // query sqlite for row
    return row;
}

It seems as if the 'row' object is not being retained, so when it needs to be accessed in loop its already been deallocated.

Do I need to save the results when iterating in 'countByEnumeratingWithState' in a'strong' dataset, so that it is retained?

IE:

@property (nonatomic, strong) NSMutableArray *resultList;

Then inside the while loop:

while (count < len) {
    int result = sqlite3_step(self.statement);

    if (result == SQLITE_DONE) {
        break;
    }

    MyRow *row = [self queryRow];
    [self.resultList addObject:row];  // throw into a strong array so its retained
    stackbuf[count] = row;
    count += 1;
}

EDIT:

A little more research reveals that maybe I can just use __autoreleasing:

MyRow * __autoreleasing row = [self queryRow];

Without having to maintain a strong array of objects.  Is this the right solution?


问:
Oembed for youtube
Do I need Developer's key for using oembed for youtube in my website?

The problems is that following code does not works, It does not returns to succes

```<code> $.ajax({
                    url: "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=PVzljDmoPVs",
                    dataType: "jsonp",
                    timeout: 15000,
                    success: function (jo) {
                        if (jo) {
                            setIMg(jo.thumbnail_url);
                            setTitle(jo.title);
                        }
                    }
                });
</code>```

But when i fire the url in the browser then it gives me the json:

{"provider_url": "http:\/\/www.youtube.com\/", "thumbnail_url": "http:\/\/i1.ytimg.com\/vi\/PVzljDmoPVs\/hqdefault.jpg", "title": "David Guetta - She Wolf (Falling To Pieces) ft. Sia", "html": "\u003ciframe width=\"480\" height=\"270\" src=\"http:\/\/www.youtube.com\/embed\/PVzljDmoPVs?fs=1\u0026feature=oembed\" frameborder=\"0\" allowfullscreen\u003e\u003c\/iframe\u003e", "author_name": "davidguettavevo", "height": 270, "thumbnail_width": 480, "width": 480, "version": "1.0", "author_url": "http:\/\/www.youtube.com\/user\/davidguettavevo", "provider_name": "YouTube", "type": "video", "thumbnail_height": 360}

答:
No, We do not need any developer key to use oEmbed endpoints of any oEmbed providers.

oEmbed spec supports two formats one is json and the other is xml type. oEmbed providers would provide response to oEmbed api in either one of the formats.

There is no format like jsonp according to the spec that's why you couldn't get proper response from the oEmbed provider like "youtube". Invoking the url with type query param as json should produce expected result

```<code>url: "http://www.youtube.com/oembed?type=json&url=http://www.youtube.com/watch?v=PVzljDmoPVs"
</code>```

You can specify the type value as json or xml in request - else the provider would provider would respond with json by default.

oEmbed spec doesn't mention anything about JSONP support: So, youtube haven't provided support for JSONP I guess..

Anyways to access a cross site resource (CORS - Cross Origin resource sharing) the response header must contain Access-Control-Allow-Origin set else we can go with should go for default jsonp standard which youtube doesn't support.

I hope this little hack on JSONP could solve our need. Else we can go for external libraries like yuilibrary.

Title: Oembed for youtube

Body:
Do I need Developer's key for using oembed for youtube in my website?

The problems is that following code does not works, It does not returns to succes

 $.ajax({
                    url: "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=PVzljDmoPVs",
                    dataType: "jsonp",
                    timeout: 15000,
                    success: function (jo) {
                        if (jo) {
                            setIMg(jo.thumbnail_url);
                            setTitle(jo.title);
                        }
                    }
                });

But when i fire the url in the browser then it gives me the json:

{"provider_url": "http:\/\/www.youtube.com\/", "thumbnail_url": "http:\/\/i1.ytimg.com\/vi\/PVzljDmoPVs\/hqdefault.jpg", "title": "David Guetta - She Wolf (Falling To Pieces) ft. Sia", "html": "\u003ciframe width=\"480\" height=\"270\" src=\"http:\/\/www.youtube.com\/embed\/PVzljDmoPVs?fs=1\u0026feature=oembed\" frameborder=\"0\" allowfullscreen\u003e\u003c\/iframe\u003e", "author_name": "davidguettavevo", "height": 270, "thumbnail_width": 480, "width": 480, "version": "1.0", "author_url": "http:\/\/www.youtube.com\/user\/davidguettavevo", "provider_name": "YouTube", "type": "video", "thumbnail_height": 360}

Body:
No, We do not need any developer key to use oEmbed endpoints of any oEmbed providers.

oEmbed spec supports two formats one is json and the other is xml type. oEmbed providers would provide response to oEmbed api in either one of the formats.

There is no format like jsonp according to the spec that's why you couldn't get proper response from the oEmbed provider like "youtube". Invoking the url with type query param as json should produce expected result

url: "http://www.youtube.com/oembed?type=json&url=http://www.youtube.com/watch?v=PVzljDmoPVs"

You can specify the type value as json or xml in request - else the provider would provider would respond with json by default.

oEmbed spec doesn't mention anything about JSONP support: So, youtube haven't provided support for JSONP I guess..

Anyways to access a cross site resource (CORS - Cross Origin resource sharing) the response header must contain Access-Control-Allow-Origin set else we can go with should go for default jsonp standard which youtube doesn't support.

I hope this little hack on JSONP could solve our need. Else we can go for external libraries like yuilibrary.


问:
Count and Distinct SQL query
I have a table of Books, that contains the following columns:

```<code>Book_Id   User_Id
001       1
002       2
001       1
004       2
005       3
006       3
007       2
008       2
009       1
</code>```

Where :

Book_Id - identifier of a book that a user read; User_Id - identifier
  of a reader/user.

Let's assume that User1 read books three times, but 2 of them were same, so the user 1 read 2 distinct books (001 and 009). User 2 read 4 distinct books, while user 3 read 2 distinct books.
In overall, there are 2 users that read 2 distinct books, and 1 user that read 4 distinct books.
The output expected is as below:

```<code>Distinct_Books_Count --- User_Count
2                           2
4                           1
</code>```

I tried the following:

SELECT COUNT(DISTINCT Book_Id), COUNT(User_Id) FROM Books GROUP BY
  User_Id

But I receive the following table:

```<code>Distinct_Books_Count  User_Count
2                     3
4                     4
2                     2
</code>```

So any alternative solution or changes?

答:
I call this a "histogram of histograms" query.  You can do it using two group bys:

```<code>SELECT num_books, COUNT(*)
FROM (SELECT b.User_Id, COUNT(DISTINCT Book_Id) as num_books
      FROM Books b
      GROUP BY User_Id
     ) b
GROUP BY num_books
ORDER BY num_books;
</code>```

Title: Count and Distinct SQL query

Body:
I have a table of Books, that contains the following columns:

Book_Id   User_Id
001       1
002       2
001       1
004       2
005       3
006       3
007       2
008       2
009       1

Where :

Book_Id - identifier of a book that a user read; User_Id - identifier
  of a reader/user.

Let's assume that User1 read books three times, but 2 of them were same, so the user 1 read 2 distinct books (001 and 009). User 2 read 4 distinct books, while user 3 read 2 distinct books.
In overall, there are 2 users that read 2 distinct books, and 1 user that read 4 distinct books.
The output expected is as below:

Distinct_Books_Count --- User_Count
2                           2
4                           1

I tried the following:

SELECT COUNT(DISTINCT Book_Id), COUNT(User_Id) FROM Books GROUP BY
  User_Id

But I receive the following table:

Distinct_Books_Count  User_Count
2                     3
4                     4
2                     2

So any alternative solution or changes?

Body:
I call this a "histogram of histograms" query.  You can do it using two group bys:

SELECT num_books, COUNT(*)
FROM (SELECT b.User_Id, COUNT(DISTINCT Book_Id) as num_books
      FROM Books b
      GROUP BY User_Id
     ) b
GROUP BY num_books
ORDER BY num_books;


问:
Control flow syntax in c++
With the following c++ example(indention was left out in purpose).

```<code>if(condA)          // if #1
if(condB)          // if #2
if(condC)          // if #3
if(condD)          // if #4
funcA();
else if(condD)     // else #1 if #5
funcB();
else if(condE)     // else #2 if #6
funcC();
else               // else #3
funcD();
else if(condF)     // else #4 if #7
funcE();
else               // else #5
funcF();
</code>```

What else refers to what if and what is the rule about this? (yes I know using { } will solve this).

答:
C++ knows which else matches which if, and C++ compilers have just-fine parsers that sort this out in flash.  The problem is the you aren't good at this.

Run this through a C++ prettyprinter and the result formatted text will make it very clear.

ContentLicense: CC BY-SA 2.5

Title: Control flow syntax in c++

Body:
With the following c++ example(indention was left out in purpose).

if(condA)          // if #1
if(condB)          // if #2
if(condC)          // if #3
if(condD)          // if #4
funcA();
else if(condD)     // else #1 if #5
funcB();
else if(condE)     // else #2 if #6
funcC();
else               // else #3
funcD();
else if(condF)     // else #4 if #7
funcE();
else               // else #5
funcF();

What else refers to what if and what is the rule about this? (yes I know using { } will solve this).


问:
issue with adding upload field to mautic form
I need to add a file upload custom type to my mautic form but I can't find the right way to do it.
Is there a plugin to add or I must work with symfony to add it
Any suggestions please !</p>

答:
The closest thing to the file upload field feature is this PR: https://github.com/mautic/mautic/pull/3054

If you need it and you know PHP a little, you could help the author to finish it.

UPDATE: Form file upload was finished in PR https://github.com/mautic/mautic/pull/5082 and released in Mautic 2.11.0.

ContentLicense: CC BY-SA 4.0


问:
Getting RestEASY, HIbernate, Maven and JBossAS5.1 to play nicely
I'm trying to build a restful webservice that uses hibernate for data access.  I am using Maven to build and have to deploy on JBossAS5.1 - probably EAP5.x in future.

RestEASY is fine, but I'm having issues with Hibernate, as soon as I add hibernate dependencies to pom.xml the resulting WAR crashes immediately after deploy.

I'm reasonably comfortable with Java and Maven but am new to JavaEE beyond simple JSP.

pom.xml extract:

```<code>      <repositories>
          <repository>
              <id>jboss</id>
              <name>jboss repo</name>
              <url>http://repository.jboss.org/nexus/content/groups/public/</url>
          </repository>
      </repositories>

    <dependencies>
        <!-- hibernate -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>3.5.6-Final</version>
         <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
        </exclusions>

    </dependency>
         <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

      <dependency>
          <groupId>org.jboss.resteasy</groupId>
          <artifactId>resteasy-jaxrs</artifactId>
          <version>2.0.0.GA</version>
          <exclusions>
              <exclusion>
                  <groupId>com.sun.xml.bind</groupId>
                  <artifactId>jaxb-impl</artifactId>
              </exclusion>
                <exclusion>
                  <groupId>org.slf4j</groupId>
                  <artifactId>slf4j-api</artifactId>
              </exclusion>
               <exclusion>
                  <groupId>org.slf4j</groupId>
                  <artifactId>slf4j-simple</artifactId>
              </exclusion>
              <exclusion>
                  <groupId>org.slf4j</groupId>
                  <artifactId>jcl-over-slf4j</artifactId>
              </exclusion>
          </exclusions>
      </dependency>
      <dependency>
          <groupId>org.jboss.resteasy</groupId>
          <artifactId>resteasy-jaxb-provider</artifactId>
          <version>2.0.0.GA</version>
           <exclusions>
              <exclusion>
                  <groupId>com.sun.xml.bind</groupId>
                  <artifactId>jaxb-impl</artifactId>
              </exclusion>
          </exclusions>
      </dependency>

  <build>
    <finalName>hedgehog-rest</finalName>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>
</code>```

web.xml:

```<code><web-app>
   <display-name>Archetype Created Web Application</display-name>
   <context-param>
      <param-name>resteasy.scan</param-name>
      <param-value>true</param-value>
   </context-param>
   <listener>
      <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
   </listener>
   <servlet>
      <servlet-name>Resteasy</servlet-name>
      <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>Resteasy</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>
</web-app>
</code>```

I removed all my code except this class:

```<code>@Path("/echo")
public class Echo
{
    @GET
    @Produces("text/*")
    @Path("/{message}")
    public Response echoService(@PathParam("message") String message)
    {
        return Response.status(200).entity(message).build();
    }
}
</code>```

Beginning of error log below:

```<code>20:37:05,848 INFO  [TomcatDeployment] deploy, ctxPath=/hedgehog-rest
20:37:06,956 INFO  [ConfigurationBootstrap] Adding scanned resource: com.ecs.hedgehog.Echo
20:37:07,057 ERROR [[/hedgehog-rest]] Exception sending context initialized event to listener instance of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
java.lang.RuntimeException: java.lang.RuntimeException: Unable to instantiate MessageBodyReader
    at org.jboss.resteasy.plugins.providers.RegisterBuiltin.register(RegisterBuiltin.java:36)
    at org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:171)
    at org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap.contextInitialized(ResteasyBootstrap.java:28)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3910)
</code>```

答:
yup Hibernate JARs being included by Maven were conflicting with those in JBossAS.  Discovered dependency scope: http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope

```<code><dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>3.5.6-Final</version>
  <scope>provided</scope>
</dependency>
</code>```

Solved! :-)

Body:
I'm trying to build a restful webservice that uses hibernate for data access.  I am using Maven to build and have to deploy on JBossAS5.1 - probably EAP5.x in future.

RestEASY is fine, but I'm having issues with Hibernate, as soon as I add hibernate dependencies to pom.xml the resulting WAR crashes immediately after deploy.

I'm reasonably comfortable with Java and Maven but am new to JavaEE beyond simple JSP.

pom.xml extract:

      <repositories>
          <repository>
              <id>jboss</id>
              <name>jboss repo</name>
              <url>http://repository.jboss.org/nexus/content/groups/public/</url>
          </repository>
      </repositories>

    <dependencies>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>3.5.6-Final</version>
         <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
        </exclusions>

    </dependency>
         <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

      <dependency>
          <groupId>org.jboss.resteasy</groupId>
          <artifactId>resteasy-jaxrs</artifactId>
          <version>2.0.0.GA</version>
          <exclusions>
              <exclusion>
                  <groupId>com.sun.xml.bind</groupId>
                  <artifactId>jaxb-impl</artifactId>
              </exclusion>
                <exclusion>
                  <groupId>org.slf4j</groupId>
                  <artifactId>slf4j-api</artifactId>
              </exclusion>
               <exclusion>
                  <groupId>org.slf4j</groupId>
                  <artifactId>slf4j-simple</artifactId>
              </exclusion>
              <exclusion>
                  <groupId>org.slf4j</groupId>
                  <artifactId>jcl-over-slf4j</artifactId>
              </exclusion>
          </exclusions>
      </dependency>
      <dependency>
          <groupId>org.jboss.resteasy</groupId>
          <artifactId>resteasy-jaxb-provider</artifactId>
          <version>2.0.0.GA</version>
           <exclusions>
              <exclusion>
                  <groupId>com.sun.xml.bind</groupId>
                  <artifactId>jaxb-impl</artifactId>
              </exclusion>
          </exclusions>
      </dependency>

  <build>
    <finalName>hedgehog-rest</finalName>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>

web.xml:

<web-app>
   <display-name>Archetype Created Web Application</display-name>
   <context-param>
      <param-name>resteasy.scan</param-name>
      <param-value>true</param-value>
   </context-param>
   <listener>
      <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
   </listener>
   <servlet>
      <servlet-name>Resteasy</servlet-name>
      <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>Resteasy</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>
</web-app>

I removed all my code except this class:

@Path("/echo")
public class Echo
{
    @GET
    @Produces("text/*")
    @Path("/{message}")
    public Response echoService(@PathParam("message") String message)
    {
        return Response.status(200).entity(message).build();
    }
}

Beginning of error log below:

20:37:05,848 INFO  [TomcatDeployment] deploy, ctxPath=/hedgehog-rest
20:37:06,956 INFO  [ConfigurationBootstrap] Adding scanned resource: com.ecs.hedgehog.Echo
20:37:07,057 ERROR [[/hedgehog-rest]] Exception sending context initialized event to listener instance of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
java.lang.RuntimeException: java.lang.RuntimeException: Unable to instantiate MessageBodyReader
    at org.jboss.resteasy.plugins.providers.RegisterBuiltin.register(RegisterBuiltin.java:36)
    at org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:171)
    at org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap.contextInitialized(ResteasyBootstrap.java:28)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3910)

Body:
yup Hibernate JARs being included by Maven were conflicting with those in JBossAS.  Discovered dependency scope: http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>3.5.6-Final</version>
  <scope>provided</scope>
</dependency>

Solved! :-)


问:
Set language for moth abbreviations
I have months specified as numbers from 1 to 12 in my pandas dataframe. By using calendar.month_abbr I convert them to words as follows:

```<code>df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])
</code>```

By default it's English.

Is it possible to specify a language?

答:
Demo:</p>

```<code>In [29]: df
Out[29]:
    Month
0       1
1       2
2       3
3       4
4       5
5       6
6       7
7       8
8       9
9      10
10     11
11     12

In [30]: import locale

In [31]: locale.setlocale(locale.LC_ALL, 'de')
Out[31]: 'de'

In [32]: import calendar

In [33]: df['de'] = df['Month'].apply(lambda x: calendar.month_abbr[x])

In [34]: df
Out[34]:
    Month   de
0       1  Jan
1       2  Feb
2       3  Mrz
3       4  Apr
4       5  Mai
5       6  Jun
6       7  Jul
7       8  Aug
8       9  Sep
9      10  Okt
10     11  Nov
11     12  Dez
</code>```

Title: Set language for moth abbreviations

Body:
I have months specified as numbers from 1 to 12 in my pandas dataframe. By using calendar.month_abbr I convert them to words as follows:

df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])

By default it's English.

Is it possible to specify a language?

Body:
Demo:

In [29]: df
Out[29]:
    Month
0       1
1       2
2       3
3       4
4       5
5       6
6       7
7       8
8       9
9      10
10     11
11     12

In [30]: import locale

In [31]: locale.setlocale(locale.LC_ALL, 'de')
Out[31]: 'de'

In [32]: import calendar

In [33]: df['de'] = df['Month'].apply(lambda x: calendar.month_abbr[x])

In [34]: df
Out[34]:
    Month   de
0       1  Jan
1       2  Feb
2       3  Mrz
3       4  Apr
4       5  Mai
5       6  Jun
6       7  Jul
7       8  Aug
8       9  Sep
9      10  Okt
10     11  Nov
11     12  Dez


问:
event keyboard does not work in tkinter
I do not know why the event does not work with my script.
It seems logical but I do not know why it does not go to the specified function.
here is my script</p>

```<code>from tkinter import *

root = Tk()

start = Label(root, text="press 's' to start the game.")
start.pack()
quitGame = Label(root, text="press 'q' to quit the game.")
quitGame.pack()

def start(event):
    if event.char == 's':
        print("Start")

def exit(event):
    if event.char == 'q':
        root.quit

frame = Frame(root, width=800, height=600)
root.bind('<Key>', start)
root.bind('<Key>', exit)
frame.pack()

root.mainloop()
</code>```

答:
When you call bind, you also unbind all other function from that event. There is a way to bind multiple functions but in your case it would be better to combine your functions into one.

```<code>import tkinter as tk

root = tk.Tk()

start = tk.Label(root, text="press 's' to start the game.")
start.pack()
quitGame = tk.Label(root, text="press 'q' to quit the game.")
quitGame.pack()

def key_pressed(event):
    if event.char == 's':
        print("Start")
    if event.char == 'q':
        root.quit()

frame = tk.Frame(root, width=800, height=600)
root.bind('<Key>', key_pressed)
frame.pack()

root.mainloop()
</code>```

Also, try to avoid using wildcard imports; they only lead to confusing code and bugs.

Title: event keyboard does not work in tkinter

Body:
I do not know why the event does not work with my script.
It seems logical but I do not know why it does not go to the specified function.
here is my script

from tkinter import *

root = Tk()

start = Label(root, text="press 's' to start the game.")
start.pack()
quitGame = Label(root, text="press 'q' to quit the game.")
quitGame.pack()

def start(event):
    if event.char == 's':
        print("Start")

def exit(event):
    if event.char == 'q':
        root.quit

frame = Frame(root, width=800, height=600)
root.bind('<Key>', start)
root.bind('<Key>', exit)
frame.pack()

root.mainloop()

Body:
When you call bind, you also unbind all other function from that event. There is a way to bind multiple functions but in your case it would be better to combine your functions into one.

import tkinter as tk

root = tk.Tk()

start = tk.Label(root, text="press 's' to start the game.")
start.pack()
quitGame = tk.Label(root, text="press 'q' to quit the game.")
quitGame.pack()

def key_pressed(event):
    if event.char == 's':
        print("Start")
    if event.char == 'q':
        root.quit()

frame = tk.Frame(root, width=800, height=600)
root.bind('<Key>', key_pressed)
frame.pack()

root.mainloop()

Also, try to avoid using wildcard imports; they only lead to confusing code and bugs.


问:
How to connect to Chromium Headless using Selenium
I would like to use chromium headless for automated testing using selenium. (https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md)

I do have the headless version already running on 9222. So if i open http://10.252.100.33:9222/json/I do get

```<code>[ {
   "description": "",
   "devtoolsFrontendUrl": "/devtools/inspector.html?ws=127.0.0.1:9223/devtools/page/0261be06-1271-485b-bdff-48e443de7a91",
   "id": "0261be06-1271-485b-bdff-48e443de7a91",
   "title": "The Chromium Projects",
   "type": "page",
   "url": "https://www.chromium.org/",
   "webSocketDebuggerUrl": "ws://127.0.0.1:9223/devtools/page/0261be06-1271-485b-bdff-48e443de7a91"
} ]
</code>```

As a next step I'd like to connect selenium to the headless chromium. But when i try

```<code>final DesiredCapabilities caps = DesiredCapabilities.chrome();
final WebDriver driver = new RemoteWebDriver(new URL("http://localhost:9222/json"), caps);
driver.get("http://www.google.com");
</code>```

I do get the following logout

```<code>Jän 24, 2017 7:14:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Jän 24, 2017 7:14:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Falling back to original OSS JSON Wire Protocol.
Jän 24, 2017 7:14:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Falling back to straight W3C remote end connection

org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{browserName=chrome, version=, platform=ANY}], required capabilities = Capabilities [{}]
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'Geralds-MacBook-Pro.local', ip: '192.168.0.249', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.2', java.version: '1.8.0_111'
Driver info: driver.version: RemoteWebDriver
</code>```

Questions are:

Is the RemoteWebDriver the correct driver to connect to the headless
chromium?

I read about the DevTool protocol (https://docs.google.com/presentation/d/1gqK9F4lGAY3TZudAtdcxzMQNEE7PcuQrGu83No3l0lw/), but I'm not sure, how to create such a client using selenium.

Connecting the Chromium Headless using the Chrome DevTools works (https://developers.google.com/web/tools/chrome-devtools/remote-debugging/) besides some segmentation vaults ;-)

答:
Chrome 59 has the ability to create instance as headless . I have tried for Windows with new chrome driver 2.30 and it worked for me
https://www.automation99.com/2017/07/how-to-use-chrome-headless-using.html?m=1</p>

Body:
I would like to use chromium headless for automated testing using selenium. (https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md)

I do have the headless version already running on 9222. So if i open http://10.252.100.33:9222/json/I do get

[ {
   "description": "",
   "devtoolsFrontendUrl": "/devtools/inspector.html?ws=127.0.0.1:9223/devtools/page/0261be06-1271-485b-bdff-48e443de7a91",
   "id": "0261be06-1271-485b-bdff-48e443de7a91",
   "title": "The Chromium Projects",
   "type": "page",
   "url": "https://www.chromium.org/",
   "webSocketDebuggerUrl": "ws://127.0.0.1:9223/devtools/page/0261be06-1271-485b-bdff-48e443de7a91"
} ]

As a next step I'd like to connect selenium to the headless chromium. But when i try

final DesiredCapabilities caps = DesiredCapabilities.chrome();
final WebDriver driver = new RemoteWebDriver(new URL("http://localhost:9222/json"), caps);
driver.get("http://www.google.com");

I do get the following logout

Jän 24, 2017 7:14:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Jän 24, 2017 7:14:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Falling back to original OSS JSON Wire Protocol.
Jän 24, 2017 7:14:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Falling back to straight W3C remote end connection

org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{browserName=chrome, version=, platform=ANY}], required capabilities = Capabilities [{}]
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'Geralds-MacBook-Pro.local', ip: '192.168.0.249', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.2', java.version: '1.8.0_111'
Driver info: driver.version: RemoteWebDriver

Questions are:

Is the RemoteWebDriver the correct driver to connect to the headless
chromium?

I read about the DevTool protocol (https://docs.google.com/presentation/d/1gqK9F4lGAY3TZudAtdcxzMQNEE7PcuQrGu83No3l0lw/), but I'm not sure, how to create such a client using selenium.

Connecting the Chromium Headless using the Chrome DevTools works (https://developers.google.com/web/tools/chrome-devtools/remote-debugging/) besides some segmentation vaults ;-)


问:
Firefox + Edge input placeholder opacity transition
I have tried the solutions here and the other duplicate here, but those questions are 4 years old and the solutions do not work on newer versions of Firefox. Also, the bug linked in the latter has status: VERIFIED FIXED.

I have tried using only the transition prefix matching the placeholder prefix along with the transition fallback with no luck. ex:

```<code>&::-moz-placeholder {
    -moz-transition: $transition;
    transition: $transition;
}
</code>```

What's below works on chrome but not Firefox or Edge. The opacity changes fine but there is no transition. Am I missing something to support both Firefox and Edge placeholder transitions?

```<code>@mixin transition($transition...) {
    -webkit-transition: $transition;
    -moz-transition: $transition;
    -o-transition: $transition;
    transition: $transition;
}

@mixin placeholderOpacity($opacity) {
    &:-moz-placeholder {opacity: $opacity}
    &:-ms-input-placeholder  {opacity: $opacity}
    &::-webkit-input-placeholder {opacity: $opacity}
    &::-moz-placeholder {opacity: $opacity}
    &::placeholder  {opacity: $opacity}
}

@mixin placeholderTransition($transition) {
    &:-moz-placeholder {@include transition($transition);}
    &:-ms-input-placeholder  {@include transition($transition);}
    &::-webkit-input-placeholder {@include transition($transition);}
    &::-moz-placeholder {@include transition($transition);}
    &::placeholder  {@include transition($transition);}
}

input {
    @include placeholderOpacity(0);
    @include placeholderTransition(opacity 500ms ease-in-out);
}

input:focus {
    @include placeholderOpacity(1);
}
</code>```

答:
Since there is no real cross browser solution to style and animate placeholder's, I decided to post an updated version from another answer of mine, where this one having both a label, a placeholder and a required asterisk.

I have added a tiny script with one purpose only, to replicate what is written in an input field to its attribute value.

With that, one can then use CSS alone for the actual styling and animations, by simply use the attribute selector [attribute="value"] (in the way I think most users expect it to be used)

(function(pls) {
  /* run this script when page loaded */
  window.addEventListener('load', function() {
    /* find and iterate all "input placeholder" elements */
    pls = document.querySelectorAll('.placeholder input');
    for (var i = 0; i < pls.length; i++) {
      /* attach a handler to replicate input value */
      pls[i].addEventListener('input', function() {
        this.setAttribute('value', this.value);
      })
    }
  })
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.placeholder {
  position: relative;
  padding-top: 15px;
}
.placeholder + .placeholder {
  margin-top: 10px;
}
.placeholder label {
  position: absolute;
  left: 5px;
  width: 100%;
  top: calc(50.5% + 7.5px);
  transform: translateY(-50.5%);
  pointer-events: none;
  font-size: 16px;
  line-height: 16px;
}
.placeholder label::before,
.placeholder label span {
  position: relative;
  top: 0;
  transition: top .5s;
}

/* the label text + asterisk */
.placeholder input + label::before {
  content: attr(data-text) ' ';
  color: black;
}
.placeholder label span {
  color: red;
}
.placeholder input:not([required]) + label span {
  display: none;
}
.placeholder input:not([value=""]) + label::before,
.placeholder input:focus + label::before,
.placeholder input:not([value=""]) + label span,
.placeholder input:focus + label span {
  top: -22px;
}

/* the placeholder text */
.placeholder input + label::after {
  content: attr(data-placeholder);
  position: absolute;
  left: 0; top: 0;
  color: gray;
  opacity: 0;
  transition: opacity .5s .2s;
}
.placeholder input:focus + label::after {
  opacity:  1;
}
.placeholder input:not([value=""]) + label::after {
  opacity:  0;
  transition: opacity .2s;
}</code>```

  <input type="text" name="name" value="">
  *

  <input type="text" name="mail" value="" required>
  *

```

Body:
I have tried the solutions here and the other duplicate here, but those questions are 4 years old and the solutions do not work on newer versions of Firefox. Also, the bug linked in the latter has status: VERIFIED FIXED.

I have tried using only the transition prefix matching the placeholder prefix along with the transition fallback with no luck. ex:

&::-moz-placeholder {
    -moz-transition: $transition;
    transition: $transition;
}

What's below works on chrome but not Firefox or Edge. The opacity changes fine but there is no transition. Am I missing something to support both Firefox and Edge placeholder transitions?

@mixin transition($transition...) {
    -webkit-transition: $transition;
    -moz-transition: $transition;
    -o-transition: $transition;
    transition: $transition;
}

@mixin placeholderOpacity($opacity) {
    &:-moz-placeholder {opacity: $opacity}
    &:-ms-input-placeholder  {opacity: $opacity}
    &::-webkit-input-placeholder {opacity: $opacity}
    &::-moz-placeholder {opacity: $opacity}
    &::placeholder  {opacity: $opacity}
}

@mixin placeholderTransition($transition) {
    &:-moz-placeholder {@include transition($transition);}
    &:-ms-input-placeholder  {@include transition($transition);}
    &::-webkit-input-placeholder {@include transition($transition);}
    &::-moz-placeholder {@include transition($transition);}
    &::placeholder  {@include transition($transition);}
}

input {
    @include placeholderOpacity(0);
    @include placeholderTransition(opacity 500ms ease-in-out);
}

input:focus {
    @include placeholderOpacity(1);
}

Body:
Since there is no real cross browser solution to style and animate placeholder's, I decided to post an updated version from another answer of mine, where this one having both a label, a placeholder and a required asterisk.

I have added a tiny script with one purpose only, to replicate what is written in an input field to its attribute value.

With that, one can then use CSS alone for the actual styling and animations, by simply use the attribute selector [attribute="value"] (in the way I think most users expect it to be used)

(function(pls) {
  /* run this script when page loaded */
  window.addEventListener('load', function() {
    /* find and iterate all "input placeholder" elements */
    pls = document.querySelectorAll('.placeholder input');
    for (var i = 0; i < pls.length; i++) {
      /* attach a handler to replicate input value */
      pls[i].addEventListener('input', function() {
        this.setAttribute('value', this.value);
      })
    }
  })
})();

.placeholder {
  position: relative;
  padding-top: 15px;
}
.placeholder + .placeholder {
  margin-top: 10px;
}
.placeholder label {
  position: absolute;
  left: 5px;
  width: 100%;
  top: calc(50.5% + 7.5px);
  transform: translateY(-50.5%);
  pointer-events: none;
  font-size: 16px;
  line-height: 16px;
}
.placeholder label::before,
.placeholder label span {
  position: relative;
  top: 0;
  transition: top .5s;
}

/* the label text + asterisk */
.placeholder input + label::before {
  content: attr(data-text) ' ';
  color: black;
}
.placeholder label span {
  color: red;
}
.placeholder input:not([required]) + label span {
  display: none;
}
.placeholder input:not([value=""]) + label::before,
.placeholder input:focus + label::before,
.placeholder input:not([value=""]) + label span,
.placeholder input:focus + label span {
  top: -22px;
}

/* the placeholder text */
.placeholder input + label::after {
  content: attr(data-placeholder);
  position: absolute;
  left: 0; top: 0;
  color: gray;
  opacity: 0;
  transition: opacity .5s .2s;
}
.placeholder input:focus + label::after {
  opacity:  1;
}
.placeholder input:not([value=""]) + label::after {
  opacity:  0;
  transition: opacity .2s;
}

<div class="placeholder">
  <input type="text" name="name" value="">
  <label data-text="Name" data-placeholder="Add your name"><span>*</span></label>
</div>
<div class="placeholder">
  <input type="text" name="mail" value="" required>
  <label data-text="Email" data-placeholder="Add your email address"><span>*</span></label>
</div>


问:
remove all fields from 2nd col which is not 5 consecutive numerical digits
```<code> Record | RegistrationID

 41-1|10551
 1-105|5569
  4-7|10043
  78-3|2176
   3-1|19826
   12-1|1981
</code>```

Output file has to

```<code> Record | RegistrationID
1-1|10551
3-1|19826
5-7|10043
</code>```

My file is a Pipe delimited

any number in the 2nd col which is less than or more than 5lenght must be removed i.e only records that have 5 consecutive numbers must remain.I'm with google since an hour to fix this out any advice given would be highly appreciable. thanks in advance

tried this grep -E ' [0-9]{5}$|$' filename   - > not getting any results ,tx to cyrus

答:
If this doesn't do what you want:

```<code>$ awk '(NR==1) || ($NF~/^[0-9]{5}$/)' file
 Acno | Zip
 high | 12345
tyty | 19812
</code>```

then your real input file simply does not match the format that you provided in your example and you'd have to follow up on that yourself to figure out the difference and post more truly representative sample input if you want more help.

Given your updated input file with no spaces around the |s:

```<code>$ awk -F'|' '(NR==1) || ($NF~/^[0-9]{5}$/)' file
 Acno | Zip
 45775-1|10551
  2734455-7|10043
   167115-1|19826
</code>```

If you REALLY have leading white space in your input that you want to remove from the output that's easily done but I'm going to assume for now that you actually don't really have that situation and it's just more mistakes in your posted sample input file.

With gawk 3.1.7 as the OP has (see comments below):

```<code>awk --re-interval -F'|' '(NR==1) || ($NF~/^[0-9]{5}$/)' file
</code>```

Body:
 Record | RegistrationID

 41-1|10551
 1-105|5569
  4-7|10043
  78-3|2176
   3-1|19826
   12-1|1981

Output file has to

 Record | RegistrationID
1-1|10551
3-1|19826
5-7|10043

My file is a Pipe delimited

any number in the 2nd col which is less than or more than 5lenght must be removed i.e only records that have 5 consecutive numbers must remain.I'm with google since an hour to fix this out any advice given would be highly appreciable. thanks in advance

tried this grep -E ' [0-9]{5}$|$' filename   - > not getting any results ,tx to cyrus

Body:
If this doesn't do what you want:

$ awk '(NR==1) || ($NF~/^[0-9]{5}$/)' file
 Acno | Zip
 high | 12345
tyty | 19812

then your real input file simply does not match the format that you provided in your example and you'd have to follow up on that yourself to figure out the difference and post more truly representative sample input if you want more help.

Given your updated input file with no spaces around the |s:

$ awk -F'|' '(NR==1) || ($NF~/^[0-9]{5}$/)' file
 Acno | Zip
 45775-1|10551
  2734455-7|10043
   167115-1|19826

If you REALLY have leading white space in your input that you want to remove from the output that's easily done but I'm going to assume for now that you actually don't really have that situation and it's just more mistakes in your posted sample input file.

With gawk 3.1.7 as the OP has (see comments below):

awk --re-interval -F'|' '(NR==1) || ($NF~/^[0-9]{5}$/)' file


问:
Show DIV only in a certain date range
Hi SO-Community,

i figure this may be an amateur type of question, but i just could not find a proper solution anywhere:

I am trying to show a specific DIV only in Christmas Time via JavaScript. Here goes my code so far:

```<code>function WinterTime() {
var WinterStart = new Date(2017, 12, 21);
var WinterEnd = new Date(2017, 12, 27);
if
(WinterStart <= CurrentDate && CurrentDate <= WinterEnd) {
song2.style.display = "block";
}
else {
song2.style.display = "none";
}
}
</code>```

I defined the variable "song2" earlier in case you're wondering.

I figure this may be complete rubbish code but please show mercy since I am a total noob and just tried to learn from various other threats.
I am grateful for your Feedback. :)

Regards

Jonas

答:
What you have should work, but I've cleaned it up a bit.  I used console logging to show how your evaluation is working, you can adjust to work with your HTML as needed.

```<code>function winterTime(currentDate) {
  var winterStart = new Date(2017, 12, 21);
  var winterEnd = new Date(2017, 12, 27);
  if(winterStart <= currentDate && currentDate <= winterEnd) {
    // current date is within range
    console.log('true')
  } else {
    // current date is out of range
    console.log('false')
  }
}

winterTime(new Date()); // now
winterTime(new Date(2017, 12, 25)); // within range
</code>```

https://jsfiddle.net/34dv5y9a/

Title: Show DIV only in a certain date range

Body:
Hi SO-Community,

i figure this may be an amateur type of question, but i just could not find a proper solution anywhere:

I am trying to show a specific DIV only in Christmas Time via JavaScript. Here goes my code so far:

function WinterTime() {
var WinterStart = new Date(2017, 12, 21);
var WinterEnd = new Date(2017, 12, 27);
if
(WinterStart <= CurrentDate && CurrentDate <= WinterEnd) {
song2.style.display = "block";
}
else {
song2.style.display = "none";
}
}

I defined the variable "song2" earlier in case you're wondering.

I figure this may be complete rubbish code but please show mercy since I am a total noob and just tried to learn from various other threats.
I am grateful for your Feedback. :)

Regards

Jonas

Body:
What you have should work, but I've cleaned it up a bit.  I used console logging to show how your evaluation is working, you can adjust to work with your HTML as needed.

function winterTime(currentDate) {
  var winterStart = new Date(2017, 12, 21);
  var winterEnd = new Date(2017, 12, 27);
  if(winterStart <= currentDate && currentDate <= winterEnd) {
    // current date is within range
    console.log('true')
  } else {
    // current date is out of range
    console.log('false')
  }
}

winterTime(new Date()); // now
winterTime(new Date(2017, 12, 25)); // within range

https://jsfiddle.net/34dv5y9a/


问:
How to Determine Unicode Characters from a UTF-16 String?
I have string that contains an odd Unicode space character, but I'm not sure what character that is. I understand that in C# a string in memory is encoded using the UTF-16 format. What is a good way to determine which Unicode characters make up the string?

This question was marked as a possible duplicate to
Determine a string's encoding in C#
It's not a duplicate of this question because I'm not asking about what the encoding is. I already know that a string in C# is encoded as UTF-16. I'm just asking for an easy way to determine what the Unicode values are in the string.

答:
Unicode seems to identify characters as numeric code points. Not all code points actually refer to characters, however, because Unicode has the concept of combining characters (which I don’t know much about). However, each Unicode string, even some invalid ones (e.g., illegal sequence of combining characters), can be thought of as a list of code points (numbers).

In the UTF-16 encoding, each code point is encoded as a 2 or 4 byte sequence. In .net, Char might roughly correspond to either a 2 byte UTF-16 sequence or half of a 4 byte UTF-16 sequence. When Char contains half of a 4 byte sequence, it is considered a “surrogate” because it only has meaning when combined with another Char which it must be kept with. To get started with inspecting your .net string, you can get .net to tell you the code points contained in the string, automatically combining surrogate pairs together if necessary. .net provides Char.ConvertToUtf32 which is described the following way:

Converts the value of a UTF-16 encoded character or surrogate pair at a specified position in a string into a Unicode code point.

The documentation for Char.ConvertToUtf32(String s, Int32 index) states that an ArgumentException is thrown for the following case:

The specified index position contains a surrogate pair, and either the first character in the pair is not a valid high surrogate or the second character in the pair is not a valid low surrogate.

Thus, you can go character by character in a string and find all of the Unicode code points with the help of Char.IsHighSurrogate() and Char.ConvertToUtf32(). When you don’t encounter a high surrogate, the current character fits in one Char and you only need to advance one Char in your string. If you do encounter a high surrogate, the character requires two Char and you need to advance by two:

```<code>static IEnumerable<int> GetCodePoints(string s)
{
    for (var i = 0; i < s.Length; i += char.IsHighSurrogate(s[i]) ? 2 : 1)
    {
        yield return char.ConvertToUtf32(s, i);
    }
}
</code>```

When you say “from a UTF-16 String”, that might imply that you have read in a series of bytes formatted as UTF-16. If that is the case, you would need to convert that to a .net string before passing to the above method:

```<code>GetCodePoints(Encoding.UTF16.GetString(myUtf16Blob));
</code>```

Another note: depending on how you build your String instance, it is possible that it contains an illegal sequence of Char with regards to surrogate pairs. For such strings, Char.ConvertToUtf32() will throw an exception when encountered. However, I think that Encoding.GetString() will always either return a valid string or throw an exception. So, generally, as long as your String instances are from “good” sources, you needn’t worry about Char.ConvertToUtf32() throwing (unless you pass in random values for the index offset because your offset might be in the middle of a surrogate pair).

Body:
Unicode seems to identify characters as numeric code points. Not all code points actually refer to characters, however, because Unicode has the concept of combining characters (which I don’t know much about). However, each Unicode string, even some invalid ones (e.g., illegal sequence of combining characters), can be thought of as a list of code points (numbers).

In the UTF-16 encoding, each code point is encoded as a 2 or 4 byte sequence. In .net, Char might roughly correspond to either a 2 byte UTF-16 sequence or half of a 4 byte UTF-16 sequence. When Char contains half of a 4 byte sequence, it is considered a “surrogate” because it only has meaning when combined with another Char which it must be kept with. To get started with inspecting your .net string, you can get .net to tell you the code points contained in the string, automatically combining surrogate pairs together if necessary. .net provides Char.ConvertToUtf32 which is described the following way:

Converts the value of a UTF-16 encoded character or surrogate pair at a specified position in a string into a Unicode code point.

The documentation for Char.ConvertToUtf32(String s, Int32 index) states that an ArgumentException is thrown for the following case:

The specified index position contains a surrogate pair, and either the first character in the pair is not a valid high surrogate or the second character in the pair is not a valid low surrogate.

Thus, you can go character by character in a string and find all of the Unicode code points with the help of Char.IsHighSurrogate() and Char.ConvertToUtf32(). When you don’t encounter a high surrogate, the current character fits in one Char and you only need to advance one Char in your string. If you do encounter a high surrogate, the character requires two Char and you need to advance by two:

static IEnumerable<int> GetCodePoints(string s)
{
    for (var i = 0; i < s.Length; i += char.IsHighSurrogate(s[i]) ? 2 : 1)
    {
        yield return char.ConvertToUtf32(s, i);
    }
}

When you say “from a UTF-16 String”, that might imply that you have read in a series of bytes formatted as UTF-16. If that is the case, you would need to convert that to a .net string before passing to the above method:

GetCodePoints(Encoding.UTF16.GetString(myUtf16Blob));

Another note: depending on how you build your String instance, it is possible that it contains an illegal sequence of Char with regards to surrogate pairs. For such strings, Char.ConvertToUtf32() will throw an exception when encountered. However, I think that Encoding.GetString() will always either return a valid string or throw an exception. So, generally, as long as your String instances are from “good” sources, you needn’t worry about Char.ConvertToUtf32() throwing (unless you pass in random values for the index offset because your offset might be in the middle of a surrogate pair).


问:
Naming a new variable based on a quosure
I'm trying to write a custom function that will compute a new variable based on values from a predefined vector of variables (e.g., vector_heavy) and then name the new variable based on an argument provided to the function (e.g., custom_name).

This variable naming is where my quosure skills are failing me. Any help is greatly appreciated.

```<code>library(tidyverse)

vector_heavy <- quos(disp, wt, cyl)

cv_compute <- function(data, cv_name, cv_vector){
  cv_name <- enquo(cv_name)
  data %>%
    rowwise() %>%
    mutate(!!cv_name = mean(c(!!!cv_vector), na.rm = TRUE)) %>%
    ungroup()
}

d <- cv_compute(mtcars, cv_name = custom_name, cv_vector = vector_heavy)
</code>```

My error message reads:

```<code>Error: unexpected '=' in:
"    rowwise() %>%
    mutate(!!cv_name ="
</code>```

Removing the !! before cv_name within mutate() will result in a function that calculates a new variable literally named cv_name, and ignoring the custom_name I've included as an argument.

```<code>cv_compute <- function(data, cv_name, cv_vector){
  cv_name <- enquo(cv_name)
  data %>%
    rowwise() %>%
    mutate(cv_name = mean(c(!!!cv_vector), na.rm = TRUE)) %>%
    ungroup()
}
</code>```

How can I get this function to utilize the custom_name I supply as an argument for cv_name?

答:
You need to use the := helper within mutate.  You'll also need quo_name to convert the input to a string.

The mutate line of your function will then look like

mutate(!!quo_name(cv_name) := mean(c(!!!cv_vector), na.rm = TRUE))

In its entirety:

```<code>cv_compute <- function(data, cv_name, cv_vector){
     cv_name <- enquo(cv_name)
     data %>%
          rowwise() %>%
          mutate(!!quo_name(cv_name) := mean(c(!!!cv_vector), na.rm = TRUE)) %>%
          ungroup()
}

cv_compute(mtcars, cv_name = custom_name, cv_vector = vector_heavy)

    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb custom_name
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>       <dbl>
1  21.0     6   160   110  3.90 2.620 16.46     0     1     4     4    56.20667
2  21.0     6   160   110  3.90 2.875 17.02     0     1     4     4    56.29167
3  22.8     4   108    93  3.85 2.320 18.61     1     1     4     1    38.10667
4  21.4     6   258   110  3.08 3.215 19.44     1     0     3     1    89.07167
5  18.7     8   360   175  3.15 3.440 17.02     0     0     3     2   123.81333
6  18.1     6   225   105  2.76 3.460 20.22     1     0     3     1    78.15333
</code>```

Body:
I'm trying to write a custom function that will compute a new variable based on values from a predefined vector of variables (e.g., vector_heavy) and then name the new variable based on an argument provided to the function (e.g., custom_name).

This variable naming is where my quosure skills are failing me. Any help is greatly appreciated.

library(tidyverse)

vector_heavy <- quos(disp, wt, cyl)

cv_compute <- function(data, cv_name, cv_vector){
  cv_name <- enquo(cv_name)
  data %>%
    rowwise() %>%
    mutate(!!cv_name = mean(c(!!!cv_vector), na.rm = TRUE)) %>%
    ungroup()
}

d <- cv_compute(mtcars, cv_name = custom_name, cv_vector = vector_heavy)

My error message reads:

Error: unexpected '=' in:
"    rowwise() %>%
    mutate(!!cv_name ="

Removing the !! before cv_name within mutate() will result in a function that calculates a new variable literally named cv_name, and ignoring the custom_name I've included as an argument.

cv_compute <- function(data, cv_name, cv_vector){
  cv_name <- enquo(cv_name)
  data %>%
    rowwise() %>%
    mutate(cv_name = mean(c(!!!cv_vector), na.rm = TRUE)) %>%
    ungroup()
}

How can I get this function to utilize the custom_name I supply as an argument for cv_name?

Body:
You need to use the := helper within mutate.  You'll also need quo_name to convert the input to a string.

The mutate line of your function will then look like

mutate(!!quo_name(cv_name) := mean(c(!!!cv_vector), na.rm = TRUE))

In its entirety:

cv_compute <- function(data, cv_name, cv_vector){
     cv_name <- enquo(cv_name)
     data %>%
          rowwise() %>%
          mutate(!!quo_name(cv_name) := mean(c(!!!cv_vector), na.rm = TRUE)) %>%
          ungroup()
}

cv_compute(mtcars, cv_name = custom_name, cv_vector = vector_heavy)

    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb custom_name
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>       <dbl>
1  21.0     6   160   110  3.90 2.620 16.46     0     1     4     4    56.20667
2  21.0     6   160   110  3.90 2.875 17.02     0     1     4     4    56.29167
3  22.8     4   108    93  3.85 2.320 18.61     1     1     4     1    38.10667
4  21.4     6   258   110  3.08 3.215 19.44     1     0     3     1    89.07167
5  18.7     8   360   175  3.15 3.440 17.02     0     0     3     2   123.81333
6  18.1     6   225   105  2.76 3.460 20.22     1     0     3     1    78.15333


问:
jquery class selector function won't accept date as arguement
I'm using a function that successfully calculates and (should successfully) return the date for Tuesday if today is Tuesday, Wednesday if it's Wednesday, and if it's some other day today it should return next Tuesday.  This function is used to put this date into put into a datepicker input's default value.  I've verified that the function does in fact calculate the correct date to use.  However, when passing the return value to the selector's arguements, no date is displayed in the input object.

I tried entering strings and numbers into the second argument of the selector function instead of setDate() and it still doesn't display anything.

For a history of what led to this question, you can reference this question Original question that led to this question

```<code><!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>My Title</title>
    <!-- for datepicker -->
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
    <!-- for timepicker -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
    <!-- for momentjs -->
    <script src="//momentjs.com/downloads/moment.min.js"/></script>
    <script src="//momentjs.com/downloads/moment-with-locales.min.js"></script>

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css" />
    <script type="text/javascript">
        $(document).ready(function(){
            $( ".datepicker" ).datepicker({
                minDate:'0',
                changeMonth:true,
                changeYear:true,
            beforeShowDay:
                  function(dt)
                  {
                      return [dt.getDay() === 2 || dt.getDay() === 3, ""];
                  }});
            });

        // function moment().isoWeekday is from Momentjs script source above.
        // to automatically set the date to the next tuesday or wednesday if not already one of those days.
        function setDate() {
            var today = moment().isoWeekday(); //or just = new Date().getDay();
            var timestamp;
            if (today <= 2) {
                timestamp = moment().isoWeekday(2);
            } else if (today === 3) {
                timestamp = moment().isoWeekday(3);
            } else {
                timestamp = moment().add(1, 'weeks').isoWeekday(2);
            }
            document.write(new Date(timestamp));
            return new Date(timestamp);
        }
        // Problem occurs here: it's like setDate() wont' give datepicker something it can display.

        $('.datepicker').datepicker("setDate", setDate());

        $(document).ready(function(){
            $('input.timepicker').timepicker({
                timeFormat: 'h:mm p',
                interval: 90,
                minTime: '9',
                maxTime: '10:30am',
                defaultTime: '9',
                startTime: '9:00',
                dynamic: false,
                dropdown: true,
                scrollbar: false
            });
        });
    </script>
</head>
<body>

<form method="POST">
  <div style='margin:0 auto; text-align:center;'>
    <label>Appointment Date: </label>
    <input type="hidden" name="action" value="list_appointments" />
    <input type="text" id="datepicker" name="date" class="datepicker" />
    <input type="submit" value="Refresh List" name="Update" />
    <br />
  </div>
</form>
<body>
</code>```

答:
I believe this is what you need. Remember to keep your function calls within the same document load function, i.e. $(document.ready).</p>

```<code>    <script type="text/javascript">
        $(document).ready(function() {
            $( ".datepicker" ).datepicker({
                minDate:'0',
                changeMonth:true,
                changeYear:true,
                beforeShowDay: function(dt)
                  {
                      return [dt.getDay() === 2 || dt.getDay() === 3, ""];
                  }
            });

            $('input.timepicker').timepicker({
                timeFormat: 'h:mm p',
                interval: 90,
                minTime: '9',
                maxTime: '10:30am',
                defaultTime: '9',
                startTime: '9:00',
                dynamic: false,
                dropdown: true,
                scrollbar: false
            });

            function setDate() {
                var today = moment().isoWeekday(); //or just = new Date().getDay();
                var timestamp;
                if (today <= 2) {
                    timestamp = moment().isoWeekday(2);
                } else if (today === 3) {
                    timestamp = moment().isoWeekday(3);
                } else {
                    timestamp = moment().add(1, 'weeks').isoWeekday(2);
                }
                return new Date(timestamp);
            }

            $('.datepicker').datepicker("setDate", setDate());
        });

        // function moment().isoWeekday is from Momentjs script source above.
        // to automatically set the date to the next tuesday or wednesday if not already one of those days.

        // Problem occurs here: it's like setDate() wont' give datepicker something it can display.
    </script>
</code>```

Body:
I'm using a function that successfully calculates and (should successfully) return the date for Tuesday if today is Tuesday, Wednesday if it's Wednesday, and if it's some other day today it should return next Tuesday.  This function is used to put this date into put into a datepicker input's default value.  I've verified that the function does in fact calculate the correct date to use.  However, when passing the return value to the selector's arguements, no date is displayed in the input object.

I tried entering strings and numbers into the second argument of the selector function instead of setDate() and it still doesn't display anything.

For a history of what led to this question, you can reference this question Original question that led to this question

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>My Title</title>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css" />

<form method="POST">

    Appointment Date:
    <input type="hidden" name="action" value="list_appointments" />
    <input type="text" id="datepicker" name="date" class="datepicker" />
    <input type="submit" value="Refresh List" name="Update" />

</form>

Body:
I believe this is what you need. Remember to keep your function calls within the same document load function, i.e. $(document.ready).

    <script type="text/javascript">
        $(document).ready(function() {
            $( ".datepicker" ).datepicker({
                minDate:'0',
                changeMonth:true,
                changeYear:true,
                beforeShowDay: function(dt)
                  {
                      return [dt.getDay() === 2 || dt.getDay() === 3, ""];
                  }
            });

            $('input.timepicker').timepicker({
                timeFormat: 'h:mm p',
                interval: 90,
                minTime: '9',
                maxTime: '10:30am',
                defaultTime: '9',
                startTime: '9:00',
                dynamic: false,
                dropdown: true,
                scrollbar: false
            });

            function setDate() {
                var today = moment().isoWeekday(); //or just = new Date().getDay();
                var timestamp;
                if (today <= 2) {
                    timestamp = moment().isoWeekday(2);
                } else if (today === 3) {
                    timestamp = moment().isoWeekday(3);
                } else {
                    timestamp = moment().add(1, 'weeks').isoWeekday(2);
                }
                return new Date(timestamp);
            }

            $('.datepicker').datepicker("setDate", setDate());
        });

        // function moment().isoWeekday is from Momentjs script source above.
        // to automatically set the date to the next tuesday or wednesday if not already one of those days.

        // Problem occurs here: it's like setDate() wont' give datepicker something it can display.
    </script>


问:
Array.map doesn't seem to work on uninitialized arrays
I'm trying to set default values on an uninitialized array using the map function but it doesn't seem to work, any ideas on how to set default values?

Consider this code snippet I tried in Chrome console.

```<code>> var N = 10;
> var x = new Array(N);
> x
  [undefined x 10]

> x.map(function(i) { return 0;});
  [undefined x 10]
</code>```

I was expecting the array to be initialized to 0's.

答:
Building on a previous answer there is new shorter syntax. The OP wanted to create an array of N items initialized with 0.

```<code>var N = 10;
var x = new Array(N).fill(0);
// x is now: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
</code>```

You also don't need the new - it's optional in this context.

Check the compatibility of your target platform and/or use a pollyfill if not available.

Body:
I'm trying to set default values on an uninitialized array using the map function but it doesn't seem to work, any ideas on how to set default values?

Consider this code snippet I tried in Chrome console.

> var N = 10;
> var x = new Array(N);
> x
  [undefined x 10]

> x.map(function(i) { return 0;});
  [undefined x 10]

I was expecting the array to be initialized to 0's.

Body:
Building on a previous answer there is new shorter syntax. The OP wanted to create an array of N items initialized with 0.

var N = 10;
var x = new Array(N).fill(0);
// x is now: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

You also don't need the new - it's optional in this context.

Check the compatibility of your target platform and/or use a pollyfill if not available.


问:
ngOnDestroy Uncaught (in promise): TypeError: Cannot read property 'unsubscribe' of undefined
I'm getting an error when unsubscribing during the ngOnDestroy method in my shopping-edit.component.ts when i click the link to go to my recipes page. here is the image

error on link click

here is a link to my git https://github.com/CHBaker/First-Angular-App

and my code snippet:

```<code>import {
    Component,
    OnInit,
    OnDestroy,
    ViewChild
} from '@angular/core';
import { NgForm } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';

import { Ingredient } from '../../shared/ingredient.model';
import { ShoppingListService } from '../shopping-list.service';

@Component({
    selector: 'app-shopping-edit',
    templateUrl: './shopping-edit.component.html',
    styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit, OnDestroy {
    @ViewChild('f') slForm: NgForm;
    subscription: Subscription;
    editMode = false;
    editedItemIndex: number;
    editedItem: Ingredient;

    constructor(private slService: ShoppingListService) { }

    ngOnInit() {
        this.slService.startedEditing
            .subscribe(
                (index: number) => {
                    this.editedItemIndex = index;
                    this.editMode = true;
                    this.editedItem = this.slService.getIngredient(index);
                    this.slForm.setValue({
                        name: this.editedItem.name,
                        amount: this.editedItem.amount
                    })
                }
            );
    }

    onSubmit(form: NgForm) {
        const value = form.value;
        const newIngredient = new Ingredient(value.name, value.amount);
        if (this.editMode) {
            this.slService.updateIngredient(this.editedItemIndex, newIngredient);
        } else {
            this.slService.addIngredient(newIngredient);
        }
        this.editMode = false;
        form.reset();
    }

    onClear() {
        this.slForm.reset();
        this.editMode = false;
    }

    onDelete() {
        this.slService.deleteIngredient(this.editedItemIndex);
        this.onClear();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
</code>```

答: You must assign the result of this.slService.startedEditing.subscribe() to this.subscription

Body:
I'm getting an error when unsubscribing during the ngOnDestroy method in my shopping-edit.component.ts when i click the link to go to my recipes page. here is the image

error on link click

here is a link to my git https://github.com/CHBaker/First-Angular-App

and my code snippet:

import {
    Component,
    OnInit,
    OnDestroy,
    ViewChild
} from '@angular/core';
import { NgForm } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';

import { Ingredient } from '../../shared/ingredient.model';
import { ShoppingListService } from '../shopping-list.service';

@Component({
    selector: 'app-shopping-edit',
    templateUrl: './shopping-edit.component.html',
    styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit, OnDestroy {
    @ViewChild('f') slForm: NgForm;
    subscription: Subscription;
    editMode = false;
    editedItemIndex: number;
    editedItem: Ingredient;

    constructor(private slService: ShoppingListService) { }

    ngOnInit() {
        this.slService.startedEditing
            .subscribe(
                (index: number) => {
                    this.editedItemIndex = index;
                    this.editMode = true;
                    this.editedItem = this.slService.getIngredient(index);
                    this.slForm.setValue({
                        name: this.editedItem.name,
                        amount: this.editedItem.amount
                    })
                }
            );
    }

    onSubmit(form: NgForm) {
        const value = form.value;
        const newIngredient = new Ingredient(value.name, value.amount);
        if (this.editMode) {
            this.slService.updateIngredient(this.editedItemIndex, newIngredient);
        } else {
            this.slService.addIngredient(newIngredient);
        }
        this.editMode = false;
        form.reset();
    }

    onClear() {
        this.slForm.reset();
        this.editMode = false;
    }

    onDelete() {
        this.slService.deleteIngredient(this.editedItemIndex);
        this.onClear();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}


问:
Fixing IllegalStateException
```<code>try {
        Response response = client.newCall(request).execute();
        getStockInfoFromJSON(response.body().string());
    } catch (IOException | JSONException | IllegalStateException e) {
        Log.i("GraphAsyncTask", e.toString());
    }
</code>```

For the code block seen above, I am now getting an IllegalStateException. I wasn't getting this error originally. I needed to change the API, so the URL in the request object is different. The error comes after the Response object is created. The getStockInfoFromJSON() method isn't running. I know it isn't running because I placed a log statement at the very beginning and it didn't show up in the console. How can I keep this error from being thrown.

```<code>private void getStockInfoFromJSON(String JsonString)
        throws JSONException {
    Log.i("MSA JSON string", JsonString);
    MyStocksActivity.StockData = new ArrayList<>();
    JSONObject Json = new JSONObject(JsonString);
    JSONObject StockInfo = Json.getJSONObject("Time Series (Daily)");
    JSONArray array = new JSONArray();
    StockInfo.toJSONArray(array);
    Log.i("MSA", "JSON array " + StockInfo.toString());

    for (int i = 0; i < array.length(); i++) {
        StockData datum = new StockData();
        JSONObject stockPrice = array.getJSONObject(i);
        Log.i("stock price array", stockPrice.toString());
        String date = array.getString(i);
        Log.i("date", date);
        String[] stringDate = date.split("-");
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(stringDate[0]),
                Integer.parseInt(stringDate[1]), Integer.parseInt(stringDate[2].substring(0, 2)));
        Log.i("cal", cal.toString());
        datum.date = cal.getTimeInMillis();
        datum.price = array.getDouble(3);
        datum.CalDate = date.split(" ")[0];
        MyStocksActivity.StockData.add(datum);

    }
}
</code>```

This is the error message I get.

```<code>07-03 15:05:29.586 27929-28167/com.example.sam_chordas.stockhawk I/GraphAsyncTask: java.lang.IllegalStateException: closed
</code>```

答: Are you reading the response body twice? You can only call string() once.

Title: Fixing IllegalStateException

Body:
try {
        Response response = client.newCall(request).execute();
        getStockInfoFromJSON(response.body().string());
    } catch (IOException | JSONException | IllegalStateException e) {
        Log.i("GraphAsyncTask", e.toString());
    }

For the code block seen above, I am now getting an IllegalStateException. I wasn't getting this error originally. I needed to change the API, so the URL in the request object is different. The error comes after the Response object is created. The getStockInfoFromJSON() method isn't running. I know it isn't running because I placed a log statement at the very beginning and it didn't show up in the console. How can I keep this error from being thrown.

private void getStockInfoFromJSON(String JsonString)
        throws JSONException {
    Log.i("MSA JSON string", JsonString);
    MyStocksActivity.StockData = new ArrayList<>();
    JSONObject Json = new JSONObject(JsonString);
    JSONObject StockInfo = Json.getJSONObject("Time Series (Daily)");
    JSONArray array = new JSONArray();
    StockInfo.toJSONArray(array);
    Log.i("MSA", "JSON array " + StockInfo.toString());

    for (int i = 0; i < array.length(); i++) {
        StockData datum = new StockData();
        JSONObject stockPrice = array.getJSONObject(i);
        Log.i("stock price array", stockPrice.toString());
        String date = array.getString(i);
        Log.i("date", date);
        String[] stringDate = date.split("-");
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(stringDate[0]),
                Integer.parseInt(stringDate[1]), Integer.parseInt(stringDate[2].substring(0, 2)));
        Log.i("cal", cal.toString());
        datum.date = cal.getTimeInMillis();
        datum.price = array.getDouble(3);
        datum.CalDate = date.split(" ")[0];
        MyStocksActivity.StockData.add(datum);

    }
}

This is the error message I get.

07-03 15:05:29.586 27929-28167/com.example.sam_chordas.stockhawk I/GraphAsyncTask: java.lang.IllegalStateException: closed


问:
jRuby threading - am I doing it right?
Would you mind telling me if I am threading correctly in Ruby?

I have an array items that I want to process in 16 threads, wait until all the threads have finished, and then do more work.

Here is my code;

```<code>    chunks = items.each_slice(items.count / 16).to_a
puts chunks.length

queue = Queue.new
semaphore = Mutex.new
threads = []

puts '[+] Building Queue'
chunks.each do |chunk|
    threads << Thread.new {
        chunk.each do |item|
            array = []
            metadata.each do |m|
                array << m.evaluate(item) rescue ''
            end
semaphore.synchronize {
    queue << array.join(20.chr)
}
        end
    }
end
puts '[+] Running threads'
threads.each{|t|t.join; puts 'Threads done'}

#Do more work here, queue should be fully populated
puts '[+] Writing to file'
File.open('E:/Export.dat', 'wt', encoding: 'UTF-16LE') do |f|
    until queue.empty?
        unit = queue.pop(true) rescue nil
        if unit
            f.puts unit
        end
    end
end
</code>```

The code runs, but doesn't give me the performance I would expect from threading, is it correct?

Thanks

答:
It's unlikely that you will see a performance improvement because each thread is blocking to add the result to the queue. The Queue class is thread safe so you don't need a Mutex to guard it.

To make multi-threaded code work better, you want each thread to operate as independently as possible. The below implementation should improve the performance.

```<code>chunks = items.each_slice(items.count / 16).to_a
puts chunks.length

queue = Queue.new
threads = []

puts '[+] Building Queue'
chunks.each do |chunk|
    threads << Thread.new do
        chunk.each do |item|
            array = []
            metadata.each do |m|
                array << m.evaluate(item) rescue ''
            end
            queue << array.join(20.chr)
        end
    end
end
puts '[+] Running threads'
threads.each{|t|t.join; puts 'Threads done'}

#Do more work here, queue should be fully populated
puts '[+] Writing to file'
File.open('E:/Export.dat', 'wt', encoding: 'UTF-16LE') do |f|
    until queue.empty?
        unit = queue.pop(true) rescue nil
        if unit
            f.puts unit
        end
    end
end
</code>```

You also need to measure where the bottlenecks are in your code.  Simple timers (difference between start and end times) are fine. If the evaluation of metadata takes 10ms with threads and 100ms without, and writing to the file takes 1000ms. Then you aren't going to notice a big difference from multi-threading.

Title: jRuby threading - am I doing it right?

Body:
Would you mind telling me if I am threading correctly in Ruby?

I have an array items that I want to process in 16 threads, wait until all the threads have finished, and then do more work.

Here is my code;

    chunks = items.each_slice(items.count / 16).to_a
puts chunks.length

queue = Queue.new
semaphore = Mutex.new
threads = []

puts '[+] Building Queue'
chunks.each do |chunk|
    threads << Thread.new {
        chunk.each do |item|
            array = []
            metadata.each do |m|
                array << m.evaluate(item) rescue ''
            end
semaphore.synchronize {
    queue << array.join(20.chr)
}
        end
    }
end
puts '[+] Running threads'
threads.each{|t|t.join; puts 'Threads done'}

#Do more work here, queue should be fully populated
puts '[+] Writing to file'
File.open('E:/Export.dat', 'wt', encoding: 'UTF-16LE') do |f|
    until queue.empty?
        unit = queue.pop(true) rescue nil
        if unit
            f.puts unit
        end
    end
end

The code runs, but doesn't give me the performance I would expect from threading, is it correct?

Thanks

Body:
It's unlikely that you will see a performance improvement because each thread is blocking to add the result to the queue. The Queue class is thread safe so you don't need a Mutex to guard it.

To make multi-threaded code work better, you want each thread to operate as independently as possible. The below implementation should improve the performance.

chunks = items.each_slice(items.count / 16).to_a
puts chunks.length

queue = Queue.new
threads = []

puts '[+] Building Queue'
chunks.each do |chunk|
    threads << Thread.new do
        chunk.each do |item|
            array = []
            metadata.each do |m|
                array << m.evaluate(item) rescue ''
            end
            queue << array.join(20.chr)
        end
    end
end
puts '[+] Running threads'
threads.each{|t|t.join; puts 'Threads done'}

#Do more work here, queue should be fully populated
puts '[+] Writing to file'
File.open('E:/Export.dat', 'wt', encoding: 'UTF-16LE') do |f|
    until queue.empty?
        unit = queue.pop(true) rescue nil
        if unit
            f.puts unit
        end
    end
end

You also need to measure where the bottlenecks are in your code.  Simple timers (difference between start and end times) are fine. If the evaluation of metadata takes 10ms with threads and 100ms without, and writing to the file takes 1000ms. Then you aren't going to notice a big difference from multi-threading.


问:
Create 2-D Array and Set Values
I am trying to write a C program that generates R files that solve systems of linear equations. In main, I have six nested for loops to get every iteration of where the coefficients are integers 0 - 9:

```<code>ax + by + c = dx + ey + f
a_2x + b_2y + c_2 = d_2x + e_2y + f
</code>```

Each equation is a array of 6 integer coefficients. I set the values of the coefficients in my main function before passing it to generateContentForSystems.

However, my print statement returns:
value of numx:-000-0 value of numy:000-0 value of numz:00-0 value of numx_2:0-0 value of numy_2:-0 value of numz_2:0
I believe this is because of bad pointer arithmetic. I am now trying to and from a pointer to an array (in main) and have an array of arrays.

```<code>#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "scaffold.c"

void * generateContentForSystems(int * row1, int * row2) {
  static int index = 0;
  int x = row1[0] - row1[3];
  int y = row1[1] - row1[4];
  int z = row1[5] - row1[2];

  int x_2 = row2[0] - row2[3];
  int y_2 = row2[1] - row2[4];
  int z_2 = row2[5] - row2[2];

  int prod1 = x * y_2;
  int prod2 = x_2 * y;
  int determinant = prod1 - prod2;
  if (determinant != 0) {
    printf("the value of determinant: %d", determinant);
    char * error1;
    char Q[1000];
    strcpy(Q, "emake <- function(){\noptions(\"warn\"=-1)\ne <- 0\nfor (n in 0:2000){\ne <- e+ 1/(factorial(n))\n}\nreturn(e)\n}\ne <- emake()\n");
    char numx[1];
    char numy[1];
    char numz[1];
    char numx_2[1];
    char numy_2[1];
    char numz_2[1];
    sprintf(numx, "%d", x);
    sprintf(numy, "%d", y);
    sprintf(numz, "%d", z);
    sprintf(numx_2, "%d", x_2);
    sprintf(numy_2, "%d", y_2);
    sprintf(numz_2, "%d", z_2);

      //debug:
 printf("value of numx:%s value of numy:%s value of numz:%s value of numx_2:%s value of numy_2:%s value of numz_2:%s", numx, numy, numz, numx_2, numy_2, numz_2);

    strcat(Q, "A = array(c(");
    strcat(Q, numx);
    strcat(Q, ", ");
    strcat(Q, numx_2);
    strcat(Q, ", ");
    strcat(Q, numy);
    strcat(Q, ", ");
    strcat(Q, numy_2);
    strcat(Q, "), dim = c(2,2,1))\n");
    strcat(Q, "b = c(");
    strcat(Q, numz);
    strcat(Q, ", ");
    strcat(Q, numz_2);
    strcat(Q, ")\n");
    strcat(Q, "solve(A[,,1],b)\n");

    char filename[100];
    char snum[5];
    itoa(index, snum);
    index++;
    strcpy(filename, "practice/");
    strcat(filename, snum);
    strcat(filename, ".R");
    FILE * F = fopen(filename, "w");
    fputs(Q, F);
    fclose(F);
    char path[1024];
    char command[300];
    strcpy(command, "Rscript ");
    strcat(command, "practice/");
    debug("After Rscript formation");
    strcat(command, snum);
    strcat(command, ".R");
    FILE * fp = popen(command, "r");
    if (!fp) { //validate file is open
      return NULL;
    }

    while (fgets(path, sizeof(path) - 1, fp) != NULL) {
      debug("in Primary While Loop");
      fflush(stdout);
      printf("the solution: %s", path);
      if (strstr(path, ".") > strstr(path, "with absolute error") || strstr(path, ".5 ") != NULL) {
        printf("answer was accepted");

      }
    }

  }
}

int main() {

  int arrayIndexes = 0;
  int ** myArray = malloc(1 * sizeof( * myArray));

  for (int a = 0; a < 10; a++) {
    for (int b = 0; b < 10; b++) {
      for (int c = 0; c < 10; c++) {
        for (int d = 0; d < 10; d++) {
          for (int e = 0; e < 10; e++) {
            for (int f = 0; f < 10; f++) {

              myArray[arrayIndexes] = malloc(6 * sizeof(int));
              myArray[arrayIndexes][0] = a;
              myArray[arrayIndexes][1] = b;
              myArray[arrayIndexes][2] = c;
              myArray[arrayIndexes][3] = d;
              myArray[arrayIndexes][4] = e;
              myArray[arrayIndexes][5] = f;

              if (arrayIndexes > 0) {
                for (int i = 0; i < arrayIndexes; i++) {
                  generateContentForSystems(myArray[arrayIndexes], myArray[i]);
                }
              }

              ++arrayIndexes;
              myArray = realloc(myArray, (arrayIndexes + 1) * sizeof( * myArray));

            }
          }
        }
      }
    }

  }
  for (int n = 0; n = arrayIndexes; n++) {
    free(myArray[n]);
  }
  free(myArray);

  return 0;
}
</code>```

答:
Your number strings are not long enough:

```<code>char numx[1];
char numy[1];
char numz[1];
char numx_2[1];
char numy_2[1];
char numz_2[1];
</code>```

A string consists of a sequence of characters plus a null terminating byte.  So even a single digit needs an array size of at least 2.  When you use sprintf to write the text representation of a number to one of these arrays you write past the end of the array.  This invokes undefined behavior.

These arrays need to be large enough to accommodate whatever value you may pass in, including a negation sign if needed.

```<code>char numx[10];
char numy[10];
char numz[10];
char numx_2[10];
char numy_2[10];
char numz_2[10];
</code>```

Title: Create 2-D Array and Set Values

Body:
I am trying to write a C program that generates R files that solve systems of linear equations. In main, I have six nested for loops to get every iteration of where the coefficients are integers 0 - 9:

ax + by + c = dx + ey + f
a_2x + b_2y + c_2 = d_2x + e_2y + f

Each equation is a array of 6 integer coefficients. I set the values of the coefficients in my main function before passing it to generateContentForSystems.

However, my print statement returns:
value of numx:-000-0 value of numy:000-0 value of numz:00-0 value of numx_2:0-0 value of numy_2:-0 value of numz_2:0
I believe this is because of bad pointer arithmetic. I am now trying to and from a pointer to an array (in main) and have an array of arrays.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "scaffold.c"

void * generateContentForSystems(int * row1, int * row2) {
  static int index = 0;
  int x = row1[0] - row1[3];
  int y = row1[1] - row1[4];
  int z = row1[5] - row1[2];

  int x_2 = row2[0] - row2[3];
  int y_2 = row2[1] - row2[4];
  int z_2 = row2[5] - row2[2];

  int prod1 = x * y_2;
  int prod2 = x_2 * y;
  int determinant = prod1 - prod2;
  if (determinant != 0) {
    printf("the value of determinant: %d", determinant);
    char * error1;
    char Q[1000];
    strcpy(Q, "emake <- function(){\noptions(\"warn\"=-1)\ne <- 0\nfor (n in 0:2000){\ne <- e+ 1/(factorial(n))\n}\nreturn(e)\n}\ne <- emake()\n");
    char numx[1];
    char numy[1];
    char numz[1];
    char numx_2[1];
    char numy_2[1];
    char numz_2[1];
    sprintf(numx, "%d", x);
    sprintf(numy, "%d", y);
    sprintf(numz, "%d", z);
    sprintf(numx_2, "%d", x_2);
    sprintf(numy_2, "%d", y_2);
    sprintf(numz_2, "%d", z_2);

      //debug:
 printf("value of numx:%s value of numy:%s value of numz:%s value of numx_2:%s value of numy_2:%s value of numz_2:%s", numx, numy, numz, numx_2, numy_2, numz_2);

    strcat(Q, "A = array(c(");
    strcat(Q, numx);
    strcat(Q, ", ");
    strcat(Q, numx_2);
    strcat(Q, ", ");
    strcat(Q, numy);
    strcat(Q, ", ");
    strcat(Q, numy_2);
    strcat(Q, "), dim = c(2,2,1))\n");
    strcat(Q, "b = c(");
    strcat(Q, numz);
    strcat(Q, ", ");
    strcat(Q, numz_2);
    strcat(Q, ")\n");
    strcat(Q, "solve(A[,,1],b)\n");

    char filename[100];
    char snum[5];
    itoa(index, snum);
    index++;
    strcpy(filename, "practice/");
    strcat(filename, snum);
    strcat(filename, ".R");
    FILE * F = fopen(filename, "w");
    fputs(Q, F);
    fclose(F);
    char path[1024];
    char command[300];
    strcpy(command, "Rscript ");
    strcat(command, "practice/");
    debug("After Rscript formation");
    strcat(command, snum);
    strcat(command, ".R");
    FILE * fp = popen(command, "r");
    if (!fp) { //validate file is open
      return NULL;
    }

    while (fgets(path, sizeof(path) - 1, fp) != NULL) {
      debug("in Primary While Loop");
      fflush(stdout);
      printf("the solution: %s", path);
      if (strstr(path, ".") > strstr(path, "with absolute error") || strstr(path, ".5 ") != NULL) {
        printf("answer was accepted");

      }
    }

  }
}

int main() {

  int arrayIndexes = 0;
  int ** myArray = malloc(1 * sizeof( * myArray));

  for (int a = 0; a < 10; a++) {
    for (int b = 0; b < 10; b++) {
      for (int c = 0; c < 10; c++) {
        for (int d = 0; d < 10; d++) {
          for (int e = 0; e < 10; e++) {
            for (int f = 0; f < 10; f++) {

              myArray[arrayIndexes] = malloc(6 * sizeof(int));
              myArray[arrayIndexes][0] = a;
              myArray[arrayIndexes][1] = b;
              myArray[arrayIndexes][2] = c;
              myArray[arrayIndexes][3] = d;
              myArray[arrayIndexes][4] = e;
              myArray[arrayIndexes][5] = f;

              if (arrayIndexes > 0) {
                for (int i = 0; i < arrayIndexes; i++) {
                  generateContentForSystems(myArray[arrayIndexes], myArray[i]);
                }
              }

              ++arrayIndexes;
              myArray = realloc(myArray, (arrayIndexes + 1) * sizeof( * myArray));

            }
          }
        }
      }
    }

  }
  for (int n = 0; n = arrayIndexes; n++) {
    free(myArray[n]);
  }
  free(myArray);

  return 0;
}

Body:
Your number strings are not long enough:

char numx[1];
char numy[1];
char numz[1];
char numx_2[1];
char numy_2[1];
char numz_2[1];

A string consists of a sequence of characters plus a null terminating byte.  So even a single digit needs an array size of at least 2.  When you use sprintf to write the text representation of a number to one of these arrays you write past the end of the array.  This invokes undefined behavior.

These arrays need to be large enough to accommodate whatever value you may pass in, including a negation sign if needed.

char numx[10];
char numy[10];
char numz[10];
char numx_2[10];
char numy_2[10];
char numz_2[10];