问:
Angular2: How do you properly bind to nested data?
I have a component I'm going to use as a shell for multiple choice questions to load into.  Here's how the component is set up so far

component

```<code>import { Component }    from '@angular/core';

export class Answers{
    id: string;
    answer: string;
}

const answers: Answers[] = [
        {
        id: 'exp01q',
        answer: 'Its fine as is.'
        },
        {
        id: 'exp02q',
        answer: 'I want to make minor adjustments.'
        },
        {
        id: 'exp03q',
        answer: 'I want to change my image'
        },
        {
        id: 'exp04q',
        answer: 'Ive never wanted to use a particular image until now.'
        }
    ];

@Component({
    moduleId: module.id,
    selector: 'multi-radio-btn',
    templateUrl: 'multi-rad-btn.component.html',
    styleUrls: ['multi-rad-btn.component.css']
})

export class MultiRadioBtnShell {

    question = 'How do you feel about your current image?';
    id = 'exp-img-q';
    name = 'exp-ques1';
    ans = answers;

}
</code>```

HTML Template

```<code><h3>radio button shell</h3>

<div class="row justify-content-center">
    <fieldset [attr.id]='id' class="card col-8 justify-content-center">

        <label class="ques-title">
            {{question}}
        </label>

        <div class="row answer-row-section justify-content-center">

            <div *ngFor="let answers of ans" class="col col-12 answer-row justify-content-center">
                <div class="col justify-content-center">

                    <input type="radio"
                        [attr.id]="answers.id"
                        [attr.name]="name"
                        [attr.value]="answers.answer" hidden />

                    <label [attr.for]="answers.id" class="col ques-ans-title" style="background-color: #4b73a0;">
                        {{answers.answer}}
                    </label>
                </div>
            </div>

        </div>

    </fieldset>
</div>
</code>```

The reason it's set up like this now is because the way I was trying to do it at first wasn't working so I went to the Tour of Heroes tutorial to follow along with how they loaded all the heroes.  The problem was coming from answer not being defined.  So I rigged that part up the same way they did the heroes just for the sake of doing something I'm able to follow just to be sure I get the mechanics of how things load.

The original way I tried to do it was with this

```<code>// I had this right above the component
export class ExpQ{
    question: string;
    id: string;
    name: string;
    answers:[
        {
        id: string;
        answer: string;
        }
    ]
}

// I had this in the component's class
export const expq: ExpQ[] = [
    {
    question: 'How do you feel about your current image?',
    id: 'exp-img-q',
    name: 'exp-ques1',
    answers:[
        {
        id: 'exp01q',
        answer: 'Its fine as is.'
        },
        {
        id: 'exp02q',
        answer: 'I want to make minor adjustments.'
        },
        {
        id: 'exp03q',
        answer: 'I want to change my image'
        },
        {
        id: 'exp04q',
        answer: 'Ive never wanted to use a particular image until now.'
        }
        ]
    }
]
</code>```

I was calling it in the html with

{{expq.question}}, {{expq.name}}, {{expq.answers.id}}, {{expq.answers.answer}}, etc.

at first with just loading the question it worked fine, but as I got to the answers: part it started breaking.  I came across this https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol and seen the syntax for the addresses: part was pretty much the same as how I needed to structure my data.  So I remade everything to resemble that.  I still had no luck getting it to work.

Ultimately I'm going to be sending the questions through the parent component with @input and @output as well as a couple other tricks I came across.  But before I can even think about that I need to get a handle on how to put the data all into one source so that it properly reads the nested bits of data.  All the examples I come across are simple single tier bits of data, so I'm not sure on the syntax I need to use.  How can I make this work?

答:
Need to flatten the objects,

Params :

Objects : at least n>0 array off JSON objects (dose not matter is circular)
   target : {}

path : ""

Note : make sure the Objects Array passed in is n>0 at least

```<code>flatten(objects, target, path) {
let me = this;
let retArray = [];
for(let x=0; x < objects.length; x++) {

  let object = objects[x];
  path = path || '';
  target={};

  target = me.flattenHelper(object, target, path);

  retArray.push(target);
}
return retArray;}
</code>```

..

```<code>flattenHelper(object, target, path){
let me = this;
Object.keys(object).forEach(function (key) {
  console.log("key : "+ key + " : object : " +  (object[key] && typeof object[key] === 'object') + " path : " + path);
  if (object[key] && typeof object[key] === 'object') {
      me.flattenHelper(object[key], target, path + key);
  }
  target[path + key] = object[key];
  console.log(target);
});
return target;}
</code>```

Body:
I have a component I'm going to use as a shell for multiple choice questions to load into.  Here's how the component is set up so far

component

import { Component }    from '@angular/core';

export class Answers{
    id: string;
    answer: string;
}

const answers: Answers[] = [
        {
        id: 'exp01q',
        answer: 'Its fine as is.'
        },
        {
        id: 'exp02q',
        answer: 'I want to make minor adjustments.'
        },
        {
        id: 'exp03q',
        answer: 'I want to change my image'
        },
        {
        id: 'exp04q',
        answer: 'Ive never wanted to use a particular image until now.'
        }
    ];

@Component({
    moduleId: module.id,
    selector: 'multi-radio-btn',
    templateUrl: 'multi-rad-btn.component.html',
    styleUrls: ['multi-rad-btn.component.css']
})

export class MultiRadioBtnShell {

    question = 'How do you feel about your current image?';
    id = 'exp-img-q';
    name = 'exp-ques1';
    ans = answers;

}

HTML Template

radio button shell

    <fieldset [attr.id]='id' class="card col-8 justify-content-center">

            {{question}}

                    <input type="radio"
                        [attr.id]="answers.id"
                        [attr.name]="name"
                        [attr.value]="answers.answer" hidden />

                        {{answers.answer}}

    </fieldset>

The reason it's set up like this now is because the way I was trying to do it at first wasn't working so I went to the Tour of Heroes tutorial to follow along with how they loaded all the heroes.  The problem was coming from answer not being defined.  So I rigged that part up the same way they did the heroes just for the sake of doing something I'm able to follow just to be sure I get the mechanics of how things load.

The original way I tried to do it was with this

// I had this right above the component
export class ExpQ{
    question: string;
    id: string;
    name: string;
    answers:[
        {
        id: string;
        answer: string;
        }
    ]
}

// I had this in the component's class
export const expq: ExpQ[] = [
    {
    question: 'How do you feel about your current image?',
    id: 'exp-img-q',
    name: 'exp-ques1',
    answers:[
        {
        id: 'exp01q',
        answer: 'Its fine as is.'
        },
        {
        id: 'exp02q',
        answer: 'I want to make minor adjustments.'
        },
        {
        id: 'exp03q',
        answer: 'I want to change my image'
        },
        {
        id: 'exp04q',
        answer: 'Ive never wanted to use a particular image until now.'
        }
        ]
    }
]

I was calling it in the html with

{{expq.question}}, {{expq.name}}, {{expq.answers.id}}, {{expq.answers.answer}}, etc.

at first with just loading the question it worked fine, but as I got to the answers: part it started breaking.  I came across this https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol and seen the syntax for the addresses: part was pretty much the same as how I needed to structure my data.  So I remade everything to resemble that.  I still had no luck getting it to work.

Ultimately I'm going to be sending the questions through the parent component with @input and @output as well as a couple other tricks I came across.  But before I can even think about that I need to get a handle on how to put the data all into one source so that it properly reads the nested bits of data.  All the examples I come across are simple single tier bits of data, so I'm not sure on the syntax I need to use.  How can I make this work?

Body:
Need to flatten the objects,

Params :

Objects : at least n>0 array off JSON objects (dose not matter is circular)
   target : {}

path : ""

Note : make sure the Objects Array passed in is n>0 at least

flatten(objects, target, path) {
let me = this;
let retArray = [];
for(let x=0; x < objects.length; x++) {

  let object = objects[x];
  path = path || '';
  target={};

  target = me.flattenHelper(object, target, path);

  retArray.push(target);
}
return retArray;}

..

flattenHelper(object, target, path){
let me = this;
Object.keys(object).forEach(function (key) {
  console.log("key : "+ key + " : object : " +  (object[key] && typeof object[key] === 'object') + " path : " + path);
  if (object[key] && typeof object[key] === 'object') {
      me.flattenHelper(object[key], target, path + key);
  }
  target[path + key] = object[key];
  console.log(target);
});
return target;}


来源: stackexchange

问:
Mysql Encryption Key
Is it possible to get the AES_ENCRYPT() key if i have the original string and the encrypted string?
Any help appreciated

答:
This is called a known-plaintext attack. Any modern cipher that have known plaintext attack is consider broken.

So, the answer is "no". (or, not yet, unless you count those academical papers)

ContentLicense: CC BY-SA 2.5

Title: Mysql Encryption Key


问:
How to make 2 circles rotate/spin like a wheel in Matlab
I've plotted two circles and filled them with the colormap 'jet'. However, every time I try to rotate the circles using rotate function or even the spin function of colormap to make the colour jet spin inside the circle - It changes the plot entirely - Rotating only 1 circle, filling up the screen, and rotating it at an angle.

Can someone please explain how I can rotate those 2 circles, as though they are wheels of a car?

The code is as follows: (I commented out my attempt at rotating and spin)

