问:
Weird behaviour of multiprocessing and global file handle
Can somebody help me to understand the following code snippet ? I know that I must not use global variables using multiprocessing but I'm still suprised about the result I see.

I use a global file handle within the function executed remotely in a different worker process.

```<code>import multiprocessing
import os

fh = open("out.txt", "w")

def process(i):
    print("i={}  pid={}  id(fh)={}".format(i, os.getpid(), id(fh)))
    print(i, file=fh)

def main():
    p = multiprocessing.Pool(3)
    p.map(process, (1, 2, 3))
    p.terminate()
    fh.close()

main()
</code>```

The output is

```<code>i=1  pid=92045  id(fh)=4314964256
i=2  pid=92046  id(fh)=4314964256
i=3  pid=92047  id(fh)=4314964256
</code>```

So we see that there are three different process ids as expected.

What suprises me:

the unpickable file handle is available in the worker processes

the memory address computed by id is the same for all workers

the worker process can write to this file handle without throwing an exception

nevertheless the file is empty after programm execution.

答:
Found the answers myself:

the unpickable file handle is available in the worker processes: multiprocessing forks from the Python interpreter process and global variables thus are copied within memory (SO post multiprocessing global variable memory copying). Pickling of variables only happens for the function arguments when calling functions in sub interpreters.

the memory address computed by id is the same for all workers: the shown memory address is the address within the virtual address space thus relative. After forking the initial memory layout is the same. (SO post Fork - same memory addresses?)

the worker process can write to this file handle without throwing an exception: see answer 1 +
for the forked processes the underlying fileno of fh is the same.

nevertheless the file is empty after programm execution: the file is not empty if I call the flush method before returning from process. So the file buffer is not flushed when the process is killed by it's parent.

Remark:
My example should behave differently on Windows. multiprocessing on Windows has to start new Python interpreters because of the different process model / implementation.

Body:
Can somebody help me to understand the following code snippet ? I know that I must not use global variables using multiprocessing but I'm still suprised about the result I see.

I use a global file handle within the function executed remotely in a different worker process.

import multiprocessing
import os

fh = open("out.txt", "w")

def process(i):
    print("i={}  pid={}  id(fh)={}".format(i, os.getpid(), id(fh)))
    print(i, file=fh)

def main():
    p = multiprocessing.Pool(3)
    p.map(process, (1, 2, 3))
    p.terminate()
    fh.close()

main()

The output is

i=1  pid=92045  id(fh)=4314964256
i=2  pid=92046  id(fh)=4314964256
i=3  pid=92047  id(fh)=4314964256

So we see that there are three different process ids as expected.

What suprises me:

the unpickable file handle is available in the worker processes

the memory address computed by id is the same for all workers

the worker process can write to this file handle without throwing an exception

nevertheless the file is empty after programm execution.


来源: stackexchange

问:
JButton in Eclipse: "Button cannot be resolved or is not a field"
New to Java and this Page.
I am trying to perfom a certain action when a JButton is pressed. Following this tutorial (in German, sorry) http://www.java-tutorial.org/actionlistener.html, I used the JFrame Design feature and added content afterwards:

```<code>public class JFrame extends javax.swing.JFrame implements ActionListener
{

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                JFrame frame = new JFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public JFrame()
{

    this.setTitle("BMS Anpassen");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnFlush = new JButton("Flush!");
    btnFlush.setBounds(170, 209, 89, 23);
    contentPane.add(btnFlush);

    JSpinner spinner = new JSpinner();
    spinner.setToolTipText("Gib die Spannung ein!");
    spinner.setModel(new SpinnerNumberModel(new Float(3000), new Float(2700), new Float(4100), new Float(100)));
    spinner.setBounds(56, 49, 52, 20);
    contentPane.add(spinner);

    JLabel lblMv = new JLabel("mV");
    lblMv.setFont(new Font("Tahoma", Font.PLAIN, 13));
    lblMv.setBounds(113, 51, 24, 14);
    contentPane.add(lblMv);

    JButton btnSetParameters = new JButton("Set Parameters");
    btnSetParameters.setBounds(152, 175, 130, 23);
    contentPane.add(btnSetParameters);

    //Buttons dem Listener zuordnen
    btnFlush.addActionListener(this);
    btnSetParameters.addActionListener(this);

}

public void actionPerformed(ActionEvent ae){

    if(ae.getSource() == this.btnSetParameters){

    // Parameter in Config schreiben/Write parameters in Config
    FileWriter fw = new FileWriter("ConfigBMS.txt");
    BufferedWriter bw = new BufferedWriter(fw);

    bw.write("25000");
    bw.newLine();
    bw.write("42000");
    bw.newLine();
    bw.write("27000");
    bw.newLine();
    bw.write("41000");

    bw.close();
    }
    else
    {
    }
}

}
</code>```

It now gives me the errormessage "btnSetParameters cannot be resolved or is not a field". Reading through other posts on JButtons here didn't help me or I didn't understand it. I feel like the this in if(ae.getSource() == this.btnSetParameters){ is the problem, but I can't find a way to fix it.

Any push in the right direction is greatly appreciated and thank you in advance,

Oli

答:
you have an scope issue, btnSetParameters must be declared as a Frame member field

```<code>public class JFrame extends javax.swing.JFrame implements ActionListener {
    private JButton btnSetParameters;
</code>```

and no inside the constructor, use the constructor instead to initialize the button!

```<code>public JFrame() {
    ....
    btnSetParameters = new JButton("Set Parameters");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
New to Java and this Page.
I am trying to perfom a certain action when a JButton is pressed. Following this tutorial (in German, sorry) http://www.java-tutorial.org/actionlistener.html, I used the JFrame Design feature and added content afterwards:

public class JFrame extends javax.swing.JFrame implements ActionListener
{

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                JFrame frame = new JFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public JFrame()
{

    this.setTitle("BMS Anpassen");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnFlush = new JButton("Flush!");
    btnFlush.setBounds(170, 209, 89, 23);
    contentPane.add(btnFlush);

    JSpinner spinner = new JSpinner();
    spinner.setToolTipText("Gib die Spannung ein!");
    spinner.setModel(new SpinnerNumberModel(new Float(3000), new Float(2700), new Float(4100), new Float(100)));
    spinner.setBounds(56, 49, 52, 20);
    contentPane.add(spinner);

    JLabel lblMv = new JLabel("mV");
    lblMv.setFont(new Font("Tahoma", Font.PLAIN, 13));
    lblMv.setBounds(113, 51, 24, 14);
    contentPane.add(lblMv);

    JButton btnSetParameters = new JButton("Set Parameters");
    btnSetParameters.setBounds(152, 175, 130, 23);
    contentPane.add(btnSetParameters);

    //Buttons dem Listener zuordnen
    btnFlush.addActionListener(this);
    btnSetParameters.addActionListener(this);

}

public void actionPerformed(ActionEvent ae){

    if(ae.getSource() == this.btnSetParameters){

    // Parameter in Config schreiben/Write parameters in Config
    FileWriter fw = new FileWriter("ConfigBMS.txt");
    BufferedWriter bw = new BufferedWriter(fw);

    bw.write("25000");
    bw.newLine();
    bw.write("42000");
    bw.newLine();
    bw.write("27000");
    bw.newLine();
    bw.write("41000");

    bw.close();
    }
    else
    {
    }
}

}

It now gives me the errormessage "btnSetParameters cannot be resolved or is not a field". Reading through other posts on JButtons here didn't help me or I didn't understand it. I feel like the this in if(ae.getSource() == this.btnSetParameters){ is the problem, but I can't find a way to fix it.

Any push in the right direction is greatly appreciated and thank you in advance,

Oli

Body:
you have an scope issue, btnSetParameters must be declared as a Frame member field

public class JFrame extends javax.swing.JFrame implements ActionListener {
    private JButton btnSetParameters;

and no inside the constructor, use the constructor instead to initialize the button!

public JFrame() {
    ....
    btnSetParameters = new JButton("Set Parameters");
}


问:
Getting the link URL tapped in WKWebView
I want to get the url of a tapped link in WKWebView. The links are in a custom format that will trigger certain actions in the app. e.g. http://my-site/help#deeplink-intercom. I am using KVO like so:

```<code>override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
        view = webView
    }

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let newValue = change?[.newKey] {
            print("url changed: \(newValue)")
        }
        print("Did tap!!")
    }
