问:
How to mock location on device?
How can I mock my location on a physical device (Nexus One)?

I know you can do this with the emulator in the Emulator Control panel, but this doesn't work for a physical device.

答:
I've had success with the following code. Albeit it got me a single lock for some reason (even if I've tried different LatLng pairs), it worked for me. mLocationManager is a LocationManager which is hooked up to a LocationListener:

```<code>private void getMockLocation()
{
    mLocationManager.removeTestProvider(LocationManager.GPS_PROVIDER);
    mLocationManager.addTestProvider
    (
      LocationManager.GPS_PROVIDER,
      "requiresNetwork" == "",
      "requiresSatellite" == "",
      "requiresCell" == "",
      "hasMonetaryCost" == "",
      "supportsAltitude" == "",
      "supportsSpeed" == "",
      "supportsBearing" == "",

      android.location.Criteria.POWER_LOW,
      android.location.Criteria.ACCURACY_FINE
    );

    Location newLocation = new Location(LocationManager.GPS_PROVIDER);

    newLocation.setLatitude (/* TODO: Set Some Lat */);
    newLocation.setLongitude(/* TODO: Set Some Lng */);

    newLocation.setAccuracy(500);

    mLocationManager.setTestProviderEnabled
    (
      LocationManager.GPS_PROVIDER,
      true
    );

    mLocationManager.setTestProviderStatus
    (
       LocationManager.GPS_PROVIDER,
       LocationProvider.AVAILABLE,
       null,
       System.currentTimeMillis()
    );

    mLocationManager.setTestProviderLocation
    (
      LocationManager.GPS_PROVIDER,
      newLocation
    );
}
</code>```

Title: How to mock location on device?

Body:
I've had success with the following code. Albeit it got me a single lock for some reason (even if I've tried different LatLng pairs), it worked for me. mLocationManager is a LocationManager which is hooked up to a LocationListener:

private void getMockLocation()
{
    mLocationManager.removeTestProvider(LocationManager.GPS_PROVIDER);
    mLocationManager.addTestProvider
    (
      LocationManager.GPS_PROVIDER,
      "requiresNetwork" == "",
      "requiresSatellite" == "",
      "requiresCell" == "",
      "hasMonetaryCost" == "",
      "supportsAltitude" == "",
      "supportsSpeed" == "",
      "supportsBearing" == "",

      android.location.Criteria.POWER_LOW,
      android.location.Criteria.ACCURACY_FINE
    );

    Location newLocation = new Location(LocationManager.GPS_PROVIDER);

    newLocation.setLatitude (/* TODO: Set Some Lat */);
    newLocation.setLongitude(/* TODO: Set Some Lng */);

    newLocation.setAccuracy(500);

    mLocationManager.setTestProviderEnabled
    (
      LocationManager.GPS_PROVIDER,
      true
    );

    mLocationManager.setTestProviderStatus
    (
       LocationManager.GPS_PROVIDER,
       LocationProvider.AVAILABLE,
       null,
       System.currentTimeMillis()
    );

    mLocationManager.setTestProviderLocation
    (
      LocationManager.GPS_PROVIDER,
      newLocation
    );
}


来源: stackexchange

问:
how to check item in a list contains in python
I have 2 lists,

```<code>my_list = ['on@3','one',"$", "lo#"]
spl = ["@","$"]
</code>```

I am trying to get the items in 'my_list' which contains any of the items in spl.

I tried

```<code>out_list = [item for item in my_list if item.contains("!".join(spl))]
</code>```

but this gives error.

My expected output is

```<code>out_list = ["on@3","$"]
</code>```

答:
```<code>result = [item for item in my_list for s in spl if s in item]
</code>```

And more human readable form:

```<code>result = []

for item in my_list:
    for s in spl:
        if s in item:
            result.append(item)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 2 lists,

my_list = ['on@3','one',"$", "lo#"]
spl = ["@","$"]

I am trying to get the items in 'my_list' which contains any of the items in spl.

I tried

out_list = [item for item in my_list if item.contains("!".join(spl))]

but this gives error.

My expected output is

out_list = ["on@3","$"]

Body:
result = [item for item in my_list for s in spl if s in item]

And more human readable form:

result = []

for item in my_list:
    for s in spl:
        if s in item:
            result.append(item)


问:
How to color System.out.println output?
How can I color Java output?

For example in C and other languages I can use ANSI-escape like \033[0m to do this. But in Java it doesn't work.

```<code>public static void main(String[] x) {
    System.out.println("\033[0m BLABLA \033[0m\n");
}
</code>```

答:
I've written a library called AnsiScape that allows you to write coloured output in a more structured way:

Example:

```<code>AnsiScape ansiScape = new AnsiScape();
String colors = ansiScape.format("{red {blueBg Red text with blue background}} {b Bold text}");
System.out.println(colors);
</code>```

The library it also allows you to define your own "escape classes" akin to css classes.

Example:

```<code>AnsiScapeContext context = new AnsiScapeContext();

// Defines a "class" for text
AnsiClass text = AnsiClass.withName("text").add(RED);
// Defines a "class" for the title used
AnsiClass title = AnsiClass.withName("title").add(BOLD, BLUE_BG, YELLOW);
// Defines a "class" to render urls
AnsiClass url = AnsiClass.withName("url").add(BLUE, UNDERLINE);

// Registering the classes to the context
context.add(text).add(title).add(url);

// Creating an AnsiScape instance with the custom context
AnsiScape ansiScape = new AnsiScape(context);

String fmt = "{title Chapter 1}\n" +
              "{text So it begins:}\n" +
              "- {text Option 1}\n" +
              "- {text Url: {url www.someurl.xyz}}";

System.out.println(ansiScape.format(fmt));
</code>```

Title: How to color System.out.println output?

Body:
How can I color Java output?

For example in C and other languages I can use ANSI-escape like \033[0m to do this. But in Java it doesn't work.

public static void main(String[] x) {
    System.out.println("\033[0m BLABLA \033[0m\n");
}

Body:
I've written a library called AnsiScape that allows you to write coloured output in a more structured way:

Example:

AnsiScape ansiScape = new AnsiScape();
String colors = ansiScape.format("{red {blueBg Red text with blue background}} {b Bold text}");
System.out.println(colors);

The library it also allows you to define your own "escape classes" akin to css classes.

Example:

AnsiScapeContext context = new AnsiScapeContext();

// Defines a "class" for text
AnsiClass text = AnsiClass.withName("text").add(RED);
// Defines a "class" for the title used
AnsiClass title = AnsiClass.withName("title").add(BOLD, BLUE_BG, YELLOW);
// Defines a "class" to render urls
AnsiClass url = AnsiClass.withName("url").add(BLUE, UNDERLINE);

// Registering the classes to the context
context.add(text).add(title).add(url);

// Creating an AnsiScape instance with the custom context
AnsiScape ansiScape = new AnsiScape(context);

String fmt = "{title Chapter 1}\n" +
              "{text So it begins:}\n" +
              "- {text Option 1}\n" +
              "- {text Url: {url www.someurl.xyz}}";

System.out.println(ansiScape.format(fmt));


问:
Scroll to the very bottom of UIScrollView when Keyboard appears (AutoLayout)
I am trying to scroll to the bottom content of the UIScrollView when the keyboard is shown, but the method setContentOffset doesnt seem to work. I am using AutoLayout on Interface Builder. Perhaps this is what causes the problem? Any thoughts?

How could I scroll to the bottom of my UIScrollView when my the keyboard is shown.

P.S.: It will show the textField just fine, what I need is to show the very bottom of the UIScrollView when the keyboard is shown

Thank You!!

Below is my current code

```<code>func textFieldDidBeginEditing(textField: UITextField) {
    var bottomOffset: CGPoint = CGPoint(x: 0, y: mainScrollView.contentSize.height - mainScrollView.bounds.size.height);
    mainScrollView.setContentOffset(bottomOffset, animated: true);
}

func keyboardDidShow(notification: NSNotification) {
    var userInfoDictionary: NSDictionary = notification.userInfo!;

    var keyboardSize: CGSize = userInfoDictionary.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size;

    var contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0);

    mainScrollView.contentInset = contentInsets;
    mainScrollView.scrollIndicatorInsets = contentInsets;
}

