问:
Draw lines through figure of subplot matrix in matplotlib
I want to draw lines on a figure consisting of a varying number of subplots, looking like the red lines for the 3x3 example. How can I do this in matplotlib?

The code is basically an array of 2D projections of multidimensional data (upper-right half of a scatter matrix plot), on a 4D example.

```<code>from matplotlib import pyplot as plt
import numpy as np
data = np.random.random_sample((10,4))
labels = ['p1','p2','p3','p4']
fig, axarr = plt.subplots(3,3, sharex='col', sharey='row')
# Iterate over rows of subplots array
for row in range(axarr.shape[0]):
    i = row # data index corresponds to row index
    # Iterate over columns of subplots array
    for col in range(axarr.shape[1]):
        j = col+1 # data index corresponds to column index +1
        # Do what's needed in lower-left half of array and leave
        if row>col:
            if col==0:
                axarr[row,col].set_ylabel(labels[i],labelpad=5)
            axarr[row,col].spines['left'].set_visible(False)
            axarr[row,col].spines['right'].set_visible(False)
            axarr[row,col].spines['bottom'].set_visible(False)
            axarr[row,col].spines['top'].set_visible(False)
            axarr[row,col].xaxis.set_ticks_position('none')
            axarr[row,col].yaxis.set_ticks_position('none')
            axarr[row,col].tick_params(labelleft=False)
            axarr[row,col].tick_params(labelbottom=False)
            continue
        # Proceed with upper-right half of array
        axarr[row,col].scatter(data[:,i],data[:,j], s=4)
        axarr[row,col].tick_params(labelleft=False)
        axarr[row,col].tick_params(labelbottom=False)
        if row==0:
            axarr[row,col].set_xlabel(labels[j],labelpad=5)
            axarr[row,col].xaxis.set_label_position('top')
        if col==0:
            axarr[row,col].set_ylabel(labels[i],labelpad=5)
            axarr[row,col].yaxis.set_label_position('left')
</code>```

答:
Here is a solution which is independent of the actual figure size and scales together with the figure.

We use a blended transform to be able to specify the length of the line in figure coordinates, while specifying the vertical or horizontal position in axes coordinates of the top left subplot. So the vertical line goes from 0 to 1 in figure coordinates in y direction, while it is bound to x=0 in axes coordinates of the first subplot.

We then also add an offset transform to move it by half the linewidth in points, such that it sits tight against the axes spines.

```<code>from matplotlib import pyplot as plt
import matplotlib.lines
import matplotlib.transforms as transforms
import numpy as np

data = np.random.random_sample((10,10))
labels = "Some labels around all the subplots"
fig, axarr = plt.subplots(3,3, sharex='col', sharey='row')
for i, ax in enumerate(axarr.flatten()):
    ax.scatter(data[:,i], data[:,i+1])
    ax.xaxis.set_label_position('top')
for i in range(3):
    axarr[2-i,0].set_ylabel(labels.split()[i])
    axarr[0,i].set_xlabel(labels.split()[i+3])
    axarr[2-i,0].set_yticklabels([])

#### Create lines ####
lw=4  # linewidth in points
#vertical line
offset1 = transforms.ScaledTranslation(-lw/72./2., 0, fig.dpi_scale_trans)
trans1 = transforms.blended_transform_factory(
    axarr[0,0].transAxes +offset1, fig.transFigure)
l1 = matplotlib.lines.Line2D([0,0], [0, 1], transform=trans1,
            figure=fig, color="#dd0000", linewidth=4, zorder=0)
#horizontal line
offset2 = transforms.ScaledTranslation(0,lw/72./2., fig.dpi_scale_trans)
trans2 = transforms.blended_transform_factory(
     fig.transFigure, axarr[0,0].transAxes+offset2)
l2 = matplotlib.lines.Line2D([0, 1], [1,1], transform=trans2,
            figure=fig, color="#dd0000", linewidth=4, zorder=0)
#add lines to canvas
fig.lines.extend([l1, l2])

plt.show()
</code>```

Here a smaller version, from which can be seen that the lines' position adapt to the figure size.

Body:
I want to draw lines on a figure consisting of a varying number of subplots, looking like the red lines for the 3x3 example. How can I do this in matplotlib?

The code is basically an array of 2D projections of multidimensional data (upper-right half of a scatter matrix plot), on a 4D example.

from matplotlib import pyplot as plt
import numpy as np
data = np.random.random_sample((10,4))
labels = ['p1','p2','p3','p4']
fig, axarr = plt.subplots(3,3, sharex='col', sharey='row')
# Iterate over rows of subplots array
for row in range(axarr.shape[0]):
    i = row # data index corresponds to row index
    # Iterate over columns of subplots array
    for col in range(axarr.shape[1]):
        j = col+1 # data index corresponds to column index +1
        # Do what's needed in lower-left half of array and leave
        if row>col:
            if col==0:
                axarr[row,col].set_ylabel(labels[i],labelpad=5)
            axarr[row,col].spines['left'].set_visible(False)
            axarr[row,col].spines['right'].set_visible(False)
            axarr[row,col].spines['bottom'].set_visible(False)
            axarr[row,col].spines['top'].set_visible(False)
            axarr[row,col].xaxis.set_ticks_position('none')
            axarr[row,col].yaxis.set_ticks_position('none')
            axarr[row,col].tick_params(labelleft=False)
            axarr[row,col].tick_params(labelbottom=False)
            continue
        # Proceed with upper-right half of array
        axarr[row,col].scatter(data[:,i],data[:,j], s=4)
        axarr[row,col].tick_params(labelleft=False)
        axarr[row,col].tick_params(labelbottom=False)
        if row==0:
            axarr[row,col].set_xlabel(labels[j],labelpad=5)
            axarr[row,col].xaxis.set_label_position('top')
        if col==0:
            axarr[row,col].set_ylabel(labels[i],labelpad=5)
            axarr[row,col].yaxis.set_label_position('left')

Body:
Here is a solution which is independent of the actual figure size and scales together with the figure.

We use a blended transform to be able to specify the length of the line in figure coordinates, while specifying the vertical or horizontal position in axes coordinates of the top left subplot. So the vertical line goes from 0 to 1 in figure coordinates in y direction, while it is bound to x=0 in axes coordinates of the first subplot.

We then also add an offset transform to move it by half the linewidth in points, such that it sits tight against the axes spines.

from matplotlib import pyplot as plt
import matplotlib.lines
import matplotlib.transforms as transforms
import numpy as np

data = np.random.random_sample((10,10))
labels = "Some labels around all the subplots"
fig, axarr = plt.subplots(3,3, sharex='col', sharey='row')
for i, ax in enumerate(axarr.flatten()):
    ax.scatter(data[:,i], data[:,i+1])
    ax.xaxis.set_label_position('top')
for i in range(3):
    axarr[2-i,0].set_ylabel(labels.split()[i])
    axarr[0,i].set_xlabel(labels.split()[i+3])
    axarr[2-i,0].set_yticklabels([])

#### Create lines ####
lw=4  # linewidth in points
#vertical line
offset1 = transforms.ScaledTranslation(-lw/72./2., 0, fig.dpi_scale_trans)
trans1 = transforms.blended_transform_factory(
    axarr[0,0].transAxes +offset1, fig.transFigure)
l1 = matplotlib.lines.Line2D([0,0], [0, 1], transform=trans1,
            figure=fig, color="#dd0000", linewidth=4, zorder=0)
#horizontal line
offset2 = transforms.ScaledTranslation(0,lw/72./2., fig.dpi_scale_trans)
trans2 = transforms.blended_transform_factory(
     fig.transFigure, axarr[0,0].transAxes+offset2)
l2 = matplotlib.lines.Line2D([0, 1], [1,1], transform=trans2,
            figure=fig, color="#dd0000", linewidth=4, zorder=0)
#add lines to canvas
fig.lines.extend([l1, l2])

plt.show()

Here a smaller version, from which can be seen that the lines' position adapt to the figure size.


来源: stackexchange

问:
Angular 4.0 Rxjs variables undefined
After upgrading to angular 4.0 i am getting errors for RxJs variables.  Everything builds fine.  But when i load the page i get this error

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forkJoin' of undefined
  TypeError: Cannot read property 'forkJoin' of undefined

i am using forkJoin in an init function

```<code>init(){
  return Observable.forKJoin()
}
</code>```

I import the Observable at the top and it looks like this

import {Observable,Observer,Subject,BehaviorSubject} from 'rxjs/Rx';

what changes were made that would all of a sudden cause these issues.  My code runs fine pre 4.0

答:
rxjs has a bit of a "choose what you want to import" approach to Observables. Basically it's a Decorator pattern where you import the base Observable and then you import all the fancy things you want it to do. In addition to importing the observable, you also need to import:

```<code>import 'rxjs/add/observable/forkJoin';
</code>```

I usually have an rxjs-operators.ts file that I just import anytime I need anything from it.

Older versions of rxjs didn't work like this. I believe it was sometime during v2's RC period rxjs switched to this model.

All of these extra imports are part of the rxjs package so you won't need to download anything new or add anything to your package.json to access them.

ContentLicense: CC BY-SA 3.0

Title: Angular 4.0 Rxjs variables undefined

Body:
After upgrading to angular 4.0 i am getting errors for RxJs variables.  Everything builds fine.  But when i load the page i get this error

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forkJoin' of undefined
  TypeError: Cannot read property 'forkJoin' of undefined

i am using forkJoin in an init function

init(){
  return Observable.forKJoin()
}

I import the Observable at the top and it looks like this

import {Observable,Observer,Subject,BehaviorSubject} from 'rxjs/Rx';

what changes were made that would all of a sudden cause these issues.  My code runs fine pre 4.0

Body:
rxjs has a bit of a "choose what you want to import" approach to Observables. Basically it's a Decorator pattern where you import the base Observable and then you import all the fancy things you want it to do. In addition to importing the observable, you also need to import:

import 'rxjs/add/observable/forkJoin';

I usually have an rxjs-operators.ts file that I just import anytime I need anything from it.

Older versions of rxjs didn't work like this. I believe it was sometime during v2's RC period rxjs switched to this model.

All of these extra imports are part of the rxjs package so you won't need to download anything new or add anything to your package.json to access them.


问:
Extract part of text in PowerShell
This is my input file which is random, can be any number not just 9999 and any letters:
The below format will always come after a - (dash).