</code>```

This works great when the link is tapped on the first time. However if I tap the same link twice in a row it won't report the link tap (obviously because the actual value hasn't changed). Is there a workaround to fix this so I can detect every tap and get the link? Any pointer on this would be great! Thanks!

答:
Change addObserver like this

```<code>webView.addObserver(self, forKeyPath: "URL", options: [.new, .old], context: nil)
</code>```

In observeValue function you able get both value

```<code>override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let newValue = change?[.newKey] as? Int, let oldValue = change?[.oldKey] as? Int, newValue != oldValue {
        //Value Changed
        print(change?[.newKey])
    }else{
        //Value not Changed
        print(change?[.oldKey])
    }
}
</code>```

Body:
I want to get the url of a tapped link in WKWebView. The links are in a custom format that will trigger certain actions in the app. e.g. http://my-site/help#deeplink-intercom. I am using KVO like so:

override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
        view = webView
    }

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let newValue = change?[.newKey] {
            print("url changed: \(newValue)")
        }
        print("Did tap!!")
    }

This works great when the link is tapped on the first time. However if I tap the same link twice in a row it won't report the link tap (obviously because the actual value hasn't changed). Is there a workaround to fix this so I can detect every tap and get the link? Any pointer on this would be great! Thanks!

Body:
Change addObserver like this

webView.addObserver(self, forKeyPath: "URL", options: [.new, .old], context: nil)

In observeValue function you able get both value

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let newValue = change?[.newKey] as? Int, let oldValue = change?[.oldKey] as? Int, newValue != oldValue {
        //Value Changed
        print(change?[.newKey])
    }else{
        //Value not Changed
        print(change?[.oldKey])
    }
}


问:
MIME::Lite not working with SMTP
I have been using MIME::Lite for a while to send to my mailing list without any problems, but have recently decided to use SMTP authentication as I've heard it's better for email source verification.

I can't get it to work. I checked for and installed the Net::SMTP module which I understand Mime::Lite uses for this.

Any ideas?

Here's my code:

```<code>my $mailHost = 'mail.domain.com';
my $user     = 'username';
my $pass     = 'password';
my $html     = 'someHTML';
my $text     = 'someText';

use MIME::Lite;

MIME::Lite->send( 'smtp', $mailHost, AuthUser => $user, AuthPass => $pass );

my $msg = MIME::Lite->new(
    From    => 'Mailing list <list@domain.com>',
    To      => $email,
    Subject => $subject,
    Type    => 'multipart/alternative'
);

$msg->attach(
    Type => 'TEXT',
    Data => $text
);

$msg->attach(
    Type => 'text/html',
    Data => $html
);

$msg->send();
</code>```

答:
I found the solution. Authenticating through SMTP requires NET::SMTP. The following code now works for sending email with MIME::LITE and SMTP:

```<code>my $mailHost = 'domain.com';
my $user     = 'username';
my $pass     = 'password';
my $html     = 'someHTML';
my $text     = 'someText';

use MIME::Lite;
use Net::SMTP;

MIME::Lite->send( 'smtp', $mailHost, AuthUser => $user, AuthPass => $pass );

my $msg = MIME::Lite->new(
    From    => 'Mailing list <list@domain.com>',
    To      => $email,
    Subject => $subject,
    Type    => 'multipart/alternative'
);

$msg->attach(
    Type => 'TEXT',
    Data => $text
);

$msg->attach(
    Type => 'text/html',
    Data => $html
);

$msg->send();
</code>```

Title: MIME::Lite not working with SMTP

Body:
I have been using MIME::Lite for a while to send to my mailing list without any problems, but have recently decided to use SMTP authentication as I've heard it's better for email source verification.

I can't get it to work. I checked for and installed the Net::SMTP module which I understand Mime::Lite uses for this.

Any ideas?

Here's my code:

my $mailHost = 'mail.domain.com';
my $user     = 'username';
my $pass     = 'password';
my $html     = 'someHTML';
my $text     = 'someText';

use MIME::Lite;

MIME::Lite->send( 'smtp', $mailHost, AuthUser => $user, AuthPass => $pass );

my $msg = MIME::Lite->new(
    From    => 'Mailing list <list@domain.com>',
    To      => $email,
    Subject => $subject,
    Type    => 'multipart/alternative'
);

$msg->attach(
    Type => 'TEXT',
    Data => $text
);

$msg->attach(
    Type => 'text/html',
    Data => $html
);

$msg->send();

Body:
I found the solution. Authenticating through SMTP requires NET::SMTP. The following code now works for sending email with MIME::LITE and SMTP:

my $mailHost = 'domain.com';
my $user     = 'username';
my $pass     = 'password';
my $html     = 'someHTML';
my $text     = 'someText';

use MIME::Lite;
use Net::SMTP;

MIME::Lite->send( 'smtp', $mailHost, AuthUser => $user, AuthPass => $pass );

my $msg = MIME::Lite->new(
    From    => 'Mailing list <list@domain.com>',
    To      => $email,
    Subject => $subject,
    Type    => 'multipart/alternative'
);

$msg->attach(
    Type => 'TEXT',
    Data => $text
);

$msg->attach(
    Type => 'text/html',
    Data => $html
);

$msg->send();


问:
How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?
A very frequently asked question here is how to do an upsert, which is what MySQL calls INSERT ... ON DUPLICATE UPDATE and the standard supports as part of the MERGE operation.

Given that PostgreSQL doesn't support it directly (before pg 9.5), how do you do this? Consider the following:

```<code>CREATE TABLE testtable (
    id integer PRIMARY KEY,
    somedata text NOT NULL
);

INSERT INTO testtable (id, somedata) VALUES
(1, 'fred'),
(2, 'bob');
</code>```

Now imagine that you want to "upsert" the tuples (2, 'Joe'), (3, 'Alan'), so the new table contents would be:

```<code>(1, 'fred'),
(2, 'Joe'),    -- Changed value of existing tuple
(3, 'Alan')    -- Added new tuple
</code>```

That's what people are talking about when discussing an upsert. Crucially, any approach must be safe in the presence of multiple transactions working on the same table - either by using explicit locking, or otherwise defending against the resulting race conditions.

This topic is discussed extensively at Insert, on duplicate update in PostgreSQL?, but that's about alternatives to the MySQL syntax, and it's grown a fair bit of unrelated detail over time. I'm working on definitive answers.

These techniques are also useful for "insert if not exists, otherwise do nothing", i.e. "insert ... on duplicate key ignore".

答:
SQLAlchemy upsert for Postgres >=9.5

Since the large post above covers many different SQL approaches for Postgres versions (not only non-9.5 as in the question), I would like to add how to do it in SQLAlchemy if you are using Postgres 9.5. Instead of implementing your own upsert, you can also use SQLAlchemy's functions (which were added in SQLAlchemy 1.1). Personally, I would recommend using these, if possible. Not only because of convenience, but also because it lets PostgreSQL handle any race conditions that might occur.

Cross-posting from another answer I gave yesterday (https://stackoverflow.com/a/44395983/2156909)

SQLAlchemy supports ON CONFLICT now with two methods on_conflict_do_update() and on_conflict_do_nothing():

Copying from the documentation:

```<code>from sqlalchemy.dialects.postgresql import insert

stmt = insert(my_table).values(user_email='a@b.com', data='inserted data')
stmt = stmt.on_conflict_do_update(
    index_elements=[my_table.c.user_email],
    index_where=my_table.c.user_email.like('%@gmail.com'),
    set_=dict(data=stmt.excluded.data)
    )
