问:
Qt5 Separating a video widget
I am trying to find a way to create and separate a video widget into two parts, in order to process stereo videos:

The first one would play a part of the video;

The second one would play the other part of the video.

I currently do not know where to start. I am searching around qt multimedia module, but I do not know how to achieve this behavior.

Does anyone have an idea?

I was also thinking to build two video widgets and run them into two threads but they have to be perfectly synchronized. The idea was to cut the video into two ones with ffmpeg and affecting each one to a video widget. However I do not think it would be easy to achieve this (each frame would have to be sync).

Thanks for your answers.

答:
If your stereo video data is encoded in some special format that needs decoding on the codec/container format, I think that the QMultiMedia stuff in Qt is too basic for this kind of use case as it does not allow tuning into "one stream" of a multi-stream transport container.

However, if you have alternating scan-lines, alternating frames or even "side-by-side" or "over-and-under" image per frame encoded in a "normal" video stream, then all you will have to do is intercept the frames as they are being decoded and separate the frame into two QImages and display them.

That is definitely doable!

However depending on your video source and even the platform, you might want to select different methods. For example if you are using a QCamera as the source of your video you could use the QVideoProbe or QViewFinder approaches. Interrestingly the availability of those methods on different platforms vary, so definitely figure out that first.

If you are decoding video using QMediaPlayer, QVideoProbe will probably be the way to go.

For an inttroduction to how you can grab frames using the different methods, please look at some of the examples from the official documentation on the subject.

Here is a short example of using the QVideoProbe approach:

```<code>videoProbe = new QVideoProbe(this);
// Here, myVideoSource is a camera or other media object compatible with QVideoProbe
if (videoProbe->setSource(myVideoSource)) {
    // Probing succeeded, videoProbe->isValid() should be true.
    connect(videoProbe, SIGNAL(videoFrameProbed(QVideoFrame)),
            this, SLOT(processIndividualFrame(QVideoFrame)));
}

// Cameras need to be started. Do whatever your video source requires to start here
myVideoSource->start();

// [...]

// This is the slot where the magic happens (separating each single frame from video into two `QImage`s and posting the result to two `QLabel`s for example):

void processIndividualFrame(QVideoFrame &frame){
    QVideoFrame cloneFrame(frame);
    cloneFrame.map(QAbstractVideoBuffer::ReadOnly);
    const QImage image(cloneFrame.bits(),
                           cloneFrame.width(),
                           cloneFrame.height(),
QVideoFrame::imageFormatFromPixelFormat(cloneFrame.pixelFormat()));
    cloneFrame.unmap();
    QSize sz = image.size();
    const int w = sz.width();
    const int h2 = sz.height() / 2;
    // Assumes "over-and-under" placement of stereo data for simplicity.
    // If you instead need access to individual scanlines, please have a look at [this][2].
    QImage leftImage = image.copy(0, 0,   w, h2);
    QImage rightImage = image.copy(0, h2, w, h2);
    // Assumes you have a UI set up with labels named as below, and with sizing / layout set up correctly
    ui->myLeftEyeLabel.setPixmap(QPixmap::fromImage(leftImage));
    ui->myRightEyeLabel.setPixmap(QPixmap::fromImage(leftImage));
    // Should play back rather smooth since they are effectively updated simultaneously
}
</code>```

I hope this was useful.

BIG FAT WARNING: Only parts of this code has been tested or even compiled!

Title: Qt5 Separating a video widget

Body:
If your stereo video data is encoded in some special format that needs decoding on the codec/container format, I think that the QMultiMedia stuff in Qt is too basic for this kind of use case as it does not allow tuning into "one stream" of a multi-stream transport container.

However, if you have alternating scan-lines, alternating frames or even "side-by-side" or "over-and-under" image per frame encoded in a "normal" video stream, then all you will have to do is intercept the frames as they are being decoded and separate the frame into two QImages and display them.

That is definitely doable!

However depending on your video source and even the platform, you might want to select different methods. For example if you are using a QCamera as the source of your video you could use the QVideoProbe or QViewFinder approaches. Interrestingly the availability of those methods on different platforms vary, so definitely figure out that first.

If you are decoding video using QMediaPlayer, QVideoProbe will probably be the way to go.

For an inttroduction to how you can grab frames using the different methods, please look at some of the examples from the official documentation on the subject.

Here is a short example of using the QVideoProbe approach:

videoProbe = new QVideoProbe(this);
// Here, myVideoSource is a camera or other media object compatible with QVideoProbe
if (videoProbe->setSource(myVideoSource)) {
    // Probing succeeded, videoProbe->isValid() should be true.
    connect(videoProbe, SIGNAL(videoFrameProbed(QVideoFrame)),
            this, SLOT(processIndividualFrame(QVideoFrame)));
}

// Cameras need to be started. Do whatever your video source requires to start here
myVideoSource->start();

// [...]

// This is the slot where the magic happens (separating each single frame from video into two `QImage`s and posting the result to two `QLabel`s for example):

void processIndividualFrame(QVideoFrame &frame){
    QVideoFrame cloneFrame(frame);
    cloneFrame.map(QAbstractVideoBuffer::ReadOnly);
    const QImage image(cloneFrame.bits(),
                           cloneFrame.width(),
                           cloneFrame.height(),
QVideoFrame::imageFormatFromPixelFormat(cloneFrame.pixelFormat()));
    cloneFrame.unmap();
    QSize sz = image.size();
    const int w = sz.width();
    const int h2 = sz.height() / 2;
    // Assumes "over-and-under" placement of stereo data for simplicity.
    // If you instead need access to individual scanlines, please have a look at [this][2].
    QImage leftImage = image.copy(0, 0,   w, h2);
    QImage rightImage = image.copy(0, h2, w, h2);
    // Assumes you have a UI set up with labels named as below, and with sizing / layout set up correctly
    ui->myLeftEyeLabel.setPixmap(QPixmap::fromImage(leftImage));
    ui->myRightEyeLabel.setPixmap(QPixmap::fromImage(leftImage));
    // Should play back rather smooth since they are effectively updated simultaneously
}

I hope this was useful.

BIG FAT WARNING: Only parts of this code has been tested or even compiled!


来源: stackexchange

问:
how can I get price cart from database in Code Igniter
it's my controller

```<code>function set_hargabesar($id){

    $this->load->library('cart');
        $condition['id'] = 'id';
        $get = $this->myigniter_model->getharga('harga_satuan','id');

        $data = array(
            'rowid'   => $id,
            'qty'     => 5,
            'price'   => $get,
        );

        $this->cart->update_all($data);

}
</code>```

it's my model

```<code>public function getharga($harga, $id){

    $this->db->select($harga);
    $this->db->from('barang');
    $this->db->where('id',$id);

    $query=$this->db->get();

   }
</code>```

How can I get a 'harga_satuan' (price cart) from database
please help me.

I can get the data(harga_satuan) from database with this code.

答:
You've only executed your query, you need to retrieve data.
Model:

```<code>public function getharga($harga, $id){
   $this->db->select($harga);
   $this->db->from('barang');
   $this->db->where('id',$id);

   $query=$this->db->get();
   $row = $query->row_array();
   return $row;
}
</code>```

In your controller just change this:

```<code>'price'   => $get['harga_satuan'],
</code>```

And, of course, you need to pass id to your model:

```<code>$get = $this->myigniter_model->getharga('harga_satuan', $id);
</code>```

(but I hope you are doing it)

ContentLicense: CC BY-SA 3.0

Body:
it's my controller

function set_hargabesar($id){

    $this->load->library('cart');
        $condition['id'] = 'id';
        $get = $this->myigniter_model->getharga('harga_satuan','id');

        $data = array(
            'rowid'   => $id,
            'qty'     => 5,
            'price'   => $get,
        );

        $this->cart->update_all($data);

}

it's my model

public function getharga($harga, $id){

    $this->db->select($harga);
    $this->db->from('barang');
    $this->db->where('id',$id);

    $query=$this->db->get();

   }

How can I get a 'harga_satuan' (price cart) from database
please help me.

I can get the data(harga_satuan) from database with this code.

Body:
You've only executed your query, you need to retrieve data.
Model:

public function getharga($harga, $id){
   $this->db->select($harga);
   $this->db->from('barang');
   $this->db->where('id',$id);

   $query=$this->db->get();
   $row = $query->row_array();
   return $row;
}

In your controller just change this:

'price'   => $get['harga_satuan'],

And, of course, you need to pass id to your model:

$get = $this->myigniter_model->getharga('harga_satuan', $id);

(but I hope you are doing it)


问:
c++ graphical programming
I'm new to c++ 3D, so I may just be missing something obvious, but how do I convert from 3D to 2D and (for a given z location) from 2D to 3D?</p>

答:
It is a matter of casting a ray from the screen onto a plane which is parallel to x-y and is at the required z location. You then need to find out where on the plane the ray is colliding.

Here's one example, considering that screen_x and screen_y ranges from [0, 1], where 0 is the left-most or top-most coordinate and 1 is right-most or bottom-most, respectively:

```<code>Vector3 point_of_contact(-1.0f, -1.0f, -1.0f);
Matrix4 view_matrix = camera->getViewMatrix();
Matrix4 proj_matrix = camera->getProjectionMatrix();
Matrix4 inv_view_proj_matrix = (proj_matrix * view_matrix).inverse();
float nx = (2.0f * screen_x) - 1.0f;
float ny = 1.0f - (2.0f * screen_y);
Vector3 near_point(nx, ny, -1.0f);
Vector3 mid_point(nx, ny, 0.0f);
// Get ray origin and ray target on near plane in world space
Vector3 ray_origin, ray_target;
ray_origin = inv_view_proj_matrix * near_point;
ray_target = inv_view_proj_matrix * mid_point;

Vector3 ray_direction = ray_target - ray_origin;
ray_direction.normalise();

// Check for collision with the plane
Vector3 plane_normal(0.0f, 0.0f, 1.0f);
float denominator = plane_normal.dotProduct(ray_direction);
if (fabs(denom) >= std::numeric_limits<float>::epsilon())
{
    float num = plane_normal.dotProduct(ray.getOrigin()) + Vector3(0, 0, z_pos);
    float distance = -(num/denom);
    if (distance > 0)
    {
        point_of_contact = ray_origin + (ray_direction * distance);
    }
}
return point_of_contact
</code>```

Disclaimer Notice: This solution was taken from bits and pieces of Ogre3D graphics library.

ContentLicense: CC BY-SA 2.5

Title: c++ graphical programming

Body:
It is a matter of casting a ray from the screen onto a plane which is parallel to x-y and is at the required z location. You then need to find out where on the plane the ray is colliding.

Here's one example, considering that screen_x and screen_y ranges from [0, 1], where 0 is the left-most or top-most coordinate and 1 is right-most or bottom-most, respectively:

Vector3 point_of_contact(-1.0f, -1.0f, -1.0f);
Matrix4 view_matrix = camera->getViewMatrix();
Matrix4 proj_matrix = camera->getProjectionMatrix();
Matrix4 inv_view_proj_matrix = (proj_matrix * view_matrix).inverse();
float nx = (2.0f * screen_x) - 1.0f;
float ny = 1.0f - (2.0f * screen_y);
Vector3 near_point(nx, ny, -1.0f);
Vector3 mid_point(nx, ny, 0.0f);
// Get ray origin and ray target on near plane in world space
Vector3 ray_origin, ray_target;
ray_origin = inv_view_proj_matrix * near_point;
ray_target = inv_view_proj_matrix * mid_point;

Vector3 ray_direction = ray_target - ray_origin;
ray_direction.normalise();

// Check for collision with the plane
Vector3 plane_normal(0.0f, 0.0f, 1.0f);
float denominator = plane_normal.dotProduct(ray_direction);
if (fabs(denom) >= std::numeric_limits<float>::epsilon())
{
    float num = plane_normal.dotProduct(ray.getOrigin()) + Vector3(0, 0, z_pos);
    float distance = -(num/denom);
    if (distance > 0)
    {
        point_of_contact = ray_origin + (ray_direction * distance);
    }
}
return point_of_contact

Disclaimer Notice: This solution was taken from bits and pieces of Ogre3D graphics library.


问:
how to sort values of 1st column and print only corresponding values of third column using awk
I tried to sort the file using awk '{print $0|"sort -t',' -nk1 "}' but I want to print only the third column of sorted file. Input file:

1   4   7   9
9   7   4   1
4   6   8   9
1   2   3   4
5   4   5   2

the expected output:

3
7
8
5
4

答:
Try this - </p>

```<code>sort file|awk '{print $3}'
3
7
8
5
4
</code>```

Body:
Try this -

sort file|awk '{print $3}'
3
7
8
5
4


问:
undefined Class method in Ruby (being called before method definition)
I ended up having a very strange error:

When I run this code:

```<code>class HomeFeature
    include Mongoid::Document
    include Mongoid::Timestamps
    include Mongoid::Bitfield

    belongs_to :home

    def self.amenities
        %w(lobby jacuzzi sauna cinema games roof_garden events_room tennis_court visits_space roaster green_areas cistern)
    end

    bitfield :amenities, *HomeFeature.amenities.map(&:to_sym)
end
</code>```

It works perfectly fine, but this:

```<code>class HomeFeature
    include Mongoid::Document
    include Mongoid::Timestamps
    include Mongoid::Bitfield

    belongs_to :home

    bitfield :amenities, *HomeFeature.amenities.map(&:to_sym)

    def self.amenities
        %w(lobby jacuzzi sauna cinema games roof_garden events_room tennis_court visits_space roaster green_areas cistern)
    end
end
</code>```

Gives me the error:
```NoMethodError: undefined method `amenities' for HomeFeature:Class````

Can someone please explain why is this happening? Thanks a lot

答: In the second example, you are trying to call the class method amenities before it has been defined (it is called on the line *HomeFeature.amenities.map(&:to_sym), but only defined later). The ordering of the source is important here, as the code is parsed top to bottom.

Body:
I ended up having a very strange error:

When I run this code:

class HomeFeature
    include Mongoid::Document
    include Mongoid::Timestamps
    include Mongoid::Bitfield

    belongs_to :home

    def self.amenities
        %w(lobby jacuzzi sauna cinema games roof_garden events_room tennis_court visits_space roaster green_areas cistern)
    end

    bitfield :amenities, *HomeFeature.amenities.map(&:to_sym)
end

It works perfectly fine, but this:

class HomeFeature
    include Mongoid::Document
    include Mongoid::Timestamps
    include Mongoid::Bitfield

    belongs_to :home

    bitfield :amenities, *HomeFeature.amenities.map(&:to_sym)

    def self.amenities
        %w(lobby jacuzzi sauna cinema games roof_garden events_room tennis_court visits_space roaster green_areas cistern)
    end
end

Gives me the error:
```NoMethodError: undefined method `amenities' for HomeFeature:Class````

Can someone please explain why is this happening? Thanks a lot


问:
os.listdir and os.path.isdir confusion, isdir is acting random?
I have this simple process below for listing the contents of a folder:

```<code>def some_process(self):

    dir3 = os.listdir('/Users/somepath/programming/somepathanother/Data_samples')
    for d in dir3:
        if os.path.isdir(d):
            print "DIR: " + d
        elif os.path.isfile(d):
            print "FILE: " + d

    print "PATH THREE:"
    print str(dir3)

    sys.exit(0)
</code>```

The actual contents of the Data_samples folder is:
dir1
dir2
dir3
dir4
file.zip
anotherfile.zip
dir5

The output of the process does not work as expected. For a file it just prints:

FILE .DS_Store
and nothing else (should print out file.zip and anotherfile.zip)

I also realize that if I copy the resourcetest.py file and it's corresponding ini file into this folder and run it then it does see it

```<code>FILE: .DS_Store
FILE: resourcetest.ini
FILE: resourcetest.py
</code>```

The full output of print str(dir3)

```<code>PATH THREE:
['.DS_Store', 'dir1', 'dir2', 'dir3', 'dir4', 'resourcetest.ini','resourcetest.py', 'test.file', 'test.zip', 'dir5']
</code>```

Then should also print out dir1 dir2 dir3 dir4 as DIR: " , yet none of this happens and I have no idea why, though in an odd twist if I execute this code from the folder that is listed, it does show everything correctly.

Is this an anomaly of running python 2.7 from the mac os x terminal, or am I missing something else here.  Is my thinking on the usage of listdir and isdir wrong?

答:
listdir gives only the names, not the full path. You will need to create the full path:

```<code>for d in dir3:
    path = os.path.join('/Users/somepath/programming/somepathanother/Data_samples', d)
    if os.path.isdir(path):
        ...
</code>```

Body:
I have this simple process below for listing the contents of a folder:

def some_process(self):

    dir3 = os.listdir('/Users/somepath/programming/somepathanother/Data_samples')
    for d in dir3:
        if os.path.isdir(d):
            print "DIR: " + d
        elif os.path.isfile(d):
            print "FILE: " + d

    print "PATH THREE:"
    print str(dir3)

    sys.exit(0)

The actual contents of the Data_samples folder is:
dir1
dir2
dir3
dir4
file.zip
anotherfile.zip
dir5

The output of the process does not work as expected. For a file it just prints:

FILE .DS_Store
and nothing else (should print out file.zip and anotherfile.zip)

I also realize that if I copy the resourcetest.py file and it's corresponding ini file into this folder and run it then it does see it

FILE: .DS_Store
FILE: resourcetest.ini
FILE: resourcetest.py

The full output of print str(dir3)

PATH THREE:
['.DS_Store', 'dir1', 'dir2', 'dir3', 'dir4', 'resourcetest.ini','resourcetest.py', 'test.file', 'test.zip', 'dir5']

Then should also print out dir1 dir2 dir3 dir4 as DIR: " , yet none of this happens and I have no idea why, though in an odd twist if I execute this code from the folder that is listed, it does show everything correctly.

Is this an anomaly of running python 2.7 from the mac os x terminal, or am I missing something else here.  Is my thinking on the usage of listdir and isdir wrong?

Body:
listdir gives only the names, not the full path. You will need to create the full path:

for d in dir3:
    path = os.path.join('/Users/somepath/programming/somepathanother/Data_samples', d)
    if os.path.isdir(path):
        ...


问:
Closeness centrality with igraph package in R
I wanted to measure closeness centrality, specifically incloseness and outcloseness, with the igraph package in R version 3. I used the dataset "flo" in the package "network" to do the analysis. the density (graph.density) and centralization (centralization.degree) functions of igraph package worked fine. but the closeness function showed errors. The code and the errors are posted below:

code:

```<code>library(network)
library(igraph)
data(flo)
gr <- graph.adjacency(flo, mode="undirected")
closeness(gr)
</code>```

