问:
Kubernetes StatefulSets after cluster restart
I have a database running in a Kubernetes cluster on AWS. The database is deployed as a StatefulSet with 3 replicas. Each replica uses an AWS EBS storage as its persistent volume.

If I shutdown a database node, Kubernetes starts automatically a new one. The newly started node finds its corresponding persistent volume (AWS EBS volume) without any problems.

But what happens if I shut the Kubernetes cluster down? The AWS EBS volumes are still there. But does the Kubernetes cluster or the database StatefulSet find its corresponding persistent volumes on AWS after a full cluster restart?

答:
Kubernetes relies on etcd for state storage. If you're using kops to bring your cluster up then your etcd is backed up by AWS EBS volumes. It is recommended to backup your etcd periodically to be able to fully recover from disaster.

See here:
https://github.com/kubernetes/kops/blob/master/docs/etcd_backup.md


来源: stackexchange

问:
How can I enable emails for my Sylius projects? (Symfony)
I installed Sylius using the documentation:

http://docs.sylius.org/en/latest/book/index.html#installation

Everything seems to work fine as you can see there:

http://sylius.krown.ch/app_dev.php/en_US/

```<code>Laurence
4567
</code>```

Except with emails. I just want to enable default emails, as described there. Unfortunately no email is sent my the website after an order confirmation for example.

I have several projects installed in my server, including Symfony projects. Usually emails work just fine

How can I enable emails for my Sylius projects?

答:
check your config_dev.yml if you have disabled mail delivery for dev environment:</p>

```<code>swiftmailer:
    disable_delivery: true
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I installed Sylius using the documentation:

http://docs.sylius.org/en/latest/book/index.html#installation

Everything seems to work fine as you can see there:

http://sylius.krown.ch/app_dev.php/en_US/

Laurence
4567

Except with emails. I just want to enable default emails, as described there. Unfortunately no email is sent my the website after an order confirmation for example.

I have several projects installed in my server, including Symfony projects. Usually emails work just fine

How can I enable emails for my Sylius projects?

Body:
check your config_dev.yml if you have disabled mail delivery for dev environment:

swiftmailer:
    disable_delivery: true


问:
Adding content to wordpress page
So, i finally got my css and js scripts to load on WP

Now there is but one thing i need to get done.

i have my own theme, including header.php, footer.php, page.php

header.php and footer.php is working just fine, loading scripts and showing properly, but now i need to add all the other content.

my page.php is currently:

```<code><?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php the_content(); ?>

<?php get_footer(); ?>
</code>```

I would need to somehow add html content to pages, i have about 20 ready made .php pages which needs to be transfered to WP.

Soooo how do i go about making new page (pages -> add new) and using page template while getting the html content to show up?

I've tried to just make new page and in text mode add up all the html into page, but it only shows empty page with header and footer, so the problem is most likely the page.php and i have no idea how to get it to work.

答:
You are on the good way. While developing a custom theme from scratch is a great challenge it's not too hard.

I could recommend to take it easy and follow this tutorial I found really helpful some time ago, I learned a lot there:

Developing a WordPress Theme from Scratch

You must have the official source documentation always in your mind:

Theme Development

Do some reading and you will see that making themes is really fun and gratifying :)

EDIT:
I would recommend picking a good starter theme or framework and work using child themes. You have plenty of them to pick.

Title: Adding content to wordpress page

Body:
So, i finally got my css and js scripts to load on WP

Now there is but one thing i need to get done.

i have my own theme, including header.php, footer.php, page.php

header.php and footer.php is working just fine, loading scripts and showing properly, but now i need to add all the other content.

my page.php is currently:

<?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php the_content(); ?>

<?php get_footer(); ?>

I would need to somehow add html content to pages, i have about 20 ready made .php pages which needs to be transfered to WP.

Soooo how do i go about making new page (pages -> add new) and using page template while getting the html content to show up?

I've tried to just make new page and in text mode add up all the html into page, but it only shows empty page with header and footer, so the problem is most likely the page.php and i have no idea how to get it to work.


问:
Set & load environment variables in a phoenix app
I'm new to a Phoenix framework and am looking for a way to set environment variables in the app. One way I found is here.

However, I don't like this way since I need to type source .env whenever I restart the app.

I tried setting the ENV variables in prod.secret.exs like below:

```<code>config :oauth,
  GITHUB_CLIENT_ID: "(CLIENT ID)",
  GITHUB_CLIENT_SECRET: "(SECRET)"
</code>```

And I tried retrieving ENV variables in a following way:

```<code> config :ueberauth, Ueberauth.Strategy.Github.OAuth,
   client_id: System.get_env("GITHUB_CLIENT_ID"),
   client_secret: System.get_env("GITHUB_CLIENT_SECRET")
</code>```

However, when I run the server using mix phoenix.server, it gives me an error like below and I'm not sure what it really means:

```<code>You have configured application :oauth in your configuration
file, but the application is not available.

This usually means one of:

1. You have not added the application as a dependency in a mix.exs file.

2. You are configuring an application that does not really exist.

Please ensure :oauth exists or remove the configuration.
</code>```

I'm looking for a way to save ENV variables in the project itself in a hidden file so it can be retrieved anytime I want. Can someone tell me what's the right way of saving ENV variables and retrieving them in a Phoenix app?

答:
When starting phoenix and using environment variables (System.get_env("GITHUB_CLIENT_ID"))you'll need to do something like this to pass in variables:

GITHUB_CLIENT_ID=12345 GITHUB_CLIENT_SECRET=67890 mix phoenix.server

Body:
I'm new to a Phoenix framework and am looking for a way to set environment variables in the app. One way I found is here.

However, I don't like this way since I need to type source .env whenever I restart the app.

I tried setting the ENV variables in prod.secret.exs like below:

config :oauth,
  GITHUB_CLIENT_ID: "(CLIENT ID)",
  GITHUB_CLIENT_SECRET: "(SECRET)"

And I tried retrieving ENV variables in a following way:

 config :ueberauth, Ueberauth.Strategy.Github.OAuth,
   client_id: System.get_env("GITHUB_CLIENT_ID"),
   client_secret: System.get_env("GITHUB_CLIENT_SECRET")

However, when I run the server using mix phoenix.server, it gives me an error like below and I'm not sure what it really means:

You have configured application :oauth in your configuration
file, but the application is not available.

This usually means one of:

1. You have not added the application as a dependency in a mix.exs file.

2. You are configuring an application that does not really exist.

Please ensure :oauth exists or remove the configuration.

I'm looking for a way to save ENV variables in the project itself in a hidden file so it can be retrieved anytime I want. Can someone tell me what's the right way of saving ENV variables and retrieving them in a Phoenix app?


问:
how to destroy session and cookies from same server in php?
I have drupal login module which will trigger whenever user login from wordpress site it will be triggered and login to the site but when user logout from drupal it doesnt logout from wordpress. Please check with the below code and guide me solve this problem</p>

```<code>function wp_login_user_logout( $account) {
    if (isset($_SERVER['HTTP_COOKIE'])) {
        $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
        foreach($cookies as $cookie) {
            $parts = explode('=', $cookie);
            $name = trim($parts[0]);
            setcookie($name, '', time()-1000);
            setcookie($name, '', time()-1000, '/','sitedomain.com');
        }

    }

}
</code>```

答:
You cant modify cookies of another domain from one domain.

so I suggest you create some kind of api like this.

on WordPress installation...

```<code><?php

// file: wp/api/logout.php
require_once("../wp-load.php");

if(empty($_GET["email"])) {
    die('no email given');
}

// get wordpress user_id by email
$email = $_GET["email"];
$user = get_user_by( 'email', $email );
$user_id =  $user->ID;

// get all sessions for user with ID $user_id
$sessions = WP_Session_Tokens::get_instance($user_id);

// we have got the sessions, destroy them all!
$sessions->destroy_all();

print("user logged out.");
</code>```

now if you access url of your wordpress like this(be sure to url encode email id):
https://example.com/api/logout.php?email=email%40gmail.com

it will logout user with email id: email@gmail.com

now you can do curl request from your drupal to this url.

off course this is not very secure (one can logout any user if they have email id)

Body:
I have drupal login module which will trigger whenever user login from wordpress site it will be triggered and login to the site but when user logout from drupal it doesnt logout from wordpress. Please check with the below code and guide me solve this problem

function wp_login_user_logout( $account) {
    if (isset($_SERVER['HTTP_COOKIE'])) {
        $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
        foreach($cookies as $cookie) {
            $parts = explode('=', $cookie);
            $name = trim($parts[0]);
            setcookie($name, '', time()-1000);
            setcookie($name, '', time()-1000, '/','sitedomain.com');
        }

    }

}

Body:
You cant modify cookies of another domain from one domain.

so I suggest you create some kind of api like this.

on WordPress installation...

<?php

// file: wp/api/logout.php
require_once("../wp-load.php");

if(empty($_GET["email"])) {
    die('no email given');
}

// get wordpress user_id by email
$email = $_GET["email"];
$user = get_user_by( 'email', $email );
$user_id =  $user->ID;

// get all sessions for user with ID $user_id
$sessions = WP_Session_Tokens::get_instance($user_id);

// we have got the sessions, destroy them all!
$sessions->destroy_all();

print("user logged out.");

now if you access url of your wordpress like this(be sure to url encode email id):
https://example.com/api/logout.php?email=email%40gmail.com

it will logout user with email id: email@gmail.com

now you can do curl request from your drupal to this url.

off course this is not very secure (one can logout any user if they have email id)


答:
There are two main glitches with what you are trying to do:

First of all, you are trying to instruct mix to configure oauth OTP application, while what you need is to configure your own one:

```<code>config :my_app, :oauth,
  github_client_id: "(CLIENT ID)",
  github_client_secret: "(SECRET)"
</code>```

Now in your main config you might do:

```<code>config :ueberauth, Ueberauth.Strategy.Github.OAuth,
   client_id: Application.get_env(:my_app, :oauth)[:github_client_id],
   client_secret: Application.get_env(:my_app, :oauth)[:github_client_secret]