func keyboardWillHide(notification: NSNotification) {
    var contentInsets = UIEdgeInsetsZero;

    mainScrollView.contentInset = contentInsets;
    mainScrollView.scrollIndicatorInsets = contentInsets;
}
</code>```

答:
To me scrolling to the bottom of a scroll view means setting an offset equal to the total content height minus the actual scroll view height.

For instance, to scroll to the bottom of a UIScrollView when the keyboard appears I use the following code:

Objective-C

```<code>- (void)onKeyboardDidShow:(NSNotification *)notification {
    NSValue *value = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardHeight = value.CGRectValue.size.height;
    self.scrollViewBottomConstraint.constant = keyboardHeight;
    CGPoint offset = self.scrollView.contentOffset;
    CGFloat scrollViewHeight = self.scrollView.frame.size.height - keyboardHeight;
    offset.y = self.scrollView.contentSize.height - scrollViewHeight;
    [self.scrollView setContentOffset:offset animated:YES];
}
</code>```

Swift 3

```<code>func onKeyboardDidShow(notification: NSNotification) {
    if let value = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] {
        let keyboardHeight = (value as AnyObject).cgRectValue.size.height
        self.scrollViewBottomConstraint.constant = keyboardHeight
        var offset = self.scrollView.contentOffset
        let scrollViewHeight = self.scrollView.frame.size.height - keyboardHeight
        offset.y = self.scrollView.contentSize.height - scrollViewHeight
        self.scrollView.setContentOffset(offset, animated: true)
    }
}
</code>```

The bottom constraint is changed to the keyboard height when it appears and back to 0 when it disappears.

Interestingly the scroll view actual height is not just self.scrollView.frame.size.height (at least when the keyboard just appeared). I had to subtract the keyboard size to obtain the real value.

Body:
I am trying to scroll to the bottom content of the UIScrollView when the keyboard is shown, but the method setContentOffset doesnt seem to work. I am using AutoLayout on Interface Builder. Perhaps this is what causes the problem? Any thoughts?

How could I scroll to the bottom of my UIScrollView when my the keyboard is shown.

P.S.: It will show the textField just fine, what I need is to show the very bottom of the UIScrollView when the keyboard is shown

Thank You!!

Below is my current code

func textFieldDidBeginEditing(textField: UITextField) {
    var bottomOffset: CGPoint = CGPoint(x: 0, y: mainScrollView.contentSize.height - mainScrollView.bounds.size.height);
    mainScrollView.setContentOffset(bottomOffset, animated: true);
}

func keyboardDidShow(notification: NSNotification) {
    var userInfoDictionary: NSDictionary = notification.userInfo!;

    var keyboardSize: CGSize = userInfoDictionary.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size;

    var contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0);

    mainScrollView.contentInset = contentInsets;
    mainScrollView.scrollIndicatorInsets = contentInsets;
}

func keyboardWillHide(notification: NSNotification) {
    var contentInsets = UIEdgeInsetsZero;

    mainScrollView.contentInset = contentInsets;
    mainScrollView.scrollIndicatorInsets = contentInsets;
}

Body:
To me scrolling to the bottom of a scroll view means setting an offset equal to the total content height minus the actual scroll view height.

For instance, to scroll to the bottom of a UIScrollView when the keyboard appears I use the following code:

Objective-C

- (void)onKeyboardDidShow:(NSNotification *)notification {
    NSValue *value = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardHeight = value.CGRectValue.size.height;
    self.scrollViewBottomConstraint.constant = keyboardHeight;
    CGPoint offset = self.scrollView.contentOffset;
    CGFloat scrollViewHeight = self.scrollView.frame.size.height - keyboardHeight;
    offset.y = self.scrollView.contentSize.height - scrollViewHeight;
    [self.scrollView setContentOffset:offset animated:YES];
}

Swift 3

func onKeyboardDidShow(notification: NSNotification) {
    if let value = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] {
        let keyboardHeight = (value as AnyObject).cgRectValue.size.height
        self.scrollViewBottomConstraint.constant = keyboardHeight
        var offset = self.scrollView.contentOffset
        let scrollViewHeight = self.scrollView.frame.size.height - keyboardHeight
        offset.y = self.scrollView.contentSize.height - scrollViewHeight
        self.scrollView.setContentOffset(offset, animated: true)
    }
}

The bottom constraint is changed to the keyboard height when it appears and back to 0 when it disappears.

Interestingly the scroll view actual height is not just self.scrollView.frame.size.height (at least when the keyboard just appeared). I had to subtract the keyboard size to obtain the real value.


问:
how to handle execution timeout in flink
```<code>        Connected to JobManager at Actor[akka.tcp://flink@localhost:6123/user/jobmanager#-1119198862] with leader session id 00000000-0000-0000-0000-000000000000.
org.apache.flink.client.program.ProgramInvocationException: The program execution failed: Couldn't retrieve the JobExecutionResult from the JobManager.
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:478)
    at org.apache.flink.client.program.StandaloneClusterClient.submitJob(StandaloneClusterClient.java:105)
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:442)
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:429)
    at org.apache.flink.client.program.ContextEnvironment.execute(ContextEnvironment.java:62)
    at FileSetWordCount.main(FileSetWordCount.java:178)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:528)
    at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:419)
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:381)
    at org.apache.flink.client.CliFrontend.executeProgram(CliFrontend.java:838)
    at org.apache.flink.client.CliFrontend.run(CliFrontend.java:259)
    at org.apache.flink.client.CliFrontend.parseParameters(CliFrontend.java:1086)
    at org.apache.flink.client.CliFrontend$2.call(CliFrontend.java:1133)
    at org.apache.flink.client.CliFrontend$2.call(CliFrontend.java:1130)
    at org.apache.flink.runtime.security.HadoopSecurityContext$1.run(HadoopSecurityContext.java:43)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1556)
    at org.apache.flink.runtime.security.HadoopSecurityContext.runSecured(HadoopSecurityContext.java:40)
    at org.apache.flink.client.CliFrontend.main(CliFrontend.java:1130)
Caused by: org.apache.flink.runtime.client.JobExecutionException: Couldn't retrieve the JobExecutionResult from the JobManager.
    at org.apache.flink.runtime.client.JobClient.awaitJobResult(JobClient.java:309)
    at org.apache.flink.runtime.client.JobClient.submitJobAndWait(JobClient.java:396)
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:467)
    ... 23 more
Caused by: org.apache.flink.runtime.client.JobClientActorSubmissionTimeoutException: Job submission to the JobManager timed out. You may increase 'akka.client.timeout' in case the JobManager needs more time to configure and confirm the job submission.
    at org.apache.flink.runtime.client.JobSubmissionClientActor.handleCustomMessage(JobSubmissionClientActor.java:119)
    at org.apache.flink.runtime.client.JobClientActor.handleMessage(JobClientActor.java:251)
    at org.apache.flink.runtime.akka.FlinkUntypedActor.handleLeaderSessionID(FlinkUntypedActor.java:89)
    at org.apache.flink.runtime.akka.FlinkUntypedActor.onReceive(FlinkUntypedActor.java:68)
    at akka.actor.UntypedActor$$anonfun$receive$1.applyOrElse(UntypedActor.scala:167)
    at akka.actor.Actor$class.aroundReceive(Actor.scala:467)
    at akka.actor.UntypedActor.aroundReceive(UntypedActor.scala:97)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516)
    at akka.actor.ActorCell.invoke(ActorCell.scala:487)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:238)
    at akka.dispatch.Mailbox.run(Mailbox.scala:220)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:397)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