error:

```<code>Error in FUN(X[[1L]], ...) :
as.edgelist.sna input must be an adjacency matrix/array, edgelist matrix, network, or sparse matrix, or list thereof.
</code>```

I am new to network analysis and the R packages for the analysis. Can someone please show me what went wrong and how to do it?

答:
Why don't you give this a try and see if it works for you:

```<code>centralization.closeness(gnr)
</code>```

For some reason some of the commands in igraph only work with "centralization." appended to them. I'm in the process of figuring this out myself.

Body:
I wanted to measure closeness centrality, specifically incloseness and outcloseness, with the igraph package in R version 3. I used the dataset "flo" in the package "network" to do the analysis. the density (graph.density) and centralization (centralization.degree) functions of igraph package worked fine. but the closeness function showed errors. The code and the errors are posted below:

code:

library(network)
library(igraph)
data(flo)
gr <- graph.adjacency(flo, mode="undirected")
closeness(gr)

error:

Error in FUN(X[[1L]], ...) :
as.edgelist.sna input must be an adjacency matrix/array, edgelist matrix, network, or sparse matrix, or list thereof.

I am new to network analysis and the R packages for the analysis. Can someone please show me what went wrong and how to do it?

Body:
Why don't you give this a try and see if it works for you:

centralization.closeness(gnr)

For some reason some of the commands in igraph only work with "centralization." appended to them. I'm in the process of figuring this out myself.

ContentLicense: CC BY-SA 4.0


问:
Time in milliseconds in Python
In this logging that I built part of it is to time the entire process from start to finish. In this script we are unzipping, pulling data and merging and rezipping these files. Imported default_timer from timeit as shown below. All of the processes are timed as is the entire time it takes to run the script. The out put in the log is this -1.207415584403293e-06 for the time it takes to rezip and I cannot figure out how to get it out of scientific notation and display it as either milliseconds or microseconds. Any ideas? The coding is as below:

```<code>from timeit import default_timer as timer
start = timer()
fullstart = start
</code>```

this is the import and call for the timer at the beginning and the coding at the end is as follows:

```<code>end = timer()
logger.info("Total time in sec "+str(end - fullstart))
</code>```

答:
You can multiply this number by 1,000 in order to get the mili-seconds (1/1000) time difference, or multiply by 1,000,000 and you will get the micro-seconds (1/1000000) time difference.
The default_timer returns the time in microsecond.

For more information: default_timer.

Title: Time in milliseconds in Python

Body:
In this logging that I built part of it is to time the entire process from start to finish. In this script we are unzipping, pulling data and merging and rezipping these files. Imported default_timer from timeit as shown below. All of the processes are timed as is the entire time it takes to run the script. The out put in the log is this -1.207415584403293e-06 for the time it takes to rezip and I cannot figure out how to get it out of scientific notation and display it as either milliseconds or microseconds. Any ideas? The coding is as below:

from timeit import default_timer as timer
start = timer()
fullstart = start

this is the import and call for the timer at the beginning and the coding at the end is as follows:

end = timer()
logger.info("Total time in sec "+str(end - fullstart))


问:
how to use the object property of NSNotificationcenter
Could somebody please show me how to use the object property on NSNotifcationCenter. I want to be able to use it to pass an integer value to my selector method.

This is how I have set up the notification listener in my UI View. Seeing as I want an integer value to be passed I'm not sure what to replace nil with.

```<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"myevent" object:nil];

- (void)receiveEvent:(NSNotification *)notification {
    // handle event
    NSLog(@"got event %@", notification);
}
</code>```

I dispatch the notification from another class like this. The function is passed a variable named index. It's this value that I want to somehow fire off with the notification.

```<code>-(void) disptachFunction:(int) index
{
    int pass= (int)index;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:pass];
    //[[NSNotificationCenter defaultCenter] postNotificationName:<#(NSString *)aName#>   object:<#(id)anObject#>
}
</code>```

答:
The object property is not appropriate for that. Instead you want to use the userinfo parameter:

```<code>+ (id)notificationWithName:(NSString *)aName
                    object:(id)anObject
                  userInfo:(NSDictionary *)userInfo
</code>```

userInfo is, as you can see, an NSDictionary specifically for sending information along with the notification.

Your dispatchFunction method would instead be something like this:

```<code>- (void) disptachFunction:(int) index {
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:index] forKey:@"pass"];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:nil userInfo:userInfo];
}
</code>```

Your receiveEvent method would be something like this:

```<code>- (void)receiveEvent:(NSNotification *)notification {
    int pass = [[[notification userInfo] valueForKey:@"pass"] intValue];
}
</code>```

Body:
Could somebody please show me how to use the object property on NSNotifcationCenter. I want to be able to use it to pass an integer value to my selector method.

This is how I have set up the notification listener in my UI View. Seeing as I want an integer value to be passed I'm not sure what to replace nil with.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"myevent" object:nil];

- (void)receiveEvent:(NSNotification *)notification {
    // handle event
    NSLog(@"got event %@", notification);
}

I dispatch the notification from another class like this. The function is passed a variable named index. It's this value that I want to somehow fire off with the notification.

-(void) disptachFunction:(int) index
{
    int pass= (int)index;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:pass];
    //[[NSNotificationCenter defaultCenter] postNotificationName:<#(NSString *)aName#>   object:<#(id)anObject#>
}

Body:
The object property is not appropriate for that. Instead you want to use the userinfo parameter:

+ (id)notificationWithName:(NSString *)aName
                    object:(id)anObject
                  userInfo:(NSDictionary *)userInfo

userInfo is, as you can see, an NSDictionary specifically for sending information along with the notification.

Your dispatchFunction method would instead be something like this:

- (void) disptachFunction:(int) index {
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:index] forKey:@"pass"];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:nil userInfo:userInfo];
}

Your receiveEvent method would be something like this:

- (void)receiveEvent:(NSNotification *)notification {
    int pass = [[[notification userInfo] valueForKey:@"pass"] intValue];
}


问:
How can I use Linq with JSON to get all the Ids from this odd JSON?
I receive JSON from a web service that looks something like this:

```<code>{
   "RESULTS": {
      "1220": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 5199,
           "DDR_NAME": "Mesa Building"
      },
      "5455": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 417,
           "DDR_NAME": "Scottsdale Building"
      },
      "1462": {
           "DDR_TYPE_ID": 12,
           "DDR_ID": 3324,
           "DDR_NAME": "Gentry Building"
      }
   }
}
</code>```

I can't really serialize in my usual method because this isn't an array of the same objects thanks the the strange numbered keys.

All I need from this is a list of the DDR_ID values.

Is there a way to use Linq to JSON to get these values from this JSON?  Or is there a better way?

答:
Is there a way to use Linq to JSON to get these values from this
  JSON?

Using Linq to JSON you can get the values like this with no need for other objects

```<code>var obj = (JObject) JObject.Parse(json)["RESULTS"];
var ids = obj.Properties().Select(p => (int)p.Value["DDR_ID"]);
</code>```

Body:
I receive JSON from a web service that looks something like this:

{
   "RESULTS": {
      "1220": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 5199,
           "DDR_NAME": "Mesa Building"
      },
      "5455": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 417,
           "DDR_NAME": "Scottsdale Building"
      },
      "1462": {
           "DDR_TYPE_ID": 12,
           "DDR_ID": 3324,
           "DDR_NAME": "Gentry Building"
      }
   }
}

I can't really serialize in my usual method because this isn't an array of the same objects thanks the the strange numbered keys.

All I need from this is a list of the DDR_ID values.

Is there a way to use Linq to JSON to get these values from this JSON?  Or is there a better way?

Body:
Is there a way to use Linq to JSON to get these values from this
  JSON?

Using Linq to JSON you can get the values like this with no need for other objects

var obj = (JObject) JObject.Parse(json)["RESULTS"];
var ids = obj.Properties().Select(p => (int)p.Value["DDR_ID"]);


