答:
I assume you're talking about this notebook.

I looked at the code and the scores array indicate the confidence level for each detected box. The class of each box is in the classes variable (detection_classes:0 tensor).

This line runs the input through the network:

```<code>(boxes, scores, classes, num) = sess.run(
          [detection_boxes, detection_scores, detection_classes, num_detections],
          feed_dict={image_tensor: image_np_expanded})
</code>```

In order to print the class along with the scores you can:

```<code>for class, score in zip(classes, scores):
    print(class, ':', score)
</code>```

The descriptions of categories used in the notebook are here (mscoco labels).

Title: How to get the category of the object detected - tensorflow

Body:
I'm new to tensorflow and I'm wondering how do you get the 'category' of the object detected back along with its score?

Here'a a score array I have for a sample image, as you can see there's 4 'boxes' with over 50% confidence:

    scores
Out[104]:
array([[ 0.86274904,  0.68427145,  0.53348649,  0.51449829,  0.4737072 ,
         0.20210901,  0.18676876,  0.15660423,  0.15557742,  0.15542269,
         0.15463693,  0.14486608,  0.13966955,  0.1298867 ,  0.12409254,
         0.12288965,  0.10780571,  0.10559474,  0.10537479,  0.10148374,
         0.10037792,  0.09754734,  0.09640686,  0.09590817,  0.09435588,
         0.09198856,  0.0918662 ,  0.09173656,  0.0879355 ,  0.08762371,
         0.08711197,  0.08627746,  0.08621041,  0.08481266,  0.08390592,
         0.08365501,  0.08259587,  0.08251529,  0.08152138,  0.08019584,
         0.07996205,  0.07962734,  0.07907323,  0.07718709,  0.07715672,
         0.07693762,  0.07692765,  0.07642546,  0.07611038,  0.07582222,
         0.0754476 ,  0.07542069,  0.07490928,  0.07476845,  0.0747645 ,
         0.07418264,  0.07383376,  0.07275221,  0.07237192,  0.0722541 ,
         0.07183521,  0.07175662,  0.07174246,  0.07155806,  0.071283  ,
         0.0710848 ,  0.07026858,  0.06924678,  0.06890308,  0.06833564,
         0.06827622,  0.06769758,  0.06753176,  0.06721075,  0.0663776 ,
         0.06553975,  0.06466822,  0.06375053,  0.06349288,  0.0633459 ,
         0.06320453,  0.06309631,  0.06307632,  0.06258182,  0.06233004,
         0.06231011,  0.06228941,  0.06161467,  0.06125913,  0.06117567,
         0.06101252,  0.06089024,  0.0608751 ,  0.06063354,  0.06047466,
         0.06046106,  0.0603817 ,  0.06035899,  0.06034132,  0.06016544]], dtype=float32)

What I'm wondering is how you get the output of what each of these scores is categorizing the object as, I'm can't seem to see it in any of the variables. Here's a list of what is returned:

    print(locals().keys())
dict_keys(['__name__', '__builtin__', '__builtins__', '_ih', '_oh', '_dh', 'In', 'Out', 'get_ipython', 'exit', 'quit', '_i', '_ii', '_iii', '_i52', 'np', 'os', 'urllib', 'sys', 'tarfile', 'tf', 'zipfile', 'defaultdict', 'StringIO', 'plt', 'Image', 'total_count', 'label_map_util', 'vis_util', 'MODEL_NAME', 'MODEL_FILE', 'DOWNLOAD_BASE', 'PATH_TO_CKPT', 'PATH_TO_LABELS', 'NUM_CLASSES', 'opener', 'tar_file', 'file', 'file_name', 'detection_graph', 'od_graph_def', 'fid', 'serialized_graph', 'label_map', 'categories', 'category_index', 'load_image_into_numpy_array', 'PATH_TO_TEST_IMAGES_DIR', 'TEST_IMAGE_PATHS', 'IMAGE_SIZE', 'sess', 'image_tensor', 'detection_boxes', 'detection_scores', 'detection_classes', 'num_detections', 'image_path', 'image', 'image_np', 'image_np_expanded', 'boxes', 'scores', 'classes', 'num',

This is using the primary tutorial script from the object_detection tutorial on github found here: https://github.com/tensorflow/models/tree/master/research/object_detection

Any help would be appreciated.
Cheers,

Body:
I assume you're talking about this notebook.

I looked at the code and the scores array indicate the confidence level for each detected box. The class of each box is in the classes variable (detection_classes:0 tensor).

This line runs the input through the network:

(boxes, scores, classes, num) = sess.run(
          [detection_boxes, detection_scores, detection_classes, num_detections],
          feed_dict={image_tensor: image_np_expanded})

In order to print the class along with the scores you can:

for class, score in zip(classes, scores):
    print(class, ':', score)

The descriptions of categories used in the notebook are here (mscoco labels).


来源: stackexchange

问:
Phonegap app can not connect to database on mobile
I have been been working on an app in phonegap and make login and register with JavaScript and ajax call. </p>

<p>So I tested it on Google Chrome and it works perfect, connecting on server (mysql) and inserting data etc... So I decide to build app to test it on mobile (android), and it just not responding when I click on register or login button.
Is there some code or file which I need to import ? </p>

答:
Application did not receive internet connection, so I changed my config.xml file.
Core plugins I found here: https://build.phonegap.com/plugins</p>

ContentLicense: CC BY-SA 3.0

Body:
I have been been working on an app in phonegap and make login and register with JavaScript and ajax call.

So I tested it on Google Chrome and it works perfect, connecting on server (mysql) and inserting data etc... So I decide to build app to test it on mobile (android), and it just not responding when I click on register or login button.
Is there some code or file which I need to import ?


问:
awaiting 2 methods instead of 1
I am trying to start a count and then another method will stop this counting by generating a random number between 1 and 6 seconds. I can do the counting but stopper function did not start asynchronously with my Count function.
I want both of them to sart at the same time so I put two await statements inside same DoAsync method. But it does not work as intended because random number is generated at the end of counting. I need the generation start at the beginning of the count...

The output is like this:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
In2126  milliseconds: count will stop...

```<code>using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
class Program
{
    static void Main(string[] args)
    {
        CancellationTokenSource ctSource = new CancellationTokenSource();
        CancellationToken ctToken = ctSource.Token;

        Task t1 = DoAsync(ctSource, ctToken);

        t1.Wait();
    }

    private static async Task DoAsync(CancellationTokenSource ctSource, CancellationToken ctoken)
    {
        if (ctoken.IsCancellationRequested)
            return;

        await Task.Run(() => Count(ctoken), ctoken);
        await Task.Run(() => Stop(ctSource), ctoken);
    }

    public static void Count(CancellationToken ctoken)
    {
        for (int i = 0; i < 20; i++)
        {
            if (ctoken.IsCancellationRequested)
            {
                Console.WriteLine("stopped at :" + i);

                break;
            }
            else
            {
                Console.WriteLine(i);
                Thread.Sleep(150);
            }
        }
    }

    public static void Stop(CancellationTokenSource cSource)
    {
        Random r = new Random();
        int milliseconds = r.Next(1000, 6000);
        Console.WriteLine("In" + milliseconds + "  milliseconds: " + "count will stop...");

        Thread.Sleep(milliseconds);
        cSource.Cancel();
    }

}
</code>```

}

答:
You can use Task.WhenAll() for this purpose. It takes an array of tasks and creates a new task that will finish when all source tasks are finished.</p>

```<code>var taskCount = Task.Run(() => Count(ctoken), ctoken);
var taskStop = Task.Run(() => Stop(ctSource), ctoken);
await Task.WhenAll(new [] { taskCount, taskStop });
</code>```

Title: awaiting 2 methods instead of 1

Body:
I am trying to start a count and then another method will stop this counting by generating a random number between 1 and 6 seconds. I can do the counting but stopper function did not start asynchronously with my Count function.
I want both of them to sart at the same time so I put two await statements inside same DoAsync method. But it does not work as intended because random number is generated at the end of counting. I need the generation start at the beginning of the count...

The output is like this:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
In2126  milliseconds: count will stop...

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
class Program
{
    static void Main(string[] args)
    {
        CancellationTokenSource ctSource = new CancellationTokenSource();
        CancellationToken ctToken = ctSource.Token;

        Task t1 = DoAsync(ctSource, ctToken);

        t1.Wait();
    }

    private static async Task DoAsync(CancellationTokenSource ctSource, CancellationToken ctoken)
    {
        if (ctoken.IsCancellationRequested)
            return;

        await Task.Run(() => Count(ctoken), ctoken);
        await Task.Run(() => Stop(ctSource), ctoken);
    }

    public static void Count(CancellationToken ctoken)
    {
        for (int i = 0; i < 20; i++)
        {
            if (ctoken.IsCancellationRequested)
            {
                Console.WriteLine("stopped at :" + i);

                break;
            }
            else
            {
                Console.WriteLine(i);
                Thread.Sleep(150);
            }
        }
    }

    public static void Stop(CancellationTokenSource cSource)
    {
        Random r = new Random();
        int milliseconds = r.Next(1000, 6000);
        Console.WriteLine("In" + milliseconds + "  milliseconds: " + "count will stop...");

        Thread.Sleep(milliseconds);
        cSource.Cancel();
    }

}

}

Body:
You can use Task.WhenAll() for this purpose. It takes an array of tasks and creates a new task that will finish when all source tasks are finished.

var taskCount = Task.Run(() => Count(ctoken), ctoken);
var taskStop = Task.Run(() => Stop(ctSource), ctoken);
await Task.WhenAll(new [] { taskCount, taskStop });


问:
How to auto load controllers with different sub-namespaces?
Here is a partial structure of my project

```<code>root
  |-App
     |--Controller
          |--Common
               |-HomeController.php
               |-HeaderController.php
               |-FooterController.php
               |-SidebarController.php
           |--Info
               |-AboutController.php
               |-ContactController.php
</code>```

I have my controllers placed in their corresponding directories for better management.

I recently added namespaces to them.

```<code>HomeController.php = namespace app\controller\common;
HeaderController.php = namespace app\controller\common;

AboutController.php = namespace app\controller\info;
ContactController.php = namespace app\controller\info;
</code>```

To load these controllers, I am checking this autoloader below

```<code>spl_autoload_register(function ($class) {

    $prefix = 'app\controller\common\\';
    $base_dir = __DIR__ . '/app/controller/common/'; // your classes folder

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});

$home = new app\controller\common\HomeController();
$home->index();
</code>```

and it works i.e. it autoload all controllers in the folder app > controller > common.

The problem is I do not understand how to load all other controllers which are in different folders (like the ones in the Info folder) and with different sub-namespace (namespace app\controller\info, namespace app\controller\client)?

The autoload has the namespace prefixed defined to $prefix = 'app\controller\common\\'; and I guess this is what I need to fix to accommodate all other controllers that there is to load them.

How do I fix this $prefix?

答:
You had the right idea there. But you went for anonymous functions, which in itself isn't necessarily wrong it just doesn't fit the your current case problem very well. You're better of with regular functions.

You could do something like this:

```<code>spl_autoload_register('myAutoloader');

function myAutoloader($path) {
    foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path),\FilesystemIterator::SKIP_DOTS) as $file) {
        if ($file->getFileExtension() == 'php') {
            require $file->getFilename() . $file->getFileExtension();
        }
    }
}
</code>```