</code>```

The second glitch is that GITHUB_CLIENT_ID is an atom, and you are trying to access it lately as a string. In general, one should not use atom names starting with an uppercase since they kinda reserved for modules names.

On the other hand, you might still use System.get_env/2 (with your config.ex,) assuming the values were previously put there in environment:

prod.secret.exs (as it is still plain Elixir)

```<code>System.put_env("GITHUB_CLIENT_ID", "(CLIENT ID)")
System.put_env("GITHUB_CLIENT_SECRET", "(CLIENT SECRET)")
</code>```

Title: Set & load environment variables in a phoenix app

Body:
There are two main glitches with what you are trying to do:

First of all, you are trying to instruct mix to configure oauth OTP application, while what you need is to configure your own one:

config :my_app, :oauth,
  github_client_id: "(CLIENT ID)",
  github_client_secret: "(SECRET)"

Now in your main config you might do:

config :ueberauth, Ueberauth.Strategy.Github.OAuth,
   client_id: Application.get_env(:my_app, :oauth)[:github_client_id],
   client_secret: Application.get_env(:my_app, :oauth)[:github_client_secret]

The second glitch is that GITHUB_CLIENT_ID is an atom, and you are trying to access it lately as a string. In general, one should not use atom names starting with an uppercase since they kinda reserved for modules names.

On the other hand, you might still use System.get_env/2 (with your config.ex,) assuming the values were previously put there in environment:

prod.secret.exs (as it is still plain Elixir)

System.put_env("GITHUB_CLIENT_ID", "(CLIENT ID)")
System.put_env("GITHUB_CLIENT_SECRET", "(CLIENT SECRET)")


问:
Unable to Close Excel Workbook without SaveAs Prompt
Hi there I have thorny little problem thats causing me a major headache,  I have a section of code in VB.NET where I need to close the current Excel workbook, however whenever I make the call to:

```<code> 'Now force a close of the active workbook without saving
 _myXLApp.Workbooks(1).Close(Excel.XlSaveAction.xlDoNotSaveChanges)
</code>```

The SaveAs dialog gets displayed...  How do I prevent this from happening?  My understanding of the code is that making the call as above should close the workbook without any SaveAs prompt.  Any assistance much appreciated.

Kind Regards
paul J.

答:
Try this instead:

```<code>_myXLApp.Workbooks(1).Close(SaveChanges:=False) 'Instead of Excel.xlSaveAction.xlDoNotSaveChanges
</code>```

This should do the trick.  Any time I've closed Excel workbooks in VB.Net this is the command I use. It actually mirrors the Excel VBA Format.

Body:
Hi there I have thorny little problem thats causing me a major headache,  I have a section of code in VB.NET where I need to close the current Excel workbook, however whenever I make the call to:

 'Now force a close of the active workbook without saving
 _myXLApp.Workbooks(1).Close(Excel.XlSaveAction.xlDoNotSaveChanges)

The SaveAs dialog gets displayed...  How do I prevent this from happening?  My understanding of the code is that making the call as above should close the workbook without any SaveAs prompt.  Any assistance much appreciated.

Kind Regards
paul J.

Body:
Try this instead:

_myXLApp.Workbooks(1).Close(SaveChanges:=False) 'Instead of Excel.xlSaveAction.xlDoNotSaveChanges

This should do the trick.  Any time I've closed Excel workbooks in VB.Net this is the command I use. It actually mirrors the Excel VBA Format.


问:
ios - How to prevent UICollectionview scrolling when new cell is added
I have a messenger app, conversations are displayed in a UICollectionview.

When a new message is received, a new item is added to bottom of the collectionview. Everything is ok when user has scrolled to the bottom of the view, but when user scrolls up (to older messages) and a new message is received, collectionview scrolls to the bottom a bit (about new message's size).
I want to keep the collectionview position and prevent scrolling when a new message is received and collectionview updates. How should I do this?

答: One solution can be to store your new messages in date model and add after user scroll to bottom. You do not need them before that because user can view them . That will fix your problems with scroll</p>


问:
Using MacRuby to Test iPhone Application?
I have an existing iPhone app, written in Objective-C, that I'd like to add some automated tests to. I've read this article about testing with MacRuby, which sounds great but it's aimed at testing desktop frameworks.

How can I add MacRuby tests to my iPhone app? The Ruby code doesn't recognize my Objective-C classes, and I don't know how to set it up to do that. Do I need to somehow point it at the compiled code or the headers?

答: rbiphonetest worked for me back in the iPhone OS 2 and 3.x days with regular ruby. It was fairly limited though. I haven't tried it with 4.x or macruby specifically.</p>

ContentLicense: CC BY-SA 2.5


问:
REST/HATEOAS - Available methods in HAL links
I am looking at defining a REST API using HATEOAS. In particular, I find very interesting the concept of indicating for a given resource the actions that are available right now.

Some of the HATEOAS specifications include too much overhead for my needs, so I was looking at the HAL specification, as I find it very concise and practical:

```<code>{
    _links: {
        self: { href: "/orders/523" },
        warehouse: { href: "/warehouse/56" },
        invoice: { href: "/invoices/873" }
    },
    currency: "USD",
    status: "shipped",
    total: 10.20
 }
</code>```

However, links in HAL only contain a list of related resources, but not the available actions on them. As per the example above, am I allowed to cancel the order now, or not anymore? Some HAL examples solve this by using a specific URL for cancellations, and add a corresponding link in the response only if cancellation is possible:

```<code>"cancel": { "href": "/orders/523/cancel" }
</code>```

But that is not very RESTful. Cancellations are not a resource. Cancellations are a DELETE of a resource, i.e.:

```<code>DELETE /orders/523
</code>```

Is there a nice way to represent this with HAL, or should I use a different HATEOAS specification?

I am considering returning a "cancel" link with the same URL as self, but in this case the client would have to know that to cancel they have to use the DELETE verb, which is not really being described in the HATEOAS response.

```<code>self: { "href": "/orders/523" },
cancel: { "href": "/orders/523" }
</code>```

Would this be the recommended approach as per HATEOAS / HAL? I understand HAL does not have any "method" parameter, and adding it myself would be against the HAL specification.

答:
Some HAL examples solve this by using a specific URL for cancellations, and add a corresponding link in the response only if cancellation is possible

Yes.  Just like web sites: if you want to alert the client to the possibility of reaching some other application state, you provide the client with a link, including the identifier for the resource involved.

But that is not very RESTful.

It may not be "RESTful", but it is certainly conforms to the REST architectural style.

Cancellations are a DELETE of a resource, i.e.: DELETE /orders/523

You are confusing the actions on the domain model with the actions on the integration model.  What a REST API does is guide the client through a protocol to achieve some end; it is not a mapping of domain semantics onto HTTP.

Jim Webber phrased it this way:

The web is not your domain; it's a document management system.  All of the HTTP verbs apply to the document management domain.  URIs do NOT map onto domain objects -- that violates encapsulation.  Work (ex: issuing commands to the domain model) is a side effect of managing resources.

One of the REST constraints is the uniform interface; in the case of HTTP, it means that all resources understand methods in a uniform way; DELETE means the semantics described in RFC 7231, section 4.3.5.

In other words, if I send the request

```<code>OPTIONS /x/y/z/foobar ...
</code>```

and the response includes DELETE in the Allow header, then I know what it means.  The side effects in your domain?  I don't know anything about the side effects.

In the definition of DELETE, note the following

Relatively few resources allow the DELETE method -- its primary use is for remote authoring environments, where the user has some direction regarding its effect.

Anyway, you aren't really asking about DELETE, but about HAL

Is there a nice way to represent this with HAL, or should I use a different HATEOAS specification?

From what I can tell, the official way to do it is to document it with the link relation.  In other words, instead of using "cancel" as the link relation, you use something like

https://www.rfc-editor.org/rfc/rfc5023#section-5.4.2

And then your consumers, if they want to discover what a link is for, can follow the relation to learn what is going on.

HAL Discuss: Why No Methods?  has a lot of good information.

I like Mike Kelly's summary:

The idea is the available methods can be conveyed via the link
relation documentation and don't need to be in the json messages.

Body:
I am looking at defining a REST API using HATEOAS. In particular, I find very interesting the concept of indicating for a given resource the actions that are available right now.

Some of the HATEOAS specifications include too much overhead for my needs, so I was looking at the HAL specification, as I find it very concise and practical:

{
    _links: {
        self: { href: "/orders/523" },
        warehouse: { href: "/warehouse/56" },
        invoice: { href: "/invoices/873" }
    },
    currency: "USD",
    status: "shipped",
    total: 10.20
 }

However, links in HAL only contain a list of related resources, but not the available actions on them. As per the example above, am I allowed to cancel the order now, or not anymore? Some HAL examples solve this by using a specific URL for cancellations, and add a corresponding link in the response only if cancellation is possible:

"cancel": { "href": "/orders/523/cancel" }

But that is not very RESTful. Cancellations are not a resource. Cancellations are a DELETE of a resource, i.e.:

DELETE /orders/523

Is there a nice way to represent this with HAL, or should I use a different HATEOAS specification?

I am considering returning a "cancel" link with the same URL as self, but in this case the client would have to know that to cancel they have to use the DELETE verb, which is not really being described in the HATEOAS response.

self: { "href": "/orders/523" },
cancel: { "href": "/orders/523" }

Would this be the recommended approach as per HATEOAS / HAL? I understand HAL does not have any "method" parameter, and adding it myself would be against the HAL specification.

Body:
Some HAL examples solve this by using a specific URL for cancellations, and add a corresponding link in the response only if cancellation is possible

Yes.  Just like web sites: if you want to alert the client to the possibility of reaching some other application state, you provide the client with a link, including the identifier for the resource involved.

But that is not very RESTful.

It may not be "RESTful", but it is certainly conforms to the REST architectural style.

Cancellations are a DELETE of a resource, i.e.: DELETE /orders/523

You are confusing the actions on the domain model with the actions on the integration model.  What a REST API does is guide the client through a protocol to achieve some end; it is not a mapping of domain semantics onto HTTP.

Jim Webber phrased it this way:

The web is not your domain; it's a document management system.  All of the HTTP verbs apply to the document management domain.  URIs do NOT map onto domain objects -- that violates encapsulation.  Work (ex: issuing commands to the domain model) is a side effect of managing resources.

One of the REST constraints is the uniform interface; in the case of HTTP, it means that all resources understand methods in a uniform way; DELETE means the semantics described in RFC 7231, section 4.3.5.

In other words, if I send the request

OPTIONS /x/y/z/foobar ...

and the response includes DELETE in the Allow header, then I know what it means.  The side effects in your domain?  I don't know anything about the side effects.

In the definition of DELETE, note the following

Relatively few resources allow the DELETE method -- its primary use is for remote authoring environments, where the user has some direction regarding its effect.

Anyway, you aren't really asking about DELETE, but about HAL

Is there a nice way to represent this with HAL, or should I use a different HATEOAS specification?

From what I can tell, the official way to do it is to document it with the link relation.  In other words, instead of using "cancel" as the link relation, you use something like

https://www.rfc-editor.org/rfc/rfc5023#section-5.4.2

And then your consumers, if they want to discover what a link is for, can follow the relation to learn what is going on.

HAL Discuss: Why No Methods?  has a lot of good information.

I like Mike Kelly's summary:

The idea is the available methods can be conveyed via the link
relation documentation and don't need to be in the json messages.


问:
Interesting Applications of Interfaces
Why are interfaces useful?

Actually, I have a [small] idea of why interfaces are useful/necessary but...

What are [interesting or realistic] applications of interfaces?

答:
Interfaces are useful when you want to allow interoperability between two classes that do not share a common class hierarchy.

A good example of this is java.lang.CharSequence. Lots of other things can be abstractly treated as strings, but it wouldn't be correct to subclass String to do so. In fact String is final so it couldn't be done anyway.

Some time around JDK 1.4 (I beleive?) the CharSequence interface was introduced. Now String, StringBuffer, CharBuffer and lots of other existing classes in the JDK implement it. With that, new methods could be added to other APIs which accept CharSequence, allowing them to abstractly handle all of these in a unified way.

You can also implement this interface yourself and use it the same way. It's far more flexible to implement a common interface than try and force things to extend from a specific base class (or sometimes it's impossible).

OwnerDisplayName: koldfyre

Title: Interesting Applications of Interfaces

OwnerDisplayName: tweakt


问:
How do I apply date formatting and add attributes to a textbox in MVC3?
In my application, I want all dates to display in the MM/DD/YYYY format and I also want the text box to be limited to 10 characters and have a certain class applied to it.

To that end, I made a custom editor template for Date that looks like this:

```<code>@ModelType System.Nullable(Of DateTime)