```
-
9999 99AKDSLY9ZWSRK99999
9999 99BGRPOE99FTRQ99999
```

Expected output:

```
AKDSLY9ZSRK
BGRPOE99TRQ
```

So I need to remove the first part of each line, always numbers:

```
9999 99
9999 99
```

Then remove the not-required characters:

99AKDSLY9ZW → in this case is the W but could be any letter

99BGRPOE99F → in this case is the F but could be any letter

And finally remove the last 5 digits, always numbers:

```
99999
99999
```

What I´m trying to use, regex (first time using it):

```<code>$result = [regex]::Matches($InputFile, '(^\d{4}\s\d{2}[A-Z0-9]\d{5}$)') -replace '\d{4}\s\d{2}', '')
$result
</code>```

It's not giving me an error message but it's not showing me the characters I'm expecting to see at $result.

I was expecting to see something in $result to then start the formatting, deleting the characters I don't need.

What could be missing here, please?

答:
Try something like this:

```<code>$str = (Get-Content ... -Raw) -replace '\r'

$cb = {
  $args[0].Groups[1].Value -replace '(?m)^.{7}' -replace '(?m).(.{3}).{5}$', '$1'
}

$re = [regex]'(?m)^(?<=-\n)((?:\d{4}\s\d{2}[^\n]*\d{5}(?:\n|$))+)'

$re.Replace($str, $cb)
</code>```

The regular expression $re matches multiline substrings that start with a hyphen and a newline, followed by one or more line with your digit/letter combinations. The (?<=...) is a positive lookbehind assertion to ensure that you only get a match when the lines with the digit/letter combinations are preceded by a line with a hyphen (without making that line part of the actual match).

The scriptblock $cb is an anonymous callback function that the Regex.Replace() method calls on each match. For each line in a match it removes the first 7 characters from the beginning of the line, and replaces the last 9 characters from the end of the line with the 2nd through 4th of those characters.

For simplicity reasons the sample code removes carriage return characters (CR, \r) from the string, so that all newlines are linefeed characters (LF, \n) instead of the default CR-LF.

Title: Extract part of text in PowerShell

Body:
This is my input file which is random, can be any number not just 9999 and any letters:
The below format will always come after a - (dash).

-
9999 99AKDSLY9ZWSRK99999
9999 99BGRPOE99FTRQ99999

Expected output:

AKDSLY9ZSRK
BGRPOE99TRQ

So I need to remove the first part of each line, always numbers:

9999 99
9999 99

Then remove the not-required characters:

99AKDSLY9ZW → in this case is the W but could be any letter

99BGRPOE99F → in this case is the F but could be any letter

And finally remove the last 5 digits, always numbers:

99999
99999

What I´m trying to use, regex (first time using it):

$result = [regex]::Matches($InputFile, '(^\d{4}\s\d{2}[A-Z0-9]\d{5}$)') -replace '\d{4}\s\d{2}', '')
$result

It's not giving me an error message but it's not showing me the characters I'm expecting to see at $result.

I was expecting to see something in $result to then start the formatting, deleting the characters I don't need.

What could be missing here, please?

Body:
Try something like this:

$str = (Get-Content ... -Raw) -replace '\r'

$cb = {
  $args[0].Groups[1].Value -replace '(?m)^.{7}' -replace '(?m).(.{3}).{5}$', '$1'
}

$re = [regex]'(?m)^(?<=-\n)((?:\d{4}\s\d{2}[^\n]*\d{5}(?:\n|$))+)'

$re.Replace($str, $cb)

The regular expression $re matches multiline substrings that start with a hyphen and a newline, followed by one or more line with your digit/letter combinations. The (?<=...) is a positive lookbehind assertion to ensure that you only get a match when the lines with the digit/letter combinations are preceded by a line with a hyphen (without making that line part of the actual match).

The scriptblock $cb is an anonymous callback function that the Regex.Replace() method calls on each match. For each line in a match it removes the first 7 characters from the beginning of the line, and replaces the last 9 characters from the end of the line with the 2nd through 4th of those characters.

For simplicity reasons the sample code removes carriage return characters (CR, \r) from the string, so that all newlines are linefeed characters (LF, \n) instead of the default CR-LF.


问:
ffmpeg can't concat movies from two different devices

I've got bunch of movies from two different Panasonic devices. As long as I concat movies from only ONE device - final movie is smooth.

However, when I add movie clip from second device, right after final movie ends playing movies from first device it display audio and only still images from movie clip from other device.

```<code>ffmpeg -f concat -i mylist.txt -c copy final_movie.MP4
</code>```

Example ffprobe:

```<code>Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'S6810001.MP4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.27.100
  Duration: 00:00:10.62, start: 0.021333, bitrate: 1131 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 998 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 132 kb/s (default)
    Metadata:
      handler_name    : SoundHandle
</code>```

Second device movie clip:

```<code>Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'a/T00004.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.27.100
  Duration: 00:00:33.18, start: 0.000000, bitrate: 1190 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 929 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: ac3 (ac-3 / 0x332D6361), 48000 Hz, stereo, fltp, 256 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
    Side data:
      audio service type: main
</code>```

Why movie is still? How to prepare it so it could be joined correctly?

答:
You're trying to concat videos that likely have different profiles. Also, the audio formats are different, but they should be the same if you want to stream copy.

Use ffprobe to view more detailed info about each input:

```<code>ffprobe -loglevel error -show_streams S6810001.MP4
ffprobe -loglevel error -show_streams a/T00004.mp4
</code>```