This function will recursively iterate thru a folder and require any php file it finds. What it won't do is take care of various dependencies, so keep that in mind.

spl_autoload_register() allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a "new Class" is declared.

Quote is from this question, which I strongly recommend you read.

With that said, I encourage you to use Composer. It was designed specifically for your exact problem. You can load anything with it. Not just php files.

Body:
Here is a partial structure of my project

root
  |-App
     |--Controller
          |--Common
               |-HomeController.php
               |-HeaderController.php
               |-FooterController.php
               |-SidebarController.php
           |--Info
               |-AboutController.php
               |-ContactController.php

I have my controllers placed in their corresponding directories for better management.

I recently added namespaces to them.

HomeController.php = namespace app\controller\common;
HeaderController.php = namespace app\controller\common;

AboutController.php = namespace app\controller\info;
ContactController.php = namespace app\controller\info;

To load these controllers, I am checking this autoloader below

spl_autoload_register(function ($class) {

    $prefix = 'app\controller\common\\';
    $base_dir = __DIR__ . '/app/controller/common/'; // your classes folder

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});

$home = new app\controller\common\HomeController();
$home->index();

and it works i.e. it autoload all controllers in the folder app > controller > common.

The problem is I do not understand how to load all other controllers which are in different folders (like the ones in the Info folder) and with different sub-namespace (namespace app\controller\info, namespace app\controller\client)?

The autoload has the namespace prefixed defined to $prefix = 'app\controller\common\\'; and I guess this is what I need to fix to accommodate all other controllers that there is to load them.

How do I fix this $prefix?

Body:
You had the right idea there. But you went for anonymous functions, which in itself isn't necessarily wrong it just doesn't fit the your current case problem very well. You're better of with regular functions.

You could do something like this:

spl_autoload_register('myAutoloader');

function myAutoloader($path) {
    foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path),\FilesystemIterator::SKIP_DOTS) as $file) {
        if ($file->getFileExtension() == 'php') {
            require $file->getFilename() . $file->getFileExtension();
        }
    }
}

This function will recursively iterate thru a folder and require any php file it finds. What it won't do is take care of various dependencies, so keep that in mind.

spl_autoload_register() allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a "new Class" is declared.

Quote is from this question, which I strongly recommend you read.

With that said, I encourage you to use Composer. It was designed specifically for your exact problem. You can load anything with it. Not just php files.


问:
Getting/using output of CMD window of Jmeter
I,m running a Java file from BeanShell Sampler in jmeter, I'm getting the output successful in cmd windows of jmeter. The output comprises of series of logger files,I need to extract only a specified string from the cmd window and use it for another sample</p>

答:
This java bean shell Command made the console out by j meter  that is std out to be written in a file

System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("D:\\dir1\\dir2\\abc.out")),true));

Make sure your path to file should have double backward slash


问:
Start activity from service takes too long
I have a Service that when one function gives to me true it will start a new Activity but it takes like 5 seconds...

I've read about this issue, and I've found on StackOverflow this example to "avoid" this bug..

```<code>Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
try {
   pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
   e.printStackTrace();
}
</code>```

but sadly it doesn't start the Activity faster, I don't need to be inmmediate (better if it's possible), but I don't want to wait +5 seconds to launch the new Activity, do you knwo any trick to avoid this?

I'm using PendingIntent because I've found that guy that said that it should solve this issue :
Starting an activity from a service after HOME button pressed without the 5 seconds delay

Note

If I press back button it launch it autommatically, 0 delay, but I'm looking pressing the home button.

答:
First thing we cannot update any UI related stuff in service, neither calling activity nor updating any UI elements,
Same problem i too have faced.

Then i have used EventBus library to communicate UI elements from service
Below is the sample example

```<code>public class SendSPLocationService extends Service {
Handler mHandler = new Handler();
Thread downloadThread;
boolean isRunning = true;
private VolleyHelper volleyHelper;

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    //  Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
    volleyHelper = new VolleyHelper(this);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    final Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            Log.d("run: ", "service is running!");

            try {
                                        EventBus.getDefault().post(new FutureJobEvent(false, error.networkResponse.statusCode, errorJson.getString("message")));

            } catch (JSONException e) {
                e.printStackTrace();
            }
            // t.cancel();
            Log.d("run: ", "service is stopped!");

        }
    }, 0, 5000);
    return START_STICKY;
}
}
</code>```

Use below code for triggered event to observe..either in activity/fragment

```<code>@Override
public void onStart() {
    super.onStart();
    if (!EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    if (EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().unregister(this);
}
 @Subscribe(threadMode = ThreadMode.MAIN)
 public void onMessageEvent(TrackSPEvent event) {
    if (event.success) {
         startActivity(new Intent(this,MainActivity.class));
 }
 }
</code>```

Body:
I have a Service that when one function gives to me true it will start a new Activity but it takes like 5 seconds...

I've read about this issue, and I've found on StackOverflow this example to "avoid" this bug..

Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
try {
   pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
   e.printStackTrace();
}

but sadly it doesn't start the Activity faster, I don't need to be inmmediate (better if it's possible), but I don't want to wait +5 seconds to launch the new Activity, do you knwo any trick to avoid this?

I'm using PendingIntent because I've found that guy that said that it should solve this issue :
Starting an activity from a service after HOME button pressed without the 5 seconds delay

Note

If I press back button it launch it autommatically, 0 delay, but I'm looking pressing the home button.

Body:
First thing we cannot update any UI related stuff in service, neither calling activity nor updating any UI elements,
Same problem i too have faced.

Then i have used EventBus library to communicate UI elements from service
Below is the sample example

public class SendSPLocationService extends Service {
Handler mHandler = new Handler();
Thread downloadThread;
boolean isRunning = true;
private VolleyHelper volleyHelper;

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    //  Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
    volleyHelper = new VolleyHelper(this);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    final Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            Log.d("run: ", "service is running!");

            try {
                                        EventBus.getDefault().post(new FutureJobEvent(false, error.networkResponse.statusCode, errorJson.getString("message")));

            } catch (JSONException e) {
                e.printStackTrace();
            }
            // t.cancel();
            Log.d("run: ", "service is stopped!");

        }
    }, 0, 5000);
    return START_STICKY;
}
}

Use below code for triggered event to observe..either in activity/fragment