conn.execute(stmt)
</code>```

http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html?highlight=conflict#insert-on-conflict-upsert

Body:
A very frequently asked question here is how to do an upsert, which is what MySQL calls INSERT ... ON DUPLICATE UPDATE and the standard supports as part of the MERGE operation.

Given that PostgreSQL doesn't support it directly (before pg 9.5), how do you do this? Consider the following:

CREATE TABLE testtable (
    id integer PRIMARY KEY,
    somedata text NOT NULL
);

INSERT INTO testtable (id, somedata) VALUES
(1, 'fred'),
(2, 'bob');

Now imagine that you want to "upsert" the tuples (2, 'Joe'), (3, 'Alan'), so the new table contents would be:

(1, 'fred'),
(2, 'Joe'),    -- Changed value of existing tuple
(3, 'Alan')    -- Added new tuple

That's what people are talking about when discussing an upsert. Crucially, any approach must be safe in the presence of multiple transactions working on the same table - either by using explicit locking, or otherwise defending against the resulting race conditions.

This topic is discussed extensively at Insert, on duplicate update in PostgreSQL?, but that's about alternatives to the MySQL syntax, and it's grown a fair bit of unrelated detail over time. I'm working on definitive answers.

These techniques are also useful for "insert if not exists, otherwise do nothing", i.e. "insert ... on duplicate key ignore".

Body:
SQLAlchemy upsert for Postgres >=9.5

Since the large post above covers many different SQL approaches for Postgres versions (not only non-9.5 as in the question), I would like to add how to do it in SQLAlchemy if you are using Postgres 9.5. Instead of implementing your own upsert, you can also use SQLAlchemy's functions (which were added in SQLAlchemy 1.1). Personally, I would recommend using these, if possible. Not only because of convenience, but also because it lets PostgreSQL handle any race conditions that might occur.

Cross-posting from another answer I gave yesterday (https://stackoverflow.com/a/44395983/2156909)

SQLAlchemy supports ON CONFLICT now with two methods on_conflict_do_update() and on_conflict_do_nothing():

Copying from the documentation:

from sqlalchemy.dialects.postgresql import insert

stmt = insert(my_table).values(user_email='a@b.com', data='inserted data')
stmt = stmt.on_conflict_do_update(
    index_elements=[my_table.c.user_email],
    index_where=my_table.c.user_email.like('%@gmail.com'),
    set_=dict(data=stmt.excluded.data)
    )
conn.execute(stmt)

http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html?highlight=conflict#insert-on-conflict-upsert


问:
Any PHP editor from Microsoft available for Windows?
Does Microsoft offer any PHP editor or universal-programming-editor in general }except Notepad, of course ;) ? I know they have Visual Studio (VB, C#, C++, ...), but PHP support is not included.

is there any Microsoft product which allows this?

Thanks in advance.

答:
Check out Visual Studio Code.

https://code.visualstudio.com/


问:
Bindings from Multiple ViewModels in same View WPF MVVM
I have a WPF MVVM project that includes a View which contains several controls.

There is a DockPanel which contains all the controls in the View with DataContext to a MainViewModel Class, and inside of it there is a Grid with DataContext to other object ViewModel which it's property contained in the MainViewModel Class.

Now, in that Grid I have a 2 buttons surrounds with WrapPanel, and the buttons have a Commands to a property which wrote in the MainViewModel Class, and when I pressed on it nothing happens (Because the Grid's DataContext is to other object).

I need the Commands to be stay in the MainViewModel Class, How can I do that?

XAML: (just the relevant parts)

```<code><DockPanel x:Name="MonitorParent" DataContext="{Binding MonitorMainViewModel}" LastChildFill="False" Width="1144" HorizontalAlignment="Left">
      .......
    <StackPanel>
        <ContentControl Visibility="{Binding Path=NoMonitorsMessageVisibility, Converter={StaticResource visibilityConverter}}">
            <StackPanel Width="804" Height="574">
                <Grid DataContext="{Binding CurrentMonitor}" Margin="10 0" Height="auto">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" MinHeight="23" />
                        <RowDefinition Height="Auto" MinHeight="23" />
                        <RowDefinition Height="Auto" MinHeight="23" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="140" />
                    </Grid.ColumnDefinitions>
                    <Label Grid.Column="0" Grid.Row="15"  Content="Serial Number" x:Name="SerialNumber"   />
                    <WrapPanel  DataContext="{Binding MonitorMainViewModel}" HorizontalAlignment="Center" Margin="0,10,0,10" Grid.ColumnSpan="2" Grid.Row="6" >
                        <Button Content="Add" Width="60" Margin="0,0,40,0" Command="{Binding AddConfidenceCommand}" />
                        <Button Content="Delete" Width="60" Margin="30,0,0,0" Command="{Binding DeleteConfidenceCommand}"/>
                    </WrapPanel>

                     ........
  </DockPanel
</code>```

答:
You could use the name of the DockPanel for binding like this:

```<code><DockPanel x:Name="MonitorParent" DataContext="{Binding MonitorMainViewModel}" LastChildFill="False" Width="1144" HorizontalAlignment="Left">
  .......
<StackPanel>
    <ContentControl Visibility="{Binding Path=NoMonitorsMessageVisibility, Converter={StaticResource visibilityConverter}}">
        <StackPanel Width="804" Height="574">
            <Grid DataContext="{Binding CurrentMonitor}" Margin="10 0" Height="auto">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" MinHeight="23" />
                    <RowDefinition Height="Auto" MinHeight="23" />
                    <RowDefinition Height="Auto" MinHeight="23" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="140" />
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0" Grid.Row="15"  Content="Serial Number" x:Name="SerialNumber"   />
                <WrapPanel  DataContext="{Binding MonitorMainViewModel}" HorizontalAlignment="Center" Margin="0,10,0,10" Grid.ColumnSpan="2" Grid.Row="6" >
                    <Button Content="Add" Width="60" Margin="0,0,40,0" Command="{Binding ElementName=MonitorParent, Path=DataContext.AddConfidenceCommand}" />
                    <Button Content="Delete" Width="60" Margin="30,0,0,0" Command="{Binding ElementName=MonitorParent, Path=DataContext.DeleteConfidenceCommand}"/>
                </WrapPanel>

                 ........
</code>```

Body:
I have a WPF MVVM project that includes a View which contains several controls.

There is a DockPanel which contains all the controls in the View with DataContext to a MainViewModel Class, and inside of it there is a Grid with DataContext to other object ViewModel which it's property contained in the MainViewModel Class.

Now, in that Grid I have a 2 buttons surrounds with WrapPanel, and the buttons have a Commands to a property which wrote in the MainViewModel Class, and when I pressed on it nothing happens (Because the Grid's DataContext is to other object).

I need the Commands to be stay in the MainViewModel Class, How can I do that?

XAML: (just the relevant parts)

<DockPanel x:Name="MonitorParent" DataContext="{Binding MonitorMainViewModel}" LastChildFill="False" Width="1144" HorizontalAlignment="Left">
      .......
    <StackPanel>
        <ContentControl Visibility="{Binding Path=NoMonitorsMessageVisibility, Converter={StaticResource visibilityConverter}}">
            <StackPanel Width="804" Height="574">
                <Grid DataContext="{Binding CurrentMonitor}" Margin="10 0" Height="auto">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" MinHeight="23" />
                        <RowDefinition Height="Auto" MinHeight="23" />
                        <RowDefinition Height="Auto" MinHeight="23" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="140" />
                    </Grid.ColumnDefinitions>

                    <WrapPanel  DataContext="{Binding MonitorMainViewModel}" HorizontalAlignment="Center" Margin="0,10,0,10" Grid.ColumnSpan="2" Grid.Row="6" >
                        <Button Content="Add" Width="60" Margin="0,0,40,0" Command="{Binding AddConfidenceCommand}" />
                        <Button Content="Delete" Width="60" Margin="30,0,0,0" Command="{Binding DeleteConfidenceCommand}"/>
                    </WrapPanel>

                     ........
  </DockPanel

Body:
You could use the name of the DockPanel for binding like this:

<DockPanel x:Name="MonitorParent" DataContext="{Binding MonitorMainViewModel}" LastChildFill="False" Width="1144" HorizontalAlignment="Left">
  .......
<StackPanel>
    <ContentControl Visibility="{Binding Path=NoMonitorsMessageVisibility, Converter={StaticResource visibilityConverter}}">
        <StackPanel Width="804" Height="574">
            <Grid DataContext="{Binding CurrentMonitor}" Margin="10 0" Height="auto">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" MinHeight="23" />
                    <RowDefinition Height="Auto" MinHeight="23" />
                    <RowDefinition Height="Auto" MinHeight="23" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="140" />
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0" Grid.Row="15"  Content="Serial Number" x:Name="SerialNumber"   />
                <WrapPanel  DataContext="{Binding MonitorMainViewModel}" HorizontalAlignment="Center" Margin="0,10,0,10" Grid.ColumnSpan="2" Grid.Row="6" >
                    <Button Content="Add" Width="60" Margin="0,0,40,0" Command="{Binding ElementName=MonitorParent, Path=DataContext.AddConfidenceCommand}" />
                    <Button Content="Delete" Width="60" Margin="30,0,0,0" Command="{Binding ElementName=MonitorParent, Path=DataContext.DeleteConfidenceCommand}"/>
                </WrapPanel>

                 ........


问:
Saving screenshots with protractor
I'm attempting to save a screenshot using a generic method in protractor. Two features, it creates the folder if it does not exist and it saves the file (with certain conditions).

```<code>export function WriteScreenShot(data: string, filename: string) {
    let datetime = moment().format('YYYYMMDD-hhmmss');
    filename = `../../../test-reports/${filename}.${datetime}.png`;

    let path =filename.substring(0, filename.lastIndexOf('/'));
    if (!fs.existsSync(path)) {
        fs.mkdirSync(path);
    }

    let stream = fs.createWriteStream(filename);
    stream.write(new Buffer(data, 'base64'));
    stream.end();
}
</code>```

This can be used by calling browser.takeScreenshot().then(png => WriteScreenShot(png, 'login/login-page'));  Using this example call, a file will be created, I assumed, in the path relative where my WriteScreenShot method's file resides.  But that does not appear to be the case.

For example, when I run my spec test in the spec's folder, the image gets saved in the correct place.  But if I run it at the project root, an error is capture.  Obviously, this has to do with my relative path reference.  How do I capture the project's root directory and build from that so that I can run the test from any directory?

答:
This is a classical directory access error. Let me just explain what is happening to your code -

```<code> let path =filename.substring(0, filename.lastIndexOf('/'));
</code>```

The above line outputs to ../../../test-reports

fs.existsSync checks whether thispath exists or not -

case 1 :(postive flow) Your spec folder is in the same current working directory in which you are trying to create reports folder. When you run your test, the path exists, it generates the test-reports directory & screenshots and your code works fine.

case 2:(negative flow)  When you try to run it from the root directory which is the current working directory now, fs.existsSync tries to check the path & the reports folder inside it. If it doesn't exist , fs.mkdirSync tries to create your directories but it would fail as it cannot create multiple directories.

You should be using native path module of nodejs to extract the path instead of using file substring and the mkdirp external module for creating multiple directories.

```<code>import * as path from 'path';
let {mkdirp} = require('mkdirp'); // npm i -D mkdirp

