问:
Cannot start bundle programmatically
Note: In my case, I'm using Apache Felix implementation if that's matters.

I have written bundle which I'm using as test. It's very simple "Hello World" bundle that do nothing more than print message to stdout when started/stopped:

```<code>public class Activator implements BundleActivator {

    @Override
    public void start(BundleContext context) throws Exception {
        System.out.println("Hello, World.");
    }

    @Override
    public void stop(BundleContext context) throws Exception {
        System.out.println("Goodbye, World.");
    }

}
</code>```

There is also MANIFEST file which rather pointless to post since when I deploy above bundle through Apache Felix console from standard distribution (which can be downloaded here) bundle starts and print out message.

Next step I'm trying to do is deploy the very same bundle using programmatic approach. Unfortunately this is not working for me. My code looks as follow:

```<code>public static void main(String[] args) throws Exception {
    FrameworkFactory frameworkFactory = getFrameworkFactory();
    Framework framework = frameworkFactory.newFramework(null);

    System.out.println("BundleID = " + framework.getBundleId());
    System.out.println("State = " + getState(framework.getState()));

    framework.init();

    System.out.println("BundleID = " + framework.getBundleId());
    System.out.println("State = " + getState(framework.getState()));

    BundleContext bundleContext = framework.getBundleContext();
    bundleContext.addBundleListener((event) -> {
        System.out.println("Bundle Changed Event");
    });
    bundleContext.addFrameworkListener((event) -> {
        System.out.println("Framework Event");
    });
    bundleContext.addServiceListener((event) -> {
        System.out.println("Service Changed Event");
    });

    Bundle bundle = bundleContext.installBundle("file://<absolute-path-to-bundle-jar-same-as-above");

    System.out.println("BundleID = " + bundle.getBundleId());
    System.out.println("State = " + getState(bundle.getState()));

    bundle.start();

    System.out.println("BundleID = " + bundle.getBundleId());
    System.out.println("State = " + getState(bundle.getState()));
}

private static FrameworkFactory getFrameworkFactory() throws IllegalStateException {
    ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class);

    FrameworkFactory factory = null;
    for (FrameworkFactory iterator : loader) {
        if (factory != null) {
            throw new IllegalStateException("Ambiguous SPI implementations.");
        }

        factory = iterator;
    }

    return factory;
}

private static String getState(int state) {
    switch (state) {
    case Bundle.UNINSTALLED:
        return "UNINSTALLED";
    case Bundle.INSTALLED:
        return "INSTALLED";
    case Bundle.RESOLVED:
        return "RESOLVED";
    case Bundle.STARTING:
        return "STARTING";
    case Bundle.STOPPING:
        return "STOPPING";
    case Bundle.ACTIVE:
        return "ACTIVE";
    default:
        throw new IllegalStateException("Unknown state");
    }
}
</code>```

The output looks like follow:

```<code>BundleID = 0
State = INSTALLED
BundleID = 0
State = STARTING
Bundle Changed Event
BundleID = 1
State = INSTALLED
BundleID = 1
State = INSTALLED
</code>```

So as far as I understand bundle got installed but last 4 lines indicate that bundle.start() got ignored for some reason.

Could you point out me what am I missing to make this work?

答:
After hour of debugging and reading through javadoc more carefully this is happening because framework was only initialized instead of being started. To make example work you have to simply  add framework.start() after framework.init() (or just call framwork.start() which calls framework.init() if found it necessary).

I'm leaving this information as there are few confusing things:

Official documentation to Apache Felix have information about embedding framework into host application. Unfortunately there is only example that use Apache Felix custom mechanisms that make it not portable to other implementations. What is confusing is warning note which if you want to create portable solution you should use init() and getBundleContext(). Whole note cited bellow:

WARNING The felix.systembundle.activators configuration property is specific to the Felix framework implementation. If you want your code to work with other framework implementations, you should call init() on the framework instance and use getBundleContext() directly. Otherwise, the approach would be very similar.

JavaDoc for parameterless version of init() method do not mention about initialization is not same as starting the framework, although init(FrameworkListener...) have such information.

This Framework will not actually be started until start is called.

Title: Cannot start bundle programmatically

Body:
Note: In my case, I'm using Apache Felix implementation if that's matters.

I have written bundle which I'm using as test. It's very simple "Hello World" bundle that do nothing more than print message to stdout when started/stopped:

public class Activator implements BundleActivator {

    @Override
    public void start(BundleContext context) throws Exception {
        System.out.println("Hello, World.");
    }

    @Override
    public void stop(BundleContext context) throws Exception {
        System.out.println("Goodbye, World.");
    }

}

There is also MANIFEST file which rather pointless to post since when I deploy above bundle through Apache Felix console from standard distribution (which can be downloaded here) bundle starts and print out message.

Next step I'm trying to do is deploy the very same bundle using programmatic approach. Unfortunately this is not working for me. My code looks as follow:

public static void main(String[] args) throws Exception {
    FrameworkFactory frameworkFactory = getFrameworkFactory();
    Framework framework = frameworkFactory.newFramework(null);

    System.out.println("BundleID = " + framework.getBundleId());
    System.out.println("State = " + getState(framework.getState()));

    framework.init();

    System.out.println("BundleID = " + framework.getBundleId());
    System.out.println("State = " + getState(framework.getState()));

    BundleContext bundleContext = framework.getBundleContext();
    bundleContext.addBundleListener((event) -> {
        System.out.println("Bundle Changed Event");
    });
    bundleContext.addFrameworkListener((event) -> {
        System.out.println("Framework Event");
    });
    bundleContext.addServiceListener((event) -> {
        System.out.println("Service Changed Event");
    });

    Bundle bundle = bundleContext.installBundle("file://<absolute-path-to-bundle-jar-same-as-above");

    System.out.println("BundleID = " + bundle.getBundleId());
    System.out.println("State = " + getState(bundle.getState()));

    bundle.start();

    System.out.println("BundleID = " + bundle.getBundleId());
    System.out.println("State = " + getState(bundle.getState()));
}

private static FrameworkFactory getFrameworkFactory() throws IllegalStateException {
    ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class);

    FrameworkFactory factory = null;
    for (FrameworkFactory iterator : loader) {
        if (factory != null) {
            throw new IllegalStateException("Ambiguous SPI implementations.");
        }

        factory = iterator;
    }

    return factory;
}

private static String getState(int state) {
    switch (state) {
    case Bundle.UNINSTALLED:
        return "UNINSTALLED";
    case Bundle.INSTALLED:
        return "INSTALLED";
    case Bundle.RESOLVED:
        return "RESOLVED";
    case Bundle.STARTING:
        return "STARTING";
    case Bundle.STOPPING:
        return "STOPPING";
    case Bundle.ACTIVE:
        return "ACTIVE";
    default:
        throw new IllegalStateException("Unknown state");
    }
}

The output looks like follow:

BundleID = 0
State = INSTALLED
BundleID = 0
State = STARTING
Bundle Changed Event
BundleID = 1
State = INSTALLED
BundleID = 1
State = INSTALLED

So as far as I understand bundle got installed but last 4 lines indicate that bundle.start() got ignored for some reason.

Could you point out me what am I missing to make this work?


来源: stackexchange

问:
Code stuck in loop
I made a script that takes a picture, starts from the top left corner (a white pixel in the case of my test image), and proceeds to go through the image like a magic wand tool, selecting the pixels that are of a similar enough color.

But the script doesn't finish executing even after going through the loop more times than there are pixels in the image.

The test image is roughly 160K pixels. Tools.loadImage() is a self-written method. I've used it elsewhere, it most probably works. The following is not the entirety of my code, but the part that seemed relevant to the problem.

```<code>static int[][][] image;

public static void main(String[] args) {
    image = Tools.loadImage(path1);

    int height = image.length;
    int width = image[0].length;
    int[][][] newImage = new int[height][width][4];

    ArrayList<Integer> toCheck = new ArrayList<Integer>();
    ArrayList<Integer> checked = new ArrayList<Integer>();

    int[] baseColor = image[0][0];
    toCheck.add(0);

    while (!toCheck.isEmpty()) {
        i++;
        int coords = toCheck.get(0);
        int x = coords % width;
        int y = coords / width;

        if (check(x, y, baseColor, 128)) {
            coords = y * width + x - 1;
            if (x > 0 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = y * width + x + 1;
            if (x < width - 1 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = (y - 1) * width + x;
            if (y > 0 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = (y + 1) * width + x;
            if (y < height - 1 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
        }

        checked.add(coords);
        toCheck.remove(0);
    }
}

static boolean check(int x, int y, int[] color, int threshold) {
    for (int i = 0; i < 3; i++) {
        if (Math.abs(image[y][x][i] - color[i]) > threshold) {
            return false;
        }
    }
    return true;
}
</code>```

PS. If you feel like pointing out obvious ways to make this loop faster, that would be appreciated as well.

答:
You're overwriting coords in the body of the loop, so at the end of each iteration you're marking the wrong pixel.  It's perfectly safe to move the marking immediately after popping the next point off toCheck.