In this example assuming the video in S6810001.MP4 has Main profile and a/T00004.mp4 has Baseline profile you can "conform" a/T00004.mp4 to be more like S6810001.MP4, or vice versa (note that audio can have a profile too, so make sure you're looking at the right section in the ffprobe output). This example command will use the same profile and same audio format:

```<code>ffmpeg -i a/T00004.mp4 -profile:v main -c:a aac a/T00004_encoded.mp4
</code>```

Now use a/T00004_encoded.mp4 as your second input instead of a/T00004.mp4:

```<code>ffmpeg -f concat -i mylist.txt -c copy final_movie.MP4
</code>```

Body:
I've got bunch of movies from two different Panasonic devices. As long as I concat movies from only ONE device - final movie is smooth.

However, when I add movie clip from second device, right after final movie ends playing movies from first device it display audio and only still images from movie clip from other device.

ffmpeg -f concat -i mylist.txt -c copy final_movie.MP4

Example ffprobe:

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'S6810001.MP4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.27.100
  Duration: 00:00:10.62, start: 0.021333, bitrate: 1131 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 998 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 132 kb/s (default)
    Metadata:
      handler_name    : SoundHandle

Second device movie clip:

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'a/T00004.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.27.100
  Duration: 00:00:33.18, start: 0.000000, bitrate: 1190 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 929 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: ac3 (ac-3 / 0x332D6361), 48000 Hz, stereo, fltp, 256 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
    Side data:
      audio service type: main

Why movie is still? How to prepare it so it could be joined correctly?

Body:
You're trying to concat videos that likely have different profiles. Also, the audio formats are different, but they should be the same if you want to stream copy.

Use ffprobe to view more detailed info about each input:

ffprobe -loglevel error -show_streams S6810001.MP4
ffprobe -loglevel error -show_streams a/T00004.mp4

In this example assuming the video in S6810001.MP4 has Main profile and a/T00004.mp4 has Baseline profile you can "conform" a/T00004.mp4 to be more like S6810001.MP4, or vice versa (note that audio can have a profile too, so make sure you're looking at the right section in the ffprobe output). This example command will use the same profile and same audio format:

ffmpeg -i a/T00004.mp4 -profile:v main -c:a aac a/T00004_encoded.mp4

Now use a/T00004_encoded.mp4 as your second input instead of a/T00004.mp4:

ffmpeg -f concat -i mylist.txt -c copy final_movie.MP4


问:
Trouble with header files in c++: linker command failed
Apologizing ahead of time for what I'm certain is a very simple problem, but I've been unable to find a solution for this. I'm putting a very simple C++ project together, but having trouble using a header file appropriately.

The directory structure is below:

```<code>.
├── mainGraph
│   └── hnsw.cpp
└── utils
    ├── distances.cpp
    └── distances.h
</code>```

The distances header file (distances.h):

```<code>#ifndef DISTANCES
#define DISTANCES

#include <vector>

enum class Metric { Cosine, Euclidean};

double distance(const std::vector<double>& A, const std::vector<double>& B, Metric metric);
double similarity(const std::vector<double>& A, const std::vector<double>& B, Metric metric);

#endif
</code>```

And finally hnsw.cpp:

```<code>#include "../utils/distances.h"
#include <vector>
#include <iostream>

int main(){
    std::vector<double> A = {0.1, 0.5, 0.7, 1.1};
    std::vector<double> B = {0.5, 0.3, 0.8, 0.9};

    std::cout << distance(A, B, Metric::Cosine) << '\n';
}
</code>```

Now, when I actually try to compile hnsw.cpp with the following command: g++ hnsw.cpp --std=c++11 I get the following error:

```<code>Undefined symbols for architecture x86_64:
  "distance(std::__1::vector<double, std::__1::allocator<double> > const&, std::__1::vector<double, std::__1::allocator<double> > const&, Metric)", referenced from:
      _main in hnsw-ad0e05.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

If I move the main into the distances.cpp file then everything works smoothly. For the purposes of brevity I'm not posting that whole file as it's sizable and I'm fairly certain it's not relevant. If there are any resources about understanding the general process here that would also be very helpful.

答:
When you run g++ hnsw.cpp --std=c++11, you're telling the compiler to compile hnsw.cpp and link the output with the c++ standard library to create an executable. The linker fails to find the implementation of distances because it lives in distances.cpp.

You need to compile both files and link them together. There are many ways to achieve this, but the simplest is to specify both source files when invoking gcc, like this:

```<code>g++ -std=c++11 hnsw.cpp ../utils/distances.cpp
</code>```

Body:
Apologizing ahead of time for what I'm certain is a very simple problem, but I've been unable to find a solution for this. I'm putting a very simple C++ project together, but having trouble using a header file appropriately.

The directory structure is below:

.
├── mainGraph
│   └── hnsw.cpp
└── utils
    ├── distances.cpp
    └── distances.h

The distances header file (distances.h):

#ifndef DISTANCES
#define DISTANCES

#include <vector>

enum class Metric { Cosine, Euclidean};

double distance(const std::vector<double>& A, const std::vector<double>& B, Metric metric);
double similarity(const std::vector<double>& A, const std::vector<double>& B, Metric metric);

#endif

And finally hnsw.cpp:

#include "../utils/distances.h"
#include <vector>
#include <iostream>

int main(){
    std::vector<double> A = {0.1, 0.5, 0.7, 1.1};
    std::vector<double> B = {0.5, 0.3, 0.8, 0.9};

    std::cout << distance(A, B, Metric::Cosine) << '\n';
}

Now, when I actually try to compile hnsw.cpp with the following command: g++ hnsw.cpp --std=c++11 I get the following error:

Undefined symbols for architecture x86_64:
  "distance(std::__1::vector<double, std::__1::allocator<double> > const&, std::__1::vector<double, std::__1::allocator<double> > const&, Metric)", referenced from:
      _main in hnsw-ad0e05.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

If I move the main into the distances.cpp file then everything works smoothly. For the purposes of brevity I'm not posting that whole file as it's sizable and I'm fairly certain it's not relevant. If there are any resources about understanding the general process here that would also be very helpful.

Body:
When you run g++ hnsw.cpp --std=c++11, you're telling the compiler to compile hnsw.cpp and link the output with the c++ standard library to create an executable. The linker fails to find the implementation of distances because it lives in distances.cpp.

You need to compile both files and link them together. There are many ways to achieve this, but the simplest is to specify both source files when invoking gcc, like this:

g++ -std=c++11 hnsw.cpp ../utils/distances.cpp


问:
Install Microsoft R server
How we can Download & install Microsoft R Server in Ubuntu 14.04 using terminal.The link to Microsoft R documentation is given below.

https://msdn.microsoft.com/en-us/microsoft-r/
and the link to download it is as follows.
https://my.visualstudio.com/Downloads?PId=1962
Thanks

答:
To view what platforms are supported by MRS please visit https://msdn.microsoft.com/en-us/microsoft-r/rserver-install-supported-platforms

Ubuntu 14.04 and 16.04 are supported platforms from version 9.0.1 on. The link which you provided is for version 8.0.5.

To download version 9.0.1 for Ubuntu, you must sign up for Visual Studio Dev Essentials here: https://www.visualstudio.com/dev-essentials/

After you have registered, please download "Microsoft R Server 9.0.1 for Linux (x64) - (English)" from https://my.visualstudio.com/Downloads?q=Microsoft%20R

You can follow the install guide for version 9.0.1 here: https://msdn.microsoft.com/en-us/microsoft-r/rserver-install-linux-server

This is the same link which you provided, and will always be updated with the latest version install guide, older version guides will be broken off into their own pages.

Title: Install Microsoft R server


问:
Best way to execute multiple animations synchronously
This will be a 'best way to do' kind of a question.

I know there are multiple ways to do sequence animations, but which one is the better way to do it?

let's say I have 3 animations that I'm trying to execute, one after the other, so the next one only starts when the previous has finished.

I can do it with the UIView.animate(withCompletionBlock:) so in the completion section I call the second one and on the completionBlock of the second one I call the third one.

This one in particular makes me think: Is that a 'beautiful' way to do it? Is there any known issues using completionBlocks within another?

Just a thought. Calling animations within the previous animation completion block, may bring the code somehow like the pyramid of doom, if there's something like 10 synchronous animations, don't you think?

Another way to do is with the dispatch_after, the I call the next animation based on the NSTimeInterval of the previous one. In this case it may cause a app crash suspending the Main thread for the next one to execute, then suspend it again to execute the third one.

The last known way that I know is that I can use a NSTimeInterval to call the next animation, but this one is somewhat like the dispatch_after option.

In your opinion which would be the best way to do it?
Executing 3 or more visual animations, all synchronously (waiting for the previous one to finish to start the next one).

I might use this a lot in my app and I want to start it with the best way.

EXAMPLES

Animations within completionBlocks

```<code>DispatchQueue.main.async {
        UIView.animate(withDuration: 2.0, animations: {
            view1.alpha = 1
        }, completion: { (_) in
            UIView.animate(withDuration: 5.0, animations: {
                view2.alpha = 1
            }, completion: { (_) in
                UIView.animate(withDuration: 2.0, animations: {
                    view3.alpha = 0
                }, completion: { (_) in
                    UIView.animate(withDuration: 2.0, animations: {
                        view4.alpha = 0
                    }, completion: { (_) in
                            print("all completed")
                    })
                })
            })
        })
    }
</code>```

With dispatch_after:

```<code>    let anim1_duration = 2.0
    let anim2_duration = 3.0
    let anim3_duraiton = 5.0

    UIView.animate(withDuration: anim1_duration, animations: {
        view1.alpha = 1
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64(anim1_duration * Double(NSEC_PER_SEC)))) {
        UIView.animate(withDuration: anim2_duration, animations: {
            view2.alpha = 1
        }
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64((anim1_duration + anim2_duration) * Double(NSEC_PER_SEC)))) {
        UIView.animate(withDuration: anim3_duration, animations: {
            view3.alpha = 1
        }
    }
</code>```

答:
In terms of 'better reading code' consider these 2 ways of performing animations:

building stacks of animations: more

create keyframe animations using CAKeyframeAnimation: more

These options are avoiding completion blocks, which I like.

Body:
This will be a 'best way to do' kind of a question.

I know there are multiple ways to do sequence animations, but which one is the better way to do it?

let's say I have 3 animations that I'm trying to execute, one after the other, so the next one only starts when the previous has finished.

I can do it with the UIView.animate(withCompletionBlock:) so in the completion section I call the second one and on the completionBlock of the second one I call the third one.

This one in particular makes me think: Is that a 'beautiful' way to do it? Is there any known issues using completionBlocks within another?

Just a thought. Calling animations within the previous animation completion block, may bring the code somehow like the pyramid of doom, if there's something like 10 synchronous animations, don't you think?

Another way to do is with the dispatch_after, the I call the next animation based on the NSTimeInterval of the previous one. In this case it may cause a app crash suspending the Main thread for the next one to execute, then suspend it again to execute the third one.

The last known way that I know is that I can use a NSTimeInterval to call the next animation, but this one is somewhat like the dispatch_after option.

In your opinion which would be the best way to do it?
Executing 3 or more visual animations, all synchronously (waiting for the previous one to finish to start the next one).

I might use this a lot in my app and I want to start it with the best way.

EXAMPLES

Animations within completionBlocks

DispatchQueue.main.async {
        UIView.animate(withDuration: 2.0, animations: {
            view1.alpha = 1
        }, completion: { (_) in
            UIView.animate(withDuration: 5.0, animations: {
                view2.alpha = 1
            }, completion: { (_) in
                UIView.animate(withDuration: 2.0, animations: {
                    view3.alpha = 0
                }, completion: { (_) in
                    UIView.animate(withDuration: 2.0, animations: {
                        view4.alpha = 0
                    }, completion: { (_) in
                            print("all completed")
                    })
                })
            })
        })
    }

With dispatch_after:

    let anim1_duration = 2.0
    let anim2_duration = 3.0
    let anim3_duraiton = 5.0

    UIView.animate(withDuration: anim1_duration, animations: {
        view1.alpha = 1
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64(anim1_duration * Double(NSEC_PER_SEC)))) {
        UIView.animate(withDuration: anim2_duration, animations: {
            view2.alpha = 1
        }
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64((anim1_duration + anim2_duration) * Double(NSEC_PER_SEC)))) {
        UIView.animate(withDuration: anim3_duration, animations: {
            view3.alpha = 1
        }
    }


问:
Facebook SDK PHP 5.0 getLoginUrl() Error 500
I am trying to use the examples provided under Facebook PHP SDK 5.0 to login to Facebook. I am getting back 500 Internal Server Error. I am using the Baby Plan from HostGator which is running Php 5.5.27 PHP INFO . Is there configuration I would need to add to my server to get things working?

login.php

```<code><?php
session_start();
// Include the required dependencies.
require_once( 'vendor/autoload.php' );
// Initialize the Facebook PHP SDK v5.
$fb = new Facebook\Facebook([
  'app_id'                => '495994870548274',
  'app_secret'            => '593f18b375c9e23d34b9794136cf7158',
  'default_graph_version' => 'v2.3',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://techcomsgb.com/kidneytest/login-callback.php', $permissions);

echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>'
</code>```

login-callback.php

```<code><?php
session_start();

// Include the required dependencies.
require_once( 'vendor/autoload.php' );

// Initialize the Facebook PHP SDK v5.
$fb = new Facebook\Facebook([
  'app_id'                => '495994870548274',
  'app_secret'            => '593f18b375c9e23d34b9794136cf7158',
  'default_graph_version' => 'v2.3',
]);

$helper = $fb->getRedirectLoginHelper();

try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

if (! isset($accessToken)) {
  if ($helper->getError()) {
    header('HTTP/1.0 401 Unauthorized');
    echo "Error: " . $helper->getError() . "\n";
    echo "Error Code: " . $helper->getErrorCode() . "\n";
    echo "Error Reason: " . $helper->getErrorReason() . "\n";
    echo "Error Description: " . $helper->getErrorDescription() . "\n";
  } else {
    header('HTTP/1.0 400 Bad Request');
    echo 'Bad request';
  }
  exit;
}

// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);

// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($config['app_id']);
// If you know the user ID this access token belongs to, you can validate it     here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();

if (! $accessToken->isLongLived()) {
  // Exchanges a short-lived access token for a long-lived one
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "<p>Error getting long-lived access token: " . $helper-    >getMessage() . "</p>\n\n";
    exit;
  }

  echo '<h3>Long-lived</h3>';
  var_dump($accessToken->getValue());
}

$_SESSION['fb_access_token'] = (string) $accessToken;

// User is logged in with a long-lived access token.
</code>```

// You can redirect them to a members-only page.
    //header('Location: https://example.com/members.php');

答:
For me it was the link returned by  $helper->getLoginUrl(), so I just replaced https://www.facebook.com/v2.8/dialog/oauth with https://graph.facebook.com/oauth/authorize.

```<code> $login_url = $login_helper->getLoginUrl('www.yoururl.com/fb-callback.php'), $permissions);
 $login_url = str_replace('https://www.facebook.com/v2.8/dialog/oauth?', 'https://graph.facebook.com/oauth/authorize?', $login_url);
</code>```

Look at this post for reference Facebook oauth authorize URL and parameter options

"when you want to build the login flow manually you should use /oauth/authorize.. else if you are using javascript/Apps api provided by facbook it uses /dialog/oauth"

Body:
I am trying to use the examples provided under Facebook PHP SDK 5.0 to login to Facebook. I am getting back 500 Internal Server Error. I am using the Baby Plan from HostGator which is running Php 5.5.27 PHP INFO . Is there configuration I would need to add to my server to get things working?

login.php

<?php
session_start();
// Include the required dependencies.
require_once( 'vendor/autoload.php' );
// Initialize the Facebook PHP SDK v5.
$fb = new Facebook\Facebook([
  'app_id'                => '495994870548274',
  'app_secret'            => '593f18b375c9e23d34b9794136cf7158',
  'default_graph_version' => 'v2.3',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://techcomsgb.com/kidneytest/login-callback.php', $permissions);

echo 'Log in with Facebook!'

login-callback.php

<?php
session_start();

// Include the required dependencies.
require_once( 'vendor/autoload.php' );

// Initialize the Facebook PHP SDK v5.
$fb = new Facebook\Facebook([
  'app_id'                => '495994870548274',
  'app_secret'            => '593f18b375c9e23d34b9794136cf7158',
  'default_graph_version' => 'v2.3',
]);

$helper = $fb->getRedirectLoginHelper();

try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

if (! isset($accessToken)) {
  if ($helper->getError()) {
    header('HTTP/1.0 401 Unauthorized');
    echo "Error: " . $helper->getError() . "\n";
    echo "Error Code: " . $helper->getErrorCode() . "\n";
    echo "Error Reason: " . $helper->getErrorReason() . "\n";
    echo "Error Description: " . $helper->getErrorDescription() . "\n";
  } else {
    header('HTTP/1.0 400 Bad Request');
    echo 'Bad request';
  }
  exit;
}

// Logged in
echo '
Access Token
';
var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '
Metadata
';
var_dump($tokenMetadata);

// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($config['app_id']);
// If you know the user ID this access token belongs to, you can validate it     here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();

if (! $accessToken->isLongLived()) {
  // Exchanges a short-lived access token for a long-lived one
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "
Error getting long-lived access token: " . $helper-    >getMessage() . "
\n\n";
    exit;
  }

  echo '
Long-lived
';
  var_dump($accessToken->getValue());
}

$_SESSION['fb_access_token'] = (string) $accessToken;

// User is logged in with a long-lived access token.

// You can redirect them to a members-only page.
    //header('Location: https://example.com/members.php');

Body:
For me it was the link returned by  $helper->getLoginUrl(), so I just replaced https://www.facebook.com/v2.8/dialog/oauth with https://graph.facebook.com/oauth/authorize.

 $login_url = $login_helper->getLoginUrl('www.yoururl.com/fb-callback.php'), $permissions);
 $login_url = str_replace('https://www.facebook.com/v2.8/dialog/oauth?', 'https://graph.facebook.com/oauth/authorize?', $login_url);

Look at this post for reference Facebook oauth authorize URL and parameter options

"when you want to build the login flow manually you should use /oauth/authorize.. else if you are using javascript/Apps api provided by facbook it uses /dialog/oauth"


问:
C while(false) loop
I was looking at a lexical analyzer code and i came across this:

```<code>while ("false")
{
    c = fgetc(f);
    switch (state)
    ...
</code>```

I tested it and the code works, it produces correct results. Why does the loop run if there is false condition? Shouldnt the loop never run?

答:
In order for the while loop to never run, the condition should be the number 0, or the keyword false without any apostrophes, quotation marks, etc... enclosing it.

A 0 or false is a Boolean-type value. However, passing "0" is not the same as just 0, because "0" is a string value. Anything else inside the condition of the for-loop apart from 0 or false will cause the while() to run (unless you've specified some condition, but that's irrelevant to this question).

Therefore, since "0" is a string, which is not equal to 0, the compiler passes sees it as a non-false value (or non-zero value), and runs the while() loop.

If you do while(0) then the while loop will not run even once.

Title: C while(false) loop

Body:
I was looking at a lexical analyzer code and i came across this:

while ("false")
{
    c = fgetc(f);
    switch (state)
    ...

I tested it and the code works, it produces correct results. Why does the loop run if there is false condition? Shouldnt the loop never run?


问:
Why do I need to declare CUDA variables on the Host before allocating them on the Device
I've just started trying to learn CUDA again and came across some code I don't fully understand.

```<code>// declare GPU memory pointers
float * d_in;
float * d_out;

// allocate GPU memory
cudaMalloc((void**) &d_in, ARRAY_BYTES);
cudaMalloc((void**) &d_out, ARRAY_BYTES);
</code>```

When the GPU memory pointers are declared, they allocate memory on the host. The cudaMalloc calls throw away the information that d_in and d_out are pointers to floats.

I can't think why cudaMalloc would need to know about where in host memory d_in & d_out have originally been stored. It's not even clear why I need to use the host bytes to store whatever host address d_in & d_out point to.

So, what is the purpose of the original variable declarations on the host?

======================================================================

I would've thought something like this would make more sense:

```<code>// declare GPU memory pointers
cudaFloat * d_in;
cudaFloat * d_out;

// allocate GPU memory
cudaMalloc((void**) &d_in, ARRAY_BYTES);
cudaMalloc((void**) &d_out, ARRAY_BYTES);
</code>```

This way, everything GPU related takes place on the GPU. If d_in or d_out are accidentally used in host code, an error can be thrown at compile time, since those variables wouldn't be defined on the host.

I guess what I also find confusing is that by storing device memory addresses on the host, it feels like the device isn't in fully in charge of managing its own memory. It feels like there's a risk of host code accidentally overwriting the value of either d_in or d_out either through accidentally assigning to them in host code or another more subtle error, which could cause the GPU to lose access to its own memory. Also, it seems strange that the addresses assigned to d_in & d_out are chosen by the host, instead of the device. Why should the host know anything about which addresses are/are not available on the device?

What am I failing to understand here?

答:
Your fundamental conceptual failure is mixing up host-side code and device-side code. If you call cudaMalloc() from code execution on the CPU, then, well, it's on the CPU: It's you who want to have the arguments in CPU memory, and the result in CPU memory. You asked for it. cudaMalloc has told the GPU/device how much of its (the device's) memory to allocate, but if the CPU/host wants to access that memory, it needs a way to refer to it that the device will understand. The memory location on the device is a way to do this.

Alternatively, you can call it from device-side code; then everything takes place on the GPU. (Although, frankly, I've never done it myself and it's not such a great idea except in special cases).

Body:
I've just started trying to learn CUDA again and came across some code I don't fully understand.

// declare GPU memory pointers
float * d_in;
float * d_out;

// allocate GPU memory
cudaMalloc((void**) &d_in, ARRAY_BYTES);
cudaMalloc((void**) &d_out, ARRAY_BYTES);

When the GPU memory pointers are declared, they allocate memory on the host. The cudaMalloc calls throw away the information that d_in and d_out are pointers to floats.

I can't think why cudaMalloc would need to know about where in host memory d_in & d_out have originally been stored. It's not even clear why I need to use the host bytes to store whatever host address d_in & d_out point to.

So, what is the purpose of the original variable declarations on the host?

======================================================================

I would've thought something like this would make more sense:

// declare GPU memory pointers
cudaFloat * d_in;
cudaFloat * d_out;

// allocate GPU memory
cudaMalloc((void**) &d_in, ARRAY_BYTES);
cudaMalloc((void**) &d_out, ARRAY_BYTES);

This way, everything GPU related takes place on the GPU. If d_in or d_out are accidentally used in host code, an error can be thrown at compile time, since those variables wouldn't be defined on the host.

I guess what I also find confusing is that by storing device memory addresses on the host, it feels like the device isn't in fully in charge of managing its own memory. It feels like there's a risk of host code accidentally overwriting the value of either d_in or d_out either through accidentally assigning to them in host code or another more subtle error, which could cause the GPU to lose access to its own memory. Also, it seems strange that the addresses assigned to d_in & d_out are chosen by the host, instead of the device. Why should the host know anything about which addresses are/are not available on the device?

What am I failing to understand here?


问:
How can i put a logo partially over an image and then have text over the image
I have a theme that has markup like this:

```<code><div class="logo">
   <a id="logo" href="http://test.rudtek.com" title="test">
        <img class="logo-main scale-with-grid" src="/wp-content/uploads/2017/03/seasons_management_logo.jpg" alt="seasons_management_logo">
    </a>
    <div class="containerBox">
        <img class="img-responsive" <img="" src="/wp-content/uploads/revslider/slider-home-4/img-slider-4-3-825x510.jpg">
        <div class="text-box">
            <p class="dataNumber">Home 4</p>
        </div>
    </div>
</div>
</code>```

This gives me an image like this:

BUt what I really want it to look like is this:

Size ratio isn't the most important here, but I can't fiture out how to get the seasons logo to go over the dear image.

This is my css:

```<code>.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}
</code>```

答:
Michael beat me to it, but here's another method.

https://codepen.io/anon/pen/VpErXP

```<code>.logo {
  position: relative;
  max-width: 960px;
  margin: 0 auto;
}

#logo {
  position: absolute;
  top: 80px;
  left: 0;
  z-index: 99;
}
#logo img {
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.25);
}

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}
</code>```

Body:
I have a theme that has markup like this:

        <img class="img-responsive"

Home 4

This gives me an image like this:

BUt what I really want it to look like is this:

Size ratio isn't the most important here, but I can't fiture out how to get the seasons logo to go over the dear image.

This is my css:

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}

Body:
Michael beat me to it, but here's another method.

https://codepen.io/anon/pen/VpErXP

.logo {
  position: relative;
  max-width: 960px;
  margin: 0 auto;
}

#logo {
  position: absolute;
  top: 80px;
  left: 0;
  z-index: 99;
}
#logo img {
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.25);
}

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}


问:
Maya - How to update file name displayed on menu bar after renaming the scene
Using this command:

```<code>cmds.file(rename = "newName.mb")
</code>```

Doesn't display the new name in the menu bar on the top of the window. It still displays the old name but adding an asterisk * to show it has been changed.

The problem is this is confusing for the user. The file will be saved in a different path, but you don't know until you do it.

How can I update the name displayed on top, if rename doesn't?

答:
I handled this by changing the selection, which forces Maya to update the titlebar (and thereby show the new filename):</p>

```<code>cmds.file(rename = "newName.mb")
cur_selection = cmds.ls(sl=True)  # Save current selection
cmds.select('renderPartition')  # Select something (anything) the user doesn't already have selected
cmds.select(cur_selection)  # Restore user's selection
</code>```

Body:
Using this command:

cmds.file(rename = "newName.mb")

Doesn't display the new name in the menu bar on the top of the window. It still displays the old name but adding an asterisk * to show it has been changed.

The problem is this is confusing for the user. The file will be saved in a different path, but you don't know until you do it.

How can I update the name displayed on top, if rename doesn't?

Body:
I handled this by changing the selection, which forces Maya to update the titlebar (and thereby show the new filename):

cmds.file(rename = "newName.mb")
cur_selection = cmds.ls(sl=True)  # Save current selection
cmds.select('renderPartition')  # Select something (anything) the user doesn't already have selected
cmds.select(cur_selection)  # Restore user's selection


问:
MySQL query to check a row's cells for value and return column name
I have been struggling with a certain query all day and I decided to ask for help.

I need a query that checks an entire table row and all its table cells for a value 'yes' and then it needs to give me the names of the columns where this is true.

To clarify with an example:
in the table above I need to check the fruit row for all the cells with the value 'yes' and have the corresponding column names returned to me. In this case the result would be 'banana', 'apple' and 'pear'.

I hope that example helps.

```<code>-- pseudo code
SELECT `COLUMN_NAMES`
FROM `My_Table`
ROW `fruit`
WHERE `value` = 'yes';
</code>```

I'd also like to note that I can't rearrange my database. The db structure can't be changed because we are already doing queries like SELECT 'property' WHERE 'Banana' = 'yes'(which would return 'fruit'). I need it to work the other way around too.

答:
It sounds like you already have other queries that depend on this table structure, but I would still seriously consider changing the structure anyway, even if it meant rewriting some queries.

I assume the query Barmar wrote will work to get you what you want. It looks like it should, and from what I've seen, nothing is impossible for Barmar with SQL. But consider the effect this structure will have on the rest of your application.

What if you want to add an item? (Like another fruit or something.) Normally adding an item to a database would be done with an INSERT query. In this case you would have to use ALTER TABLE instead, and add a column. After you have done that, you would also have to alter the query that selects items that have a certain property (the one you're asking about here) to include the new column. You'd have to either change your application code any time you added an item, or come up with some way to dynamically include every column in the query.

What if you want to select items that have multiple properties? Obviously there aren't many liquid fruits, (unless you leave them in the fridge too long) but I assume those two aren't the only properties you're going to have. The CONCAT approaches will have trouble dealing with that. I'm sure there are ways to work around it, but you really are just working around a problem instead of fixing it.

Those are a couple of examples, but there are numerous other issues that will make this structure a real pain to deal with.

A less cumbersome way to deal with a many-to-many relationship like this is to use three tables. One for items, one for properties, and another to link items to their properties. Like this:

```<code>items                 properties          item_properties