export function WriteScreenShot(data: string, filename: string) {
    let datetime = moment().format('YYYYMMDD-hhmmss');
    filename = `../../../test-reports/${filename}.${datetime}.png`;

    let filePath = path.dirname(filename); // output: '../../..' (relative path)
            // or
    let filePath = path.resolve(__dirname); // output: 'your_root_dir_path' (absolute path)
            // or
    let filePath = path.resolve('.'); // output: 'your_root_dir_path' (absolute path)

    if (!fs.existsSync(filePath )) {
        mkdirp.sync(filePath); // creates multiple folders if they don't exist
    }

    let stream = fs.createWriteStream(filename);
    stream.write(new Buffer(data, 'base64'));
    stream.end();
}
</code>```

If you are curious to know the difference btw mkdir & mkdir-p please read this SO thread.

Title: Saving screenshots with protractor

Body:
I'm attempting to save a screenshot using a generic method in protractor. Two features, it creates the folder if it does not exist and it saves the file (with certain conditions).

export function WriteScreenShot(data: string, filename: string) {
    let datetime = moment().format('YYYYMMDD-hhmmss');
    filename = `../../../test-reports/${filename}.${datetime}.png`;

    let path =filename.substring(0, filename.lastIndexOf('/'));
    if (!fs.existsSync(path)) {
        fs.mkdirSync(path);
    }

    let stream = fs.createWriteStream(filename);
    stream.write(new Buffer(data, 'base64'));
    stream.end();
}

This can be used by calling browser.takeScreenshot().then(png => WriteScreenShot(png, 'login/login-page'));  Using this example call, a file will be created, I assumed, in the path relative where my WriteScreenShot method's file resides.  But that does not appear to be the case.

For example, when I run my spec test in the spec's folder, the image gets saved in the correct place.  But if I run it at the project root, an error is capture.  Obviously, this has to do with my relative path reference.  How do I capture the project's root directory and build from that so that I can run the test from any directory?

Body:
This is a classical directory access error. Let me just explain what is happening to your code -

 let path =filename.substring(0, filename.lastIndexOf('/'));

The above line outputs to ../../../test-reports

fs.existsSync checks whether thispath exists or not -

case 1 :(postive flow) Your spec folder is in the same current working directory in which you are trying to create reports folder. When you run your test, the path exists, it generates the test-reports directory & screenshots and your code works fine.

case 2:(negative flow)  When you try to run it from the root directory which is the current working directory now, fs.existsSync tries to check the path & the reports folder inside it. If it doesn't exist , fs.mkdirSync tries to create your directories but it would fail as it cannot create multiple directories.

You should be using native path module of nodejs to extract the path instead of using file substring and the mkdirp external module for creating multiple directories.

import * as path from 'path';
let {mkdirp} = require('mkdirp'); // npm i -D mkdirp

export function WriteScreenShot(data: string, filename: string) {
    let datetime = moment().format('YYYYMMDD-hhmmss');
    filename = `../../../test-reports/${filename}.${datetime}.png`;

    let filePath = path.dirname(filename); // output: '../../..' (relative path)
            // or
    let filePath = path.resolve(__dirname); // output: 'your_root_dir_path' (absolute path)
            // or
    let filePath = path.resolve('.'); // output: 'your_root_dir_path' (absolute path)

    if (!fs.existsSync(filePath )) {
        mkdirp.sync(filePath); // creates multiple folders if they don't exist
    }

    let stream = fs.createWriteStream(filename);
    stream.write(new Buffer(data, 'base64'));
    stream.end();
}

If you are curious to know the difference btw mkdir & mkdir-p please read this SO thread.


问:
Elasticsearch different results with boolean queries
I have two queries that I think, should return same amount of results.
First is a "must" with query_string on 2 fields. E.g.

```<code>{
  "query": {
    "nested": {
      "path": "app.pub",
      "query": {
        "bool": {
          "must": [
            {
              "query_string": {
                "query": "wheel* chair* foot* driven*",
                "fields": [
                  "app.pub.title.*.docdba",
                  "app.pub.abstract.*.docdba"
                ],
                "default_operator": "and"
              }
            }
          ]
        }
      }
    }
  }
}
</code>```

That gives me 120 results. Second one is a "should" query, that searches for same strings with wildcards, on title field or abstract. E.g.:

```<code>{
  "query": {
    "nested": {
      "path": "app.pub",
      "query": {
        "bool": {
          "should": [
            {
              "query_string": {
                "query": "wheel* chair* foot* driven*",
                "fields": [
                  "app.pub.title.*.docdba"
                ],
                "default_operator": "and"
              }
            },
            {
              "query_string": {
                "query": "wheel* chair* foot* driven*",
                "fields": [
                  "app.pub.abstract.*.docdba"
                ],
                "default_operator": "and"
              }
            }
          ]
        }
      }
    }
  }
}
</code>```

Here I'm getting 109 results. So I have 11 hits less. Anyone have idea why?

答: Easy. In first search I'm looking for 4 words in two fields. That means it matches fields that does not have all searched words in one field, but also combination of two. While in second search all 4 words have to be present in one field or another. </p>

Body:
I have two queries that I think, should return same amount of results.
First is a "must" with query_string on 2 fields. E.g.

{
  "query": {
    "nested": {
      "path": "app.pub",
      "query": {
        "bool": {
          "must": [
            {
              "query_string": {
                "query": "wheel* chair* foot* driven*",
                "fields": [
                  "app.pub.title.*.docdba",
                  "app.pub.abstract.*.docdba"
                ],
                "default_operator": "and"
              }
            }
          ]
        }
      }
    }
  }
}

That gives me 120 results. Second one is a "should" query, that searches for same strings with wildcards, on title field or abstract. E.g.:

{
  "query": {
    "nested": {
      "path": "app.pub",
      "query": {
        "bool": {
          "should": [
            {
              "query_string": {
                "query": "wheel* chair* foot* driven*",
                "fields": [
                  "app.pub.title.*.docdba"
                ],
                "default_operator": "and"
              }
            },
            {
              "query_string": {
                "query": "wheel* chair* foot* driven*",
                "fields": [
                  "app.pub.abstract.*.docdba"
                ],
                "default_operator": "and"
              }
            }
          ]
        }
      }
    }
  }
}

Here I'm getting 109 results. So I have 11 hits less. Anyone have idea why?


问:
Filtering users who are able to sign in with Devise
I have a Rails app using Devise for authentication. Users belong to Dealers and I want to prevent users who belong to disabled dealers from being able to sign in.

Is there a straightforward way to extend Devise's authentication finder so that it will not include users from deleted dealers? Perhaps using a named scope on User?

Cheers

Tristan

答:
Searching Stackoverflow.com gave me this question/answer: Custom authentication strategy for devise

Basically, you have to implement a custom authentication strategy at Warden's level (that underlies Devise). For my project, I did the following:

In config/initializers/devise.rb:

```<code>Devise.setup do |config|
  config.warden do |manager|
    manager.default_strategies(:scope => :user).unshift :user_has_login_access
  end
end