Perfomance-wise, consider using a BitSet for checked (as per @JB Nizet's suggestion,) and an ArrayDeque for toCheck.

ContentLicense: CC BY-SA 3.0

Title: Code stuck in loop

Body:
I made a script that takes a picture, starts from the top left corner (a white pixel in the case of my test image), and proceeds to go through the image like a magic wand tool, selecting the pixels that are of a similar enough color.

But the script doesn't finish executing even after going through the loop more times than there are pixels in the image.

The test image is roughly 160K pixels. Tools.loadImage() is a self-written method. I've used it elsewhere, it most probably works. The following is not the entirety of my code, but the part that seemed relevant to the problem.

static int[][][] image;

public static void main(String[] args) {
    image = Tools.loadImage(path1);

    int height = image.length;
    int width = image[0].length;
    int[][][] newImage = new int[height][width][4];

    ArrayList<Integer> toCheck = new ArrayList<Integer>();
    ArrayList<Integer> checked = new ArrayList<Integer>();

    int[] baseColor = image[0][0];
    toCheck.add(0);

    while (!toCheck.isEmpty()) {
        i++;
        int coords = toCheck.get(0);
        int x = coords % width;
        int y = coords / width;

        if (check(x, y, baseColor, 128)) {
            coords = y * width + x - 1;
            if (x > 0 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = y * width + x + 1;
            if (x < width - 1 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = (y - 1) * width + x;
            if (y > 0 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = (y + 1) * width + x;
            if (y < height - 1 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
        }

        checked.add(coords);
        toCheck.remove(0);
    }
}

static boolean check(int x, int y, int[] color, int threshold) {
    for (int i = 0; i < 3; i++) {
        if (Math.abs(image[y][x][i] - color[i]) > threshold) {
            return false;
        }
    }
    return true;
}

PS. If you feel like pointing out obvious ways to make this loop faster, that would be appreciated as well.


问:
SQL Server and asp.net application security models / best practice
For my asp.net web applications against sql server(at least the ones that require a logon to access) I generally implement security as follows:

I generally roll my own user signup, user login pages and keep a userid and an encrypted password in an sql server and validate the login against that table - I also provide for forgotten passwords, 'send me my password', email verification to activate accounts etc all thru custom code.

Once the user has been validated by the app (and lets assume that all users have the same privileges), I generally use a utility logonid to let asp.net talk to sql server, so in other words I only need to create a single logon id per application, and since 100% of all data access is done thru stored procedures, I need only grant access to a single user to execute stored procedures, and no other work is required on sql server. Each application has its own database, and the logon for that app can only access that database.

All this works perfectly well for me, the only negative of this is that it would be nice to be able to setup a trace in sql server and see the userid and the procs that are being called, but since all users are 'talking' to the database thru a single database logon, this can't happen.

So, two part question:

1) Are there security models are you folks using that I should consider? Its easy to always do the same thing over and over, - especially since it works - but are there other models that would work better or that I should consider? Is it recommended practice that all database access from an asp.net app would all share a single database login? or is this considered bad practice? and if so, why?

2) Assuming I stick with my model, is there a way to allow for the application login id to be seen in the sql trace window? It would be nice to see the sp's being called and the user id of the person logged into the system (not the database login).

答:
1)As long as you are using stored procedures for access one login may be fine.  Some peolple like to use one for admin as well.

2)You could modify your stored procedures to accept a user id as a parameter.

OwnerDisplayName: E.J. Brennan

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Sam


问:
blank PNG UIImageView
Hopefully a quick one for someone?! I am TOTALLY at a loss.
I have two images,

p1-slide01.png and p3-slide01.png

Both PNG images open in Preview and when I click on them in Xcode, I see them. They are there. They are in the right folder etc.

Yet, when I do myImage.image = [UIImage imageNamed:@"p1-slide01.png"] it doesn't work. It does however work for p3-slide01.png. The code is no different. I have generated the PNG images via an export in PowerPoint. They look fine everywhere.

Does anyone know what I might be doing wrong?! The UIImageViews are declared and retained in the .h file.

[UPDATE] - I renamed the image to "testy.png" and it loaded. Yet when I changed it back to the original p1-slide01.png - it comes up blank. It's like there are cached images somewhere (I've used these file names in another app?!) - do I just need to change file names?!

答: Also, change them to JPEGs and see if that makes a difference.</p>

Title: blank PNG UIImageView


问:
Read existing SMS using Xamarin Forms
I am new to Xamarin. Can someone point me to a way to read existing SMSs using Xamarin Forms.
I know we can do it using Android specific libraries (and probably with iOS specific libraries as well). But, I want to use a library that will help me avoid using platform specific library.</p>

答:
You will have to use platform specific code for this. Remember; all libraries out there actually are platform specific code but just offer you an abstraction. This includes Xamarin.Forms itself.

As mentioned by Jason in the comments, you aren't going to be able to do this on iOS altogether, they do not allow to read or sends texts directly. So you should probably rethink what you are trying to do.

Title: Read existing SMS using Xamarin Forms


问:
SQL WHERE Clause Condition Not working
This is my table:

```<code>City1      City2

London     New York
New York   London
Mumbai     London
New York   Mumbai
</code>```

This is, what i want:

If someone select: London + New York, then all the rows, which contain both London+New York will get displayed. No matter, what comes first.

I want this to display, if someone select: London & New York

```<code>London     New York
New York   London
</code>```

This is my current code:

```<code>WHERE City1='London' AND City2='New York';\
</code>```

It only display this:

```<code>London     New York
</code>```

答:
You can use WHERE IN():

```<code>WHERE City1 IN ('London','New York') AND City2 IN ('London','New York');
</code>```

If you like to don't select row if are same, you can try this:

```<code>WHERE City1 IN ('London','New York') AND City2 IN ('London','New York') and City1 != City2
</code>```

Title: SQL WHERE Clause Condition Not working

Body:
This is my table:

City1      City2

London     New York
New York   London
Mumbai     London
New York   Mumbai

This is, what i want:

If someone select: London + New York, then all the rows, which contain both London+New York will get displayed. No matter, what comes first.

I want this to display, if someone select: London & New York

London     New York
New York   London

This is my current code:

WHERE City1='London' AND City2='New York';\

It only display this:

London     New York

Body:
You can use WHERE IN():

WHERE City1 IN ('London','New York') AND City2 IN ('London','New York');

If you like to don't select row if are same, you can try this:

WHERE City1 IN ('London','New York') AND City2 IN ('London','New York') and City1 != City2


问:
localhost 3000 doesn't work
http://localhost:3000

Somehow I can't connect to above address but my app is accessible using

http://192.168.0.25:3000

I'm running this boilerplate. https://github.com/notrab/create-react-app-redux

I don't know what is wrong and this is my first time having this issue.

答: If you want to connect to localhost:3000 your server should use this ip address: 127.0.0.1:3000.</p>

Title: localhost 3000 doesn't work


问:
PHP session not transferring through frame redirect
I have a website set up for people to sign up for a small event.

After pressing submit on the
index.php I start my functions to insert their data into my DB and depending on if it works or not, set a session variable with the result in it. Like this:

part of the function:

```<code>$_SESSION['message'] = "That worked, thank you!";
header("location:thankyou.php")
exit();
</code>```

on the thankyou.php I do echo it like this:

```<code><?php  echo "<div id='content'><h1>".$_SESSION['message']."</h1></div>"; ?>
</code>```

Everything works locally.

Everything works hosted on my webspace.

But as this is an event for a students council, I did a frame redirect (to keep their domain in the browsers adressbar) to my domain. At this point, the session gets lost after I submit an entry. The thankyou.php stays empty.

I tried to check for the $_SESSION with a var_dump(), but it is completely empty.

Any hints on how to transfer the $_SESSION array while keeping the frame redirect would be really appreciated!

EDIT: session_start() is already there on every file.

答:
Essentially, you can regard the iframe as a new browser window, now displayed within the same page. You said:

I did a frame redirect (to keep their domain in the browsers adressbar) to my domain.

Which means you try to fool the user a bit. The way sessions usually work is with an session identifier that PHP uses to retrieve the session data. So either:

the session ID is not passed correctly (perhaps due to safety restrictions), you better check this first, use session_id() or the devtools from the browser to monitor http requests. It's possible that using the Location: header does not pass the session ID, it might even be browser specific.

the main window sets the session ID, there might be a mismatch between how sessions are stored in the iframe and the main window. First thing to check is the configuration.

Body:
I have a website set up for people to sign up for a small event.

After pressing submit on the
index.php I start my functions to insert their data into my DB and depending on if it works or not, set a session variable with the result in it. Like this:

part of the function:

$_SESSION['message'] = "That worked, thank you!";
header("location:thankyou.php")
exit();

on the thankyou.php I do echo it like this:

<?php  echo "

".$_SESSION['message']."

"; ?>

Everything works locally.

Everything works hosted on my webspace.

But as this is an event for a students council, I did a frame redirect (to keep their domain in the browsers adressbar) to my domain. At this point, the session gets lost after I submit an entry. The thankyou.php stays empty.

I tried to check for the $_SESSION with a var_dump(), but it is completely empty.

Any hints on how to transfer the $_SESSION array while keeping the frame redirect would be really appreciated!

EDIT: session_start() is already there on every file.


答:
you can use

```<code>WHERE (City1='London' AND City2='New York') or (City1='New York' AND City2='London')
</code>```

it is not the best solution but it might work;)

Title: SQL WHERE Clause Condition Not working

Body:
you can use

WHERE (City1='London' AND City2='New York') or (City1='New York' AND City2='London')

it is not the best solution but it might work;)


问:
Issue with preg_replace_callback_array
The function below checks for multiple regex parsed but its not working and i couldn't spot where am getting it wrong.</p>

```<code>function getig($string)
{
$string = preg_replace_callback_array(
[
    "/\[instagram=(.+?)\]/" => function($matches) {
    $pid=$matches[1];
    $result = fetchData("https://api.instagram.com/oembed/?url=$pid");
    $result = json_decode($result);
    return $result->html; },
    "/https?\:\/\/(?:www.)?instagram.com\/p\/(.+\/?)/" => function($matches)
{
    $pid=$matches[1];
    $urlen=urlencode($url);
    $result = fetchData("https://api.instagram.com/oembed/?url=https://instagr.am/p/$pid");
    $result = json_decode($result);
   return $result->html; },
    "#\[ig\](.*?)\[/ig\]#is" => function($matches) {
   $pid=$matches[1];
    $result = fetchData("https://api.instagram.com/oembed/?url=$pid");
  $result = json_decode($result);
 return $result->html; }
    ], $string);
  return $string;
 }
</code>```

答: There is no error in my code. Where am getting things wrong is that am on PHP5.6 and preg_replace_callback_array() only available in PHP7.</p>

Title: Issue with preg_replace_callback_array

Body:
The function below checks for multiple regex parsed but its not working and i couldn't spot where am getting it wrong.

function getig($string)
{
$string = preg_replace_callback_array(
[
    "/\[instagram=(.+?)\]/" => function($matches) {
    $pid=$matches[1];
    $result = fetchData("https://api.instagram.com/oembed/?url=$pid");
    $result = json_decode($result);
    return $result->html; },
    "/https?\:\/\/(?:www.)?instagram.com\/p\/(.+\/?)/" => function($matches)
{
    $pid=$matches[1];
    $urlen=urlencode($url);
    $result = fetchData("https://api.instagram.com/oembed/?url=https://instagr.am/p/$pid");
    $result = json_decode($result);
   return $result->html; },
    "#\[ig\](.*?)\[/ig\]#is" => function($matches) {
   $pid=$matches[1];
    $result = fetchData("https://api.instagram.com/oembed/?url=$pid");
  $result = json_decode($result);
 return $result->html; }
    ], $string);
  return $string;
 }


