问:
Split without some spaces
Good morning,

If I have a string:

```<code>"@Hello(first second), one two"
</code>```

And I want an array:

```<code>["@Hello(first second)", "one", "two"]
</code>```

How I can do this?

Thanks,

答:
You can use .split() with RegExp /\s(?!\w+\))/ to match space character not followed by word characters followed by closing parenthesis ")"

```<code>var str = "@Hello(first second), one two";
var res = str.split(/\s(?!\w+\))/);
console.log(res);
</code>```

Alternatively you can use .match() with RegExp /@\w+\(\w+\s\w+(?=\))\)|\w+(?=\s|$)/g to match "@" followed by one or more word characters followed by "(" followed by word characters followed by space character followed by word characters followed by closing parenthsis ")" or word characters followed by space or end of string

```<code>var str = "@Hello(first second), one two";
var res = str.match(/@\w+\(\w+\s\w+(?=\))\)|\w+(?=\s|$)/g);
console.log(res);
</code>```

Title: Split without some spaces

Body:
Good morning,

If I have a string:

"@Hello(first second), one two"

And I want an array:

["@Hello(first second)", "one", "two"]

How I can do this?

Thanks,

Body:
You can use .split() with RegExp /\s(?!\w+\))/ to match space character not followed by word characters followed by closing parenthesis ")"

var str = "@Hello(first second), one two";
var res = str.split(/\s(?!\w+\))/);
console.log(res);

Alternatively you can use .match() with RegExp /@\w+\(\w+\s\w+(?=\))\)|\w+(?=\s|$)/g to match "@" followed by one or more word characters followed by "(" followed by word characters followed by space character followed by word characters followed by closing parenthsis ")" or word characters followed by space or end of string

var str = "@Hello(first second), one two";
var res = str.match(/@\w+\(\w+\s\w+(?=\))\)|\w+(?=\s|$)/g);
console.log(res);


来源: stackexchange

问:
Optional error while converting from Swift 2 to 3 in keyboardWillShow notification
I am converting my app to Swift 3 at the moment and I have problems with this function I used to show the keyboard before.

Initializer for conditional binding must have Optional type, not 'CGFloat'

The error appears in the third line.

It's been a while since I've programmed the last time and so I am not sure how to solve this.

```<code>func keyboardWillShow(_ sender: Notification) {
        if let userInfo = sender.userInfo {
            if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {
                let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
                let edgeInsets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
                UIView.animate(withDuration: duration!, animations: { () -> Void in
                    self.tableView.contentInset = edgeInsets
                    self.tableView.scrollIndicatorInsets = edgeInsets
                    self.view.layoutIfNeeded()
                })
            }
        }
    }
</code>```

答:
This is one of those rare situations where I recommend force-unwrapping. You know the userInfo contains this information, and you are hosed if it doesn't. Moreover, there is no need to pass through AnyObject or to call cgRectValue; you can cast all the way down to a CGRect in a single move. So I would write:

```<code>    let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect).size.height
</code>```

(Note that there is no if, because we are not doing a conditional binding; we simply cast, kaboom.)

[Note too that there is no need now to fetch the duration or to call animate or layoutIfNeeded; you can throw all of that away. We are already in an animation, and your changes to the contentInset and scrollIndicatorInsets will be animated in time to the keyboard.]

ContentLicense: CC BY-SA 3.0

Body:
I am converting my app to Swift 3 at the moment and I have problems with this function I used to show the keyboard before.

Initializer for conditional binding must have Optional type, not 'CGFloat'

The error appears in the third line.

It's been a while since I've programmed the last time and so I am not sure how to solve this.

func keyboardWillShow(_ sender: Notification) {
        if let userInfo = sender.userInfo {
            if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {
                let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
                let edgeInsets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
                UIView.animate(withDuration: duration!, animations: { () -> Void in
                    self.tableView.contentInset = edgeInsets
                    self.tableView.scrollIndicatorInsets = edgeInsets
                    self.view.layoutIfNeeded()
                })
            }
        }
    }

Body:
This is one of those rare situations where I recommend force-unwrapping. You know the userInfo contains this information, and you are hosed if it doesn't. Moreover, there is no need to pass through AnyObject or to call cgRectValue; you can cast all the way down to a CGRect in a single move. So I would write:

    let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect).size.height

(Note that there is no if, because we are not doing a conditional binding; we simply cast, kaboom.)

[Note too that there is no need now to fetch the duration or to call animate or layoutIfNeeded; you can throw all of that away. We are already in an animation, and your changes to the contentInset and scrollIndicatorInsets will be animated in time to the keyboard.]


问:
I wrote a script which makes a new dataframe based on a condition, how can I make it more efficient ?
Here's my code

```<code>df = *some df
coin = *some string
color = 'red'

events = pd.DataFrame()
events['date'] = df.date
events['event'] = np.NaN

data_list = []
for i in range(len(df)):
    if df.iloc[i].color == color:
        data_list.append(1)
    else:
        data_list.append(np.NaN)

events['event'] = l
</code>```

from the original data frame if the color == 'red' the corresponding date in the new dataframe (events) should be 1 otherwise NaN.

I know you can probably do it in one line but I'm not sure how

bonus question after performing this I reset the index to the date column, something I cant do before because iloc doesn't work with range i-> len(df)

```<code>events = pd.DataFrame()
events[coin] = data_list
events = events.set_index(events['date'].values)

data = pd.DataFrame()
data[coin] = df.close
data = data.set_index(events['date'].values)
data = {'close':data}
</code>```

答:
You need numpy.where:

```<code>df['event'] = np.where(df.color == 'red', 1, np.nan)
</code>```

Sample:

```<code>df = pd.DataFrame({'color' : ['red', 'blue'],
                    'd'  : ['a', 'b']})

print (df)
  color  d
0   red  a
1  blue  b

df['event'] = np.where(df.color == 'red', 1, np.nan)
print (df)
  color  d  event
0   red  a    1.0
1  blue  b    NaN
</code>```

Another solution:

```<code>df.loc[df.color == 'red', 'event'] = 1
print (df)
  color  d  event
0   red  a    1.0
1  blue  b    NaN
</code>```

Performance is similar:

```<code>df = pd.DataFrame({'color' : ['red', 'blue'],
                    'd'  : ['a', 'b']})
df = pd.concat([df]*100000).reset_index(drop=True)
print (df)

In [31]: %timeit df['event1'] = np.where(df.color == 'red', 1, np.nan)
10 loops, best of 3: 23.6 ms per loop

In [32]: %timeit df.loc[df.color == 'red', 'event'] = 1
10 loops, best of 3: 25.4 ms per loop
</code>```

Body:
Here's my code

df = *some df
coin = *some string
color = 'red'

events = pd.DataFrame()
events['date'] = df.date
events['event'] = np.NaN

data_list = []
for i in range(len(df)):
    if df.iloc[i].color == color:
        data_list.append(1)
    else:
        data_list.append(np.NaN)

events['event'] = l

from the original data frame if the color == 'red' the corresponding date in the new dataframe (events) should be 1 otherwise NaN.

I know you can probably do it in one line but I'm not sure how

bonus question after performing this I reset the index to the date column, something I cant do before because iloc doesn't work with range i-> len(df)

events = pd.DataFrame()
events[coin] = data_list
events = events.set_index(events['date'].values)

data = pd.DataFrame()
data[coin] = df.close
data = data.set_index(events['date'].values)
data = {'close':data}

Body:
You need numpy.where:

df['event'] = np.where(df.color == 'red', 1, np.nan)

Sample:

df = pd.DataFrame({'color' : ['red', 'blue'],
                    'd'  : ['a', 'b']})

print (df)
  color  d
0   red  a
1  blue  b

df['event'] = np.where(df.color == 'red', 1, np.nan)
print (df)
  color  d  event
0   red  a    1.0
1  blue  b    NaN

Another solution:

df.loc[df.color == 'red', 'event'] = 1
print (df)
  color  d  event
0   red  a    1.0
1  blue  b    NaN

Performance is similar:

df = pd.DataFrame({'color' : ['red', 'blue'],
                    'd'  : ['a', 'b']})
df = pd.concat([df]*100000).reset_index(drop=True)
print (df)

In [31]: %timeit df['event1'] = np.where(df.color == 'red', 1, np.nan)
10 loops, best of 3: 23.6 ms per loop

In [32]: %timeit df.loc[df.color == 'red', 'event'] = 1
10 loops, best of 3: 25.4 ms per loop


问:
What tool can I use to build a nicely-formatted SQL DB diagram on a Mac?
I need to create an entity relationship diagram for a MySQL database. It doesn't need to be automatically generated or anything, and I don't have foreign keys defined anyway.

I could swear that I once used a tool that would display the relationships between fields, but this old screenshot from MS Access is the closest I've been able to find to what I'm trying to do (source: http://acdrupal.evergreen.edu/files/studycenter/database_entity_relationship_diagram.jpg).

Can anyone name an app (preferably for Macs) that can be used to build this kind of diagram? I've tried several of the popular ones - ArgoUML, OmniGraffle, MySQL Workbench - but it doesn't seem that any of them will show those relationship lines from one specific field to another. Instead, they have a generic one-to-one or many-to-one line that goes to the table, but not the specific field.

答: i like Visio for these drawings.</p>

ContentLicense: CC BY-SA 2.5

Body: i like Visio for these drawings.


问:
Cucumber tests - browser detects bot user agent
I need to test some behavior on cucumber with both "bot" and "user" user-agent.

In some controllers, I have a bot guard clause

```<code>if browser.bot?
  redirect_to(canonical_path, status: :moved_permanently)
else
  do_some_tracking
  redirect_somewhere
end
</code>```

I have a cucumber test with features that can vary according to whether a bot or a user visits the page

```<code>Feature: Visit the special page

  Scenario: A bot visits the special page
    When I visit the special page
    I should see the home page

  Scenario: A user visits the special page not signed in
    Given I am not logged-in
    When I visit the special page
    I should see "Who are you ?"

  Scenario: A user visits the special page signed in
    Given I am logged-in as "michael"
    When I visit the special page
    I should see "Achievement earned : explorer"
</code>```

Is there a way to modify the user agent on a per-scenario basis ?

I though of using tags and Before/After blocks in env.rb But I'm not sure how to actually change the user-agent string of the current driver (and revert it back to normal afterwards)

Otherwise the default Poltergeist driver's user-agent is "PhantomJS" which is always recognized as a bot for the browser gem

答:
Assuming you're using Poltergeist (since it's mentioned in your question) You can override the user-agent for the current test by setting the 'User-Agent' header in a tag based Before block (it will automatically get reset at the next test).

```<code>page.driver.add_header("User-Agent", "whatever you want")
</code>```

This is documented in the Poltergeist README - https://github.com/teampoltergeist/poltergeist#manipulating-request-headers