No JobSubmissionResult returned, please make sure you called ExecutionEnvironment.execute()
</code>```

This is an exception threw by Flink. How to handle the client timeout exception? This Flink application is going to run in the local envirionment. The application is used for about 1TB files processing.

答: I have figure it out. It is necessary to modify the 'flink-conf.yaml' file with adding a new line "akka.client.timeout: xx s"(e.g. "akka.client.timeout: 600 s"). </p>

Body:
        Connected to JobManager at Actor[akka.tcp://flink@localhost:6123/user/jobmanager#-1119198862] with leader session id 00000000-0000-0000-0000-000000000000.
org.apache.flink.client.program.ProgramInvocationException: The program execution failed: Couldn't retrieve the JobExecutionResult from the JobManager.
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:478)
    at org.apache.flink.client.program.StandaloneClusterClient.submitJob(StandaloneClusterClient.java:105)
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:442)
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:429)
    at org.apache.flink.client.program.ContextEnvironment.execute(ContextEnvironment.java:62)
    at FileSetWordCount.main(FileSetWordCount.java:178)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:528)
    at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:419)
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:381)
    at org.apache.flink.client.CliFrontend.executeProgram(CliFrontend.java:838)
    at org.apache.flink.client.CliFrontend.run(CliFrontend.java:259)
    at org.apache.flink.client.CliFrontend.parseParameters(CliFrontend.java:1086)
    at org.apache.flink.client.CliFrontend$2.call(CliFrontend.java:1133)
    at org.apache.flink.client.CliFrontend$2.call(CliFrontend.java:1130)
    at org.apache.flink.runtime.security.HadoopSecurityContext$1.run(HadoopSecurityContext.java:43)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1556)
    at org.apache.flink.runtime.security.HadoopSecurityContext.runSecured(HadoopSecurityContext.java:40)
    at org.apache.flink.client.CliFrontend.main(CliFrontend.java:1130)
Caused by: org.apache.flink.runtime.client.JobExecutionException: Couldn't retrieve the JobExecutionResult from the JobManager.
    at org.apache.flink.runtime.client.JobClient.awaitJobResult(JobClient.java:309)
    at org.apache.flink.runtime.client.JobClient.submitJobAndWait(JobClient.java:396)
    at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:467)
    ... 23 more
Caused by: org.apache.flink.runtime.client.JobClientActorSubmissionTimeoutException: Job submission to the JobManager timed out. You may increase 'akka.client.timeout' in case the JobManager needs more time to configure and confirm the job submission.
    at org.apache.flink.runtime.client.JobSubmissionClientActor.handleCustomMessage(JobSubmissionClientActor.java:119)
    at org.apache.flink.runtime.client.JobClientActor.handleMessage(JobClientActor.java:251)
    at org.apache.flink.runtime.akka.FlinkUntypedActor.handleLeaderSessionID(FlinkUntypedActor.java:89)
    at org.apache.flink.runtime.akka.FlinkUntypedActor.onReceive(FlinkUntypedActor.java:68)
    at akka.actor.UntypedActor$$anonfun$receive$1.applyOrElse(UntypedActor.scala:167)
    at akka.actor.Actor$class.aroundReceive(Actor.scala:467)
    at akka.actor.UntypedActor.aroundReceive(UntypedActor.scala:97)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516)
    at akka.actor.ActorCell.invoke(ActorCell.scala:487)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:238)
    at akka.dispatch.Mailbox.run(Mailbox.scala:220)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:397)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
No JobSubmissionResult returned, please make sure you called ExecutionEnvironment.execute()

This is an exception threw by Flink. How to handle the client timeout exception? This Flink application is going to run in the local envirionment. The application is used for about 1TB files processing.


问:
Shiny-server can't connect to PostgreSQL
I have a shiny dashboard on a Ubuntu server that connects to the 'local'  PostgreSQL db to collect data. It works perfectly well when I launch the dashboard from my R-Studio environment (on the same server), but the dashboard fails to load when I access it as a shiny-server dashboard. Every other dashboard works perfectly well, so I know shiny-server is functional. This is the only dashboard that connects to a potgres db though.

I managed to figure out it's the dbConnect function that creates the error. When I comment it out (and everything that depends on it), the dashboard loads (as a skeleton obviously).

When I access the shiny-server dashboard through http://serverIPAddress/dashboardName/, I get the following error:

```<code>ERROR: An error has occurred. Check your logs or contact the app author for clarification.
</code>```

And this is the log file:

```<code>Error in ans[!test & ok] <- rep(no, length.out = length(ans))[!test &:
  replacement has length zero
Calls: <Anonymous> -> ifelse
In addition: Warning message:
In rep(no, length.out = length(ans)) :
  'x' is NULL so the result will be NULL
Execution halted
</code>```

My suspicion is that shiny-server can't access the postgres db, even though root can. Has anyone experience this problem before?

Thanks

EDIT: adding parts of my code. It's only the top bits, but you get the idea. The error goes away when I comment out the dbDriver and src_postgres functions

ui.R

```<code>library(shiny)
library(dplyr)
library(RPostgreSQL)
library(magrittr)
library(leaflet)
library(tidyr)

drv <- dbDriver("PostgreSQL")
con <- src_postgres(dbname = "sandtonrelocation")

travelEventTransactional <-  tbl(con, "travel_event_transactional")

# for the next two connections, the inner join section is to only
  select the latest entry

employeeData <-
  tbl(con, "employee_data") %>%
  inner_join(tbl(con, "employee_data")  %>%
               group_by(employee_id) %>%
               summarise(date_added = max(date_added)),
                 by = c("employee_id", "date_added"))

employeeAddressData <-
  tbl(con, "employee_address_data") %>%
  inner_join(tbl(con, "employee_address_data")  %>%
               group_by(employee_id) %>%
               summarise(date_added = max(date_added)),
             by = c("employee_id", "date_added"))

# UI start ====
shinyUI(fluidPage(

  # title ====
  titlePanel("Sandton relocation impact study"),

  # sidebar ====
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "businessUnitId",
                  label = "Select business unit",
                  choices = c("All", employeeData %>%
                                select(business_unit) %>%
                                distinct  %>%
                                arrange(business_unit) %>%
                                collect %$%
                                business_unit),
                  selected = "CPS"),
</code>```

and so on

server.R

```<code>  library(shiny)
  library(dplyr)
  library(RPostgreSQL)
  library(magrittr)
  library(leaflet)
  library(leaflet.extras)
  library(ggplot2)
  library(rlang)

  source('./lib/mulitplot.R')
  source('./lib/compareScenarios.R')
  source('./lib/maritalStatus.R')
  source('./lib/extra_dfs.R')

  ## connect to DB =====
  drv <- dbDriver("PostgreSQL")
  con <- src_postgres(dbname = "sandtonrelocation")
  travelEventTransactional <-  tbl(con, "travel_event_transactional")

  # for the next two connections, the inner join section is to only select the
  # latest entry
  employeeData <-
    tbl(con, "employee_data") %>%
    inner_join(tbl(con, "employee_data")  %>%
                 group_by(employee_id) %>%
                 summarise(date_added = max(date_added)),
               by = c("employee_id", "date_added"))

  employeeAddressData <-
    tbl(con, "employee_address_data") %>%
    inner_join(tbl(con, "employee_address_data")  %>%
                 group_by(employee_id) %>%
                 summarise(date_added = max(date_added)),
               by = c("employee_id", "date_added"))

  ## leaflet map object ====
  gautrainIcon <- makeIcon(
    iconUrl = "./images/Gautrain.png",
    iconWidth = 10, iconHeight = 10
  )

  mmiIcon <- makeIcon(
    iconUrl = "./images/Map-Icons-02.png",
    iconWidth = 22.5, iconHeight = 22.5
  )

  m <-
    leaflet() %>%
    fitBounds(
      lng1 = 27.8,
      lat1 = -26.3,
      lng2 = 28.42,
      lat2 = -25.66
    ) %>%
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
    addMarkers(lat = -25.8537801, lng = 28.1919999,
               labelOptions = labelOptions(noHide = T, textOnly = TRUE,
                                           style = list(color = 'red')),
               icon=mmiIcon) %>%
    addMarkers(lat = -26.10306, lng = 28.060131,
               labelOptions = labelOptions(noHide = T, textOnly = TRUE,
                                           style = list(color = 'red')),
               icon=mmiIcon)

  ## Shiny server start ====
  shinyServer(function(input, output) {

    # DF deltaTravelReactive ====
    deltaTravelReactive <- reactive({

      travelEventTransactionalScenario <-
        if(input$selectScenario == "Everyone relocates")  {
          travelEventTransactional %>% collect() %>%
            filter(work_location %in% c("current", "MARC"))
        } else {
          travelEventTransactional %>%
            collect() %>%
            left_join(read.csv(paste("./scenarios/",
                                     input$selectScenario,
                                     ".csv",
                                     sep = "")),
                      by = c("employee_id" = "Employee.ID"), copy = T) %>%
            mutate(Future.occupancy = ifelse(Future.occupancy == "Sandton", "MARC",
                                             ifelse(Future.occupancy == "Centurion", "Centurion Main Building"))) %>%
            filter((work_location == "current") |
                     work_location == Future.occupancy) %>%
            select(-Future.occupancy) %>%
            ungroup
        }

      travelEventTransactionalSubset <-
        travelEventTransactionalScenario %>%
        left_join(employeeData %>%
                    select(employee_id,
                           age, gender,
                           business_unit,
                           children,
                           marital_status,
                           rem_bin),
                  by = 'employee_id', copy = T) %>%
        filter(if(input$businessUnitId == "All") {event_id > 0} else {
          business_unit == input$businessUnitId
        }) %$%
        mutate(.,
               marital_status = sapply(marital_status,
                                       function(x) mapMaritalStatus(x)),
               children = sapply(children,
                                 function(x) if(x == T | x > 0) T else F))

      # cheap escape, fix this later on
      if(length(travelEventTransactionalSubset$work_location %>% unique) == 1) {
        -1
      } else {

        compareScenarios(travelEventTransactionalSubset,
                         "travel_time_car") %>%
          left_join(compareScenarios(travelEventTransactionalSubset,
                                     "travel_cost_car"),
                    by = c("employee_id", "children", "marital_status")) %>%
          left_join(compareScenarios(travelEventTransactionalSubset,
                                     "travel_time_gautrain"),
                    by = c("employee_id", "children", "marital_status")) %>%
          left_join(compareScenarios(travelEventTransactionalSubset,
                                     "travel_cost_gautrain"),
                    by = c("employee_id", "children", "marital_status")) %>%
          left_join(employeeData %>% select(employee_id,rem_bin), copy = T,
                    by = "employee_id") %>%
          mutate(current_train_faster = current_travel_time_car > current_travel_time_gautrain &
                   current_travel_time_gautrain != 0,
                 current_train_cheaper = current_travel_cost_car > current_travel_cost_gautrain &
                   current_travel_time_gautrain != 0,
                 future_train_faster = future_travel_time_car > future_travel_time_gautrain &
                   future_travel_time_gautrain != 0,
                 future_train_cheaper = future_travel_cost_car > future_travel_cost_gautrain &
                   future_travel_time_gautrain != 0,
                 delta_cost_car = future_travel_cost_car - current_travel_cost_car,
                 delta_time_car = future_travel_time_car - current_travel_time_car)
      }

    })

    # PLOT deltaDriveTime ====
    output$deltaDriveTime <- renderPlot({

      deltaTravel <- deltaTravelReactive()

      if(deltaTravel == -1) {
        ggplot() +
          geom_text(aes(x = 0, y = 0,
                        label = paste('No change for', input$businessUnitId)), col = 'dodgerblue3', size = 9) +
          theme_minimal() %+replace%
          theme(axis.text = element_blank(),
                axis.title = element_blank())
      } else {

        deltaTravel%>%
          mutate(deltaTimeCar = future_travel_time_car - current_travel_time_car) %>%
          ggplot() +
          geom_histogram(aes(x = deltaTimeCar), binwidth = input$binSizeTime,
                         fill = 'dodgerblue',col = 'dodgerblue',
                         alpha = .85) +
          stat_bin(aes(x = deltaTimeCar,
                       label = scales::percent(..count../sum(..count..))),
                   geom = 'text', binwidth = input$binSizeTime, size = 3, vjust = -1) +
          theme_minimal() %+replace%
          theme(plot.title = element_text(size = 12),
                axis.title.y = element_blank(),
                axis.text.y = element_blank()) +
          xlab("Time") +
          ggtitle("Increase in travel time after moving to MARC")
      }
    })
</code>```

答:
Seems like it was an issue with rights. Shiny-server does not connect to psql as root, but as shiny.

All I had to do was add shiny as a role to psql and give it login rights.

```<code>create role shiny;
alter user shiny with login;
</code>```

Problem solved :)

Body:
I have a shiny dashboard on a Ubuntu server that connects to the 'local'  PostgreSQL db to collect data. It works perfectly well when I launch the dashboard from my R-Studio environment (on the same server), but the dashboard fails to load when I access it as a shiny-server dashboard. Every other dashboard works perfectly well, so I know shiny-server is functional. This is the only dashboard that connects to a potgres db though.

I managed to figure out it's the dbConnect function that creates the error. When I comment it out (and everything that depends on it), the dashboard loads (as a skeleton obviously).

When I access the shiny-server dashboard through http://serverIPAddress/dashboardName/, I get the following error:

ERROR: An error has occurred. Check your logs or contact the app author for clarification.

And this is the log file:

Error in ans[!test & ok] <- rep(no, length.out = length(ans))[!test &:
  replacement has length zero
Calls: <Anonymous> -> ifelse
In addition: Warning message:
In rep(no, length.out = length(ans)) :
  'x' is NULL so the result will be NULL
Execution halted

My suspicion is that shiny-server can't access the postgres db, even though root can. Has anyone experience this problem before?

Thanks

EDIT: adding parts of my code. It's only the top bits, but you get the idea. The error goes away when I comment out the dbDriver and src_postgres functions

ui.R

library(shiny)
library(dplyr)
library(RPostgreSQL)
library(magrittr)
library(leaflet)
library(tidyr)

drv <- dbDriver("PostgreSQL")
con <- src_postgres(dbname = "sandtonrelocation")

travelEventTransactional <-  tbl(con, "travel_event_transactional")

# for the next two connections, the inner join section is to only
  select the latest entry

employeeData <-
  tbl(con, "employee_data") %>%
  inner_join(tbl(con, "employee_data")  %>%
               group_by(employee_id) %>%
               summarise(date_added = max(date_added)),
                 by = c("employee_id", "date_added"))

employeeAddressData <-
  tbl(con, "employee_address_data") %>%
  inner_join(tbl(con, "employee_address_data")  %>%
               group_by(employee_id) %>%
               summarise(date_added = max(date_added)),
             by = c("employee_id", "date_added"))

# UI start ====
shinyUI(fluidPage(

  # title ====
  titlePanel("Sandton relocation impact study"),

  # sidebar ====
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "businessUnitId",
                  label = "Select business unit",
                  choices = c("All", employeeData %>%
                                select(business_unit) %>%
                                distinct  %>%
                                arrange(business_unit) %>%
                                collect %$%
                                business_unit),
                  selected = "CPS"),

and so on

server.R

  library(shiny)
  library(dplyr)
  library(RPostgreSQL)
  library(magrittr)
  library(leaflet)
  library(leaflet.extras)
  library(ggplot2)
  library(rlang)

  source('./lib/mulitplot.R')
  source('./lib/compareScenarios.R')
  source('./lib/maritalStatus.R')
  source('./lib/extra_dfs.R')

  ## connect to DB =====
  drv <- dbDriver("PostgreSQL")
  con <- src_postgres(dbname = "sandtonrelocation")
  travelEventTransactional <-  tbl(con, "travel_event_transactional")

  # for the next two connections, the inner join section is to only select the
  # latest entry
  employeeData <-
    tbl(con, "employee_data") %>%
    inner_join(tbl(con, "employee_data")  %>%
                 group_by(employee_id) %>%
                 summarise(date_added = max(date_added)),
               by = c("employee_id", "date_added"))

  employeeAddressData <-
    tbl(con, "employee_address_data") %>%
    inner_join(tbl(con, "employee_address_data")  %>%
                 group_by(employee_id) %>%
                 summarise(date_added = max(date_added)),
               by = c("employee_id", "date_added"))

  ## leaflet map object ====
  gautrainIcon <- makeIcon(
    iconUrl = "./images/Gautrain.png",
    iconWidth = 10, iconHeight = 10
  )

  mmiIcon <- makeIcon(
    iconUrl = "./images/Map-Icons-02.png",
    iconWidth = 22.5, iconHeight = 22.5
  )

  m <-
    leaflet() %>%
    fitBounds(
      lng1 = 27.8,
      lat1 = -26.3,
      lng2 = 28.42,
      lat2 = -25.66
    ) %>%
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
    addMarkers(lat = -25.8537801, lng = 28.1919999,
               labelOptions = labelOptions(noHide = T, textOnly = TRUE,
                                           style = list(color = 'red')),
               icon=mmiIcon) %>%
    addMarkers(lat = -26.10306, lng = 28.060131,
               labelOptions = labelOptions(noHide = T, textOnly = TRUE,
                                           style = list(color = 'red')),
               icon=mmiIcon)

  ## Shiny server start ====
  shinyServer(function(input, output) {

    # DF deltaTravelReactive ====
    deltaTravelReactive <- reactive({

      travelEventTransactionalScenario <-
        if(input$selectScenario == "Everyone relocates")  {
          travelEventTransactional %>% collect() %>%
            filter(work_location %in% c("current", "MARC"))
        } else {
          travelEventTransactional %>%
            collect() %>%
            left_join(read.csv(paste("./scenarios/",
                                     input$selectScenario,
                                     ".csv",
                                     sep = "")),
                      by = c("employee_id" = "Employee.ID"), copy = T) %>%
            mutate(Future.occupancy = ifelse(Future.occupancy == "Sandton", "MARC",
                                             ifelse(Future.occupancy == "Centurion", "Centurion Main Building"))) %>%
            filter((work_location == "current") |
                     work_location == Future.occupancy) %>%
            select(-Future.occupancy) %>%
            ungroup
        }

      travelEventTransactionalSubset <-
        travelEventTransactionalScenario %>%
        left_join(employeeData %>%
                    select(employee_id,
                           age, gender,
                           business_unit,
                           children,
                           marital_status,
                           rem_bin),
                  by = 'employee_id', copy = T) %>%
        filter(if(input$businessUnitId == "All") {event_id > 0} else {
          business_unit == input$businessUnitId
        }) %$%
        mutate(.,
               marital_status = sapply(marital_status,
                                       function(x) mapMaritalStatus(x)),
               children = sapply(children,
                                 function(x) if(x == T | x > 0) T else F))

      # cheap escape, fix this later on
      if(length(travelEventTransactionalSubset$work_location %>% unique) == 1) {
        -1
      } else {

        compareScenarios(travelEventTransactionalSubset,
                         "travel_time_car") %>%
          left_join(compareScenarios(travelEventTransactionalSubset,
                                     "travel_cost_car"),
                    by = c("employee_id", "children", "marital_status")) %>%
          left_join(compareScenarios(travelEventTransactionalSubset,
                                     "travel_time_gautrain"),
                    by = c("employee_id", "children", "marital_status")) %>%
          left_join(compareScenarios(travelEventTransactionalSubset,
                                     "travel_cost_gautrain"),
                    by = c("employee_id", "children", "marital_status")) %>%
          left_join(employeeData %>% select(employee_id,rem_bin), copy = T,
                    by = "employee_id") %>%
          mutate(current_train_faster = current_travel_time_car > current_travel_time_gautrain &
                   current_travel_time_gautrain != 0,
                 current_train_cheaper = current_travel_cost_car > current_travel_cost_gautrain &
                   current_travel_time_gautrain != 0,
                 future_train_faster = future_travel_time_car > future_travel_time_gautrain &
                   future_travel_time_gautrain != 0,
                 future_train_cheaper = future_travel_cost_car > future_travel_cost_gautrain &
                   future_travel_time_gautrain != 0,
                 delta_cost_car = future_travel_cost_car - current_travel_cost_car,
                 delta_time_car = future_travel_time_car - current_travel_time_car)
      }

    })

    # PLOT deltaDriveTime ====
    output$deltaDriveTime <- renderPlot({

      deltaTravel <- deltaTravelReactive()

      if(deltaTravel == -1) {
        ggplot() +
          geom_text(aes(x = 0, y = 0,
                        label = paste('No change for', input$businessUnitId)), col = 'dodgerblue3', size = 9) +
          theme_minimal() %+replace%
          theme(axis.text = element_blank(),
                axis.title = element_blank())
      } else {

        deltaTravel%>%
          mutate(deltaTimeCar = future_travel_time_car - current_travel_time_car) %>%
          ggplot() +
          geom_histogram(aes(x = deltaTimeCar), binwidth = input$binSizeTime,
                         fill = 'dodgerblue',col = 'dodgerblue',
                         alpha = .85) +
          stat_bin(aes(x = deltaTimeCar,
                       label = scales::percent(..count../sum(..count..))),
                   geom = 'text', binwidth = input$binSizeTime, size = 3, vjust = -1) +
          theme_minimal() %+replace%
          theme(plot.title = element_text(size = 12),
                axis.title.y = element_blank(),
                axis.text.y = element_blank()) +
          xlab("Time") +
          ggtitle("Increase in travel time after moving to MARC")
      }
    })

Body:
Seems like it was an issue with rights. Shiny-server does not connect to psql as root, but as shiny.

All I had to do was add shiny as a role to psql and give it login rights.

create role shiny;
alter user shiny with login;

Problem solved :)


问:
Terminology when copying the captured variable for a lambda/ anon-method
I translated this code(it has bad side effect that it just capture the outer variable):

```<code>foreach (TaskPluginInfo tpi in Values)
{
    GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { tpi.ShowTask() });
}
</code>```

To this code(because the above is not working):

```<code>foreach (TaskPluginInfo tpi in Values)
{
    // must capture the variable
    var x = tpi;
    GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { x.ShowTask(); });
}
</code>```

What's the correct terminology for that work-around on that little known side effect?  For now, I commented "must capture the variable."  Is the word capture, the correct terminology?

答: "assign the iteration variable to a local variable that's scoped inside the loop"</p>

ContentLicense: CC BY-SA 2.5

Body:
I translated this code(it has bad side effect that it just capture the outer variable):

foreach (TaskPluginInfo tpi in Values)
{
    GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { tpi.ShowTask() });
}

To this code(because the above is not working):

foreach (TaskPluginInfo tpi in Values)
{
    // must capture the variable
    var x = tpi;
    GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { x.ShowTask(); });
}

What's the correct terminology for that work-around on that little known side effect?  For now, I commented "must capture the variable."  Is the word capture, the correct terminology?


问:
How to get all messages using method consume in lib amqp.node?
Greeting guys.

Can you help me with asynchronnous in node.js?

Problem this:

I'm use amqplib module for work with RabbitMQ and here there method consume, who gives messages from RabbitMQ, but that method first return promise about he starts and after this promise starts, he call callbacks to get data from RabbitMQ, and i dont know how to catch when all messages will be send to my node js app.

For more explain, here my code and at end code at comments i wrote what i want:

```<code>/**
 * Here my test code
 *
 * requirng amqp.node lib
 */
let amqp = require('amqplib')
  , configConnection = { /* ..config options */ }
  , queue = 'users'
  , exchange = 'users.exchange'
  , type = 'fanout'

/**
 * declare annonymous function as async and immediately called it
 */
(async () => {
  /**
   * declare connection and channel with using async/await construction
   * who support version node.js >= 8.5.0
   */
  let conn = await amqp.connect(configConnection)
  let channel = await conn.createChannel()
  await channel.assertExchange(exchange, type)
  let response = await channel.assertQueue(queue)
  /**
   * response: { queue: 'users', messageCount: 10, consumerCount: 0 }
   */
  response = await channel.bindQueue(response.queue, exchange, '')
  response = await channel.consume(response.queue, logMessage, {noAck: false})
  /**
   * {noAck: false} false for not expect an acknowledgement
   */
  console.log('reading for query finish')

  function logMessage(msg) {
    console.log("[*] recieved: '%s'", msg.content.toString())
  }
})()
  /**
   * output will show:
   * reading for query finish
   * [*] recieved: 'message content'
   * [*] recieved: 'message content'
   * [*] recieved: 'message content'
   * ...
   *
   * But i'm need show message 'reading for query finish' after when
   * all consumes will executed
   *
   * Ask: How i can do this?
   */
</code>```

答:
I found answer on my question here.

Answer in use: EventEmitter && Promise

magic (for me) is here:

await new Promise(resolve => eventEmitter.once('consumeDone', resolve))

So ended code is:

```<code>/**
 * Here my test code
 *
 * requirng amqp.node lib
 */
let amqp = require('amqplib')
  , EventEmitter = require('events')
  , eventEmitter = new EventEmitter()
  , timeout = 10000
  , configConnection = { /* ..config options */ }
  , queue = 'users'
  , exchange = 'users.exchange'
  , type = 'fanout'

/**
 * declare annonymous function as async and immediately called it
 */
(async () => {
  /**
   * declare connection and channel with using async/await construction
   * who support version node.js >= 8.5.0
   */
  let conn = await amqp.connect(configConnection)
  let channel = await conn.createChannel()
  await channel.assertExchange(exchange, type)
  let response = await channel.assertQueue(queue)
  /**
   * response: { queue: 'users', messageCount: 10, consumerCount: 0 }
   */
  let messageCount = response.messageCount
  response = await channel.bindQueue(response.queue, exchange, '')
  response = await channel.consume(response.queue, logMessage(messageCount), {noAck: false})
  /**
   * {noAck: false} false for not expect an acknowledgement
   */

  /**
   * declare timeout if we have problems with emit event in consume
   * we waiting when event will be emit once 'consumeDone' and promise gain resolve
   * so we can go to the next step
   */
  setTimeout(() => eventEmitter.emit('consumeDone'), timeout)
  await new Promise(resolve => eventEmitter.once('consumeDone', resolve))
  console.log('reading for query finish')

  function logMessage(messageCount) {
    return msg => {
      console.log("[*] recieved: '%s'", msg.content.toString())
      if (messageCount == msg.fields.deliveryTag) {
        eventEmitter.emit('consumeDone')
      }
    }

  }
})()
</code>```

Body:
Greeting guys.

Can you help me with asynchronnous in node.js?

Problem this:

I'm use amqplib module for work with RabbitMQ and here there method consume, who gives messages from RabbitMQ, but that method first return promise about he starts and after this promise starts, he call callbacks to get data from RabbitMQ, and i dont know how to catch when all messages will be send to my node js app.

For more explain, here my code and at end code at comments i wrote what i want:

/**
 * Here my test code
 *
 * requirng amqp.node lib
 */
let amqp = require('amqplib')
  , configConnection = { /* ..config options */ }
  , queue = 'users'
  , exchange = 'users.exchange'
  , type = 'fanout'

/**
 * declare annonymous function as async and immediately called it
 */
(async () => {
  /**
   * declare connection and channel with using async/await construction
   * who support version node.js >= 8.5.0
   */
  let conn = await amqp.connect(configConnection)
  let channel = await conn.createChannel()
  await channel.assertExchange(exchange, type)
  let response = await channel.assertQueue(queue)
  /**
   * response: { queue: 'users', messageCount: 10, consumerCount: 0 }
   */
  response = await channel.bindQueue(response.queue, exchange, '')
  response = await channel.consume(response.queue, logMessage, {noAck: false})
  /**
   * {noAck: false} false for not expect an acknowledgement
   */
  console.log('reading for query finish')

  function logMessage(msg) {
    console.log("[*] recieved: '%s'", msg.content.toString())
  }
})()
  /**
   * output will show:
   * reading for query finish
   * [*] recieved: 'message content'
   * [*] recieved: 'message content'
   * [*] recieved: 'message content'
   * ...
   *
   * But i'm need show message 'reading for query finish' after when
   * all consumes will executed
   *
   * Ask: How i can do this?
   */

Body:
I found answer on my question here.

Answer in use: EventEmitter && Promise

magic (for me) is here:

await new Promise(resolve => eventEmitter.once('consumeDone', resolve))

So ended code is:

/**
 * Here my test code
 *
 * requirng amqp.node lib
 */
let amqp = require('amqplib')
  , EventEmitter = require('events')
  , eventEmitter = new EventEmitter()
  , timeout = 10000
  , configConnection = { /* ..config options */ }
  , queue = 'users'
  , exchange = 'users.exchange'
  , type = 'fanout'

/**
 * declare annonymous function as async and immediately called it
 */
(async () => {
  /**
   * declare connection and channel with using async/await construction
   * who support version node.js >= 8.5.0
   */
  let conn = await amqp.connect(configConnection)
  let channel = await conn.createChannel()
  await channel.assertExchange(exchange, type)
  let response = await channel.assertQueue(queue)
  /**
   * response: { queue: 'users', messageCount: 10, consumerCount: 0 }
   */
  let messageCount = response.messageCount
  response = await channel.bindQueue(response.queue, exchange, '')
  response = await channel.consume(response.queue, logMessage(messageCount), {noAck: false})
  /**
   * {noAck: false} false for not expect an acknowledgement
   */

  /**
   * declare timeout if we have problems with emit event in consume
   * we waiting when event will be emit once 'consumeDone' and promise gain resolve
   * so we can go to the next step
   */
  setTimeout(() => eventEmitter.emit('consumeDone'), timeout)
  await new Promise(resolve => eventEmitter.once('consumeDone', resolve))
  console.log('reading for query finish')

  function logMessage(messageCount) {
    return msg => {
      console.log("[*] recieved: '%s'", msg.content.toString())
      if (messageCount == msg.fields.deliveryTag) {
        eventEmitter.emit('consumeDone')
      }
    }

  }
})()


问:
Determine which DLL and/or OCX files are actually used by my program?
My software is written in VB6. For diagnostic purposes I need to determine the actual DLL / OCX files which are loaded and used by the application on a customer's computer.

Since VB6 DLLs (including OCX files) are COM libraries they are loaded indirectly based on information in the registry. This means it is possible that a different file is being used than what was used in development / testing environments. Sometimes in a client environment this can cause malfunctions which are hard to diagnose without this information.

(My plan is to build a diagnostic readout window in my program that shows the libraries that the program is using at that moment.)

答:
You can use the Dependency Walker to find which DLL your program depend on.

But the OCX are not so easy to find because they are loaded at run-time based on the application dependencies and the registered components through the Windows registry. But you have to already know which OCX components your application references - from the Tools > References and all the places you call CreateObject.

ContentLicense: CC BY-SA 4.0


问:
How to compare Character for empty space
I need to check if a Character is a space, how do you do that?</p>

```<code>for (index, val) in (self.textField.text?.enumerated())! {
  if val == " " { // How?
    if index % 2 == 0 {
      // ...
    }
  }
}
</code>```

答:
In Swift, You can iterate directly over a String</p>

```<code>   let phrase = "Hello, This is Test String."
        for chr in phrase {
            if chr == " " {
                print("White space")
            }
        }
</code>```

Body:
I need to check if a Character is a space, how do you do that?

for (index, val) in (self.textField.text?.enumerated())! {
  if val == " " { // How?
    if index % 2 == 0 {
      // ...
    }
  }
}

Body:
In Swift, You can iterate directly over a String

   let phrase = "Hello, This is Test String."
        for chr in phrase {
            if chr == " " {
                print("White space")
            }
        }


问:
How can I show line numbers in Code tab of Talend?
Whenever I click on the Code tab to see the Java code of Talend job, I never see see the line numbers. Is there any settings to enable line numbers?</p>

答:
You can enable line numbers from Preferences

You will see a parameter for Show line numbers if you follow this breadcrumb -

Window > Preferences > General > Editors > Text Editors


问:
jQuery animate on previously appended div
I'm trying to animate a div that I previously appended, but the animation doesn't happen, even though the complete function is executed.

Here is a very simple example:

EDIT: I corrected the typo in my jsFiddle and the problem is still there, but thank you for pointing it out.

HTML:

```<code><button id="test">
    Go
</button>
<div class="elements">
</div>
</code>```

JS:

```<code>$('#test').click(function(){
  $("<div class='element-test'><img src='https://image.flaticon.com/icons/png/128/148/148836.png' style='position:absolute; z-index:40; top:400px; left:200px; width:2%;'></div>")
  .appendTo('.elements').animate({top:'100px', left:'400px'}, 500, function(){
      $('.element-test').fadeOut(200);
    });
});
</code>```

I wrote a jsFiddle showing the problem.

In my application, I would need to animate this with % positions, and I thought that was the problem in the beginning. However, changing it to pixel positions or even pure int numbers in the animate parameters doesn't solve it.

At the beginning, I was using .append() and then animate(). The idea of using appendTo().animate() comes from there.

答:
You made a mistake in typing:

You used top:100px' instead of top:'100px'

Here is correct code:

```<code>$('#test').click(function(){
  $("<div class='element-test'><img src='https://image.flaticon.com/icons/png/128/148/148836.png' style='position:absolute; z-index:40; top:400px; left:200px; width:2%;'></div>").appendTo('.elements').animate({top:'100px', left:'400px'}, 500, function(){
    $('.element-test').fadeOut(200);
  });
});
</code>```

Here is JSBin showing you how to append and animate, adjust your code to it:
http://jsbin.com/wotafijiru/edit?html,js,output

Body:
I'm trying to animate a div that I previously appended, but the animation doesn't happen, even though the complete function is executed.

Here is a very simple example:

EDIT: I corrected the typo in my jsFiddle and the problem is still there, but thank you for pointing it out.

HTML:

<button id="test">
    Go
</button>

JS:

$('#test').click(function(){
  $("

")
  .appendTo('.elements').animate({top:'100px', left:'400px'}, 500, function(){
      $('.element-test').fadeOut(200);
    });
});

I wrote a jsFiddle showing the problem.

In my application, I would need to animate this with % positions, and I thought that was the problem in the beginning. However, changing it to pixel positions or even pure int numbers in the animate parameters doesn't solve it.

At the beginning, I was using .append() and then animate(). The idea of using appendTo().animate() comes from there.

Body:
You made a mistake in typing:

You used top:100px' instead of top:'100px'

Here is correct code:

$('#test').click(function(){
  $("<div class='element-test'><img src='https://image.flaticon.com/icons/png/128/148/148836.png' style='position:absolute; z-index:40; top:400px; left:200px; width:2%;'></div>").appendTo('.elements').animate({top:'100px', left:'400px'}, 500, function(){
    $('.element-test').fadeOut(200);
  });
});

Here is JSBin showing you how to append and animate, adjust your code to it:
http://jsbin.com/wotafijiru/edit?html,js,output


问:
Java: duplicate method signature in nested class
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

```<code>class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}
</code>```

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

答:
At first method signature is not the combination of return type and method name it is method name and parameters.

if you call x() it will run x() inside the B

A.this.x(); it will run x() in A

Body:
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.


问:
Mutex for two threads in C++
I've created two threads that use a variable declared in main via pthread_create's last argument. I want thread2  to use modify the value of that variable after thread1 is done with a set of particular instructions. I know how we can use mutex in one thread but how about two or more threads?
Refer to the following code:</p>

```<code>#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM 6
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *even(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( !(i % 2) )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Even Thread: " << sum << endl;
    pthread_mutex_lock(&mutex);
    *((int*)arg) = sum;
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond);
}
void *odd(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( i % 2 )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Odd Thread: " << sum << endl;
    pthread_cond_wait(&cond, &mutex);
    *((int*)arg) = *((int*)arg) + sum;
}