问:
User control click event not working when clicking on text inside control?
I have a user control called GameButton that has a label inside it. When I add the user control to my form, and add a click event to it, its triggered when you click on the background of the custom button, but not the text in the label? How would I fix this without adding a bunch of click events inside the user controls code?

edit: UI framework: winforms

答: Set the "enable" property of your labels "False, then mouse events will work in user control.</p>

ContentLicense: CC BY-SA 4.0


问:
How to select data from EAV structure with multiple values
Here is my sql structure

```<code>CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) unsigned NOT NULL,
  `sku` varchar(32) NOT NULL,
  `name` tinytext NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=409 ;

INSERT INTO `products` (`id`, `sku`, `name`, `created_at`, `updated_at`) VALUES
(1, '111', 'Item 1', '', '0000-00-00 00:00:00'),
(2, '222', 'Item 2', '', '0000-00-00 00:00:00'),
(3, '333', 'Item 3', '', '0000-00-00 00:00:00');

CREATE TABLE IF NOT EXISTS `product_attributes` (
`id` int(10) unsigned NOT NULL,
  `attribute_id` int(10) unsigned NOT NULL,
  `value_id` int(10) unsigned NOT NULL,
  `product_id` int(10) unsigned NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4820 ;

INSERT INTO `product_attributes` (`id`, `attribute_id`, `value_id`, `product_id`) VALUES
(1, 11, 1, 1),
(2, 12, 2, 1),
(3, 13, 3, 1),
(4, 11, 1, 2),
(5, 12, 5, 2),
(6, 13, 6, 2),
(7, 11, 1, 3),
(8, 12, 8, 3),
(9, 13, 3, 3);
</code>```

I want to select products with n selected values. For example ((attribute_id=11 AND value_id=1) AND (attribute_id=13 AND value_id=3)). I expect to get product 1 and 3.

Try this query, but no luck

```<code>select
    p.id,
    p.name,
    pa.attribute_id,
    pa.value_id
FROM products p
JOIN product_attributes pa
ON p.id=pa.product_id
WHERE ((pa.attribute_id=11 AND pa.value_id=1) AND (pa.attribute_id=13 AND pa.value_id=3))
</code>```

答:
With the query you have in your question, the where clause will never be true because for a single row, attribute_id will never equal both 11 and 13 while value_id = both 1 and 3.

Try this:

```<code>select
    p.id,
    p.name,
    pa1.attribute_id,
    pa1.value_id,
    pa2.attribute_id,
    pa2.value_id
FROM products p
JOIN product_attributes pa1
ON p.id = pa1.product_id
JOIN product_attributes pa2
ON p.id = pa2.product_id
WHERE ((pa1.attribute_id=11 AND pa1.value_id=1) AND (pa2.attribute_id=13 AND pa2.value_id=3))
</code>```

It joins to the attribute table twice so you can separate the two conditions and test for both being true.

Body:
Here is my sql structure

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) unsigned NOT NULL,
  `sku` varchar(32) NOT NULL,
  `name` tinytext NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=409 ;

INSERT INTO `products` (`id`, `sku`, `name`, `created_at`, `updated_at`) VALUES
(1, '111', 'Item 1', '', '0000-00-00 00:00:00'),
(2, '222', 'Item 2', '', '0000-00-00 00:00:00'),
(3, '333', 'Item 3', '', '0000-00-00 00:00:00');

CREATE TABLE IF NOT EXISTS `product_attributes` (
`id` int(10) unsigned NOT NULL,
  `attribute_id` int(10) unsigned NOT NULL,
  `value_id` int(10) unsigned NOT NULL,
  `product_id` int(10) unsigned NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4820 ;

INSERT INTO `product_attributes` (`id`, `attribute_id`, `value_id`, `product_id`) VALUES
(1, 11, 1, 1),
(2, 12, 2, 1),
(3, 13, 3, 1),
(4, 11, 1, 2),
(5, 12, 5, 2),
(6, 13, 6, 2),
(7, 11, 1, 3),
(8, 12, 8, 3),
(9, 13, 3, 3);

I want to select products with n selected values. For example ((attribute_id=11 AND value_id=1) AND (attribute_id=13 AND value_id=3)). I expect to get product 1 and 3.

Try this query, but no luck

select
    p.id,
    p.name,
    pa.attribute_id,
    pa.value_id
FROM products p
JOIN product_attributes pa
ON p.id=pa.product_id
WHERE ((pa.attribute_id=11 AND pa.value_id=1) AND (pa.attribute_id=13 AND pa.value_id=3))

Body:
With the query you have in your question, the where clause will never be true because for a single row, attribute_id will never equal both 11 and 13 while value_id = both 1 and 3.

Try this:

select
    p.id,
    p.name,
    pa1.attribute_id,
    pa1.value_id,
    pa2.attribute_id,
    pa2.value_id
FROM products p
JOIN product_attributes pa1
ON p.id = pa1.product_id
JOIN product_attributes pa2
ON p.id = pa2.product_id
WHERE ((pa1.attribute_id=11 AND pa1.value_id=1) AND (pa2.attribute_id=13 AND pa2.value_id=3))

It joins to the attribute table twice so you can separate the two conditions and test for both being true.


问:
C++ chrono Difference between 2 time clocks in seconds
I want to find the difference between 2 time clocks using chrono library in seconds. I tried various ways, Following is one among them. All of them works fine till the difference is 59 seconds but times out after that. I really need the actual value of difference even if it is more than 59 seconds

```<code>#include <iostream>
#include <chrono>
#include <thread>

int main ()
{
    using std::chrono::system_clock;
   using std::chrono::milliseconds;
   using std::chrono::seconds;
   using std::chrono::duration_cast;
   const auto duration = milliseconds(1000);
   const auto start = system_clock::now();

   for(int i=0; i<65; i++)
   {
       std::this_thread::sleep_for(duration);
   const auto stop = system_clock::now();

   const auto difference = std::chrono::duration_cast<seconds>(stop - start).count();

   std::cout << "Difference is =>" << difference << std::endl;

   }
}
</code>```

The above outputs the difference till 59 and times out after that. Whats going on wrong here?

答:
This code works fine: I could compile and execute it succesfully on macOs with Xcode and on Wingdows with MSVC2017, getting timings until 65 as expected.

Durations in seconds are not limited to 60 by std::chrono. std::chrono::seconds are just a unit of measure.  You can even find out the maximum number of seconds that could be counted this way. Of course, there are system dependent limits, but these are far above 60:

```<code>std::cout << "Max is "
    << std::chrono::duration_cast<seconds>(start-start).max().count() << std::endl;
</code>```

I also get the expected result ideone (online demo), with timings between 60 and 65.  But ideone has an execution time limit of around 10 seconds so that it first timed out.  So I had to adjust your code by substracting 55 seconds from the start time:

```<code>const auto start = system_clock::now()-milliseconds(55000);
</code>```

There's no reason for your code to fail, except a compiler/library dependent bug.

Body:
I want to find the difference between 2 time clocks using chrono library in seconds. I tried various ways, Following is one among them. All of them works fine till the difference is 59 seconds but times out after that. I really need the actual value of difference even if it is more than 59 seconds

#include <iostream>
#include <chrono>
#include <thread>

int main ()
{
    using std::chrono::system_clock;
   using std::chrono::milliseconds;
   using std::chrono::seconds;
   using std::chrono::duration_cast;
   const auto duration = milliseconds(1000);
   const auto start = system_clock::now();

   for(int i=0; i<65; i++)
   {
       std::this_thread::sleep_for(duration);
   const auto stop = system_clock::now();

   const auto difference = std::chrono::duration_cast<seconds>(stop - start).count();

   std::cout << "Difference is =>" << difference << std::endl;

   }
}

The above outputs the difference till 59 and times out after that. Whats going on wrong here?

Body:
This code works fine: I could compile and execute it succesfully on macOs with Xcode and on Wingdows with MSVC2017, getting timings until 65 as expected.

Durations in seconds are not limited to 60 by std::chrono. std::chrono::seconds are just a unit of measure.  You can even find out the maximum number of seconds that could be counted this way. Of course, there are system dependent limits, but these are far above 60:

std::cout << "Max is "
    << std::chrono::duration_cast<seconds>(start-start).max().count() << std::endl;

I also get the expected result ideone (online demo), with timings between 60 and 65.  But ideone has an execution time limit of around 10 seconds so that it first timed out.  So I had to adjust your code by substracting 55 seconds from the start time:

const auto start = system_clock::now()-milliseconds(55000);

There's no reason for your code to fail, except a compiler/library dependent bug.


问:
Ruby on Rails: How to add a form text field if the corresponding filed in the model doesn't exist?
I have the following models:

```<code>Product: name, shop_id (foreign key)
Shop:    name
</code>```

The associations are:

```<code>Product: belongs_to :shop
Shop:    has_many   :products
</code>```

In the form that creates a new Product I have:

```<code><%= f.label(:shop, "Shop:") %>
<%= f.select(...) %>
</code>```

This is a select box with all existing shops. The last option in this select box is Create New Shop. When user clicks this option, Javascript shows an extra field:

```<code><div id="new_shop_wrapper">
    <label for="new_shop">New shop:</label>
    <input id="new_shop" name="new_shop" type="text" />
</div>
</code>```

(This div is hidden by default with display: none.)

How should I add this div in the Rails form creation ?

I tried:

```<code><%= f.label(:new_shop, "New Shop:") %>
<%= f.text_field(:new_shop) %>
</code>```

but it doesn't work because new_shop is not Product's field.

I thought to use:

```<code><%= text_field(<object>, :new_shop) %>
</code>```

but I don't know what  to use.

Please advise.

答:
Try</p>

```<code><%= text_field_tag("new_shop") %>
</code>```

Body:
I have the following models:

Product: name, shop_id (foreign key)
Shop:    name

The associations are:

Product: belongs_to :shop
Shop:    has_many   :products

In the form that creates a new Product I have:

<%= f.label(:shop, "Shop:") %>
<%= f.select(...) %>

This is a select box with all existing shops. The last option in this select box is Create New Shop. When user clicks this option, Javascript shows an extra field:

    New shop:
    <input id="new_shop" name="new_shop" type="text" />

(This div is hidden by default with display: none.)

How should I add this div in the Rails form creation ?

I tried:

<%= f.label(:new_shop, "New Shop:") %>
<%= f.text_field(:new_shop) %>

but it doesn't work because new_shop is not Product's field.

I thought to use:

<%= text_field(<object>, :new_shop) %>

but I don't know what  to use.

Please advise.

Body:
Try

<%= text_field_tag("new_shop") %>


问:
Serializing PHP object to JSON
So I was wandering around php.net for information about serializing PHP objects to JSON, when I stumbled across the new JsonSerializable Interface. It's only PHP >= 5.4 though, and I'm running in a 5.3.x environment.

How is this sort of functionality achieved PHP < 5.4?

I've not worked much with JSON yet, but I'm trying to support an API layer in an application, and dumping the data object (that would otherwise be sent to the view) into JSON would be perfect.

If I attempt to serialize the object directly, it returns an empty JSON string; which is because I assume json_encode() doesn't know what the heck to do with the object. Should I recursively reduce the object into an array, and then encode that?

Example

```<code>$data = new Mf_Data();
$data->foo->bar['hello'] = 'world';
</code>```

echo json_encode($data) produces an empty object:

```<code>{}
</code>```

var_dump($data) however, works as expected:

```<code>object(Mf_Data)#1 (5) {
  ["_values":"Mf_Data":private]=>
  array(0) {
  }
  ["_children":"Mf_Data":private]=>
  array(1) {
    [0]=>
    array(1) {
      ["foo"]=>
      object(Mf_Data)#2 (5) {
        ["_values":"Mf_Data":private]=>
        array(0) {
        }
        ["_children":"Mf_Data":private]=>
        array(1) {
          [0]=>
          array(1) {
            ["bar"]=>
            object(Mf_Data)#3 (5) {
              ["_values":"Mf_Data":private]=>
              array(1) {
                [0]=>
                array(1) {
                  ["hello"]=>
                  string(5) "world"
                }
              }
              ["_children":"Mf_Data":private]=>
              array(0) {
              }
              ["_parent":"Mf_Data":private]=>
              *RECURSION*
              ["_key":"Mf_Data":private]=>
              string(3) "bar"
              ["_index":"Mf_Data":private]=>
              int(0)
            }
          }
        }
        ["_parent":"Mf_Data":private]=>
        *RECURSION*
        ["_key":"Mf_Data":private]=>
        string(3) "foo"
        ["_index":"Mf_Data":private]=>
        int(0)
      }
    }
  }
  ["_parent":"Mf_Data":private]=>
  NULL
  ["_key":"Mf_Data":private]=>
  NULL
  ["_index":"Mf_Data":private]=>
  int(0)
}
</code>```

Addendum

1)