@Html.TextBoxFor(Function(d) d, New With {.class="polkDate", .maxlength="10"})
</code>```

Then in my view I just can just call @Html.EditorFor(Function(m) m.someDate) and this works pretty well. However, because I'm using TextBoxFor, it doesn't respect the DisplayFormat attribute that's applied to my model class (i.e. it's spitting out the time as well instead of formatting the date).

I would love to use EditorFor so that it would respect the formatting that I want, but you can't add attributes like class and maxlength. I also tried just using the plain old TextBox helper, but I don't know how to make it generate the correct ID so that model binding still works.

Anybody know a way to make this happen? I don't feel like what I want to do here is too outlandish.

答:
This appears to do the trick:

```<code>@ModelType Date

@If Date.MinValue.Equals(Model) Then
    @Html.TextBox("", Nothing, New With {.class="polkDate", .maxlength="10"})
Else
    @Html.TextBox("", Model.ToShortDateString(), New With {.class="polkDate", .maxlength="10"})
End If
</code>```

Looks like the framework automatically assigns the ID and name fields of the html input tag so everything works properly.

Body:
In my application, I want all dates to display in the MM/DD/YYYY format and I also want the text box to be limited to 10 characters and have a certain class applied to it.

To that end, I made a custom editor template for Date that looks like this:

@ModelType System.Nullable(Of DateTime)

@Html.TextBoxFor(Function(d) d, New With {.class="polkDate", .maxlength="10"})

Then in my view I just can just call @Html.EditorFor(Function(m) m.someDate) and this works pretty well. However, because I'm using TextBoxFor, it doesn't respect the DisplayFormat attribute that's applied to my model class (i.e. it's spitting out the time as well instead of formatting the date).

I would love to use EditorFor so that it would respect the formatting that I want, but you can't add attributes like class and maxlength. I also tried just using the plain old TextBox helper, but I don't know how to make it generate the correct ID so that model binding still works.

Anybody know a way to make this happen? I don't feel like what I want to do here is too outlandish.

Body:
This appears to do the trick:

@ModelType Date

@If Date.MinValue.Equals(Model) Then
    @Html.TextBox("", Nothing, New With {.class="polkDate", .maxlength="10"})
Else
    @Html.TextBox("", Model.ToShortDateString(), New With {.class="polkDate", .maxlength="10"})
End If

Looks like the framework automatically assigns the ID and name fields of the html input tag so everything works properly.


问:
TensorFlow RandomForest vs Deep learning
I am using TensorFlow for training model which has 1 output for the 4 inputs. The problem is of regression.

I found that when I use RandomForest to train the model, it quickly converges and also runs well on the test data. But when I use a simple Neural network for the same problem, the loss(Random square error) does not converge. It gets stuck on a particular value.

I tried increasing/decreasing number of hidden layers, increasing/decreasing learning rate. I also tried multiple optimizers and tried to train the model on both normalized and non-normalized data.

I am new to this field but the literature that I have read so far vehemently asserts that the neural network should marginally and categorically work better than the random forest.

What could be the reason behind non-convergence of the model in this case?

答:
A useful rule for beginning training models, is not to begin with the more complex methods, for example, a Linear model, which you will be able to understand and debug more easily.

In case you continue with the current methods, some ideas:

Check the initial weight values (init them with a normal distribution)

As a previous poster said, diminish the learning rate

Do some additional checking on the data, check for NAN and outliers, the current models could be more sensitive to noise. Remember, garbage in, garbage out.


问:
C# foreach with string - ignore last character
I have a methode who add numbers together parsed from a string.

If user type : "52+7+1", it will result in (60)
"52++2+3", "52+c+2", "+52+2", "52+2++", ... won't work.

My code works almost perfectly, expect... it ignores the last character. It works when, in the code I add "+0" to the string but of course it brokes the condition who prevent the user to type "+" as a last character.

```<code>    public int addFromString(string str)
    {
        bool valid_str = true;
        bool current_char_numeric = false;

        string unparsedNumber = "";
        int parsedNumber = 0;
        List<int> parsedNumbers = new List<int>();

        if (string.IsNullOrEmpty(chaine))
            chaine_valide = false;
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber))
               valid_str = false;

            if (!int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
                valid_str = false;
        }

        foreach (char c in str)
        {
            current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);

            if (current_char_numeric)
                unparsedNumber += c;
            else if(c == '+')
            {
                int.TryParse(unparsedNumber, out parsedNumber);
                parsedNumbers.Add(parsedNumber);

                if (str.IndexOf(c) < str.Length && str.ElementAt(str.IndexOf(c) + 1) == '+')
                    valid_str = false;

                //Just in case :
                unparsedNumber = "";
                current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);
            }
            else valid_str = false;
        }

        int result = 0;

        if(valid_str) { foreach(int n in parsedNumbers) { result += n; } }

        return result;
}
</code>```

So if I type : "52+2" I get 52

If I type : "52+2+6" I get 54

答:
You can do a more elegant version:</p>

```<code>public int addFromString(string str)
{
        int parsedNumber = 0;
        int result = 0;

        if (string.IsNullOrEmpty(chaine))
        {
            return result;
        }
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber)
                 || !int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
            {
                 return result;
            }
        }

        try
        {
             result = str.Split(new char[] { '+' }).Select(s => Convert.ToInt32(s)).Sum();
        }
        finally
        {
             return result;
        }
}
</code>```

Body:
I have a methode who add numbers together parsed from a string.

If user type : "52+7+1", it will result in (60)
"52++2+3", "52+c+2", "+52+2", "52+2++", ... won't work.

My code works almost perfectly, expect... it ignores the last character. It works when, in the code I add "+0" to the string but of course it brokes the condition who prevent the user to type "+" as a last character.

    public int addFromString(string str)
    {
        bool valid_str = true;
        bool current_char_numeric = false;

        string unparsedNumber = "";
        int parsedNumber = 0;
        List<int> parsedNumbers = new List<int>();

        if (string.IsNullOrEmpty(chaine))
            chaine_valide = false;
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber))
               valid_str = false;

            if (!int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
                valid_str = false;
        }

        foreach (char c in str)
        {
            current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);

            if (current_char_numeric)
                unparsedNumber += c;
            else if(c == '+')
            {
                int.TryParse(unparsedNumber, out parsedNumber);
                parsedNumbers.Add(parsedNumber);

                if (str.IndexOf(c) < str.Length && str.ElementAt(str.IndexOf(c) + 1) == '+')
                    valid_str = false;

                //Just in case :
                unparsedNumber = "";
                current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);
            }
            else valid_str = false;
        }

        int result = 0;

        if(valid_str) { foreach(int n in parsedNumbers) { result += n; } }

        return result;
}

So if I type : "52+2" I get 52

If I type : "52+2+6" I get 54

Body:
You can do a more elegant version:

public int addFromString(string str)
{
        int parsedNumber = 0;
        int result = 0;

        if (string.IsNullOrEmpty(chaine))
        {
            return result;
        }
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber)
                 || !int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
            {
                 return result;
            }
        }

        try
        {
             result = str.Split(new char[] { '+' }).Select(s => Convert.ToInt32(s)).Sum();
        }
        finally
        {
             return result;
        }
}


问:
Backbone events not delegated to new element after setElement
I'm implementing a Backbone view with an Underscore template. The view el is replaced with the template html using the setElement-function. The declaration of the function says that "...move the view's delegated events from the old element to the new one" but for some reason this doesn't work. Any ideas why this isn't working as described on Backbone declaration?

Here's an example of the situation (relevant parts of the view):

```<code>     initialize: function(args) {
        _.extend(this, args);
        this.listenTo(this.model, 'change', this.render);
     },

     events: {
        'click .active-area': '_test'
     },

     _test: function() {
        // After "setElement" this doesn't fire anymore.
        this.model.set('color', 'green');
     },

     render: function() {
        // After this the "click" listener no longer exists.
        this.setElement(this.template(this.model.toJSON());

        return this;
     }
</code>```

答:
this.template(...) isn't an element in the DOM.

In your code, setElement removes the event listeners from the old element, then delegates them to the new element, which only exist in memory, not on the page.

You should simply change the content of the current element instead.

```<code>this.$el.html(this.template(this.model.toJSON()));
</code>```

I need to replace the whole element html with the template html and that's why I need to use the setElement function.

Say you have the following HTML:

```<code><div id="currentView"><!-- view's root (el) -->
    <button type="button" class="active-area">Click me</button>
    <span class="color"><%= color %></span>
</div>
</code>```

Add a wrapping div and move the #currentView div into the template.

```<code><div class="wrapper"><!-- view's root (el) -->
    <div id="currentView">
        <button type="button" class="active-area">Click me</button>
        <span class="color"><%= color %></span>
    </div>
</div>
</code>```

Now this.$el.html will swap the whole element.

In the situation where you really want a view to swap its own root element, you can create a new element, then use jQuery's replaceWith to put the new element in place of the old.

```<code>render: function() {
    // create a new element from the template
    var $newEl = $(this.template(this.model.toJSON()));

    // completely replace the current element in the DOM
    this.$el.replaceWith($newEl);

    // then tell the view
    this.setElement($newEl);

    return this;
}
</code>```

Body:
I'm implementing a Backbone view with an Underscore template. The view el is replaced with the template html using the setElement-function. The declaration of the function says that "...move the view's delegated events from the old element to the new one" but for some reason this doesn't work. Any ideas why this isn't working as described on Backbone declaration?

Here's an example of the situation (relevant parts of the view):

     initialize: function(args) {
        _.extend(this, args);
        this.listenTo(this.model, 'change', this.render);
     },

     events: {
        'click .active-area': '_test'
     },

     _test: function() {
        // After "setElement" this doesn't fire anymore.
        this.model.set('color', 'green');
     },

     render: function() {
        // After this the "click" listener no longer exists.
        this.setElement(this.template(this.model.toJSON());

        return this;
     }

Body:
this.template(...) isn't an element in the DOM.

In your code, setElement removes the event listeners from the old element, then delegates them to the new element, which only exist in memory, not on the page.

You should simply change the content of the current element instead.

this.$el.html(this.template(this.model.toJSON()));

I need to replace the whole element html with the template html and that's why I need to use the setElement function.

Say you have the following HTML:

<div id="currentView"><!-- view's root (el) -->
    <button type="button" class="active-area">Click me</button>
    <span class="color"><%= color %></span>
</div>

Add a wrapping div and move the #currentView div into the template.

<div class="wrapper"><!-- view's root (el) -->
    <div id="currentView">
        <button type="button" class="active-area">Click me</button>
        <span class="color"><%= color %></span>
    </div>
</div>

Now this.$el.html will swap the whole element.

In the situation where you really want a view to swap its own root element, you can create a new element, then use jQuery's replaceWith to put the new element in place of the old.

render: function() {
    // create a new element from the template
    var $newEl = $(this.template(this.model.toJSON()));

    // completely replace the current element in the DOM
    this.$el.replaceWith($newEl);

    // then tell the view
    this.setElement($newEl);

    return this;
}


问:
How do I open an old Microsoft Access adp file with invalid connection strings?
We have moved our SQL Server instance to a new hosting company. Months later (after the overlapping migration period), front office have dug up an old adp file (old-school access data project) which connects to our (now non-existing) SQL Server. I need to change the connection string inside.

The file won't open, and crashes Access when I try.
I have searched in vain and only come across: "Hold down SHIFT while opening the file". This doesn't solve it.

Has anyone experienced this and has a solution?

答:
Well, I am going to close this question. Issue still exists (as such), but we are simply deleting the adp file now and build a replacement from scratch. I have now tried everything I can come to think of, including renaming the file extension to .mdb or .accdb, and unplugging the pc from any network connection while opening.

Every attempt ends in the same: Access does not respond, and I have to force-kill the application. I don't even know if the issue is what I suspect: the connection string being invalid due to a change of server names. But I can't think of any other explanation.


问:
How to extract the content of a cursor from a SQLite DB to a class?
i need to do a function on MyDBAdapter to extract a all the users from the SQLite database, and then, return a List<Friend>.

this is too munch hard for me, i am testing and trying to understand a lot of  google examples and stackoverflow posts but i can't do it

i tryed with this code but it doesn't works, CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3

```<code>public List<Friend> retrieveAllUsers()
    {
        List <Friend> friends=new ArrayList<Friend>();

        Cursor result=fetchAllUsers();

        for (int i=0; i<result.getCount();i++)
        {
            //note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
            friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
        }

        return friends;
    }
</code>```

please can someone help me doing that function ?

i have a user (Friend) class, like this:

```<code>public class Friend {
private String email; //id de usuario
    private String password;
    private String fullName;
    private String movilephone;
    private String movileOperatingSystem;
</code>```

And also i have a SQLite database like this:

```<code>public class MyDbAdapter {

    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";

    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }

    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
}
</code>```

答:
```<code>    Cursor result=fetchAllUsers();
    if( result.moveToFirst() ){
        do{
            //note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
            friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
        }while( result.moveToNext() );
    }
</code>```

Body:
i need to do a function on MyDBAdapter to extract a all the users from the SQLite database, and then, return a List<Friend>.

this is too munch hard for me, i am testing and trying to understand a lot of  google examples and stackoverflow posts but i can't do it

i tryed with this code but it doesn't works, CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3

public List<Friend> retrieveAllUsers()
    {
        List <Friend> friends=new ArrayList<Friend>();

        Cursor result=fetchAllUsers();

        for (int i=0; i<result.getCount();i++)
        {
            //note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
            friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
        }

        return friends;
    }

please can someone help me doing that function ?

i have a user (Friend) class, like this:

public class Friend {
private String email; //id de usuario
    private String password;
    private String fullName;
    private String movilephone;
    private String movileOperatingSystem;

And also i have a SQLite database like this:

public class MyDbAdapter {

    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";

    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }

    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
}


问:
Netsuite search filter for list of items
I am trying to add a filter in the search condition.

The problem I am facing is that while I am using the internalid and the int 1111 it works fine. But if i replace with some other column with string it does not work. It throws error in cust search line.
Can anyone suggest ?

```<code>        var custSearch = search.create({
        type : record.Type.CUSTOMER,
        columns : searchColumn,
        filters: [
                 'email', 'ANYOF', ["abanks@acera.com","3m@3m.com"]]
                 //'internalid', 'ANYOF', ["1397","1251"]] // Works fine

        });
        custSearch.run().each(function(result) { // throw errors
            log.debug("Found !",result);
            return true;
        });
</code>```

答:
function stringFieldAnyOf(fieldId, listOfValues) {
  var result = [];
  if (listOfValues.length > 0) {
    for (var i = 0; i < listOfValues.length; i++) {
      result.push([fieldId, 'startswith', listOfValues[i]]);
      result.push('or');
    }
    result.pop(); // remove the last 'or'
  }
  return result;
}

// usage: (two more filters added just to illustrate how to combine with other filters)
var custSearch = search.create({
  type: record.Type.CUSTOMER,
  columns: searchColumn,
  filters: [
    ['companyname', 'startswith', 'A'], 'and',
    stringFieldAnyOf('email', ['abanks@acera.com', '3m@3m.com']), 'and',
    ['companyname', 'contains', 'b']
  ]

});
```

Body:
I am trying to add a filter in the search condition.

The problem I am facing is that while I am using the internalid and the int 1111 it works fine. But if i replace with some other column with string it does not work. It throws error in cust search line.
Can anyone suggest ?

        var custSearch = search.create({
        type : record.Type.CUSTOMER,
        columns : searchColumn,
        filters: [
                 'email', 'ANYOF', ["abanks@acera.com","3m@3m.com"]]
                 //'internalid', 'ANYOF', ["1397","1251"]] // Works fine

        });
        custSearch.run().each(function(result) { // throw errors
            log.debug("Found !",result);
            return true;
        });


问:
PHP mysql json_set
I am stuck with the following: I have a mysql database (5.7). I want to update a json-data-entry.

This is how my data in the database looks like:

```<code>{
    "version": {
        "0": {
            "value": "1.9.6.81"
        }
    }
}
</code>```

When I try to update this field with SQL directly from the command line there is no issue:

```<code>update item set elements = JSON_SET(elements, '$."version"."0"."value"', "1.9.8.40") where name like 'Client XZY';
</code>```

but when I try it with PHP, I have some issues with the mixed quotes and double quotes.

```<code>$connection = new mysqli('localhost', 'user', 'password');
$updateSql = "update item set elements = JSON_SET(elements, '$."version'.'0'.'value"', '1.9.8.20') where name like 'Client XYZ';';

if($connection->query($updateSql) === TRUE){
        echo 'good :) ';
}
else{
        echo 'bad :( ';
}
</code>```

答:
got it working </p>

```<code>$connection = new mysqli('localhost', 'root', 'xxxxx');
mysqli_select_db($connection,"MYSQL5");

$updateSql = "UPDATE item SET elements = JSON_SET(elements, '$.\"version\".\"0\".\"value\"', '1.9.8.40') WHERE name LIKE 'lient XYZ';";

if($connection->query($updateSql) === TRUE){
        echo 'good :)';
}
else{
        printf("Errormessage: %s\n", $connection->error);
}
</code>```

Title: PHP mysql json_set

Body:
I am stuck with the following: I have a mysql database (5.7). I want to update a json-data-entry.

This is how my data in the database looks like:

{
    "version": {
        "0": {
            "value": "1.9.6.81"
        }
    }
}

When I try to update this field with SQL directly from the command line there is no issue:

update item set elements = JSON_SET(elements, '$."version"."0"."value"', "1.9.8.40") where name like 'Client XZY';

but when I try it with PHP, I have some issues with the mixed quotes and double quotes.

$connection = new mysqli('localhost', 'user', 'password');
$updateSql = "update item set elements = JSON_SET(elements, '$."version'.'0'.'value"', '1.9.8.20') where name like 'Client XYZ';';

if($connection->query($updateSql) === TRUE){
        echo 'good :) ';
}
else{
        echo 'bad :( ';
}

Body:
got it working

$connection = new mysqli('localhost', 'root', 'xxxxx');
mysqli_select_db($connection,"MYSQL5");

$updateSql = "UPDATE item SET elements = JSON_SET(elements, '$.\"version\".\"0\".\"value\"', '1.9.8.40') WHERE name LIKE 'lient XYZ';";

if($connection->query($updateSql) === TRUE){
        echo 'good :)';
}
else{
        printf("Errormessage: %s\n", $connection->error);
}


问:
How to remove all non-uppercase characters in a string?
Yeah I'm basically just trying to explode a phrase like Social Inc. or David Jason to SI and DJ. I've tried using explode but couldn't figure out how to explode everything BUT the capital letters, do I need to use preg_match()?

答:
Quick and easy:

```<code>$ucaseletters = preg_replace('/[^A-Z]/', '', $input);
</code>```

This will replace everything that is not an uppercase Letter within the Range A-Z.

Explanation:

```<code>^ within [] (Character-Set) is the negation-Operator (=anything that is NOT...)
</code>```

Body:
Quick and easy:

$ucaseletters = preg_replace('/[^A-Z]/', '', $input);

This will replace everything that is not an uppercase Letter within the Range A-Z.

Explanation:

^ within [] (Character-Set) is the negation-Operator (=anything that is NOT...)


问:
Get min,max and avg per hour of the created_at time
I have a table with a field created_at with the following values:

```<code>2017-06-06 13:04:50
2017-06-06 13:09:54
2017-06-06 13:20:20
2017-06-06 13:40:29
2017-06-06 14:05:30
2017-06-06 14:12:50
2017-06-06 14:30:40
2017-06-06 15:01:36
2017-06-06 15:06:16
</code>```

What I want is to create a new table and do the following thing:
I want to get per hour the min, max and average and save it into another table.

Body:
I have a table with a field created_at with the following values:

2017-06-06 13:04:50
2017-06-06 13:09:54
2017-06-06 13:20:20
2017-06-06 13:40:29
2017-06-06 14:05:30
2017-06-06 14:12:50
2017-06-06 14:30:40
2017-06-06 15:01:36
2017-06-06 15:06:16

What I want is to create a new table and do the following thing:
I want to get per hour the min, max and average and save it into another table.

Body:
Here is a start for you.

I make new date values with Y-m-d H values.

Since I remove the minutes and seconds all times in the same hour will be duplicates.

The I count the duplicate values with array count values.

https://3v4l.org/690ne

$arr = array("2017-06-06 13:04:50",
"2017-06-06 13:09:54",
"2017-06-06 13:20:20",
"2017-06-06 13:40:29",
"2017-06-06 14:05:30",
"2017-06-06 14:12:50",
"2017-06-06 14:30:40",
"2017-06-06 15:01:36",
"2017-06-06 15:06:16");

Foreach($arr as $val){
    $newarr[] = date("Y-m-d H", strtotime($val));
}

Var_dump($newarr);

Var_dump(array_count_values($newarr));

Output of above code is:

array(9) {

    [0]=>

    string(13) "2017-06-06 13"

    [1]=>

    string(13) "2017-06-06 13"

    [2]=>

    string(13) "2017-06-06 13"

    [3]=>

    string(13) "2017-06-06 13"

    [4]=>

    string(13) "2017-06-06 14"

    [5]=>

    string(13) "2017-06-06 14"

    [6]=>

    string(13) "2017-06-06 14"

    [7]=>

    string(13) "2017-06-06 15"

    [8]=>

    string(13) "2017-06-06 15"

  }

  array(3) {

    ["2017-06-06 13"]=>

    int(4)

    ["2017-06-06 14"]=>

    int(3)

    ["2017-06-06 15"]=>

    int(2)

  }

Edit reading David's answer it seems it was unclear what "per hour" means.

David reads it as one hour rolling time.

I read it as between 13-14, between 14-15 and so on.


问:
Do I need to run compaction on each node of the cluster in cassandra 3
We are having 4 node cassandra cluster . Do I need to run compact and repair on each node of the cluster ?

Cassandra Version:- Cassandra 3.0.10
No of nodes in a cluster : 4
Replication Factor :- 4
Compaction Strategy:- LeveledCompactionStrategy

Thanks

答:
To answer the question, "Yes" compaction needs to run on all nodes.

The right answer, is that you shouldn't be the one running compaction.  Cassandra is almost always capable of figuring out when to run compaction on its own, and you should not need to invoke it manually.

In fact, once you run compaction manually, the odds of compaction happening organically in the future are minuscule, so then you're stuck having to do it manually.

Similar answer on DBA.StackExchange: https://dba.stackexchange.com/questions/71781/cassandra-maintenance/74213#74213


问:
Adding content to wordpress page
So, i finally got my css and js scripts to load on WP

Now there is but one thing i need to get done.

i have my own theme, including header.php, footer.php, page.php

header.php and footer.php is working just fine, loading scripts and showing properly, but now i need to add all the other content.

my page.php is currently:

```<code><?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php the_content(); ?>

<?php get_footer(); ?>
</code>```

I would need to somehow add html content to pages, i have about 20 ready made .php pages which needs to be transfered to WP.

Soooo how do i go about making new page (pages -> add new) and using page template while getting the html content to show up?

I've tried to just make new page and in text mode add up all the html into page, but it only shows empty page with header and footer, so the problem is most likely the page.php and i have no idea how to get it to work.

答:
To get started adding a new page to your WordPress site, find the Pages menu in the WordPress Dashboard Navigation menu. Click Add new.

The WordPress page editor looks nearly identical to the post editor, except for a few different boxes located on the right side of the screen.

Add the title of the page, like About. Note: If you have pretty permalinks set up, the title of your page will also be the URL slug.

Next, add some content.

The Publish section of the page editor is exactly the same as for writing posts. When you’re ready to publish, you can either publish immediately, save this or a draft, or schedule the page to be published later.

The Page Attributes section applies a parent page and template to your new page. For the Parent section, you can arrange your pages into hierarchies. For example, you could create this new page with additional pages under it. There are no limits to how many levels you can nest pages.

Some WordPress themes have custom page templates, so the next Template section allows you to apply a template to your new page.

The Order box allows you to order your page numerically. Pages are usually ordered alphabetically, but you can choose your own order by entering a number in this field.

Preview the page one last time, then click Publish. You’ve added a new page to your WordPress site.

This is how your
your index.php should look like :

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

<div class="YourContainer">

 <div class="Whatever">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <div class="ContentSectionDiv">

   <?php the_content();?>

  </div>
  <?php endwhile; ?>
  <?php else: ?>
<?php endif; ?>
 </div>
</div>

 <?php get_footer();?>
</code>```

Title: Adding content to wordpress page

Body:
So, i finally got my css and js scripts to load on WP

Now there is but one thing i need to get done.

i have my own theme, including header.php, footer.php, page.php

header.php and footer.php is working just fine, loading scripts and showing properly, but now i need to add all the other content.

my page.php is currently:

<?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php the_content(); ?>

<?php get_footer(); ?>

I would need to somehow add html content to pages, i have about 20 ready made .php pages which needs to be transfered to WP.

Soooo how do i go about making new page (pages -> add new) and using page template while getting the html content to show up?

I've tried to just make new page and in text mode add up all the html into page, but it only shows empty page with header and footer, so the problem is most likely the page.php and i have no idea how to get it to work.

Body:
To get started adding a new page to your WordPress site, find the Pages menu in the WordPress Dashboard Navigation menu. Click Add new.

The WordPress page editor looks nearly identical to the post editor, except for a few different boxes located on the right side of the screen.

Add the title of the page, like About. Note: If you have pretty permalinks set up, the title of your page will also be the URL slug.

Next, add some content.

The Publish section of the page editor is exactly the same as for writing posts. When you’re ready to publish, you can either publish immediately, save this or a draft, or schedule the page to be published later.

The Page Attributes section applies a parent page and template to your new page. For the Parent section, you can arrange your pages into hierarchies. For example, you could create this new page with additional pages under it. There are no limits to how many levels you can nest pages.

Some WordPress themes have custom page templates, so the next Template section allows you to apply a template to your new page.

The Order box allows you to order your page numerically. Pages are usually ordered alphabetically, but you can choose your own order by entering a number in this field.

Preview the page one last time, then click Publish. You’ve added a new page to your WordPress site.

This is how your
your index.php should look like :

<?php
 get_header();?>

<div class="YourContainer">

 <div class="Whatever">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <div class="ContentSectionDiv">

   <?php the_content();?>

  </div>
  <?php endwhile; ?>
  <?php else: ?>
<?php endif; ?>
 </div>
</div>

 <?php get_footer();?>


问:
MS Access SQL: Troubles combining UNION ALL with a LEFT JOIN
I have created a query in MS Access to simulate a FULL OUTER JOIN and combine the results that looks something like the following:

```<code>SELECT NZ(estimates.employee_id, actuals.employee_id) AS employee_id
, NZ(estimates.a_date, actuals.a_date) AS a_date
, estimates.estimated_hours
, actuals.actual_hours
FROM (SELECT *
      FROM estimates
      LEFT JOIN actuals ON estimates.employee_id = actuals.employee_id
         AND estimates.a_date = actuals.a_date
      UNION ALL
      SELECT *
      FROM estimates
      RIGHT JOIN actuals ON estimates.employee_id = actuals.employee_id
         AND estimates.a_date = actuals.a_date
      WHERE estimates.employee_id IS NULL
         OR estimates.a_date IS NULL) AS qFullJoinEstimatesActuals
</code>```

I have saved this query as an object (let's call it qEstimatesAndActuals).  My objective is to LEFT JOIN qEstimatesAndActuals with another table.  Something like the following:

```<code>SELECT *
FROM qJoinedTable
LEFT JOIN (SELECT *
           FROM labor_rates) AS rates
ON qJoinedTable.employee_id = rates.employee_id
   AND qJoinedTable.a_date BETWEEN rates.begin_date AND rates.end_date
</code>```

MS Access accepts the syntax and runs the query, but it omits results that are clearly within the result set.  Wondering if the date format was somehow lost, I placed a FORMAT around the begin_date and end_date to force them to be interpreted as Short Dates.  Oddly, this produced a different result set, but it still omitted result that it shouldn't have.

I am wondering if the queries are performed in such a way that you can't LEFT JOIN the result set of a UNION ALL.  Does anyone have any thoughts/ideas on this?  Is there a better way of accomplishing the end goal?

答:
Consistent with the odd behavior surrounding the dates, this issue turned out to be related to the use of NZ to select a date from qFullJoinEstimatesActuals.  The use of NZ appears to make the data type ambiguous.  As such, the following line from the example in my post caused the error:

```<code>, NZ(estimates.a_date, actuals.a_date) AS a_date
</code>```

The ambiguous data type of a_date caused the BETWEEN operator to produce erroneous results when comparing a_date to rates.begin_date and rates.end_date in the LEFT JOIN.  The issue was resolved by type casting the result of the NZ function, as follows:

```<code>, CDate(NZ(estimates.a_date, actuals.a_date)) AS a_date
</code>```

Body:
I have created a query in MS Access to simulate a FULL OUTER JOIN and combine the results that looks something like the following:

SELECT NZ(estimates.employee_id, actuals.employee_id) AS employee_id
, NZ(estimates.a_date, actuals.a_date) AS a_date
, estimates.estimated_hours
, actuals.actual_hours
FROM (SELECT *
      FROM estimates
      LEFT JOIN actuals ON estimates.employee_id = actuals.employee_id
         AND estimates.a_date = actuals.a_date
      UNION ALL
      SELECT *
      FROM estimates
      RIGHT JOIN actuals ON estimates.employee_id = actuals.employee_id
         AND estimates.a_date = actuals.a_date
      WHERE estimates.employee_id IS NULL
         OR estimates.a_date IS NULL) AS qFullJoinEstimatesActuals

I have saved this query as an object (let's call it qEstimatesAndActuals).  My objective is to LEFT JOIN qEstimatesAndActuals with another table.  Something like the following:

SELECT *
FROM qJoinedTable
LEFT JOIN (SELECT *
           FROM labor_rates) AS rates
ON qJoinedTable.employee_id = rates.employee_id
   AND qJoinedTable.a_date BETWEEN rates.begin_date AND rates.end_date

MS Access accepts the syntax and runs the query, but it omits results that are clearly within the result set.  Wondering if the date format was somehow lost, I placed a FORMAT around the begin_date and end_date to force them to be interpreted as Short Dates.  Oddly, this produced a different result set, but it still omitted result that it shouldn't have.

I am wondering if the queries are performed in such a way that you can't LEFT JOIN the result set of a UNION ALL.  Does anyone have any thoughts/ideas on this?  Is there a better way of accomplishing the end goal?

Body:
Consistent with the odd behavior surrounding the dates, this issue turned out to be related to the use of NZ to select a date from qFullJoinEstimatesActuals.  The use of NZ appears to make the data type ambiguous.  As such, the following line from the example in my post caused the error:

, NZ(estimates.a_date, actuals.a_date) AS a_date

The ambiguous data type of a_date caused the BETWEEN operator to produce erroneous results when comparing a_date to rates.begin_date and rates.end_date in the LEFT JOIN.  The issue was resolved by type casting the result of the NZ function, as follows:

, CDate(NZ(estimates.a_date, actuals.a_date)) AS a_date


问:
knockout "submit" interferring with Razor @html.beginform submit
I have a form that includes some Knockout code, but the form is being submitted too early.  I have the following

```<code>  <form data-bind="submit:addItem">
            Add illness: <input type="text" data-bind='value:itemToAdd, valueUpdate: "afterkeydown"' />
            <button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
        </form>
</code>```

The button is interfering with my Razor form, I assume that because it is of type="submit", so when I click this button unfortunately the form is being submitted, when all I want to use this button for is to call a Knockout function.

So I guess one way to solve the problem is to not use the code above, but I don't know what the alternative would be.  Hopefully I don't need to put type="submit" right there, because I need to save that functionality for when I submit my final form much much later

答:
Try this:

```<code><form data-bind="submit:addItem.bind($data)">
</code>```

I use the .bind in all my click events as it stops the click events being fired on applying of bindings and also allows you to pass extra parameters.

Body:
I have a form that includes some Knockout code, but the form is being submitted too early.  I have the following

  <form data-bind="submit:addItem">
            Add illness: <input type="text" data-bind='value:itemToAdd, valueUpdate: "afterkeydown"' />
            <button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
        </form>

The button is interfering with my Razor form, I assume that because it is of type="submit", so when I click this button unfortunately the form is being submitted, when all I want to use this button for is to call a Knockout function.

So I guess one way to solve the problem is to not use the code above, but I don't know what the alternative would be.  Hopefully I don't need to put type="submit" right there, because I need to save that functionality for when I submit my final form much much later

Body:
Try this:

<form data-bind="submit:addItem.bind($data)">

I use the .bind in all my click events as it stops the click events being fired on applying of bindings and also allows you to pass extra parameters.


问:
Updating the contents of a kml file, using libxml2 library in C
I am trying to extract particular data set using libxml2 header file using C. Every other part is working except for the change of contents of the node. This is very crucial since I dont want the program to read the same set of data points. The program works without error but the content wont change.

Here is the part of the code :

```<code>int parseName (xmlDocPtr doc,xmlNodePtr cur) {
    xmlChar *key;
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if ((!xmlStrcmp(cur->name, (const xmlChar *)"Placemark"))) {
            cur = cur ->xmlChildrenNode;
            while(cur != NULL){
                if((!xmlStrcmp(cur->name, (const xmlChar *)"name"))) {
                    key = xmlNodeListGetString(doc,cur->xmlChildrenNode,1);
                    if((!xmlStrcmp(key,(const xmlChar *)"Untitled Polygon"))){
                        xmlNodeSetContent(cur->content,(const xmlChar *)"Done");
                        return 1;
                    }
                    else if((!xmlStrcmp(key,(const xmlChar *)"Out")))
                        return -1;

                }
                cur=cur->next;
            }

    }
    cur=cur->next;
    }
return 0;
}
</code>```

Here xmlNodeSetContent does not work. But the function still returns 1.

Edit : The kml file goes like this :

```<code><?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<Placemark>
        <name>Untitled Polygon</name>
        <styleUrl>#m_ylw-pushpin</styleUrl>
        <Polygon>
            <tessellate>1</tessellate>
            <outerBoundaryIs>
                <LinearRing>
                    <coordinates>
                        77.58482071603055,12.86858949944241,0 77.60057575684357,12.86642619038822,0 77.60374633781389,12.88004602175216,0 77.5844101227442,12.88296731261186,0 77.58482071603055,12.86858949944241,0
                    </coordinates>
                </LinearRing>
            </outerBoundaryIs>
        </Polygon>
    </Placemark>