@Override
public void onStart() {
    super.onStart();
    if (!EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    if (EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().unregister(this);
}
 @Subscribe(threadMode = ThreadMode.MAIN)
 public void onMessageEvent(TrackSPEvent event) {
    if (event.success) {
         startActivity(new Intent(this,MainActivity.class));
 }
 }


答:
You can do this with the package chron:

```<code>install.packages("chron")
</code>```

I reproduced a short version of your data as follows:

```<code>list1 <- c(0,1,2,3, 68)
</code>```

The code that you should use is the following - replacing the list1 with the name of your list or dataframe column.

```<code>library(chron)
substr(times((list1%/%60 +  list1%%60 /60)/24), 1, 5)
</code>```

Title: Missing time class

Body:
Below are two columns with what I have and what I want.
I need to convert the have into want. Essentially, I am creating a 24 hour time sequence.

HAVE
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

WANT
0:00
0:01
0:02
0:03
0:04
0:05
0:06
0:07
0:08
0:09
0:10
0:11
0:12
0:13
0:14
0:15
0:16
0:17
0:18
0:19
0:20
0:21
0:22
0:23
0:24
0:25
0:26
0:27
0:28
0:29
0:30
0:31
0:32
0:33
0:34
0:35
0:36
0:37
0:38
0:39
0:40
0:41
0:42
0:43
0:44
0:45
0:46
0:47
0:48
0:49
0:50
0:51
0:52
0:53
0:54
0:55
0:56
0:57
0:58
0:59
1:00
1:01
1:02
1:03
1:04
1:05
1:06
1:07
1:08
1:09
1:10
1:11
1:12
1:13
1:14
1:15
1:16
1:17
1:18
1:19
1:20
1:21
1:22
1:23
1:24
1:25
1:26
1:27
1:28
1:29
1:30
1:31
1:32
1:33
1:34
1:35
1:36
1:37
1:38
1:39
1:40
1:41
1:42
1:43
1:44
1:45
1:46
1:47
1:48
1:49
1:50
1:51
1:52
1:53
1:54
1:55
1:56
1:57
1:58
1:59

Body:
You can do this with the package chron:

install.packages("chron")

I reproduced a short version of your data as follows:

list1 <- c(0,1,2,3, 68)

The code that you should use is the following - replacing the list1 with the name of your list or dataframe column.

library(chron)
substr(times((list1%/%60 +  list1%%60 /60)/24), 1, 5)


问:
Ionic tabs & authentication - tabs are persisting after logout
I have an Ionic app which has tabs and authentication, the auth works perfectly but when logging out the tabs still display. Here is my login method:

```<code>  this.authProvider.loginUser(email, password).then(
    authData => {
      this.loading.dismiss().then(() => {
        this.navCtrl.push(TabsPage);
        //this.navCtrl.setRoot(TabsPage);
      });
</code>```

And here is my logout method:

```<code>  logOut(): void {
    this.authProvider.logoutUser().then(() => {
      this.navCtrl.setRoot('LoginPage');
      this.navCtrl.popToRoot();
    });
  }
</code>```

Any help appreciated

答:
Use getRootNav of App to remove the tabs from the view. Refer to this working version.

```<code>import { Component } from '@angular/core';
import { NavController, App } from 'ionic-angular';
import { LoggedInComponent } from '../../pages/loggedIn/loggedIn.component';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, public app : App) {
    this.loggedInPage=LoggedInComponent;
  }

  goTopage(){
    this.app.getRootNav().setRoot(this.loggedInPage);
  }
}
</code>```

Body:
I have an Ionic app which has tabs and authentication, the auth works perfectly but when logging out the tabs still display. Here is my login method:

  this.authProvider.loginUser(email, password).then(
    authData => {
      this.loading.dismiss().then(() => {
        this.navCtrl.push(TabsPage);
        //this.navCtrl.setRoot(TabsPage);
      });

And here is my logout method:

  logOut(): void {
    this.authProvider.logoutUser().then(() => {
      this.navCtrl.setRoot('LoginPage');
      this.navCtrl.popToRoot();
    });
  }

Any help appreciated

Body:
Use getRootNav of App to remove the tabs from the view. Refer to this working version.

import { Component } from '@angular/core';
import { NavController, App } from 'ionic-angular';
import { LoggedInComponent } from '../../pages/loggedIn/loggedIn.component';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, public app : App) {
    this.loggedInPage=LoggedInComponent;
  }

  goTopage(){
    this.app.getRootNav().setRoot(this.loggedInPage);
  }
}


问:
How to connect to a third party API from node.js using Express.js
I am trying to connect to a third party api with authorization key but no luck. Any suggestion/direction/comment would be appreciated.

server.js

```<code>...

app.get('/products', (req, res) => {

request.get(BASE_URL, {
  'auth': {
  'bearer': 'abcdsfegete'
}
 }).on('error', function (error) {
    console.log(error);

 }).on('response', function (response) {
    console.log(response);
 })
res.send();
})
...
</code>```

Result: I keep getting "This response has to data available".

答:
The issue seems to be the properties were wrong (auth, bearer). So basic authentication is used instead.

```<code>app.get('/products', (req, res) => {
const options = {
url: BASE_URL + '/products',
headers: {
  'Authorization': 'abcdefghghgh',
  'Accept': 'application/json'
}
};
   request.get(options).pipe(res);
})
</code>```

Body:
I am trying to connect to a third party api with authorization key but no luck. Any suggestion/direction/comment would be appreciated.

server.js

...

app.get('/products', (req, res) => {

request.get(BASE_URL, {
  'auth': {
  'bearer': 'abcdsfegete'
}
 }).on('error', function (error) {
    console.log(error);

 }).on('response', function (response) {
    console.log(response);
 })
res.send();
})
...

Result: I keep getting "This response has to data available".

Body:
The issue seems to be the properties were wrong (auth, bearer). So basic authentication is used instead.

app.get('/products', (req, res) => {
const options = {
url: BASE_URL + '/products',
headers: {
  'Authorization': 'abcdefghghgh',
  'Accept': 'application/json'
}
};
   request.get(options).pipe(res);
})


问:
Arranging numbers within the digits in descending order without using arrays
I want to arrange the digits of a number in descending order without using arrays. When I am using String it gives run time error.
For example:

```<code>Input: 2436
Output: 6432
</code>```

Here is what I wrote but the problem is the first digit isn't getting printed which is not the expected output.

```<code>public static void main (String[] args) throws java.lang.Exception {
    Scanner sc = new Scanner(System.in);
    int num,n,r=0,FinalNo=0;
    System.out.println("Enter any number");
    num=sc.nextInt();
    n=num;
    while(n>0) {
        r=n%10;
        n=n/10;
        FinalNo=(FinalNo*10)+r;
    }
    System.out.println("The number in descending order is "+FinalNo);
}
</code>```

答:
Your example reverses the inputted value, but does not sort it in descending order. You're not allowed to use Strings or arrays (school assignment?), but how about lists?</p>

```<code>List<Integer> ints = new LinkedList<>(); // Because ArrayList uses an array internally
while (n > 0) {
    ints.add(n % 10);
    n = n / 10;
}
ints.sort((a, b) -> Integer.compare(b, a)); // Sort in reverse order
System.out.print("The digits in reversed order are: ");
ints.forEach(System.out::print);
System.out.println();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to arrange the digits of a number in descending order without using arrays. When I am using String it gives run time error.
For example:

Input: 2436
Output: 6432

Here is what I wrote but the problem is the first digit isn't getting printed which is not the expected output.

public static void main (String[] args) throws java.lang.Exception {
    Scanner sc = new Scanner(System.in);
    int num,n,r=0,FinalNo=0;
    System.out.println("Enter any number");
    num=sc.nextInt();
    n=num;
    while(n>0) {
        r=n%10;
        n=n/10;
        FinalNo=(FinalNo*10)+r;
    }
    System.out.println("The number in descending order is "+FinalNo);
}

Body:
Your example reverses the inputted value, but does not sort it in descending order. You're not allowed to use Strings or arrays (school assignment?), but how about lists?

List<Integer> ints = new LinkedList<>(); // Because ArrayList uses an array internally
while (n > 0) {
    ints.add(n % 10);
    n = n / 10;
}
ints.sort((a, b) -> Integer.compare(b, a)); // Sort in reverse order
System.out.print("The digits in reversed order are: ");
ints.forEach(System.out::print);
System.out.println();


问:
How to specify port of MySQL in Drupal?
I need to change the default port of MySQL from 3306 to something else (let us say 3300)

I have edited setting.php in sites/default.settings.php and changed

$db_url['default'] = 'mysqli://root:password@localhost/dbname'; TO

$db_url['default'] = 'mysqli://root:password@localhost:3300/dbname';

but this didn't work!
How can I change the default port?

答: Make sure you're editing the correct file. Either sites/default/settings.php or sites/mysite.com/settings.php. You shouldn't be editing the 'default.settings.php' file at all. It's a little unclear from your question if you might be.</p>

Title: How to specify port of MySQL in Drupal?

ContentLicense: CC BY-SA 2.5


问:
Why does my merge function output an array that is not ordered?
I built a simple function that, given two arrays aa[5] = {5, 4, 9, -1, 3} and bb[2] = {16, -11}, orders them in a third array cc[7].

```<code>#include<stdio.h>
void merge(int *, int *, int *, int, int);

int main(){
    int aa[5] = {5, 4, 9, -1, 3};
    int bb[2] = {16, -11};
    int cc[7];

    merge(aa, bb, cc, 5, 2);

    return 0;
}

void merge(int *aa, int *bb, int *cc, int m, int n){

    int i = 0, j = 0, k = 0;

    while(i < m && j < n){
        if(aa[i] < bb[j])
            cc[k++] = aa[i++];    /*Smallest value should be assigned to cc*/
        else
            cc[k++] = bb[j++];
    }

    while(i < m)              /*Transfer the remaining part of longest array*/
        cc[k++] = aa[i++];

    while(j < n)
        cc[k++] = bb[j++];
}
</code>```

The cc array is correctly filled, but the values are not ordered. Instead of the expected cc = {-11, -1, 3, 4, 5, 9, 16} it returns cc = {5, 4, 9, -1, 3, 16, 11}.
Like the assignments cc[k++] = aa[i++] and cc[k++] = bb[j++] do not work, somehow, or the logical test if aa[i] < bb[j] goes ignored.

I hypothesized operators priority problems, hence I tested with two different standard, with no differences:

```<code>gcc main.c -o main.x -Wall
gcc main.c -o main.x -Wall -std=c89
</code>```

I checked the code many times, unable to find any relevant error. Any suggestion at this point would be appreciated.

答:
There's no bug in your implementation (at least I don't see any, imho)  The problem is that the merging you have done is not for two sorted arrays (it's for several bunches of sorted numbers).  Case you had feed two already sorted arrays you'd have the result sorted correctly.

The merge sorting algorithm begins with splitting the input into two parts of sorted arrays.  This is done by switching arrays when you detect the element is not in order (it is not greater to last number) You get the first ordered set to fill an array (the first a elements of initial list which happen to be in order, to put into array A, and the second bunch of elements to put them into array B.  This produces two arrays that can be merged (because they are already in order) and this merging makes the result a larger array (this fact is what warrants the algorithm will make larger and larger arrays at each pass and warrants it will finish at some pass.  You don't need to operate array by array, as at each pass the list has less and less packs of larger bunch of sorted elements.  in your case:

```<code>1st pass input (the switching points are where the input
is not in order, you don't see them, but you switch arrays
when the next input number is less than the last input one):
  {5}, {4, 9}, {-1, 3}, {16}, {-11}  (See note 2)
after first split:
  {5}, {-1, 3}, {-11}
  {4, 9}, {16}
after first merge result:
  {4, 5, 9}, {-1, 3, 16}, {-11}
after second pass split:
  {4, 5, 9}, {-11}
  {-1, 3, 16}
  result:
  {-1, 3, 4, 5, 9, 16}, {-11}
third pass split:
  {-1, 3, 4, 5, 9, 16}
  {-11}
third pass result:
  {-11, -1, 3, 4, 5, 9, 16}
</code>```

The algorithm finishes when you don't get two bunches of ordered streams (you don't switch arrays), and you cannot divide further the stream of data.

Your implementation only executes one pass of merge sorting algorithm you need to implement it completely to get sorted output.  The algorithm was designed to make it possible to do several passes when input is not feasible to put in arrays (as you do, so it doesn't fully illustrate the thing with arrays).  Case you have it read from files, you'll see the idea better.

NOTE

Sort programs for huge amounts of data use merging algorithm for bunchs of data that are quicksort'ed first, so we start with buckets of data that don't fit in an array all together.

NOTE 2

The number 16 after number 3 should have been in the same bunch as previous bunch, making it {-1, 3, 16}, but as they where in different arrays at first, and I have not found any way to put them in a list that splits into this arrangement, I have forced the buckets as if 16 < 3, switching artificially the arrays on splitting the input.  This could affect the final result in making an extra pass through the data, but doesn't affect the final result, which is a sorted list of numbers.  I have made this on purpose, and it is not a mistake (it has no relevance to explain how the algorithm works)  Anyway, the algorithm switches lists (I don't like to use arrays when describing this algoritm, as normally merging algorithms don't operate on arrays, as arrays are random access, while lists must be accessed by some iterator means from beginning to end, which is the requirement of the merging sort algorithm)  The same happens to {4, 9}, {16} after the first split, just imagine the result of the comparisons was the one shown, as after the first merge everything is correct.

Body:
I built a simple function that, given two arrays aa[5] = {5, 4, 9, -1, 3} and bb[2] = {16, -11}, orders them in a third array cc[7].

#include<stdio.h>
void merge(int *, int *, int *, int, int);

int main(){
    int aa[5] = {5, 4, 9, -1, 3};
    int bb[2] = {16, -11};
    int cc[7];

    merge(aa, bb, cc, 5, 2);

    return 0;
}

void merge(int *aa, int *bb, int *cc, int m, int n){

    int i = 0, j = 0, k = 0;

    while(i < m && j < n){
        if(aa[i] < bb[j])
            cc[k++] = aa[i++];    /*Smallest value should be assigned to cc*/
        else
            cc[k++] = bb[j++];
    }

    while(i < m)              /*Transfer the remaining part of longest array*/
        cc[k++] = aa[i++];

    while(j < n)
        cc[k++] = bb[j++];
}

The cc array is correctly filled, but the values are not ordered. Instead of the expected cc = {-11, -1, 3, 4, 5, 9, 16} it returns cc = {5, 4, 9, -1, 3, 16, 11}.
Like the assignments cc[k++] = aa[i++] and cc[k++] = bb[j++] do not work, somehow, or the logical test if aa[i] < bb[j] goes ignored.

I hypothesized operators priority problems, hence I tested with two different standard, with no differences:

gcc main.c -o main.x -Wall
gcc main.c -o main.x -Wall -std=c89

I checked the code many times, unable to find any relevant error. Any suggestion at this point would be appreciated.

Body:
There's no bug in your implementation (at least I don't see any, imho)  The problem is that the merging you have done is not for two sorted arrays (it's for several bunches of sorted numbers).  Case you had feed two already sorted arrays you'd have the result sorted correctly.

The merge sorting algorithm begins with splitting the input into two parts of sorted arrays.  This is done by switching arrays when you detect the element is not in order (it is not greater to last number) You get the first ordered set to fill an array (the first a elements of initial list which happen to be in order, to put into array A, and the second bunch of elements to put them into array B.  This produces two arrays that can be merged (because they are already in order) and this merging makes the result a larger array (this fact is what warrants the algorithm will make larger and larger arrays at each pass and warrants it will finish at some pass.  You don't need to operate array by array, as at each pass the list has less and less packs of larger bunch of sorted elements.  in your case:

1st pass input (the switching points are where the input
is not in order, you don't see them, but you switch arrays
when the next input number is less than the last input one):
  {5}, {4, 9}, {-1, 3}, {16}, {-11}  (See note 2)
after first split:
  {5}, {-1, 3}, {-11}
  {4, 9}, {16}
after first merge result:
  {4, 5, 9}, {-1, 3, 16}, {-11}
after second pass split:
  {4, 5, 9}, {-11}
  {-1, 3, 16}
  result:
  {-1, 3, 4, 5, 9, 16}, {-11}
third pass split:
  {-1, 3, 4, 5, 9, 16}
  {-11}
third pass result:
  {-11, -1, 3, 4, 5, 9, 16}

The algorithm finishes when you don't get two bunches of ordered streams (you don't switch arrays), and you cannot divide further the stream of data.

Your implementation only executes one pass of merge sorting algorithm you need to implement it completely to get sorted output.  The algorithm was designed to make it possible to do several passes when input is not feasible to put in arrays (as you do, so it doesn't fully illustrate the thing with arrays).  Case you have it read from files, you'll see the idea better.

NOTE

Sort programs for huge amounts of data use merging algorithm for bunchs of data that are quicksort'ed first, so we start with buckets of data that don't fit in an array all together.

NOTE 2

The number 16 after number 3 should have been in the same bunch as previous bunch, making it {-1, 3, 16}, but as they where in different arrays at first, and I have not found any way to put them in a list that splits into this arrangement, I have forced the buckets as if 16 < 3, switching artificially the arrays on splitting the input.  This could affect the final result in making an extra pass through the data, but doesn't affect the final result, which is a sorted list of numbers.  I have made this on purpose, and it is not a mistake (it has no relevance to explain how the algorithm works)  Anyway, the algorithm switches lists (I don't like to use arrays when describing this algoritm, as normally merging algorithms don't operate on arrays, as arrays are random access, while lists must be accessed by some iterator means from beginning to end, which is the requirement of the merging sort algorithm)  The same happens to {4, 9}, {16} after the first split, just imagine the result of the comparisons was the one shown, as after the first merge everything is correct.


问:
How to run 2 servers from the same script in Python
I'm building a solution that depends on pub/sub events from IOT devices in the field to kick off some processing. For my purposes, I'm using Flask as to run my main app. I then run the mqtt Client to connect to an MQTT server and listen for events.

When I run my main Flask app.py using python app.py it starts both the Flask service and the MQTT Client. However, when I try to run with gunicorn, it only starts the the Flask service but does not start the MQTT Client.

What production grade service (if not gunicorn) can I use to have both these two services run and how to use it?

```<code>import logging, json, requests, os
import paho.mqtt.client as mqtt

from flask import Flask, request, url_for
from flask_restful import reqparse, abort, Api, Resource
from logging.handlers import SysLogHandler
from logging import StreamHandler
from flask.ext.superadmin import Admin, BaseView, model
from redis import Redis
from rq import Queue
from task import Task
from dateutil.relativedelta import relativedelta
from datetime import datetime, date
..
..
from commons import db, bootstrap

app = Flask(__name__)
api = Api(app)

bootstrap.bootstrap_app(app)

#Setup (Redis) Queue store
q = Queue(connection=Redis())

#Intialize task instance
task = Task(app)
..
...
@app.before_request
def log_request_info():
    app.logger.debug('Headers: %s', request.headers)
    app.logger.debug('Body: %s', request.get_data())

#API resource routing
api.add_resource(Test, '/test')

def session_report(client, userdata, message):
    print message.topic, message.payload

    # Redirect to session_report endpoint
    with app.test_request_context():
        url = 'http://localhost:5000'+url_for('sessionreport', _external=False)
        headers = {'content-type': 'application/json'}
        response = requests.request("POST", url, data=message.payload,
            headers=headers)

def process_ack(client, userdata, message):
    try:
        user = User()
        user.update_account(account_number=next(iter(json.loads(message.payload))))
    except Exception, e:
        print e

def publish_accounts(client):
    user_obj = User()
    users = {user.id: user.account_number for user in user_obj.get_users()}
    client.publish('accounts', payload=json.dumps(users), qos=1, retain=True)

# paho callbacks

def on_connect(client, userdata, flags, rc):
    print "CONNECTED!", str(rc)

    # Subscribe to topis(s) here
    client.subscribe("mine/#")
    client.subscribe("session/#")
    client.subscribe("ack")

    # Add callbacks to subscribed topics
    client.message_callback_add("session/#", session_report)
    client.message_callback_add("ack", process_ack)

    # Publish latest list of accounts
    publish_accounts(client)

def on_subscribe(client, userdata, mid, granted_qos):
    print "Subscribed: ", str(mid), str(granted_qos)

def on_message(client, userdata, msg):
    print msg.topic, msg.payload

def on_publish(client, userdata, mid):
    print "PUBLISHED!"
    app.logger.info('PUBLISHED : {} -- {}'.format(mid, userdata))

if __name__ == '__main__':
    handler = StreamHandler()   #SysLogHandler()
    handler.setLevel(logging.DEBUG)
    app.logger.addHandler(handler)
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_subscribe = on_subscribe
    client.on_message = on_message
    client.connect("localhost", 1883, 60)
    client.loop_start()
    app.run(debug=True, host='0.0.0.0', port=5000)
</code>```

答:
Flask is just a microframework for Python.
if you want to run multi-method at the same time by python, you need to use multi-threading programming.

I read some more Flask document and found that Flask supports multithreaded concurrency.

just try：

```<code>app.run(host='0.0.0.0',port=5000,debug=True, threaded = True)
</code>```

Body:
I'm building a solution that depends on pub/sub events from IOT devices in the field to kick off some processing. For my purposes, I'm using Flask as to run my main app. I then run the mqtt Client to connect to an MQTT server and listen for events.

When I run my main Flask app.py using python app.py it starts both the Flask service and the MQTT Client. However, when I try to run with gunicorn, it only starts the the Flask service but does not start the MQTT Client.

What production grade service (if not gunicorn) can I use to have both these two services run and how to use it?

import logging, json, requests, os
import paho.mqtt.client as mqtt

from flask import Flask, request, url_for
from flask_restful import reqparse, abort, Api, Resource
from logging.handlers import SysLogHandler
from logging import StreamHandler
from flask.ext.superadmin import Admin, BaseView, model
from redis import Redis
from rq import Queue
from task import Task
from dateutil.relativedelta import relativedelta
from datetime import datetime, date
..
..
from commons import db, bootstrap

app = Flask(__name__)
api = Api(app)

bootstrap.bootstrap_app(app)

#Setup (Redis) Queue store
q = Queue(connection=Redis())

#Intialize task instance
task = Task(app)
..
...
@app.before_request
def log_request_info():
    app.logger.debug('Headers: %s', request.headers)
    app.logger.debug('Body: %s', request.get_data())

#API resource routing
api.add_resource(Test, '/test')

def session_report(client, userdata, message):
    print message.topic, message.payload

    # Redirect to session_report endpoint
    with app.test_request_context():
        url = 'http://localhost:5000'+url_for('sessionreport', _external=False)
        headers = {'content-type': 'application/json'}
        response = requests.request("POST", url, data=message.payload,
            headers=headers)

def process_ack(client, userdata, message):
    try:
        user = User()
        user.update_account(account_number=next(iter(json.loads(message.payload))))
    except Exception, e:
        print e

def publish_accounts(client):
    user_obj = User()
    users = {user.id: user.account_number for user in user_obj.get_users()}
    client.publish('accounts', payload=json.dumps(users), qos=1, retain=True)

# paho callbacks

def on_connect(client, userdata, flags, rc):
    print "CONNECTED!", str(rc)

    # Subscribe to topis(s) here
    client.subscribe("mine/#")
    client.subscribe("session/#")
    client.subscribe("ack")

    # Add callbacks to subscribed topics
    client.message_callback_add("session/#", session_report)
    client.message_callback_add("ack", process_ack)

    # Publish latest list of accounts
    publish_accounts(client)

def on_subscribe(client, userdata, mid, granted_qos):
    print "Subscribed: ", str(mid), str(granted_qos)

def on_message(client, userdata, msg):
    print msg.topic, msg.payload

def on_publish(client, userdata, mid):
    print "PUBLISHED!"
    app.logger.info('PUBLISHED : {} -- {}'.format(mid, userdata))

if __name__ == '__main__':
    handler = StreamHandler()   #SysLogHandler()
    handler.setLevel(logging.DEBUG)
    app.logger.addHandler(handler)
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_subscribe = on_subscribe
    client.on_message = on_message
    client.connect("localhost", 1883, 60)
    client.loop_start()
    app.run(debug=True, host='0.0.0.0', port=5000)

Body:
Flask is just a microframework for Python.
if you want to run multi-method at the same time by python, you need to use multi-threading programming.

I read some more Flask document and found that Flask supports multithreaded concurrency.

just try：

app.run(host='0.0.0.0',port=5000,debug=True, threaded = True)


答:
This is simple when using data.table's non-equi join capabilities:</p>

```<code>library(data.table)

# convert to data.table
setDT(df_X)
setDT(df_Y)

# data preparation:
df_X[, X1 := as.IDate(X1)]
df_Y[, c("Y3", "Y4") := lapply(.SD, as.IDate), .SDcols = c("Y3", "Y4")]
df_Y[, Y1 := as.numeric(Y1)]
df_X[, X5 := as.numeric(X5)]

# non-equi join + update by reference
df_X[df_Y, on = .(X3 = Y1, X1 >= Y3, X1 <= Y4), X5 := i.Y2]  #  <-- the main part

# convert back to data.frame
setDF(df_X)
setDF(df_Y)
</code>```

Title: R - Replace column values where certain conditions between dataframes are met

Body:
I have two dataframes which look like this:

> df_X
            X1 X2 X3 X5
1   2017-05-02 21  1 NA
2   2017-05-02 10  1 NA
3   2017-05-02  5  1 NA
4   2017-05-02  5  1 NA
5   2017-05-02 25  1 NA
6   2017-05-02 20  1 NA
7   2017-05-04 25  1 NA
8   2017-05-08 25  1 NA
9   2017-05-10 20  1 NA
10  2017-05-13 30  1 NA
11  2017-05-17  5  1 NA
12  2017-05-20 25  1 NA
13  2017-05-23 15  1 NA
14  2017-05-25 20  1 NA
15  2017-05-27 35  1 NA
16  2017-05-30 30  1 NA
17  2017-06-01 10  1 NA
18  2017-06-03 10  1 NA
19  2017-06-05  5  1 NA
20  2017-06-08 10  1 NA

and

> df_Y
   Y1        Y2         Y3         Y4
1   1 0.6656641 2017-08-01 2017-08-02
2   1 1.0285626 2017-08-17 2017-08-18
3   1 1.1905584 2017-08-21 2017-08-22
4   1 1.1026008 2017-08-24 2017-08-25
5   1 1.1570583 2017-08-28 2017-08-29
6   1 1.0676820 2017-08-31 2017-09-01
7   2 1.1003816 2017-08-31 2017-09-01
8   2 1.1901956 2017-09-04 2017-09-05
9   1 1.1636756 2017-09-05 2017-09-05
10  1 1.1724968 2017-09-07 2017-09-07
11  2 1.1335978 2017-09-08 2017-09-09
12  1 1.0873912 2017-09-08 2017-09-08
13  1 1.1238168 2017-09-11 2017-09-11
14  2 1.1564612 2017-09-12 2017-09-13
15  2 1.1688628 2017-09-14 2017-09-15
16  1 1.2326152 2017-09-14 2017-09-15
17  2 1.2014378 2017-09-16 2017-09-16
18  2 1.1911753 2017-09-19 2017-09-19
19  1 1.1445341 2017-09-19 2017-09-20
20  1 1.1299295 2017-09-21 2017-09-22

I'd like to replace the values of X5 with the value from Y2 where X1 is between Y3 and Y4, and X3 matches Y1.

This is easy to achieve using a loop:

for (i in 1:NROW(df_Y)) {
  df_X$X5[(df_X$X1 >= df_Y$Y3[i]) &
            (df_X$X1 <= df_Y$Y4[i]) & (df_X$X3 == df_Y$Y1[i])] <- df_Y$Y2[i]
}

> df_X_result
            X1 X2 X3        X5
1   2017-05-02 21  1        NA
            ...
26  2017-08-13 11  1        NA
27  2017-08-18 10  1 1.0285626
28  2017-08-21  5  1 1.1905584
29  2017-08-23  5  1        NA
30  2017-08-25 20  1 1.1026008
31  2017-08-28 10  1 1.1570583
32  2017-08-30  3  1        NA
33  2017-08-31 10  1 1.0676820
34  2017-09-04 18  1        NA
35  2017-09-05 25  1 1.1636756
36  2017-09-07 30  1 1.1724968
37  2017-09-08 20  1 1.0873912
38  2017-09-11 20  1 1.1238168
39  2017-09-13  5  1        NA
40  2017-09-14 25  1 1.2326152
41  2017-09-15 30  1 1.2326152

The loop takes quite a while to complete for the whole dataframe, so I was wondering if there is a vectorized solution, possibly using group_by()?

df_X <- structure(list(X1 = c("2017-05-02", "2017-05-02", "2017-05-02",
"2017-05-02", "2017-05-02", "2017-05-02", "2017-05-04", "2017-05-08",
"2017-05-10", "2017-05-13", "2017-05-17", "2017-05-20", "2017-05-23",
"2017-05-25", "2017-05-27", "2017-05-30", "2017-06-01", "2017-06-03",
"2017-06-05", "2017-06-08", "2017-06-10", "2017-06-14", "2017-06-16",
"2017-07-15", "2017-08-09", "2017-08-13", "2017-08-18", "2017-08-21",
"2017-08-23", "2017-08-25", "2017-08-28", "2017-08-30", "2017-08-31",
"2017-09-04", "2017-09-05", "2017-09-07", "2017-09-08", "2017-09-11",
"2017-09-13", "2017-09-14", "2017-09-15", "2017-09-18", "2017-09-19",
"2017-09-21", "2017-09-23", "2017-09-25", "2017-09-26", "2017-09-28",
"2017-09-29", "2017-09-30", "2017-10-02", "2017-10-03", "2017-10-04",
"2017-10-05", "2017-10-06", "2017-10-09", "2017-10-10", "2017-10-11",
"2017-10-12", "2017-10-12", "2017-10-14", "2017-10-16", "2017-10-18",
"2017-10-20", "2017-10-21", "2017-10-24", "2017-10-27", "2017-10-28",
"2017-10-31", "2017-11-02", "2017-11-03", "2017-11-06", "2017-11-08",
"2017-05-02", "2017-05-02", "2017-05-02", "2017-05-02", "2017-05-02",
"2017-05-03", "2017-05-05", "2017-05-09", "2017-05-12", "2017-05-16",
"2017-05-19", "2017-05-22", "2017-05-25", "2017-05-27", "2017-05-29",
"2017-05-31", "2017-06-02", "2017-06-05", "2017-06-07", "2017-06-14",
"2017-06-16", "2017-06-19", "2017-09-01", "2017-09-05", "2017-09-07",
"2017-09-08", "2017-09-11", "2017-09-12", "2017-09-14", "2017-09-15",
"2017-09-18", "2017-09-19", "2017-09-21", "2017-09-22", "2017-09-25",
"2017-09-27", "2017-09-29", "2017-09-30", "2017-10-02", "2017-10-03",
"2017-10-04", "2017-10-05", "2017-10-06", "2017-10-09", "2017-10-09",
"2017-10-11", "2017-10-11", "2017-10-12", "2017-10-14", "2017-10-16",
"2017-10-17", "2017-10-19", "2017-10-20", "2017-10-21", "2017-10-25",
"2017-10-27", "2017-10-31", "2017-11-01", "2017-11-02", "2017-11-03",
"2017-11-06", "2017-11-08"), X2 = c(21, 10, 5, 5, 25, 20, 25,
25, 20, 30, 5, 25, 15, 20, 35, 30, 10, 10, 5, 10, 5, 10, 15,
7, 23, 11, 10, 5, 5, 20, 10, 3, 10, 18, 25, 30, 20, 20, 5, 25,
30, 15, 10, 20, 29, 25, 30, 10, 10, 5, 5, 30, 15, 25, 25, 5,
30, 5, 10, 3, 20, 55, 10, 15, 30, 20, 30, 10, 20, 25, 25, 15,
20, 35, 20, 10, 15, 10, 15, 5, 5, 5, 25, 20, 5, 15, 30, 20, 20,
10, 20, 5, 20, 15, 5, 5, 5, 25, 25, 10, 10, 5, 5, 30, 25, 10,
5, 20, 10, 30, 20, 25, 10, 20, 15, 10, 5, 30, 5, 10, 30, 3, 10,
10, 40, 20, 24, 30, 40, 15, 10, 10, 5, 15, 30), X3 = c(1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2), X5 = c(NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("X1",
"X2", "X3", "X5"), row.names = c(NA, 135L), class = "data.frame")

.

df_Y <- structure(list(Y1 = c("1", "1", "1", "1", "1", "1", "2", "2",
"1", "1", "2", "1", "1", "2", "2", "1", "2", "2", "1", "1", "2",
"1", "1", "2", "2", "1", "2", "2", "1", "1", "2", "1", "1", "2",
"2", "1", "2", "2", "2", "1", "1", "1", "2", "2", "1", "1", "2",
"1", "1", "2", "2", "2", "2", "2", "2", "2"), Y2 = c(0.665664077829585,
1.02856261889775, 1.19055836913068, 1.10260084679125, 1.15705828895831,
1.06768199117752, 1.10038159049195, 1.19019555343219, 1.16367557830325,
1.17249680795712, 1.13359781336505, 1.08739115948259, 1.12381677088993,
1.15646116283926, 1.16886280825931, 1.23261515446765, 1.20143782448638,
1.19117526432255, 1.14453414539176, 1.12992954478391, 1.00942359172597,
1.36304817720811, 0.977737663980795, 0.803038132093719, 0.658557316689605,
1.08897993760763, 1.02561012617194, 0.953197521830857, 1.10932969513697,
1.14650953305854, 1.08216085976536, 1.04156195299253, 0.945898621136812,
0.949689535186447, 1.00475292030475, 1.1143173236383, 1.00267210653824,
0.887215247393604, 0.974738456110934, 1.05929723094296, 1.02576829587045,
1.02233864565999, 0.984999990038355, 1.06285567360253, 1.04974288902827,
1.0846639113405, 1.11423291175236, 0.851355064479879, 0.749599945595823,
0.935991720991809, 0.895595684187917, 0.9096390430551, 1.07024512065878,
0.999910689243934, 0, NA), Y3 = c("2017-08-01", "2017-08-17",
"2017-08-21", "2017-08-24", "2017-08-28", "2017-08-31", "2017-08-31",
"2017-09-04", "2017-09-05", "2017-09-07", "2017-09-08", "2017-09-08",
"2017-09-11", "2017-09-12", "2017-09-14", "2017-09-14", "2017-09-16",
"2017-09-19", "2017-09-19", "2017-09-21", "2017-09-21", "2017-09-22",
"2017-09-25", "2017-09-25", "2017-09-27", "2017-09-27", "2017-09-28",
"2017-09-30", "2017-09-30", "2017-10-02", "2017-10-03", "2017-10-02",
"2017-10-04", "2017-10-05", "2017-10-06", "2017-10-06", "2017-10-07",
"2017-10-09", "2017-10-10", "2017-10-07", "2017-10-10", "2017-10-11",
"2017-10-11", "2017-10-12", "2017-10-14", "2017-10-16", "2017-10-16",
"2017-10-17", "2017-10-19", "2017-10-18", "2017-10-20", "2017-10-20",
"2017-10-21", "2017-10-25", "2017-11-02", "2017-11-06"), Y4 = c("2017-08-02",
"2017-08-18", "2017-08-22", "2017-08-25", "2017-08-29", "2017-09-01",
"2017-09-01", "2017-09-05", "2017-09-05", "2017-09-07", "2017-09-09",
"2017-09-08", "2017-09-11", "2017-09-13", "2017-09-15", "2017-09-15",
"2017-09-16", "2017-09-19", "2017-09-20", "2017-09-22", "2017-09-22",
"2017-09-23", "2017-09-26", "2017-09-26", "2017-09-28", "2017-09-28",
"2017-09-28", "2017-09-30", "2017-09-30", "2017-10-02", "2017-10-03",
"2017-10-03", "2017-10-04", "2017-10-05", "2017-10-07", "2017-10-06",
"2017-10-07", "2017-10-09", "2017-10-10", "2017-10-09", "2017-10-10",
"2017-10-12", "2017-10-11", "2017-10-12", "2017-10-14", "2017-10-17",
"2017-10-16", "2017-10-17", "2017-10-19", "2017-10-19", "2017-10-20",
"2017-10-21", "2017-10-25", "2017-10-28", "2017-11-04", NA)), .Names = c("Y1",
"Y2", "Y3", "Y4"), row.names = c(NA, 56L), class = "data.frame")

Body:
This is simple when using data.table's non-equi join capabilities:

library(data.table)

# convert to data.table
setDT(df_X)
setDT(df_Y)

# data preparation:
df_X[, X1 := as.IDate(X1)]
df_Y[, c("Y3", "Y4") := lapply(.SD, as.IDate), .SDcols = c("Y3", "Y4")]
df_Y[, Y1 := as.numeric(Y1)]
df_X[, X5 := as.numeric(X5)]

# non-equi join + update by reference
df_X[df_Y, on = .(X3 = Y1, X1 >= Y3, X1 <= Y4), X5 := i.Y2]  #  <-- the main part

# convert back to data.frame
setDF(df_X)
setDF(df_Y)


问:
How to add multiple data rows at once from UserForm to Excel DataBase
I'm making some sort of football database where I would input data using a userform and where I want to retrieve data from my excel database.

I have a worksheet named: "wedstrijden" This worksheet contain the columns: Date, HomeTeam, AwayTeam, HomeScore,AwayScore, HomeOdds and AwayOdds

My other worksheet is named: "ingevenuitslagen" This worksheet contains my userform called UitslagenIngeven

Using the code below I'm able to input my data from the userform to my "wedstrijden" worksheet

```<code>Private Sub putAway_Click()
Dim ingevenuitslagen As Worksheet
Set ingevenuitslagen = ThisWorkbook.Sheets("wedstrijden")
NextRow = ingevenuitslagen.Cells(Rows.Count, 1).End(xlUp).Row + 1
ingevenuitslagen.Cells(NextRow, 1) = CDate(date_txt.Text)
ingevenuitslagen.Cells(NextRow, 2) = UitslagenIngeven.cboHomeTeam
ingevenuitslagen.Cells(NextRow, 3) = UitslagenIngeven.cboAwayTeam
ingevenuitslagen.Cells(NextRow, 4) = UitslagenIngeven.cboHScore
ingevenuitslagen.Cells(NextRow, 5) = UitslagenIngeven.cboAScore
ingevenuitslagen.Cells(NextRow, 6) = Val(UitslagenIngeven.hodds_txt.Text)
ingevenuitslagen.Cells(NextRow, 7) = Val(UitslagenIngeven.aodds_txt.Text)
End Sub
</code>```

But this is only to put away 1 row. I would like to make the possibility to put away 10 or 15 rows at once. So I would make a userform with the possibility to put away 20 rows BUT it should be able to put away only those rows that are filled in.

Is this possible? And how should I adjust my userform? Can I just copy the text and combobox areas ?

答:
Good day all.

I have this same challenge. Mine is to be able to place a Customer's Orders. With the code I have I can only place one product per order at a time for the customer. I want to be able to place multiple products per order for one customer at the same time in a Userform and it will update multiple rows. The code below can only update one row with one product in a row for one customer:

```<code>Private Sub cmdAdd_Click()
Dim lRow As Long
Dim ws As Worksheet
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
With ws
    .Cells(lRow, 1).Value = Me.Data1.Value
    .Cells(lRow, 2).Value = Me.Data2.Value
    .Cells(lRow, 3).Value = Me.Data3.Value
    .Cells(lRow, 4).Value = Me.Data4.Value
    .Cells(lRow, 5).Value = Me.Data5.Value
    .Cells(lRow, 6).Value = Me.Data6.Value
    .Cells(lRow, 7).Value = Me.Data7.Value
    .Cells(lRow, 8).Value = Me.Data8.Value
    .Cells(lRow, 9).Value = Me.Data9.Value
    .Cells(lRow, 10).Value = Me.Data10.Value
End With
End Sub
</code>```

The above can only update One product per customer. A customer could place order for more than one product.

Body:
I'm making some sort of football database where I would input data using a userform and where I want to retrieve data from my excel database.

I have a worksheet named: "wedstrijden" This worksheet contain the columns: Date, HomeTeam, AwayTeam, HomeScore,AwayScore, HomeOdds and AwayOdds

My other worksheet is named: "ingevenuitslagen" This worksheet contains my userform called UitslagenIngeven

Using the code below I'm able to input my data from the userform to my "wedstrijden" worksheet

Private Sub putAway_Click()
Dim ingevenuitslagen As Worksheet
Set ingevenuitslagen = ThisWorkbook.Sheets("wedstrijden")
NextRow = ingevenuitslagen.Cells(Rows.Count, 1).End(xlUp).Row + 1
ingevenuitslagen.Cells(NextRow, 1) = CDate(date_txt.Text)
ingevenuitslagen.Cells(NextRow, 2) = UitslagenIngeven.cboHomeTeam
ingevenuitslagen.Cells(NextRow, 3) = UitslagenIngeven.cboAwayTeam
ingevenuitslagen.Cells(NextRow, 4) = UitslagenIngeven.cboHScore
ingevenuitslagen.Cells(NextRow, 5) = UitslagenIngeven.cboAScore
ingevenuitslagen.Cells(NextRow, 6) = Val(UitslagenIngeven.hodds_txt.Text)
ingevenuitslagen.Cells(NextRow, 7) = Val(UitslagenIngeven.aodds_txt.Text)
End Sub

But this is only to put away 1 row. I would like to make the possibility to put away 10 or 15 rows at once. So I would make a userform with the possibility to put away 20 rows BUT it should be able to put away only those rows that are filled in.

Is this possible? And how should I adjust my userform? Can I just copy the text and combobox areas ?

Body:
Good day all.

I have this same challenge. Mine is to be able to place a Customer's Orders. With the code I have I can only place one product per order at a time for the customer. I want to be able to place multiple products per order for one customer at the same time in a Userform and it will update multiple rows. The code below can only update one row with one product in a row for one customer:

Private Sub cmdAdd_Click()
Dim lRow As Long
Dim ws As Worksheet
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
With ws
    .Cells(lRow, 1).Value = Me.Data1.Value
    .Cells(lRow, 2).Value = Me.Data2.Value
    .Cells(lRow, 3).Value = Me.Data3.Value
    .Cells(lRow, 4).Value = Me.Data4.Value
    .Cells(lRow, 5).Value = Me.Data5.Value
    .Cells(lRow, 6).Value = Me.Data6.Value
    .Cells(lRow, 7).Value = Me.Data7.Value
    .Cells(lRow, 8).Value = Me.Data8.Value
    .Cells(lRow, 9).Value = Me.Data9.Value
    .Cells(lRow, 10).Value = Me.Data10.Value
End With
End Sub

The above can only update One product per customer. A customer could place order for more than one product.


问:
C++ Modules TS & CMake
I am curious about the C++ Modules TS. I have played a little around with Clang's implementation. Only one or two files or so at a time.

Now I would like to try something bigger than that. And I would like to use CMake.

Does someone know if there is some good way to use the Clang modules implementation with CMake or are there already some CMake modules which help me with this?

I would really like to know. Otherwise I have to consider using a different build system.

答:
I would suggest you try build2:

https://build2.org/build2/doc/build2-build-system-manual.xhtml#cxx-modules

It supports modules for Visual Studio, gcc and clang. And for gcc there is a package that contains the standard library:

https://build2.org/pkg/hello/libstd-modules?f=full&q=library

Note that Microsoft implementation, as of Visual Studio 2017 update 4, is using the old syntax in the .ixx files (module xyz; instead of export module xyz; where the latter is what the last Modules TS draft mandates)

Title: C++ Modules TS & CMake


问:
add text , subtext & image in single table cell
I want to add text , subtext & image in single table cell like this =>

http://img153.imageshack.us/img153/5451/tablevcinterface.jpg

I want add subtext below main text (e.g. => Apple in main text & iphone is subtext which is shown below Apple)
How can i add ?
Any sample code or tutorial link is helpful.
Thanks in advance..

答: To achieve this you can refer to TableViewSuite sample application.</p>


问:
fullcalendar (Premium Scheduler add-on) - reduce the gap between days and show 3 months
I am using fullcalendar - premium Scheduler add-on to show 3 months view

But unable to reduce the gap inside the cell content to show all 3 months at once.

PS: Not able to simulate jsFiddle example while I am using the licenced version... Sorry for that

Code:

```<code>$(function() {
  $('#calendar').fullCalendar({
    now: '2017-11-07',
    editable: true,
    aspectRatio: 1.8,
    header: {
      left: 'today prev,next',
      center: 'title',
      right: 'month,timeline3Months'
    },
    defaultView: 'timeline3Months',
    views: {
      timeline3Months: {
        type: 'timelineMonth',
        slotDuration: { days: 1 },
        duration: { months: 3 }
      }
    },
    buttonText: {
      month: '1 Month',
      timeline3Months: '3 Months',
    },
    navLinks: true,
    events: [
      { id: '1', resourceId: 'b', start: '2017-11-15T02:00:00', end: '2017-12-08T07:00:00', title: 'Event 1' },
    ],
  });
});
</code>```

Output:

Show all 3 months without scrolling by reducing the gap between cell
  content

答:
Hurray!

Got the answer by doing the below

```<code>slotWidth: 8,
</code>```

Body:
I am using fullcalendar - premium Scheduler add-on to show 3 months view

But unable to reduce the gap inside the cell content to show all 3 months at once.

PS: Not able to simulate jsFiddle example while I am using the licenced version... Sorry for that

Code:

$(function() {
  $('#calendar').fullCalendar({
    now: '2017-11-07',
    editable: true,
    aspectRatio: 1.8,
    header: {
      left: 'today prev,next',
      center: 'title',
      right: 'month,timeline3Months'
    },
    defaultView: 'timeline3Months',
    views: {
      timeline3Months: {
        type: 'timelineMonth',
        slotDuration: { days: 1 },
        duration: { months: 3 }
      }
    },
    buttonText: {
      month: '1 Month',
      timeline3Months: '3 Months',
    },
    navLinks: true,
    events: [
      { id: '1', resourceId: 'b', start: '2017-11-15T02:00:00', end: '2017-12-08T07:00:00', title: 'Event 1' },
    ],
  });
});

Output:

Show all 3 months without scrolling by reducing the gap between cell
  content

Body:
Hurray!

Got the answer by doing the below

slotWidth: 8,


答:
Add these two code lines:

```<code>geom_text(aes(color = value > 0.1)) +
scale_color_manual(guide = FALSE, values = c("black", "white"))
</code>```

Here text color depends on value (value > 0.1) and colors are specified with scale_color_manual.

For the output like this:

Title: Text color based on contrast against background

Body:
I have the following plot:

m <- structure(list(Var1 = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L), .Label = c("FE", "AG",
"NO", "SPH", "SEP", "H/I", "CMP"), class = "factor"), Var2 = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L
), .Label = c("FE", "AG", "NO", "SPH", "SEP", "H/I", "CMP"), class = "factor"),
    value = c(0, 0.0419753086419753, 0.172839506172839, 0.0740740740740741,
    0.0123456790123457, 0.111111111111111, 0.0617283950617284,
    0.0419753086419753, 0, 0.0765432098765432, 0.0246913580246914,
    0.00493827160493827, 0.0567901234567901, 0.0320987654320988,
    0.172839506172839, 0.0765432098765432, 0, 0.175308641975309,
    0.0197530864197531, 0.177777777777778, 0.120987654320988,
    0.0740740740740741, 0.0246913580246914, 0.175308641975309,
    0, 0.00740740740740741, 0.0814814814814815, 0.0395061728395062,
    0.0123456790123457, 0.00493827160493827, 0.0197530864197531,
    0.00740740740740741, 0, 0.0197530864197531, 0.00987654320987654,
    0.111111111111111, 0.0567901234567901, 0.177777777777778,
    0.0814814814814815, 0.0197530864197531, 0, 0.0716049382716049,
    0.0617283950617284, 0.0320987654320988, 0.120987654320988,
    0.0395061728395062, 0.00987654320987654, 0.0716049382716049,
    0), vtext = c("0.0%", "4.2%", "17.3%", "7.4%", "1.2%", "11.1%",
    "6.2%", "4.2%", "0.0%", "7.7%", "2.5%", "0.5%", "5.7%", "3.2%",
    "17.3%", "7.7%", "0.0%", "17.5%", "2.0%", "17.8%", "12.1%",
    "7.4%", "2.5%", "17.5%", "0.0%", "0.7%", "8.1%", "4.0%",
    "1.2%", "0.5%", "2.0%", "0.7%", "0.0%", "2.0%", "1.0%", "11.1%",
    "5.7%", "17.8%", "8.1%", "2.0%", "0.0%", "7.2%", "6.2%",
    "3.2%", "12.1%", "4.0%", "1.0%", "7.2%", "0.0%")), .Names = c("Var1",
"Var2", "value", "vtext"), row.names = c(NA, -49L), class = "data.frame")

library(ggplot2)
ggplot(data = m, aes(x = Var2, y = Var1, fill = value, label = vtext)) +
    xlab("") + ylab("") +
    geom_tile() +
    geom_text() +
    scale_fill_gradient(low="white", high="darkmagenta") +
    # Sample code for subtitles: ggtitle(bquote(atop("Age distribution", atop(italic(.(subtitle)), ""))))
    ggtitle(bquote(atop(.(title), atop(italic(.(subtitle)), "")))) +
    theme(axis.text.y = element_text(size = 12), axis.text.x = element_text(size = 12),
          axis.title = element_text(size = 16, face = "bold"),
          plot.title = element_text(size = 20),
          panel.background = element_rect(fill = "white"),
          legend.key.size = unit(0.02, "npc"),
          legend.text = element_text(size = 14),
          legend.title = element_text(size = 16))

Which results in:

The problem, is that the text in the darker squares is difficult to read. Is it possible to change the text color based on the background color, so the text in the clear boxes is black and in the darker boxes is white?

Body:
Add these two code lines:

geom_text(aes(color = value > 0.1)) +
scale_color_manual(guide = FALSE, values = c("black", "white"))

Here text color depends on value (value > 0.1) and colors are specified with scale_color_manual.

For the output like this:


问:
Change button styles for ngx-ui-switch angular 2
I'm using ngx-ui-switch for switch buttons. I wanted to give custom size for the buttons.

This plugin generates some css which is not found in my project folder.

If i try to change it manually like .switch-small[_ngcontent-c20] {size:40px} is not working. Please help

Original HTML

<ui-switch [checked]="staticProposalFlag" (change)="onProposalChange($event)" size="small" class="float-left" switchColor="#D9D9D9" color="#1D79D1"></ui-switch>```
</div>
</div>
</p>

<p>Generated HTML
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ui-switch _ngcontent-c13="" class="float-left" color="#1D79D1" size="small" switchcolor="#D9D9D9" _nghost-c20="" ng-reflect-size="small" ng-reflect-color="#1D79D1" ng-reflect-switch-color="#D9D9D9" ng-reflect-checked="true">
  <span _ngcontent-c20="" class="switch checked switch-small" style="background-color: rgb(29, 121, 209); border-color: rgb(223, 223, 223);">
    <small _ngcontent-c20="" style="background: rgb(217, 217, 217);">
    </small>
    </span>
</ui-switch></code>```

答:
You cannot change the CSS of the component itself with the ng identifier added before, so try to add a real class instead of float left which is a style rule. Create a class customSwitch (replace float:left). And in your CSS add
.switchCustom { float:left; width: 100px } + remove size=small it looks like a parameter that could be in conflict when trying to set the width.

Body:
I'm using ngx-ui-switch for switch buttons. I wanted to give custom size for the buttons.

This plugin generates some css which is not found in my project folder.

If i try to change it manually like .switch-small[_ngcontent-c20] {size:40px} is not working. Please help

Original HTML

<ui-switch [checked]="staticProposalFlag" (change)="onProposalChange($event)" size="small" class="float-left" switchColor="#D9D9D9" color="#1D79D1"></ui-switch>

Generated HTML

<ui-switch _ngcontent-c13="" class="float-left" color="#1D79D1" size="small" switchcolor="#D9D9D9" _nghost-c20="" ng-reflect-size="small" ng-reflect-color="#1D79D1" ng-reflect-switch-color="#D9D9D9" ng-reflect-checked="true">

</ui-switch>


问:
How to store username and password in one application and retrieve values in another application nativescript angular2
I just want to save user name and password in one nativescript application. Then in Second nativescript application, I have to retrieve the saved username and password.

I don't know how to achieve this in nativescript angular2. Any help is appreciated.thanks.

答:
I know one way for passing secure data between application which might be helpful for now.

You can store the encrypted username and password in the local storage of the browser and than retrieve these encrypted username and password from local storage for further processing.

For encryption, you can use RSA-128 with timestamp.


问:
VBA: Using the DateAdd Function
I have a spreadsheet of with identical rows repeated in sequences of three. For example below A represents a row of information.  In column S are dates.  I'd like to change the date in column S in the second row of each sequence to one month after the original date and the third row of each sequence to two months after the original date and do continue this for the entire spreadsheet using a loop and the DateAdd function.

Here is the code I have now, but the I'm getting a compile error on the DateAdd function (this is my first time using it):

```<code>Sub DateChange()

Dim r As Long

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    With Cells(r, 1).EntireRow
        .Copy
        .Resize(2).Offset(1, 0).Insert Shift:=xlDown
    End With
    Cells(r + 1, "S").Value = DateAdd("m", 1, Cells(r, "S"))
    Cells(r + 2, "S").Value = DateAdd("m", 2, Cells(r, "S"))
Next r

Application.ScreenUpdating = True

End Sub
</code>```

答:
If you experience difficulties using the DataAdd function then you can bypass it like this:

```<code>Option Explicit

Sub DateChange()

Dim r As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("Sheet1")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
    With ws.Cells(r, 1).EntireRow
        .Copy
        .Resize(2).Offset(1, 0).Insert Shift:=xlDown
    End With
    dttTemp = ws.Cells(r, "S").Value
    ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1, Day(dttTemp))
    ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2, Day(dttTemp))