```<code>%First Circle
r1 = linspace(0,1,10);
theta1 = linspace(0, 2*pi, 100);
[rg, thg] = meshgrid(r1,theta1);
[x1,y1] = pol2cart(thg,rg);
circ1 = pcolor(x1,y1,thg);
colormap(jet);

ylim([-2 2]);
hold on

%Second Circle
r2 = linspace(0,1,10);
theta2 = linspace(0, 2*pi, 100);
[rg, thg] = meshgrid(r2,theta2);

[x2,y2] = pol2cart(thg,rg);
circ2 = pcolor(x2+2.5,y2,thg);
%colormap(jet);

%for ang=1:360
%  rotate(circ2,[0 1 1],-1);
% drawnow;
%end

%spinmap(5,1); %Spins colorjet map

view ([0 90]);
shading interp;
axis equal;
grid off;
hold off
</code>```

答:
Change your plotting to:

```<code>for ang=1:360
    cla; hold on
    circ1 = pcolor(x1,y1,thg);
    circ2 = pcolor(x2,y2,thg);
    rotate(circ2,[0 0 1],-ang);
    rotate(circ1,[0 0 1],-ang);
    set(circ1,'XData',get(circ1,'Xdata')+2.5); %change circ1 position
    view ([0 90]);
    shading interp;
    axis equal;
    grid off;
    hold off
    drawnow;
end
</code>```

The problem with rotate is that rotates the whole figure, so once one circle is rotating on place, if you apply rotate again the other one will rotate around the first one. To solve that, create both circles in the same place, rotate both, and then put one in a different position

ContentLicense: CC BY-SA 3.0

Body:
I've plotted two circles and filled them with the colormap 'jet'. However, every time I try to rotate the circles using rotate function or even the spin function of colormap to make the colour jet spin inside the circle - It changes the plot entirely - Rotating only 1 circle, filling up the screen, and rotating it at an angle.

Can someone please explain how I can rotate those 2 circles, as though they are wheels of a car?

The code is as follows: (I commented out my attempt at rotating and spin)

%First Circle
r1 = linspace(0,1,10);
theta1 = linspace(0, 2*pi, 100);
[rg, thg] = meshgrid(r1,theta1);
[x1,y1] = pol2cart(thg,rg);
circ1 = pcolor(x1,y1,thg);
colormap(jet);

ylim([-2 2]);
hold on

%Second Circle
r2 = linspace(0,1,10);
theta2 = linspace(0, 2*pi, 100);
[rg, thg] = meshgrid(r2,theta2);

[x2,y2] = pol2cart(thg,rg);
circ2 = pcolor(x2+2.5,y2,thg);
%colormap(jet);

%for ang=1:360
%  rotate(circ2,[0 1 1],-1);
% drawnow;
%end

%spinmap(5,1); %Spins colorjet map

view ([0 90]);
shading interp;
axis equal;
grid off;
hold off

Body:
Change your plotting to:

for ang=1:360
    cla; hold on
    circ1 = pcolor(x1,y1,thg);
    circ2 = pcolor(x2,y2,thg);
    rotate(circ2,[0 0 1],-ang);
    rotate(circ1,[0 0 1],-ang);
    set(circ1,'XData',get(circ1,'Xdata')+2.5); %change circ1 position
    view ([0 90]);
    shading interp;
    axis equal;
    grid off;
    hold off
    drawnow;
end

The problem with rotate is that rotates the whole figure, so once one circle is rotating on place, if you apply rotate again the other one will rotate around the first one. To solve that, create both circles in the same place, rotate both, and then put one in a different position


问:
tkinter output returns strings as a dict
```<code>from tkinter import *
from tkinter.messagebox import showinfo

def output():

    yield 'The %s line' % ('first')
    yield '\n'
    yield 'The %s line' % ('second')

def reply():
    showinfo(title='Log size', message=(list(output())))

window = Tk()
button = Button(window, text='Get info', command=reply)
button.pack()
window.mainloop()
</code>```

which returns this.

How can I make the output looks better as:

The first line

The second line

I have tried to get message as list(i for i in output()), but the result is the same.

答:
You don't need a list! Just join generator's content as string:

```<code>def reply():
    showinfo(title='Log size', message=''.join(output()))
</code>```

And there's no dicts at all, let the curly braces not bother you. Try to print your list:

```<code>>>> list(output())
['The first line', '\n', 'The second line']
</code>```

So if you really loves lists, you can join your return list:

```<code>def reply():
    showinfo(title='Log size', message=(''.join(list(output()))))
</code>```

Another note, as you see that you can treat generators like list, but it's not completely true, try this:

```<code>def reply():
    gen = output()
    showinfo(title='Log size', message=''.join(gen))
    showinfo(title='Log size', message=''.join(gen))
</code>```

So as you see, it's some sort of temporary list, that lets you take off each item one at a time or all of them only once. So if you want to preserve information - list is a good idea!

More here.

Body:
from tkinter import *
from tkinter.messagebox import showinfo

def output():

    yield 'The %s line' % ('first')
    yield '\n'
    yield 'The %s line' % ('second')

def reply():
    showinfo(title='Log size', message=(list(output())))

window = Tk()
button = Button(window, text='Get info', command=reply)
button.pack()
window.mainloop()

which returns this.

How can I make the output looks better as:

The first line

The second line

I have tried to get message as list(i for i in output()), but the result is the same.

Body:
You don't need a list! Just join generator's content as string:

def reply():
    showinfo(title='Log size', message=''.join(output()))

And there's no dicts at all, let the curly braces not bother you. Try to print your list:

>>> list(output())
['The first line', '\n', 'The second line']

So if you really loves lists, you can join your return list:

def reply():
    showinfo(title='Log size', message=(''.join(list(output()))))

Another note, as you see that you can treat generators like list, but it's not completely true, try this:

def reply():
    gen = output()
    showinfo(title='Log size', message=''.join(gen))
    showinfo(title='Log size', message=''.join(gen))

So as you see, it's some sort of temporary list, that lets you take off each item one at a time or all of them only once. So if you want to preserve information - list is a good idea!

More here.


问:
IOS/Objective-C: call of another class(VC) method not working
I've searched and searched for the answer to this issue and the solutions i've found doesn't seem to work, so I guess i'm doing something wrong: i want to call this method

```<code>-(void)customFade:(UILabel *)theLabel withDelay:(float)delayAmount {

    [UIView animateWithDuration:0.5
                          delay:delayAmount
                          options:UIViewAnimationOptionCurveEaseInOut
                          animations:^{
                          [theLabel setAlpha:1.0f];
                          [theLabel setAlpha:0];
                          }completion:nil];
}
</code>```

from a VC called View Controller to another but it isn't being recognized despite the imports... here's what i'm trying on the desired VC:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    ViewController *ViewController = [[ViewController alloc] init];

    [ViewController customFade:_label withDelay:0.3];
}
</code>```

the warning says "no visible @interface for "ViewController" declares the selector alloc

Can someone help me out? I'm kind of new at this, thank you

答:
such an error usually happens when you have mistyped the name of the method, or that method doesn't belong to that class at all and doesn't exist in your class.

and ensure once your VC is subclass with UIViewController

@interface ViewController : UIViewController

change your instance object type  and check once

```<code>  ViewController *vc = [[ViewController alloc] init];

  [vc customFade:_label withDelay:0.3];
</code>```

and change the animation like

```<code>[UIView animateWithDuration:0.5
                      delay:delayAmount
                      options:UIViewAnimationOptionCurveEaseInOut
                      animations:^{
                      [theLabel setAlpha:1.0f];

                      }completion:{
                     [theLabel setAlpha:0];
       }];