</Document>
</kml>
</code>```

I can succesfully extract the coordinates but cannot change the name to something else. It just sticks to "Untitled Polygon".

Update answer : One line changed, xmlNodeSetContent(cur->xmlChildrenNode,(const xmlChar *)"Done"); and one more line is to be added to save the changes made to the content of the file : xmlSaveFormatFile ("NOW1.kml", doc, 0);
Thank you.

答:
xmlNodeSetContent takes an xmlNodePtr as first argument:

```<code>void xmlNodeSetContent (xmlNodePtr cur,
                        const xmlChar * content)
</code>```

So change the line

```<code>xmlNodeSetContent(cur->content,(const xmlChar *)"Done");
</code>```

to

```<code>xmlNodeSetContent(cur, (const xmlChar *)"Done");
</code>```

If you had enabled compiler warnings, the compiler would have pointed you to this issue.

Body:
I am trying to extract particular data set using libxml2 header file using C. Every other part is working except for the change of contents of the node. This is very crucial since I dont want the program to read the same set of data points. The program works without error but the content wont change.

Here is the part of the code :

int parseName (xmlDocPtr doc,xmlNodePtr cur) {
    xmlChar *key;
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if ((!xmlStrcmp(cur->name, (const xmlChar *)"Placemark"))) {
            cur = cur ->xmlChildrenNode;
            while(cur != NULL){
                if((!xmlStrcmp(cur->name, (const xmlChar *)"name"))) {
                    key = xmlNodeListGetString(doc,cur->xmlChildrenNode,1);
                    if((!xmlStrcmp(key,(const xmlChar *)"Untitled Polygon"))){
                        xmlNodeSetContent(cur->content,(const xmlChar *)"Done");
                        return 1;
                    }
                    else if((!xmlStrcmp(key,(const xmlChar *)"Out")))
                        return -1;

                }
                cur=cur->next;
            }

    }
    cur=cur->next;
    }
return 0;
}

Here xmlNodeSetContent does not work. But the function still returns 1.

Edit : The kml file goes like this :

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<Placemark>
        <name>Untitled Polygon</name>

        <Polygon>
            <tessellate>1</tessellate>
            <outerBoundaryIs>
                <LinearRing>
                    <coordinates>
                        77.58482071603055,12.86858949944241,0 77.60057575684357,12.86642619038822,0 77.60374633781389,12.88004602175216,0 77.5844101227442,12.88296731261186,0 77.58482071603055,12.86858949944241,0
                    </coordinates>
                </LinearRing>
            </outerBoundaryIs>
        </Polygon>
    </Placemark>
</Document>
</kml>

I can succesfully extract the coordinates but cannot change the name to something else. It just sticks to "Untitled Polygon".

Update answer : One line changed, xmlNodeSetContent(cur->xmlChildrenNode,(const xmlChar *)"Done"); and one more line is to be added to save the changes made to the content of the file : xmlSaveFormatFile ("NOW1.kml", doc, 0);
Thank you.

Body:
xmlNodeSetContent takes an xmlNodePtr as first argument:

void xmlNodeSetContent (xmlNodePtr cur,
                        const xmlChar * content)

So change the line

xmlNodeSetContent(cur->content,(const xmlChar *)"Done");

to

xmlNodeSetContent(cur, (const xmlChar *)"Done");

If you had enabled compiler warnings, the compiler would have pointed you to this issue.


问:
Manage abstract classes in std container
After a lot of research I still don't understand how to deal with an abstract class collection with smart pointers.

Here are the errors I got:

```<code>error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Shape; _Dp = std::default_delete<Shape>]'
   base_ptr s = shapes.front();