Warden::Strategies.add(:user_has_login_access) do
  def valid?
    # pass the commit parameter as 'login' or something like that, so that this strategy only activates when the user is trying to login
    params[:commit] == 'login'
  end

  def authenticate!
    u = User.find_by_email(params[:user][:email])
    if u.can_login? # retrieves boolean value stored in the User model, set wherever
      success! u
    else
      fail! "Account does not have login privilages."
    end
  end
end
</code>```

You can read more about custom Warden strategies here: https://github.com/hassox/warden/wiki/Strategies

Hope that helps!

ContentLicense: CC BY-SA 2.5

Body:
Searching Stackoverflow.com gave me this question/answer: Custom authentication strategy for devise

Basically, you have to implement a custom authentication strategy at Warden's level (that underlies Devise). For my project, I did the following:

In config/initializers/devise.rb:

Devise.setup do |config|
  config.warden do |manager|
    manager.default_strategies(:scope => :user).unshift :user_has_login_access
  end
end

Warden::Strategies.add(:user_has_login_access) do
  def valid?
    # pass the commit parameter as 'login' or something like that, so that this strategy only activates when the user is trying to login
    params[:commit] == 'login'
  end

  def authenticate!
    u = User.find_by_email(params[:user][:email])
    if u.can_login? # retrieves boolean value stored in the User model, set wherever
      success! u
    else
      fail! "Account does not have login privilages."
    end
  end
end

You can read more about custom Warden strategies here: https://github.com/hassox/warden/wiki/Strategies

Hope that helps!


问:
Linker errors after upgrading Xcode to 4.5.2 and OpenCV to 2.4.3
My project was working just fine until this morning. I was using xcode 4.3, and an older version of OpenCV (I'm not sure about the exact version). OSX was already 10.7.x, but not 10.7.5

Today, after upgrading OSX to 10.7.5, xcode to 4.5.2, and downloading OpenCV 2.4.3, I am getting the following linker errors when trying to build the project:

Undefined symbols for architecture armv7:

    "_OBJC_CLASS_$_ALAssetsLibrary", referenced from:

        objc-class-ref in opencv2(cap_ios_video_camera.o)

    "cv::FeatureDetector::create(std::string const&)", referenced from:

        -[ImageAnalyzer detectBlobs:] in ImageAnalyzer.o

    "cv::FeatureDetector::detect(cv::Mat const&, std::vector >&, cv::Mat const&) const", referenced from:

        -[ImageAnalyzer detectBlobs:] in ImageAnalyzer.o

  ld: symbol(s) not found for architecture armv7

  clang: error: linker command failed with exit code 1 (use -v to see invocation)

In order to use the new opencv framework I removed the reference to the old framework, and referenced the project to the official prebuilt opencv2.framework downloaded from here.

I also removed the reference to libz.dylib, and added a reference to libc++.dylib instead.

Last step was to update the prefix file to the new framework. The relevant part in the prefix file now looks like this:

```<code>#ifdef __cplusplus
#import <opencv2/opencv.hpp>
#endif
</code>```

It all narrowed down to these 4 linker errors I can't seem to get rid of. I tried using libstdc++.dylib, but I am getting even more errors. I also tried building OpenCV myself as explained here, but I am still getting the same errors as the prebuilt framework.

What did I miss? Is there anything else I need to change in my project?

UPDATE:

As seen here, setting the "C++ Standard Library" to "libc++ (LLVM C++ standard libray with C++ 11 support" yielded only one error:

clang: error: invalid deployment target for -stdlib=libc++ (requires iOS 5.0 or later)

Changing the deployment target to iOS 5 finally got my project to run again.

Does this mean OpenCV 2.4.3 doesn't work on iOS versions older than 5?

答:
Go Xcode/General/Linked Frameworks and Libraries

Press "+" button

type: AssetsLibrary

Select "AssetsLibrary.framework" and import it

Done

Good luck!

Body:
My project was working just fine until this morning. I was using xcode 4.3, and an older version of OpenCV (I'm not sure about the exact version). OSX was already 10.7.x, but not 10.7.5

Today, after upgrading OSX to 10.7.5, xcode to 4.5.2, and downloading OpenCV 2.4.3, I am getting the following linker errors when trying to build the project:

Undefined symbols for architecture armv7:

    "_OBJC_CLASS_$_ALAssetsLibrary", referenced from:

        objc-class-ref in opencv2(cap_ios_video_camera.o)

    "cv::FeatureDetector::create(std::string const&)", referenced from:

        -[ImageAnalyzer detectBlobs:] in ImageAnalyzer.o

    "cv::FeatureDetector::detect(cv::Mat const&, std::vector >&, cv::Mat const&) const", referenced from:

        -[ImageAnalyzer detectBlobs:] in ImageAnalyzer.o

  ld: symbol(s) not found for architecture armv7

  clang: error: linker command failed with exit code 1 (use -v to see invocation)

In order to use the new opencv framework I removed the reference to the old framework, and referenced the project to the official prebuilt opencv2.framework downloaded from here.

I also removed the reference to libz.dylib, and added a reference to libc++.dylib instead.

Last step was to update the prefix file to the new framework. The relevant part in the prefix file now looks like this:

#ifdef __cplusplus
#import <opencv2/opencv.hpp>
#endif

It all narrowed down to these 4 linker errors I can't seem to get rid of. I tried using libstdc++.dylib, but I am getting even more errors. I also tried building OpenCV myself as explained here, but I am still getting the same errors as the prebuilt framework.

What did I miss? Is there anything else I need to change in my project?

UPDATE:

As seen here, setting the "C++ Standard Library" to "libc++ (LLVM C++ standard libray with C++ 11 support" yielded only one error:

clang: error: invalid deployment target for -stdlib=libc++ (requires iOS 5.0 or later)

Changing the deployment target to iOS 5 finally got my project to run again.

Does this mean OpenCV 2.4.3 doesn't work on iOS versions older than 5?


问:
regex error on apache nifi (replace text processor)
i'm trying to ingest some data from twitter to elasticsearch using apache nifi, the problem is that all my attributes are written between double quotes, i have an attribute that is supposed to be a number and i don't know how to remove double quotes from it.
i tried using "replace text" process but i get errors.
here is my configuration:

Search Value : (?s:("([0-9]*[.]){1}[0-9]+"))

Replacement Value : ${$1:replace('\"', '')}

答:
sample: {"a":"1","b": "2"}

search value: (?s)(:\s*)"(\d+)"

replacement value: $1$2

produces: {"a":1,"b": 2}


问:
Entity Framework 6 with ASE 15.7
Is ADO.NET Data Provider released with ASE 15.7 supports Entity Framework 6?

And is there any documentation which shows how to create Web.config / App.config with ASE 15.7 + Entity Framework 6?

答:
Official Reply from SAP support:

Currently ASE SDK doesn't support EF 6.0.
CR# 765581 is the request for this support.
You can follow KBA#  2484554 to know when this is supported.
I've updated the Team lead of this request as well.
Currently .Net 4.5 Ado.Net driver supports EF 5.0.

There is currently no target SAP SDK Service Pack scheduled for the new feature >request CR 765581. It is being reviewed by our Product Group.  Please mark this >KBA as a Favorite to receive an update when this enhancement is implemented.

ContentLicense: CC BY-SA 4.0

Title: Entity Framework 6 with ASE 15.7


问:
Django not loading static files (Pycharm)
I am working on a project which requires loading on a CSS stylesheet and a logo file. But my Django server also returns 404 resource not found while loading these files. I have checked other questions like this but none of them is using the format to specify static files I used.
This is the html code i am using

```<code>{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="/static/Emu86/style.css">
{% endblock stylesheets %}
</code>```

This is my settings.py file:

```<code>    """
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.9.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Application definition

INSTALLED_APPS = [
    'Emu86',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',

]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] \
                %(message)s",
                'datefmt': "%d%b%Y %H:%M:%S"
         },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'Emu86.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'DEBUG',
        },
        'Emu86': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    },
}
</code>```

Project Structure:

```<code>Emu86/
  mysite/
      static/
        Emu86/
</code>```

答:
you need to do some changes in setting.py

Add

STATICFILES_DIRS = [
     os.path.join(BASE_DIR, "static"),
]

below BASE_DIR....

hope it works

Body:
I am working on a project which requires loading on a CSS stylesheet and a logo file. But my Django server also returns 404 resource not found while loading these files. I have checked other questions like this but none of them is using the format to specify static files I used.
This is the html code i am using

{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="/static/Emu86/style.css">
{% endblock stylesheets %}

This is my settings.py file:

    """
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.9.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Application definition

INSTALLED_APPS = [
    'Emu86',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',

]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] \
                %(message)s",
                'datefmt': "%d%b%Y %H:%M:%S"
         },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'Emu86.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'DEBUG',
        },
        'Emu86': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    },
}