So this is the toArray() function I've devised for the Mf_Data class:

```<code>public function toArray()
{
    $array = (array) $this;
    array_walk_recursive($array, function (&$property) {
        if ($property instanceof Mf_Data) {
            $property = $property->toArray();
        }
    });
    return $array;
}
</code>```

However since the Mf_Data objects also have a reference to their parent (containing) object, this fails with recursion. Works like a charm though when I remove the _parent reference.

2)

Just to follow up, the final function to transform a complex tree-node object I went with was:

```<code>// class name - Mf_Data
// exlcuded properties - $_parent, $_index
public function toArray()
{
    $array = get_object_vars($this);
    unset($array['_parent'], $array['_index']);
    array_walk_recursive($array, function (&$property) {
        if (is_object($property) && method_exists($property, 'toArray')) {
            $property = $property->toArray();
        }
    });
    return $array;
}
</code>```

3)

I'm following up again, with a bit cleaner of an implementation. Using interfaces for an instanceof check seems much cleaner than method_exists() (however method_exists() does cross-cut inheritance/implementation).

Using unset() seemed a bit messy too, and it seems that logic should be refactored into another method. However, this implementation does copy the property array (due to array_diff_key), so something to consider.

```<code>interface ToMapInterface
{

    function toMap();

    function getToMapProperties();

}

class Node implements ToMapInterface
{

    private $index;
    private $parent;
    private $values = array();

    public function toMap()
    {
        $array = $this->getToMapProperties();
        array_walk_recursive($array, function (&$value) {
            if ($value instanceof ToMapInterface) {
                $value = $value->toMap();
            }
        });
        return $array;
    }

    public function getToMapProperties()
    {
        return array_diff_key(get_object_vars($this), array_flip(array(
            'index', 'parent'
        )));
    }

}
</code>```

答:
My version:

```<code>json_encode(self::toArray($ob))
</code>```

Implementation:

```<code>private static function toArray($object) {
    $reflectionClass = new \ReflectionClass($object);

    $properties = $reflectionClass->getProperties();

    $array = [];
    foreach ($properties as $property) {
        $property->setAccessible(true);
        $value = $property->getValue($object);
        if (is_object($value)) {
            $array[$property->getName()] = self::toArray($value);
        } else {
            $array[$property->getName()] = $value;
        }
    }
    return $array;
}
</code>```

JsonUtils : GitHub

Title: Serializing PHP object to JSON

Body:
So I was wandering around php.net for information about serializing PHP objects to JSON, when I stumbled across the new JsonSerializable Interface. It's only PHP >= 5.4 though, and I'm running in a 5.3.x environment.

How is this sort of functionality achieved PHP < 5.4?

I've not worked much with JSON yet, but I'm trying to support an API layer in an application, and dumping the data object (that would otherwise be sent to the view) into JSON would be perfect.

If I attempt to serialize the object directly, it returns an empty JSON string; which is because I assume json_encode() doesn't know what the heck to do with the object. Should I recursively reduce the object into an array, and then encode that?

Example

$data = new Mf_Data();
$data->foo->bar['hello'] = 'world';

echo json_encode($data) produces an empty object:

{}

var_dump($data) however, works as expected:

object(Mf_Data)#1 (5) {
  ["_values":"Mf_Data":private]=>
  array(0) {
  }
  ["_children":"Mf_Data":private]=>
  array(1) {
    [0]=>
    array(1) {
      ["foo"]=>
      object(Mf_Data)#2 (5) {
        ["_values":"Mf_Data":private]=>
        array(0) {
        }
        ["_children":"Mf_Data":private]=>
        array(1) {
          [0]=>
          array(1) {
            ["bar"]=>
            object(Mf_Data)#3 (5) {
              ["_values":"Mf_Data":private]=>
              array(1) {
                [0]=>
                array(1) {
                  ["hello"]=>
                  string(5) "world"
                }
              }
              ["_children":"Mf_Data":private]=>
              array(0) {
              }
              ["_parent":"Mf_Data":private]=>
              *RECURSION*
              ["_key":"Mf_Data":private]=>
              string(3) "bar"
              ["_index":"Mf_Data":private]=>
              int(0)
            }
          }
        }
        ["_parent":"Mf_Data":private]=>
        *RECURSION*
        ["_key":"Mf_Data":private]=>
        string(3) "foo"
        ["_index":"Mf_Data":private]=>
        int(0)
      }
    }
  }
  ["_parent":"Mf_Data":private]=>
  NULL
  ["_key":"Mf_Data":private]=>
  NULL
  ["_index":"Mf_Data":private]=>
  int(0)
}

Addendum

1)

So this is the toArray() function I've devised for the Mf_Data class:

public function toArray()
{
    $array = (array) $this;
    array_walk_recursive($array, function (&$property) {
        if ($property instanceof Mf_Data) {
            $property = $property->toArray();
        }
    });
    return $array;
}

However since the Mf_Data objects also have a reference to their parent (containing) object, this fails with recursion. Works like a charm though when I remove the _parent reference.

2)

Just to follow up, the final function to transform a complex tree-node object I went with was:

// class name - Mf_Data
// exlcuded properties - $_parent, $_index
public function toArray()
{
    $array = get_object_vars($this);
    unset($array['_parent'], $array['_index']);
    array_walk_recursive($array, function (&$property) {
        if (is_object($property) && method_exists($property, 'toArray')) {
            $property = $property->toArray();
        }
    });
    return $array;
}

3)

I'm following up again, with a bit cleaner of an implementation. Using interfaces for an instanceof check seems much cleaner than method_exists() (however method_exists() does cross-cut inheritance/implementation).

Using unset() seemed a bit messy too, and it seems that logic should be refactored into another method. However, this implementation does copy the property array (due to array_diff_key), so something to consider.

interface ToMapInterface
{

    function toMap();

    function getToMapProperties();

}

class Node implements ToMapInterface
{

    private $index;
    private $parent;
    private $values = array();

    public function toMap()
    {
        $array = $this->getToMapProperties();
        array_walk_recursive($array, function (&$value) {
            if ($value instanceof ToMapInterface) {
                $value = $value->toMap();
            }
        });
        return $array;
    }

    public function getToMapProperties()
    {
        return array_diff_key(get_object_vars($this), array_flip(array(
            'index', 'parent'
        )));
    }

}

Body:
My version:

json_encode(self::toArray($ob))

Implementation:

private static function toArray($object) {
    $reflectionClass = new \ReflectionClass($object);

    $properties = $reflectionClass->getProperties();

    $array = [];
    foreach ($properties as $property) {
        $property->setAccessible(true);
        $value = $property->getValue($object);
        if (is_object($value)) {
            $array[$property->getName()] = self::toArray($value);
        } else {
            $array[$property->getName()] = $value;
        }
    }
    return $array;
}

JsonUtils : GitHub


问:
How to use python 2.7 packages in Anaconda python 2.7 environment
I am trying to have two environments in anaconda, one with python 3.4 and one with python 2.7. I already had everything working for python 3.4 and created a new environment with:

```<code>conda create -n python2 python=2.7 anaconda
</code>```

and i activated this with:

```<code>activate python2
</code>```

When i then run python, it still uses packages from C:\anaconda3\lib. Here are the standard packages for python 3.4 located (I think). This will give errors when using python 2.7. How can i make sure the python 2.7 environment uses al standard packages for python 2.7?