问:
Getting info about each redirection on the way to the final url using curl_getinfo
is there any way to get (and, let's say display that) info about each redirection on the way to the final url using cURL (e.g. curl_getinfo function)?

Thanks!

答: You can get the header of a page using get_meta_tags. I do not know if this will get you all headers or just the last one.</p>


问:
Run WMIC queries under another user
I am trying to run a WMIC command under another user.

I do not have their password but i have admin access on the machine, is this possible?

Its simply to export mapped drives etc for backup purposes.

答: Mapped drives are stored in HKEY_CURRENT_USER. 99 times out of 100 it is just easier to run a script from the user's context (say, a logon script) that writes their mapped drives somewhere.

Title: Run WMIC queries under another user


问:
getElementbyId is not a function
I have a simple piece of JavaScript that changes the color of a button, but I keep getting he error that getting the button is not a function, even though the same function (with the same capitalisation and case) works just a couple of lines above.</p>

```<code>if (this.ButtonColor != "") {
      var button = document.getElementbyId('modal-close');
      button.style.backgroundColor = this.ButtonColor;
 }
</code>```

答: The function is document.getElementById(), not document.getElementbyId()

Title: getElementbyId is not a function

Body:
I have a simple piece of JavaScript that changes the color of a button, but I keep getting he error that getting the button is not a function, even though the same function (with the same capitalisation and case) works just a couple of lines above.

if (this.ButtonColor != "") {
      var button = document.getElementbyId('modal-close');
      button.style.backgroundColor = this.ButtonColor;
 }


问:
Tomcat 8 Oracle 11 JNDI Cannot create JDBC driver of class '' for connect URL 'null'
I'm trying to set up a Spring 4 MVC application in STS using a Tomcat 8 server and an Oracle 11g database, and I'm having problems setting up the datasource.

I know there's nothing wrong with the Spring setup because, without the datasource, it works fine.

Here's the datasource bean:

```<code><bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myDB" />
    <property name="resourceRef" value="false" />
</bean>
</code>```

My web.xml resource ref:

```<code><resource-ref>
   <res-ref-name>jdbc/myDB</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>
</code>```

My Tomcat's server.xml resources:

-->

```<code><Resource name="jdbc/myDB"
          global="jdbc/myDB"
          auth="Container"
          type="javax.sql.DataSource"
          username="xxxxx"
          password="yyyyyy"
          url="jdbc:oracle:thin:@xxx.yyy"
          driverClassName="oracle.jdbc.OracleDriver"
          initialSize="20"
          maxWaitMillis="15000"
          maxTotal="75"
          maxIdle="20"
          maxAge="7200000"
          testOnBorrow="true"
          validationQuery="select 1 from dual"
          />
</code>```

And my context.xml

```<code>  <ResourceLink name="jdbc/myDB"
    global="jdbc/myDB"
    type="javax.sql.DataSource"/>
</code>```

The error I'm getting is this:

ERROR: Unable obtain JDBC Connection java.sql.SQLException: Cannot
  create JDBC driver of class '' for connect URL 'null'     at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2167)
    at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2037)
    at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
    at
  org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    at
  org.hibernate.internal.SessionFactoryImpl$1.obtainConnection(SessionFactoryImpl.java:419)
    at
  org.hibernate.hql.spi.id.IdTableHelper.executeIdTableCreationStatements(IdTableHelper.java:67)
    at
  org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:125)
    at
  org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:42)
    at
  org.hibernate.hql.spi.id.AbstractMultiTableBulkIdStrategyImpl.prepare(AbstractMultiTableBulkIdStrategyImpl.java:88)
    at
  org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:302)
    at
  org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
    at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
    at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at
  org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:511)
    at
  org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:495)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at
  org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at
  org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at
  org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at
  org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at
  org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at
  org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4940)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5250)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at java.util.concurrent.FutureTask.run(Unknown Source)  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)     at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)    at
  java.lang.Thread.run(Unknown Source) Caused by: java.sql.SQLException:
  No suitable driver    at java.sql.DriverManager.getDriver(Unknown
  Source)   at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2151)
    ... 44 more

My Tomcat lib directory has the ojdbc jar that I need,  and I've even included it on my build script. What could be causing this?

答:
Check your connection URL.  Also, always use the long form of the connection URL where you could pass various connection descriptors.

Example: jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(HOST=myhost)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=myorcldbservicename)))

Body:
I'm trying to set up a Spring 4 MVC application in STS using a Tomcat 8 server and an Oracle 11g database, and I'm having problems setting up the datasource.

I know there's nothing wrong with the Spring setup because, without the datasource, it works fine.

Here's the datasource bean:

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myDB" />
    <property name="resourceRef" value="false" />
</bean>

My web.xml resource ref:

<resource-ref>
   <res-ref-name>jdbc/myDB</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>

My Tomcat's server.xml resources:

-->

<Resource name="jdbc/myDB"
          global="jdbc/myDB"
          auth="Container"
          type="javax.sql.DataSource"
          username="xxxxx"
          password="yyyyyy"
          url="jdbc:oracle:thin:@xxx.yyy"
          driverClassName="oracle.jdbc.OracleDriver"
          initialSize="20"
          maxWaitMillis="15000"
          maxTotal="75"
          maxIdle="20"
          maxAge="7200000"
          testOnBorrow="true"
          validationQuery="select 1 from dual"
          />

And my context.xml

  <ResourceLink name="jdbc/myDB"
    global="jdbc/myDB"
    type="javax.sql.DataSource"/>

The error I'm getting is this:

ERROR: Unable obtain JDBC Connection java.sql.SQLException: Cannot
  create JDBC driver of class '' for connect URL 'null'     at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2167)
    at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2037)
    at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
    at
  org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    at
  org.hibernate.internal.SessionFactoryImpl$1.obtainConnection(SessionFactoryImpl.java:419)
    at
  org.hibernate.hql.spi.id.IdTableHelper.executeIdTableCreationStatements(IdTableHelper.java:67)
    at
  org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:125)
    at
  org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:42)
    at
  org.hibernate.hql.spi.id.AbstractMultiTableBulkIdStrategyImpl.prepare(AbstractMultiTableBulkIdStrategyImpl.java:88)
    at
  org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:302)
    at
  org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
    at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
    at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at
  org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:511)
    at
  org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:495)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at
  org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at
  org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at
  org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at
  org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at
  org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at
  org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4940)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5250)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at java.util.concurrent.FutureTask.run(Unknown Source)  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)     at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)    at
  java.lang.Thread.run(Unknown Source) Caused by: java.sql.SQLException:
  No suitable driver    at java.sql.DriverManager.getDriver(Unknown
  Source)   at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2151)
    ... 44 more

My Tomcat lib directory has the ojdbc jar that I need,  and I've even included it on my build script. What could be causing this?