int main()
{
    int mainSum = 0;
    pthread_t tidO, tidE;
    pthread_create(&tidO, NULL, odd, (void *)&mainSum);
    pthread_create(&tidE, NULL, even, (void *)&mainSum);
    pthread_join(tidO, NULL);
    pthread_join(tidE, NULL);
    cout << "Sum of first " << NUM << " Natural Numbers: " << mainSum << endl;
    return 0;
}
</code>```

答:
You should create mutex in same place as shared variable. In your case it is main function.
Then you need to share this mutex in all threads which are accessing shared variable.

You can share this mutex over global variable or better in same attribute as shared variable. But you will have to define structure where you place variable and mutex together.

Update

You should lock mutex pthread_mutex_lock(&mutex); before pthread_cond_wait(&cond, &mutex);

The pthread_cond_signal() and pthread_cond_broadcast() functions have no effect if there are no threads currently blocked on cond.

Title: Mutex for two threads in C++

Body:
I've created two threads that use a variable declared in main via pthread_create's last argument. I want thread2  to use modify the value of that variable after thread1 is done with a set of particular instructions. I know how we can use mutex in one thread but how about two or more threads?
Refer to the following code:

#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM 6
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *even(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( !(i % 2) )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Even Thread: " << sum << endl;
    pthread_mutex_lock(&mutex);
    *((int*)arg) = sum;
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond);
}
void *odd(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( i % 2 )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Odd Thread: " << sum << endl;
    pthread_cond_wait(&cond, &mutex);
    *((int*)arg) = *((int*)arg) + sum;
}

int main()
{
    int mainSum = 0;
    pthread_t tidO, tidE;
    pthread_create(&tidO, NULL, odd, (void *)&mainSum);
    pthread_create(&tidE, NULL, even, (void *)&mainSum);
    pthread_join(tidO, NULL);
    pthread_join(tidE, NULL);
    cout << "Sum of first " << NUM << " Natural Numbers: " << mainSum << endl;
    return 0;
}


问:
Twilio.Device.setup(token) is throwing exception. Twilio js version 1.4
I am using Twilio api for developing a video calling web app. Web app is responsive and can be used on mobile device to make video calls.
But when I open my web page on mobile device browser it is not using loudspeaker by default.
As per Twilio API Doc we can use Twilio.Device object to set loudspeaker as default. I am stucked on below code, where it is throwing exception followed by the code.

```<code>Twilio.Device.setup(token)