I tried manually copying the files to C:\Anaconda3\envs\python2\lib, but without success.

答:
I found why it was not working. I was using Spyder, which sets the environment variable PYTHONPATH to C:\anaconda3\lib.

I removed the variable with

```<code>set PYTHONPATH=
</code>```

in cmd and now it works. The only thing left is that i have to do this every time and i suspect this to be because Spyder changes it back.

Body:
I am trying to have two environments in anaconda, one with python 3.4 and one with python 2.7. I already had everything working for python 3.4 and created a new environment with:

conda create -n python2 python=2.7 anaconda

and i activated this with:

activate python2

When i then run python, it still uses packages from C:\anaconda3\lib. Here are the standard packages for python 3.4 located (I think). This will give errors when using python 2.7. How can i make sure the python 2.7 environment uses al standard packages for python 2.7?

I tried manually copying the files to C:\Anaconda3\envs\python2\lib, but without success.

Body:
I found why it was not working. I was using Spyder, which sets the environment variable PYTHONPATH to C:\anaconda3\lib.

I removed the variable with

set PYTHONPATH=

in cmd and now it works. The only thing left is that i have to do this every time and i suspect this to be because Spyder changes it back.


问:
Reduced VS 2017 IDE interactivity in MVC 5 Razor views in 2015 project
I just installed VS 2017 and am opening an MVC 5 project created in VS 2015.  The application runs fine, but I am experiencing reduced interactivity between my MVC Razor view code and the 2017 IDE.

Here's is the context menu when I right-click on an HTML helper method in VS 2015:

However, I only see this in 2017:

Also notice the lack of syntax color-coding in the 2017 verison.  It's like it's not recognizing Razor syntax at all.

I did not do any special solution/project upgrades.  I just opened the solution in 2017 and expected it to prompt me to upgrade any files that needed upgrading.

答:
Go to Tools Options and customize menus and ribbons

also have a look: https://msdn.microsoft.com/en-us/library/wdee4yb6.aspx

and or: https://msdn.microsoft.com/en-us/library/wdee4yb6(v=vs.110).aspx

try reset the existing window layout or menus and options.

or repair your VS


问:
I want to handle alert as in write `Username and Password` in it and then click OK
The popup comes when we navigate to website and asks for authentication.Something like this. Please let me know how to handle the alert with username and pass, that pops up as this pop up could not be distinguished with firebug etc

I already tried "INPUT TEXT into prompt" #input text into prompt  https://username:password@url.com  but I get error that There is no alert present. However when I use function Alert should be present it gets passed

I am using robot framework and Selenium2Library.

答:
What you are running into is called BASIC web server authentication. While searching on SO there are a number of similar questions that have been asked over time. This particular one is nice as it has several solution approaches that can be tried.

As the popup is technically not part of the page's DOM, this can not be addressed using xpath. There are roughly two approaches:

Fill in the text boxes using a key stroke simulator like SendKeys.

Prevent the popup from appearing.

In this case you're already on your way for the second one. By including the username and password in the url, the popup is prevented. The following Robot Script uses that example to access a local page that is secured by basic authentication using this tutorial.

```<code>*** Settings ***
Library    Selenium2Library

*** Test Cases ***
Test Chrome
    Create Webdriver    Chrome
    Go To    http://admin:admin@localhost:8090/basic-auth/
    Capture Page Screenshot
    [Teardown]  Close All Browsers
</code>```

As the popup is prevented, there is no need separately input the username and password.

Body:
What you are running into is called BASIC web server authentication. While searching on SO there are a number of similar questions that have been asked over time. This particular one is nice as it has several solution approaches that can be tried.

As the popup is technically not part of the page's DOM, this can not be addressed using xpath. There are roughly two approaches:

Fill in the text boxes using a key stroke simulator like SendKeys.

Prevent the popup from appearing.

In this case you're already on your way for the second one. By including the username and password in the url, the popup is prevented. The following Robot Script uses that example to access a local page that is secured by basic authentication using this tutorial.

*** Settings ***
Library    Selenium2Library

*** Test Cases ***
Test Chrome
    Create Webdriver    Chrome
    Go To    http://admin:admin@localhost:8090/basic-auth/
    Capture Page Screenshot
    [Teardown]  Close All Browsers

As the popup is prevented, there is no need separately input the username and password.


问:
Get Session to expire gracefully in ASP.NET
I need a way to tell ASP.NET "Kill the current session and start over with a brand new one" before/after a redirect to a page.

Here's what I'm trying to do:

1) Detect when a session is expired in the master page (or Global.asax) of an ASP.NET application.

2) If the session is expired, redirect the user to a page telling them that their session is expired.  On this page, it will wait 5 seconds and then redirect the user to the main page of the application, or alternatively they can click a link to get there sooner if they wish.

3)  User arrives at main page and begins to use the application again.

Ok, so far I have steps 1 and 2 covered.  I have a function that detects session expiry by using the IsNewSession property and the ASP.NET Session ID cookie value.  if it detects an expired session it redirects, waits five seconds and then TRIES to go to the main page.

The problem is that when it tries to redirect, it gets to the part in the master page to detect an expired session and it returns true.  I've tried calling Session.Abandon(), Session.Clear(), even setting the session to NULL, with no luck.

Someone out there has had to have faced this problem before, so I'm confident in the community to have a good solution.  Thanks in advance.

答:
For ASP.NET MVC this is what I'm doing with an action method.

Note:

Returns a simple view with no other resources that might accidentally re-create a session

I return the current time and session id so you can verify the action completed succcessfully

```<code>public ActionResult ExpireSession()
{
    string sessionId = Session.SessionID;
    Session.Abandon();
    return new ContentResult()
    {
        Content = "Session '" + sessionId + "' abandoned at " + DateTime.Now
    };
}
</code>```

OwnerDisplayName: Robert Iver

Body:
For ASP.NET MVC this is what I'm doing with an action method.

Note:

Returns a simple view with no other resources that might accidentally re-create a session

I return the current time and session id so you can verify the action completed succcessfully

public ActionResult ExpireSession()
{
    string sessionId = Session.SessionID;
    Session.Abandon();
    return new ContentResult()
    {
        Content = "Session '" + sessionId + "' abandoned at " + DateTime.Now
    };
}


问:
How do you change the default folder of a select file?
How do you change the default folder of a choose file button? I've made a choose file button. When you click it, I want it to open a specific folder. Please help! Thanks :)</p>

答:
This is impossible, as it is a security risk to let website code set any value on the machine.

Also, you can never be sure that directory exists. What if I'm on a Mac? My stuff are in ~/Pictures. What if I installed Windows on D:\?

All credit goes to casraf for this answer.


问:
SQL getting the average count of diagnosis based on specialty
I have 2 tables one for appointments and one for doctors.

I want to    select    the average number of patients for each specialty, which is stored in the doctors table. The appointments table has the patients' id the doctors' id and the diagnosis, if a patient has had a diagnosis.

I tried this, but doesn't work.

```<code>SELECT  AVG(patientAMKA)
  FROM appointments
 WHERE diagnosis IS NOT NULL
 GROUP
    BY doctor.specialty
</code>```

EDIT: I just want to clarify that patientAMKA is the id of the patient.
EDIT2: I specifically mean how many patients (with a diagnosis) exist for each speciaity, then take the average of those numbers.

答:
Based on your clarifications, I believe what you want is:</p>

```<code>SELECT
    AVG(CountOfDiagnoses) as TheAverage
FROM
    (
    SELECT
        d.specialty,
        COUNT(1) as CountOfDiagnoses
    FROM
        appointments a
        JOIN doctor d ON
            d.doctor_id = a.doctor_id
    WHERE
        a.diagnosis IS NOT NULL
    GROUP BY
        d.specialty
    ) Counts
</code>```

Body:
I have 2 tables one for appointments and one for doctors.

I want to    select    the average number of patients for each specialty, which is stored in the doctors table. The appointments table has the patients' id the doctors' id and the diagnosis, if a patient has had a diagnosis.

I tried this, but doesn't work.

SELECT  AVG(patientAMKA)
  FROM appointments
 WHERE diagnosis IS NOT NULL
 GROUP
    BY doctor.specialty

EDIT: I just want to clarify that patientAMKA is the id of the patient.
EDIT2: I specifically mean how many patients (with a diagnosis) exist for each speciaity, then take the average of those numbers.

Body:
Based on your clarifications, I believe what you want is:

SELECT
    AVG(CountOfDiagnoses) as TheAverage
FROM
    (
    SELECT
        d.specialty,
        COUNT(1) as CountOfDiagnoses
    FROM
        appointments a
        JOIN doctor d ON
            d.doctor_id = a.doctor_id
    WHERE
        a.diagnosis IS NOT NULL
    GROUP BY
        d.specialty
    ) Counts


问:
program that determines if array is ascending, descending, or random(C language)
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

```<code>int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}
</code>```

i'd appreciate some guidance.

答:
```<code>        int UpOrDown(int *arr,int size)
{
int i = 0 ; //try to intialize the elements its good habbit also put spaces like i had done .its just good coding guidance
int j = 0 ;
int flag = 0;

if ( arr[0] < arr[1] )// ascending or random
{
        for(i = 1 ; i < size ;i++)
           {
            if(arr[i]>arr[i+1])
                flag = 1;
             else
    {
                flag = 0 ;
        break ;
    }

            }
}

else //descending or random
{

            for(i=1;i< size;i++)
                {
                  if(arr[i]<arr[i+1])
                    flag = -1;
        else
        {
                    flag = 0 ;
        break ;
        }
            }
  }
return flag;
}
</code>```

<p>i am considering there is no repeated elements in your code </p>

Body:
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}

i'd appreciate some guidance.

Body:
        int UpOrDown(int *arr,int size)
{
int i = 0 ; //try to intialize the elements its good habbit also put spaces like i had done .its just good coding guidance
int j = 0 ;
int flag = 0;

if ( arr[0] < arr[1] )// ascending or random
{
        for(i = 1 ; i < size ;i++)
           {
            if(arr[i]>arr[i+1])
                flag = 1;
             else
    {
                flag = 0 ;
        break ;
    }

            }
}

else //descending or random
{

            for(i=1;i< size;i++)
                {
                  if(arr[i]<arr[i+1])
                    flag = -1;
        else
        {
                    flag = 0 ;
        break ;
        }
            }
  }
return flag;
}