问:
How to use tlb file in C?
tlb file(using regasm) is made from a dll(using c# code), and i can use this in c++ using #import. and everything is working fine.
Is there a way, i can use this in C language? I just found that #import is c++ specific. So, can someone please tell me how can i use in my C program?

my main intention is to use COM DLL developed in C# in my C program.

Thanks & Rgds,
~calvin

答:
You can use regasm with /tlb option to register the types in windows registry. After that, you can create your instances like regular COM calls from C++ code.

From MSDN:

When you specify the /tlb option, Regasm.exe generates and registers a type library describing the types found in the assembly. Regasm.exe places the generated type libraries in the current working directory or the directory specified for the output file. Generating a type library for an assembly that references other assemblies may cause several type libraries to be generated at once. You can use the type library to provide type information to development tools like Visual Studio 2005. You should not use the /tlb option if the assembly you are registering was produced by the Type Library Importer (Tlbimp.exe). You cannot export a type library from an assembly that was imported from a type library. Using the /tlb option has the same effect as using the Type Library Exporter (Tlbexp.exe) and Regasm.exe, with the exception that Tlbexp.exe does not register the type library it produces. If you use the /tlb option to registered a type library, you can use /tlb option with the /unregister option to unregistered the type library. Using the two options together will unregister the type library and interface entries, which can clean the registry considerably.

Title: How to use tlb file in C?


问:
How can add a new column in df1 called value that looks up the value from df2 based on the year column?
I have two DataFrames,

df1

```<code>Name    Year
A       2008
A       2009
B       2008
B       2008
</code>```

df2

```<code>year    value
2008    10
2009    15
</code>```

How can add a new column in df1 called value that looks up the value from df2 based on the year column?

Goal

```<code>Name  Year  Value
A     2008  10
A     2009  15
B     2008  10
B     2009  15
</code>```

My issue ended up being datatypes..

```<code> df = df.convert_objects(convert_numeric=True)
</code>```

The map solution was the fastest with 76,000 rows

答:
you can use join to achieve this

```<code>df1.join(df2.set_index('year'), on='Year')

  Name  Year  value
0    A  2008     10
1    A  2009     15
2    B  2008     10
3    B  2008     10
</code>```

Body:
I have two DataFrames,

df1

Name    Year
A       2008
A       2009
B       2008
B       2008

df2

year    value
2008    10
2009    15

How can add a new column in df1 called value that looks up the value from df2 based on the year column?

Goal

Name  Year  Value
A     2008  10
A     2009  15
B     2008  10
B     2009  15

My issue ended up being datatypes..

 df = df.convert_objects(convert_numeric=True)

The map solution was the fastest with 76,000 rows

Body:
you can use join to achieve this

df1.join(df2.set_index('year'), on='Year')

  Name  Year  value
0    A  2008     10
1    A  2009     15
2    B  2008     10
3    B  2008     10


问:
Expression in FOR section of PIVOT
I'm trying to use PIVOT to get the total weight of purchases per product, broken down by year/month in columns. Something like this:

```<code>+------------+--------+--------+--------+
| ProductKey | Jan-14 | Feb-14 | Mar-14 | Etc...
+------------+--------+--------+--------+
|         10 |   5000 |   7000 |   3000 |
|         20 |  10000 |   8000 |   6000 |
|         30 |    250 |    500 |    400 |
+------------+--------+--------+--------+
</code>```

This is my first time trying to use PIVOT, so not sure this is right:

```<code>PIVOT
(
SUM([PO_PurchaseOrderLines].[EstimatedWeight])
FOR
LEFT(DATENAME(MONTH,[PO_Date]),3) & "-" & RIGHT(YEAR([PO_Date]),2)
IN (Jan-14, Feb-14, Mar-14, Apr-14, May-14, Jun-14, Jul-14, Aug-14, Sep-14, Oct-14, Nov-14, Dec-14, Jan-15, Feb-15, Mar-15, Apr-15, May-15, Jun-15, Jul-15, Aug-15, Sep-15, Oct-15, Nov-15, Dec-15, Jan-16, Feb-16, Mar-16, Apr-16, May-16, Jun-16, Jul-16, Aug-16, Sep-16, Oct-16, Nov-16, Dec-16, Jan-17, Feb-17, Mar-17)
) AS POPivot
</code>```

Running this results in:

```<code>[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'LEFT'.
</code>```

Is using an expression like this in the FOR section not possible? Is there something else incorrect?

答:
```<code>Select *
From (
        Select ProductKey
              ,Col = format(PO_Date,'MMM-yy')
              ,EstimatedWeight
         From YourTable A
     ) A
 Pivot (sum(EstimatedWeight) For [Col] in ([Jan-14],[Feb-14],[Mar-14]) ) p
</code>```

Title: Expression in FOR section of PIVOT

Body:
I'm trying to use PIVOT to get the total weight of purchases per product, broken down by year/month in columns. Something like this:

+------------+--------+--------+--------+
| ProductKey | Jan-14 | Feb-14 | Mar-14 | Etc...
+------------+--------+--------+--------+
|         10 |   5000 |   7000 |   3000 |
|         20 |  10000 |   8000 |   6000 |
|         30 |    250 |    500 |    400 |
+------------+--------+--------+--------+

This is my first time trying to use PIVOT, so not sure this is right:

PIVOT
(
SUM([PO_PurchaseOrderLines].[EstimatedWeight])
FOR
LEFT(DATENAME(MONTH,[PO_Date]),3) & "-" & RIGHT(YEAR([PO_Date]),2)
IN (Jan-14, Feb-14, Mar-14, Apr-14, May-14, Jun-14, Jul-14, Aug-14, Sep-14, Oct-14, Nov-14, Dec-14, Jan-15, Feb-15, Mar-15, Apr-15, May-15, Jun-15, Jul-15, Aug-15, Sep-15, Oct-15, Nov-15, Dec-15, Jan-16, Feb-16, Mar-16, Apr-16, May-16, Jun-16, Jul-16, Aug-16, Sep-16, Oct-16, Nov-16, Dec-16, Jan-17, Feb-17, Mar-17)
) AS POPivot

Running this results in:

[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'LEFT'.

Is using an expression like this in the FOR section not possible? Is there something else incorrect?


问:
Lifting Functions using Cats Functor
with Cats, I can write this simple program

```<code>def foo(x: Int) = x + 1
val bar = Functor[Future](foo)
</code>```

and Now I can do a bar(future(1)) and get a Future.Success(2) as a result. Very good.

But suppose my function was

```<code>def foo[T](x: T)(implicit m: Manifest[T]) : String = {...}
</code>```

Now if I try to lift this function

```<code>def futureFoo = Functor[Future].lift(foo)
</code>```

I get a compiler error No Manifest available for T.

So how do I lift this function?

I searched and found this thread (which is for scalaz)

Lifting a function which takes implicit parameter using functor (Scalaz7)

But I still couldn't create anything which worked for me. I tried

```<code>val futureFoo = Functor[T].lift2(foo[T] _)
</code>```

but this doesn't compile

答:
Functions in Scala cannot have implicit parameters, so when you try to eta-expand a method with an implicit parameter into a function, the implicit needs to be resolved before the function itself is applied. That is, at the time of eta-expansion. The compiler doesn't have a generic Manifest[T] in scope, but futureFoo can require one.

```<code>def foo[T](x: T)(implicit m: Manifest[T]) : String = ""

scala> def optionFoo[T: Manifest] = Functor[Option].lift(foo[T] _)
optionFoo: [T](implicit evidence$1: Manifest[T])Option[T] => Option[String]
</code>```

I used Option because I didn't have a Functor[Future] readily available, the the same concept applies. Note that in order to use this, you'll need to supply the type parameter manually for it to return the correct function.

```<code>scala> optionFoo[Int].apply(Option(1))
res2: Option[String] = Some()
</code>```

Title: Lifting Functions using Cats Functor

Body:
with Cats, I can write this simple program

def foo(x: Int) = x + 1
val bar = Functor[Future](foo)

and Now I can do a bar(future(1)) and get a Future.Success(2) as a result. Very good.

But suppose my function was

def foo[T](x: T)(implicit m: Manifest[T]) : String = {...}

Now if I try to lift this function

def futureFoo = Functor[Future].lift(foo)

I get a compiler error No Manifest available for T.

So how do I lift this function?

I searched and found this thread (which is for scalaz)

Lifting a function which takes implicit parameter using functor (Scalaz7)

But I still couldn't create anything which worked for me. I tried

val futureFoo = Functor[T].lift2(foo[T] _)

but this doesn't compile

Body:
Functions in Scala cannot have implicit parameters, so when you try to eta-expand a method with an implicit parameter into a function, the implicit needs to be resolved before the function itself is applied. That is, at the time of eta-expansion. The compiler doesn't have a generic Manifest[T] in scope, but futureFoo can require one.

def foo[T](x: T)(implicit m: Manifest[T]) : String = ""

scala> def optionFoo[T: Manifest] = Functor[Option].lift(foo[T] _)
optionFoo: [T](implicit evidence$1: Manifest[T])Option[T] => Option[String]

I used Option because I didn't have a Functor[Future] readily available, the the same concept applies. Note that in order to use this, you'll need to supply the type parameter manually for it to return the correct function.

scala> optionFoo[Int].apply(Option(1))
res2: Option[String] = Some()


问:
How to access nested object array Javascript
I know this has been asked before but I can't seem to find the answer.
I just want to know how to access the values in service_name array in a console.log

Below is the array and just a snip out of the data.

var a = [{"ID":102254,"Name":"obj 1","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":226619,"Name":"DIDE","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":224522,"Name":"CAT","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":122533,"Name":"Mirror","service_name":["Open  Ticket","Escalation Ticket"]}]

console.log(JSON.stringify(a, 0, 4))```

答:
You can create a function to return the service names array of the element whose ID matches the id you are looking for like so:

function getServiceNamesById (data, id) {
  for (var i = 0; i < data.length; i++) {
    if (data[i].ID === id) {
      return data[i].service_name;
    }
  }
  return [];
}

var a = [{"ID":102254,"Name":"obj 1","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":226619,"Name":"DIDE","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":224522,"Name":"CAT","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":122533,"Name":"Mirror","service_name":["Open  Ticket","Escalation Ticket"]}];

var id = 226619;

console.log(getServiceNamesById(a, id));```


答:
Try this one  :

```<code>  var a = [{"ID":102254,"Name":"obj 1","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":226619,"Name":"DIDE","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":224522,"Name":"CAT","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":122533,"Name":"Mirror","service_name":["Open  Ticket","Escalation Ticket"]}]

 a.forEach(function(item){ // item is an object
     item.service_name.forEach(function(service){ //item.service_name is  an array
     console.log(service);
     });
 });
</code>```

Good luck

Title: How to access nested object array Javascript

Body:
I know this has been asked before but I can't seem to find the answer.
I just want to know how to access the values in service_name array in a console.log

Below is the array and just a snip out of the data.

var a = [{"ID":102254,"Name":"obj 1","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":226619,"Name":"DIDE","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":224522,"Name":"CAT","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":122533,"Name":"Mirror","service_name":["Open  Ticket","Escalation Ticket"]}]

console.log(JSON.stringify(a, 0, 4))

Body:
Try this one  :

  var a = [{"ID":102254,"Name":"obj 1","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":226619,"Name":"DIDE","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":224522,"Name":"CAT","service_name":["Open  Ticket","Escalation Ticket"]},{"ID":122533,"Name":"Mirror","service_name":["Open  Ticket","Escalation Ticket"]}]

 a.forEach(function(item){ // item is an object
     item.service_name.forEach(function(service){ //item.service_name is  an array
     console.log(service);
     });
 });

Good luck


问:
PyPDF2: Stream has ended unexpectedly
I have a Python script which uses PyPDF2 to reverse the order of pages of a PDF.

```<code>from  PyPDF2 import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
rpage = []
name = input("What's the file called?")

filename = name.split('.', 1)

input1 = PdfFileReader(open(name,'rb'), strict = False)

pages = list(range(1,input1.getNumPages() + 1))

for i in range(0, (input1.getNumPages())):
    rpage.append(pages[input1.getNumPages() - i -1])
for i in rpage:
    output.addPage(input1.getPage(i-1))

outputpath = filename[0] + '-reversed.pdf'

outputStream = open(outputpath, "wb")
output.write(outputStream)
</code>```

Which functions as intended up until trying to write the output stream, where it returns this error:

```<code>PdfReadWarning: Invalid stream (index 59) within object 108 0: Stream has ended unexpectedly [pdf.py:1573]
Traceback (most recent call last):
  File "D:\Documents\Google Drive\Programming\Python\PDF Scripts\reverse pdf.py", line 22, in <module>
output.write(outputStream)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 482, in write
self._sweepIndirectReferences(externalReferenceMap, self._root)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 556, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, data[i])
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 577, in _sweepIndirectReferences
    newobj = data.pdf.getObject(data)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1611, in getObject
    retval = readObject(self.stream, self)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 66, in readObject
    return DictionaryObject.readFromStream(stream, pdf)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 611, in readFromStream
    data["__streamdata__"] = stream.read(length)
TypeError: integer argument expected, got 'NullObject'
</code>```

The code does create a PDF file but it has a size of 0KB and is, therefore, unreadable. I have tested a sample script to merge three PDFs found here which produces another empty file and results in this error:

```<code>PdfReadWarning: Invalid stream (index 59) within object 108 0: Stream has ended unexpectedly [pdf.py:1573]
Traceback (most recent call last):
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1567, in _getObjectFromStream
    obj = readObject(streamData, self)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 98, in readObject
    return NumberObject.readFromStream(stream)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 269, in readFromStream
    num = utils.readUntilRegex(stream, NumberObject.NumberPattern)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\utils.py", line 134, in readUntilRegex
    raise PdfStreamError("Stream has ended unexpectedly")
PyPDF2.utils.PdfStreamError: Stream has ended unexpectedly

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Documents\Google Drive\Programming\Python\PDF Scripts\untitled1.py", line 27, in <module>
    merger.write(output)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\merger.py", line 230, in write
    self.output.write(fileobj)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 482, in write
    self._sweepIndirectReferences(externalReferenceMap, self._root)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 556, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, data[i])
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 577, in _sweepIndirectReferences
    newobj = data.pdf.getObject(data)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1611, in getObject
    retval = readObject(self.stream, self)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 66, in readObject
    return DictionaryObject.readFromStream(stream, pdf)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 609, in readFromStream
    length = pdf.getObject(length)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1593, in getObject
    retval = self._getObjectFromStream(indirectReference)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1576, in _getObjectFromStream
    raise utils.PdfReadError("Can't read object stream: %s"%e)
PyPDF2.utils.PdfReadError: Can't read object stream: Stream has ended unexpectedly
</code>```

The previous error is also outputted when this script is used to split a PDF into its constituent pages:

```<code>from PyPDF2 import PdfFileWriter, PdfFileReader
infile = PdfFileReader(open('test.pdf', 'rb'))

for i in range(infile.getNumPages()):
    p = infile.getPage(i)
    outfile = PdfFileWriter()
    outfile.addPage(p)
    with open('page-%02d.pdf' % i, 'wb') as f:
        outfile.write(f)
</code>```

The above code produces (n-1) readable PDFs but with nth PDF is an empty file. Any idea how I can fix this?

答:
If all you want is to be able to reverse the pages for printing, and you don't care about trying to preserve internal links and annotations, pdfrw might be better for the task than pyPDF2:

```<code>from  pdfrw import PdfWriter, PdfReader

iname = input("What's the file called? ")
oname = iname.rsplit('.', 1)[0] + '-reversed.pdf'

output = PdfWriter()
output.addpages(reversed(PdfReader(iname).pages))
output.write(oname)
</code>```

Disclaimer:  I am the primary pdfrw author.

Title: PyPDF2: Stream has ended unexpectedly

Body:
I have a Python script which uses PyPDF2 to reverse the order of pages of a PDF.

from  PyPDF2 import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
rpage = []
name = input("What's the file called?")

filename = name.split('.', 1)

input1 = PdfFileReader(open(name,'rb'), strict = False)

pages = list(range(1,input1.getNumPages() + 1))

for i in range(0, (input1.getNumPages())):
    rpage.append(pages[input1.getNumPages() - i -1])
for i in rpage:
    output.addPage(input1.getPage(i-1))

outputpath = filename[0] + '-reversed.pdf'

outputStream = open(outputpath, "wb")
output.write(outputStream)

Which functions as intended up until trying to write the output stream, where it returns this error:

PdfReadWarning: Invalid stream (index 59) within object 108 0: Stream has ended unexpectedly [pdf.py:1573]
Traceback (most recent call last):
  File "D:\Documents\Google Drive\Programming\Python\PDF Scripts\reverse pdf.py", line 22, in <module>
output.write(outputStream)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 482, in write
self._sweepIndirectReferences(externalReferenceMap, self._root)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 556, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, data[i])
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 577, in _sweepIndirectReferences
    newobj = data.pdf.getObject(data)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1611, in getObject
    retval = readObject(self.stream, self)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 66, in readObject
    return DictionaryObject.readFromStream(stream, pdf)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 611, in readFromStream
    data["__streamdata__"] = stream.read(length)
TypeError: integer argument expected, got 'NullObject'

The code does create a PDF file but it has a size of 0KB and is, therefore, unreadable. I have tested a sample script to merge three PDFs found here which produces another empty file and results in this error:

PdfReadWarning: Invalid stream (index 59) within object 108 0: Stream has ended unexpectedly [pdf.py:1573]
Traceback (most recent call last):
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1567, in _getObjectFromStream
    obj = readObject(streamData, self)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 98, in readObject
    return NumberObject.readFromStream(stream)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 269, in readFromStream
    num = utils.readUntilRegex(stream, NumberObject.NumberPattern)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\utils.py", line 134, in readUntilRegex
    raise PdfStreamError("Stream has ended unexpectedly")
PyPDF2.utils.PdfStreamError: Stream has ended unexpectedly

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Documents\Google Drive\Programming\Python\PDF Scripts\untitled1.py", line 27, in <module>
    merger.write(output)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\merger.py", line 230, in write
    self.output.write(fileobj)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 482, in write
    self._sweepIndirectReferences(externalReferenceMap, self._root)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 556, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, data[i])
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 577, in _sweepIndirectReferences
    newobj = data.pdf.getObject(data)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1611, in getObject
    retval = readObject(self.stream, self)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 66, in readObject
    return DictionaryObject.readFromStream(stream, pdf)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\generic.py", line 609, in readFromStream
    length = pdf.getObject(length)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1593, in getObject
    retval = self._getObjectFromStream(indirectReference)
  File "C:\Users\Charles\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1576, in _getObjectFromStream
    raise utils.PdfReadError("Can't read object stream: %s"%e)