Project Structure:

Emu86/
  mysite/
      static/
        Emu86/


问:
Identifying the Number of Positions then Outputting the Positions and Number in another Column

Hi everyone, Im new to VBA and StackOverflow. Currently, I am trying to use VBA to create a process to summarise the data that I have collected.The above photo is a part of the long macro process that I am facing issues with. I need to find the number of unique positions in column "A" (new positions can be added in over time), then output the unique positions into the positions column in column "J". After that, in column "K", I would need to count the number of each unique rank.

As of now, I have the following code to find for a position.

```<code>Sub test ()
Dim Manager as Integer
Sheets("Sheet1").Select
Manager = Application.WorksheetFunction.CountIf(Range("A:A"), "Manager")
'Output the Manager value anywhere as require
End Sub
</code>```

However, I face challenges in identifying the unique positions, counting the unique positions and then outputting the number of unique positions beside the position. Is this even possible in VBA?

Thanks so much

答:
Create "Temp" sheet first then execute this VBA below:</p>

```<code>    Sub ExtractUnique()
    Dim sh As Worksheet
    Dim shTemp As Worksheet
    Dim LastRow As Long

    Set sh = ActiveSheet 'or change to your sheet name Sheets("your sheet")
    LastRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row

   'temporary sheet
   Set shTemp = ThisWorkbook.Sheets("Temp") 'MAKE SURE YOU CREATE 'Temp' sheet first!!!

   'copy your positions to temporary sheet for manipulation
   sh.Range("A1:A" & LastRow).Copy
   shTemp.Range("A1").PasteSpecial xlValues
   Application.CutCopyMode = False

   'remove duplicates
   shTemp.Range("A1:A" & LastRow).RemoveDuplicates Columns:=Array(1), Header:=xlYes

   'copy it back to J1 of your original sheet
   'first check the last row of unique position list
   LastRow = shTemp.Cells(sh.Rows.Count, "A").End(xlUp).Row

   shTemp.Range("A1:A" & LastRow).Copy
   sh.Range("J1").PasteSpecial xlValues
   Application.CutCopyMode = False

   'set the formula to count the number of positions
   sh.Range("K2:K" & LastRow).Formula = "=COUNTIF(A:A,J2)"

   End Sub
</code>```

Body:
Hi everyone, Im new to VBA and StackOverflow. Currently, I am trying to use VBA to create a process to summarise the data that I have collected.The above photo is a part of the long macro process that I am facing issues with. I need to find the number of unique positions in column "A" (new positions can be added in over time), then output the unique positions into the positions column in column "J". After that, in column "K", I would need to count the number of each unique rank.

As of now, I have the following code to find for a position.

Sub test ()
Dim Manager as Integer
Sheets("Sheet1").Select
Manager = Application.WorksheetFunction.CountIf(Range("A:A"), "Manager")
'Output the Manager value anywhere as require
End Sub

However, I face challenges in identifying the unique positions, counting the unique positions and then outputting the number of unique positions beside the position. Is this even possible in VBA?

Thanks so much

Body:
Create "Temp" sheet first then execute this VBA below:

    Sub ExtractUnique()
    Dim sh As Worksheet
    Dim shTemp As Worksheet
    Dim LastRow As Long

    Set sh = ActiveSheet 'or change to your sheet name Sheets("your sheet")
    LastRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row

   'temporary sheet
   Set shTemp = ThisWorkbook.Sheets("Temp") 'MAKE SURE YOU CREATE 'Temp' sheet first!!!

   'copy your positions to temporary sheet for manipulation
   sh.Range("A1:A" & LastRow).Copy
   shTemp.Range("A1").PasteSpecial xlValues
   Application.CutCopyMode = False

   'remove duplicates
   shTemp.Range("A1:A" & LastRow).RemoveDuplicates Columns:=Array(1), Header:=xlYes

   'copy it back to J1 of your original sheet
   'first check the last row of unique position list
   LastRow = shTemp.Cells(sh.Rows.Count, "A").End(xlUp).Row

   shTemp.Range("A1:A" & LastRow).Copy
   sh.Range("J1").PasteSpecial xlValues
   Application.CutCopyMode = False

   'set the formula to count the number of positions
   sh.Range("K2:K" & LastRow).Formula = "=COUNTIF(A:A,J2)"

   End Sub


问:
Hiding flash message after some seconds in codeigniter php
Hi i have tried with some script hiding the flash message once it is shown but it is not working.Displaying the flash message until i refresh the page.

Controller:

```<code>if ($this->email->send())
        {
           $this->session->set_flashdata('msg','<div class="alert alert-success text-center" id="successMessage">Thank you for contacting us we will get back to you soon!</div>');
            redirect('contact');
        }
        else
        {
            $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">There is error in sending mail! Please try again later</div>');
            redirect('contact');
        }
</code>```

View:

```<code><script>
$(function() {
// setTimeout() function will be fired after page is loaded
// it will wait for 5 sec. and then will fire
// $("#successMessage").hide() function
setTimeout(function() {
    $(".alert-success").hide('blind', {}, 500)
}, 5000);
});
</script>
<div class="container">

<div class="row contactpageback">

        <div class="col-lg-6 contactuspagedetails">
            <form name="contact"  id="contactform" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>contact">
            <?php echo  $this->session->flashdata('msg');?>
            <?php if(isset($msg)){?>
             <?php echo $msg;?>
               <?php } ?>
</code>```

答:
This will help you to hide your message after 3 seconds with fadeOut animation.
You can change seconds in timeout variable.

var timeout = 3000; // in miliseconds (3*1000)

$('.alert').delay(timeout).fadeOut(300);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="alert alert-success">
  Success Message.
</div></code>```

Body:
Hi i have tried with some script hiding the flash message once it is shown but it is not working.Displaying the flash message until i refresh the page.

Controller:

if ($this->email->send())
        {
           $this->session->set_flashdata('msg','
Thank you for contacting us we will get back to you soon!
');
            redirect('contact');
        }
        else
        {
            $this->session->set_flashdata('msg','
There is error in sending mail! Please try again later
');
            redirect('contact');
        }

View:

            <form name="contact"  id="contactform" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>contact">
            <?php echo  $this->session->flashdata('msg');?>
            <?php if(isset($msg)){?>
             <?php echo $msg;?>
               <?php } ?>

Body:
This will help you to hide your message after 3 seconds with fadeOut animation.
You can change seconds in timeout variable.

var timeout = 3000; // in miliseconds (3*1000)

$('.alert').delay(timeout).fadeOut(300);

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="alert alert-success">
  Success Message.
</div>


问:
Having Trouble Formatting Website for All Resolutions
Hello fellow techies who will fix your relatives computer for free,

Anyway, I am a fairly new coder, and am only still a beginner in HTML/CSS. As a first project, I am making a website for my Dad as a birthday present, because he hasn't updated his small business' website in about 15 years, and gets most of his work through his rep, but I want to help him out and bring it into the 21st century.

Anyway, I followed a few YT tutorials on how to create a simple website, but ATM my website is about 800px across, and it looks like his current website since no matter what size your screen is, the text only fills up about 1/3-1/2 of the screen.

The main thing I want first of all is for the background colors, especially the header, to bleed off screen, and secondly, for the text/pictures to scale as you change the browser size.

I tried looking for some answers on other threads, but it was hard for me to understand since the other people had their own names for their dividers and variables.

Here is a portion of my HTML and CSS. Of course I cut out most of the code like most of the text, text formatting, etc, as well as names and places.

HTML:

```<code><DOCTYPE html>
<html>
<head>
<title>Website</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="container">
<div id="header">
<h1>Dad's Company</h1>
</div>
<div id="content">
<div id="main">
<h2>Person Name</h2>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</div>
<div id= "footer">
Copyright © 2017 Ye Co.
</div>
</div>
</body>
</html>
----------
</code>```

This is the CSS

```<code>body {
    background-color: #FFFFFF;
    overflow-x: hidden;
    width: 100%;
    height: 100%;
}

h1 {
    margin-left: 10px;
    padding: 30px;
    text-align: center;
}

h2 {
    color: #4F4F4F;
    text-align: center;
}

#header {
    background-color: #992626;
}

#container {
    background-color: #DDDDDD;
    width: 800px;
    margin-left: auto;
    margin-right: auto;
}

 #site {
    overflow-x: hidden;
 }

#content {
    padding: 10px;
    text-align: center;
    float: right;
}

#main {
    width: 600px;
    float: center;
}