i am considering there is no repeated elements in your code


问:
AngularFire2 iterate through array of objects
I have the following Firebase database structure:

```<code>orders {
  $uid { // user UID
    order {
    // ...
    }
  }
}
</code>```

And I'm trying to get all orders, this way:

```<code>public getOrders() {
  this.db.list('/orders).subscribe(items => {
    items.forEach(item => {
      console.log(item);
    })
  })
}
</code>```

My question is, how I can get all orders ?
Because now, I can't iterate through item.

答:
Ok, so finally I could resolve it in the following way:

```<code>public getOrders() {
  this.db.list('/orders).subscribe(items => {
    items.forEach(item => {
      Object.keys(item).map(key=>item[key]).map(order => {
        console.log(order);
      })
    })
  })
}
</code>```

So, first we getting all orders, then iterate using forEach through each object with orders. Then, using Object.keys we can access to the order of each user.

Body:
I have the following Firebase database structure:

orders {
  $uid { // user UID
    order {
    // ...
    }
  }
}

And I'm trying to get all orders, this way:

public getOrders() {
  this.db.list('/orders).subscribe(items => {
    items.forEach(item => {
      console.log(item);
    })
  })
}

My question is, how I can get all orders ?
Because now, I can't iterate through item.

Body:
Ok, so finally I could resolve it in the following way:

public getOrders() {
  this.db.list('/orders).subscribe(items => {
    items.forEach(item => {
      Object.keys(item).map(key=>item[key]).map(order => {
        console.log(order);
      })
    })
  })
}

So, first we getting all orders, then iterate using forEach through each object with orders. Then, using Object.keys we can access to the order of each user.


问:
how to make POST action from another server - Laravel
How can i make post request from another server to my laravel server?

I have a website from another provider (lets say domainA.com) , they have CMS system, so I can make my custom pages - the question is, I want to make a form in domainA.com, and post it to domainB.com (my original Server), how can I make it in laravel? As far as I understand I should use api route file for this, is it secure to make such a POST request? because as far as I understand there is no token protection on api requests right?

sorry for my english - i am most interested in security side of such a action - if you show me an example, it would be appreciated.

答:
Laravel 5.4 has 2 route groups: web and api

the web group is used for all requests that come from the current laravel application. Laravel uses a csrf token with every request to make sure every request is coming from the own page to prevent cross site scripting.

the api group is for requests that a fired from an external server. For this group the csrf protection is disabled.

Remember: csrf protection ONLY checks if the requests is from your site, it does not handle the authentication or authorization.

To secure your API you can use json web tokens (jwt). There is a package that will handle the authentication parts for APIs.

If you want to keep it really simple you can write a middleware for all api calls, that is checking if the requests has a special value (your personal token) to give access to the api.


问:
Pasting two vectors with combinations of all vectors' elements
I have two vectors:

```<code>vars <- c("SR", "PL")
vis <- c(1,2,3)
</code>```

Based on these vectors I would like to create the following vector:

```<code>"SR.1"  "SR.2"  "SR.3"  "PL.1"  "PL.2"  "PL.3"
</code>```

With paste I have the following result:

```<code>paste(vars, vis, sep=".")
 [1] "SR.1" "PL.2" "SR.3"
</code>```

How can I create the vector I need?

答:
This old question already has an accepted answer. But as it's being used as dupe target, I believe it's worthwhile to add a data.table solution which uses the cross join function CJ():

```<code>library(data.table)
options(datatable.CJ.names=FALSE) # required with version version 1.12.0+
CJ(vars, vis)[, paste(V1, V2, sep =".")]
#[1] "PL.1" "PL.2" "PL.3" "SR.1" "SR.2" "SR.3"
</code>```

In case the original order is important:

```<code>CJ(vars, vis, sorted = FALSE)[, paste(V1, V2, sep =".")]
#[1] "SR.1" "SR.2" "SR.3" "PL.1" "PL.2" "PL.3"
</code>```

Edit: CJ() has changed default behaviour with version 1.12.0

As announced in the release notes of version 1.12.0 (Point 3) the default option options(datatable.CJ.names=TRUE) has changed. CJ() now auto-names its inputs exactly as data.table() does.

So, the code above has to be amended for data.table version 1.12.0 and above:

```<code>library(data.table)   ### version 1.12.0+
CJ(vars, vis)[, paste(vars, vis, sep =".")]
</code>```

and

```<code>CJ(vars, vis, sorted = FALSE)[, paste(vars, vis, sep =".")]
</code>```

resp.

Body:
I have two vectors:

vars <- c("SR", "PL")
vis <- c(1,2,3)

Based on these vectors I would like to create the following vector:

"SR.1"  "SR.2"  "SR.3"  "PL.1"  "PL.2"  "PL.3"

With paste I have the following result:

paste(vars, vis, sep=".")
 [1] "SR.1" "PL.2" "SR.3"

How can I create the vector I need?

Body:
This old question already has an accepted answer. But as it's being used as dupe target, I believe it's worthwhile to add a data.table solution which uses the cross join function CJ():

library(data.table)
options(datatable.CJ.names=FALSE) # required with version version 1.12.0+
CJ(vars, vis)[, paste(V1, V2, sep =".")]
#[1] "PL.1" "PL.2" "PL.3" "SR.1" "SR.2" "SR.3"

In case the original order is important:

CJ(vars, vis, sorted = FALSE)[, paste(V1, V2, sep =".")]
#[1] "SR.1" "SR.2" "SR.3" "PL.1" "PL.2" "PL.3"

Edit: CJ() has changed default behaviour with version 1.12.0

As announced in the release notes of version 1.12.0 (Point 3) the default option options(datatable.CJ.names=TRUE) has changed. CJ() now auto-names its inputs exactly as data.table() does.

So, the code above has to be amended for data.table version 1.12.0 and above:

library(data.table)   ### version 1.12.0+
CJ(vars, vis)[, paste(vars, vis, sep =".")]

and

CJ(vars, vis, sorted = FALSE)[, paste(vars, vis, sep =".")]

resp.


问:
SimpleDateFormat - Unparseable date
I try to convert String to Date.

Here is my code:

```<code>    SimpleDateFormat format =  new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    Date date = format.parse("Sun Apr 08 16:37:00 CEST 2012");
</code>```

I get exception:

04-08 13:51:36.536: W/System.err(8005): java.text.ParseException:
  Unparseable date: "Sun Apr 08 16:37:00 CEST 2012".

Format seems to be ok. Am I missing something?

Thanks.

答:
The other answers were fine answers in 2012. Here’s an example of how to do with the modern (2014) Java date and time classes:

```<code>    System.out.println("date de la requete est " + dateq);
    DateTimeFormatter dtf = DateTimeFormatter
            .ofPattern("EEE MMM dd HH:mm:ss xx uuuu", Locale.ROOT);
    OffsetDateTime dateTime1 = OffsetDateTime.parse(dateq, dtf);

    System.out.println("new date " + dateTime1);
</code>```

The code example was inspired from a duplicate question (as I see it), How to convert Xml String date to int in java. With the example string from that question it prints:

```<code>date de la requete est Tue Feb 08 12:30:27 +0000 2011
new date 2011-02-08T12:30:27Z
</code>```

Q: I cannot use the newer classes on Android(?)

A: Yes you can. For Android, use the backport specifically tailored to Android, ThreeTenABP. Otherwise for Java 6 and 7, use ThreeTen Backport.

Q: Your code doesn’t work for the date-time string in this question!

A: (1) If you can, avoid the three and four letter time zone abbreviations like CEST. Many are ambiguous and interpretation may even vary with your JVM’s current time zone setting. CEST is just the summer half of a time zone, not a full time zone. (2) If you cannot get a string without CEST or similar in it, try using ZonedDateTime instead of OffsetDateTime and use zzz in the format pattern as in the question. This works in the example and produces 2012-04-08T16:37+02:00[Europe/Paris].

Q: How do I use the newer classes?

A: One good place to start is the Oracle Tutorial.

Q: Locale.ROOT??

A: If your date-time string comes from a specific place in the world and in the language of that place, use the corresponding locale, of course. If it’s just in English because computer systems everywhere tend to output English, I prefer to use Locale.ROOT for “the locale neutral locale”, like saying “do not do anything locale-specific here”.

Title: SimpleDateFormat - Unparseable date

Body:
I try to convert String to Date.

Here is my code:

    SimpleDateFormat format =  new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    Date date = format.parse("Sun Apr 08 16:37:00 CEST 2012");

I get exception:

04-08 13:51:36.536: W/System.err(8005): java.text.ParseException:
  Unparseable date: "Sun Apr 08 16:37:00 CEST 2012".

Format seems to be ok. Am I missing something?

Thanks.

Body:
The other answers were fine answers in 2012. Here’s an example of how to do with the modern (2014) Java date and time classes:

    System.out.println("date de la requete est " + dateq);
    DateTimeFormatter dtf = DateTimeFormatter
            .ofPattern("EEE MMM dd HH:mm:ss xx uuuu", Locale.ROOT);
    OffsetDateTime dateTime1 = OffsetDateTime.parse(dateq, dtf);

    System.out.println("new date " + dateTime1);

The code example was inspired from a duplicate question (as I see it), How to convert Xml String date to int in java. With the example string from that question it prints:

date de la requete est Tue Feb 08 12:30:27 +0000 2011
new date 2011-02-08T12:30:27Z

Q: I cannot use the newer classes on Android(?)

A: Yes you can. For Android, use the backport specifically tailored to Android, ThreeTenABP. Otherwise for Java 6 and 7, use ThreeTen Backport.

Q: Your code doesn’t work for the date-time string in this question!

A: (1) If you can, avoid the three and four letter time zone abbreviations like CEST. Many are ambiguous and interpretation may even vary with your JVM’s current time zone setting. CEST is just the summer half of a time zone, not a full time zone. (2) If you cannot get a string without CEST or similar in it, try using ZonedDateTime instead of OffsetDateTime and use zzz in the format pattern as in the question. This works in the example and produces 2012-04-08T16:37+02:00[Europe/Paris].

Q: How do I use the newer classes?

A: One good place to start is the Oracle Tutorial.

Q: Locale.ROOT??