If you're not using Poltergeist the other drivers also have ways of setting headers, and there is a capybara-user_agent gem that provides a uniform API for setting the user-agent.  The gem hasn't been updated in a while though so I don't know whether it still works or not.

Body:
I need to test some behavior on cucumber with both "bot" and "user" user-agent.

In some controllers, I have a bot guard clause

if browser.bot?
  redirect_to(canonical_path, status: :moved_permanently)
else
  do_some_tracking
  redirect_somewhere
end

I have a cucumber test with features that can vary according to whether a bot or a user visits the page

Feature: Visit the special page

  Scenario: A bot visits the special page
    When I visit the special page
    I should see the home page

  Scenario: A user visits the special page not signed in
    Given I am not logged-in
    When I visit the special page
    I should see "Who are you ?"

  Scenario: A user visits the special page signed in
    Given I am logged-in as "michael"
    When I visit the special page
    I should see "Achievement earned : explorer"

Is there a way to modify the user agent on a per-scenario basis ?

I though of using tags and Before/After blocks in env.rb But I'm not sure how to actually change the user-agent string of the current driver (and revert it back to normal afterwards)

Otherwise the default Poltergeist driver's user-agent is "PhantomJS" which is always recognized as a bot for the browser gem

Body:
Assuming you're using Poltergeist (since it's mentioned in your question) You can override the user-agent for the current test by setting the 'User-Agent' header in a tag based Before block (it will automatically get reset at the next test).

page.driver.add_header("User-Agent", "whatever you want")

This is documented in the Poltergeist README - https://github.com/teampoltergeist/poltergeist#manipulating-request-headers

If you're not using Poltergeist the other drivers also have ways of setting headers, and there is a capybara-user_agent gem that provides a uniform API for setting the user-agent.  The gem hasn't been updated in a while though so I don't know whether it still works or not.


问:
valgrind finds errors passing pointer to function, but no errors when the code is in the same scope
I am wondering why, in this example code, valgrind finds no errors or lost memory:

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(8);
   strcpy(str, "example");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);

   return(0);
}
</code>```

However, when I replace these lines with a function:

```<code>int main() {
   ...
   /* Reallocating memory */
   newstr(str);
   ...
}

void newstr(char *str) {
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
}
</code>```

I am getting 19 errors on valgrind, complaining mostly about invalid reads. However, the program executes and outputs everything the same, without an error. Is there something going on when I pass str into the function that happens in memory that valgrind is notifying me of? What can I do to fix this? How can I learn more about this behavior and what the implications are?

This is the output of the program in either case:

```<code>String = example,  Address = 16445456
String = example.com,  Address = 16445456
</code>```

答:
valgrind complain to the read correctly, you read from the invalid memory. You read from invalid value of str.
Correct code below.

```<code>int main() {
   ...
   /* Reallocating memory */
   str = newstr(str);
   ...
}

char * newstr(char *str) {
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   return str;
}
</code>```

Body:
I am wondering why, in this example code, valgrind finds no errors or lost memory:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(8);
   strcpy(str, "example");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);

   return(0);
}

However, when I replace these lines with a function:

int main() {
   ...
   /* Reallocating memory */
   newstr(str);
   ...
}

void newstr(char *str) {
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
}

I am getting 19 errors on valgrind, complaining mostly about invalid reads. However, the program executes and outputs everything the same, without an error. Is there something going on when I pass str into the function that happens in memory that valgrind is notifying me of? What can I do to fix this? How can I learn more about this behavior and what the implications are?

This is the output of the program in either case:

String = example,  Address = 16445456
String = example.com,  Address = 16445456

Body:
valgrind complain to the read correctly, you read from the invalid memory. You read from invalid value of str.
Correct code below.

int main() {
   ...
   /* Reallocating memory */
   str = newstr(str);
   ...
}

char * newstr(char *str) {
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   return str;
}


问:
Putting a dict into a dataframe - python
I have a list called 'gender', of which I counted all the occurrences of the values with Counter:

```<code>gender = ['2',
          'Female,',
          'All Female Group,',
          'All Male Group,',
          'Female,',
          'Couple,',
          'Mixed Group,'....]

gender_count = Counter(gender)
gender_count
Counter({'2': 1,
     'All Female Group,': 222,
     'All Male Group,': 119,
     'Couple,': 256,
     'Female,': 1738,
     'Male,': 2077,
     'Mixed Group,': 212,
     'NA': 16})
</code>```

I want to put this dict into a pandas Dataframe. I have used pd.series(Convert Python dict into a dataframe):

```<code>s = pd.Series(gender_count, name='gender count')
s.index.name = 'gender'
s.reset_index()
</code>```

Which gives me the dataframe I want, but I don't know how to save these steps into a pandas DataFrame.
I also tried using DataFrame.from_dict()

```<code>s2 = pd.DataFrame.from_dict(gender_count, orient='index')
</code>```

But this creates a dataframe with the categories of gender as the index.

I eventually want to use gender categories and the count for a piechart.

答:
```<code>In [21]: df = pd.Series(gender_count).rename_axis('gender').reset_index(name='count')

In [22]: df
Out[22]:
              gender  count
0                  2      1
1  All Female Group,    222
2    All Male Group,    119
3            Couple,    256
4            Female,   1738
5              Male,   2077
6       Mixed Group,    212
7                 NA     16
</code>```

Body:
I have a list called 'gender', of which I counted all the occurrences of the values with Counter:

gender = ['2',
          'Female,',
          'All Female Group,',
          'All Male Group,',
          'Female,',
          'Couple,',
          'Mixed Group,'....]

gender_count = Counter(gender)
gender_count
Counter({'2': 1,
     'All Female Group,': 222,
     'All Male Group,': 119,
     'Couple,': 256,
     'Female,': 1738,
     'Male,': 2077,
     'Mixed Group,': 212,
     'NA': 16})

I want to put this dict into a pandas Dataframe. I have used pd.series(Convert Python dict into a dataframe):

s = pd.Series(gender_count, name='gender count')
s.index.name = 'gender'
s.reset_index()

Which gives me the dataframe I want, but I don't know how to save these steps into a pandas DataFrame.
I also tried using DataFrame.from_dict()

s2 = pd.DataFrame.from_dict(gender_count, orient='index')

But this creates a dataframe with the categories of gender as the index.

I eventually want to use gender categories and the count for a piechart.


问:
using aggregate to generate report based on multiple categories in r
I have a .dbf containing roughly 2.8 million records that contain residential parcel data with a year built category field, a county code field, and a windzone field (for building code restrictions). There are 3  year built categories and 5 wind zones. I need to get the number of parcels for each year built category in each windzone for each county. Basically I have a county (CNTY_ID = 11) with three year built categories (BUILT_CAT = "1" , "2" , "3") each that are also assigned to one of five windspeed categories (WINDSPEED = "100", "110", "120", etc.). I think I need to use the aggregate() function but haven't had any luck. Optimally the generated table would look something like:

```<code>CNTY_ID = 11
                  BUILT_CAT
             1        2        3
WINDSPEED
   100       x        x        x
   120       x        x        x
    .
    .
    .
   150       x        x        x

CNTY_ID = 12
                  BUILT_CAT
             1        2        3
WINDSPEED
   100       x        x        x
   120       x        x        x
    .
    .
    .
   150       x        x        x
</code>```

Is this kind of task possible to accomplish?

答:
Actually, you're better of using table, that's less hassle and more performant. You get an array back, and this one is easily converted to a data frame.

Some test data:

```<code>n <- 10000
df <- data.frame(
  windspeed = sample(c(110,120,130), n, TRUE),
  built_cat = sample(c(1,2,3),n,TRUE),
  cnty_id = sample(1:20,n,TRUE)
)
</code>```

Constructing the table and converting to a data frame:

```<code>tbl <- with(df, table(windspeed, built_cat, cnty_id))
as.data.frame(tbl)
</code>```

Note that I use with here so I have the variable names automatically as the dimnames of my table. That helps with the conversion.

Body:
I have a .dbf containing roughly 2.8 million records that contain residential parcel data with a year built category field, a county code field, and a windzone field (for building code restrictions). There are 3  year built categories and 5 wind zones. I need to get the number of parcels for each year built category in each windzone for each county. Basically I have a county (CNTY_ID = 11) with three year built categories (BUILT_CAT = "1" , "2" , "3") each that are also assigned to one of five windspeed categories (WINDSPEED = "100", "110", "120", etc.). I think I need to use the aggregate() function but haven't had any luck. Optimally the generated table would look something like:

CNTY_ID = 11
                  BUILT_CAT
             1        2        3
WINDSPEED
   100       x        x        x
   120       x        x        x
    .
    .
    .
   150       x        x        x

CNTY_ID = 12
                  BUILT_CAT
             1        2        3
WINDSPEED
   100       x        x        x
   120       x        x        x
    .
    .
    .
   150       x        x        x

Is this kind of task possible to accomplish?

Body:
Actually, you're better of using table, that's less hassle and more performant. You get an array back, and this one is easily converted to a data frame.

Some test data:

n <- 10000
df <- data.frame(
  windspeed = sample(c(110,120,130), n, TRUE),
  built_cat = sample(c(1,2,3),n,TRUE),
  cnty_id = sample(1:20,n,TRUE)
)

Constructing the table and converting to a data frame:

tbl <- with(df, table(windspeed, built_cat, cnty_id))
as.data.frame(tbl)

Note that I use with here so I have the variable names automatically as the dimnames of my table. That helps with the conversion.


问:
Change XMLGregorianCalendar to Date using external binding file (XJB)
In my maven project, I want all my datetime entries should be generated as java.util.date instead of XMLGregorianCalendar. As you might know XMLGregorianCalendar gets generated by default.

We can take example project provided here.

Here in the CustomersOrders.xsd, you can see attriute ShippedDate is of type dateTime.

```<code><xs:attribute name='ShippedDate' type='xs:dateTime' />
</code>```

To convert its data type into java.util.date, I'm following approach provided in documentation here. i.e. by using external binding file, like:

Customer.xjb

```<code><bindings xmlns="http://java.sun.com/xml/ns/jaxb" version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <globalBindings>
    <javaType name="java.util.date" xmlType="xs:datetime"
      parseMethod="javax.xml.bind.DatatypeConverter.parseDate"
      printMethod="javax.xml.bind.DatatypeConverter.printDate"
    />
  </globalBindings>