Next r

Application.ScreenUpdating = True

End Sub
</code>```

Note, that I am also fully qualifying all references (for good coding practice and to avoid errors). This means I am referring to ThisWorkbook.Worksheets("Sheet1").Cells(r, "S").Value instead of just Cells(r, "S") (as you did). Like this VBA knows in which Excel file to look and at which sheet to look at when searching for cell S3 (for example). Also, I am telling VBA that I am interested in that cell's .Value and not .Value2 or .Formula or anything else.

Let me know if the above helped.

Title: VBA: Using the DateAdd Function

Body:
I have a spreadsheet of with identical rows repeated in sequences of three. For example below A represents a row of information.  In column S are dates.  I'd like to change the date in column S in the second row of each sequence to one month after the original date and the third row of each sequence to two months after the original date and do continue this for the entire spreadsheet using a loop and the DateAdd function.

Here is the code I have now, but the I'm getting a compile error on the DateAdd function (this is my first time using it):

Sub DateChange()

Dim r As Long

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    With Cells(r, 1).EntireRow
        .Copy
        .Resize(2).Offset(1, 0).Insert Shift:=xlDown
    End With
    Cells(r + 1, "S").Value = DateAdd("m", 1, Cells(r, "S"))
    Cells(r + 2, "S").Value = DateAdd("m", 2, Cells(r, "S"))
Next r

Application.ScreenUpdating = True

End Sub

Body:
If you experience difficulties using the DataAdd function then you can bypass it like this:

Option Explicit

Sub DateChange()

Dim r As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("Sheet1")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
    With ws.Cells(r, 1).EntireRow
        .Copy
        .Resize(2).Offset(1, 0).Insert Shift:=xlDown
    End With
    dttTemp = ws.Cells(r, "S").Value
    ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1, Day(dttTemp))
    ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2, Day(dttTemp))
Next r

Application.ScreenUpdating = True

End Sub

Note, that I am also fully qualifying all references (for good coding practice and to avoid errors). This means I am referring to ThisWorkbook.Worksheets("Sheet1").Cells(r, "S").Value instead of just Cells(r, "S") (as you did). Like this VBA knows in which Excel file to look and at which sheet to look at when searching for cell S3 (for example). Also, I am telling VBA that I am interested in that cell's .Value and not .Value2 or .Formula or anything else.

Let me know if the above helped.


问:
pointers in C++ (need overview)
```<code>int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
</code>```

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.

答:
Sorry, but your analysis is incorrect.

Starting with the first part of your code

```<code>int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
</code>```

and your analysis of it

p1 points to the first value and p2 points to the second value.

Your analysis is roughly correct.   I'll give a slightly more complete description.

p1 is a variable of type int * (i.r. a pointer to an int).   The assignment p1 = &firstvalue assigns the value of p1 to be the address of the variable firstvalue.    This is sometimes said to mean that the pointer p1 is assigned to point at firstvalue.

The same description applies to p2 and secondvalue.

Now, for the next statement

```<code>*p1 = 10;    //line 1
</code>```

and your analysis of it

Now, p1 points to value 10.

This is incorrect.   p1 does not point to the value 10.

The statement, *p1 = 10 assigns the value 10 to the result of *p1.   *p1 is a reference to whatever p1 points at, which (as per above) is firstvalue.   Accordingly, the assignment *p1 = 10 has the effect of assigning firstvalue to the value 10.

This brings us to your first question (albeit one you wrote without a question mark).

Does this means that first value now stores 10. (line 1)

If by "first value" you mean "the variable named firstvalue", the answer here is "yes".

Now, we come to the next code statement

```<code>*p2 = *p1;  //line 2
</code>```

and your analysis

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

You are completely and utterly wrong here.

To better understand, let's break the statement into parts.  *p1 obtains a reference to the variable pointed to by p1 - which is firstvalue (which has a value 10).   *p2 obtains a reference to the variable pointed to by p2 - which is secondvalue.    The assignment *p2 = *p1 therefore has the same effect as secondvalue = firstvalue.

p1 still points at (contains the address of) firstvalue.   Similarly, p2 still points at secondvalue.   Both variables firstvalue and secondvalue have the value 10.

Now we come to line 3

```<code>p1 = p2;   //line 3
</code>```

And your observation about it it

Lastly, I have no clue of line 3. So, need some help over there too.

Uh hu.

p2 is a pointer, and its value is &secondvalue - the address of secondvalue.   The assignment p1 = p2 assign the value of p1 to equal the value of p2.   This means that p1 and p2 both contain the value &secondvalue.   (Or that both the pointers p1 and p2 point to secondvalue).

A consequence is that

```<code>*p1 = 20;
</code>```

has the effect of assigning secondvalue to have the value 20.   firstvalue is unaffected, and still contains the value 10.

Title: pointers in C++ (need overview)

Body:
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.

Body:
Sorry, but your analysis is incorrect.

Starting with the first part of your code

int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;

and your analysis of it

p1 points to the first value and p2 points to the second value.

Your analysis is roughly correct.   I'll give a slightly more complete description.

p1 is a variable of type int * (i.r. a pointer to an int).   The assignment p1 = &firstvalue assigns the value of p1 to be the address of the variable firstvalue.    This is sometimes said to mean that the pointer p1 is assigned to point at firstvalue.

The same description applies to p2 and secondvalue.

Now, for the next statement

*p1 = 10;    //line 1

and your analysis of it

Now, p1 points to value 10.

This is incorrect.   p1 does not point to the value 10.

The statement, *p1 = 10 assigns the value 10 to the result of *p1.   *p1 is a reference to whatever p1 points at, which (as per above) is firstvalue.   Accordingly, the assignment *p1 = 10 has the effect of assigning firstvalue to the value 10.

This brings us to your first question (albeit one you wrote without a question mark).

Does this means that first value now stores 10. (line 1)

If by "first value" you mean "the variable named firstvalue", the answer here is "yes".

Now, we come to the next code statement

*p2 = *p1;  //line 2

and your analysis

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

You are completely and utterly wrong here.

To better understand, let's break the statement into parts.  *p1 obtains a reference to the variable pointed to by p1 - which is firstvalue (which has a value 10).   *p2 obtains a reference to the variable pointed to by p2 - which is secondvalue.    The assignment *p2 = *p1 therefore has the same effect as secondvalue = firstvalue.

p1 still points at (contains the address of) firstvalue.   Similarly, p2 still points at secondvalue.   Both variables firstvalue and secondvalue have the value 10.

Now we come to line 3

p1 = p2;   //line 3

And your observation about it it

Lastly, I have no clue of line 3. So, need some help over there too.

Uh hu.

p2 is a pointer, and its value is &secondvalue - the address of secondvalue.   The assignment p1 = p2 assign the value of p1 to equal the value of p2.   This means that p1 and p2 both contain the value &secondvalue.   (Or that both the pointers p1 and p2 point to secondvalue).

A consequence is that

*p1 = 20;

has the effect of assigning secondvalue to have the value 20.   firstvalue is unaffected, and still contains the value 10.


问:
Check equality for two Spark DataFrames in Scala
I'm new to Scala and am having problems writing unit tests.

I'm trying to compare and check equality for two Spark DataFrames in Scala for unit testing, and realized that there is no easy way to check equality for two Spark DataFrames.

The C++ equivalent code would be (assuming that the DataFrames are represented as double arrays in C++):

```<code>    int expected[10][2];
    int result[10][2];
    for (int row = 0; row < 10; row++) {
        for (int col = 0; col < 2; col++) {
            if (expected[row][col] != result[row][col]) return false;
        }
    }