</code>```

for more information you can get the reference from here

Body:
I've searched and searched for the answer to this issue and the solutions i've found doesn't seem to work, so I guess i'm doing something wrong: i want to call this method

-(void)customFade:(UILabel *)theLabel withDelay:(float)delayAmount {

    [UIView animateWithDuration:0.5
                          delay:delayAmount
                          options:UIViewAnimationOptionCurveEaseInOut
                          animations:^{
                          [theLabel setAlpha:1.0f];
                          [theLabel setAlpha:0];
                          }completion:nil];
}

from a VC called View Controller to another but it isn't being recognized despite the imports... here's what i'm trying on the desired VC:

- (void)viewDidLoad {
    [super viewDidLoad];
    ViewController *ViewController = [[ViewController alloc] init];

    [ViewController customFade:_label withDelay:0.3];
}

the warning says "no visible @interface for "ViewController" declares the selector alloc

Can someone help me out? I'm kind of new at this, thank you

Body:
such an error usually happens when you have mistyped the name of the method, or that method doesn't belong to that class at all and doesn't exist in your class.

and ensure once your VC is subclass with UIViewController

@interface ViewController : UIViewController

change your instance object type  and check once

  ViewController *vc = [[ViewController alloc] init];

  [vc customFade:_label withDelay:0.3];

and change the animation like

[UIView animateWithDuration:0.5
                      delay:delayAmount
                      options:UIViewAnimationOptionCurveEaseInOut
                      animations:^{
                      [theLabel setAlpha:1.0f];

                      }completion:{
                     [theLabel setAlpha:0];
       }];

for more information you can get the reference from here


问:
ERROR 1064 iYou have an error in your SQL syntax;
Hi I have an error when I am inserting data into my database:

1064 You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'User,hello,2017-03-30 10:42:43,0)' at line 3 SQL=INSERT INTO
  #__registentrys (name,type_entry,date_regist,published)
  VALUES (Super User,hello,2017-03-30 10:42:43,0)

My code:

```<code>$greating1=$this->item->greeting;
                $datetime = new Jdate('now + 1 hour'); //GTM hour Lisbon
                $this->item->menssage1 = $datetime;
                //session portection
                $user = JFactory::getUser();
                if($user->guest)
                {
                    $this->item->menssage2 = "You are not allowed to enter this site";
                }
                else
                {
                    $username = $user->name;
                    $this->item->menssage2 = $username;
                    $db1 = JFactory::getDbo();
                    $query1 = $db1->getQuery(true);

                    // Insert columns.
                    $columns = array('name', 'type_entry', 'date_regist', 'published');

                    // Insert values.
                    $values = array($username, $greating1, $datetime, 0);

                    // Build the query
                    $query1
                    ->insert($db1->quoteName('#__registentrys'))
                    ->columns($db1->quoteName($columns))
                    ->values(implode(',', $values));

                    $db1->setQuery($query1);
                    $db1->execute();
</code>```

Thanks in advance for your answers.

答:
The literal value mus be inside quote </p>

```<code> SQL=INSERT INTO `#__registentrys` (`name`,`type_entry`,`date_regist`,`published`)
 VALUES ( 'Super User', 'hello', '2017-03-30 10:42:43',0)
</code>```

<p>otherwise are assumed  as column name </p>

Body:
Hi I have an error when I am inserting data into my database:

1064 You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'User,hello,2017-03-30 10:42:43,0)' at line 3 SQL=INSERT INTO
  #__registentrys (name,type_entry,date_regist,published)
  VALUES (Super User,hello,2017-03-30 10:42:43,0)

My code:

$greating1=$this->item->greeting;
                $datetime = new Jdate('now + 1 hour'); //GTM hour Lisbon
                $this->item->menssage1 = $datetime;
                //session portection
                $user = JFactory::getUser();
                if($user->guest)
                {
                    $this->item->menssage2 = "You are not allowed to enter this site";
                }
                else
                {
                    $username = $user->name;
                    $this->item->menssage2 = $username;
                    $db1 = JFactory::getDbo();
                    $query1 = $db1->getQuery(true);

                    // Insert columns.
                    $columns = array('name', 'type_entry', 'date_regist', 'published');

                    // Insert values.
                    $values = array($username, $greating1, $datetime, 0);

                    // Build the query
                    $query1
                    ->insert($db1->quoteName('#__registentrys'))
                    ->columns($db1->quoteName($columns))
                    ->values(implode(',', $values));

                    $db1->setQuery($query1);
                    $db1->execute();

Thanks in advance for your answers.

Body:
The literal value mus be inside quote

 SQL=INSERT INTO `#__registentrys` (`name`,`type_entry`,`date_regist`,`published`)
 VALUES ( 'Super User', 'hello', '2017-03-30 10:42:43',0)

otherwise are assumed  as column name


问:
How to clone button between tabs C# Visual Studio 2015
Example

Hi! How can I clone a button on other tabs? I need the same button in many tabs, the same button with the same proprieties, same code, same events, same name, ect.

"Compress file" button is going to be the same in Tab1, Tab4, Tab6 and Tab8... is going to do the same thing in many tabs, therebefore I don't want to make a new button every time. I don't want to make 10000 buttons which do the same thing.

I need to clone many buttons, not just "compress file", that's why I can't just put "Compress file" outside the TabControl and make it invisible or visible.

I'm working on Visual Studio 2015 with C#.

答:
Create a generic function, feel free to add more parameters to make it more flexible:

```<code>void CreateButton(TabControl tc, string text, EventHandler click)
{
    Button button = new Button();
    button.Width = 100;
    button.Height = 100;
    button.ForeColor = Color.Blue;
    button.Text = text;

    button.Click += click;

    tc.Controls.Add(button);
}
</code>```

Usage:

```<code>CreateButton(Tab1, "Compress file", Button_Click);
</code>```

Body:
Create a generic function, feel free to add more parameters to make it more flexible:

void CreateButton(TabControl tc, string text, EventHandler click)
{
    Button button = new Button();
    button.Width = 100;
    button.Height = 100;
    button.ForeColor = Color.Blue;
    button.Text = text;

    button.Click += click;

    tc.Controls.Add(button);
}

Usage:

CreateButton(Tab1, "Compress file", Button_Click);


问:
How can I paste a bitmap of an Excel chart using VSTO and C#
I'm creating a GUI application using WPF and i have to display a picture of a chart generated in Excel in the GUI.

I Generate the chart in Excel using code similar to this, which works fine:

```<code>        ChartObjects charts = ActiveWorkbook.Sheets[1].ChartObjects(Type.Missing);
        ChartObject chartObject = charts.Add(0, 0, 400,400);
        Chart chart = chartObject.Chart;

        // Set chart object properties
        chart.ChartType = XlChartType.XlChartType.xl3DBarClustered;
        SeriesCollection seriesCollection = (SeriesCollection)chart.SeriesCollection();

        var series = seriesCollection.NewSeries();
        series.Values = new int[] { 1, 2, 3, 4, 5 };
        series.XValues = new int[] { 100, 200, 300, 400, 500 };
        series.Name = "MySeries";
        ChartArea chartArea = chart.ChartArea;
</code>```

The result end up looking like this

I then copy the image to the clipboard using this code:

```<code>    ChartArea chartArea = chart.ChartArea;
    chartArea.Copy();
</code>```

And paste it to my GUI using:

```<code>    BitmapSource bitmap = Clipboard.GetImage();
</code>```

However, the result does not contain the axes, the chart title or the series name.

The result looks like this:

I've tried pasting the content of my clipboard into paint after running the method, and that results in a picture like the one i want, with axes and all. I suppose that means the problem occurs on the last line that returns the image from the clipboard.

Does anyone know how i can solve this?

答: There appears to be a bug in Clipboard.GetImage(), as explained and solved in the following article: http://www.thomaslevesque.com/2009/02/05/wpf-paste-an-image-from-the-clipboard/</p>

Body:
I'm creating a GUI application using WPF and i have to display a picture of a chart generated in Excel in the GUI.

I Generate the chart in Excel using code similar to this, which works fine:

        ChartObjects charts = ActiveWorkbook.Sheets[1].ChartObjects(Type.Missing);
        ChartObject chartObject = charts.Add(0, 0, 400,400);
        Chart chart = chartObject.Chart;

        // Set chart object properties
        chart.ChartType = XlChartType.XlChartType.xl3DBarClustered;
        SeriesCollection seriesCollection = (SeriesCollection)chart.SeriesCollection();

        var series = seriesCollection.NewSeries();
        series.Values = new int[] { 1, 2, 3, 4, 5 };
        series.XValues = new int[] { 100, 200, 300, 400, 500 };
        series.Name = "MySeries";
        ChartArea chartArea = chart.ChartArea;

The result end up looking like this

I then copy the image to the clipboard using this code:

    ChartArea chartArea = chart.ChartArea;
    chartArea.Copy();

And paste it to my GUI using:

    BitmapSource bitmap = Clipboard.GetImage();

However, the result does not contain the axes, the chart title or the series name.

The result looks like this:

I've tried pasting the content of my clipboard into paint after running the method, and that results in a picture like the one i want, with axes and all. I suppose that means the problem occurs on the last line that returns the image from the clipboard.

Does anyone know how i can solve this?


问:
Debugging application when launched via ShellExecute
I am trying to launch an application via the ShellExecute() API call. This application contains only a main function which does some processing and exits.

Now I have put DebugBreak() in starting of main. When ShellExecute() is called the application is launched successfully but it does not ask for breaking.

How can I debug my application when launched from other application using ShellExecute()?

I am using VC++ .

答:
If DebugBreak() isn't workign for you, try _CrtDbgBreak(). Note that _CrtDbgBreak only works in a debug build.

_CrtDebugBreak definitely works for me to make a launched process break on startup, although I'm pretty sure DebugBreak does also.

Note that both functions will make it look like the process has crashed, since they raise an exception. That is normal and gives you the opportunity to attach a debugger via the crash dialog. (The crash dialog also lets you terminate the process; don't use that, obviously.)

Also note that if you have a catch-all SEH exception handler around your main then the exception raise by DebugBreak & friends will be swallowed up and the app will simply exit without showing the crash dialog or letting you attach to it.


问:
why is my express API not responding?

Background

I am testing a simple Hello World app using NodeJs v7 and express in cloud9.
I am trying to make my example work but I am failing.

Problem

All my cloud9 configurations are fine so that is not the problem. The problem is my app. When i debug, the route "api/v1/HolaBananas" never gets called and I don't know why!

Even worst, when i make the request, the browser just hangs, like it is waiting for an answer from the server that will never come!

Code

The index.js has the initialization and launch code. It is important for me that I keep this separate from api.js for modular reasons.

index.js

```<code>"use strict";

const express = require("express");

const app = express();
app.use("/api/v1", require("./api.js"));

app.listen(process.env.PORT);
console.log(`Server listening on port ${process.env.PORT}!`);
</code>```

The api.js simply contains the routes and what they are supposed to do.

api.js

```<code>"use strict";

const express = require("express");

module.exports = function() {

    const api = express.Router();

    api.get("/HolaBananas", function(req, res){
        res.send("hello bananas!");
    });

    return api;
};
</code>```

Question

I am sure I am not using api.get in the right way, but I truly want to separate my initialization and launch code from the api.

How can I fix my code so it works?

Note

I am following the course

https://www.edx.org/course/introduction-mongodb-using-mean-stack-mongodbx-m101x-0

答:
You can fix it by two following  ways

```<code>var api = require("./api.js")();
app.use("/api/v1", require("./api.js"));
</code>```

as API.js return a function reference. so you need to call that function to access route.

Or You need to modify your api.js as follows if you don't want to change  index.js

```<code>"use strict";

const express = require("express");
const api = express.Router();

    api.get("/HolaBananas", function(req, res){
        res.send("hello bananas!");
    });
module.exports = api;
</code>```

Title: why is my express API not responding?

Body:
Background

I am testing a simple Hello World app using NodeJs v7 and express in cloud9.
I am trying to make my example work but I am failing.

Problem

All my cloud9 configurations are fine so that is not the problem. The problem is my app. When i debug, the route "api/v1/HolaBananas" never gets called and I don't know why!

Even worst, when i make the request, the browser just hangs, like it is waiting for an answer from the server that will never come!

Code

The index.js has the initialization and launch code. It is important for me that I keep this separate from api.js for modular reasons.

index.js

"use strict";

const express = require("express");

const app = express();
app.use("/api/v1", require("./api.js"));

app.listen(process.env.PORT);
console.log(`Server listening on port ${process.env.PORT}!`);

The api.js simply contains the routes and what they are supposed to do.

api.js

"use strict";

const express = require("express");

module.exports = function() {

    const api = express.Router();

    api.get("/HolaBananas", function(req, res){
        res.send("hello bananas!");
    });

    return api;
};

Question

I am sure I am not using api.get in the right way, but I truly want to separate my initialization and launch code from the api.

How can I fix my code so it works?

Note

I am following the course

https://www.edx.org/course/introduction-mongodb-using-mean-stack-mongodbx-m101x-0

Body:
You can fix it by two following  ways

var api = require("./api.js")();
app.use("/api/v1", require("./api.js"));

as API.js return a function reference. so you need to call that function to access route.

Or You need to modify your api.js as follows if you don't want to change  index.js

"use strict";

const express = require("express");
const api = express.Router();

    api.get("/HolaBananas", function(req, res){
        res.send("hello bananas!");
    });
module.exports = api;


问:
Parsing array of objects using jackson spring
I have the following request

```<code>{
  "name":"Ajeesh",
  "description":"hello",
  "platform_settings":[
      {"key":"value"},
      {"key1":"key2"}..  // This key value can be anything upto n times
  ]
}
</code>```

I have created a POJO for the above as follows

```<code>package com.payunow.socialsharemodule.models;

import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
import java.util.List;
import java.util.Map;

public class Share {
    private String name;
    private String description;

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString(){
        return getName() + ", "+getDescription();
    }
}
</code>```

How will I define platform_settings array of objects when converting the JSON to Java objects?

答:
You could declare platform_settings as a list of maps:</p>

```<code> public class Share {
    private String name;
    private String description;
    private List<Map<String, String>> platform_settings;

    ...
}
</code>```

Body:
I have the following request

{
  "name":"Ajeesh",
  "description":"hello",
  "platform_settings":[
      {"key":"value"},
      {"key1":"key2"}..  // This key value can be anything upto n times
  ]
}

I have created a POJO for the above as follows

package com.payunow.socialsharemodule.models;

import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
import java.util.List;
import java.util.Map;

public class Share {
    private String name;
    private String description;

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString(){
        return getName() + ", "+getDescription();
    }
}

How will I define platform_settings array of objects when converting the JSON to Java objects?

Body:
You could declare platform_settings as a list of maps:

 public class Share {
    private String name;
    private String description;
    private List<Map<String, String>> platform_settings;

    ...
}


问:
which button should be shown
Suppose we have a lot of buttons with specified texts & locations.

For example our buttons are {'main','report', 'memory', 'bills',...},
now we have an array that determine which button should be visible.

For example z1=['report', 'bills'], the contents of this array can be the other buttons. In your oponions, how can i write the code? Should i compare the text of every button with "z1" array, before defining every button? This is not reasonable, because the numbers of buttons are a lot.

This is my sample code:

```<code>    z1=['report','bills','setting']

    self.button = Button(self.master,text="memory", command=self.ouvrir)
    self.button.grid(row=1, column=1)

    self.button2 = Button(self.master,text="report", command=self.tabluh)
    self.button2.grid(row=1, column=2)

    self.button3 = Button(self.master,text="setting", command=self.new_window)
    self.button3.grid(row=1, column=3)

    self.button4 = Button(self.master,text="calibration", command=self.cal)
    self.button4.grid(row=1, column=4)

    self.button5 = Button(self.master,text="empty weight", command=self.weighing)
    self.button5.grid(row=1, column=5)

    self.button6 = Button(self.master,text="bills", command=self.history)
    self.button6.grid(row=1, column=6)

    self.button7 = Button(self.master,text="full weight", command=self.full)
    self.button7.grid(row=1, column=7)
</code>```

答:
One way to do this is by storing your commands in a dictionary as values and the text as the keys. If you give the GUI a list containing the keys you want to see, he will select the right keys from this. Next, you dynamically create the buttons.

Kind regards, S

```<code>from tkinter import *

class Window:
    def __init__(self, root,a):
        self.root = root
        action = self.find_command(a)

        for y,element in enumerate(action):
            self.Make_Button(1,y, element[0], element[1])

    def find_command(self, list_):
        d = {"test": self.printX, "value" : self.printY, "practice" : self.printZ}
        action = []
        for element in list_:
            for key, value in d.items():
                if key == element:
                    action.append([key, value])
        return(action)

    def Make_Button(self, x, y, text_, command_):
        self.StopButton = Button(self.root, text = text_, command =  command_)
        self.StopButton.grid(row = x, column = y, columnspan = 1, pady=(2,1))

    def printX(self):
        print("testX")

    def printY(self):
        print("testY")

    def printZ(self):
        print("testZ")

a = ["test", "practice"]

root = Tk()
Window = Window(root,a)
Window.root.mainloop()
</code>```

Title: which button should be shown

Body:
Suppose we have a lot of buttons with specified texts & locations.

For example our buttons are {'main','report', 'memory', 'bills',...},
now we have an array that determine which button should be visible.

For example z1=['report', 'bills'], the contents of this array can be the other buttons. In your oponions, how can i write the code? Should i compare the text of every button with "z1" array, before defining every button? This is not reasonable, because the numbers of buttons are a lot.

This is my sample code:

    z1=['report','bills','setting']

    self.button = Button(self.master,text="memory", command=self.ouvrir)
    self.button.grid(row=1, column=1)

    self.button2 = Button(self.master,text="report", command=self.tabluh)
    self.button2.grid(row=1, column=2)

    self.button3 = Button(self.master,text="setting", command=self.new_window)
    self.button3.grid(row=1, column=3)

    self.button4 = Button(self.master,text="calibration", command=self.cal)
    self.button4.grid(row=1, column=4)

    self.button5 = Button(self.master,text="empty weight", command=self.weighing)
    self.button5.grid(row=1, column=5)

    self.button6 = Button(self.master,text="bills", command=self.history)
    self.button6.grid(row=1, column=6)

    self.button7 = Button(self.master,text="full weight", command=self.full)
    self.button7.grid(row=1, column=7)

Body:
One way to do this is by storing your commands in a dictionary as values and the text as the keys. If you give the GUI a list containing the keys you want to see, he will select the right keys from this. Next, you dynamically create the buttons.

Kind regards, S

from tkinter import *

class Window:
    def __init__(self, root,a):
        self.root = root
        action = self.find_command(a)

        for y,element in enumerate(action):
            self.Make_Button(1,y, element[0], element[1])

    def find_command(self, list_):
        d = {"test": self.printX, "value" : self.printY, "practice" : self.printZ}
        action = []
        for element in list_:
            for key, value in d.items():
                if key == element:
                    action.append([key, value])
        return(action)

    def Make_Button(self, x, y, text_, command_):
        self.StopButton = Button(self.root, text = text_, command =  command_)
        self.StopButton.grid(row = x, column = y, columnspan = 1, pady=(2,1))

    def printX(self):
        print("testX")

    def printY(self):
        print("testY")

    def printZ(self):
        print("testZ")

a = ["test", "practice"]

root = Tk()
Window = Window(root,a)
Window.root.mainloop()


问:
Intersect doesn't work between Lists
I have a little strange problem.
 I use Visual Studio and I am developing a project with C#.

I have two custom classes "Attr" and "FD" and I use lists that includes their objects e.g.

```<code>List<Attr> attrList = new List<Attr>();
List<FD> fdList = new List<FD>();
</code>```

So when I try to find the intersection of two lists the result is not what I expect. To make it more simple I tried to Intersect similar Objects and the result is wrong again. What is going wrong?

This is the fd. It is an object of class FD.

This is the ff which is also an object of FD class.

As you can see these object contains exactly the same values.

The method GetLeft() returns a list that contains objects of class Attr.

So when I try to find the intersection between those two lists (fd.GetLeft() and ff.GetLeft() ) the result is nothing (it should be a list that contains an Attr object "A").

What did I miss?

P.S. These screenshots are from the debugg mode in Visual Studio.

答:
In order to use Intersect I suggest implementing IEqualityComparer<T>, something like this :

```<code>public class FD
{
    public string Name { get; set; }
}

 static void Main()
    {
        List<FD> fdList1 = new List<FD>();
        fdList1.Add(new FD { Name = "a" });

        List<FD> fdList2 = new List<FD>();
        fdList2.Add(new FD { Name = "a" });

       IEnumerable<FD> fd = fdList1.Intersect<FD>(fdList2, new ComparerFd()).ToList();
    }
</code>```

And the CamparerFd should be like this :

```<code>public class ComparerFd : IEqualityComparer<FD>
{

    public bool Equals(FD x, FD y)
    {
        return x.Name == y.Name;
    }

    public int GetHashCode(FD obj)
    {
        if(obj == null) return 0;

        return obj.Name.GetHashCode();//Or whatever way to get hash code
    }
}
</code>```

Title: Intersect doesn't work between Lists

Body:
I have a little strange problem.
 I use Visual Studio and I am developing a project with C#.

I have two custom classes "Attr" and "FD" and I use lists that includes their objects e.g.

List<Attr> attrList = new List<Attr>();
List<FD> fdList = new List<FD>();

So when I try to find the intersection of two lists the result is not what I expect. To make it more simple I tried to Intersect similar Objects and the result is wrong again. What is going wrong?

This is the fd. It is an object of class FD.

This is the ff which is also an object of FD class.

As you can see these object contains exactly the same values.

The method GetLeft() returns a list that contains objects of class Attr.

So when I try to find the intersection between those two lists (fd.GetLeft() and ff.GetLeft() ) the result is nothing (it should be a list that contains an Attr object "A").

What did I miss?

P.S. These screenshots are from the debugg mode in Visual Studio.

Body:
In order to use Intersect I suggest implementing IEqualityComparer<T>, something like this :

public class FD
{
    public string Name { get; set; }
}

 static void Main()
    {
        List<FD> fdList1 = new List<FD>();
        fdList1.Add(new FD { Name = "a" });

        List<FD> fdList2 = new List<FD>();
        fdList2.Add(new FD { Name = "a" });

       IEnumerable<FD> fd = fdList1.Intersect<FD>(fdList2, new ComparerFd()).ToList();
    }

And the CamparerFd should be like this :

public class ComparerFd : IEqualityComparer<FD>
{

    public bool Equals(FD x, FD y)
    {
        return x.Name == y.Name;
    }

    public int GetHashCode(FD obj)
    {
        if(obj == null) return 0;

        return obj.Name.GetHashCode();//Or whatever way to get hash code
    }
}

ContentLicense: CC BY-SA 4.0


问:
How do I install ionicons in my Ionic 2 project
When I try to do  (for example)

```<code><ion-icon name="university"></ion-icon>
</code>```

I see that the icon doesn't appear, though its been listed at the http://ionicons.com/. I think may be the icons with my project are not updated one, so I thought to download the package from the site and install.

After unzipping I have no idea about how to do it. I tried the suggestion in the forum, but there it was suggested to go to 'lib' folder in 'www' directory. But, in my project I don't see any 'lib' directory. I tried with the instructions at the repo site , but its again confusing in my case (I think).

答:
I faced the same issue today.
I realized some Ionic 2 Icons have been renamed.
For example, in your case :

```<code><ion-icon name="university"></ion-icon>
</code>```

Becomes:

```<code><ion-icon name="school"></ion-icon>
</code>```

I would advise anyone else facing the same issue to carefully look through the new Ionic 2 icons.

Body:
When I try to do  (for example)

<ion-icon name="university"></ion-icon>

I see that the icon doesn't appear, though its been listed at the http://ionicons.com/. I think may be the icons with my project are not updated one, so I thought to download the package from the site and install.

After unzipping I have no idea about how to do it. I tried the suggestion in the forum, but there it was suggested to go to 'lib' folder in 'www' directory. But, in my project I don't see any 'lib' directory. I tried with the instructions at the repo site , but its again confusing in my case (I think).

Body:
I faced the same issue today.
I realized some Ionic 2 Icons have been renamed.
For example, in your case :

<ion-icon name="university"></ion-icon>

Becomes:

<ion-icon name="school"></ion-icon>

I would advise anyone else facing the same issue to carefully look through the new Ionic 2 icons.


问:
CQRS + ES: Can you process multiple commands in parallel?
I can see how commands can be executed in a strict one at a time sequence with the CQRS + ES pattern. Having multiple commands executing in parallel would significantly increase the throughput of the system and make use of all the cores I have on the server. But surely this risks concurrency issues?

Take a simple example, two users update the customers name and submit the commands at the same time. In parallel two processes replay previous events to get aggregates into the latest state and then both determine everything is valid. Both then save a new update event. Whichever one saves last would seem to be the winner because any future replay would result in that last update being the customers name.

What if the result of the command is to send an email to the customer. Now we send two emails instead of the expected one. What if the command results in creating a new aggregate that gets attached to the customer using a customer property, we end up with two new aggregates created but one is a zombie because it is never referenced by the customer because the other aggregate has been saved as the reference instead.

It feels like you would need to implement your own transaction locking capability to ensure you never get overwrites and that is a complex solution I would rather avoid!

UPDATE:

My example was a little too simple. Imagine we have an Invoice and Item entries that go into an Invoice. After adding/changing/removing an Item from the Invoice we need to find the new total and set it into the Invoice.Total property field.

If in parallel two users both add a new Item then the total would be wrong with no explicit locking mechanism. Both recreate the Invoice aggregate and the existing list of Item child aggregates for that Invoice. In parallel both create a new Item and then add up the new total and set it to the Invoice.Total property.

Both then save events for these actions. But now we have an error because whichever command finished last will have a total that does not include the new item from the instance that finished first. This has nothing to do with pessimistic/optimistic concurrency but with transactional locking.

答:
I can see how commands can be executed in a strict one at a time
  sequence with the CQRS + ES pattern. Having multiple commands
  executing in parallel would significantly increase the throughput of
  the system and make use of all the cores I have on the server. But
  surely this risks concurrency issues?

From the CQRS+ES point of view there is not concurrency issue. Any good Event store implementation has a Aggregate version constraint that guards against concurrent event addition on the same Aggregate, using optimistic locking for example.

UPDATE: CQRS+ES loves and welcomes concurrent commands.

What if the result of the command is to send an email to the customer.
  Now we send two emails instead of the expected one.

Expected by whom? Again, this is not a CQRS+ES problem. This is business design issue. In this particular case you should have designed another bounded context Aggregate that deals with sending emails to client, having a business invariant that ensures that multiple emails regarding some topic (i.e. username change) are grouped into a single one, the last one having higher priority.

What if the command results in creating a new aggregate that gets
  attached to the customer using a customer property, we end up with two
  new aggregates created but one is a zombie because it is never
  referenced by the customer because the other aggregate has been saved
  as the reference instead.

Again, it depends on your business. From the CQRS+ES point of view there is no problem. Event stores are great at dealing with a lot of data (and this is because an event store is an append only persistence). That zombie aggregate is harmless. It occupies only some events in the event store. In the projections (read models) there is no pain as it is not present.

It feels like you would need to implement your own transaction locking
  capability to ensure you never get overwrites and that is a complex
  solution I would rather avoid!

This is a problem that you would have regardless of using CQRS+ES. If this is a business requirement you have to do it anyway.

In the case of two users changing the username at the same time you could do some additional checks and inform the loosing user that other user has modified the username, possibly even showing what username and letting him to decide what to do next: retry or cancel.

AFTER UPDATE:

My example was a little too simple. Imagine we have an Invoice and
  Item entries that go into an Invoice. After adding/changing/removing
  an Item from the Invoice we need to find the new total and set it into
  the Invoice.Total property field.

If in parallel two users both add a new Item then the total would be
  wrong with no explicit locking mechanism. Both recreate the Invoice
  aggregate and the existing list of Item child aggregates for that
  Invoice. In parallel both create a new Item and then add up the new
  total and set it to the Invoice.Total property.

Both then save events for these actions. But now we have an error
  because whichever command finished last will have a total that does
  not include the new item from the instance that finished first. This
  has nothing to do with pessimistic/optimistic concurrency but with
  transactional locking

I think that you must understand how Event sourcing works:
Let's suppose that both users have in front of them the Invoice (in fact it is the Cart that they see, not the Invoice; the Invoice is generated after an Order is placed, but for the sake of simplicity let's assume that). Let's suppose they see 2 items and every one of them wants to add a new item. both of them initiate a command: AddAnItemToInvoiceCommand. This is what happens:

the command dispatcher/handler receive the commands at the same time.

for each of the commands, it loads the aggregate from the repository, storing the aggregate version, let's suppose that is 10.

for each command, the handler calls a method on the aggregate that adds an invoice then it receives the ItemWasAddedToInvoiceEvent twice, one for every command handler execution.

for each command, the handler tries to persist the event to the Event store

for the first event persisting action (it always it is a first at a nanosecond level) the event is persisted and the aggregate version is incremented; now it is 11;

for the second identical event, generated by the second command handler, the event is not persisted because the expected version 10 is not found, as now it is 11. So, the repository retries the commnand execution (This is very important to understand). That is, the all command execution is called again: the aggregate is loaded again from the repository, now at version 11, then the command is applied on it then the event is persisted to the Event store.

So, two events are added to the event store, so the Invoice has the correct state: now there are 4 items with a correct total price being the sum of all 4.


问:
AngularJS: Access promise callback outside a async method
```<code>function graphreport(agentList) {

    var b;
    var self = this;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        b = data.data.users.length;
    });

    console.log(b);
}
</code>```

First console.log will return the value. Second console log will return undefined. How do get the variable outside a method? BTW, I'm resolving a promise in the method.

答:
You could achieve this by using promises or a callback. But you will not be able to make it like you tried to in just one linear procedure. Get aware of async JavaScript bevhaviors. Here is an example fiddle.

With promises

```<code>function graphreport(agentList) {

    var b;
    var self = this;
    var deferred = $q.defer();
    var promise = deferred.promise;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        b = data.data.users.length;
        deferred.resolve(data.data.users.length);
    });

    promise.then(function (b) {
        console.log(b);
    });
}
</code>```

With callback function

```<code>function graphreport(agentList) {

    var self = this;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        myCallack(data.data.users.length);
    });

    function myCallack(b) {
      console.log(b);
    }
}
</code>```

With co & yield like in this demo fiddle.

```<code>var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($timeout, $q) {

   co(function *() {
     var deferred = $q.defer();
     var promise = deferred.promise;

     function someAsync() {
        $timeout(function () {
              deferred.resolve('test');
        }, 250);
     }

     someAsync();
     var b = yield promise;
     console.log(b);
   });
});
</code>```

Body:
function graphreport(agentList) {

    var b;
    var self = this;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        b = data.data.users.length;
    });

    console.log(b);
}