</bindings>
</code>```

Then I mapped Customer.xjb file in pom.xml like:

```<code><executions>
    <execution>
        <goals>
            <goal>generate</goal>
        </goals>
        <configuration>
            <!-- the package for the generated java classes -->
            <generatePackage>com.dimitrisli.jaxb.producedClasses</generatePackage>
            <!-- If the following not specified all xsd in resources are included -->
            <schemaIncludes>
                <include>sampleJaxb/CustomersOrders.xsd</include>
            </schemaIncludes>
            <!-- if you don't want old output -->
            <removeOldOutput>true</removeOldOutput>
            <!-- if you want verbosity -->
            <!-- verbose>true</verbose -->

            <xjbSources>
                <xjbSource>sampleJaxb/Customers.xjb</xjbSource>
            </xjbSources>

        </configuration>

    </execution>
</executions>
</code>```

But when I do mvn clean install, I'm still not able to see any difference in ShippedDate, which is still being generated as XMLGregorianCalendar.

Please suggest what am I missing.

Thank You

答:
If you use the org.jvnet.jaxb2.maven2:maven-jaxb2-plugin then you should use bindingIncludes instead of xjbSources (it's for org.codehaus.mojo:jaxb2-maven-plugin).

```<code><bindingIncludes>
    <include>sampleJaxb/Customers.xjb</include>
</bindingIncludes>`
</code>```

Also, you have to implement a custom adapter for java.util.Date like you have seen in the tutorial or convert to java.util.Calendar:

```<code><javaType name="java.util.Calendar" xmlType="xsd:dateTime"
parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />`
</code>```

Hope it helps!

Body:
In my maven project, I want all my datetime entries should be generated as java.util.date instead of XMLGregorianCalendar. As you might know XMLGregorianCalendar gets generated by default.

We can take example project provided here.

Here in the CustomersOrders.xsd, you can see attriute ShippedDate is of type dateTime.

<xs:attribute name='ShippedDate' type='xs:dateTime' />

To convert its data type into java.util.date, I'm following approach provided in documentation here. i.e. by using external binding file, like:

Customer.xjb

<bindings xmlns="http://java.sun.com/xml/ns/jaxb" version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <globalBindings>
    <javaType name="java.util.date" xmlType="xs:datetime"
      parseMethod="javax.xml.bind.DatatypeConverter.parseDate"
      printMethod="javax.xml.bind.DatatypeConverter.printDate"
    />
  </globalBindings>
</bindings>

Then I mapped Customer.xjb file in pom.xml like:

<executions>
    <execution>
        <goals>
            <goal>generate</goal>
        </goals>
        <configuration>

            <generatePackage>com.dimitrisli.jaxb.producedClasses</generatePackage>

            <schemaIncludes>
                <include>sampleJaxb/CustomersOrders.xsd</include>
            </schemaIncludes>

            <removeOldOutput>true</removeOldOutput>

            <xjbSources>
                <xjbSource>sampleJaxb/Customers.xjb</xjbSource>
            </xjbSources>

        </configuration>

    </execution>
</executions>

But when I do mvn clean install, I'm still not able to see any difference in ShippedDate, which is still being generated as XMLGregorianCalendar.

Please suggest what am I missing.

Thank You

Body:
If you use the org.jvnet.jaxb2.maven2:maven-jaxb2-plugin then you should use bindingIncludes instead of xjbSources (it's for org.codehaus.mojo:jaxb2-maven-plugin).

<bindingIncludes>
    <include>sampleJaxb/Customers.xjb</include>
</bindingIncludes>`

Also, you have to implement a custom adapter for java.util.Date like you have seen in the tutorial or convert to java.util.Calendar:

<javaType name="java.util.Calendar" xmlType="xsd:dateTime"
parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />`

Hope it helps!


问:
Update variable when scrapy crawler is done
I would like to keep track of how many crawlers are done when im running multiple crawlers within a loop. What I've tried is to use signals but it seems like my crawlers cannot find other modules outside its scope. What I would like to do is to register that the crawling is done inside another script e.g. by passing/updating a variable.

Example code (shortened version - explaining problem):

Controller.py

```<code>isWikipediaDone = False
for file in Spiders:
    process.crawl(file)

print(isWikipediaDone)
</code>```

wikipediaSpider.py

```<code>class WikipediaSpider(scrapy.Spider):
 .... initialize ....

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        spider = super(wikipediaSpider, cls).from_crawler(crawler, *args, **kwargs)
        crawler.signals.connect(spider.spider_closed, signal=signals.spider_closed)
        return spider

    def spider_closed(self, spider):
        print("Now we are done updating variable in Controller.py!")
        Controller.isWikipediaDone = True
</code>```

答:
You can create a controller class and later import it in your spider:

```<code># controller.py
class Controller:
    def mark_as_done(self, spider):
        print("{} is done!".format(spider.name))
controller = Controller()
</code>```

And connect controller method to your signal inside of your spider:

```<code># myspider.py
from mypackage.controller import controller
...
crawler.signals.connect(controller.mark_as_done, signals.spider_closed)
</code>```

Body:
I would like to keep track of how many crawlers are done when im running multiple crawlers within a loop. What I've tried is to use signals but it seems like my crawlers cannot find other modules outside its scope. What I would like to do is to register that the crawling is done inside another script e.g. by passing/updating a variable.

Example code (shortened version - explaining problem):

Controller.py

isWikipediaDone = False
for file in Spiders:
    process.crawl(file)

print(isWikipediaDone)

wikipediaSpider.py

class WikipediaSpider(scrapy.Spider):
 .... initialize ....

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        spider = super(wikipediaSpider, cls).from_crawler(crawler, *args, **kwargs)
        crawler.signals.connect(spider.spider_closed, signal=signals.spider_closed)
        return spider

    def spider_closed(self, spider):
        print("Now we are done updating variable in Controller.py!")
        Controller.isWikipediaDone = True

Body:
You can create a controller class and later import it in your spider:

# controller.py
class Controller:
    def mark_as_done(self, spider):
        print("{} is done!".format(spider.name))
controller = Controller()

And connect controller method to your signal inside of your spider:

# myspider.py
from mypackage.controller import controller
...
crawler.signals.connect(controller.mark_as_done, signals.spider_closed)


问:
processing this string with php
I have a text string that looks like this

```<code>var1=red&var2=green&var3=blue&var4=magenta
</code>```

How can manipulate this string isolate the value of var2 which in this case is green

答:
```<code>parse_str($str, $vars);
echo $vars['var2'];
</code>```

Title: processing this string with php

Body:
I have a text string that looks like this

var1=red&var2=green&var3=blue&var4=magenta

How can manipulate this string isolate the value of var2 which in this case is green


问:
Can I not catch a specific or custom exception?
I dont want to catch some exception. Can I do it somehow?

Can I say something like this:

```<code>catch (Exception e BUT not CustomExceptionA)
{
}
</code>```

?

答:
Starting with C# 6, you can use an exception filter:</p>

```<code>try
{
    // Do work
}
catch (Exception e) when (!(e is CustomExceptionA))
{
    // Catch anything but CustomExceptionA
}
</code>```

Body:
I dont want to catch some exception. Can I do it somehow?

Can I say something like this:

catch (Exception e BUT not CustomExceptionA)
{
}

?

Body:
Starting with C# 6, you can use an exception filter:

try
{
    // Do work
}
catch (Exception e) when (!(e is CustomExceptionA))
{
    // Catch anything but CustomExceptionA
}


问:
Executing data validation rules from a table using a procedure with runtime values
I have a table that is filled with many data validation queries. For example a row:

```<code>SELECT end_time - start_time
FROM mt_process_status
WHERE process_id = <PROCESS_ID> AND ref_date = <REF_DATE>
</code>```

I have to execute all these SQL statements filling the values within '<>' with run time values and check if the performance of the process has not changed.

Can this be done with a stored procedure? I want to understand what the solution would look like.  Any links to documentation of this sort of thing, anything to guide me in the right direction.

答:
Somewhere there's a bunch of analysts in your organization telling each other, "We've done the difficult stuff, we've defined the queries. All the database has to do is execute them, how hard can that be?" Answer: very hard.

Let's take the query you posted:

```<code>select end_time - start_time  from mt_process_status where process_id = <PROCESS_ID> AND ref_date = <REF_DATE>
</code>```

It's easy enough to use replace(the_str, '<PROCESS_ID>', 1234) to substitute a value. But for ref_date that's presumably a date, so it needs to be replace(the_str, '<REF_DATE>', 'date ''2017-01-01'''). Starting to get icky, and that's just handling literals. It will be even ickier when the substitution values are passed as parameters.

Of course I've made an assumption that PROCESS_ID is numeric. Maybe it isn't. Who can tell? Is there a data dictionary where these details are defined?

It would be easier if the query was defined with dynamic SQL placeholders:

```<code>select end_time - start_time  from mt_process_status where process_id = :PROCESS_ID AND ref_date = :REF_DATE
</code>```

Then you could forget about the replace and simply run

```<code> execute immediate the_str
     using 1234, date '2017-01-01'
     into whatever;
</code>```

But you still need to know how many placeholders there are, in what order they occur and what datatype they are. It may feel like this is soft-coded and configurable but there is still a really hard dependency between the query and the program which calls it.

Plus you have lost the ability to do impact analysis. What queries will be affected when you change mt_process_status? Who can tell?

Body:
I have a table that is filled with many data validation queries. For example a row:

SELECT end_time - start_time
FROM mt_process_status
WHERE process_id = <PROCESS_ID> AND ref_date = <REF_DATE>

I have to execute all these SQL statements filling the values within '<>' with run time values and check if the performance of the process has not changed.

Can this be done with a stored procedure? I want to understand what the solution would look like.  Any links to documentation of this sort of thing, anything to guide me in the right direction.

Body:
Somewhere there's a bunch of analysts in your organization telling each other, "We've done the difficult stuff, we've defined the queries. All the database has to do is execute them, how hard can that be?" Answer: very hard.

Let's take the query you posted:

select end_time - start_time  from mt_process_status where process_id = <PROCESS_ID> AND ref_date = <REF_DATE>

It's easy enough to use replace(the_str, '<PROCESS_ID>', 1234) to substitute a value. But for ref_date that's presumably a date, so it needs to be replace(the_str, '<REF_DATE>', 'date ''2017-01-01'''). Starting to get icky, and that's just handling literals. It will be even ickier when the substitution values are passed as parameters.

Of course I've made an assumption that PROCESS_ID is numeric. Maybe it isn't. Who can tell? Is there a data dictionary where these details are defined?

It would be easier if the query was defined with dynamic SQL placeholders:

select end_time - start_time  from mt_process_status where process_id = :PROCESS_ID AND ref_date = :REF_DATE

Then you could forget about the replace and simply run

 execute immediate the_str
     using 1234, date '2017-01-01'
     into whatever;

But you still need to know how many placeholders there are, in what order they occur and what datatype they are. It may feel like this is soft-coded and configurable but there is still a really hard dependency between the query and the program which calls it.

Plus you have lost the ability to do impact analysis. What queries will be affected when you change mt_process_status? Who can tell?


问:
Android: what happens to background process when a new version is installed from the Market Place?
I have developed an Android health app which launches a process running in the background and monitoring user activities such as steps. If the app is closed by the user, the core sensors monitor keeps running in the background.
I am about to upload a new version of the app to the marketplace. What will happen to the background service when the app is updated? Will it be killed?
Tests on the beta channel seem to indicate that the background process is somehow left in a semi-dead status (i.e. the process is there but is not working).
Shall I make sure that the background process stops when a new version is installed? If so, how?
Thanks</p>

答:
All the processes are killed. If you want them to be restarted you have to set an intent filter with android.intent.action.MY_PACKAGE_REPLACED on the background processes. For example in my Manifest file I have created a receiver that has the following:

```<code><intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</code>```

This will guarantee that this receiver (which will restart the services) will restart after reboot and after package reinstall

Body:
All the processes are killed. If you want them to be restarted you have to set an intent filter with android.intent.action.MY_PACKAGE_REPLACED on the background processes. For example in my Manifest file I have created a receiver that has the following:

<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>

This will guarantee that this receiver (which will restart the services) will restart after reboot and after package reinstall


问:
Rails routes: Can object ids be separated by non-backslash strings?
I'd like to do the following:

```<code>/products/compare/:product_a_id--vs--:product_b_id
</code>```

Is this possible?

答:
You can use the "id" however you like.

In the controller action, you can just split it based on the string

```<code>def compare
  product_a_id, product_b_id = params[:id].split('--vs--')
  ...