</code>```

The actual test would involve testing for equality based on the data types of the columns of the DataFrames (testing with precision tolerance for floats, etc).

It seems like there's not an easy way to iteratively loop over all the elements in the DataFrames using Scala and the other solutions for checking equality of two DataFrames such as df1.except(df2) do not work in my case as I need to be able to provide support for testing equality with tolerance for floats and doubles.

Of course, I could try to round all the elements beforehand and compare the results afterwards, but I would like to see if there are any other solutions that would allow me to iterate through the DataFrames to check for equality.

答:
```<code>import org.scalatest.{BeforeAndAfterAll, FeatureSpec, Matchers}

outDf.collect() should contain theSameElementsAs (dfComparable.collect())
# or ( obs order matters ! )

// outDf.except(dfComparable).toDF().count should be(0)
outDf.except(dfComparable).count should be(0)
</code>```

Body:
I'm new to Scala and am having problems writing unit tests.

I'm trying to compare and check equality for two Spark DataFrames in Scala for unit testing, and realized that there is no easy way to check equality for two Spark DataFrames.

The C++ equivalent code would be (assuming that the DataFrames are represented as double arrays in C++):

    int expected[10][2];
    int result[10][2];
    for (int row = 0; row < 10; row++) {
        for (int col = 0; col < 2; col++) {
            if (expected[row][col] != result[row][col]) return false;
        }
    }

The actual test would involve testing for equality based on the data types of the columns of the DataFrames (testing with precision tolerance for floats, etc).

It seems like there's not an easy way to iteratively loop over all the elements in the DataFrames using Scala and the other solutions for checking equality of two DataFrames such as df1.except(df2) do not work in my case as I need to be able to provide support for testing equality with tolerance for floats and doubles.

Of course, I could try to round all the elements beforehand and compare the results afterwards, but I would like to see if there are any other solutions that would allow me to iterate through the DataFrames to check for equality.


问:
Regex matching multiple negative lookaheads
I'm trying to match a string (using a Perl regex) only if it doesn't start with "abc:" or "defg:", but I can't seem to find out how. I've tried something like</p>
```<code>^(?:(?!abc:)|(?!defg:))
</code>```

答:
Use this regex:

^(?!abc:|defg:)\s*\w+

This will avoid line start with "abc:" and "defg:" as you want.

Body:
I'm trying to match a string (using a Perl regex) only if it doesn't start with "abc:" or "defg:", but I can't seem to find out how. I've tried something like

^(?:(?!abc:)|(?!defg:))


问:
How to hide parent's method from the particular children in TypeScript?
I’d like to hide some parent’s methods from particular ancestors.
However, I can’t figure out how to do that.

Let’s say we’ve got:

```<code>class GrandPa {
   // must not be accessible from the GrandSon:
   protected gradPaDoing() {}
}