PyPDF2.utils.PdfReadError: Can't read object stream: Stream has ended unexpectedly

The previous error is also outputted when this script is used to split a PDF into its constituent pages:

from PyPDF2 import PdfFileWriter, PdfFileReader
infile = PdfFileReader(open('test.pdf', 'rb'))

for i in range(infile.getNumPages()):
    p = infile.getPage(i)
    outfile = PdfFileWriter()
    outfile.addPage(p)
    with open('page-%02d.pdf' % i, 'wb') as f:
        outfile.write(f)

The above code produces (n-1) readable PDFs but with nth PDF is an empty file. Any idea how I can fix this?

Body:
If all you want is to be able to reverse the pages for printing, and you don't care about trying to preserve internal links and annotations, pdfrw might be better for the task than pyPDF2:

from  pdfrw import PdfWriter, PdfReader

iname = input("What's the file called? ")
oname = iname.rsplit('.', 1)[0] + '-reversed.pdf'

output = PdfWriter()
output.addpages(reversed(PdfReader(iname).pages))
output.write(oname)

Disclaimer:  I am the primary pdfrw author.


问:
How to run appveyor.yml script locally?
I want to install mlpack in windows and I found the appveyor.yml script in github. Instead of following and executing each step manually, is there a way to run this script in my laptop? Like, something similar to a bat file?</p>

答:
appveyor.ymlis configuration file for AppVeyor builds, and supposed to be executed on AppVeyor build VMs. I heard about project LocalAppVeyor which should help you to run this locally but I did not try it.

If you want just bat file, you can copy all commands from install and build_script to your bat file. Command with just - in the beginning are standard cmd commands. Command with just - ps: in the beginning are expected to run in PowerShell, however I do not see anything PowerShell specific in command is this file. Sure you need to remove - and - ps: to run them in bat file.

artifacts, notifications and other AppVeyor specific steps cannot be called from bat file, they require engine which understand this file, which is AppVeyor build or this LocalAppVeyor which again I never tested.

Title: How to run appveyor.yml script locally?


问:
Asterisk 13 unable to read the extensions.conf file
I have an odd issue, asterisk was work just fine, then it suddenly stopped working.
when i make a call it always replay with code 404, which means user not found, which means it can't read the extensions.conf file, also when i do the command
dialplan reload in asterisk cli, it replies with command not found, also when i do the command core reload in asterisk cli nothing happend.
i tried to restart the service and restart the server and still no solution.
please help me with this problem.

答: It may be possible that your modules aren't loaded. Check if they exist. Sometimes file permissions of the modules can also create such problems. You can try rebuilding your asterisk too.</p>


问:
How to unit test that object was passed with correct state?
Lets say there is such function:

```<code>function a()
{
    $entity = $this->getEntity();

    $entity->setSomePrivateVar();

    $service = $this->getService();

    $service->doSomething($entity);

}
</code>```

I want to test that

```<code> $service->doSomething($entity);
</code>```

is called with correct $entity.

The $entity calls setSomePrivateVar()

In real application code I have done something like this:

Get mock of entity and test that setSomePrivateVar is called.

Get mock of $service and test that doSomething() is called with parameter $entity.

Looks ok.

But the problem is - if I refactor code and first call doSomething() on service and then setSomePrivateVar() on $entity, test still passes.

But the function is now wrong, because doSomething is depending on $entity private field which is set by setSomePrivateVar().

For example I would refactor to this:

```<code>function a()
{
    $entity = $this->getEntity();

    $service = $this->getService();

    $service->doSomething($entity);

    // this line moved
    $entity->setSomePrivateVar();

}
</code>```

So it looks like PhpUnit is not checking $entity private fields. If it was for example array, then with() function would see that array passed is not same as expected.

So how do I test that doSomething() gets $entity in correct state (that setSomePrivateVar() was called on entity before passing it to doSomething() )?

Maybe it has something to do that $entity is mocked.

Update with real world example