Uncaught TypeError: Cannot read property 'length' of undefined
    at twilio.min.js:182
    at Object.objectize (twilio.min.js:179)
    at a.register (twilio.min.js:80)
    at new a (twilio.min.js:76)
    at Function.setup (twilio.min.js:90)
    at Object.success (index.js:159)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)
</code>```

Twilio team please help ...

答:
This help page did it for me: https://www.twilio.com/docs/tutorials/browser-calls-csharp-mvc#make-a-dashboard-for-our-support-agents

Where I was using Claims before, it was scopes that got it working

```<code>var scopes = new HashSet<IScope>
{
    new IncomingClientScope(identity),
    new OutgoingClientScope(appSid)
};
var capability = new Twilio.Jwt.ClientCapability(accountSid, authToken, scopes: scopes);
var token = capability.ToJwt();
</code>```

I was using this before,
    capability.Claims.Add("allow_client_outgoing", appSid);
    capability.Claims.Add("allow_client_incoming", identity);

My code is for allowing incoming and outgoing voice calls. But its likely similar for your video calls.

Body:
I am using Twilio api for developing a video calling web app. Web app is responsive and can be used on mobile device to make video calls.
But when I open my web page on mobile device browser it is not using loudspeaker by default.
As per Twilio API Doc we can use Twilio.Device object to set loudspeaker as default. I am stucked on below code, where it is throwing exception followed by the code.

Twilio.Device.setup(token)

Uncaught TypeError: Cannot read property 'length' of undefined
    at twilio.min.js:182
    at Object.objectize (twilio.min.js:179)
    at a.register (twilio.min.js:80)
    at new a (twilio.min.js:76)
    at Function.setup (twilio.min.js:90)
    at Object.success (index.js:159)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

Twilio team please help ...

Body:
This help page did it for me: https://www.twilio.com/docs/tutorials/browser-calls-csharp-mvc#make-a-dashboard-for-our-support-agents

Where I was using Claims before, it was scopes that got it working

var scopes = new HashSet<IScope>
{
    new IncomingClientScope(identity),
    new OutgoingClientScope(appSid)
};
var capability = new Twilio.Jwt.ClientCapability(accountSid, authToken, scopes: scopes);
var token = capability.ToJwt();

I was using this before,
    capability.Claims.Add("allow_client_outgoing", appSid);
    capability.Claims.Add("allow_client_incoming", identity);

My code is for allowing incoming and outgoing voice calls. But its likely similar for your video calls.


问:
C# rounding differently depending on platform?
I have this tiny piece of code

```<code>double s = -2.6114289999999998;
double s7 = Math.Round(s, 7);
double s5 = Math.Round(s, 5);
double s6 = Math.Round(s, 6);
</code>```

With Platform = Any CPU, I get

```<code>s7: -2.611429
s5: -2.61143
s6: -2.611429
</code>```

With Platform = x64, I get

```<code>s7: -2.6114289999999998
s5: -2.61143
s6: -2.6114289999999998
</code>```

Why? (Output copied from VS's Locals window)

The whole piece of code is:

```<code>    private void btnAlign_Click(object sender, EventArgs e)
    {
        double s = -2.6114289999999998;
        double s7 = Math.Round(s, 7);
        double s5 = Math.Round(s, 5);
        double s6 = Math.Round(s, 6);
    }