end
</code>```

And in routes, throw on a constraint to ensure the --vs-- is there.

```<code>:constraints => { :id => /\d+--vs--\d+/ }
</code>```

Body:
I'd like to do the following:

/products/compare/:product_a_id--vs--:product_b_id

Is this possible?

Body:
You can use the "id" however you like.

In the controller action, you can just split it based on the string

def compare
  product_a_id, product_b_id = params[:id].split('--vs--')
  ...
end

And in routes, throw on a constraint to ensure the --vs-- is there.

:constraints => { :id => /\d+--vs--\d+/ }


答:
Try this:</p>

```<code>parse_str($str,$tmp);
// $tmp['var2'] is now what you're looking for
</code>```

Title: processing this string with php

Body:
Try this:

parse_str($str,$tmp);
// $tmp['var2'] is now what you're looking for


问:
How to extract row based on list of hex interval with awk?

Input file

```<code>U+3400  qiū
U+3401  tiàn
…
U+4E00  yī
U+4E01  dīng
…
U+2B5E7 sù
U+2B5EE huáng
</code>```

List of intervals

List of unicode codepoint

```<code>4E00-9FFF
3400-4DBF
20000-2A6DF
2A700-2B73F
2B740-2B81F
2B820-2CEAF
F900-FAFF
</code>```

Question

How do I print only the row that belong to one of the hexadecimal interval?

答:
Try this -

```<code>awk -F'[+ -]' 'NR==FNR{a[$1]=$2;next} $2 in a {print $0}' f2 f1
U+3400  qiū
U+4E00  yī
</code>```

Here f2 is List of intervals.

Body:
Input file

U+3400  qiū
U+3401  tiàn
…
U+4E00  yī
U+4E01  dīng
…
U+2B5E7 sù
U+2B5EE huáng

List of intervals

List of unicode codepoint

4E00-9FFF
3400-4DBF
20000-2A6DF
2A700-2B73F
2B740-2B81F
2B820-2CEAF
F900-FAFF

Question

How do I print only the row that belong to one of the hexadecimal interval?

Body:
Try this -

awk -F'[+ -]' 'NR==FNR{a[$1]=$2;next} $2 in a {print $0}' f2 f1
U+3400  qiū
U+4E00  yī

Here f2 is List of intervals.


问:
Python - Method that calls itself
I am trying to learn Python. I just made a simple rock, paper, scissors game for practice. I am having a small problem.

When each player choose the same item, the game ends in a tie.

When the player makes a mistake and has to choose again, the variable is empty. Notice that Player 1 says "none".

This is the method. The problem occurs in the else branch.

```<code>def play1():
    player1_choice = input("Player 1 - Go: ")
    if (check(player1_choice)):
        return player1_choice
    else:
        print(error_msg)
        play1() # Something is wrong here.
</code>```

What did I do wrong? How can I fix it? Thanks

答:
This is a classic while loop application; you want to loop until you get a reasonable answer (while the known answer is unacceptable), returning that answer to the calling program.

Use a for loop when you know as you enter the loop how many times you have to repeat it.

Recursion is proper when you have a job in which you can:

do something simple;

reduce the remaining task to something smaller, closer to a trivial "completed" state;

pass that smaller task to the same function for further processing.

In this application, getting a wrong answer from the user doesn't put you any closer to a solution (a valid answer) than when you started.  The task isn't any simpler now.  Further processing is the same, but you get that just as well with an iteration loop.

Title: Python - Method that calls itself

Body:
I am trying to learn Python. I just made a simple rock, paper, scissors game for practice. I am having a small problem.

When each player choose the same item, the game ends in a tie.

When the player makes a mistake and has to choose again, the variable is empty. Notice that Player 1 says "none".

This is the method. The problem occurs in the else branch.

def play1():
    player1_choice = input("Player 1 - Go: ")
    if (check(player1_choice)):
        return player1_choice
    else:
        print(error_msg)
        play1() # Something is wrong here.

What did I do wrong? How can I fix it? Thanks


问:
Swift Custom Data Push Notification
I am attempting to retrieve the custom data sent in a push notification.

The custom data is :

[{"test":"01"}]

The pushNotification is recieved as:

[AnyHashable("aps"): { alert = "Hello World!"; sound = default;}, AnyHashable("u"): [{"test":"01"}] , AnyHashable("p"):2Q]

And my push accepted is as follows:

 func onPushAccepted(_ pushManager: PushNotificationManager!, withNotification pushNotification: [AnyHashable : Any]!, onStart: Bool) {
        print("Push notification accepted: \(pushNotification!)")

        if let aps = pushNotification["aps"] as? [String:Any] {
            let customData = aps["u"] as! String

            print("json String:\(customData)")
        }
```

When I run the code it crashes on line:

let customData = aps["u"] as! String

Any help much appreciated!

答:
First of all excuse me if I am not correct but you are picking the wrong key.

```<code>if let aps = pushNotification["aps"] as? [String:Any]
</code>```

should be

```<code>if let data = pushNotification["u"] as? [String:Any]
</code>```

and then you can get the value for test like this

```<code>data["test"]
</code>```

hope I am correct and this will help you

Title: Swift Custom Data Push Notification

Body:
I am attempting to retrieve the custom data sent in a push notification.

The custom data is :

[{"test":"01"}]

The pushNotification is recieved as:

[AnyHashable("aps"): { alert = "Hello World!"; sound = default;}, AnyHashable("u"): [{"test":"01"}] , AnyHashable("p"):2Q]

And my push accepted is as follows:

 func onPushAccepted(_ pushManager: PushNotificationManager!, withNotification pushNotification: [AnyHashable : Any]!, onStart: Bool) {
        print("Push notification accepted: \(pushNotification!)")

        if let aps = pushNotification["aps"] as? [String:Any] {
            let customData = aps["u"] as! String

            print("json String:\(customData)")
        }

When I run the code it crashes on line:

let customData = aps["u"] as! String

Any help much appreciated!

Body:
First of all excuse me if I am not correct but you are picking the wrong key.

if let aps = pushNotification["aps"] as? [String:Any]

should be

if let data = pushNotification["u"] as? [String:Any]

and then you can get the value for test like this

data["test"]

hope I am correct and this will help you


问:
How do I get the weighted sum of multiple losses & accuracy (caffe)
I have trained a network on two different modals of the same image. I pass the data together in one layer but after that, it is pretty much two networks in parallel, they don't share a layer and the two tasks have different set of labels, therefore I have two different loss and accuracy layers.

I have read that caffe averages multiple losses and accuracy (following this question How can I have multiple losses in a network in Caffe?), is it the case only when at least a layer is shared? I intended to create an ensemble, however now it seems like I simply have two different networks. I intended to average the losses & accuracy so that both network branches would contribute to one accuracy. On training I see two separate losses & accuracy. How do I get this average loss & accuracy while testing on a new image pair?

By forwarding the network, is it possible to get two predictions at all? If so, how?

答:
Multiple Losses can be used with one network using the caffe-parameter loss_weight. For example, you can have the following for one of your loss layers with weight 0.5 .

```<code>...
layer{
  name: "loss_a"
  type: "SigmoidCrossEntropyLoss"
  bottom: "fc8_a"
  bottom: "attributes_a"
  top : "loss_a"
  loss_weight : 0.5
 }

 layer{
  name: "loss_b"
  type: "SigmoidCrossEntropyLoss"
  bottom: "fc8_b"
  bottom: "attributes_b"
  top : "loss_b"
}
</code>```

Body:
Multiple Losses can be used with one network using the caffe-parameter loss_weight. For example, you can have the following for one of your loss layers with weight 0.5 .

...
layer{
  name: "loss_a"
  type: "SigmoidCrossEntropyLoss"
  bottom: "fc8_a"
  bottom: "attributes_a"
  top : "loss_a"
  loss_weight : 0.5
 }

 layer{
  name: "loss_b"
  type: "SigmoidCrossEntropyLoss"
  bottom: "fc8_b"
  bottom: "attributes_b"
  top : "loss_b"
}


问:
Assigning Values based on row value
I have a large vector (column of a data frame) where values containing integers 1 to 30. I want to replace numbers from 1 to 5 with 1, 6 to 10 with 5, 11 to 15 with 9...

```<code>> x3 <- sample(1:30, 100, rep=TRUE)
> x3
  [1] 13 24 16 30 10  6 15 10  3 17 18 22 11 13 29  7 25 28 17 27  1  5  6 20 15 15  8 10 13 26 27 24  3 24  5  7 10  6 28 27  1  4 22 25 14 13  2 10  4 29 23 24 30 24 29 11  2 28 23  1  1  2
 [63]  3 23 13 26 21 22 11  4  8 26 17 11 20 23  6 14 24  5 15 21 11 13  6 14 20 11 22  9  6 29  4 30 20 30  4 24 23 29
</code>```

As I mentioned this is a column in a data frame and with above assignment I want to create a different column. If I do the following I have to do this 30 times.

```<code>myFrame$NewColumn[myFrame$oldColumn==1] <- 1
myFrame$NewColumn[myFrame$oldColumn==2] <- 1
myFrame$NewColumn[myFrame$oldColumn==3] <- 1
...
</code>```

Whats a better way to do this?

答:
Did you try:

```<code>myFrame$NewColumn[myFrame$oldColumn > 0 & myFrame$oldColumn< 6] <- 1
myFrame$NewColumn[myFrame$oldColumn > 5 & myFrame$oldColumn< 11] <- 1
...
</code>```

Or even better:

```<code>myFrame$NewColumn <- as.integer((myFrame$oldColumn - 1)/5)) * 4 + 1
</code>```

Title: Assigning Values based on row value

Body:
I have a large vector (column of a data frame) where values containing integers 1 to 30. I want to replace numbers from 1 to 5 with 1, 6 to 10 with 5, 11 to 15 with 9...

> x3 <- sample(1:30, 100, rep=TRUE)
> x3
  [1] 13 24 16 30 10  6 15 10  3 17 18 22 11 13 29  7 25 28 17 27  1  5  6 20 15 15  8 10 13 26 27 24  3 24  5  7 10  6 28 27  1  4 22 25 14 13  2 10  4 29 23 24 30 24 29 11  2 28 23  1  1  2
 [63]  3 23 13 26 21 22 11  4  8 26 17 11 20 23  6 14 24  5 15 21 11 13  6 14 20 11 22  9  6 29  4 30 20 30  4 24 23 29

As I mentioned this is a column in a data frame and with above assignment I want to create a different column. If I do the following I have to do this 30 times.

myFrame$NewColumn[myFrame$oldColumn==1] <- 1
myFrame$NewColumn[myFrame$oldColumn==2] <- 1
myFrame$NewColumn[myFrame$oldColumn==3] <- 1
...

Whats a better way to do this?

Body:
Did you try:

myFrame$NewColumn[myFrame$oldColumn > 0 & myFrame$oldColumn< 6] <- 1
myFrame$NewColumn[myFrame$oldColumn > 5 & myFrame$oldColumn< 11] <- 1
...

Or even better:

myFrame$NewColumn <- as.integer((myFrame$oldColumn - 1)/5)) * 4 + 1