id   item_name        id   name           item_id  property_id
1    banana           1    fruit          1        1
2    apple            2    liquid         2        1
3    pear                                 3        1
4    beef                                 5        2
5    water
</code>```

Then you can select all the properties of an item:

```<code>SELECT p.name
FROM properties p
INNER JOIN item_properties ip ON p.id = ip.property_id
INNER JOIN items i on ip.item_id = i.id
WHERE i.name = 'banana'
</code>```

Or all the items with a certain property:

```<code>SELECT i.name
FROM items i
INNER JOIN item_properties ip ON i.id = ip.item_id
INNER JOIN properties p ON ip.property_id = p.id
WHERE p.name = 'fruit'
</code>```

I understand if you don't want to change your existing application at this point. But for anyone who comes across this in the future, I'd really recommend a structure more like this to begin with.

Body:
I have been struggling with a certain query all day and I decided to ask for help.

I need a query that checks an entire table row and all its table cells for a value 'yes' and then it needs to give me the names of the columns where this is true.

To clarify with an example:
in the table above I need to check the fruit row for all the cells with the value 'yes' and have the corresponding column names returned to me. In this case the result would be 'banana', 'apple' and 'pear'.

I hope that example helps.

-- pseudo code
SELECT `COLUMN_NAMES`
FROM `My_Table`
ROW `fruit`
WHERE `value` = 'yes';

I'd also like to note that I can't rearrange my database. The db structure can't be changed because we are already doing queries like SELECT 'property' WHERE 'Banana' = 'yes'(which would return 'fruit'). I need it to work the other way around too.

Body:
It sounds like you already have other queries that depend on this table structure, but I would still seriously consider changing the structure anyway, even if it meant rewriting some queries.

I assume the query Barmar wrote will work to get you what you want. It looks like it should, and from what I've seen, nothing is impossible for Barmar with SQL. But consider the effect this structure will have on the rest of your application.

What if you want to add an item? (Like another fruit or something.) Normally adding an item to a database would be done with an INSERT query. In this case you would have to use ALTER TABLE instead, and add a column. After you have done that, you would also have to alter the query that selects items that have a certain property (the one you're asking about here) to include the new column. You'd have to either change your application code any time you added an item, or come up with some way to dynamically include every column in the query.

What if you want to select items that have multiple properties? Obviously there aren't many liquid fruits, (unless you leave them in the fridge too long) but I assume those two aren't the only properties you're going to have. The CONCAT approaches will have trouble dealing with that. I'm sure there are ways to work around it, but you really are just working around a problem instead of fixing it.

Those are a couple of examples, but there are numerous other issues that will make this structure a real pain to deal with.

A less cumbersome way to deal with a many-to-many relationship like this is to use three tables. One for items, one for properties, and another to link items to their properties. Like this:

items                 properties          item_properties

id   item_name        id   name           item_id  property_id
1    banana           1    fruit          1        1
2    apple            2    liquid         2        1
3    pear                                 3        1
4    beef                                 5        2
5    water

Then you can select all the properties of an item:

SELECT p.name
FROM properties p
INNER JOIN item_properties ip ON p.id = ip.property_id
INNER JOIN items i on ip.item_id = i.id
WHERE i.name = 'banana'

Or all the items with a certain property:

SELECT i.name
FROM items i
INNER JOIN item_properties ip ON i.id = ip.item_id
INNER JOIN properties p ON ip.property_id = p.id
WHERE p.name = 'fruit'

I understand if you don't want to change your existing application at this point. But for anyone who comes across this in the future, I'd really recommend a structure more like this to begin with.


问:
How to make a qframe highlight when cursor is on it in PyQt4?
I have the following window with frames.

I want frame to be highlighted (in my case change its shape) when mouse is in its area.

```<code>from PyQt4 import QtGui, QtCore
import sys