First console.log will return the value. Second console log will return undefined. How do get the variable outside a method? BTW, I'm resolving a promise in the method.

Body:
You could achieve this by using promises or a callback. But you will not be able to make it like you tried to in just one linear procedure. Get aware of async JavaScript bevhaviors. Here is an example fiddle.

With promises

function graphreport(agentList) {

    var b;
    var self = this;
    var deferred = $q.defer();
    var promise = deferred.promise;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        b = data.data.users.length;
        deferred.resolve(data.data.users.length);
    });

    promise.then(function (b) {
        console.log(b);
    });
}

With callback function

function graphreport(agentList) {

    var self = this;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        myCallack(data.data.users.length);
    });

    function myCallack(b) {
      console.log(b);
    }
}

With co & yield like in this demo fiddle.

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($timeout, $q) {

   co(function *() {
     var deferred = $q.defer();
     var promise = deferred.promise;

     function someAsync() {
        $timeout(function () {
              deferred.resolve('test');
        }, 250);
     }

     someAsync();
     var b = yield promise;
     console.log(b);
   });
});


问:
Issue using While+if statements together in Python
Can someone please check below code, as i am using while and If statement together in python and calling one more python code, but it is executing all the code except calling the other python code.</p>

```<code>import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break;
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
         print("Next has started")
         subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")*
</code>```