A: If your date-time string comes from a specific place in the world and in the language of that place, use the corresponding locale, of course. If it’s just in English because computer systems everywhere tend to output English, I prefer to use Locale.ROOT for “the locale neutral locale”, like saying “do not do anything locale-specific here”.


问:
How to keep matplotlib (python) window in background?
I have a python / matplotlib application that frequently updates a plot with new data coming in from a measurement instrument. The plot window should not change from background to foreground (or vice versa) with respect to other windows on my desktop when the plot is updated with new data.

This worked as desired with Python 3 on a machine running Ubuntu 16.10 with matplotlib 1.5.2rc. However, on a different machine with Ubuntu 17.04 and matplotlib 2.0.0, the figure window pops to the front every time the plot is updated with new data.

How can I control the window foreground/background behavior and keep the window focus when updating the plot with new data?

Here's a code example illustrating my plotting routine:

```<code>import matplotlib
import matplotlib.pyplot as plt
from time import time
from random import random

print ( matplotlib.__version__ )

# set up the figure
fig = plt.figure()
plt.xlabel('Time')
plt.ylabel('Value')
plt.ion()

# plot things while new data is generated:
t0 = time()
t = []
y = []
while True:
    t.append( time()-t0 )
    y.append( random() )
    fig.clear()
    plt.plot( t , y )
    plt.pause(1)
</code>```

答:
matplotlib was changed somewhere from version 1.5.2rc to 2.0.0 such that pyplot.show() brings the window to the foreground (see here). The key is therefore to avoid calling pyplot.show() in the loop. The same goes for pyplot.pause().

Below is a working example. This will still bring the window to the foreground at the beginning. But the user may move the window to the background, and the window will stay there when the figure is updated with new data.

Note that the matplotlib animation module might be a good choice to produce the plot shown in this example. However, I couldn't make the animation work with interactive plot, so it blocks further execution of other code. That's why I could not use the animation module in my real-life application.

```<code>import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import time
from random import random

print ( matplotlib.__version__ )

# set up the figure
plt.ion()
fig = plt.figure()
ax = plt.subplot(1,1,1)
ax.set_xlabel('Time')
ax.set_ylabel('Value')
t = []
y = []
ax.plot( t , y , 'ko-' , markersize = 10 ) # add an empty line to the plot
fig.show() # show the window (figure will be in foreground, but the user may move it to background)

# plot things while new data is generated:
# (avoid calling plt.show() and plt.pause() to prevent window popping to foreground)
t0 = time.time()
while True:
    t.append( time.time()-t0 )  # add new x data value
    y.append( random() )        # add new y data value
    ax.lines[0].set_data( t,y ) # set plot data
    ax.relim()                  # recompute the data limits
    ax.autoscale_view()         # automatic axis scaling
    fig.canvas.flush_events()   # update the plot and take care of window events (like resizing etc.)
    time.sleep(1)               # wait for next loop iteration
</code>```

Body:
I have a python / matplotlib application that frequently updates a plot with new data coming in from a measurement instrument. The plot window should not change from background to foreground (or vice versa) with respect to other windows on my desktop when the plot is updated with new data.

This worked as desired with Python 3 on a machine running Ubuntu 16.10 with matplotlib 1.5.2rc. However, on a different machine with Ubuntu 17.04 and matplotlib 2.0.0, the figure window pops to the front every time the plot is updated with new data.

How can I control the window foreground/background behavior and keep the window focus when updating the plot with new data?

Here's a code example illustrating my plotting routine:

import matplotlib
import matplotlib.pyplot as plt
from time import time
from random import random

print ( matplotlib.__version__ )

# set up the figure
fig = plt.figure()
plt.xlabel('Time')
plt.ylabel('Value')
plt.ion()

# plot things while new data is generated:
t0 = time()
t = []
y = []
while True:
    t.append( time()-t0 )
    y.append( random() )
    fig.clear()
    plt.plot( t , y )
    plt.pause(1)

Body:
matplotlib was changed somewhere from version 1.5.2rc to 2.0.0 such that pyplot.show() brings the window to the foreground (see here). The key is therefore to avoid calling pyplot.show() in the loop. The same goes for pyplot.pause().

Below is a working example. This will still bring the window to the foreground at the beginning. But the user may move the window to the background, and the window will stay there when the figure is updated with new data.

Note that the matplotlib animation module might be a good choice to produce the plot shown in this example. However, I couldn't make the animation work with interactive plot, so it blocks further execution of other code. That's why I could not use the animation module in my real-life application.

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import time
from random import random

print ( matplotlib.__version__ )

# set up the figure
plt.ion()
fig = plt.figure()
ax = plt.subplot(1,1,1)
ax.set_xlabel('Time')
ax.set_ylabel('Value')
t = []
y = []
ax.plot( t , y , 'ko-' , markersize = 10 ) # add an empty line to the plot
fig.show() # show the window (figure will be in foreground, but the user may move it to background)

# plot things while new data is generated:
# (avoid calling plt.show() and plt.pause() to prevent window popping to foreground)
t0 = time.time()
while True:
    t.append( time.time()-t0 )  # add new x data value
    y.append( random() )        # add new y data value
    ax.lines[0].set_data( t,y ) # set plot data
    ax.relim()                  # recompute the data limits
    ax.autoscale_view()         # automatic axis scaling
    fig.canvas.flush_events()   # update the plot and take care of window events (like resizing etc.)
    time.sleep(1)               # wait for next loop iteration


问:
If- satement and loops in an object arraylist
I'm doing a school project where I simulate a simple banking system where the user creates the account and can put a deposit, transfer money and delete accounts.

The method transaction should go through the arraylist, find the first account and the second account and transfer money but it jumps the code and says the account cannot be found. How is it possible to fix this problem

The code down below shows what happens in the method