#footer {
    clear: both;
    font-size: 15;
    text-align: right;
    padding: 5px;
    background-color: #992626;
    font-family: serif;
</code>```

Thanks!
I hope you guys can find an answer through my messy coding. It will also help if you guys can give me an example of some of you code instead to show me a solution. Thanks!

答:
<DOCTYPE html>

<title>Website</title>
<link rel="stylesheet" type="text/css" href="style.css"/>

Dad's Company

Person Name

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Copyright © 2017 Ye Co.

```

Body:
Hello fellow techies who will fix your relatives computer for free,

Anyway, I am a fairly new coder, and am only still a beginner in HTML/CSS. As a first project, I am making a website for my Dad as a birthday present, because he hasn't updated his small business' website in about 15 years, and gets most of his work through his rep, but I want to help him out and bring it into the 21st century.

Anyway, I followed a few YT tutorials on how to create a simple website, but ATM my website is about 800px across, and it looks like his current website since no matter what size your screen is, the text only fills up about 1/3-1/2 of the screen.

The main thing I want first of all is for the background colors, especially the header, to bleed off screen, and secondly, for the text/pictures to scale as you change the browser size.

I tried looking for some answers on other threads, but it was hard for me to understand since the other people had their own names for their dividers and variables.

Here is a portion of my HTML and CSS. Of course I cut out most of the code like most of the text, text formatting, etc, as well as names and places.

HTML:

<DOCTYPE html>

<title>Website</title>
<link rel="stylesheet" type="text/css" href="style.css"/>

Dad's Company

Person Name

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Copyright © 2017 Ye Co.

----------

This is the CSS

body {
    background-color: #FFFFFF;
    overflow-x: hidden;
    width: 100%;
    height: 100%;
}

h1 {
    margin-left: 10px;
    padding: 30px;
    text-align: center;
}

h2 {
    color: #4F4F4F;
    text-align: center;
}

#header {
    background-color: #992626;
}

#container {
    background-color: #DDDDDD;
    width: 800px;
    margin-left: auto;
    margin-right: auto;
}

 #site {
    overflow-x: hidden;
 }

#content {
    padding: 10px;
    text-align: center;
    float: right;
}

#main {
    width: 600px;
    float: center;
}

#footer {
    clear: both;
    font-size: 15;
    text-align: right;
    padding: 5px;
    background-color: #992626;
    font-family: serif;

Thanks!
I hope you guys can find an answer through my messy coding. It will also help if you guys can give me an example of some of you code instead to show me a solution. Thanks!

Body:
<DOCTYPE html>
<html>
<head>
<title>Website</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<style>
body {
    background-color: #FFFFFF;
    overflow-x: hidden;
    width: 100%;
    height: 100%;
}

h1 {
    margin-left: 10px;
    padding: 30px;
    text-align: center;
}

h2 {
    color: #4F4F4F;
    text-align: center;
}

#header {
    background-color: #992626;
}

#container {
    background-color: #DDDDDD;
    width: 800px;
    margin-left: auto;
    margin-right: auto;
}

 #site {
    overflow-x: hidden;
 }

#content {
    padding: 10px;
    text-align: center;
    float: right;
}

#main {
    width: 600px;
    float: center;
}

#footer {
    clear: both;
    font-size: 15;
    text-align: center;
    padding: 5px;
    background-color: #992626;
    font-family: serif;
}
</style>
</head>
<body>
<div id="container">
<div id="header">
<h1>Dad's Company</h1>
</div>
<div id="content">
<div >
<h2>Person Name</h2>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</div>
<div id= "footer">
Copyright &copy; 2017 Ye Co.
</div>
</div>

</body>
</html>


问:
How to sent a POST request with form-data and parameters in PL/SQL
I'm trying to call REST WebService in PL/SQL but it doesn't work. I get this error:

Content-type must be multipart/form-data

Here is what I have:

```<code>DECLARE
  req   UTL_HTTP.REQ;
  resp  UTL_HTTP.RESP;
  value VARCHAR2(1024);  -- URL to post to
  v_url VARCHAR2(200) := 'http://local/api/ws';
  -- Post Parameters
  v_param VARCHAR2(500) := 'art=11111\&qty=1';
  v_param_length NUMBER := length(v_param);
BEGIN
  req := UTL_HTTP.BEGIN_REQUEST (url=> v_url, method => 'POST');
  UTL_HTTP.SET_HEADER(req, 'User-Agent', 'Mozilla/4.0');
  UTL_HTTP.SET_HEADER (r      =>  req,
                       name   =>  'Content-Type',
                       value  =>  'multipart/form-data; charset=utf-8; boundary=/');
  UTL_HTTP.SET_HEADER (r      =>   req,
                       name   =>   'Content-Length',
                       value  =>   v_param_length);
  UTL_HTTP.WRITE_TEXT (r      =>   req,
                       data   =>   v_param);

     resp := UTL_HTTP.GET_RESPONSE(req);
  LOOP
    UTL_HTTP.READ_LINE(resp, value, TRUE);
    DBMS_OUTPUT.PUT_LINE(value);
  END LOOP;
  UTL_HTTP.END_RESPONSE(resp);
EXCEPTION
  WHEN UTL_HTTP.END_OF_BODY THEN
    UTL_HTTP.END_RESPONSE(resp);
END;
</code>```

Here is an example with CURL :

```<code>curl -v -X POST -H "Content-Type: multipart/form-data" -F "art=11111" -F "qty=1" http://local/api/ws
</code>```

This example works fine with curl but i don't know why it doesn't in PL/SQL.
Can you help me ?

答:
I don't think you can use a POST with GET query like you do in the URL...

It looks quite difficult to do what you expect. Here is some input from Ask Tom:

The idea is to generate the  post text, including a specific "boundary", which will look like this:

```<code>POST /path/to/script.php HTTP/1.0
Host: example.com
Content-type: multipart/form-data, boundary=AaB03x
Content-Length: $requestlen

--AaB03x
content-disposition: form-data; name="field1"

$field1
--AaB03x
content-disposition: form-data; name="field2"

$field2
--AaB03x
content-disposition: form-data; name="userfile"; filename="$filename"
Content-Type: $mimetype
Content-Transfer-Encoding: binary

$binarydata
--AaB03x--
</code>```

There is also same issue developed here with lots of code.

Hope it helps.

Body:
I'm trying to call REST WebService in PL/SQL but it doesn't work. I get this error:

Content-type must be multipart/form-data

Here is what I have:

DECLARE
  req   UTL_HTTP.REQ;
  resp  UTL_HTTP.RESP;
  value VARCHAR2(1024);  -- URL to post to
  v_url VARCHAR2(200) := 'http://local/api/ws';
  -- Post Parameters
  v_param VARCHAR2(500) := 'art=11111\&qty=1';
  v_param_length NUMBER := length(v_param);
BEGIN
  req := UTL_HTTP.BEGIN_REQUEST (url=> v_url, method => 'POST');
  UTL_HTTP.SET_HEADER(req, 'User-Agent', 'Mozilla/4.0');
  UTL_HTTP.SET_HEADER (r      =>  req,
                       name   =>  'Content-Type',
                       value  =>  'multipart/form-data; charset=utf-8; boundary=/');
  UTL_HTTP.SET_HEADER (r      =>   req,
                       name   =>   'Content-Length',
                       value  =>   v_param_length);
  UTL_HTTP.WRITE_TEXT (r      =>   req,
                       data   =>   v_param);

     resp := UTL_HTTP.GET_RESPONSE(req);
  LOOP
    UTL_HTTP.READ_LINE(resp, value, TRUE);
    DBMS_OUTPUT.PUT_LINE(value);
  END LOOP;
  UTL_HTTP.END_RESPONSE(resp);
EXCEPTION
  WHEN UTL_HTTP.END_OF_BODY THEN
    UTL_HTTP.END_RESPONSE(resp);
END;

Here is an example with CURL :

curl -v -X POST -H "Content-Type: multipart/form-data" -F "art=11111" -F "qty=1" http://local/api/ws

This example works fine with curl but i don't know why it doesn't in PL/SQL.
Can you help me ?

Body:
I don't think you can use a POST with GET query like you do in the URL...

It looks quite difficult to do what you expect. Here is some input from Ask Tom:

The idea is to generate the  post text, including a specific "boundary", which will look like this:

POST /path/to/script.php HTTP/1.0
Host: example.com
Content-type: multipart/form-data, boundary=AaB03x
Content-Length: $requestlen

--AaB03x
content-disposition: form-data; name="field1"

$field1
--AaB03x
content-disposition: form-data; name="field2"