答:
```<code>import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue

        if os.path.isfile("Z:\\xyz\\second.xlsx"):
            print("Next has started")
            subprocess.call([sys.executable,'Next Python.py'])
        else:
            print("Nothing")

        break
else:
    print("No Process")*
</code>```

<p>like my comment states it needs to look like this, everything ater the break statement inside the loop won't be executed. </p>

Body:
Can someone please check below code, as i am using while and If statement together in python and calling one more python code, but it is executing all the code except calling the other python code.

import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break;
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
         print("Next has started")
         subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")*

Body:
import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue

        if os.path.isfile("Z:\\xyz\\second.xlsx"):
            print("Next has started")
            subprocess.call([sys.executable,'Next Python.py'])
        else:
            print("Nothing")

        break
else:
    print("No Process")*

like my comment states it needs to look like this, everything ater the break statement inside the loop won't be executed.


问:
Css image position relative ignored in Safari
I have a gallery with images, structured like this (simplified):

```<code><div class="gallery">
  <figure class="gallery-item">
    <a class="gallery-item-link">
      <img />
    </a>
  </figure>
 <figure class="gallery-item">
    <a class="gallery-item-link">
      <img />
    </a>
  </figure>
</div>
</code>```

.gallery is a flex-container that should fit 3 items on bigger screens.