app = QtGui.QApplication(sys.argv)

window = QtGui.QWidget()
window_layout = QtGui.QVBoxLayout()
window.setLayout(window_layout)

#fill content
for i in range(10):
    label = QtGui.QLabel(str(i))
    frame = QtGui.QFrame()
    frame_layout = QtGui.QVBoxLayout()
    frame.setLayout(frame_layout)
    frame_layout.addWidget(label)
    window_layout.addWidget(frame)

def layout_widgets(layout):
   return (layout.itemAt(i) for i in range(layout.count()))

def mouse_enter(event):
    print 'frame enter'
    w.widget().setFrameShape(3)

def mouse_leave(event):
    print 'frame leave'
    w.widget().setFrameShape(0)

for w in layout_widgets(window_layout):
    print w.widget()

    w.widget().enterEvent = mouse_enter
    w.widget().leaveEvent = mouse_leave

window.show()
sys.exit(app.exec_())
</code>```

It works but only the last frame in layout highlights.
How to make only that frame change its shape where the mouse is?

I've tried the following:

```<code>def mouse_enter(event, frame):
    print 'frame enter'
    frame.setFrameShape(3)

w.widget().enterEvent = functools.partial(mouse_enter, w.widget())
</code>```

but it gives an error. I have found one more way to do that - signal mapper
but I have no idea how to use it.

答:
The problem in your code the variable w when executing the for is left with the last element, so it will only be executed in the latter. To solve this I have implemented a Frame class that inherits from QFrame where I overwrite the enterEvent and leaveEvent functions.

```<code>from PyQt4 import QtGui, QtCore
import sys

class Frame(QtGui.QFrame):
    def __init__(self, text, parent=None):
        super(Frame, self).__init__(parent=parent)
        label = QtGui.QLabel(text)
        frame_layout = QtGui.QVBoxLayout()
        frame_layout.addWidget(label)
        self.setLayout(frame_layout)

    def enterEvent(self, event):
        self.setFrameShape(3)

    def leaveEvent(self, event):
        self.setFrameShape(0)

app = QtGui.QApplication(sys.argv)

window = QtGui.QWidget()
window_layout = QtGui.QVBoxLayout()
window.setLayout(window_layout)

for i in range(10):
    frame = Frame(str(i))
    window_layout.addWidget(frame)