```<code>public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    for(int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber)){
            bList.get(i).deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
        }
        else if(bList.get(i).getBalance()< amount){
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber) && bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber)){
            JOptionPane.showMessageDialog(null, "kontot finns inte");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte");
            return false;
        }

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

The first if-statement should check if both accounts exsist and transfer money from the account that has money to the account that the user has selected but it skips the if-statement and says there is no account.

答:
```<code>if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber))
</code>```

You are checking if the same account has two different account numbers - accountNumber and newAccountNumber. This can never be true.

You must locate two accounts, one having the first account number and the other having the second account number.

The naive approach to do it is with a nested for loop:

```<code>for(int i = 0; i < bList.size(); i++){
    for(int j = 0; j < bList.size(); j++){
        if(bList.get(i).getAccountNumber().equals(accountNumber) && bList.get(j).getAccountNumber().equals(newAccountNumber)) {
            ....
        }
    }
}
</code>```

but that would take O(n^2) time. It would be more efficient to store the accounts in a HashMap where the account ID is the key and the account is the value.

Body:
I'm doing a school project where I simulate a simple banking system where the user creates the account and can put a deposit, transfer money and delete accounts.

The method transaction should go through the arraylist, find the first account and the second account and transfer money but it jumps the code and says the account cannot be found. How is it possible to fix this problem

The code down below shows what happens in the method

public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    for(int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber)){
            bList.get(i).deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
        }
        else if(bList.get(i).getBalance()< amount){
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber) && bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber)){
            JOptionPane.showMessageDialog(null, "kontot finns inte");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte");
            return false;
        }

    }
    return false;
}

The first if-statement should check if both accounts exsist and transfer money from the account that has money to the account that the user has selected but it skips the if-statement and says there is no account.

Body:
if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber))

You are checking if the same account has two different account numbers - accountNumber and newAccountNumber. This can never be true.

You must locate two accounts, one having the first account number and the other having the second account number.

The naive approach to do it is with a nested for loop:

for(int i = 0; i < bList.size(); i++){
    for(int j = 0; j < bList.size(); j++){
        if(bList.get(i).getAccountNumber().equals(accountNumber) && bList.get(j).getAccountNumber().equals(newAccountNumber)) {
            ....
        }
    }
}

but that would take O(n^2) time. It would be more efficient to store the accounts in a HashMap where the account ID is the key and the account is the value.


问:
How to extract date time from sql and bind it to datetimePicker
I have saved dates from datetimepicker to sql in my windows form app with the format (dd-MM-yyyy). To edit date, I want to first fetch saved date and show in the datetimepicker control. Like if 28-03-2000 is saved in db then datetimepicker should show this same date and should understand the format dd-MM-yyyy. The code with which I am trying to do is as follows

```<code>birthday_search.Text = Convert.ToDateTime(reader["Birthday"]).ToString("dd-MM-yyyy");
</code>```

birthday_search is the name of datetimepicker. This gives error "String was not recognized as a valid datetime" because its itself picking the format MM-dd-yyyy which is turning out to be wrong.

答:
The dd-MM-yyyy is not expected format for ToDateTime function by default. Use Convert.ToDateTime (String, IFormatProvider) overload instead. Or use ParceExact to get DateTime value:

```<code>DateTime MyDateTime = DateTime.ParseExact(reader["Birthday"], "dd-MM-yyyy", null);
</code>```

But in your case the conversion isn't necessary, becouse you could use string value for the Text property. So it's enough to use

```<code>birthday_search.Text = reader["Birthday"];
</code>```

Body:
I have saved dates from datetimepicker to sql in my windows form app with the format (dd-MM-yyyy). To edit date, I want to first fetch saved date and show in the datetimepicker control. Like if 28-03-2000 is saved in db then datetimepicker should show this same date and should understand the format dd-MM-yyyy. The code with which I am trying to do is as follows

birthday_search.Text = Convert.ToDateTime(reader["Birthday"]).ToString("dd-MM-yyyy");

birthday_search is the name of datetimepicker. This gives error "String was not recognized as a valid datetime" because its itself picking the format MM-dd-yyyy which is turning out to be wrong.

Body:
The dd-MM-yyyy is not expected format for ToDateTime function by default. Use Convert.ToDateTime (String, IFormatProvider) overload instead. Or use ParceExact to get DateTime value:

DateTime MyDateTime = DateTime.ParseExact(reader["Birthday"], "dd-MM-yyyy", null);

But in your case the conversion isn't necessary, becouse you could use string value for the Text property. So it's enough to use

birthday_search.Text = reader["Birthday"];


问:
Handling linking accounts in Firebase
I am following Firebase's instruction on social login.  Below is an example of what I am using and it is all working fine from a login authentication perspective.

I have, however, both Google and Facebook login working independently.

What I would like now to be able to do is link the accounts. You can see below in fact where this might go (see the comment):

If you are using multiple auth providers on your app you should handle linking the user's accounts here.

I have tried many variations of what I think should go here, but to no avail. Can anyone guide me in relation to what they think should go here? Thanks!

```<code>function initFBApp() {
    // Result from Redirect auth flow.
    // [START getidptoken]
    firebase.auth().getRedirectResult().then(function (result) {
        if (result.credential) {
            // This gives you a Facebook Access Token. You can use it to access the Facebook API.
            var token = result.credential.accessToken;
            // [START_EXCLUDE]
            document.getElementById('FBquickstart-oauthtoken').textContent = token;
        }
        else {
            document.getElementById('FBquickstart-oauthtoken').textContent = 'null';
            // [END_EXCLUDE]
        }
        // The signed-in user info.
        var user = result.user;
    }).catch(function (error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // [START_EXCLUDE]
        if (errorCode === 'auth/account-exists-with-different-credential') {
            alert('You have already signed up with a different auth provider for that emails.');
            // If you are using multiple auth providers on your app you should handle linking
            // the user's accounts here.
        }
        else {
            console.error(error);
        }
        // [END_EXCLUDE]
    });
    // [END getidptoken]
    // Listening for auth state changes.
    // [START authstatelistener]
    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            // User is signed in.
            var displayName = user.displayName;
            var email = user.email;
            var emailVerified = user.emailVerified;
            var photoURL = user.photoURL;
            var isAnonymous = user.isAnonymous;
            var uid = user.uid;
            var providerData = user.providerData;
            // [START_EXCLUDE]
            document.getElementById('FBquickstart-sign-in-status').textContent = 'Signed in';
            document.getElementById('FBquickstart-sign-in').textContent = 'Log out';
            document.getElementById('FBquickstart-account-details').textContent = JSON.stringify(user, null, '  ');
            // [END_EXCLUDE]
        }
        else {
            // User is signed out.
            // [START_EXCLUDE]
            document.getElementById('FBquickstart-sign-in-status').textContent = 'Signed out';
            document.getElementById('FBquickstart-sign-in').textContent = 'Log in with Facebook';
            document.getElementById('FBquickstart-account-details').textContent = 'null';
            document.getElementById('FBquickstart-oauthtoken').textContent = 'null';
            // [END_EXCLUDE]
        }
        // [START_EXCLUDE]
        document.getElementById('FBquickstart-sign-in').disabled = false;
        // [END_EXCLUDE]
    });
    // [END authstatelistener]
    document.getElementById('FBquickstart-sign-in').addEventListener('click', toggleFBSignIn, false);
}
</code>```

答:
I think the Firebase API changed a bit and firebase.auth().currentUser.link(savedCred);
is now firebase.auth().currentUser.linkWithRedirect(provider). In my implementation I'm saving the initially selected provider to sessionStorage and use that with the above method in case account linking is required.

You can also do linkWithPopUp if that suits your needs better.

Title: Handling linking accounts in Firebase

Body:
I am following Firebase's instruction on social login.  Below is an example of what I am using and it is all working fine from a login authentication perspective.

I have, however, both Google and Facebook login working independently.

What I would like now to be able to do is link the accounts. You can see below in fact where this might go (see the comment):

If you are using multiple auth providers on your app you should handle linking the user's accounts here.

I have tried many variations of what I think should go here, but to no avail. Can anyone guide me in relation to what they think should go here? Thanks!

function initFBApp() {
    // Result from Redirect auth flow.
    // [START getidptoken]
    firebase.auth().getRedirectResult().then(function (result) {
        if (result.credential) {
            // This gives you a Facebook Access Token. You can use it to access the Facebook API.
            var token = result.credential.accessToken;
            // [START_EXCLUDE]
            document.getElementById('FBquickstart-oauthtoken').textContent = token;
        }
        else {
            document.getElementById('FBquickstart-oauthtoken').textContent = 'null';
            // [END_EXCLUDE]
        }
        // The signed-in user info.
        var user = result.user;
    }).catch(function (error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // [START_EXCLUDE]
        if (errorCode === 'auth/account-exists-with-different-credential') {
            alert('You have already signed up with a different auth provider for that emails.');
            // If you are using multiple auth providers on your app you should handle linking
            // the user's accounts here.
        }
        else {
            console.error(error);
        }
        // [END_EXCLUDE]
    });
    // [END getidptoken]
    // Listening for auth state changes.
    // [START authstatelistener]
    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            // User is signed in.
            var displayName = user.displayName;
            var email = user.email;
            var emailVerified = user.emailVerified;
            var photoURL = user.photoURL;
            var isAnonymous = user.isAnonymous;
            var uid = user.uid;
            var providerData = user.providerData;
            // [START_EXCLUDE]
            document.getElementById('FBquickstart-sign-in-status').textContent = 'Signed in';
            document.getElementById('FBquickstart-sign-in').textContent = 'Log out';
            document.getElementById('FBquickstart-account-details').textContent = JSON.stringify(user, null, '  ');
            // [END_EXCLUDE]
        }
        else {
            // User is signed out.
            // [START_EXCLUDE]
            document.getElementById('FBquickstart-sign-in-status').textContent = 'Signed out';
            document.getElementById('FBquickstart-sign-in').textContent = 'Log in with Facebook';
            document.getElementById('FBquickstart-account-details').textContent = 'null';
            document.getElementById('FBquickstart-oauthtoken').textContent = 'null';
            // [END_EXCLUDE]
        }
        // [START_EXCLUDE]
        document.getElementById('FBquickstart-sign-in').disabled = false;
        // [END_EXCLUDE]
    });
    // [END authstatelistener]
    document.getElementById('FBquickstart-sign-in').addEventListener('click', toggleFBSignIn, false);
}


问:
How to navigate into other divs and access their contents

I want to to navigate from the #toDoListContainer div into the #taskDiv, how do I do this in jquery.

I want to navigate from div to div to be able to access the data of each div to get the picture to appear

I did the command

```<code>console.log($("#toDoListContainer")[0]);
</code>```

so i was trying to navigate the div like this..

console.log($("#toDoListContainer")[0].children);

I should be able to get into the zeroth div by doing:

console.log($("#toDoListContainer")[0].children[0]);

but I get undefined instead. any Ideas ?

答:
Using same Id for all your divs is bad practice, you're not respecting the HTMl Specification which says that ID must be unique for an element in the whole page

So change you id to class, and it can be accessed directly

See below snippet :

$(function(){
  $("#toDoListContainer .taskDiv").each(function(index,element){

    console.log("task n°"+index+ " data-completed = "+$(element).data("completed"));
    console.log("it's HTML Content = "+$(element).html());
    console.log("--------------------------------------");
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toDoListContainer">
  <div class="taskDiv" data-completed="Y"><p>paragraph</p></div>
  <div class="taskDiv" data-completed="Y"><span>span</span></div>
  <div class="taskDiv" data-completed="N"><h3>heading text</h3></div>
</div></code>```

Body:
I want to to navigate from the #toDoListContainer div into the #taskDiv, how do I do this in jquery.

I want to navigate from div to div to be able to access the data of each div to get the picture to appear

I did the command

console.log($("#toDoListContainer")[0]);

so i was trying to navigate the div like this..

console.log($("#toDoListContainer")[0].children);

I should be able to get into the zeroth div by doing:

console.log($("#toDoListContainer")[0].children[0]);

but I get undefined instead. any Ideas ?

Body:
Using same Id for all your divs is bad practice, you're not respecting the HTMl Specification which says that ID must be unique for an element in the whole page

So change you id to class, and it can be accessed directly

See below snippet :

$(function(){
  $("#toDoListContainer .taskDiv").each(function(index,element){

    console.log("task n°"+index+ " data-completed = "+$(element).data("completed"));
    console.log("it's HTML Content = "+$(element).html());
    console.log("--------------------------------------");
  })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toDoListContainer">
  <div class="taskDiv" data-completed="Y"><p>paragraph</p></div>
  <div class="taskDiv" data-completed="Y"><span>span</span></div>
  <div class="taskDiv" data-completed="N"><h3>heading text</h3></div>
</div>


问:
starting xmonad
I'm completely new to xmonad but I'd like to start using it to boost my productivity.

This is the guide I've been using (I'm using Apple OS X Snow Leopard)
http://xmonad.org/tour.html#start

So far I've managed to install Haskell-Platform, Cabal, dMenu, and xmonad (using cabal install).

When I attempt to run xmonad from the terminal I run into this error:

```<code>SDGL0990Z464C:~ cflynn$ echo $PATH
/Users/cflynn/.cabal/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/X11/bin
SDGL0990Z464C:~ cflynn$ xmonad
/Users/cflynn/.xmonad/xmonad-i386-darwin: executeFile: does not exist (No such file or directory)
X Error of failed request:  BadAccess (attempt to access private resource denied)
  Major opcode of failed request:  2 (X_ChangeWindowAttributes)
  Serial number of failed request:  7
  Current serial number in output stream:  8
</code>```

Can anyone explain what this means? Thanks!

答: http://www.google.com/search?q=X11+macintosh - you need X11 to be installed and running, in order to use a windowmanager that relies on it .) -> is that the case, or am I mistaken for the problems cause?</p>

Title: starting xmonad

Body:
I'm completely new to xmonad but I'd like to start using it to boost my productivity.

This is the guide I've been using (I'm using Apple OS X Snow Leopard)
http://xmonad.org/tour.html#start

So far I've managed to install Haskell-Platform, Cabal, dMenu, and xmonad (using cabal install).

When I attempt to run xmonad from the terminal I run into this error:

SDGL0990Z464C:~ cflynn$ echo $PATH
/Users/cflynn/.cabal/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/X11/bin
SDGL0990Z464C:~ cflynn$ xmonad
/Users/cflynn/.xmonad/xmonad-i386-darwin: executeFile: does not exist (No such file or directory)
X Error of failed request:  BadAccess (attempt to access private resource denied)
  Major opcode of failed request:  2 (X_ChangeWindowAttributes)
  Serial number of failed request:  7
  Current serial number in output stream:  8

Can anyone explain what this means? Thanks!