My problem is with centrally positioning of the images within .gallery-item-link.

The relevant piece of css is

```<code>.gallery-item-link img {
  display: block;
  max-width: 100%;
  position: relative;
  left: 50%;
  transform: translateY(-50%);
}
</code>```

The sizes and ratios of the images can be varying so I cannot rely on padding trick for aspect ratio.

In Chrome, this is what the gallery looks like:

In Safari, and this is the problem:

Here is the pen to illustrate the problem: http://codepen.io/afkatja/pen/EWEMNb

Am I forgetting / missing something?

EDIT: the problem seems to have something to do with align-items: stretch likely not working properly (or just ignored?) in Safari?

EDIT: I am using Safari 10.0.3

答:
I tried (among various other things) using display: table-cell; vertical-align: middle; for images which producesd unpredictable results and seemed so hacky.

I eventually solved the problem by using flexbox for image container:

```<code>  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
</code>```

I updated the pen here: http://codepen.io/afkatja/pen/EWEMNb

Tested in latest Chrome, Safari (both desktop and iOS), Firefox, MS Edge & IE11.

Body:
I have a gallery with images, structured like this (simplified):

.gallery is a flex-container that should fit 3 items on bigger screens.

My problem is with centrally positioning of the images within .gallery-item-link.

The relevant piece of css is

.gallery-item-link img {
  display: block;
  max-width: 100%;
  position: relative;
  left: 50%;
  transform: translateY(-50%);
}

The sizes and ratios of the images can be varying so I cannot rely on padding trick for aspect ratio.

In Chrome, this is what the gallery looks like:

In Safari, and this is the problem:

Here is the pen to illustrate the problem: http://codepen.io/afkatja/pen/EWEMNb

Am I forgetting / missing something?

EDIT: the problem seems to have something to do with align-items: stretch likely not working properly (or just ignored?) in Safari?

EDIT: I am using Safari 10.0.3

Body:
I tried (among various other things) using display: table-cell; vertical-align: middle; for images which producesd unpredictable results and seemed so hacky.

I eventually solved the problem by using flexbox for image container:

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

I updated the pen here: http://codepen.io/afkatja/pen/EWEMNb

Tested in latest Chrome, Safari (both desktop and iOS), Firefox, MS Edge & IE11.


问:
Ambiguous reference to member 'upload(_:_:headers:file:)'
The code below works perfectly in Swift 3 to upload an image file as multipart. However, I haven't been able to get anything similar to work in Swift 2.2. If I try to use this in Swift 2.2, I get the message Ambiguous reference to member 'upload(_:_:headers:file:)'

Is there a way to accomplish the same thing in Swift 2.2? I have found several related questions, but have only found solutions that work in Swift 3.

```<code>func submitFile(entryId: Int, entryDetailValue: String, fieldId: Int, fieldType: String) {

    let parameters = [
        "entryId": "\(entryId)",
        "entryDetail": entryDetailValue,
        "fieldId": "\(fieldId)",
        "type": fieldType
    ]

    print(parameters)

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(UIImageJPEGRepresentation(self.imageView.image!, 1)!, withName: "file", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
        }, to:"<my endpoint url>")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                //Print progress
                print(progress)
            })

            upload.responseData { response in
                print(response.result)
            }

        case .failure(let error):
            print(error)
        }
    }

}
</code>```

答:
In swift 3 try this </p>

```<code>func uploadImageWithParameter()
{
    let id = String(describing: userDefaults.value(forKey: USER_LOGIN_ID)!)

    var parameters = [String:String]()
    parameters = ["title":headingTextfield.text!,
                  "id":id,
                  "description":descriptionTextview.text,
                  "author":authorTextfield.text!,
                  "url": urlTextfield.text!]

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(UIImageJPEGRepresentation(self.capturedImage, 0.5)!, withName: "pic", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }

    }, to:"your url")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (Progress) in
                print("Upload Progress: \(Progress.fractionCompleted)")
            })

            upload.responseJSON { response in
                //self.delegate?.showSuccessAlert()
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization
                //                        self.showSuccesAlert()
                //self.removeImage("frame", fileExtension: "txt")
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
            }

        case .failure(let encodingError):
            //self.delegate?.showFailAlert()
            print(encodingError)
        }

    }
}
</code>```

Body:
The code below works perfectly in Swift 3 to upload an image file as multipart. However, I haven't been able to get anything similar to work in Swift 2.2. If I try to use this in Swift 2.2, I get the message Ambiguous reference to member 'upload(_:_:headers:file:)'

Is there a way to accomplish the same thing in Swift 2.2? I have found several related questions, but have only found solutions that work in Swift 3.

func submitFile(entryId: Int, entryDetailValue: String, fieldId: Int, fieldType: String) {

    let parameters = [
        "entryId": "\(entryId)",
        "entryDetail": entryDetailValue,
        "fieldId": "\(fieldId)",
        "type": fieldType
    ]

    print(parameters)

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(UIImageJPEGRepresentation(self.imageView.image!, 1)!, withName: "file", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
        }, to:"<my endpoint url>")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                //Print progress
                print(progress)
            })

            upload.responseData { response in
                print(response.result)
            }

        case .failure(let error):
            print(error)
        }
    }

}

Body:
In swift 3 try this

func uploadImageWithParameter()
{
    let id = String(describing: userDefaults.value(forKey: USER_LOGIN_ID)!)

    var parameters = [String:String]()
    parameters = ["title":headingTextfield.text!,
                  "id":id,
                  "description":descriptionTextview.text,
                  "author":authorTextfield.text!,
                  "url": urlTextfield.text!]

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(UIImageJPEGRepresentation(self.capturedImage, 0.5)!, withName: "pic", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }

    }, to:"your url")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (Progress) in
                print("Upload Progress: \(Progress.fractionCompleted)")
            })

            upload.responseJSON { response in
                //self.delegate?.showSuccessAlert()
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization
                //                        self.showSuccesAlert()
                //self.removeImage("frame", fileExtension: "txt")
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
            }

        case .failure(let encodingError):
            //self.delegate?.showFailAlert()
            print(encodingError)
        }

    }
}


问:
How to run Shell in background from controller and update database on execution in CakePHP
I am working on CakePHP 3.4 project.

I have to execute some command to scan through the files and directories of a particular directory.
This might take long time depending on the size of the directory, therefore I want to run it in background and mark running label in view until it executed successfully.

How can I run a Shell Task in the background from Controller and update database on execution?

I'm new to Shell tasks.

答:
Your thinking along good lines about running this in the background if it is a time consuming task. You will need to use some form of queuing system that allows you to add jobs to a queue that can then get run in the background by running the queue from a cronjob. Take a look at the Queue plugin for doing this.

You'll basically need to create a queue task that contains the functionality that you need running in the background and then add a job to the queue that will run that task in the background. The Queue plugin's documentation shows how to do this and there are a load of example queue tasks included with the plugin.

If you need to indicate the status of the queued job you could save the job's ID in a session and check if it is complete when loading a page.


问:
npm package simple-oauth2 404 not found
I have a weird bug going on with my code.