window.show()
sys.exit(app.exec_())
</code>```

Body:
I have the following window with frames.

I want frame to be highlighted (in my case change its shape) when mouse is in its area.

from PyQt4 import QtGui, QtCore
import sys

app = QtGui.QApplication(sys.argv)

window = QtGui.QWidget()
window_layout = QtGui.QVBoxLayout()
window.setLayout(window_layout)

#fill content
for i in range(10):
    label = QtGui.QLabel(str(i))
    frame = QtGui.QFrame()
    frame_layout = QtGui.QVBoxLayout()
    frame.setLayout(frame_layout)
    frame_layout.addWidget(label)
    window_layout.addWidget(frame)

def layout_widgets(layout):
   return (layout.itemAt(i) for i in range(layout.count()))

def mouse_enter(event):
    print 'frame enter'
    w.widget().setFrameShape(3)

def mouse_leave(event):
    print 'frame leave'
    w.widget().setFrameShape(0)

for w in layout_widgets(window_layout):
    print w.widget()

    w.widget().enterEvent = mouse_enter
    w.widget().leaveEvent = mouse_leave

window.show()
sys.exit(app.exec_())

It works but only the last frame in layout highlights.
How to make only that frame change its shape where the mouse is?

I've tried the following:

def mouse_enter(event, frame):
    print 'frame enter'
    frame.setFrameShape(3)

w.widget().enterEvent = functools.partial(mouse_enter, w.widget())

but it gives an error. I have found one more way to do that - signal mapper
but I have no idea how to use it.

Body:
The problem in your code the variable w when executing the for is left with the last element, so it will only be executed in the latter. To solve this I have implemented a Frame class that inherits from QFrame where I overwrite the enterEvent and leaveEvent functions.

from PyQt4 import QtGui, QtCore
import sys

class Frame(QtGui.QFrame):
    def __init__(self, text, parent=None):
        super(Frame, self).__init__(parent=parent)
        label = QtGui.QLabel(text)
        frame_layout = QtGui.QVBoxLayout()
        frame_layout.addWidget(label)
        self.setLayout(frame_layout)

    def enterEvent(self, event):
        self.setFrameShape(3)

    def leaveEvent(self, event):
        self.setFrameShape(0)

app = QtGui.QApplication(sys.argv)

window = QtGui.QWidget()
window_layout = QtGui.QVBoxLayout()
window.setLayout(window_layout)

for i in range(10):
    frame = Frame(str(i))
    window_layout.addWidget(frame)

window.show()
sys.exit(app.exec_())


问:
Query for column key when foreign key is absent in another table postgresql
We have a PostgreSQL database which has a table with a foreign key reference to the primary key of another table like below

Table A

a_key

b_key

when_

Table B

b_key

There was a bug in our code where we removed rows from Table B but did not remove the entries in Table A that were associated with those rows.  I am trying to right a query to find all of the primary keys from Table A which have a "b_key" value that does not exist in Table B, I also added a time restriction to the query.  My query is below but it is not returning any results.  Can anyone see an issue with the query?  Is it not done correctly?

```<code>select a_key
from A left join B b on a.b_key = b.b_key
where b.b_key is null and A.when_ < '2017-03-13 00:00:00.0'::timestamp
</code>```

答:
try this first</p>

```<code>SELECT
  a_key
FROM A
where not exists (
 select b_key from B where B.b_key = A.b_key)
</code>```

Body:
We have a PostgreSQL database which has a table with a foreign key reference to the primary key of another table like below

Table A

a_key

b_key

when_

Table B

b_key

There was a bug in our code where we removed rows from Table B but did not remove the entries in Table A that were associated with those rows.  I am trying to right a query to find all of the primary keys from Table A which have a "b_key" value that does not exist in Table B, I also added a time restriction to the query.  My query is below but it is not returning any results.  Can anyone see an issue with the query?  Is it not done correctly?

select a_key
from A left join B b on a.b_key = b.b_key
where b.b_key is null and A.when_ < '2017-03-13 00:00:00.0'::timestamp

Body:
try this first

SELECT
  a_key
FROM A
where not exists (
 select b_key from B where B.b_key = A.b_key)


问:
how to sync any type of data between a server and clients(mobile and other)?
I have a multi-clients environment, and i would like to sync between the client to the server both ways (server->client & client->server)

do you know of anything that can get me started on this horrified task?
i have multiple requirments:

the data to be synced can be very different (files, messages (inbox), status of messages (read, replied and etc..)

the changes to this data can happen both on the client and on the server.

the changes can happen even if there is no communication between the server and the client. (they are responsible on syncing the differences when the communication is restored)

the sync process should be light-update - when possible update only the relevant changes and not all the information.

how would you start on building such a massive protocol? where should i save the data?
Does anyone know of any framework that i can base my project on?

答:
What Sync Framework sample code wouldn't compile? We test everything we publish, but we might have missed something. It would help us to know so we can fix it!

You can also look at Code Gallery (http://code.msdn.microsoft.com/sync) for complete samples, if that works better for you.

ContentLicense: CC BY-SA 2.5


问:
How to get GitHub API notifications that match the notifications site
I'm trying to get the same information out of GitHub that's shown on the https://github.com/notifications page. Unfortunately, the standard notifications API doesn't really match that view.

If I get the notifications from that API (even with participating=false), I don't see all the items visible on the website. On the other hand, the API seems to be based on the last_read_at idea, and things I've seen on the website don't disappear automatically from the notifications list.

Is there a way (without scraping the website) to obtain the same /notifications view?

答:
So GitHub's API supports pagination for requests returning lists, so the API will return default of 30 notifications per page. What I suggest is setting the default size to 100 and then start from page 1 and call the next page till there is no results e.g. :

```<code><https://api.github.com/notifications?page=1&per_page=100>; rel="next"
<https://api.github.com/notifications?page=2&per_page=100>; rel="next"
...and so on till you get an empty list then you stop
</code>```

The rel="next" is a Link Header which is explained here: https://developer.github.com/v3/#pagination

Hope this helps

Body:
So GitHub's API supports pagination for requests returning lists, so the API will return default of 30 notifications per page. What I suggest is setting the default size to 100 and then start from page 1 and call the next page till there is no results e.g. :

<https://api.github.com/notifications?page=1&per_page=100>; rel="next"
<https://api.github.com/notifications?page=2&per_page=100>; rel="next"
...and so on till you get an empty list then you stop

The rel="next" is a Link Header which is explained here: https://developer.github.com/v3/#pagination

Hope this helps


问:
get the value of the most frequent factor using R dplyr chain
I found a simple solution to getting the most frequent factor of a column in a dataframe using

```<code>names(which.max(table(df$column)))
</code>```

but what if I wanted to find find the most frequent factor inside a chain. Is there a simple code that just gives you the 'mode' of the factors?

Or is there a method to include the above code inside a chain?

I've done it like this, which seems like a huge waste of time.

```<code>(df %>% group_by(column) %>% summarise(count=n()) %>% arrange(desc(count)))$count[1]
</code>```

A simple code would be appreciated, no need to provide sample data. Thanks!

答:
You could use the %$% infix operator from magrittr:

```<code>df %$% column %>% table %>% which.max %>% names
</code>```

Or you could use the following syntax just using the pipe:

```<code>df %>% {.$column} %>% table %>% which.max %>% names
</code>```

Or even:

```<code>df %>% `$`("column") %>% table %>% which.max %>% names
</code>```

Body:
I found a simple solution to getting the most frequent factor of a column in a dataframe using

names(which.max(table(df$column)))

but what if I wanted to find find the most frequent factor inside a chain. Is there a simple code that just gives you the 'mode' of the factors?

Or is there a method to include the above code inside a chain?

I've done it like this, which seems like a huge waste of time.

(df %>% group_by(column) %>% summarise(count=n()) %>% arrange(desc(count)))$count[1]

A simple code would be appreciated, no need to provide sample data. Thanks!

Body:
You could use the %$% infix operator from magrittr:

df %$% column %>% table %>% which.max %>% names

Or you could use the following syntax just using the pipe:

df %>% {.$column} %>% table %>% which.max %>% names

Or even:

df %>% `$`("column") %>% table %>% which.max %>% names


问:
How to get difference of days/months/years (datediff) between two dates?
I am looking for a way to implement the SQLServer-function datediff in PostgreSQL. That is, this function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified start date and end date.

```<code>datediff(dd, '2010-04-01', '2012-03-05') = 704 // 704 changes of day in this interval
datediff(mm, '2010-04-01', '2012-03-05') = 23  // 23 changes of month
datediff(yy, '2010-04-01', '2012-03-05') = 2   // 2 changes of year
</code>```

I know I could do 'dd' by simply using subtraction, but any idea about the other two?

答:
I spent some time looking for the best answer, and I think I have it.

This sql will give you the number of days between two dates as integer:

```<code>SELECT
    (EXTRACT(epoch from age('2017-6-15', now())) / 86400)::int
</code>```

..which, when run today (2017-3-28), provides me with:

```<code>?column?
------------
77
</code>```

The misconception about the accepted answer:

```<code>select age('2010-04-01', '2012-03-05'),
   date_part('year',age('2010-04-01', '2012-03-05')),
   date_part('month',age('2010-04-01', '2012-03-05')),
   date_part('day',age('2010-04-01', '2012-03-05'));
</code>```

..is that you will get the literal difference between the parts of the date strings, not the amount of time between the two dates.

I.E:

Age(interval)=-1 years -11 mons -4 days;

Years(double precision)=-1;

Months(double precision)=-11;

Days(double precision)=-4;

ContentLicense: CC BY-SA 4.0

Body:
I am looking for a way to implement the SQLServer-function datediff in PostgreSQL. That is, this function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified start date and end date.

datediff(dd, '2010-04-01', '2012-03-05') = 704 // 704 changes of day in this interval
datediff(mm, '2010-04-01', '2012-03-05') = 23  // 23 changes of month
datediff(yy, '2010-04-01', '2012-03-05') = 2   // 2 changes of year

I know I could do 'dd' by simply using subtraction, but any idea about the other two?

Body:
I spent some time looking for the best answer, and I think I have it.

This sql will give you the number of days between two dates as integer:

SELECT
    (EXTRACT(epoch from age('2017-6-15', now())) / 86400)::int

..which, when run today (2017-3-28), provides me with:

?column?
------------
77

The misconception about the accepted answer:

select age('2010-04-01', '2012-03-05'),
   date_part('year',age('2010-04-01', '2012-03-05')),
   date_part('month',age('2010-04-01', '2012-03-05')),
   date_part('day',age('2010-04-01', '2012-03-05'));

..is that you will get the literal difference between the parts of the date strings, not the amount of time between the two dates.

I.E:

Age(interval)=-1 years -11 mons -4 days;

Years(double precision)=-1;

Months(double precision)=-11;

Days(double precision)=-4;


问:
How can I view my HTML webpage in a mobile emulator and make my code more efficient?

var Person= {};

Person.Character= function(firstName, lastName, gender, age)
{
    this.FirstName= firstName;
    this.LastName= lastName;
    this.Gender= gender;
    this.Age= age;
}

Person.Character.prototype.GetAllInformation= function()
{
      return this.FirstName + " " + this.LastName + " "  + this.Gender + " "  +
       + this.Age;
}

Person.Zack = new Person.Character("Zack", "Efron", "Male", 29);
Person.Shia = new Person.Character("Shia", "Labeouf","Male", 30);

document.getElementById("demo1").innerHTML = Person.Zack.GetAllInformation();

document.getElementById("demo2").innerHTML = Person.Shia.GetAllInformation();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media screen and (max-width: 320px)
{
    #demo1{ width: 100px;}
    #demo2{ width: 100px;}
}

@media only screen and (orientation: portrait) {
    body {
        background-color: red;
    }
}</code>```