$field2
--AaB03x
content-disposition: form-data; name="userfile"; filename="$filename"
Content-Type: $mimetype
Content-Transfer-Encoding: binary

$binarydata
--AaB03x--

There is also same issue developed here with lots of code.

Hope it helps.


问:
Is creating instances of a class inside a static PageMethod thread safe?
I am using jQuery to call PageMethods.  For certain operations, the current user credentials must be validated and for other operations, I need to call other static methods.  Here is some sample code:

Sample #1

```<code>[WebMethod]
public static void PostComment(string comment)
{
    UserAuth auth = new UserAuth();
    if (auth.isAuthenticated)
        {
            //Post comment here...
        }
}
</code>```

Sample #2

```<code>[WebMethod]
public static string GetComment(int commentId)
{

    commentDto comment = //get comment data from the database...
    string friendlyDate = ConvertFriendlyDate(comment.commentDate);

    return friendlyDate + " " + comment.text;
}

public static string ConvertFriendlyDate(DateTime commentDate)
{
    string friendlyDate = //call static utility method to convert date to friendly format

    return friendlyDate;

}
</code>```

Will I be safe using these kinds of operations?

Am I better to drop page methods and just call a separate ASPX page for my AJAX requests?

答: see if your class  is immutable that menas no one can change its state if it is changed it will be new instance than you won't need to worry about threading issues but if you are changing some shared state than you should think about synchronization but i don't think you need any thread synchronization in your case.</p>

Body:
I am using jQuery to call PageMethods.  For certain operations, the current user credentials must be validated and for other operations, I need to call other static methods.  Here is some sample code:

Sample #1

[WebMethod]
public static void PostComment(string comment)
{
    UserAuth auth = new UserAuth();
    if (auth.isAuthenticated)
        {
            //Post comment here...
        }
}

Sample #2

[WebMethod]
public static string GetComment(int commentId)
{

    commentDto comment = //get comment data from the database...
    string friendlyDate = ConvertFriendlyDate(comment.commentDate);

    return friendlyDate + " " + comment.text;
}

public static string ConvertFriendlyDate(DateTime commentDate)
{
    string friendlyDate = //call static utility method to convert date to friendly format

    return friendlyDate;

}

Will I be safe using these kinds of operations?

Am I better to drop page methods and just call a separate ASPX page for my AJAX requests?


问:
ValueError: Axes instance argument was not found in a figure
I am studying scikit-learn with 'Learning scikit-learn: Machine Learning in Python by Raúl Garreta'.

In jupyter Notebook, from code In[1] to In[7] it works. But In[8] code does not work. Which is wrong?

```<code># In[1]:
from sklearn import datasets
iris = datasets.load_iris()
X_iris, y_iris = iris.data, iris.target
print X_iris.shape, y_iris.shape

# In[2]:
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing
X, y = X_iris[:, :2], y_iris
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=33)
print X_train.shape, y_train.shape

# In[3]:
scaler = preprocessing.StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

# In[4]:
get_ipython().magic(u'matplotlib inline')
import matplotlib
from matplotlib import pylab
import numpy as np
import matplotlib.pyplot as plt
colors = ['red', 'greenyellow', 'blue']
for i in xrange(len(colors)):
    xs = X_train[:,0][y_train == i]
    ys = X_train[:,1][y_train == i]
    plt.scatter(xs, ys, c=colors[i])
plt.legend(iris.target_names)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')

# In[5]:
from sklearn.linear_model import SGDClassifier
clf = SGDClassifier()
clf.fit(X_train, y_train)

# In[6]:
print clf.coef_

# In[7]:
print clf.intercept_
</code>```

Codes in In[8] does not work.

```<code># In[8]:
x_min, x_max = X_train[:,0].min() - .5, X_train[:,0].max() +.5
y_min, y_max = X_train[:,1].min() - .5, X_train[:,1].max() +.5
xs = np.arange(x_min, x_max, 0.5)
fig, axes = plt.subplots(1,3)
fig.set_size_inches(10, 6)
for i in [0, 1, 2]:
    axes[i].set_aspect('equal')
    axes[i].set_title('Class '+ str(i) + ' versus the rest')
    axes[i].set_xlabel('Sepal length')
    axes[i].set_ylabel('Sepal width')
    axes[i].set_xlim(x_min, x_max)
    axes[i].set_ylim(y_min, y_max)
    pylab.sca(axes[i])
    plt.scatter(X_train[:,0], X_train[:, 1], c=y_train, cmap=plt.cm.prism)
    ys = (-clf.intercept_[i] - xs * clf.coef_[i, 0]) / clf.coef_[i, 1]
    plt.plot(xs, ys, hold=True)
    plt.show()
</code>```

The below error message appears when running.

答:
plt.sca(axes[i])

that would be ok

Body:
I am studying scikit-learn with 'Learning scikit-learn: Machine Learning in Python by Raúl Garreta'.

In jupyter Notebook, from code In[1] to In[7] it works. But In[8] code does not work. Which is wrong?

# In[1]:
from sklearn import datasets
iris = datasets.load_iris()
X_iris, y_iris = iris.data, iris.target
print X_iris.shape, y_iris.shape

# In[2]:
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing
X, y = X_iris[:, :2], y_iris
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=33)
print X_train.shape, y_train.shape

# In[3]:
scaler = preprocessing.StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

# In[4]:
get_ipython().magic(u'matplotlib inline')
import matplotlib
from matplotlib import pylab
import numpy as np
import matplotlib.pyplot as plt
colors = ['red', 'greenyellow', 'blue']
for i in xrange(len(colors)):
    xs = X_train[:,0][y_train == i]
    ys = X_train[:,1][y_train == i]
    plt.scatter(xs, ys, c=colors[i])
plt.legend(iris.target_names)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')

# In[5]:
from sklearn.linear_model import SGDClassifier
clf = SGDClassifier()
clf.fit(X_train, y_train)

# In[6]:
print clf.coef_

# In[7]:
print clf.intercept_

Codes in In[8] does not work.

# In[8]:
x_min, x_max = X_train[:,0].min() - .5, X_train[:,0].max() +.5
y_min, y_max = X_train[:,1].min() - .5, X_train[:,1].max() +.5
xs = np.arange(x_min, x_max, 0.5)
fig, axes = plt.subplots(1,3)
fig.set_size_inches(10, 6)
for i in [0, 1, 2]:
    axes[i].set_aspect('equal')
    axes[i].set_title('Class '+ str(i) + ' versus the rest')
    axes[i].set_xlabel('Sepal length')
    axes[i].set_ylabel('Sepal width')
    axes[i].set_xlim(x_min, x_max)
    axes[i].set_ylim(y_min, y_max)
    pylab.sca(axes[i])
    plt.scatter(X_train[:,0], X_train[:, 1], c=y_train, cmap=plt.cm.prism)
    ys = (-clf.intercept_[i] - xs * clf.coef_[i, 0]) / clf.coef_[i, 1]
    plt.plot(xs, ys, hold=True)
    plt.show()

The below error message appears when running.

Body:
plt.sca(axes[i])

that would be ok


问:
How to create SQL multiple count count query by date?
I have a query that selects counts group by department.

```<code>select department, count(*) group by department
</code>```

This returns two columns data result. I wonder if select cout, count by today and count by this month same query.

```<code>Department  Total  Today  ThisMonth
AAA         40     8      23
BBB         20     6      11
</code>```

答:
Comparison of datecoulmn with getdate() should be by MMYYYY to get ThisMonth total.</p>

```<code>select department,count(*) as Total,
sum(case when convert(varchar,datecolumn,106)= convert(varchar,GETDATE(),106) then 1 else 0 end) as Today,
sum(case when cast(month(datecolumn) as varchar) + cast(year(datecolumn) as varchar)  = cast(year(GETDATE()) as varchar) + cast(year(GETDATE()) as varchar)  then 1 else 0 end) as ThisMonth
from YourTable
group by department
</code>```

Body:
I have a query that selects counts group by department.

select department, count(*) group by department

This returns two columns data result. I wonder if select cout, count by today and count by this month same query.

Department  Total  Today  ThisMonth
AAA         40     8      23
BBB         20     6      11

Body:
Comparison of datecoulmn with getdate() should be by MMYYYY to get ThisMonth total.

select department,count(*) as Total,
sum(case when convert(varchar,datecolumn,106)= convert(varchar,GETDATE(),106) then 1 else 0 end) as Today,
sum(case when cast(month(datecolumn) as varchar) + cast(year(datecolumn) as varchar)  = cast(year(GETDATE()) as varchar) + cast(year(GETDATE()) as varchar)  then 1 else 0 end) as ThisMonth
from YourTable
group by department