</code>```

答:
On x64, the SSE2 FPU is used and on x86 the x87 FPU is used.

It is possible (although not advised) to change the x87 precision to be the same as the SSE2 precision (i.e., use lower precision).

You can do that via the _controlfp() API.

The following program demonstrates. Run this program in x86 mode and you'll see how the use of _controlfp(0x00030000, 0x00020000) causes the output to change to be similar to (but not quite the same!) as the x64 version:

```<code>using System;
using System.Runtime.InteropServices;

namespace ConsoleApp3
{
    class Program
    {
        static void Main()
        {
            double s = -2.6114289999999998;

            Console.WriteLine(Math.Round(s, 7).ToString("R")); // -2.611429

            if (!Environment.Is64BitProcess)
                _controlfp(0x00030000, 0x00020000);

            Console.WriteLine(Math.Round(s, 7).ToString("R")); // -2.61142897605896
        }

        [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern uint _controlfp(uint newcw, uint mask);
    }
}
</code>```

However, you should not mess around with the FPU in this way (and if you do, you should revert to the previous setting asap).

Body:
I have this tiny piece of code

double s = -2.6114289999999998;
double s7 = Math.Round(s, 7);
double s5 = Math.Round(s, 5);
double s6 = Math.Round(s, 6);

With Platform = Any CPU, I get

s7: -2.611429
s5: -2.61143
s6: -2.611429

With Platform = x64, I get

s7: -2.6114289999999998
s5: -2.61143
s6: -2.6114289999999998

Why? (Output copied from VS's Locals window)

The whole piece of code is:

    private void btnAlign_Click(object sender, EventArgs e)
    {
        double s = -2.6114289999999998;
        double s7 = Math.Round(s, 7);
        double s5 = Math.Round(s, 5);
        double s6 = Math.Round(s, 6);
    }

Body:
On x64, the SSE2 FPU is used and on x86 the x87 FPU is used.

It is possible (although not advised) to change the x87 precision to be the same as the SSE2 precision (i.e., use lower precision).

You can do that via the _controlfp() API.

The following program demonstrates. Run this program in x86 mode and you'll see how the use of _controlfp(0x00030000, 0x00020000) causes the output to change to be similar to (but not quite the same!) as the x64 version:

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp3
{
    class Program
    {
        static void Main()
        {
            double s = -2.6114289999999998;

            Console.WriteLine(Math.Round(s, 7).ToString("R")); // -2.611429

            if (!Environment.Is64BitProcess)
                _controlfp(0x00030000, 0x00020000);

            Console.WriteLine(Math.Round(s, 7).ToString("R")); // -2.61142897605896
        }

        [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern uint _controlfp(uint newcw, uint mask);
    }
}

However, you should not mess around with the FPU in this way (and if you do, you should revert to the previous setting asap).


问:
MySQL, count the number of "filled" fields in a table
MySQL (table):

```<code>+----+------+
| id | text |
+----+------+
| 1  |      |
+----+------+
| 2  | blah |
+----+------+
| 3  |      |
+----+------+
| 4  | blah |
+----+------+
| 5  | blah |
+----+------+
</code>```

PHP:

```<code>$a = mysql_query("SELECT COUNT(*) AS count1 FROM `table`");
$b = mysql_fetch_assoc($a);

echo $b['count1'];
</code>```

Output:

```<code>5
</code>```

However, I also want to count the text fields which are filled - within the same query, if possible.

Result:

```<code>5 in total
3 with filled text fields
</code>```

答:
```<code>SELECT COUNT(*) AS `total`, SUM(IF(`text` <> "",1,0)) AS `non_empty` FROM `table`
</code>```

Body:
MySQL (table):

+----+------+
| id | text |
+----+------+
| 1  |      |
+----+------+
| 2  | blah |
+----+------+
| 3  |      |
+----+------+
| 4  | blah |
+----+------+
| 5  | blah |
+----+------+

PHP:

$a = mysql_query("SELECT COUNT(*) AS count1 FROM `table`");
$b = mysql_fetch_assoc($a);

echo $b['count1'];

Output:

5

However, I also want to count the text fields which are filled - within the same query, if possible.

Result:

5 in total
3 with filled text fields


问:
Create a new script tag (Shopify) Error: Invalid URI "/"
Based on this tutorial, I tried the below code. I'm trying to add a new script to the web page.

```<code>request.post(accessTokenRequestUrl, {
      json: accessTokenPayload
  })
  .then((accessTokenResponse) => {
          const accessToken = accessTokenResponse.access_token;
          // DONE: Use access token to make API call to 'shop' endpoint
          const shopRequestUrl = 'https://' + shop + '/admin/shop.json';
          const shopRequestHeaders = {
              'X-Shopify-Access-Token': accessToken,
              'Content-Type': 'application/json'
          };

          const createScriptTagUrl = 'https://' + shop + '/admin/script_tags.json';
          const scriptTagBody = {
              "script_tag": {
                  "event": "onload",
                  "src": "https:\/\/djavaskripped.org\/fancy.js"
              }
          }

          request.get(shopRequestUrl, {
                  headers: shopRequestHeaders
              })
              .then((shopResponse) => {
                  res.status(200).end(shopResponse);
              })
              .catch((error) => {
                  res.status(error.statusCode).send(error.error.error_description);
              });
          request.post(createScriptTagUrl, {
                  json: scriptTagBody
              }, {
                  headers: shopRequestHeaders
              })
              .then((scriptResponse) => {
                  res.status(200).end(scriptResponse);
              })
              .catch((error) => {
                  res.status(error.statusCode).send(error.error.error_description);
              });
</code>```

However, I get RequestError: Error: Invalid URI "/"

Am I missing anything? Or is the src value is having some problem?

答:
I think you are using get method to create the script tag instead of post. Please use post method and also remove \ from the src.

Thanks

Body:
Based on this tutorial, I tried the below code. I'm trying to add a new script to the web page.

request.post(accessTokenRequestUrl, {
      json: accessTokenPayload
  })
  .then((accessTokenResponse) => {
          const accessToken = accessTokenResponse.access_token;
          // DONE: Use access token to make API call to 'shop' endpoint
          const shopRequestUrl = 'https://' + shop + '/admin/shop.json';
          const shopRequestHeaders = {
              'X-Shopify-Access-Token': accessToken,
              'Content-Type': 'application/json'
          };

          const createScriptTagUrl = 'https://' + shop + '/admin/script_tags.json';
          const scriptTagBody = {
              "script_tag": {
                  "event": "onload",
                  "src": "https:\/\/djavaskripped.org\/fancy.js"
              }
          }

          request.get(shopRequestUrl, {
                  headers: shopRequestHeaders
              })
              .then((shopResponse) => {
                  res.status(200).end(shopResponse);
              })
              .catch((error) => {
                  res.status(error.statusCode).send(error.error.error_description);
              });
          request.post(createScriptTagUrl, {
                  json: scriptTagBody
              }, {
                  headers: shopRequestHeaders
              })
              .then((scriptResponse) => {
                  res.status(200).end(scriptResponse);
              })
              .catch((error) => {
                  res.status(error.statusCode).send(error.error.error_description);
              });

However, I get RequestError: Error: Invalid URI "/"

Am I missing anything? Or is the src value is having some problem?


问:
Which is more convenient to use? TextInputLayout & TextInputeEditText or EditText?
I am seeing these TextInputLayout and TextInputEditText, but since I am developing I noticed that the capabilities of these two methods can be used by EditText only.

I researched about EditText, and it only says that the advantage of TextInputLayout and TextInputEditText is that you can put a hint on it. EditText alone can also now use hint.

So I am wondering if I can just use EditText rather than use the two methods. Also, TextInputLayout and TextInputEditText is not anymore showing in the IntelliSense.

I am currently using Android Studio 3.0

答:
TextInputEditText is child of EditText whereas TextInputLayout is a linear layout which wraps an EditText (or descendant) to show a floating label when the hint is hidden due to the user inputting text. So if you need to show such thing then you use TextInputLayout otherwise edittext is good to go with. For further information please visit :

https://developer.android.com/reference/android/support/design/widget/TextInputLayout.html

https://developer.android.com/reference/android/support/design/widget/TextInputEditText.html


问:
How do I create test and train samples from one dataframe with pandas?
I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing.

Thanks!

答:
If you need to split your data with respect to the lables column in your data set you can use this:

```<code>def split_to_train_test(df, label_column, train_frac=0.8):
    train_df, test_df = pd.DataFrame(), pd.DataFrame()
    labels = df[label_column].unique()
    for lbl in labels:
        lbl_df = df[df[label_column] == lbl]
        lbl_train_df = lbl_df.sample(frac=train_frac)
        lbl_test_df = lbl_df.drop(lbl_train_df.index)
        print '\n%s:\n---------\ntotal:%d\ntrain_df:%d\ntest_df:%d' % (lbl, len(lbl_df), len(lbl_train_df), len(lbl_test_df))
        train_df = train_df.append(lbl_train_df)
        test_df = test_df.append(lbl_test_df)

    return train_df, test_df
</code>```

and use it:

```<code>train, test = split_to_train_test(data, 'class', 0.7)
</code>```

you can also pass random_state if you want to control the split randomness or use some global random seed.

Body:
If you need to split your data with respect to the lables column in your data set you can use this:

def split_to_train_test(df, label_column, train_frac=0.8):
    train_df, test_df = pd.DataFrame(), pd.DataFrame()
    labels = df[label_column].unique()
    for lbl in labels:
        lbl_df = df[df[label_column] == lbl]
        lbl_train_df = lbl_df.sample(frac=train_frac)
        lbl_test_df = lbl_df.drop(lbl_train_df.index)
        print '\n%s:\n---------\ntotal:%d\ntrain_df:%d\ntest_df:%d' % (lbl, len(lbl_df), len(lbl_train_df), len(lbl_test_df))
        train_df = train_df.append(lbl_train_df)
        test_df = test_df.append(lbl_test_df)

    return train_df, test_df

and use it:

train, test = split_to_train_test(data, 'class', 0.7)

you can also pass random_state if you want to control the split randomness or use some global random seed.


问:
How to set Robots.txt or Apache to allow crawlers only at certain hours?
As traffic is distributed unevenly over 24 hours, I would like to disallow crawlers during peek hours and allow them at non-busy hours.

Is there a method to achieve this?

edit:
thanks for all the good advice.

This is another solution we found.

2bits.com has an article on setting IPTables firewall to limit the number of connections from certain IP addresses.

the article

the setting of IPTables:

Using connlimit

In newer Linux kernels, there is a connlimit module for iptables. It can be used like this:

iptables -I INPUT -p tcp -m connlimit --connlimit-above 5 -j REJECT

This limits connections from each IP address to no more than 5 simultaneous connections. This sort of "rations" connections, and prevents crawlers from hitting the site simultaneously.
*

答:
This is not possible using some robots.txt syntax - the feature simply isn't there.

You might be able to influence crawlers  by actually altering the robots.txt file depending on the time of day. I expect Google will check the file immediately before crawling, for example. But obviously, there is the huge danger of scaring crawlers away for good that way - the risk of that being probably more problematic than whatever load you get right now.


问:
java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings
I have an Android app that uses multidex. It is released and has monthly users in the hundreds of thousands. Every so often I will get ExceptionInInitializerError crashes on Crashlytics. I've never been able to reproduce them.

I read that this can be due to multidex and that have multiDexKeepFile file('multidex-config.txt') on my config with a list of classes would help, but it doesn't seem to help, at least not for this resource. This is the content on my multidex-config.txt:

```<code>org.eclipse.jetty.http.MimeTypes
org.eclipse.jetty.server.Server
javax.servlet.LocalStrings
</code>```

Those are all classes for which I've had crashes like this in the past. I'm still waiting to see if some of those are fixed but this one below keeps coming back for sure:

```<code>Fatal Exception: java.lang.ExceptionInInitializerError
       at myapp.run(myclass.java:986)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
       at java.lang.Thread.run(Thread.java:761)
Caused by java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale it_IT
       at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1501)
       at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1324)
       at java.util.ResourceBundle.getBundle(ResourceBundle.java:723)
       at javax.servlet.GenericServlet.(GenericServlet.java)
</code>```

So how can I fix this? In this case it seems to be looking for the Italian file, this isn't always the case and I have a lot of users in Italy so I'm not sure why it is only crashing for a few. The resource bundle on Android Studio for LocalStrings only shows a default one, French and Japanese.

Thanks.

答:
Make sure you are not missing to add the servlet-api dependency.

If you're using maven make sure this dependency is in your project:

```<code><dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
</dependency>
</code>```

Body:
I have an Android app that uses multidex. It is released and has monthly users in the hundreds of thousands. Every so often I will get ExceptionInInitializerError crashes on Crashlytics. I've never been able to reproduce them.

I read that this can be due to multidex and that have multiDexKeepFile file('multidex-config.txt') on my config with a list of classes would help, but it doesn't seem to help, at least not for this resource. This is the content on my multidex-config.txt:

org.eclipse.jetty.http.MimeTypes
org.eclipse.jetty.server.Server
javax.servlet.LocalStrings

Those are all classes for which I've had crashes like this in the past. I'm still waiting to see if some of those are fixed but this one below keeps coming back for sure:

Fatal Exception: java.lang.ExceptionInInitializerError
       at myapp.run(myclass.java:986)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
       at java.lang.Thread.run(Thread.java:761)
Caused by java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale it_IT
       at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1501)
       at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1324)
       at java.util.ResourceBundle.getBundle(ResourceBundle.java:723)
       at javax.servlet.GenericServlet.(GenericServlet.java)

So how can I fix this? In this case it seems to be looking for the Italian file, this isn't always the case and I have a lot of users in Italy so I'm not sure why it is only crashing for a few. The resource bundle on Android Studio for LocalStrings only shows a default one, French and Japanese.

Thanks.

Body:
Make sure you are not missing to add the servlet-api dependency.

If you're using maven make sure this dependency is in your project:

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
</dependency>


问:
Compile-time reversal of parameter-pack expansion
In the following class template I want to initalize the member-array b with the values of the parameter-pack vv in reverse-oder!

```<code>template<typename T>
struct Test {
public:
    template<typename... B>
    explicit Test(B... vv) : b{vv...,} // how to initialize member b with pack expansion v... in reverse order
    {
    }
private:
    std::byte b[sizeof(T)];
};
</code>```

I can't imagine how to reverse the parameter-pack expansion in a form, that it is as well usable in an initializer list.

答:
With delegating constructor, you may do something like:</p>

```<code>template<typename T>
struct Test {
    template <std::size_t...Is, typename... B>
    Test(std::index_sequence<Is...>, B&&... vv) :
        b{std::get<sizeof...(Is) - 1 - Is>(std::tie(vv...))...}
    {}

public:
    template<typename... B>
    explicit Test(B... vv) : Test(std::index_sequence_for<B...>{}, vv...) {}
private:
    std::byte b[sizeof(T)];
};
</code>```

Body:
In the following class template I want to initalize the member-array b with the values of the parameter-pack vv in reverse-oder!

template<typename T>
struct Test {
public:
    template<typename... B>
    explicit Test(B... vv) : b{vv...,} // how to initialize member b with pack expansion v... in reverse order
    {
    }
private:
    std::byte b[sizeof(T)];
};

I can't imagine how to reverse the parameter-pack expansion in a form, that it is as well usable in an initializer list.

Body:
With delegating constructor, you may do something like:

template<typename T>
struct Test {
    template <std::size_t...Is, typename... B>
    Test(std::index_sequence<Is...>, B&&... vv) :
        b{std::get<sizeof...(Is) - 1 - Is>(std::tie(vv...))...}
    {}

public:
    template<typename... B>
    explicit Test(B... vv) : Test(std::index_sequence_for<B...>{}, vv...) {}
private:
    std::byte b[sizeof(T)];
};


问:
Python - Log Transformation on variables using numpy
I am working on feature engineering process as part of a machine learning project. And currently I have to determine whether to do log transformation for certain columns or not.

I came to know that log transformation should be done on those columns which are having skew distribution of values.

Now here are my questions / doubts for which I need clarifications.

How do I determine in Python whether a particular column values belong to skew distributions(either right skew or left skew) ?

And assume that I have determined the columns over which I need to apply log transformation, there are many bases to the log function such as loge, log10, log2, etc... So do I use natural log (i.e) loge or log10 or anything else in this machine learning approach ?

And if I am not wrong, log transformation can be applied only on numeric variables. Is this right ?

答:
You can use Pandas DataFrame.skew(axis=None, skipna=None, level=None, numeric_only=None, **kwargs) Pandas skew to see weather the values of a particular column is skewed or not.

Basically, natural log transormation is preferable and it can be applied only numerical values except zero and negative values.

The skewness for a normal distribution is zero, and any symmetric data should have a skewness near zero. Negative values for the skewness indicate data that are skewed left and positive values for the skewness indicate data that are skewed right. By skewed left, we mean that the left tail is long relative to the right tail. Similarly, skewed right means that the right tail is long relative to the left tail.


问:
"Expected initializer before ':' token" with range-based for
```<code>#include <iostream>
#include <array>
using namespace std;

typedef int type;
typedef array <type,6> Liste;
bool appartient(type element, Liste liste);

int main()
{
    Liste maliste = {4,5,-3,12,7,-33};

    cout << appartient(13, maliste) << endl;
    cout << appartient(12, maliste) << endl;
    return 0;
}

bool appartient(type x, Liste liste)
{
    for (auto element: liste) {  //////this line!!!!!!!
        if (x == element) return true;
    }
    return false;
}
</code>```

I am working on this exercise of table in c++. Here I am writing a fonction "appartient" that verify the appartenance of an element on a list. But I have some errors in this fonction:

1/ error: expected initializer before ':' token

2/ error: expected primary-expression before 'return'

3/ error: expected ';' before 'return'

4/ error: expected primary-expression before 'return'

5/ error: expected ')' before 'return'

Why?

答:
Are you trying to use really a for loop or youu'd like to use a for_each loop?

The sintax of the "for" require that you initialize the variable that will be used as an index, and that you specify also the increments of such variable. Try this:

```<code>bool appartient(type x, Liste liste)
{
   for(auto element = 0; element <= 6; element ++)
   {
      if (x == element) return true;
   }
   return false;
}
</code>```

This is just a very raw example. I am sure you might be able to make your code prettier that this. Check the sintax of the for - loop here: for loops.

I hope this could be of help.

Body:
#include <iostream>
#include <array>
using namespace std;

typedef int type;
typedef array <type,6> Liste;
bool appartient(type element, Liste liste);

int main()
{
    Liste maliste = {4,5,-3,12,7,-33};

    cout << appartient(13, maliste) << endl;
    cout << appartient(12, maliste) << endl;
    return 0;
}

bool appartient(type x, Liste liste)
{
    for (auto element: liste) {  //////this line!!!!!!!
        if (x == element) return true;
    }
    return false;
}

I am working on this exercise of table in c++. Here I am writing a fonction "appartient" that verify the appartenance of an element on a list. But I have some errors in this fonction:

1/ error: expected initializer before ':' token

2/ error: expected primary-expression before 'return'

3/ error: expected ';' before 'return'

4/ error: expected primary-expression before 'return'

5/ error: expected ')' before 'return'

Why?

Body:
Are you trying to use really a for loop or youu'd like to use a for_each loop?

The sintax of the "for" require that you initialize the variable that will be used as an index, and that you specify also the increments of such variable. Try this:

bool appartient(type x, Liste liste)
{
   for(auto element = 0; element <= 6; element ++)
   {
      if (x == element) return true;
   }
   return false;
}

This is just a very raw example. I am sure you might be able to make your code prettier that this. Check the sintax of the for - loop here: for loops.

I hope this could be of help.


问:
IErrorInfo.GetDescription failed with E_FAIL(0x80004005) C#
I am getting an

IErrorInfo.GetDescription failed with E_FAIL(0x80004005)

And I don't know what this means nor how to solve it. When I copy and paste the exact query into my Access-db and run it it works like a charm but when I try and run it in c# I get this error.

The parameters all do get filled with the right values.

```<code>@aankomst = 15-11-2017, @vertrek = 20-11-2017, @grootte = "large"