<meta name="viewport" content="width=device-width">
<title></title>
<link rel="stylesheet" type="text/css" href="example-style.css">

```

Hello Everyone,

I have created a webpage and used CSS to handle media queries so when I view my webpage on a mobile emulator, it will become active when I reduce the width size of the screen or when the screen is turned to portrait form. So basically I want to know how I can view HTML my page on the emulator (it doesn't see to work with on this website(http://www.mobilephoneemulator.com/)) and if I am doing my media queries right? I know they are right so far, but is there a way that I can combine the two media queries into one media query? This would then reduce the code I have in CSS. I have attached the code I have done so far in HTML, CSS, and JavaScript for anyone's viewing.

答:
You can chain media query paramaters!

For example:

```<code>/* Portrait */
@media only screen
  and (min-device-width: 320px)
  and (max-device-width: 568px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait) {
    #demo1{ width: 100px;}
    #demo2{ width: 100px;}
}
</code>```

In your case, your media query would be:

```<code>@media screen and (max-width: 320px) and (orientation: portrait)
{
    #demo1{ width: 100px;}
    #demo2{ width: 100px;}
    body { background-color: red; }
}
</code>```

@Robert I's answer has all the information you need for testing responsive web design - I'm not going to repost it.

Body:
var Person= {};

Person.Character= function(firstName, lastName, gender, age)
{
    this.FirstName= firstName;
    this.LastName= lastName;
    this.Gender= gender;
    this.Age= age;
}

Person.Character.prototype.GetAllInformation= function()
{
      return this.FirstName + " " + this.LastName + " "  + this.Gender + " "  +
       + this.Age;
}

Person.Zack = new Person.Character("Zack", "Efron", "Male", 29);
Person.Shia = new Person.Character("Shia", "Labeouf","Male", 30);

document.getElementById("demo1").innerHTML = Person.Zack.GetAllInformation();

document.getElementById("demo2").innerHTML = Person.Shia.GetAllInformation();

@media screen and (max-width: 320px)
{
    #demo1{ width: 100px;}
    #demo2{ width: 100px;}
}

@media only screen and (orientation: portrait) {
    body {
        background-color: red;
    }
}

<meta name="viewport" content="width=device-width">
<title></title>
<link rel="stylesheet" type="text/css" href="example-style.css">

Hello Everyone,

I have created a webpage and used CSS to handle media queries so when I view my webpage on a mobile emulator, it will become active when I reduce the width size of the screen or when the screen is turned to portrait form. So basically I want to know how I can view HTML my page on the emulator (it doesn't see to work with on this website(http://www.mobilephoneemulator.com/)) and if I am doing my media queries right? I know they are right so far, but is there a way that I can combine the two media queries into one media query? This would then reduce the code I have in CSS. I have attached the code I have done so far in HTML, CSS, and JavaScript for anyone's viewing.

Body:
You can chain media query paramaters!

For example:

/* Portrait */
@media only screen
  and (min-device-width: 320px)
  and (max-device-width: 568px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait) {
    #demo1{ width: 100px;}
    #demo2{ width: 100px;}
}

In your case, your media query would be:

@media screen and (max-width: 320px) and (orientation: portrait)
{
    #demo1{ width: 100px;}
    #demo2{ width: 100px;}
    body { background-color: red; }
}

@Robert I's answer has all the information you need for testing responsive web design - I'm not going to repost it.


问:
Cannot read property 'find' of null with Node/Express/Mongodb
I'm following a tutorial to create a simple Node/Express/Mongoose REST API. I'm running mongod in one terminal and my node app in another.

My app:

```<code>// BASE CONFIG
// =========================================================
var express = require('express'),
    bodyParser = require('body-parser'),
    util = require('util'),
    app = express(),
    port = process.env.PORT || 8000,

    // database
    dbURI = 'mongodb://localhost/nodeSpace',
    mongoose = require('mongoose'),
    db = null,

    // models
    Ship = require('./models/ship');

// configure use of bodyParser this lets us get data from a post
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// DB SETUP
// =========================================================
mongoose.connect(dbURI);
db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('Connected to DB!');
})

var testModel = mongoose.model('Test', new mongoose.Schema({name: String}, {bufferCommands: false}));

testModel.find(function (err, res) {
    if(err) {
        console.log('Error finding test model: ' + err);
    }
    else {
        console.log('Got test model: ' + res);
    }
});
</code>```

When it runs, mongo is reporting connections formed:

```<code>2017-03-28T10:44:28.565-0600 I -        [conn51] end connection 127.0.0.1:49289 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn50] end connection 127.0.0.1:49288 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn47] end connection 127.0.0.1:49285 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn49] end connection 127.0.0.1:49287 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn48] end connection 127.0.0.1:49286 (5 connections now open)
</code>```

But my app chokes on the 'find' call on my test model. Even if the database returned no results, I'd expect it to just be an empty object:

```<code>/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:129
    collection[i].apply(collection, args);
                ^