error: no matching function for call to 'std::unique_ptr<Shape>::unique_ptr(Shape&)'
   shapes.push(base_ptr(b));
</code>```

By compiling the minimal code to replicate the error (code online avaiable).

```<code>    #include <queue>
    #include <memory>

    class Shape {
    public:
        virtual int getPerimeter() =0;
    };

    typedef std::unique_ptr<Shape> base_ptr;

    class Circle : public Shape {
    public:
        virtual int getPerimeter() { return 1; };
    };

    class Square : public Shape {
    public:
        virtual int getPerimeter() { return 0; };
    };

    class ShapeManager {
    public:
        ShapeManager();
        void useShape() {
            if(shapes.empty())
                throw "Work stack is empty.";

            base_ptr s = shapes.front();
            s->getPerimeter();
            shapes.pop();
        }

        void submitShape(Shape &b) {
            shapes.push(base_ptr(b));
        }
    private:
        std::queue<base_ptr> shapes;
    };

    int main(int argc, char **argv) {
        ShapeManager s();
        Circle c;
        s.submitShape(c);
        s.useShape();
        return 1;
    }
</code>```

It works if I declare the queue as queue<Shape*> but I don't want to deal with pointers -meaning *.

EDIT, this code compiles. Thanks everyone. This article suggested by Guillaume Racicot helps seeing clearer the situation.

```<code>#include <queue>
#include <memory>