问:
Selecting rows which are not linked to another table
I have a table called 'messages', which contains the columns sender_id, recipient_id, message (the text of the message) and readbyrecipient (a flag to indicate whether the message was read by the person to whom it was sent.

I am implementing the option to block users, so have added a table called block with columns blocker_id (the user who did the blocking) and blockee_id (the user who was blocked). All of the *_id columns link to my users table.

I am trying to get all unread messages which are not sent from users which were blocked by the recipient. Here's the query I have been working with:

```<code>SELECT
    A.*
FROM
    messages A,
    block B
WHERE
    A.recipient_id = 18
    AND A.readbyrecipient = 0
    AND NOT (
                B.blocker_id = A.recipient_id
                AND
                B.blockee_id = A.sender_id
            )
</code>```

This returns no rows, even though I know the user id specified in A.recipient_id refers to a user who has one unread message from a user whom they have not blocked. I tried removing the AND NOT clause in the query, but it still returned zero rows until I removed block B from the SELECT part of the query, so I'm not sure whether the problem is with the WHERE clause or the SELECT clause.

Thanks in advance!

答:
You need one of these:

1) LEFT JOIN. Please don't use the old crummy JOIN syntax you use, as it does not allow LEFT JOINs and is much harder to read.

```<code>SELECT
    A.*
FROM
    messages A
    LEFT JOIN block B ON
        (B.blocker_id = A.recipient_id AND B.blockee_id = A.sender_id)
WHERE
    A.recipient_id = 18
    AND B.blocker_id IS NULL
</code>```

Note "B.blocker_id IS NULL" means "LEFT JOIN did not find rows according to JOIN criteria" which is what you want here. Read up on LEFT OUTER JOIN.

2) Good old NOT EXISTS

```<code>SELECT * FROM messages A
WHERE NOT EXISTS(
    SELECT * FROM block
    WHERE B.blocker_id = A.recipient_id AND B.blockee_id = A.sender_id
)
WHERE A.recipient_id = 18
</code>```

3) NOT IN does not apply here since we got 2 columns to test.

Body:
I have a table called 'messages', which contains the columns sender_id, recipient_id, message (the text of the message) and readbyrecipient (a flag to indicate whether the message was read by the person to whom it was sent.

I am implementing the option to block users, so have added a table called block with columns blocker_id (the user who did the blocking) and blockee_id (the user who was blocked). All of the *_id columns link to my users table.

I am trying to get all unread messages which are not sent from users which were blocked by the recipient. Here's the query I have been working with:

SELECT
    A.*
FROM
    messages A,
    block B
WHERE
    A.recipient_id = 18
    AND A.readbyrecipient = 0
    AND NOT (
                B.blocker_id = A.recipient_id
                AND
                B.blockee_id = A.sender_id
            )

This returns no rows, even though I know the user id specified in A.recipient_id refers to a user who has one unread message from a user whom they have not blocked. I tried removing the AND NOT clause in the query, but it still returned zero rows until I removed block B from the SELECT part of the query, so I'm not sure whether the problem is with the WHERE clause or the SELECT clause.

Thanks in advance!

Body:
You need one of these:

1) LEFT JOIN. Please don't use the old crummy JOIN syntax you use, as it does not allow LEFT JOINs and is much harder to read.

SELECT
    A.*
FROM
    messages A
    LEFT JOIN block B ON
        (B.blocker_id = A.recipient_id AND B.blockee_id = A.sender_id)
WHERE
    A.recipient_id = 18
    AND B.blocker_id IS NULL

Note "B.blocker_id IS NULL" means "LEFT JOIN did not find rows according to JOIN criteria" which is what you want here. Read up on LEFT OUTER JOIN.

2) Good old NOT EXISTS

SELECT * FROM messages A
WHERE NOT EXISTS(
    SELECT * FROM block
    WHERE B.blocker_id = A.recipient_id AND B.blockee_id = A.sender_id
)
WHERE A.recipient_id = 18

3) NOT IN does not apply here since we got 2 columns to test.


问:
Error handling with Observables in Angular 2
I'm trying to pass any errors that might occur in an HTTP request to a common logging service from all my services:

```<code>import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';

constructor(logger: LoggerService) { }

doSomething(): Observable<any> {
    return this.http
        .post('/foo/bar', {})
        .catch(this.notifyErrors);
}

protected notifyErrors(error: any): Observable<any> {
    this.logger.log(error);

    return Observable.throw(error);
}
</code>```

Unfortunately, inside the notifyErrors method, this is lost. I've tried defining this as a fat arrow, but i get type errors from the TS compiler. I've used the exact syntax in the Observable documentation.

答:
If you pass function references, you need to fix this

 .catch(this.notifyErrors.bind(this));
```

<p>or alternatively</p>

<pre class="lang-ts prettyprint-override"><code> .catch(() => this.notifyErrors());
</code>```

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Body:
I'm trying to pass any errors that might occur in an HTTP request to a common logging service from all my services:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';

constructor(logger: LoggerService) { }

doSomething(): Observable<any> {
    return this.http
        .post('/foo/bar', {})
        .catch(this.notifyErrors);
}

protected notifyErrors(error: any): Observable<any> {
    this.logger.log(error);

    return Observable.throw(error);
}

Unfortunately, inside the notifyErrors method, this is lost. I've tried defining this as a fat arrow, but i get type errors from the TS compiler. I've used the exact syntax in the Observable documentation.

Body:
If you pass function references, you need to fix this

 .catch(this.notifyErrors.bind(this));

or alternatively

 .catch(() => this.notifyErrors());

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions


答:
You can use parse_str function to parse the string into an array / variables. In this case I prefer outputting to array instead of variables to prevent the pollution of namespace.

```<code><?php

$str = 'var1=red&var2=green&var3=blue&var4=magenta';

parse_str($str, $output);

$result = null;
foreach($output as $k => $v){
    if($v == 'green'){
        $result = $k;
        break;
    }
}

?>
</code>```

Title: processing this string with php

Body:
I have a text string that looks like this

var1=red&var2=green&var3=blue&var4=magenta

How can manipulate this string isolate the value of var2 which in this case is green

Body:
You can use parse_str function to parse the string into an array / variables. In this case I prefer outputting to array instead of variables to prevent the pollution of namespace.

<?php

$str = 'var1=red&var2=green&var3=blue&var4=magenta';

parse_str($str, $output);

$result = null;
foreach($output as $k => $v){
    if($v == 'green'){
        $result = $k;
        break;
    }
}

?>


问:
PowerShell / Html - questions
I am new to Powershell, and I suck at html.

There's a page with a table, and each cell has a ahref link, the value of the link is dynamic, but the link which I want to automate-clicking is always in the first cell.

I know there's cellindex in html/JS, is it usable in PS?

For example, let's say I have this table on a website.

```<code><table>

 <tr>
   <td>
  <a href="http://example1.com">
    <div style="height:100%;width:100%">
      hello world1
    </div>
  </a>
</td>

 </tr>

 <tr>
   <td>
  <a href="http://example2.com">
    <div style="height:100%;width:100%">
      hello world2
    </div>
  </a>
</td>
</tr>

 <tr>
   <td>
  <a href="http://example3.com">
    <div style="height:100%;width:100%">
      hello world3
    </div>
  </a>
</td>
</tr>

</table>
</code>```

And I want to make powershell to always click on the first link, the link inside is dynamic though.

Any ideas?  Hints?

答:
Ok, the Invoke-webrequest method is working with mark's link but with my page; but I noticed a pattern that may can be used:

I noticed the the following:

```<code><table id="row" class="simple">
<thead>
<tr>
<th></th>
<th class="centerjustify">File Name</th>
<th class="centerjustify">File ID</th>
<th class="datetime">Creation Date</th>
<th class="datetime">Upload Date</th>
<th class="centerjustify">Processing Status</th>
<th class="centerjustify">Exceptions</th>
<th class="centerjustify">Unprocessed Count</th>
<th class="centerjustify">Discarded Count</th>
<th class="centerjustify">Rejected Count</th>
<th class="centerjustify">Void Count</th>
<th class="centerjustify">PO Total Count</th>
<th class="centerjustify">PO Total Amount</th>
<th class="centerjustify">CM Total Count</th>
<th class="centerjustify">CM Total Amount</th>
<th class="centerjustify">PO Processed Count</th>
<th class="centerjustify">PO Processed Amount</th>
<th class="centerjustify">CM Processed Count</th>
<th class="centerjustify">CM Processed Amount</th>
<th class="centerjustify">Counts At Upload</th></tr></thead>
<tbody>
<tr class="odd">
<td><input type="radio" disabled="disabled" name="checkedValue" value="12047" /></td>
<td class="leftjustify textColorBlack">
<a href="loadConfirmationDetails.htm?fId=12047">520170123000000_520170123000000_20170327_01.txt</a></td>
<td class="centerjustify textColorBlack">1</td>
<td class="datetime textColorBlack">Mar 27, 2017 0:00</td>
<td class="datetime textColorBlack">Mar 27, 2017 10:33:24 PM +03:00</td>
<td class="centerjustify textColorBlack">
</code>```