class Parent extends GrandPa {
   // Here probably must be some kind of adapter between GrandPa and GrandSon...
}

class GrandSon extends Parent {
   grandSonDoing() {
      this.gradPaDoing(); // I'd like to make it impossible
   }
}
</code>```

Is there a way to achieve it?

答:
I think your design has a flaw. Consider changing your design, if possible.

What I mean is: visibility is not supposed to be reduced down the hierarchy. It may be, however, increased if there need be. Just think about it, and it will make sense.

What you can do instead is, remove that grandPaDoing method all together from the ancestor class. Move it to an interface. And make your leaf classes implement that interface only if they need that behavior.

This approach will be cleaner, more consistent and more OOP way.

EDIT:

This solution still works for the case you mentioned in your comment. Here is how:

Let's say you want to rename anOldMethod to aNewMethod and prevent old method to be used anymore.

Then simply:

step1) create an interface, add aNewMethod into this interface and then make your leaf classes implement this interface.

step2) delete anOldMethod form parent class. If method is not there, it can not be accessed anymore. If you want, you can deprecate them by @Deprecated, as @toskv suggested.

Body:
I’d like to hide some parent’s methods from particular ancestors.
However, I can’t figure out how to do that.

Let’s say we’ve got:

class GrandPa {
   // must not be accessible from the GrandSon:
   protected gradPaDoing() {}
}

class Parent extends GrandPa {
   // Here probably must be some kind of adapter between GrandPa and GrandSon...
}

class GrandSon extends Parent {
   grandSonDoing() {
      this.gradPaDoing(); // I'd like to make it impossible
   }
}

Is there a way to achieve it?


问:
JMeter Groovy Set a variable for each sampler
Is there a possibility to have variables that depend on the listener where there lay in?
So I want to execute two samplers which are working with a JSR223 Assertion. I use a groovy code which asks for the value of the variable "name". If I execute Sampler A it should say "Tom" and if i execute Sampler B it should say "Paul".
It has to be possible to execute both at the same time.</p>

答:
You have sampler shorthand in the JSR223 Assertion which stands for this or that Sampler. So you can check its name by calling sampler.getName() function which will basically execute underlying AbstractTestElement.getName() method. The relevant code would look like:

```<code>if (sampler.getName().equals('Sampler A')) {
   log.info('Tom')
}
else if (sampler.getName().equals('Sampler B')) {
    log.info('Paul')
}
</code>```

You can set a JMeter Variable from Groovy code using vars shorthand which in its turn stands for JMeterVariables class instance like:

```<code>vars.put('foo', 'bar')
</code>```

Once done you will be able to refer created variable as ${foo} where required - it will have the value of bar

Check out Scripting JMeter Assertions in Groovy - A Tutorial article for more details.

Body:
You have sampler shorthand in the JSR223 Assertion which stands for this or that Sampler. So you can check its name by calling sampler.getName() function which will basically execute underlying AbstractTestElement.getName() method. The relevant code would look like:

if (sampler.getName().equals('Sampler A')) {
   log.info('Tom')
}
else if (sampler.getName().equals('Sampler B')) {
    log.info('Paul')
}

You can set a JMeter Variable from Groovy code using vars shorthand which in its turn stands for JMeterVariables class instance like:

vars.put('foo', 'bar')

Once done you will be able to refer created variable as ${foo} where required - it will have the value of bar

Check out Scripting JMeter Assertions in Groovy - A Tutorial article for more details.


问:
Method reference is ambiguous for Thread.sleep
I've come across a weird problem where a method reference to Thread::sleep is ambiguous but a method with the same signature is not.

```<code>package test;