TypeError: Cannot read property 'find' of null
    at NativeCollection.(anonymous function) [as find] (/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:129:17)
    at Query.execFind (/node_modules/mongoose/lib/query.js:1682:20)
    at Query.find (/node_modules/mongoose/lib/query.js:204:15)
    at Function.find (/node_modules/mongoose/lib/model.js:821:16)
    at Object.<anonymous> (/server.js:34:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
</code>```

答:
I'm accepting the previous answer because it is correct for the reported symptoms. However, the underlying cause was a different problem and this answer may be useful.

Various local and remote databases hung indefinitely on any type of query. Forcing unbuffered queries caused the issues reported in the original question. My mongod reported connections when the app started but no connection events fired. It appears to be a dependency versioning issue.

The tutorial here:
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

References these dependencies:

```<code>"dependencies": {
    "express": "~4.0.0",
    "mongoose": "~3.6.13",
    "body-parser": "~1.0.1"
}
</code>```

But something with that collection of packages simply doesn't work. I tried both a locally-installed mongo and a free cloud hosted install. Neither worked. After updating my dependencies to this, both local and cloud installs connected and queried without issues:

```<code>"dependencies": {
  "body-parser": "^1.17.1",
  "express": "^4.15.2",
  "mongoose": "^4.9.2"
}
</code>```

Body:
I'm following a tutorial to create a simple Node/Express/Mongoose REST API. I'm running mongod in one terminal and my node app in another.

My app:

// BASE CONFIG
// =========================================================
var express = require('express'),
    bodyParser = require('body-parser'),
    util = require('util'),
    app = express(),
    port = process.env.PORT || 8000,

    // database
    dbURI = 'mongodb://localhost/nodeSpace',
    mongoose = require('mongoose'),
    db = null,

    // models
    Ship = require('./models/ship');

// configure use of bodyParser this lets us get data from a post
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// DB SETUP
// =========================================================
mongoose.connect(dbURI);
db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('Connected to DB!');
})

var testModel = mongoose.model('Test', new mongoose.Schema({name: String}, {bufferCommands: false}));

testModel.find(function (err, res) {
    if(err) {
        console.log('Error finding test model: ' + err);
    }
    else {
        console.log('Got test model: ' + res);
    }
});

When it runs, mongo is reporting connections formed:

2017-03-28T10:44:28.565-0600 I -        [conn51] end connection 127.0.0.1:49289 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn50] end connection 127.0.0.1:49288 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn47] end connection 127.0.0.1:49285 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn49] end connection 127.0.0.1:49287 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn48] end connection 127.0.0.1:49286 (5 connections now open)

But my app chokes on the 'find' call on my test model. Even if the database returned no results, I'd expect it to just be an empty object:

/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:129
    collection[i].apply(collection, args);
                ^

TypeError: Cannot read property 'find' of null
    at NativeCollection.(anonymous function) [as find] (/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:129:17)
    at Query.execFind (/node_modules/mongoose/lib/query.js:1682:20)
    at Query.find (/node_modules/mongoose/lib/query.js:204:15)
    at Function.find (/node_modules/mongoose/lib/model.js:821:16)
    at Object.<anonymous> (/server.js:34:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)

Body:
I'm accepting the previous answer because it is correct for the reported symptoms. However, the underlying cause was a different problem and this answer may be useful.

Various local and remote databases hung indefinitely on any type of query. Forcing unbuffered queries caused the issues reported in the original question. My mongod reported connections when the app started but no connection events fired. It appears to be a dependency versioning issue.

The tutorial here:
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

References these dependencies:

"dependencies": {
    "express": "~4.0.0",
    "mongoose": "~3.6.13",
    "body-parser": "~1.0.1"
}

But something with that collection of packages simply doesn't work. I tried both a locally-installed mongo and a free cloud hosted install. Neither worked. After updating my dependencies to this, both local and cloud installs connected and queried without issues:

"dependencies": {
  "body-parser": "^1.17.1",
  "express": "^4.15.2",
  "mongoose": "^4.9.2"
}


问:
Scope of an object created in a function
I have created an object of a class inside a function. The created object is passed as a parameter to another class. I expect that when I exit the function in which the object is created, the object must be destroyed.

Also any references to this object must be invalid, but I find that the object referenced after exiting the function is still valid. Trying to understand the scope of the object. The code snipped is given below.

```<code>class TextWidget
{
    public:
        TextWidget()
        {
            cout <<  "Constructor TextWidget" << endl;
        }

        TextWidget(int id)
        {
            _ID = id;
            cout <<  "Constructor TextWidget" << endl;
        }

        ~TextWidget()
        {
            cout <<  "Destructor TextWidget" << endl;
        }

        void printWidgetInstance()
        {
            cout << this << endl;
        }
        int _ID;
};

class AnotherWidget
{
    public:
        AnotherWidget()
        {
            cout << "Constructor AnotherWidget" << endl;
        }

        ~AnotherWidget()
        {
            cout << "Destructor AnotherWidget" << endl;
        }

        TextWidget* getTextWidget()
        {
            return _textWidget;
        }

        void setTextWidget(TextWidget* t)
        {
            _textWidget = t;
        }

        int getTextID() { return _textWidget->_ID; }

    private:
        TextWidget* _textWidget;
};

ButtonWidget b;
AnotherWidget a;

void fun()
{
    TextWidget t(7);
    b.setTextWidget(&t);
    a.setTextWidget(&t);
    a.getTextWidget()->printWidgetInstance();
    b.getTextWidget()->printWidgetInstance();
}

int main()
{
    fun();
    cout << "TextWidget in AnotherWidget is ";
    a.getTextWidget()->printWidgetInstance();
    cout << "Text ID in a is " << a.getTextID() << endl;
    getchar();
    return 0;
}
</code>```

OUTPUT

```<code>Constructor AnotherWidget
Constructor TextWidget
Before deleting TextWidget in class ButtonWidget 0x73fdf0
Before deleting TextWidget in class AnotherWidget 0x73fdf0
0x73fdf0
0x73fdf0
Destructor TextWidget
TextWidget in AnotherWidget is 0x73fdf0
Text ID in a is 7
</code>```

答: A variable declared using automatic storage duration (not using new) has a lifetime of its scope.  Accessing the variable outside the scope results in undefined behavior.</p>

Body:
I have created an object of a class inside a function. The created object is passed as a parameter to another class. I expect that when I exit the function in which the object is created, the object must be destroyed.

Also any references to this object must be invalid, but I find that the object referenced after exiting the function is still valid. Trying to understand the scope of the object. The code snipped is given below.

class TextWidget
{
    public:
        TextWidget()
        {
            cout <<  "Constructor TextWidget" << endl;
        }

        TextWidget(int id)
        {
            _ID = id;
            cout <<  "Constructor TextWidget" << endl;
        }

        ~TextWidget()
        {
            cout <<  "Destructor TextWidget" << endl;
        }

        void printWidgetInstance()
        {
            cout << this << endl;
        }
        int _ID;
};

class AnotherWidget
{
    public:
        AnotherWidget()
        {
            cout << "Constructor AnotherWidget" << endl;
        }

        ~AnotherWidget()
        {
            cout << "Destructor AnotherWidget" << endl;
        }

        TextWidget* getTextWidget()
        {
            return _textWidget;
        }

        void setTextWidget(TextWidget* t)
        {
            _textWidget = t;
        }

        int getTextID() { return _textWidget->_ID; }

    private:
        TextWidget* _textWidget;
};

ButtonWidget b;
AnotherWidget a;

void fun()
{
    TextWidget t(7);
    b.setTextWidget(&t);
    a.setTextWidget(&t);
    a.getTextWidget()->printWidgetInstance();
    b.getTextWidget()->printWidgetInstance();
}

int main()
{
    fun();
    cout << "TextWidget in AnotherWidget is ";
    a.getTextWidget()->printWidgetInstance();
    cout << "Text ID in a is " << a.getTextID() << endl;
    getchar();
    return 0;
}

OUTPUT

Constructor AnotherWidget
Constructor TextWidget
Before deleting TextWidget in class ButtonWidget 0x73fdf0
Before deleting TextWidget in class AnotherWidget 0x73fdf0
0x73fdf0
0x73fdf0
Destructor TextWidget
TextWidget in AnotherWidget is 0x73fdf0
Text ID in a is 7


问:
why am I getting unused argument using c in r?
When I try:

x=c(1,2,3)

...I get the message unused argument (3)

When I type x=c(1,2) it takes the function but when I type x it gives me a value of [3]. I want to create a simple vector of numbers but I don't know why it is giving me this message.

答: I presume you created a user-defined function called c, thereby replacing the built-in base-r function. Try rm("c") and then everything should work as expected again.


问:
Quartz.NET - Jobs don't run?
I'm attempting to implement Quartz.NET as a Windows Service in C#. My jobs are not triggering when I expect them to trigger... at all, actually, as far as I can tell?

I have My Job schedule running starting on the next even minute after the and running "minutely". However, when the next minute comes, I cannot seem to tell if anything actually runs.

I would assume that when my job runs, a CLI window would pop on job execution, and the Console operations would be visible, (I even put a Console.ReadKey() in there to ensure the window isn't opening and closing so fast I can't see it), but as far as I can tell the schedule is simply not executing jobs.

I noticed that all the times are in UTC, and that the StartTimeUtc will be set to the UTC time which is +6 hours from my local computer time, but I would also assume that the Quartz scheduler handles that by calculating execution time from my TimeZone setting, though I have no way that I know of to confirm that, or to confirm the ACTUAL times that my schedule is set for.

I imagine there's some way to setup the Common Logging assembly and utilize it to help me know what my status is, but I have yet to figure out what to do with that to enable a log of any sort for feedback from my Windows Service, aside from writing to the event log I created for it.

My OnStart function of my windows service

```<code>protected override void OnStart(string[] args)
    {
        eventLog.WriteEntry("--- STARTING eLoyalty Scheduler Service ---");

        // construct a scheduler factory
        ISchedulerFactory schedFact = new StdSchedulerFactory();

        // get a scheduler
        IScheduler sched = schedFact.GetScheduler();

        // construct job info
        JobDetail jobDetail = new JobDetail("eLoyaltySchedulerService", null, typeof(PortalSchedulerJob));
        jobDetail.JobDataMap["jobSays"] = "eLoyalty Scheduler Service Executing!";
        jobDetail.JobDataMap["myStateData"] = new ArrayList();

        // fire every minute
        Trigger trigger = TriggerUtils.MakeMinutelyTrigger();

        // start on the next even minute
        trigger.StartTimeUtc = TriggerUtils.GetEvenMinuteDate(DateTime.UtcNow);

        // name it
        trigger.Name = "NextEvenMinute";

        // schedule it
        sched.ScheduleJob(jobDetail, trigger);

        // start the schedule
        sched.Start();

        eventLog.WriteEntry("--- STARTED eLoyalty Scheduler Service ---");
    }
</code>```

My Job's Execute() function is as follows:

```<code>public void Execute(JobExecutionContext context)
    {
        try
        {
            string instName = context.JobDetail.Name;
            string instGroup = context.JobDetail.Group;
            JobDataMap dataMap = context.MergedJobDataMap;
            string jobSays = dataMap.GetString("jobSays");
            ArrayList state = (ArrayList)dataMap["myStateData"];
            state.Add(DateTime.UtcNow);

            Console.WriteLine("Instance {0} of PortalSchedulerJob says: {1} @ {2}", instName, jobSays, DateTime.UtcNow);
            Console.ReadKey();
        }
        catch (JobExecutionException Ex)
        {
            throw Ex;
        }
    }
</code>```

If you can help me figure out how to troubleshoot my ACTUAL schedule activity, I may be able to solve this on my own... ?

答:
Thanks for the input everyone... I couldn't get any of this to work, unfortunately, but when I added an event logger to my Job execution function, I found that it wrote to the eventlog every minute on the minute as expected.

I guess the Console.WriteLine() and Console.ReadKey() funcs do nothing in a windows service environment?

NOTE: They do something, but in the background running as a service rather than in a console window...

Title: Quartz.NET - Jobs don't run?

Body:
I'm attempting to implement Quartz.NET as a Windows Service in C#. My jobs are not triggering when I expect them to trigger... at all, actually, as far as I can tell?

I have My Job schedule running starting on the next even minute after the and running "minutely". However, when the next minute comes, I cannot seem to tell if anything actually runs.

I would assume that when my job runs, a CLI window would pop on job execution, and the Console operations would be visible, (I even put a Console.ReadKey() in there to ensure the window isn't opening and closing so fast I can't see it), but as far as I can tell the schedule is simply not executing jobs.

I noticed that all the times are in UTC, and that the StartTimeUtc will be set to the UTC time which is +6 hours from my local computer time, but I would also assume that the Quartz scheduler handles that by calculating execution time from my TimeZone setting, though I have no way that I know of to confirm that, or to confirm the ACTUAL times that my schedule is set for.

I imagine there's some way to setup the Common Logging assembly and utilize it to help me know what my status is, but I have yet to figure out what to do with that to enable a log of any sort for feedback from my Windows Service, aside from writing to the event log I created for it.

My OnStart function of my windows service

protected override void OnStart(string[] args)
    {
        eventLog.WriteEntry("--- STARTING eLoyalty Scheduler Service ---");

        // construct a scheduler factory
        ISchedulerFactory schedFact = new StdSchedulerFactory();

        // get a scheduler
        IScheduler sched = schedFact.GetScheduler();

        // construct job info
        JobDetail jobDetail = new JobDetail("eLoyaltySchedulerService", null, typeof(PortalSchedulerJob));
        jobDetail.JobDataMap["jobSays"] = "eLoyalty Scheduler Service Executing!";
        jobDetail.JobDataMap["myStateData"] = new ArrayList();

        // fire every minute
        Trigger trigger = TriggerUtils.MakeMinutelyTrigger();

        // start on the next even minute
        trigger.StartTimeUtc = TriggerUtils.GetEvenMinuteDate(DateTime.UtcNow);

        // name it
        trigger.Name = "NextEvenMinute";

        // schedule it
        sched.ScheduleJob(jobDetail, trigger);

        // start the schedule
        sched.Start();

        eventLog.WriteEntry("--- STARTED eLoyalty Scheduler Service ---");
    }

My Job's Execute() function is as follows:

public void Execute(JobExecutionContext context)
    {
        try
        {
            string instName = context.JobDetail.Name;
            string instGroup = context.JobDetail.Group;
            JobDataMap dataMap = context.MergedJobDataMap;
            string jobSays = dataMap.GetString("jobSays");
            ArrayList state = (ArrayList)dataMap["myStateData"];
            state.Add(DateTime.UtcNow);

            Console.WriteLine("Instance {0} of PortalSchedulerJob says: {1} @ {2}", instName, jobSays, DateTime.UtcNow);
            Console.ReadKey();
        }
        catch (JobExecutionException Ex)
        {
            throw Ex;
        }
    }

If you can help me figure out how to troubleshoot my ACTUAL schedule activity, I may be able to solve this on my own... ?


问:
How to refresh switch statement cases automatically in Visual Studio?
I have previously generated a switch statement over an enum using the automatic snippet included in VS 2010 (I pressed sw [tab] [tab]). Later I extended the enum type. It now contains more values. Now I want to update the switch statement, so that it again includes cases for all possible enum values. Is it possible to automatically generate all missing cases for the enum while keeping existing ones, rather than doing that manually?</p>

答: What you need to do is sw[tab][tab] - which should give you something like "switch (switch_on)" where "switch_on" is marked. Now start typing your enum name - it is also possible to have SomeOtherClass.SomeOtherClassesEnum here - just don't start moving the cursor around. When you have the full name inside the parenthesis, hit [Enter] - boom, all enum-cases + default is there.</p>