The fId part in "loadConfirmationDetails.htm?fId=12047" is dynamic; and it's the last part of the next page;

For example: "https://aaa.xxxxxxx.com/aaa/community/loadConfirmationDetails.htm?fId=12047

And table's ID is unique, called "row" - I wonder if I can use a completely another way; other than invoking the webpage, by auto-copying this id info from its source html and concatenate it with the main link?

I am really out of ideas beyond that.

Title: PowerShell / Html - questions

Body:
I am new to Powershell, and I suck at html.

There's a page with a table, and each cell has a ahref link, the value of the link is dynamic, but the link which I want to automate-clicking is always in the first cell.

I know there's cellindex in html/JS, is it usable in PS?

For example, let's say I have this table on a website.

      hello world1

      hello world2

      hello world3

And I want to make powershell to always click on the first link, the link inside is dynamic though.

Any ideas?  Hints?

Body:
Ok, the Invoke-webrequest method is working with mark's link but with my page; but I noticed a pattern that may can be used:

I noticed the the following:

<table id="row" class="simple">
<thead>
<tr>
<th></th>
<th class="centerjustify">File Name</th>
<th class="centerjustify">File ID</th>
<th class="datetime">Creation Date</th>
<th class="datetime">Upload Date</th>
<th class="centerjustify">Processing Status</th>
<th class="centerjustify">Exceptions</th>
<th class="centerjustify">Unprocessed Count</th>
<th class="centerjustify">Discarded Count</th>
<th class="centerjustify">Rejected Count</th>
<th class="centerjustify">Void Count</th>
<th class="centerjustify">PO Total Count</th>
<th class="centerjustify">PO Total Amount</th>
<th class="centerjustify">CM Total Count</th>
<th class="centerjustify">CM Total Amount</th>
<th class="centerjustify">PO Processed Count</th>
<th class="centerjustify">PO Processed Amount</th>
<th class="centerjustify">CM Processed Count</th>
<th class="centerjustify">CM Processed Amount</th>
<th class="centerjustify">Counts At Upload</th></tr></thead>
<tbody>
<tr class="odd">
<td><input type="radio" disabled="disabled" name="checkedValue" value="12047" /></td>
<td class="leftjustify textColorBlack">
<a href="loadConfirmationDetails.htm?fId=12047">520170123000000_520170123000000_20170327_01.txt</a></td>
<td class="centerjustify textColorBlack">1</td>
<td class="datetime textColorBlack">Mar 27, 2017 0:00</td>
<td class="datetime textColorBlack">Mar 27, 2017 10:33:24 PM +03:00</td>
<td class="centerjustify textColorBlack">

The fId part in "loadConfirmationDetails.htm?fId=12047" is dynamic; and it's the last part of the next page;

For example: "https://aaa.xxxxxxx.com/aaa/community/loadConfirmationDetails.htm?fId=12047

And table's ID is unique, called "row" - I wonder if I can use a completely another way; other than invoking the webpage, by auto-copying this id info from its source html and concatenate it with the main link?

I am really out of ideas beyond that.


问:
How can I retrieve a pointer to a variable that is in a list data structure?
(All of this is done in C++)

I am working with a tree of nodes. The node class is simply some variables and a list of child-nodes. My goal is to retrieve a pointer to a node that is X layers down by matching it on a variable.

I am aiming to create a function that looks something like this.

```<code>Node* Node::returnChild(int depth, string match)
{
     ...
}
</code>```

This should recursively iterate down all of the nodes children and then search for a node with a variable matching the string variable. When finding the matching node it should take the address of the node, save it in a pointer and return it to the functioncall.

I managed to make a working function that iterated down the sub-tree of nodes to the specified depth and found the correct node. It even printed out the string value to make sure that it was the correct node. But when trying to use the node via the pointer (provided by the function) outside of the function I got nothing.

In the function I used for a for-loop looking something like this:

```<code>for(auto forNode : this->children)
</code>```

This worked fine, but it seems that the node "forNode" that is accessed within the scope of the loop is a temporary copy of the real node from the list. This copy does not "exist" outside of its for-loops scope and therefore I will not be able to access the node that was located at the pointers address when it is returned to me outside of the function (since there is no node at the address anymore).

So the real question is: How do I manage to get a pointer to the "real" node provided a list of nodes, the depth and a matching string?

答:
you'll have to switch your for loop to something like:

```<code>for (auto& forNode : this->children)
</code>```

this will make sure forNode is not copied by value and then invalidated when you leave the for loop scope.

Body:
(All of this is done in C++)

I am working with a tree of nodes. The node class is simply some variables and a list of child-nodes. My goal is to retrieve a pointer to a node that is X layers down by matching it on a variable.

I am aiming to create a function that looks something like this.

Node* Node::returnChild(int depth, string match)
{
     ...
}

This should recursively iterate down all of the nodes children and then search for a node with a variable matching the string variable. When finding the matching node it should take the address of the node, save it in a pointer and return it to the functioncall.

I managed to make a working function that iterated down the sub-tree of nodes to the specified depth and found the correct node. It even printed out the string value to make sure that it was the correct node. But when trying to use the node via the pointer (provided by the function) outside of the function I got nothing.

In the function I used for a for-loop looking something like this:

for(auto forNode : this->children)

This worked fine, but it seems that the node "forNode" that is accessed within the scope of the loop is a temporary copy of the real node from the list. This copy does not "exist" outside of its for-loops scope and therefore I will not be able to access the node that was located at the pointers address when it is returned to me outside of the function (since there is no node at the address anymore).

So the real question is: How do I manage to get a pointer to the "real" node provided a list of nodes, the depth and a matching string?

Body:
you'll have to switch your for loop to something like:

for (auto& forNode : this->children)

this will make sure forNode is not copied by value and then invalidated when you leave the for loop scope.


问:
date_format() on sql query gives error Operand should contain 1 column(s)
Original SQL query

```<code>SELECT * FROM date WHERE fecha > now() AND feriado != 1 Limit 10
</code>```

I want to format returned dates to '%d %b %y' using SQL date_format() but i get error #1241 - Operand should contain 1 column(s) when using
 SELECT DATE_FORMAT((SELECT * FROM date WHERE fecha > now() AND feriado != 1 Limit 10), '%d %b %y')
Can you give me advice on how to solve the problem? Thank you

答:
You need to put DATE_FORMAT() around specific column names.

```<code>SELECT DATE_FORMAT(column_name, '%d %b %y') AS formatted_date
FROM date
WHERE fecha > NOW() and feriado != 1
LIMIT 1
</code>```

Body:
Original SQL query

SELECT * FROM date WHERE fecha > now() AND feriado != 1 Limit 10

I want to format returned dates to '%d %b %y' using SQL date_format() but i get error #1241 - Operand should contain 1 column(s) when using
 SELECT DATE_FORMAT((SELECT * FROM date WHERE fecha > now() AND feriado != 1 Limit 10), '%d %b %y')
Can you give me advice on how to solve the problem? Thank you

Body:
You need to put DATE_FORMAT() around specific column names.

SELECT DATE_FORMAT(column_name, '%d %b %y') AS formatted_date
FROM date
WHERE fecha > NOW() and feriado != 1
LIMIT 1


问:
How draw rout between markers
I'm facing a problem with google map, the problem is,when i draw rout between markers it duplicated heres the image :
enter image description here

heres the makers:

```<code> var markers=[{"longitude":"-5.808954951287861","latitude":"35.77107409886168","deviceTime":"2017-03-29T14:02:36.000+0000"},
        {"longitude":"-5.807401662705262","latitude":"35.77029143851354","deviceTime":"2017-03-29T14:05:36.000+0000"},
        {"longitude":"-5.794769662196012","latitude":"35.77169804990058","deviceTime":"2017-03-29T14:08:36.000+0000"},
        {"longitude":"-5.784207185242776","latitude":"35.76541442176138","deviceTime":"2017-03-29T14:11:36.000+0000"},
        {"longitude":"-5.78417853735302","latitude":"35.76539666006973","deviceTime":"2017-03-29T14:14:36.000+0000"},
        {"longitude":"-5.784050767764706","latitude":"35.76528034963732","deviceTime":"2017-03-29T14:15:52.000+0000"}];
</code>```

heres the function :

```<code> storyboard.drawTrajet=function(markers){

              var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                var labelIndex = 0;

             var mapOptions = {
                    center: new google.maps.LatLng(markers[0].latitude, markers[0].longitude),
                    zoom: 10,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById("map"), mapOptions);
                var infoWindow = new google.maps.InfoWindow();
                var lat_lng = new Array();
                var latlngbounds = new google.maps.LatLngBounds();

                for (i = 0; i < markers.length; i++) {
                    var data = markers[i];

                    alert(markers.length);

                    var myLatlng = new google.maps.LatLng(data.latitude, data.longitude);
                    lat_lng.push(myLatlng);

                    var marker = new google.maps.Marker({

                        //icon: icons['info'].icon,
                        label: labels[labelIndex++ % labels.length],

                        position: myLatlng,
                        map: map
                        //title: 'data.title'
                    });
                    //path[z].push(marker.getPosition());
                    latlngbounds.extend(marker.position);
                    (function (marker, data) {
                        google.maps.event.addListener(marker, "mouseover", function (e) {

                             storyboard.geocodeLatLng($scope.geocoder , map, $scope.infoWindow,data.latitude,data.longitude, false,false);
                             //alert( $scope.MyPos);
                            infoWindow.setContent('<div ><i class="fa fa-calendar" aria-hidden="true"></i> '+$filter('date')(data.deviceTime, "HH:mm:ss")
                                +'        '+'<i class="glyphicon glyphicon-bookmark" aria-hidden="true"></i>'+$scope.MyPos
                                +'<div>'
                                +'<i class="glyphicon glyphicon-map-marker" aria-hidden="true"></i>'+data.latitude+'        '
                                +'<i class="glyphicon glyphicon-map-marker" aria-hidden="true"></i>'+data.longitude
                                +'</div>'
                                +'</div>');
                            infoWindow.open(map, marker);
                        });
                    })(marker, data);
                }
                map.setCenter(latlngbounds.getCenter());
                map.fitBounds(latlngbounds);

                //***********ROUTING****************//

                //Initialize the Path Array
                var path = new google.maps.MVCArray();

                //Initialize the Direction Service
                var service = new google.maps.DirectionsService();

                //Set the Path Stroke Color
                var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });

                //Loop and Draw Path Route between the Points on MAP
                for (var i = 0; i < lat_lng.length; i++) {
                    //alert("sss");
                    if ((i + 1) < lat_lng.length) {
                        var src = lat_lng[i];
                        //src.setMap(null);
                        var des = lat_lng[i + 1];
                        path.push(src);
                        poly.setPath(path);
                        service.route({
                            origin: src,
                            destination: des,
                            travelMode: google.maps.DirectionsTravelMode.DRIVING
                        }, function (result, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                                   // alert("sssscvvvvvvs");
                                    path.push(result.routes[0].overview_path[i]);
                                }
                            }
                        });
                    }
                }

        }
</code>```