class Shape {
public:
    virtual int getPerimeter() =0;
};

typedef std::unique_ptr<Shape> base_ptr;

class Circle : public Shape {
public:
    Circle() {};
    virtual int getPerimeter() { return 1; };
};

class Square : public Shape {
public:
    virtual int getPerimeter() { return 0; };
};

class ShapeManager {
public:
    ShapeManager();
    void useShape() {
        if(shapes.empty())
            throw "Work stack is empty.";

        base_ptr s = std::move(shapes.front());
        s->getPerimeter();
        shapes.pop();
    }

    void submitShape(base_ptr b) {
        shapes.push(std::move(b));
    }
private:
    std::queue<base_ptr> shapes;
};

int main(int argc, char **argv) {
    ShapeManager s;
    base_ptr c = std::make_unique<Circle>();
    s.submitShape(std::move(c));
    s.useShape();
    return 1;
}
</code>```

答:
There are many problems in your example, not just misuse of smart pointers. First, the most obvious once is your declaration of s:

```<code>ShapeManager s();
</code>```

This declares a function named s that returns a ShapeManager and takes no parameter.

Maybe you meant to declare an object of type ShapeManager?

```<code>ShapeManager s{};

// Or

ShapeManager s;
</code>```

Secondly, you are misusing smart pointer. You have a queue of unique pointer. A unique pointer is a RAII wrapper around a free store allocated object. That means that it's a wrapper that is constructed with an object allocated with new. In your example, you're not doing that. You are constructing unique pointer with an object that has automatic storage.

A smart pointer that points to a automatic storage allocated object is the observer pointer: is must not own, delete or try to manage anything about that object. In fact, observer pointer is a language feature instead of a library one. It's commonly called a pointer.

This is your code with usage of observer pointers:

```<code>template<typename T>
using observer_ptr = T*;