    try
    {
        standplaatslijst.Clear();
        verbinding = new OleDbConnection(
        @"Provider=Microsoft.ACE.OLEDB.12.0;
        Data Source=..\..\..\La_Rustique.accdb;
        Persist Security Info=False;");
        verbinding.Open();

        OleDbCommand query = new OleDbCommand();
        OleDbDataReader lezer = null;
        query.CommandText = @"SELECT *
                              FROM standplaats
                              WHERE id not in (SELECT standplaats_id
                              FROM reservering
                               WHERE @aankomst BETWEEN aankomst AND vertrek
                               AND @vertrek BETWEEN aankomst AND vertrek)
                               AND size = @grootte";

        query.Connection = verbinding;

        query.Parameters.Add(new OleDbParameter("@aankomst", OleDbType.DBDate));
        query.Parameters["@aankomst"].Value = aankomst;
        query.Parameters.Add(new OleDbParameter("@vertrek", OleDbType.DBDate));
        query.Parameters["@vertrek"].Value = vertrek;
        query.Parameters.Add(new OleDbParameter("@grootte", OleDbType.VarChar));
        query.Parameters["@grootte"].Value = grootte;

        lezer = query.ExecuteReader();

        while (lezer.Read())
        {
            standplaatslijst.Add(new standplaats(lezer));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        verbinding.Close();
    }
</code>```

I'm adding the reader to a new class called standplaats which looks like this:

```<code>public standplaats(OleDbDataReader lezer)
    {
        _id = lezer.GetInt32(0);
        Grootte = lezer.GetString(1);
        Name = lezer.GetString(2);
    }
</code>```

答:
SIZE is a reserved word in MS Access.

Change the query to this:

```<code>query.CommandText = @"SELECT *
                      FROM standplaats
                      WHERE id not in (SELECT standplaats_id
                      FROM reservering
                       WHERE @aankomst BETWEEN aankomst AND vertrek
                       AND @vertrek BETWEEN aankomst AND vertrek)
                       AND [size] = @grootte";
</code>```

Here you find the list of reserved words.

Body:
I am getting an

IErrorInfo.GetDescription failed with E_FAIL(0x80004005)

And I don't know what this means nor how to solve it. When I copy and paste the exact query into my Access-db and run it it works like a charm but when I try and run it in c# I get this error.

The parameters all do get filled with the right values.

@aankomst = 15-11-2017, @vertrek = 20-11-2017, @grootte = "large"

    try
    {
        standplaatslijst.Clear();
        verbinding = new OleDbConnection(
        @"Provider=Microsoft.ACE.OLEDB.12.0;
        Data Source=..\..\..\La_Rustique.accdb;
        Persist Security Info=False;");
        verbinding.Open();

        OleDbCommand query = new OleDbCommand();
        OleDbDataReader lezer = null;
        query.CommandText = @"SELECT *
                              FROM standplaats
                              WHERE id not in (SELECT standplaats_id
                              FROM reservering
                               WHERE @aankomst BETWEEN aankomst AND vertrek
                               AND @vertrek BETWEEN aankomst AND vertrek)
                               AND size = @grootte";

        query.Connection = verbinding;

        query.Parameters.Add(new OleDbParameter("@aankomst", OleDbType.DBDate));
        query.Parameters["@aankomst"].Value = aankomst;
        query.Parameters.Add(new OleDbParameter("@vertrek", OleDbType.DBDate));
        query.Parameters["@vertrek"].Value = vertrek;
        query.Parameters.Add(new OleDbParameter("@grootte", OleDbType.VarChar));
        query.Parameters["@grootte"].Value = grootte;

        lezer = query.ExecuteReader();

        while (lezer.Read())
        {
            standplaatslijst.Add(new standplaats(lezer));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        verbinding.Close();
    }

I'm adding the reader to a new class called standplaats which looks like this:

public standplaats(OleDbDataReader lezer)
    {
        _id = lezer.GetInt32(0);
        Grootte = lezer.GetString(1);
        Name = lezer.GetString(2);
    }

Body:
SIZE is a reserved word in MS Access.

Change the query to this:

query.CommandText = @"SELECT *
                      FROM standplaats
                      WHERE id not in (SELECT standplaats_id
                      FROM reservering
                       WHERE @aankomst BETWEEN aankomst AND vertrek
                       AND @vertrek BETWEEN aankomst AND vertrek)
                       AND [size] = @grootte";

Here you find the list of reserved words.


问:
Getting started with an iPad application
I have an iPhone application fully finished and it doesn't rely on any specific iPhone functionality that would not be used on an iPad (for example, my iPhone app doesn't use Text Messaging). I use xcode and I use the iPhone simulator to test my app.

How would I go about making an iPad version? Do I need to make a fully new xcode project? I know there is an iPad simulator, but how do I create an iPad version. Also, when I submit to apple, how do I specify the iPhone version and the iPad version.

For instance, in my code I have a UITableView in a particular controller that is size 320x480 (to fit the iPhone). How would I specify an iPad version of that UITableView?

Can anyone explain/give me insight? Thanks!

答:
In Addition to the UIUserInterfaceIdiom stuff, you may also want to review the iOS Application Programming Guide paying specific attention to the hardware sections.  Also if you haven't seen it this document specifically talks about building universal apps.  Unfortunately there's not a perfect one stop shop, but it's not terribly hard, especially if you already have an app and are ready to port.

Hope that helps.