can anyone help please to resolve this problem??

答:
I Think you should use Waypoints for this case. please see example from this.

https://developers.google.com/maps/documentation/javascript/directions#Waypoints

Title: How draw rout between markers

Body:
I'm facing a problem with google map, the problem is,when i draw rout between markers it duplicated heres the image :
enter image description here

heres the makers:

 var markers=[{"longitude":"-5.808954951287861","latitude":"35.77107409886168","deviceTime":"2017-03-29T14:02:36.000+0000"},
        {"longitude":"-5.807401662705262","latitude":"35.77029143851354","deviceTime":"2017-03-29T14:05:36.000+0000"},
        {"longitude":"-5.794769662196012","latitude":"35.77169804990058","deviceTime":"2017-03-29T14:08:36.000+0000"},
        {"longitude":"-5.784207185242776","latitude":"35.76541442176138","deviceTime":"2017-03-29T14:11:36.000+0000"},
        {"longitude":"-5.78417853735302","latitude":"35.76539666006973","deviceTime":"2017-03-29T14:14:36.000+0000"},
        {"longitude":"-5.784050767764706","latitude":"35.76528034963732","deviceTime":"2017-03-29T14:15:52.000+0000"}];

heres the function :

 storyboard.drawTrajet=function(markers){

              var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                var labelIndex = 0;

             var mapOptions = {
                    center: new google.maps.LatLng(markers[0].latitude, markers[0].longitude),
                    zoom: 10,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById("map"), mapOptions);
                var infoWindow = new google.maps.InfoWindow();
                var lat_lng = new Array();
                var latlngbounds = new google.maps.LatLngBounds();

                for (i = 0; i < markers.length; i++) {
                    var data = markers[i];

                    alert(markers.length);

                    var myLatlng = new google.maps.LatLng(data.latitude, data.longitude);
                    lat_lng.push(myLatlng);

                    var marker = new google.maps.Marker({

                        //icon: icons['info'].icon,
                        label: labels[labelIndex++ % labels.length],

                        position: myLatlng,
                        map: map
                        //title: 'data.title'
                    });
                    //path[z].push(marker.getPosition());
                    latlngbounds.extend(marker.position);
                    (function (marker, data) {
                        google.maps.event.addListener(marker, "mouseover", function (e) {

                             storyboard.geocodeLatLng($scope.geocoder , map, $scope.infoWindow,data.latitude,data.longitude, false,false);
                             //alert( $scope.MyPos);
                            infoWindow.setContent('
 '+$filter('date')(data.deviceTime, "HH:mm:ss")
                                +'        '+''+$scope.MyPos
                                +'
'
                                +''+data.latitude+'        '
                                +''+data.longitude
                                +'
'
                                +'
');
                            infoWindow.open(map, marker);
                        });
                    })(marker, data);
                }
                map.setCenter(latlngbounds.getCenter());
                map.fitBounds(latlngbounds);

                //***********ROUTING****************//

                //Initialize the Path Array
                var path = new google.maps.MVCArray();

                //Initialize the Direction Service
                var service = new google.maps.DirectionsService();

                //Set the Path Stroke Color
                var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });

                //Loop and Draw Path Route between the Points on MAP
                for (var i = 0; i < lat_lng.length; i++) {
                    //alert("sss");
                    if ((i + 1) < lat_lng.length) {
                        var src = lat_lng[i];
                        //src.setMap(null);
                        var des = lat_lng[i + 1];
                        path.push(src);
                        poly.setPath(path);
                        service.route({
                            origin: src,
                            destination: des,
                            travelMode: google.maps.DirectionsTravelMode.DRIVING
                        }, function (result, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                                   // alert("sssscvvvvvvs");
                                    path.push(result.routes[0].overview_path[i]);
                                }
                            }
                        });
                    }
                }

        }

can anyone help please to resolve this problem??


问:
Display only one value in selectInput in R Shiny app
I am trying to dynamically populate the values of the selectInput from the data file  uploaded by the user. The selectInput must contain only numeric columns.

Here is my code snippet for server.R

```<code>...
idx <- sapply(data.file, is.numeric)
numeric_columns <- data.file[, idx]
factor_columns <- data.file[, !idx]

updateSelectInput(session, "bar_x", "Select1", choices = names(numeric_columns))
updateSelectInput(session, "bar_y", "Select2", choices = names(factor_columns))
...
</code>```

Corresponding ui.r

```<code> ...
 selectInput("bar_x", "Select1", choices = NULL),
 selectInput("bar_y", "Select2", choices = NULL)
 ...
</code>```

The code works fine as long as there are more than one values in any dropdown. However, it fails as soon as it encounters only one value to be displayed in the selectInput.

How can I handle this specific condition, given that the data is uploaded and it cannot be controlled if there is just one column as numeric?

答:
Info: Code was adapted by OP to make error reproducible.
To solve your issue use val2 <- val[,idx, drop = FALSE]
You dropped the column names by subsetting the data.frame().
To avoid this use drop = FALSE; see Keep column name when select one column from a data frame/matrix in R.

```<code>library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
# drj's changes START block 1
        #selectInput('states', 'Select states', choices = c(1,2,4))
        selectInput('states', 'Select states', choices = NULL)
# drj's changes END block 1
      ),

      # Show a plot of the generated distribution
      mainPanel(
         plotOutput("distPlot")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {

  observe({

#drj's changes START block 2
    #val <- c(1,2,3)
    #names(val) <- c("a","b","c")
    #updateSelectInput(session, 'states', 'Select states', choices = names(val[1]))
    val <- as.data.frame(cbind(c("_1","_2","_3"), c(4, 4, 6)))
    names(val) <- c("a","b")
    val$b <- as.numeric(val$b)
    idx <- sapply(val, is.numeric)
    val2 <- val[,idx, drop = FALSE]
    updateSelectInput(session, 'states', 'Select states', choices = names(val2))
#drj's changes END block 2
  })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Body:
I am trying to dynamically populate the values of the selectInput from the data file  uploaded by the user. The selectInput must contain only numeric columns.

Here is my code snippet for server.R

...
idx <- sapply(data.file, is.numeric)
numeric_columns <- data.file[, idx]
factor_columns <- data.file[, !idx]

updateSelectInput(session, "bar_x", "Select1", choices = names(numeric_columns))
updateSelectInput(session, "bar_y", "Select2", choices = names(factor_columns))
...

Corresponding ui.r

 ...
 selectInput("bar_x", "Select1", choices = NULL),
 selectInput("bar_y", "Select2", choices = NULL)
 ...

The code works fine as long as there are more than one values in any dropdown. However, it fails as soon as it encounters only one value to be displayed in the selectInput.

How can I handle this specific condition, given that the data is uploaded and it cannot be controlled if there is just one column as numeric?

Body:
Info: Code was adapted by OP to make error reproducible.
To solve your issue use val2 <- val[,idx, drop = FALSE]
You dropped the column names by subsetting the data.frame().
To avoid this use drop = FALSE; see Keep column name when select one column from a data frame/matrix in R.

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
# drj's changes START block 1
        #selectInput('states', 'Select states', choices = c(1,2,4))
        selectInput('states', 'Select states', choices = NULL)
# drj's changes END block 1
      ),

      # Show a plot of the generated distribution
      mainPanel(
         plotOutput("distPlot")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {

  observe({

#drj's changes START block 2
    #val <- c(1,2,3)
    #names(val) <- c("a","b","c")
    #updateSelectInput(session, 'states', 'Select states', choices = names(val[1]))
    val <- as.data.frame(cbind(c("_1","_2","_3"), c(4, 4, 6)))
    names(val) <- c("a","b")
    val$b <- as.numeric(val$b)
    idx <- sapply(val, is.numeric)
    val2 <- val[,idx, drop = FALSE]
    updateSelectInput(session, 'states', 'Select states', choices = names(val2))
#drj's changes END block 2
  })
}

# Run the application
shinyApp(ui = ui, server = server)


问:
Error in callAPI(query, token)
I had tried to access my FB token using the preliminary code shown by pablo over here :

https://github.com/pablobarbera/Rfacebook

However I get the following error message :

```<code>Error in callAPI(query, token) :
  An active access token must be used to query information about the current user.
</code>```

I used this code:

```<code>fb_oauth <- fbOAuth(app_id="14025", app_secret="5fdb6ef5776",extended_permissions = TRUE)

save(fb_oauth, file="fb_oauth")

load("fb_oauth")
</code>```

I understand that I am not having access using my token despite authentication completion. Could someone please help.

答:
Quick fix is just remove type = "application/x-www-form-urlencoded"
 from fbOauth.R in RFacebook package. Because now Facebook returns response in JSON format.

Title: Error in callAPI(query, token)

Body:
I had tried to access my FB token using the preliminary code shown by pablo over here :

https://github.com/pablobarbera/Rfacebook

However I get the following error message :

Error in callAPI(query, token) :
  An active access token must be used to query information about the current user.

I used this code:

fb_oauth <- fbOAuth(app_id="14025", app_secret="5fdb6ef5776",extended_permissions = TRUE)

save(fb_oauth, file="fb_oauth")

load("fb_oauth")

I understand that I am not having access using my token despite authentication completion. Could someone please help.


问:
Delphi code to turn on screen saver doesn't work in Windows 7
I have a Delphi app that places the computer into screensave using

```<code>hWnd := GetDesktopWindow ;
SendMessage (hWnd, WM_SYSCOMMAND, SC_SCREENSAVE, 0) ;
</code>```

This works fine under XP but I find it doesn't work under (embedded) Windows 7.

Any ideas?

答: The SC_SCREENSAVE message tells the target window to execute the screen saver application specified in the [boot] section of the System.ini file. As the o/s is Embedded windows, which is a cut-down version of windows, quiet likely the system.ini file is configured for no screen-saver. Check your system.ini file.</p>

Body:
I have a Delphi app that places the computer into screensave using

hWnd := GetDesktopWindow ;
SendMessage (hWnd, WM_SYSCOMMAND, SC_SCREENSAVE, 0) ;

This works fine under XP but I find it doesn't work under (embedded) Windows 7.

Any ideas?


问:
Show Custom Post based on selected custom taxonomy in Wordpress
In the current website i am building i build the following functionality.

Current situation to give a better understanding of the problem.

There is a page called blog. This page display's all the blogs (posts) in a list. There is a aside with all the categories the posts have. The user can select a category. Once the user clicks on it the user will go to the category.php and see all the posts that have that specific category.

I want to create the same scenario but than with a custom post type. I have a template part; 'offer-list-template.php'

offer-list-template.php (here i get all the offers and display them);

```<code>  <?php
      // set up or arguments for our custom query
      $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
      $query_args = array(
        'post_type' => 'Offers',
        'posts_per_page' => 10,
        'paged' => $paged
      );
      // create a new instance of WP_Query
      $the_query = new WP_Query( $query_args );
    ?>