```<code>public function setNotifyUsers(AnnualConsolidation $consolidation, $status)
{
    $consolidation->setNotifyUsers($status);    // if move this method after the flush(), tesst does not fail

    $this->entityManager->persist($consolidation);
    $this->entityManager->flush();
}

public function testNotifyUsers()
{
    $consolidation = $this->getMockBuilder(AnnualConsolidation::class)
        ->setMethods(['setNotifyUsers'])
        ->getMock();

    $consolidation
        ->expects($this->once())
        ->method('setNotifyUsers')
    ;

    $this->entityManager
        ->expects($this->at(0))
        ->method('persist')
        ->with($consolidation)
    ;

    $this->entityManager
        ->expects($this->at(1))
        ->method('flush')
    ;

    /** @var AnnualConsolidation $consolidation */
    $this->consolidationsService->setNotifyUsers($consolidation, true);
}
</code>```

We were discussing if testing the setNotifyUsers method this way is even good. I was trying to test without hitting the database. One guy thinks that this might be needed to test with hitting database, because if refactoring method without changing logic, test might be needed to refactor. On the other hand - this method is not likely to be refactored that much.

But maybe also there is a way to just test that flush() is called after persist() without telling indexes, because in other examples, the indexes then might be needed to update after adding some call before persist and so might be too much work to keep tests working.

But for this topic - first I want to know how to make test fail  - if I move setNotifyUsers after the flush(). Test is not failing. While if we would test with hitting database - we would see that $consolidation status is not updated.

One guy told to check, assert what is passed to the persist method. I did not try yet, but I am not sure if on mocked $consolidation this will be possible. Does mocked $consolidation has some state as real $consolidation would have?

答:
As you say in your question

One guy told to check, assert what is passed to the persist method.

That would be the way to go but your code makes that rather hard and i think you should refactor a bit to make the code testable.

First your method is called "setNotifyUsers" but it does actually do 2 actions it calls the setNotifyUsers on the consolidation object and it saves/persists this data.
In my opinion those are 2 different actions that should belong in 2 different methods. It could help your test if you wrote it like :

```<code>public function setNotifyUsers(AnnualConsolidation $consolidation, $status) {
  $consolidation->setNotifyUsers($status);
}

public function persistConsolidation(AnnualConsolidation $consolidation) {
  $this->entityManager->persist($consolidation);
  $this->entityManager->flush();
}
</code>```

You could test the setNotifyUser and persistConsolidation sepperately and write a functional test for the part that calls these functions (the methods that use the consolidationsService)
then you can use the at() functionality to see if those functions are called in the correct order.

But:
Second you give both the state as the consolidation to this function with as only reason to add those together. i don't think something like that belongs in the service but rather in the method
calling that service.
Moving that functionality will again give you trouble as you cannot test the order in which they are called.

But you don't need to use the mockBuilder to make a test double.
Instead of using $this->getMockBuilder you can also create a FakeConsolidation that will actually hold the data for you

Then you will also need a mock for the AnnualConsolidation because you want to be able to check if the value was correctly set.

```<code>class FakeConsolidation extends AnnualConsolidation {

  protected $id;
  proteced $status;

  public function getId() {
    return $this->id;
  }

  public function setId($id) {
     $this->id = $id;
  }

  public function setNotifyUsers($status) {
    $this->status = $status;
  }

  public function shouldNotifyUsers() {
    $this->status
  }
}
</code>```

Now because you will give an object to the persist that has a state we can check that state in the "with" part.

Of course, I do not know exactly how your code is structured so I made some assumptions just adapt where needed and use the interfaces that you have.

Like this you could even test the code as you presented it in this question:

```<code>class SomethingTest extends PHPUnit_Framework_TestCase {
  private $consolidationsService;
  private $entityManager;

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    $this->entityManager = $this->getMockBuilder(EntityManager::class)->getMock();
    $this->consolidationsService = new ConsolidationsService($this->entityManager);
  }

  public function testNotifyUsers() {
    $consolidation = new FakeConsolidation();
    $consolidation->setId(1);
    $this->entityManager
      ->expects($this->at(0))
      ->method('persist')
      ->with($this->callback(
          function($savedConsolidation) {
            return $savedConsolidation->shouldNotifyUsers() === true;
          }
      ));

    $this->entityManager
      ->expects($this->at(1))
      ->method('flush');

    /** @var AnnualConsolidation $consolidation */
    $this->consolidationsService->setNotifyUsers($consolidation, TRUE);
  }

}
</code>```

Now when you move the setNotifyUsers below the persist

```<code>with($this->callback(
              function($savedConsolidation) {
                return $savedConsolidation->shouldNotifyUsers() === true;
              }
          ));
</code>```

Your test will fail because the status is not set yet.

Body:
Lets say there is such function:

function a()
{
    $entity = $this->getEntity();

    $entity->setSomePrivateVar();

    $service = $this->getService();

    $service->doSomething($entity);

}

I want to test that

 $service->doSomething($entity);

is called with correct $entity.

The $entity calls setSomePrivateVar()

In real application code I have done something like this:

Get mock of entity and test that setSomePrivateVar is called.

Get mock of $service and test that doSomething() is called with parameter $entity.

Looks ok.

But the problem is - if I refactor code and first call doSomething() on service and then setSomePrivateVar() on $entity, test still passes.

But the function is now wrong, because doSomething is depending on $entity private field which is set by setSomePrivateVar().

For example I would refactor to this:

function a()
{
    $entity = $this->getEntity();

    $service = $this->getService();

    $service->doSomething($entity);

    // this line moved
    $entity->setSomePrivateVar();

}

So it looks like PhpUnit is not checking $entity private fields. If it was for example array, then with() function would see that array passed is not same as expected.

So how do I test that doSomething() gets $entity in correct state (that setSomePrivateVar() was called on entity before passing it to doSomething() )?

Maybe it has something to do that $entity is mocked.

Update with real world example

public function setNotifyUsers(AnnualConsolidation $consolidation, $status)
{
    $consolidation->setNotifyUsers($status);    // if move this method after the flush(), tesst does not fail

    $this->entityManager->persist($consolidation);
    $this->entityManager->flush();
}

public function testNotifyUsers()
{
    $consolidation = $this->getMockBuilder(AnnualConsolidation::class)
        ->setMethods(['setNotifyUsers'])
        ->getMock();

    $consolidation
        ->expects($this->once())
        ->method('setNotifyUsers')
    ;

    $this->entityManager
        ->expects($this->at(0))
        ->method('persist')
        ->with($consolidation)
    ;

    $this->entityManager
        ->expects($this->at(1))
        ->method('flush')
    ;

    /** @var AnnualConsolidation $consolidation */
    $this->consolidationsService->setNotifyUsers($consolidation, true);
}

We were discussing if testing the setNotifyUsers method this way is even good. I was trying to test without hitting the database. One guy thinks that this might be needed to test with hitting database, because if refactoring method without changing logic, test might be needed to refactor. On the other hand - this method is not likely to be refactored that much.

But maybe also there is a way to just test that flush() is called after persist() without telling indexes, because in other examples, the indexes then might be needed to update after adding some call before persist and so might be too much work to keep tests working.

But for this topic - first I want to know how to make test fail  - if I move setNotifyUsers after the flush(). Test is not failing. While if we would test with hitting database - we would see that $consolidation status is not updated.

One guy told to check, assert what is passed to the persist method. I did not try yet, but I am not sure if on mocked $consolidation this will be possible. Does mocked $consolidation has some state as real $consolidation would have?

Body:
As you say in your question

One guy told to check, assert what is passed to the persist method.

That would be the way to go but your code makes that rather hard and i think you should refactor a bit to make the code testable.

First your method is called "setNotifyUsers" but it does actually do 2 actions it calls the setNotifyUsers on the consolidation object and it saves/persists this data.
In my opinion those are 2 different actions that should belong in 2 different methods. It could help your test if you wrote it like :

public function setNotifyUsers(AnnualConsolidation $consolidation, $status) {
  $consolidation->setNotifyUsers($status);
}

public function persistConsolidation(AnnualConsolidation $consolidation) {
  $this->entityManager->persist($consolidation);
  $this->entityManager->flush();
}

You could test the setNotifyUser and persistConsolidation sepperately and write a functional test for the part that calls these functions (the methods that use the consolidationsService)
then you can use the at() functionality to see if those functions are called in the correct order.

But:
Second you give both the state as the consolidation to this function with as only reason to add those together. i don't think something like that belongs in the service but rather in the method
calling that service.
Moving that functionality will again give you trouble as you cannot test the order in which they are called.

But you don't need to use the mockBuilder to make a test double.
Instead of using $this->getMockBuilder you can also create a FakeConsolidation that will actually hold the data for you

Then you will also need a mock for the AnnualConsolidation because you want to be able to check if the value was correctly set.

class FakeConsolidation extends AnnualConsolidation {

  protected $id;
  proteced $status;

  public function getId() {
    return $this->id;
  }

  public function setId($id) {
     $this->id = $id;
  }

  public function setNotifyUsers($status) {
    $this->status = $status;
  }

  public function shouldNotifyUsers() {
    $this->status
  }
}

Now because you will give an object to the persist that has a state we can check that state in the "with" part.

Of course, I do not know exactly how your code is structured so I made some assumptions just adapt where needed and use the interfaces that you have.

Like this you could even test the code as you presented it in this question:

class SomethingTest extends PHPUnit_Framework_TestCase {
  private $consolidationsService;
  private $entityManager;

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    $this->entityManager = $this->getMockBuilder(EntityManager::class)->getMock();
    $this->consolidationsService = new ConsolidationsService($this->entityManager);
  }

  public function testNotifyUsers() {
    $consolidation = new FakeConsolidation();
    $consolidation->setId(1);
    $this->entityManager
      ->expects($this->at(0))
      ->method('persist')
      ->with($this->callback(
          function($savedConsolidation) {
            return $savedConsolidation->shouldNotifyUsers() === true;
          }
      ));

    $this->entityManager
      ->expects($this->at(1))
      ->method('flush');

    /** @var AnnualConsolidation $consolidation */
    $this->consolidationsService->setNotifyUsers($consolidation, TRUE);
  }

}

Now when you move the setNotifyUsers below the persist

with($this->callback(
              function($savedConsolidation) {
                return $savedConsolidation->shouldNotifyUsers() === true;
              }
          ));

Your test will fail because the status is not set yet.


问:
Visual Studio Extension - set "Copy To Output Directory" property
I'm creating a VS extension, and I want to add a file to solution and set some properties. One of them is Copy to output directory, but I cannot find a way of setting it. Setting Build action works fine, but the desired property is not even listed in array while debugging.

```<code>private EnvDTE.ProjectItem AddFileToSolution(string filePath)
{
  var folder = CurrentProject.ProjectItems.AddFolder(Path.GetDirectoryName(filePath));
  var item = folder.ProjectItems.AddFromFileCopy(filePath);

  item.Properties.Item("BuildAction").Value = "None";
  // item.Properties.Item("CopyToOutputDirectory").Value = "CopyAlways"; // doesn't work - the dictionary doesn't contain this item, so it throws an exception

  return item;
}
</code>```

How can I set the property for my newly added item?

答:
For C# or VB projects, Cole Wu - MSFT's answer should work.

If you're trying to do the same thing for different kind of project than you might be out of luck since each project type has different properties.

From what I have tried:

C# and VB have 23 properties including "CopyToOutputDirectory"

F# has 9 properties including "CopyToOutputDirectory"

Node.js has 13 properties and "CopyToOutputDirectory" is missing

Look at property window of file in project you are trying to modify. Does it contain "CopyToOutputDirectory" property? If not than this property is probably not available.

EDIT:

Another options to set ProjectItem property is through it's attributes (modifying it in *.csproj). I would say that it is workaround, not real solution since you need to reload project afterwards.

```<code>private EnvDTE.ProjectItem AddFileToSolution(string filePath)
{
    var folder = CurrentProject.ProjectItems.AddFolder(Path.GetDirectoryName(filePath));
    var item = folder.ProjectItems.AddFromFileCopy(filePath);

    item.Properties.Item("BuildAction").Value = "None";

    // Setting attribute instead of property, becase property is not available
    SetProjectItemPropertyAsAttribute(CurrentProject, item, "CopyToOutputDirectory", "Always");

    // Reload project

    return item;
}

private void SetProjectItemPropertyAsAttribute(Project project, ProjectItem projectItem, string attributeName,
    string attributeValue)
{
    IVsHierarchy hierarchy;
    ((IVsSolution)Package.GetGlobalService(typeof(SVsSolution)))
        .GetProjectOfUniqueName(project.UniqueName, out hierarchy);

    IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;

    if (buildPropertyStorage != null)
    {
        string fullPath = (string)projectItem.Properties.Item("FullPath").Value;

        uint itemId;
        hierarchy.ParseCanonicalName(fullPath, out itemId);

        buildPropertyStorage.SetItemAttribute(itemId, attributeName, attributeValue);
    }
}
</code>```

Body:
I'm creating a VS extension, and I want to add a file to solution and set some properties. One of them is Copy to output directory, but I cannot find a way of setting it. Setting Build action works fine, but the desired property is not even listed in array while debugging.

private EnvDTE.ProjectItem AddFileToSolution(string filePath)
{
  var folder = CurrentProject.ProjectItems.AddFolder(Path.GetDirectoryName(filePath));
  var item = folder.ProjectItems.AddFromFileCopy(filePath);

  item.Properties.Item("BuildAction").Value = "None";
  // item.Properties.Item("CopyToOutputDirectory").Value = "CopyAlways"; // doesn't work - the dictionary doesn't contain this item, so it throws an exception

  return item;
}

How can I set the property for my newly added item?

Body:
For C# or VB projects, Cole Wu - MSFT's answer should work.

If you're trying to do the same thing for different kind of project than you might be out of luck since each project type has different properties.

From what I have tried:

C# and VB have 23 properties including "CopyToOutputDirectory"

F# has 9 properties including "CopyToOutputDirectory"

Node.js has 13 properties and "CopyToOutputDirectory" is missing

Look at property window of file in project you are trying to modify. Does it contain "CopyToOutputDirectory" property? If not than this property is probably not available.

EDIT:

Another options to set ProjectItem property is through it's attributes (modifying it in *.csproj). I would say that it is workaround, not real solution since you need to reload project afterwards.

private EnvDTE.ProjectItem AddFileToSolution(string filePath)
{
    var folder = CurrentProject.ProjectItems.AddFolder(Path.GetDirectoryName(filePath));
    var item = folder.ProjectItems.AddFromFileCopy(filePath);

    item.Properties.Item("BuildAction").Value = "None";

    // Setting attribute instead of property, becase property is not available
    SetProjectItemPropertyAsAttribute(CurrentProject, item, "CopyToOutputDirectory", "Always");

    // Reload project

    return item;
}

private void SetProjectItemPropertyAsAttribute(Project project, ProjectItem projectItem, string attributeName,
    string attributeValue)
{
    IVsHierarchy hierarchy;
    ((IVsSolution)Package.GetGlobalService(typeof(SVsSolution)))
        .GetProjectOfUniqueName(project.UniqueName, out hierarchy);

    IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;

    if (buildPropertyStorage != null)
    {
        string fullPath = (string)projectItem.Properties.Item("FullPath").Value;

        uint itemId;
        hierarchy.ParseCanonicalName(fullPath, out itemId);

        buildPropertyStorage.SetItemAttribute(itemId, attributeName, attributeValue);
    }
}


问:
SELECT * FROM X WHERE id IN (...) with Dapper ORM
What is the best way to write a query with IN clause using Dapper ORM when the list of values for the IN clause is coming from business logic? For example let's say I have a query:

SELECT *
  FROM SomeTable
 WHERE id IN (commaSeparatedListOfIDs)
```

The commaSeparatedListOfIDs is being passed in from business logic and it can be any type of IEnumerable(of Integer). How would I construct a query in this case? Do I have to do what I've been doing so far which is basically string concatenation or is there some sort of advanced parameter mapping technique that I'm not aware of?

答:
If your IN clause is too big for MSSQL to handle, you can use a TableValueParameter with Dapper pretty easily.

Create your TVP type in MSSQL:

```<code>CREATE TYPE [dbo].[MyTVP] AS TABLE([ProviderId] [int] NOT NULL)
</code>```

Create a DataTable with the same column(s) as the TVP and populate it with values

```<code>var tvpTable = new DataTable();
tvpTable.Columns.Add(new DataColumn("ProviderId", typeof(int)));
// fill the data table however you wish
</code>```

Modify your Dapper query to do an INNER JOIN on the TVP table:

```<code>var query = @"SELECT * FROM Providers P
    INNER JOIN @tvp t ON p.ProviderId = t.ProviderId";
</code>```

Pass the DataTable in your Dapper query call

```<code>sqlConn.Query(query, new {tvp = tvpTable.AsTableValuedParameter("dbo.MyTVP")});
</code>```

This also works fantastically when you want to do a mass update of multiple columns - simply build a TVP and do an UPDATE with an inner join to the TVP.

Body:
What is the best way to write a query with IN clause using Dapper ORM when the list of values for the IN clause is coming from business logic? For example let's say I have a query:

SELECT *
  FROM SomeTable
 WHERE id IN (commaSeparatedListOfIDs)

The commaSeparatedListOfIDs is being passed in from business logic and it can be any type of IEnumerable(of Integer). How would I construct a query in this case? Do I have to do what I've been doing so far which is basically string concatenation or is there some sort of advanced parameter mapping technique that I'm not aware of?

Body:
If your IN clause is too big for MSSQL to handle, you can use a TableValueParameter with Dapper pretty easily.

Create your TVP type in MSSQL:

CREATE TYPE [dbo].[MyTVP] AS TABLE([ProviderId] [int] NOT NULL)

Create a DataTable with the same column(s) as the TVP and populate it with values

var tvpTable = new DataTable();
tvpTable.Columns.Add(new DataColumn("ProviderId", typeof(int)));
// fill the data table however you wish

Modify your Dapper query to do an INNER JOIN on the TVP table:

var query = @"SELECT * FROM Providers P
    INNER JOIN @tvp t ON p.ProviderId = t.ProviderId";

Pass the DataTable in your Dapper query call

sqlConn.Query(query, new {tvp = tvpTable.AsTableValuedParameter("dbo.MyTVP")});

This also works fantastically when you want to do a mass update of multiple columns - simply build a TVP and do an UPDATE with an inner join to the TVP.


答:
It is simply a typo, the function you are looking for is getElementById.
By with a capital B instead of by.

here is a reference to that method.

Title: getElementbyId is not a function

Body:
I have a simple piece of JavaScript that changes the color of a button, but I keep getting he error that getting the button is not a function, even though the same function (with the same capitalisation and case) works just a couple of lines above.

if (this.ButtonColor != "") {
      var button = document.getElementbyId('modal-close');
      button.style.backgroundColor = this.ButtonColor;
 }