struct ShapeManager {
    void useShape() {
        if(shapes.empty())
            throw "Work stack is empty.";

        auto s = shapes.front();

        s->getPerimeter();
        shapes.pop();
    }

    void submitShape(Shape &b) {
        shapes.push(&b);
    }

private:
    std::queue<base_ptr> shapes;
};

int main() {
    ShapeManager s;
    Circle c; // Automatic storage
    Rectangle r; // Automatic storage too.

    s.submitShape(c);
    s.submitShape(r);
    s.useShape();
}
</code>```

However, you might not want to hold them using automatic storage. My guess is you want to use std::unique_ptr everywhere instead. This allow the object submitted to the shape manager to outlive it's scope. For that you'll need to allocate objects on the free store. The most common way is to use std::make_unique:

```<code>struct ShapeManager {
    void useShape() {
        if(shapes.empty())
            throw "Work stack is empty.";

        // We must create a reference,
        // Using simply auto would require copy,
        // Which is prohibited by unique pointers
        auto&& s = shapes.front();

        s->getPerimeter();
        shapes.pop();
    }

    void submitShape(base_ptr b) {
        shapes.push(std::move(b));
    }

private:
    std::queue<base_ptr> shapes;
};

int main() {
    ShapeManager s;

    // Allocated on the free store,
    // The lifetime of c and r are managed by
    // The unique pointer.
    auto c = std::make_unique<Circle>();
    auto r = std::make_unique<Rectangle>();

    s.submitShape(std::move(c));
    s.submitShape(std::move(r));
    s.useShape();
}
</code>```

Body:
After a lot of research I still don't understand how to deal with an abstract class collection with smart pointers.

Here are the errors I got:

error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Shape; _Dp = std::default_delete<Shape>]'
   base_ptr s = shapes.front();

error: no matching function for call to 'std::unique_ptr<Shape>::unique_ptr(Shape&)'
   shapes.push(base_ptr(b));

By compiling the minimal code to replicate the error (code online avaiable).

    #include <queue>
    #include <memory>

    class Shape {
    public:
        virtual int getPerimeter() =0;
    };

    typedef std::unique_ptr<Shape> base_ptr;

    class Circle : public Shape {
    public:
        virtual int getPerimeter() { return 1; };
    };

    class Square : public Shape {
    public:
        virtual int getPerimeter() { return 0; };
    };

    class ShapeManager {
    public:
        ShapeManager();
        void useShape() {
            if(shapes.empty())
                throw "Work stack is empty.";

            base_ptr s = shapes.front();
            s->getPerimeter();
            shapes.pop();
        }

        void submitShape(Shape &b) {
            shapes.push(base_ptr(b));
        }
    private:
        std::queue<base_ptr> shapes;
    };

    int main(int argc, char **argv) {
        ShapeManager s();
        Circle c;
        s.submitShape(c);
        s.useShape();
        return 1;
    }

It works if I declare the queue as queue<Shape*> but I don't want to deal with pointers -meaning *.

EDIT, this code compiles. Thanks everyone. This article suggested by Guillaume Racicot helps seeing clearer the situation.

#include <queue>
#include <memory>

class Shape {
public:
    virtual int getPerimeter() =0;
};

typedef std::unique_ptr<Shape> base_ptr;

class Circle : public Shape {
public:
    Circle() {};
    virtual int getPerimeter() { return 1; };
};

class Square : public Shape {
public:
    virtual int getPerimeter() { return 0; };
};

class ShapeManager {
public:
    ShapeManager();
    void useShape() {
        if(shapes.empty())
            throw "Work stack is empty.";

        base_ptr s = std::move(shapes.front());
        s->getPerimeter();
        shapes.pop();
    }

    void submitShape(base_ptr b) {
        shapes.push(std::move(b));
    }
private:
    std::queue<base_ptr> shapes;
};

int main(int argc, char **argv) {
    ShapeManager s;
    base_ptr c = std::make_unique<Circle>();
    s.submitShape(std::move(c));
    s.useShape();
    return 1;
}

Body:
There are many problems in your example, not just misuse of smart pointers. First, the most obvious once is your declaration of s:

ShapeManager s();

This declares a function named s that returns a ShapeManager and takes no parameter.

Maybe you meant to declare an object of type ShapeManager?

ShapeManager s{};

// Or

ShapeManager s;

Secondly, you are misusing smart pointer. You have a queue of unique pointer. A unique pointer is a RAII wrapper around a free store allocated object. That means that it's a wrapper that is constructed with an object allocated with new. In your example, you're not doing that. You are constructing unique pointer with an object that has automatic storage.

A smart pointer that points to a automatic storage allocated object is the observer pointer: is must not own, delete or try to manage anything about that object. In fact, observer pointer is a language feature instead of a library one. It's commonly called a pointer.

This is your code with usage of observer pointers:

template<typename T>
using observer_ptr = T*;

struct ShapeManager {
    void useShape() {
        if(shapes.empty())
            throw "Work stack is empty.";

        auto s = shapes.front();

        s->getPerimeter();
        shapes.pop();
    }

    void submitShape(Shape &b) {
        shapes.push(&b);
    }

private:
    std::queue<base_ptr> shapes;
};

int main() {
    ShapeManager s;
    Circle c; // Automatic storage
    Rectangle r; // Automatic storage too.

    s.submitShape(c);
    s.submitShape(r);
    s.useShape();
}

However, you might not want to hold them using automatic storage. My guess is you want to use std::unique_ptr everywhere instead. This allow the object submitted to the shape manager to outlive it's scope. For that you'll need to allocate objects on the free store. The most common way is to use std::make_unique:

struct ShapeManager {
    void useShape() {
        if(shapes.empty())
            throw "Work stack is empty.";

        // We must create a reference,
        // Using simply auto would require copy,
        // Which is prohibited by unique pointers
        auto&& s = shapes.front();

        s->getPerimeter();
        shapes.pop();
    }

    void submitShape(base_ptr b) {
        shapes.push(std::move(b));
    }

private:
    std::queue<base_ptr> shapes;
};

int main() {
    ShapeManager s;

    // Allocated on the free store,
    // The lifetime of c and r are managed by
    // The unique pointer.
    auto c = std::make_unique<Circle>();
    auto r = std::make_unique<Rectangle>();

    s.submitShape(std::move(c));
    s.submitShape(std::move(r));
    s.useShape();
}


问:
MySQL subquery, get 2 most recent rows of type
I'm trying to get the two latest rows of each type.

```<code>ID  TYPE    SCORE
-----------------
1   EUR       2
2   EUR       3
3   CAD       5
4   CAD       6
5   CAD       7
6   CAD       8
7   USD       5
8   USD       3
9   USD       7
10  USD       2
</code>```

The results returned should be id's:1,2,5,6,9,10.

How do i accomplishthis with mysql subquery?  I attempted below..

```<code>$sql = "SELECT * FROM `data_analysis_child`
        WHERE type IN
    (SELECT type FROM `data_analysis_child` ORDER by id DESC LIMIT 2)";