<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); // run the loop ?>
  <?php

   //$objectData is used in post-listing-item.php

    $objectData->title = get_the_title($post);
    $objectData->content = get_the_content($post);
    $objectData->permalink = get_the_permalink($post);
    $objectData->thumbnail = get_the_post_thumbnail($post);
    $objectData->posttype = get_post_type($post);

    include(locate_template('template-parts/post-listing-item.php'));
  ?>
<?php endwhile; ?>
</code>```

In the same file there is the aside which shows the categories. offer_category is the taxonomy slug.

```<code>  <?php $terms = get_terms( 'offer_category' );
    foreach ( $terms as $term ) {

        // The $term is an object, so we don't need to specify the $taxonomy.
        $term_link = get_term_link( $term );

        // If there was an error, continue to the next term.
        if ( is_wp_error( $term_link ) ) {
            continue;
        }

        // We successfully got a link. Print it out.
        echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a><span>('. $term->count . ')</span></li>';
    }
    ?>
    </ul
</code>```

The result is:

If the user clicks on the categorie it goes to: taxonomy-offer-category.php (taxonomy-slug.php)

Here i need to display the posts (post_type->offers) that have the selected category.

Registration of the custom post type:

```<code>//Register Custom post type for Offers.
function create_posttype_offer() {
  $args = array(
    'labels' => array(
      'name' => __('Offers', ''),
      'singular_name' => __('Offer'),
      'all_items' => __('All Offers'),
      'add_new_item' => __('Add New Offer'),
      'edit_item' => __('Edit Offer'),
      'view_item' => __('View Offer')
    ),
    'public' => true,
    'has_archive' => true,
    'rewrite' => array('slug' => 'Offers'),
    'show_ui' => true,
    'show_in_menu' => true,
    'show_in_nav_menus' => true,
    'capability_type' => 'page',
    'supports' => array('title', 'editor', 'thumbnail'),
    'exclude_from_search' => true,
    'menu_position' => 70,
    'has_archive' => true,
    'menu_icon' => 'dashicons-star-filled'
    );
  register_post_type('Offers', $args);
}
add_action( 'init', 'create_posttype_offer');

// Register Custom Categoeries for Custom Post Type Offers
function taxonomies_offer() {
$labels = array(
    'name'              => _x( 'Categories', 'taxonomy general name' ),
    'singular_name'     => _x( 'Category', 'taxonomy singular name' ),
    'search_items'      => __( 'Search Categories' ),
    'all_items'         => __( 'All Categories' ),
    'parent_item'       => __( 'Parent Category' ),
    'parent_item_colon' => __( 'Parent Category:' ),
    'edit_item'         => __( 'Edit Category' ),
    'update_item'       => __( 'Update Category' ),
    'add_new_item'      => __( 'Add New Category' ),
    'new_item_name'     => __( 'New Category' ),
    'menu_name'         => __( 'Categories' ),
    );

$args = array(
    'labels' => $labels,
    'hierarchical' => true,
    );

register_taxonomy( 'offer_category', 'offers', $args );
}
add_action( 'init', 'taxonomies_offer', 0 );
</code>```

When i use the default post type and i call category.php which has the following code is will display the posts with the selected category. But with a custom post type i can't find a way to manage it.

```<code>  <?php if (have_posts() ) : while ( have_posts() ) : the_post(); // run the loop ?>
    <?php

     //$objectData is used in post-listing-item.php

      $objectData->title = get_the_title($post);
      $objectData->content = get_the_content($post);
      $objectData->permalink = get_the_permalink($post);
      $objectData->thumbnail = get_the_post_thumbnail($post);
      $objectData->posttype = get_post_type($post);

      include(locate_template('template-parts/post-listing-item.php'));
    ?>
  <?php endwhile; ?>
</code>```

This is the post-listing-item (view)

```<code><article class="post-item">
     <figure>
       <?php echo $objectData->thumbnail ?>
     </figure>

     <div class="content">
       <a href="<?php echo $objectData->permalink ?>">
           <h2><?php echo $objectData->title ?></h2>
       </a>

       <p><?php echo $objectData->content ?></p>

       <div class="read-more-button">
         <a href="<?php echo $objectData->permalink ?>">read more
         <span>
           <svg class="next-arrow"><use xlink:href="#next-arrow" /></svg>
         </span>
         </a>
       </div>
     </div>
 </article>
</code>```

答:
I found it!

I got the taxonomy and slug from the url and used that in the query.

```<code>  <?php

     $term_slug = get_query_var( 'term' );
     $taxonomyName = get_query_var( 'taxonomy' );

      $the_query = new WP_Query( array(
        'post_type' => 'offers',
        'tax_query' => array(
            array (
                'taxonomy' => $taxonomyName,
                'field' => 'slug',
                'terms' => $term_slug,
              )
            ),
          ));
      ?>

        <ul>
          <?php while($the_query->have_posts()) : $the_query->the_post(); ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
          <?php endwhile; wp_reset_query(); ?>
        </ul>
</code>```

Body:
In the current website i am building i build the following functionality.

Current situation to give a better understanding of the problem.

There is a page called blog. This page display's all the blogs (posts) in a list. There is a aside with all the categories the posts have. The user can select a category. Once the user clicks on it the user will go to the category.php and see all the posts that have that specific category.

I want to create the same scenario but than with a custom post type. I have a template part; 'offer-list-template.php'

offer-list-template.php (here i get all the offers and display them);

  <?php
      // set up or arguments for our custom query
      $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
      $query_args = array(
        'post_type' => 'Offers',
        'posts_per_page' => 10,
        'paged' => $paged
      );
      // create a new instance of WP_Query
      $the_query = new WP_Query( $query_args );
    ?>

<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); // run the loop ?>
  <?php

   //$objectData is used in post-listing-item.php

    $objectData->title = get_the_title($post);
    $objectData->content = get_the_content($post);
    $objectData->permalink = get_the_permalink($post);
    $objectData->thumbnail = get_the_post_thumbnail($post);
    $objectData->posttype = get_post_type($post);

    include(locate_template('template-parts/post-listing-item.php'));
  ?>
<?php endwhile; ?>

In the same file there is the aside which shows the categories. offer_category is the taxonomy slug.

  <?php $terms = get_terms( 'offer_category' );
    foreach ( $terms as $term ) {

        // The $term is an object, so we don't need to specify the $taxonomy.
        $term_link = get_term_link( $term );

        // If there was an error, continue to the next term.
        if ( is_wp_error( $term_link ) ) {
            continue;
        }

        // We successfully got a link. Print it out.
        echo '
' . $term->name . '('. $term->count . ')
';
    }
    ?>
    </ul

The result is:

If the user clicks on the categorie it goes to: taxonomy-offer-category.php (taxonomy-slug.php)

Here i need to display the posts (post_type->offers) that have the selected category.

Registration of the custom post type:

//Register Custom post type for Offers.
function create_posttype_offer() {
  $args = array(
    'labels' => array(
      'name' => __('Offers', ''),
      'singular_name' => __('Offer'),
      'all_items' => __('All Offers'),
      'add_new_item' => __('Add New Offer'),
      'edit_item' => __('Edit Offer'),
      'view_item' => __('View Offer')
    ),
    'public' => true,
    'has_archive' => true,
    'rewrite' => array('slug' => 'Offers'),
    'show_ui' => true,
    'show_in_menu' => true,
    'show_in_nav_menus' => true,
    'capability_type' => 'page',
    'supports' => array('title', 'editor', 'thumbnail'),
    'exclude_from_search' => true,
    'menu_position' => 70,
    'has_archive' => true,
    'menu_icon' => 'dashicons-star-filled'
    );
  register_post_type('Offers', $args);
}
add_action( 'init', 'create_posttype_offer');

// Register Custom Categoeries for Custom Post Type Offers
function taxonomies_offer() {
$labels = array(
    'name'              => _x( 'Categories', 'taxonomy general name' ),
    'singular_name'     => _x( 'Category', 'taxonomy singular name' ),
    'search_items'      => __( 'Search Categories' ),
    'all_items'         => __( 'All Categories' ),
    'parent_item'       => __( 'Parent Category' ),
    'parent_item_colon' => __( 'Parent Category:' ),
    'edit_item'         => __( 'Edit Category' ),
    'update_item'       => __( 'Update Category' ),
    'add_new_item'      => __( 'Add New Category' ),
    'new_item_name'     => __( 'New Category' ),
    'menu_name'         => __( 'Categories' ),
    );

$args = array(
    'labels' => $labels,
    'hierarchical' => true,
    );

register_taxonomy( 'offer_category', 'offers', $args );
}
add_action( 'init', 'taxonomies_offer', 0 );

When i use the default post type and i call category.php which has the following code is will display the posts with the selected category. But with a custom post type i can't find a way to manage it.

  <?php if (have_posts() ) : while ( have_posts() ) : the_post(); // run the loop ?>
    <?php

     //$objectData is used in post-listing-item.php

      $objectData->title = get_the_title($post);
      $objectData->content = get_the_content($post);
      $objectData->permalink = get_the_permalink($post);
      $objectData->thumbnail = get_the_post_thumbnail($post);
      $objectData->posttype = get_post_type($post);

      include(locate_template('template-parts/post-listing-item.php'));
    ?>
  <?php endwhile; ?>

This is the post-listing-item (view)

       <?php echo $objectData->thumbnail ?>

       <a href="<?php echo $objectData->permalink ?>">

<?php echo $objectData->title ?>

<?php echo $objectData->content ?>

         <a href="<?php echo $objectData->permalink ?>">read more

           <svg class="next-arrow"><use xlink:href="#next-arrow" /></svg>

Body:
I found it!

I got the taxonomy and slug from the url and used that in the query.

  <?php

     $term_slug = get_query_var( 'term' );
     $taxonomyName = get_query_var( 'taxonomy' );

      $the_query = new WP_Query( array(
        'post_type' => 'offers',
        'tax_query' => array(
            array (
                'taxonomy' => $taxonomyName,
                'field' => 'slug',
                'terms' => $term_slug,
              )
            ),
          ));
      ?>

        <ul>
          <?php while($the_query->have_posts()) : $the_query->the_post(); ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
          <?php endwhile; wp_reset_query(); ?>
        </ul>