I'm using the simple-oauth2 library (https://github.com/lelylan/simple-oauth2) and my code works fine on Windows.

When I try to run my code on a linux server (raspberry pi zero), the oauth library keeps on returning 404 Not Found for my oauth request (specifically "Access Token Error Not Found" as per the code below).

What's going on?

Code (working with Yelp API):

```<code>var fs = require('fs');

var cID = fs.readFileSync('blahblahblah', 'utf8');
var cSecret = fs.readFileSync('blahblahblah2', 'utf8');

var credentials = {
    client: {
        id: cID,
        secret: cSecret
    },
    auth: {
        tokenHost: 'https://api.yelp.com',
        tokenPath: '/oauth2/token'
    }
};

var oauth2 = require('simple-oauth2').create(credentials);
var tokenConfig = {};

module.exports.gimmeMuhToken = function(cb) {
    oauth2.clientCredentials.getToken(tokenConfig, function(error, result) {
        if (error) {
            return console.log('Access Token Error', error.message);
        }
        cb(oauth2.accessToken.create(result).token.access_token); // Return the token
    });
};
</code>```

Thanks

答:
Found the culprit.

It was line endings...

Title: npm package simple-oauth2 404 not found

Body:
I have a weird bug going on with my code.

I'm using the simple-oauth2 library (https://github.com/lelylan/simple-oauth2) and my code works fine on Windows.

When I try to run my code on a linux server (raspberry pi zero), the oauth library keeps on returning 404 Not Found for my oauth request (specifically "Access Token Error Not Found" as per the code below).

What's going on?

Code (working with Yelp API):

var fs = require('fs');

var cID = fs.readFileSync('blahblahblah', 'utf8');
var cSecret = fs.readFileSync('blahblahblah2', 'utf8');

var credentials = {
    client: {
        id: cID,
        secret: cSecret
    },
    auth: {
        tokenHost: 'https://api.yelp.com',
        tokenPath: '/oauth2/token'
    }
};

var oauth2 = require('simple-oauth2').create(credentials);
var tokenConfig = {};

module.exports.gimmeMuhToken = function(cb) {
    oauth2.clientCredentials.getToken(tokenConfig, function(error, result) {
        if (error) {
            return console.log('Access Token Error', error.message);
        }
        cb(oauth2.accessToken.create(result).token.access_token); // Return the token
    });
};

Thanks


问:
HTML Send selected option to PHP via Ajax on same page
What I want to acheive:
I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.

The highscore section on the page

I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.

Here is the code on the home.php page (Where the highscore section is)

```<code><div class="third third-center">
            <h2>Highscores</h2>
            <div class="sortby">
                <form id="" method="post" action="home.php">
                    <select id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>
            </div>
            <div class="inner">
                <table>
                    <tr>
                        <th style="font-size: 20px">Position</th>
                        <th style="font-size: 20px">Name</th>
                        <th style="font-size: 20px">Score</th>
                    </tr>
                    <?php
                        $i = 0;

                        $choice = "score ASC";

                        $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                        while($row = mysqli_fetch_array($search)){
                            $i++;
                            echo "<tr>";
                            echo "<th>" . $i . "</th>";
                            echo "<th>" . $row['userName'] . "</th>";
                            echo "<th>" . $row['score'] . "</th>";
                            echo "</tr>";
                        }
                    ?>
                </table>
            </div>
        </div>
</code>```

I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.

I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.

Any help would be greatly appreciated!

答:
If you don't wish to have "live" high-scores that are reloaded from the database every time someone changes the sorting, you might be better off loading the scores into a JavaScript object and then (re)arranging them with JavaScript.

For this you'd need to have a div-element into which you recreate the data (+table structure, if needed) with something like innerHTML after you have sorted the array as you wish with sort. You run this with onChange event in the dropdown list, for example.

If you have a div, for example:

```<code><div id="targetdiv"></div>
</code>```

So your PHP-generated array could look something like:

```<code>var scores = [
  {
    "name" : "Adam",
    "score": "100"
  },
  {
    "name" : "Bert",
    "score": "150"
  },
  {
    "name" : "Cecilia",
    "score": "75"
  } ];
</code>```

And your sorting algorith could be something like:

```<code>scores.sort(function(a, b) {
 return parseFloat(a.scores) - parseFloat(b.scores);
});
</code>```

Then just save the result to a string variable in a for-loop or whatever you want and output it into that "targetdiv" div:

```<code>var intostring = "By SCORES!<br><br>"

for (var index = 0; index < scores.length; ++index) {
    intostring += scores[index]["name"] + ": " + scores[index]["score"] + "<br>";
}

document.getElementById('targetdiv').innerHTML = intostring;
</code>```

I made a JSFiddle example for you to better demonstrate the above code:

https://jsfiddle.net/docweird/oaqoysm6/

(Without the onChange and dropdown).

Body:
What I want to acheive:
I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.

The highscore section on the page

I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.

Here is the code on the home.php page (Where the highscore section is)

Highscores

                <form id="" method="post" action="home.php">
                    <select id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>

                        Position
                        Name
                        Score

                    <?php
                        $i = 0;

                        $choice = "score ASC";

                        $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                        while($row = mysqli_fetch_array($search)){
                            $i++;
                            echo "
";
                            echo "" . $i . "	";
                            echo "" . $row['userName'] . "	";
                            echo "" . $row['score'] . "	";
                            echo "
";
                        }
                    ?>

I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.

I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.

Any help would be greatly appreciated!

Body:
If you don't wish to have "live" high-scores that are reloaded from the database every time someone changes the sorting, you might be better off loading the scores into a JavaScript object and then (re)arranging them with JavaScript.

For this you'd need to have a div-element into which you recreate the data (+table structure, if needed) with something like innerHTML after you have sorted the array as you wish with sort. You run this with onChange event in the dropdown list, for example.

If you have a div, for example:

<div id="targetdiv"></div>

So your PHP-generated array could look something like:

var scores = [
  {
    "name" : "Adam",
    "score": "100"
  },
  {
    "name" : "Bert",
    "score": "150"
  },
  {
    "name" : "Cecilia",
    "score": "75"
  } ];

And your sorting algorith could be something like:

scores.sort(function(a, b) {
 return parseFloat(a.scores) - parseFloat(b.scores);
});

Then just save the result to a string variable in a for-loop or whatever you want and output it into that "targetdiv" div:

var intostring = "By SCORES!<br><br>"

for (var index = 0; index < scores.length; ++index) {
    intostring += scores[index]["name"] + ": " + scores[index]["score"] + "<br>";
}

document.getElementById('targetdiv').innerHTML = intostring;

I made a JSFiddle example for you to better demonstrate the above code:

https://jsfiddle.net/docweird/oaqoysm6/

(Without the onChange and dropdown).


问:
Geoserver and Geofence - using custom rules
I've checked all the options of the rule creation in GeoFence Embedded (integrated with GeoServer) and GeoFence Standalone web application. The available options for building data access rules seem to be limited to: username, user's role, service name, request name, workspace and layer. The additional option is to limit the access with the geographical area.

Is there a way, using GeoServer and GeoFence, to make rules more specific, as in the following examples:

1) restricting access to a group of features from a layer, which belong to the selected bigger layer (show only cities from a selected state)

2) using CQL expressions in GeoFence rules with system variables (showing only features from a layer which have in one attribute the username of the logged-in, using GeoFence authenticator, user)
?

答:
I have found partial answers and I will share :)

Cross-layer filtering:
http://docs.geoserver.org/stable/en/user/extensions/querylayer/index.html

Probably not possible without changes to original source code.


问:
Convert a submat from RGB to GRAY OpenCV
I'm working on an android program that should detect a face in a live video, and convert the facial region to gray-scale. I successfully manage to create a border around the detected facial region, and using the function shown below, i've managed to create a submat that shows the face on the top left of the main Mat. My plan is to convert this submat to gray-scale and then place it over the actual face, unless someone has a more efficient approach?

The code for the submat can be seen below. When i add the line:

```<code>Imgproc.cvtColor(mRgba2,mRgba2,Imgproc.COLOR_RGB2GRAY);
</code>```

There are no errors, but the stretched face on the topleft corner isn't shown. I figured this is because mRgba2 is now a different type, so i tried adding

```<code>Imgproc.cvtColor(mRgba2,mRgba2,Imgproc.COLOR_RGB2GRAY);
Imgproc.cvtColor(mRgba2,mRgba2,Imgproc.COLOR_GRAY2RGB);
</code>```

to convert mRgba2 back to RGB but this didn't work either.

```<code>public void processFrame(Mat face) {

    Mat mRgba2 = face.clone();
    Imgproc.resize(face, mRgba2, new Size (400, 200));
    Mat submat = mRgba.submat(0, 200, 0, 400);
    mRgba2.copyTo(submat);
}
</code>```

答:
Don't use in-place conversion

```<code>Imgproc.cvtColor(mRgba2,mRgba2,Imgproc.COLOR_RGB2GRAY);
</code>```

instead try to use a second variable:

```<code>Mat mGray;
Imgproc.cvtColor(mRgba2,mGray,Imgproc.COLOR_RGB2GRAY);
</code>```

But are you sure that RGB is the right type? Your variable is named Rgba, so maybe you'll need Imgproc.COLOR_RGBA2GRAY ?

Body:
I'm working on an android program that should detect a face in a live video, and convert the facial region to gray-scale. I successfully manage to create a border around the detected facial region, and using the function shown below, i've managed to create a submat that shows the face on the top left of the main Mat. My plan is to convert this submat to gray-scale and then place it over the actual face, unless someone has a more efficient approach?

The code for the submat can be seen below. When i add the line:

Imgproc.cvtColor(mRgba2,mRgba2,Imgproc.COLOR_RGB2GRAY);

There are no errors, but the stretched face on the topleft corner isn't shown. I figured this is because mRgba2 is now a different type, so i tried adding

Imgproc.cvtColor(mRgba2,mRgba2,Imgproc.COLOR_RGB2GRAY);
Imgproc.cvtColor(mRgba2,mRgba2,Imgproc.COLOR_GRAY2RGB);

to convert mRgba2 back to RGB but this didn't work either.

public void processFrame(Mat face) {

    Mat mRgba2 = face.clone();
    Imgproc.resize(face, mRgba2, new Size (400, 200));
    Mat submat = mRgba.submat(0, 200, 0, 400);
    mRgba2.copyTo(submat);
}

Body:
Don't use in-place conversion

Imgproc.cvtColor(mRgba2,mRgba2,Imgproc.COLOR_RGB2GRAY);

instead try to use a second variable:

Mat mGray;
Imgproc.cvtColor(mRgba2,mGray,Imgproc.COLOR_RGB2GRAY);

But are you sure that RGB is the right type? Your variable is named Rgba, so maybe you'll need Imgproc.COLOR_RGBA2GRAY ?


问:
Symfony setting a cookie in a listener
How do I set a cookie in a listener without interrupting other things and redirects?

I'm trying to set it on an InteractiveLoginEvent. I tried to set it like that:

```<code>$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar'));
$response->send();
</code>```

Cookie is set this way but after that I get blank page and it's not redirecting to the landing page after login. how do I solve this?

答: I use setcookie() when I need to deal with POST variables, which it seems to be not possible with RedirectResponse.</p>

Title: Symfony setting a cookie in a listener

Body:
How do I set a cookie in a listener without interrupting other things and redirects?

I'm trying to set it on an InteractiveLoginEvent. I tried to set it like that:

$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar'));
$response->send();

Cookie is set this way but after that I get blank page and it's not redirecting to the landing page after login. how do I solve this?


问:
How to line up the list style icon with the text
I am using a customer list style image for an LI and i am wanting to line up the text in the centre of the icon.

I have tried using margins and paddings to no avail.

Please see code below and screenshot

HTML:

```<code><ul class="homeList">
 <li>Over 1 million happy travellers</li>
 <li>Over 450 local pick-up points with return travel for your convenience</li
 <li>Great range of breaks across Britain, Europe & America</li>
 <li>Included excursion programmes</li>
 <li>Superb value assured</li>
</ul>
</code>```

CSS:

```<code>.homeList li {
    list-style-image: url(../images/bulleticon.png);
    line-height: 20px;
    padding: 0;
    margin: 0;
}
</code>```

And this is how it is looking currently

答:
Instead of list-style-img use background-image for the list item.

```<code>li {
  list-style: none;
  background: url(../images/bulleticon.png) left center;
  padding-left: 20px;
}
</code>```

And you can change easier the image position as you change the background-position property.

Body:
I am using a customer list style image for an LI and i am wanting to line up the text in the centre of the icon.

I have tried using margins and paddings to no avail.

Please see code below and screenshot

HTML:

Over 1 million happy travellers

Over 450 local pick-up points with return travel for your convenience</li

Great range of breaks across Britain, Europe & America

Included excursion programmes

Superb value assured

CSS:

.homeList li {
    list-style-image: url(../images/bulleticon.png);
    line-height: 20px;
    padding: 0;
    margin: 0;
}

And this is how it is looking currently

Body:
Instead of list-style-img use background-image for the list item.

li {
  list-style: none;
  background: url(../images/bulleticon.png) left center;
  padding-left: 20px;
}

And you can change easier the image position as you change the background-position property.


答:
Since, your var b only gets resolved after promise resolution, you have to retrieve it asynchronously. One of the ways is  you can use callback as shown below. So when promise is resolved b gets returned with your callback function.

function graphreport(agentList, callback) {
    var b;
    var self = this;
    agentList.getAgentsList()
            .then(function (data) {
                self.agents = data.data.users;
                console.log(data.data.users.length);
                b = data.data.users.length;
                //return the callback method
                return callback(null, b);
            });
}

graphreport(list, function(err, b){
  if(!err){
   console.log(b);
   }
});```

Title: AngularJS: Access promise callback outside a async method


问:
Mod rewriting using .htaccess friendly url
My url is http://example.com/product/Braided/table-fan

And i want to rewrite like this http://example.com/Braided/table-fan

where product is my php file.

Current rules:

```<code>Options +MultiViews +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^([0-9a-zA-Z]+)/([0-9a-zA-Z]+)/([0-9a-zA-Z]+)$ product/$1/$2/$3
RewriteRule ^([0-9a-zA-Z]+)/([0-9a-zA-Z]+)$ product.php?uname=$1&pid$2
</code>```

答:
Try and use this in your root .htaccess:

```<code>RewriteEngine On
RewriteRule ^$ product/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ product/$1
</code>```

This should remove product from your URL and leave you with: http://example.com/Braided/table-fan.

Make sure you clear your cache before testing this.

Body:
My url is http://example.com/product/Braided/table-fan

And i want to rewrite like this http://example.com/Braided/table-fan

where product is my php file.

Current rules:

Options +MultiViews +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^([0-9a-zA-Z]+)/([0-9a-zA-Z]+)/([0-9a-zA-Z]+)$ product/$1/$2/$3
RewriteRule ^([0-9a-zA-Z]+)/([0-9a-zA-Z]+)$ product.php?uname=$1&pid$2

Body:
Try and use this in your root .htaccess:

RewriteEngine On
RewriteRule ^$ product/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ product/$1

This should remove product from your URL and leave you with: http://example.com/Braided/table-fan.

Make sure you clear your cache before testing this.


问:
RSpec - How to properly use doubles and stub methods on helper objects?
An action of a Rails controller makes an instance of a helper class (say SomeService), which performs some work and returns a results, something along the lines of:

```<code>def create
  ...
  result = SomeService.new.process
  ...
end
</code>```

I want to stub what SomeService#process returns.

My question is - how do I do this?

The following works:

```<code>allow_any_instance_of(SomeService).to receive(:process).and_return('what I want')
</code>```

However, the rspec-mock documentation discourages the use of allow_any_instance_of for the reasons states here:

The rspec-mocks API is designed for individual object instances, but this feature operates on entire classes of objects. As a result there are some semantically confusing edge cases. For example in expect_any_instance_of(Widget).to receive(:name).twice it isn't clear whether each specific instance is expected to receive name twice, or if two receives total are expected. (It's the former.)

Using this feature is often a design smell. It may be that your test is trying to do too much or that the object under test is too complex.

It is the most complicated feature of rspec-mocks, and has historically received the most bug reports. (None of the core team actively use it, which doesn't help.)

I think the idea is to do something like this:

```<code>some_service = instance_double('SomeService')
allow(some_service).to receive(:process).and_return('what I want')
</code>```

However, how do I make the controller use the double and not make a new instance
of SomeService?

答:
I usually do something like this.</p>

```<code>let(:fake_service) { your double here or whatever }

before do
  allow(SomeService).to receive(:new).and_return(fake_service)
  # this might not be needed, depending on how you defined your `fake_service`
  allow(fake_service).to receive(:process).and_return(fake_results)
end
</code>```

Body:
An action of a Rails controller makes an instance of a helper class (say SomeService), which performs some work and returns a results, something along the lines of:

def create
  ...
  result = SomeService.new.process
  ...
end

I want to stub what SomeService#process returns.

My question is - how do I do this?

The following works:

allow_any_instance_of(SomeService).to receive(:process).and_return('what I want')

However, the rspec-mock documentation discourages the use of allow_any_instance_of for the reasons states here:

The rspec-mocks API is designed for individual object instances, but this feature operates on entire classes of objects. As a result there are some semantically confusing edge cases. For example in expect_any_instance_of(Widget).to receive(:name).twice it isn't clear whether each specific instance is expected to receive name twice, or if two receives total are expected. (It's the former.)

Using this feature is often a design smell. It may be that your test is trying to do too much or that the object under test is too complex.

It is the most complicated feature of rspec-mocks, and has historically received the most bug reports. (None of the core team actively use it, which doesn't help.)

I think the idea is to do something like this:

some_service = instance_double('SomeService')
allow(some_service).to receive(:process).and_return('what I want')

However, how do I make the controller use the double and not make a new instance
of SomeService?

Body:
I usually do something like this.

let(:fake_service) { your double here or whatever }

before do
  allow(SomeService).to receive(:new).and_return(fake_service)
  # this might not be needed, depending on how you defined your `fake_service`
  allow(fake_service).to receive(:process).and_return(fake_results)
end


问:
progress bar implementation using <pe:exporter > in primefaces
I would like to export data to Excel. Right now I am able to achieve this using <pe:exporter>. But when data is huge, it takes a lot of time to export to Excel. I would like to show a progress bar while exporting data to excel. How can I achieve this?

答:
Add this to your xhtml :</p>

```<code><p:ajaxStatus onstart="PF('statusDialog').show()" onsuccess="PF('statusDialog').hide()" />

<p:dialog widgetVar="statusDialog" modal="true" draggable="false" closable="false" resizable="false" showHeader="false">
    <p:graphicImage name="/images/ajaxloadingbar.gif" />
</p:dialog>
</code>```

Body:
Add this to your xhtml :

<p:ajaxStatus onstart="PF('statusDialog').show()" onsuccess="PF('statusDialog').hide()" />

<p:dialog widgetVar="statusDialog" modal="true" draggable="false" closable="false" resizable="false" showHeader="false">
    <p:graphicImage name="/images/ajaxloadingbar.gif" />
</p:dialog>