$query = $this->db->query($sql);
</code>```

How do i solve?

答:
You can try this.</p>

```<code>   select * from
(SELECT  t.*,@row_num := IF(@TYPE1=type,@row_num+1,1)AS RowNumber,@TYPE1=type  FROM data_analysis_child t, (SELECT @row_num := 1) x,(SELECT @TYPE1 := '') y
order by type desc,id desc) where RowNumber<=2
</code>```

Body:
I'm trying to get the two latest rows of each type.

ID  TYPE    SCORE
-----------------
1   EUR       2
2   EUR       3
3   CAD       5
4   CAD       6
5   CAD       7
6   CAD       8
7   USD       5
8   USD       3
9   USD       7
10  USD       2

The results returned should be id's:1,2,5,6,9,10.

How do i accomplishthis with mysql subquery?  I attempted below..

$sql = "SELECT * FROM `data_analysis_child`
        WHERE type IN
    (SELECT type FROM `data_analysis_child` ORDER by id DESC LIMIT 2)";

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

How do i solve?

Body:
You can try this.

   select * from
(SELECT  t.*,@row_num := IF(@TYPE1=type,@row_num+1,1)AS RowNumber,@TYPE1=type  FROM data_analysis_child t, (SELECT @row_num := 1) x,(SELECT @TYPE1 := '') y
order by type desc,id desc) where RowNumber<=2


问:
js setAttribute with Array
I have a problem with setAttribute. I set an Array as the value of rotation, but it doesn't work.  Alert of gradRoll is a number. But the type of gradRoll is undefined. Why? Can anybody help me? thanks in advance.

```<code>AFRAME.registerComponent('clockhand_roll',{
    schema:{
      type:'string', default: "secondClockhand"
    },

    init:function(){
      var data = this.data;
      var el=this.el;

      var oTime= new Date();
      var curTime;

      var clockhandPositonArray;

      if(data == "secondClockhand" ){
        curTime = oTime.getSeconds();
      }else if(data == "minuteClockhand"){
        curTime = oTime.getMinutes();
      }else if(data == "hourClockhand"){
        curTime = oTome.getHours;
      }else {
        alert("invalid input!");
      }

      //alert(curTime);
      //clockhandPositonArray=getClockhandPosition(curTime, data);
      //alert(el.getAttribute("rotation"));

      //el.setAttribute("rotation", 'clockhandPositonArray');

      setClockhandPosition(el, curTime, data);

    }
  });

  function setClockhandPosition(el, curTime, typeOfClockhand){
    var gradForOneUnit;
    var gradRoll;
    var rotationArray;

    if(typeOfClockhand == "secondClockhand" || typeOfClockhand == "minuteClockhand"){
      gradForOneUnit=360/60;
    }else if(typeOfClockhand == "hourClockhand"){
      gradForOneUnit=360/12;
    }

    gardRoll=curTime*gradForOneUnit;

    //alert(gardRoll); //number: 354!!!!!!!!!!!!!!!!!!!! why??????
    //alert(typeof(gradRoll)); //undefined!!!!!!!!!!!!!  why??????

    rotationArray=[curTime*gradForOneUnit, 0, 0];

    //alert(typeof(rotationArray));//object
    //alert(typeof(el.getAttribute("rotation"))); //object

    //alert(rotationArray); //number: 162 , 0, 0

    el.setAttribute("rotation", rotationArray); //dosn't work.
  }
</code>```

答:
Use:

```<code>el.setAttribute("transform", "rotate3d,x,y,z,angle)");
</code>```

or combine rotateX, rotateY, rotateZ.

Title: js setAttribute with Array

Body:
I have a problem with setAttribute. I set an Array as the value of rotation, but it doesn't work.  Alert of gradRoll is a number. But the type of gradRoll is undefined. Why? Can anybody help me? thanks in advance.

AFRAME.registerComponent('clockhand_roll',{
    schema:{
      type:'string', default: "secondClockhand"
    },

    init:function(){
      var data = this.data;
      var el=this.el;

      var oTime= new Date();
      var curTime;

      var clockhandPositonArray;

      if(data == "secondClockhand" ){
        curTime = oTime.getSeconds();
      }else if(data == "minuteClockhand"){
        curTime = oTime.getMinutes();
      }else if(data == "hourClockhand"){
        curTime = oTome.getHours;
      }else {
        alert("invalid input!");
      }

      //alert(curTime);
      //clockhandPositonArray=getClockhandPosition(curTime, data);
      //alert(el.getAttribute("rotation"));

      //el.setAttribute("rotation", 'clockhandPositonArray');

      setClockhandPosition(el, curTime, data);

    }
  });

  function setClockhandPosition(el, curTime, typeOfClockhand){
    var gradForOneUnit;
    var gradRoll;
    var rotationArray;

    if(typeOfClockhand == "secondClockhand" || typeOfClockhand == "minuteClockhand"){
      gradForOneUnit=360/60;
    }else if(typeOfClockhand == "hourClockhand"){
      gradForOneUnit=360/12;
    }

    gardRoll=curTime*gradForOneUnit;

    //alert(gardRoll); //number: 354!!!!!!!!!!!!!!!!!!!! why??????
    //alert(typeof(gradRoll)); //undefined!!!!!!!!!!!!!  why??????

    rotationArray=[curTime*gradForOneUnit, 0, 0];

    //alert(typeof(rotationArray));//object
    //alert(typeof(el.getAttribute("rotation"))); //object

    //alert(rotationArray); //number: 162 , 0, 0

    el.setAttribute("rotation", rotationArray); //dosn't work.
  }

Body:
Use:

el.setAttribute("transform", "rotate3d,x,y,z,angle)");

or combine rotateX, rotateY, rotateZ.


问:
enable_shared_from_this - empty internal weak pointer?
I'm using enable_shared_from_this<Base> and then inherit from Base. When trying to use shared_from_this() in Derived's constructor (not initializer list), I get an exception. Turns out that the internal weak pointer is null and doesn't point to this at all. How can this happen? My other use case of exactly this works perfectly fine. I don't even know where to start. I looked down at the source code of enable_shared_from_this, and it looks to me like that pointer would always be nullptr.

答:
James McNellis's answer is right.

As for the explanation of the enable_shared_from_this template itself, which as you observe appears to do nothing, note 7 at the bottom of this page explains:

...the template
  enable_shared_from_this holds a
  weak_ptr object that points to the
  derived object. There's a
  chicken-and-egg problem, though, about
  how to initialize that weak_ptr object
  when there is no corresponding
  shared_ptr object. The implementation
  trick is that the constructors for
  shared_ptr know about
  enable_shared_from_this, and set the
  weak_ptr object during construction of
  a shared_ptr object that owns a
  resource that has
  enable_shared_from_this as a public
  base class.


问:
textbox with numbers only but also pasting, copying, and selecting
I'm quite new in VB and got stuck on (i think) easy problem. I have a text box thats allows only numbers:

```<code>    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 49 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If

End Sub
</code>```

from 1 to 9. But this box doesnt allows me to paste, copy, and select text...how can i change it? I know that KeyCode for Control is 17, and for 'V' is 86, but have no idea how to use it...
thanks for any help

答:
The issue with KeyPress is that it calls only one KeyPress at a time. Hence multiple selections such as Ctrl+V, Ctrl+C would not work. Instead of flagging it under KeyPress, call the TextChanged. Add the below mentioned and the issue should be resolved. Copy, Paste and Selecting would now work as normal.</p>

```<code>Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    TextBox2.Text = System.Text.RegularExpressions.Regex.Replace(TextBox2.Text, "[^\d]", "")    'Removes all character except numbers
    TextBox2.Select(TextBox2.Text.Length + 1, 1)    'To bring the textbox focus to the right
End Sub
</code>```

Body:
I'm quite new in VB and got stuck on (i think) easy problem. I have a text box thats allows only numbers:

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 49 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If

End Sub

from 1 to 9. But this box doesnt allows me to paste, copy, and select text...how can i change it? I know that KeyCode for Control is 17, and for 'V' is 86, but have no idea how to use it...
thanks for any help

Body:
The issue with KeyPress is that it calls only one KeyPress at a time. Hence multiple selections such as Ctrl+V, Ctrl+C would not work. Instead of flagging it under KeyPress, call the TextChanged. Add the below mentioned and the issue should be resolved. Copy, Paste and Selecting would now work as normal.

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    TextBox2.Text = System.Text.RegularExpressions.Regex.Replace(TextBox2.Text, "[^\d]", "")    'Removes all character except numbers
    TextBox2.Select(TextBox2.Text.Length + 1, 1)    'To bring the textbox focus to the right
End Sub