public class Test
{
    public static void main(String[] args)
    {
        foo(Test::sleep, 1000L); //fine
        foo((FooVoid<Long>)Thread::sleep, 1000L); //fine
        foo(Thread::sleep, 1000L); //error
    }

    public static void sleep(long millis) throws InterruptedException
    {
        Thread.sleep(millis);
    }

    public static <P, R> void foo(Foo<P, R> function, P param) {}

    public static <P> void foo(FooVoid<P> function, P param) {}

    @FunctionalInterface
    public interface Foo<P, R> {
        R call(P param1) throws Exception;
    }

    @FunctionalInterface
    public interface FooVoid<P> {
        void call(P param1) throws Exception;
    }
}
</code>```

I get those 2 errors:

```<code>Error:(9, 17) java: reference to foo is ambiguous
  both method <P,R>foo(test.Test.Foo<P,R>,P) in test.Test and method <P>foo(test.Test.FooVoid<P>,P) in test.Test match

Error:(9, 20) java: incompatible types: cannot infer type-variable(s) P,R
    (argument mismatch; bad return type in method reference
      void cannot be converted to R)
</code>```

The only difference I see is that Thread::sleep is native. Does it change anything? I don't think the overload Thread::sleep(long, int) comes into play here. Why does it happen?

EDIT: Using javac version 1.8.0_111

答:
The problem is that both, Thread.sleep and foo, are overloaded. So there is a circular dependency.

In order to find out which sleep method to use, we need to know the target type, i.e. which foo method to invoke

In order to find out which foo method to invoke, we need to know the functional signature of the argument, i.e. which sleep method we have selected

While it’s clear to a human reader that for this scenario only one of the 2×2 combinations is valid, the compiler must follow formal rules that work for arbitrary combinations, therefore, the language designers had to make a cut.

For the sake of usefulness of method references, there is a special treatment for unambiguous references, like your Test::sleep:

JLS §15.13.1

For some method reference expressions, there is only one possible compile-time declaration with only one possible invocation type (§15.12.2.6), regardless of the targeted function type. Such method reference expressions are said to be exact. A method reference expression that is not exact is said to be inexact.

Note that this distinction is similar to the distinction between implicitly typed lambda expressions (arg -> expression) and explicitly typed lambda expressions ((Type arg) -> expression).

When you look at JLS, §15.12.2.5., Choosing the Most Specific Method, you’ll see that the signature of a method reference is only used for exact method references, as when choosing the right foo, the decision for the right sleep method has not made yet.

If e is an exact method reference expression (§15.13.1), then i) for all i (1 ≤ i ≤ k), Ui is the same as Vi, and ii) one of the following is true:

R₂ is void.

R₁ <: R₂.

R₁ is a primitive type, R₂ is a reference type, and the compile-time declaration for the method reference has a return type which is a primitive type.

R₁ is a reference type, R₂ is a primitive type, and the compile-time declaration for the method reference has a return type which is a reference type.

The above rule has been stated in §15.12.2.5. for non-generic methods, redirecting to §18.5.4 for generic methods (which applies here as your foo methods are generic), containing exactly the same rule with a slightly different wording.

Since the method reference’s signature is not considered when choosing the most specific method, there is no most specific method and the invocation of foo is ambiguous. The second compiler error is the result of the strategy to continue processing the source code and potentially reporting more errors, instead of stopping the compilation right at the first error. One of the two invocations of foo caused an “incompatible types” error, if that invocation was happening, but actually that has been ruled out due to the “ambiguous invocation” error.

Body:
I've come across a weird problem where a method reference to Thread::sleep is ambiguous but a method with the same signature is not.

package test;

public class Test
{
    public static void main(String[] args)
    {
        foo(Test::sleep, 1000L); //fine
        foo((FooVoid<Long>)Thread::sleep, 1000L); //fine
        foo(Thread::sleep, 1000L); //error
    }

    public static void sleep(long millis) throws InterruptedException
    {
        Thread.sleep(millis);
    }

    public static
 void foo(Foo
 function, P param) {}

    public static
 void foo(FooVoid
 function, P param) {}

    @FunctionalInterface
    public interface Foo
 {
        R call(P param1) throws Exception;
    }

    @FunctionalInterface
    public interface FooVoid
 {
        void call(P param1) throws Exception;
    }
}

I get those 2 errors:

Error:(9, 17) java: reference to foo is ambiguous
  both method
foo(test.Test.Foo
,P) in test.Test and method
foo(test.Test.FooVoid
,P) in test.Test match

Error:(9, 20) java: incompatible types: cannot infer type-variable(s) P,R
    (argument mismatch; bad return type in method reference
      void cannot be converted to R)

The only difference I see is that Thread::sleep is native. Does it change anything? I don't think the overload Thread::sleep(long, int) comes into play here. Why does it happen?

EDIT: Using javac version 1.8.0_111