问:
What's the best strategy to provide different comparison operators for the same class?
Consider this simple class storing a value and a time.

```<code>class A
{
public:
    boost::posix_time::ptime when;
    double value;
};
</code>```

Depending on the context, I need to compare two instances of A by value or by time (and/or store them in set/map, sometimes sorted by value, sometimes by time).

Providing operator<  will be confusing, because you can't tell if it will compare by value or by time.

Now, what's the best strategy?

Is it possible to provide an operator< taking a parameter? (would be used as a <(ByTime) b)?

Should I have a lowerThan (comparing values) method and a earlierThan (comparing time) method taking the right operand as parameter? But then, what would be the best practice to handle <, <=, >, >=, ==, !=, should I have one method for each comparator? Or may they take parameters (like bool isLower(bool strict, const A& right) const, bool isGreater(bool strict, const A& right) const, bool isEarlier(bool strict, const A& right) const, bool isLater(bool strict, const A& right) const...

What would be the best practice?

答:
IMHO the most versatile way is a 2-step process:

make ADL getters.

write comparison concepts in terms of those getters.

example:

```<code>#include <boost/date_time.hpp>
#include <set>
#include <vector>
#include <algorithm>

class A
{
public:
    boost::posix_time::ptime when;
    double value;
};

// get the 'when' from an A
auto get_when(A const& a) -> boost::posix_time::ptime
{
    return a.when;
}

// get the 'when' from a ptime (you could put this in the boost::posix_time namespace for easy ADL
auto get_when(boost::posix_time::ptime t) -> boost::posix_time::ptime
{
    return t;
}

// same for the concept of a 'value'
auto get_value(A const& a) -> double
{
    return a.value;
}

auto get_value(double t) -> double
{
    return t;
}

// compare any two objects by calling get_when() on them
struct increasing_when
{
    template<class L, class R>
    bool operator()(L&& l, R&& r) const
    {
        return get_when(l) < get_when(r);
    }
};

// compare any two objects by calling get_value() on them
struct increasing_value
{
    template<class L, class R>
    bool operator()(L&& l, R&& r) const
    {
        return get_value(l) < get_value(r);
    }
};

void example1(std::vector<A>& as)
{
    // sort by increasing when
    std::sort(begin(as), end(as), increasing_when());

    // sort by increasing value
    std::sort(begin(as), end(as), increasing_value());
}

int main()
{
    // same for associative collections
    std::set<A, increasing_when> a1;
    std::set<A, increasing_value> a2;
}
</code>```

update:

If you want, you can templatise the comparison:

```<code>template<class Comp>
struct compare_when
{
    template<class L, class R>
    bool operator()(L&& l, R&& r) const
    {

        return comp(get_when(l), get_when(r));
    }

    Comp comp;
};

using increasing_when = compare_when<std::less<>>;
using decreasing_when = compare_when<std::greater<>>;
</code>```

to use the comparison directly in code:

```<code>auto comp = compare_when<std::greater<>>();
if (comp(x,y)) { ... }
</code>```

Body:
Consider this simple class storing a value and a time.

class A
{
public:
    boost::posix_time::ptime when;
    double value;
};

Depending on the context, I need to compare two instances of A by value or by time (and/or store them in set/map, sometimes sorted by value, sometimes by time).

Providing operator<  will be confusing, because you can't tell if it will compare by value or by time.

Now, what's the best strategy?

Is it possible to provide an operator< taking a parameter? (would be used as a <(ByTime) b)?

Should I have a lowerThan (comparing values) method and a earlierThan (comparing time) method taking the right operand as parameter? But then, what would be the best practice to handle <, <=, >, >=, ==, !=, should I have one method for each comparator? Or may they take parameters (like bool isLower(bool strict, const A& right) const, bool isGreater(bool strict, const A& right) const, bool isEarlier(bool strict, const A& right) const, bool isLater(bool strict, const A& right) const...

What would be the best practice?

Body:
IMHO the most versatile way is a 2-step process:

make ADL getters.

write comparison concepts in terms of those getters.

example:

#include <boost/date_time.hpp>
#include <set>
#include <vector>
#include <algorithm>

class A
{
public:
    boost::posix_time::ptime when;
    double value;
};

// get the 'when' from an A
auto get_when(A const& a) -> boost::posix_time::ptime
{
    return a.when;
}

// get the 'when' from a ptime (you could put this in the boost::posix_time namespace for easy ADL
auto get_when(boost::posix_time::ptime t) -> boost::posix_time::ptime
{
    return t;
}

// same for the concept of a 'value'
auto get_value(A const& a) -> double
{
    return a.value;
}

auto get_value(double t) -> double
{
    return t;
}

// compare any two objects by calling get_when() on them
struct increasing_when
{
    template<class L, class R>
    bool operator()(L&& l, R&& r) const
    {
        return get_when(l) < get_when(r);
    }
};

// compare any two objects by calling get_value() on them
struct increasing_value
{
    template<class L, class R>
    bool operator()(L&& l, R&& r) const
    {
        return get_value(l) < get_value(r);
    }
};

void example1(std::vector<A>& as)
{
    // sort by increasing when
    std::sort(begin(as), end(as), increasing_when());

    // sort by increasing value
    std::sort(begin(as), end(as), increasing_value());
}

int main()
{
    // same for associative collections
    std::set<A, increasing_when> a1;
    std::set<A, increasing_value> a2;
}

update:

If you want, you can templatise the comparison:

template<class Comp>
struct compare_when
{
    template<class L, class R>
    bool operator()(L&& l, R&& r) const
    {

        return comp(get_when(l), get_when(r));
    }

    Comp comp;
};

using increasing_when = compare_when<std::less<>>;
using decreasing_when = compare_when<std::greater<>>;

to use the comparison directly in code:

auto comp = compare_when<std::greater<>>();
if (comp(x,y)) { ... }


来源: stackexchange

问:
Haskell: accessing lists from back
Today I started learning Haskell. I'm kind of new with functional languages, and I'm enjoying Haskell a lot.

However I've got a question about its design which is bugging me: from what I understood so far it looks like accessing an element to the back of a list is a lot more complicated that accessing the element to the front (something like xs:x where xs::[a] and x::a doesn't seem to be possible).

(From what I understood) it's possible to append a list to another one (xs++[a]), but it'll cost more at run time (it requires to traverse the whole list) and it cannot be used for pattern matching.

Why is Haskell missing such operation?

答:
These aren't issues with the language, just the List data type, which has some special syntax but is otherwise not exactly an "integral part of Haskell".  You have the same issue in C with singly linked lists but that's obviously not an issue of the C programming language.

If you want a doubly linked list with tail pointer then make such a data type and use that!  You might want to learn more data types (see the containers package, vector, and the dlist package for examples).

ContentLicense: CC BY-SA 2.5

Title: Haskell: accessing lists from back


问:
SparkR vs sparklyr
Does someone have an overview with respect to advantages/disadvantages of SparkR vs sparklyr? Google does not yield any satisfactory results and both seem fairly similar. Trying both out, SparkR appears a lot more cumbersome, whereas sparklyr is pretty straight forward (both to install but also to use, especially with the dplyr inputs). Can sparklyr only be used to run dplyr functions in parallel or also "normal" R-Code?

Best

答:
I recently wrote an overview of the advantages/disadvantages of SparkR vs sparklyr, which may be of interest: https://eddjberry.netlify.com/post/2017-12-05-sparkr-vs-sparklyr/.

There's a table at the top of the post that gives a rough overview of the differences for a range of criteria.

I conclude that sparklyr is preferable to SparkR. The most notable advantages are:

Better data manipulation through compatibility with dpylr

Better function naming conventions

Better tools for quickly evaluating ML models

Easier to run arbitrary code on a Spark DataFrame

ContentLicense: CC BY-SA 3.0

Title: SparkR vs sparklyr


问:
Using OpenStack Nova Exceptions
When I'm using nova.keypairs.create() and I pass it an invalid public key, I get the following:

```<code>BadRequest: Keypair data is invalid: failed to generate fingerprint (HTTP 400) (Request-ID: req-12bc6440-f042-4687-9ee9-d89e7edc260d)
</code>```

I tried doing the following and for obvious reasons (it's a unique exception to OpenStack) it didn't work:

```<code>try:
    nova.keypairs.create(name=keyname, public_key=key)
except BadRequest:
    raise cherrypy.HTTPError(400, "Invalid public key")
</code>```

How can I use OpenStack specific exceptions such as BadRequest within my own try and except statements?

答:
You will need to import the exceptions for nova package. Going through github for the package, it looks like you will need to do:

```<code>from nova.exception import *
</code>```

Note that the exception you are seeing is actually InvalidKeypair exception, which itself subclasses from exception class Invalid, the BadRequest message is just the template text for it.

So, your complete code would look something like:

```<code>from nova.exception import *
# You can import specific ones if you are confident about them
try:
    nova.keypairs.create(name=keyname, public_key=key)
except InvalidKeypair:
    raise cherrypy.HTTPError(400, "Invalid public key")
</code>```

Title: Using OpenStack Nova Exceptions

Body:
When I'm using nova.keypairs.create() and I pass it an invalid public key, I get the following:

BadRequest: Keypair data is invalid: failed to generate fingerprint (HTTP 400) (Request-ID: req-12bc6440-f042-4687-9ee9-d89e7edc260d)

I tried doing the following and for obvious reasons (it's a unique exception to OpenStack) it didn't work:

try:
    nova.keypairs.create(name=keyname, public_key=key)
except BadRequest:
    raise cherrypy.HTTPError(400, "Invalid public key")

How can I use OpenStack specific exceptions such as BadRequest within my own try and except statements?

Body:
You will need to import the exceptions for nova package. Going through github for the package, it looks like you will need to do:

from nova.exception import *

Note that the exception you are seeing is actually InvalidKeypair exception, which itself subclasses from exception class Invalid, the BadRequest message is just the template text for it.

So, your complete code would look something like:

from nova.exception import *
# You can import specific ones if you are confident about them
try:
    nova.keypairs.create(name=keyname, public_key=key)
except InvalidKeypair:
    raise cherrypy.HTTPError(400, "Invalid public key")


问:
JSselect keys with variable of array
Lets say I have an array:

```<code>var array = [
  {
   key1: {
     underkey1: {
       "somekey":"someValue"
     }
   },
  }
];
</code>```

I know I can reach for key1 like this:

```<code>var theVar = "key1";
array[theVar];
</code>```

But I want to reach underkey1 with one variable, like:

```<code>var theVar = "key1.underkey1";
</code>```

From what I have tried I get undefined.

How can it be done?

答:
try following:</p>

```<code>var array = [
    {
        key1: {
            underkey1: "somevalue"
        },
    }
];

var theVar = "key1";
theVar2 = "underkey1"
array[0][theVar][theVar2];
</code>```

Title: JSselect keys with variable of array

Body:
Lets say I have an array:

var array = [
  {
   key1: {
     underkey1: {
       "somekey":"someValue"
     }
   },
  }
];

I know I can reach for key1 like this:

var theVar = "key1";
array[theVar];

But I want to reach underkey1 with one variable, like:

var theVar = "key1.underkey1";

From what I have tried I get undefined.

How can it be done?

Body:
try following:

var array = [
    {
        key1: {
            underkey1: "somevalue"
        },
    }
];

var theVar = "key1";
theVar2 = "underkey1"
array[0][theVar][theVar2];


问:
Problem creating foreign keys in mySql
I created a foreign key in my sql by the following statemnt..

```<code>ALTER TABLE `users` ADD FOREIGN KEY ( `id`)
REFERENCES `user_login` (`user_id`)
ON DELETE CASCADE ;
</code>```

The creation appears to succeed then after that I execute a delete statement

```<code>DELETE From user_login WHERE user_id = 1576;
</code>```

yet in users the row still exists that is referencing that. I open up the mysql workbench and it doesn't show any signs that the foreign key was created. Does anyone know why this would be? Or what I am doing wrong? It is a one-to-one relationship in the two tables.

答: You have to also make sure that both users.id and user_login.user_id have an index each.

Title: Problem creating foreign keys in mySql

Body:
I created a foreign key in my sql by the following statemnt..

ALTER TABLE `users` ADD FOREIGN KEY ( `id`)
REFERENCES `user_login` (`user_id`)
ON DELETE CASCADE ;

The creation appears to succeed then after that I execute a delete statement

DELETE From user_login WHERE user_id = 1576;

yet in users the row still exists that is referencing that. I open up the mysql workbench and it doesn't show any signs that the foreign key was created. Does anyone know why this would be? Or what I am doing wrong? It is a one-to-one relationship in the two tables.


问:
Protobuf-net file or assembly not found when referencing assembly over COM interop
I am trying to write a wrapper in C# for the protobuf-net package to enable me to access protocol buffer files directly from VBA in excel.
I have written my code with references to protobuf-net added through the nuget package manager.  I have made my assembly COM visible and from VBA I am able to access my classes.

However when I try to load a protobuffer file, I get the following message:

"Could not load file or assembly 'protobuf-net, Version=2.0.0.668,
  Culture=neutral, PublicKeyToken=257b51d87d2e4d67' or one of its
  dependencies. The system cannot find the file specified.
  (ProtoBufInterface.OutputData)"

I have checked that the protobuf-net.dll file is being copied to the assembly directory.  Any ideas what is causing this or what I can do to fix it?

Many thanks!

答:
protobuf-net.dll also depends on other DLLs which you should add into your references.

If they are not explicitly specified, you should use a utility like "depends.net". More info can be found in this link:

Modern Equivalent of Visual Studio 6 "Depends" utility


问:
ASP.NET Filter IQueryable with Custom Expression
I'm currently working on an ASP.NET application in .NET 4.5. Currently I'm retrieving 2 View results from my database using an IQueryable:

MainProject

SubProject

MainProjects and SubProjects have different properties, but do have 1 property in common, an ObjectNumber, which I defined in an interface ISearchResult.

I would like to write an Expression to filter both View results with only 1 method, instead of writing the same coding twice.

My View result classes and the interface look like this:

```<code>public interface ISarchResult
{
    int ID { get; set; }
    string ObjectNr { get; set; }
}

public class MainProject : ISearchResult
{
    public int ID { get; set; }
    public DateTime? CreationDate { get; set; }
    public string Title { get; set; }
    public string ObjectNr { get; set; }
}

public class SubProject : ISuchResultat
{
    public int ID { get; set; }
    public string ObjectNr { get; set; }
    public short State { get; set; }
    public int? Anything { get; set; }
    public int? Something { get; set; }
}
</code>```

In my Code Behind class I have my filter method, which looks like this:

```<code>private IQueryable<MainProject> FilterObjectNumbers(IQueryable<MainProject > result)
{
    var objectNumbers = this.objectNrField.Text.Split(',').Select(objNr => objNr.Trim()).Where(t => !string.IsNullOrEmpty(t)).ToList();

    if (objectNumbers.Count > 0)
    {
        var projectIDs = objectNumbers.Select(objNr => Util.StringToInt(objNr)).Where(objNr => objNr > 0).ToList();
        result = result.Where(i => objectNumbers.Contains(i.ObjectNr) || projectIDs.Contains(i.PK_ID));
    }

    return result;
}
</code>```

Do you know how to transform this Method into a query Expression, to filter my IQueryable for type MainProject as well as type SubProject?

Is it possible to put this Expression Filter method into an extension method?

答:
Create a generic extension method with a ISarchResult constraint

```<code>public static IQueryable<T> FilterObjectNumbers<T>(this IQueryable<T> result, string objectNrFieldText)
    where T : ISarchResult {
    var objectNumbers = objectNrFieldText.Split(',').Select(objNr => objNr.Trim()).Where(t => !string.IsNullOrEmpty(t)).ToList();

    if (objectNumbers.Count > 0) {
        var projectIDs = objectNumbers.Select(objNr => Util.StringToInt(objNr)).Where(objNr => objNr > 0).ToList();
        result = result.Where(i => objectNumbers.Contains(i.ObjectNr) || projectIDs.Contains(i.ID));
    }

    return result;
}
</code>```

It can then be used

```<code>//assuming IQueriable<MainProject> mainProjectResult
var filteredResult = mainProjectResult.FilterObjectNumbers(this.objectNrField.Text);
</code>```

Body:
I'm currently working on an ASP.NET application in .NET 4.5. Currently I'm retrieving 2 View results from my database using an IQueryable:

MainProject

SubProject

MainProjects and SubProjects have different properties, but do have 1 property in common, an ObjectNumber, which I defined in an interface ISearchResult.

I would like to write an Expression to filter both View results with only 1 method, instead of writing the same coding twice.

My View result classes and the interface look like this:

public interface ISarchResult
{
    int ID { get; set; }
    string ObjectNr { get; set; }
}

public class MainProject : ISearchResult
{
    public int ID { get; set; }
    public DateTime? CreationDate { get; set; }
    public string Title { get; set; }
    public string ObjectNr { get; set; }
}

public class SubProject : ISuchResultat
{
    public int ID { get; set; }
    public string ObjectNr { get; set; }
    public short State { get; set; }
    public int? Anything { get; set; }
    public int? Something { get; set; }
}

In my Code Behind class I have my filter method, which looks like this:

private IQueryable<MainProject> FilterObjectNumbers(IQueryable<MainProject > result)
{
    var objectNumbers = this.objectNrField.Text.Split(',').Select(objNr => objNr.Trim()).Where(t => !string.IsNullOrEmpty(t)).ToList();

    if (objectNumbers.Count > 0)
    {
        var projectIDs = objectNumbers.Select(objNr => Util.StringToInt(objNr)).Where(objNr => objNr > 0).ToList();
        result = result.Where(i => objectNumbers.Contains(i.ObjectNr) || projectIDs.Contains(i.PK_ID));
    }

    return result;
}

Do you know how to transform this Method into a query Expression, to filter my IQueryable for type MainProject as well as type SubProject?

Is it possible to put this Expression Filter method into an extension method?

Body:
Create a generic extension method with a ISarchResult constraint

public static IQueryable<T> FilterObjectNumbers<T>(this IQueryable<T> result, string objectNrFieldText)
    where T : ISarchResult {
    var objectNumbers = objectNrFieldText.Split(',').Select(objNr => objNr.Trim()).Where(t => !string.IsNullOrEmpty(t)).ToList();

    if (objectNumbers.Count > 0) {
        var projectIDs = objectNumbers.Select(objNr => Util.StringToInt(objNr)).Where(objNr => objNr > 0).ToList();
        result = result.Where(i => objectNumbers.Contains(i.ObjectNr) || projectIDs.Contains(i.ID));
    }

    return result;
}

It can then be used

//assuming IQueriable<MainProject> mainProjectResult
var filteredResult = mainProjectResult.FilterObjectNumbers(this.objectNrField.Text);


问:
Convert JS object to JS array
I have a javascript object like {"1":true,"2":false,"3":true}

I want to create a javascript array like [1,3] by taking the keys whose value is true.

How can I do that?

答:
Use Object#keys with array#filter to return those key whose value is true.

var obj = {"1":true,"2":false,"3":true};
var result = Object.keys(obj).filter(k => obj[k]).map(Number);
console.log(result);```

Title: Convert JS object to JS array


问:
Clicking the back button twice to exit an activity
I've noticed this pattern in a lot of Android apps and games recently: when clicking the back button to "exit" the application, a Toast comes up with a message similar to "Please click BACK again to exit".

I was wondering, as I'm seeing it more and more often, is that a built-in feature that you can somehow access in an activity? I've looked at the source code of many classes but I can't seem to find anything about that.

Of course, I can think about a few ways to achieve the same functionality quite easily (the easiest is probably to keep a boolean in the activity that indicates whether the user already clicked once...) but I was wondering if there's something already here.

EDIT: As @LAS_VEGAS mentioned, I didn't really mean "exit" in the traditional meaning. (i.e. terminated) I meant "going back to whatever was open before the application start activity was launched", if that makes sense :)

答:
In  java

```<code>private Boolean exit = false;

if (exit) {
onBackPressed();
}
</code>```

```<code> @Override
public void onBackPressed() {
    if (exit) {
        finish(); // finish activity
    } else {
        Toast.makeText(this, "Press Back again to Exit.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);

    }
}
</code>```

In kotlin

```<code> private var exit = false

 if (exit) {
        onBackPressed()
         }
</code>```

```<code> override fun onBackPressed(){
           if (exit){
               finish() // finish activity
           }else{
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show()
            exit = true
            Handler().postDelayed({ exit = false }, 3 * 1000)

        }
    }
</code>```

Body:
In  java

private Boolean exit = false;

if (exit) {
onBackPressed();
}

 @Override
public void onBackPressed() {
    if (exit) {
        finish(); // finish activity
    } else {
        Toast.makeText(this, "Press Back again to Exit.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);

    }
}

In kotlin

 private var exit = false

 if (exit) {
        onBackPressed()
         }

 override fun onBackPressed(){
           if (exit){
               finish() // finish activity
           }else{
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show()
            exit = true
            Handler().postDelayed({ exit = false }, 3 * 1000)

        }
    }

ContentLicense: CC BY-SA 4.0


问:
Issue in making Https request from Mule with TLS v1.2 and without SSL certificate verification
I want to make a https request with a TLS v1.2.
I found a property as follows:

```<code><tls:context name="trustallcertificate" enabledProtocols="TLSv1.2">
    <tls:trust-store insecure="true" />
</tls:context>
</code>```

But it is for <http:listener-config name="globalConfig" protocol="HTTPS" host="localhost" port="8443">

Is there a similar configuration for a outbound request.
I tried with '<spring:property name="sslType" value="TLSv1.2"/>'
But following error came:

org.mule.api.config.ConfigurationException: Line 127 in XML document
  from ConnectToIssuer.xml is invalid; nested exception is
  org.xml.sax.SAXParseException; lineNumber: 127; columnNumber: 54;
  cvc-complex-type.2.4.a: Invalid content was found starting with
  element 'spring:property'. One of
  '{"http://www.mulesoft.org/schema/mule/https":tls-protocol-handler}'
  is expected. (org.mule.api.lifecycle.InitialisationException)

答:
Yes, you'll have to configure a global request-config instead of a listener-config such as:

```<code><http:request-config name="HTTP_Request_Configuration" ... >
    <tls:context name="trustallcertificate" enabledProtocols="TLSv1.2">
        <tls:trust-store insecure="true" />
    </tls:context>
</http:request-config>
</code>```

And make a request in your flow:

```<code><flow name="someflow">
    ...
    <http:request config-ref="HTTP_Request_Configuration" .../>
    ...
</flow>
</code>```

Body:
I want to make a https request with a TLS v1.2.
I found a property as follows:

<tls:context name="trustallcertificate" enabledProtocols="TLSv1.2">
    <tls:trust-store insecure="true" />
</tls:context>

But it is for <http:listener-config name="globalConfig" protocol="HTTPS" host="localhost" port="8443">

Is there a similar configuration for a outbound request.
I tried with '<spring:property name="sslType" value="TLSv1.2"/>'
But following error came:

org.mule.api.config.ConfigurationException: Line 127 in XML document
  from ConnectToIssuer.xml is invalid; nested exception is
  org.xml.sax.SAXParseException; lineNumber: 127; columnNumber: 54;
  cvc-complex-type.2.4.a: Invalid content was found starting with
  element 'spring:property'. One of
  '{"http://www.mulesoft.org/schema/mule/https":tls-protocol-handler}'
  is expected. (org.mule.api.lifecycle.InitialisationException)

Body:
Yes, you'll have to configure a global request-config instead of a listener-config such as:

<http:request-config name="HTTP_Request_Configuration" ... >
    <tls:context name="trustallcertificate" enabledProtocols="TLSv1.2">
        <tls:trust-store insecure="true" />
    </tls:context>
</http:request-config>

And make a request in your flow:

<flow name="someflow">
    ...
    <http:request config-ref="HTTP_Request_Configuration" .../>
    ...
</flow>


问:
How to link a button to another component in an array
strong text
Hello, I am new to Angular2 and I require some help. I am doing a catalogue app. I have created an array( I think it is one), however I need each item in the array to be linked to another component. I intend to have a link in the Typescript file for each item, then the button in the HTML file will call it. However, I am not sure as to how to do it.

Typescript File:

export class NikeComponent implements OnInit {
 title = 'Nike Catalgoue';

  nikeShirts =  [ {
   "id": 1,
   "name": "Nike SB x Medicom Dry",
   "description": "Men's T-Shirt",
   "inStock": "$49",
      "image": "../assets/nike_shirt_1.jpg",

  },
{
   "id": 2,
   "name": "NikeLab ACG",
   "description": "Men's T-Shirt",
   "inStock": "$109",
     "image": "../assets/nike_shirt_2.jpg"
 },
{
   "id": 3,
   "name": "Nike Futura Icon",
   "description": "Men's T-Shirt",
   "inStock": "$42",
     "image": "../assets/adidas_shirt_3.jpg"
},
{
    "id": 4,
   "name": "Nike SB x Medicom Dry",
   "description": "Men's T-Shirt",
   "inStock": "$49",
      "image": "../assets/nike_shirt_1.jpg",

  },
{
   "id": 5 ,
   "name": "NikeLab ACG",
   "description": "Men's T-Shirt",
   "inStock": "$109",
     "image": "../assets/nike_shirt_2.jpg"
 },
{
   "id": 6,
   "name": "Nike Futura Icon",
   "description": "Men's T-Shirt",
   "inStock": "$42",
     "image": "../assets/nike_shirt_3.jpg"
}];```
</div>
</div>
</p>

<p>HTML file: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><li *ngFor = "let nikeShirt of nikeShirts">
  <img src ={{nikeShirt.image}} height="200" width="250" />
  <h2> {{nikeShirt.name}} </h2>
 <p> <i>{{nikeShirt.description}}</i> </p>
 <p> {{nikeShirt.inStock}} </p>
   <button href="/home" class="btn">Review</button>
</li>
</ul></code>```

答:
If you’re intention is to actually navigate to a different place you can simply have a property on each element of the array called url or source or something similar

```<code>{
  "id": 1,
  "name": "Nike SB x Medicom Dry",
  "description": "Men's T-Shirt",
  "inStock": "$49",
  "image": "../assets/nike_shirt_1.jpg",
  “url”: “<your url here>”
</code>```

}

Then on the html you can have something like

```<code><li *ngFor = "let nikeShirt of nikeShirts">
  <img src ={{nikeShirt.image}} height="200" width="250" />
  <h2> {{nikeShirt.name}} </h2>
<p> <i>{{nikeShirt.description}}</i> </p>
<p> {{nikeShirt.inStock}} </p>
  <a href=“{{nikeShirt.url}}” </a>
   <button href="/home" class="btn">Review</button>
</li>
</code>```

By the way your button Review won’t work because buttons don’t have href. They’re not meant not navigate usually. They’re meant for triggering actions.

You can achieve the desired result by converting it to Review and style with with some css

Body:
strong text
Hello, I am new to Angular2 and I require some help. I am doing a catalogue app. I have created an array( I think it is one), however I need each item in the array to be linked to another component. I intend to have a link in the Typescript file for each item, then the button in the HTML file will call it. However, I am not sure as to how to do it.

Typescript File:

export class NikeComponent implements OnInit {
 title = 'Nike Catalgoue';

  nikeShirts =  [ {
   "id": 1,
   "name": "Nike SB x Medicom Dry",
   "description": "Men's T-Shirt",
   "inStock": "$49",
      "image": "../assets/nike_shirt_1.jpg",

  },
{
   "id": 2,
   "name": "NikeLab ACG",
   "description": "Men's T-Shirt",
   "inStock": "$109",
     "image": "../assets/nike_shirt_2.jpg"
 },
{
   "id": 3,
   "name": "Nike Futura Icon",
   "description": "Men's T-Shirt",
   "inStock": "$42",
     "image": "../assets/adidas_shirt_3.jpg"
},
{
    "id": 4,
   "name": "Nike SB x Medicom Dry",
   "description": "Men's T-Shirt",
   "inStock": "$49",
      "image": "../assets/nike_shirt_1.jpg",

  },
{
   "id": 5 ,
   "name": "NikeLab ACG",
   "description": "Men's T-Shirt",
   "inStock": "$109",
     "image": "../assets/nike_shirt_2.jpg"
 },
{
   "id": 6,
   "name": "Nike Futura Icon",
   "description": "Men's T-Shirt",
   "inStock": "$42",
     "image": "../assets/nike_shirt_3.jpg"
}];

HTML file:

 {{nikeShirt.name}}

 {{nikeShirt.description}}

 {{nikeShirt.inStock}}

   <button href="/home" class="btn">Review</button>

Body:
If you’re intention is to actually navigate to a different place you can simply have a property on each element of the array called url or source or something similar

{
  "id": 1,
  "name": "Nike SB x Medicom Dry",
  "description": "Men's T-Shirt",
  "inStock": "$49",
  "image": "../assets/nike_shirt_1.jpg",
  “url”: “<your url here>”

}

Then on the html you can have something like

<li *ngFor = "let nikeShirt of nikeShirts">
  <img src ={{nikeShirt.image}} height="200" width="250" />
  <h2> {{nikeShirt.name}} </h2>
<p> <i>{{nikeShirt.description}}</i> </p>
<p> {{nikeShirt.inStock}} </p>
  <a href=“{{nikeShirt.url}}” </a>
   <button href="/home" class="btn">Review</button>
</li>

By the way your button Review won’t work because buttons don’t have href. They’re not meant not navigate usually. They’re meant for triggering actions.

You can achieve the desired result by converting it to <a href="/home" class="btn">Review</a> and style with with some css


问:
Laravel Eloquent groupBy() AND also return count of each group
I have a table that contains, amongst other columns, a column of browser versions. And I simply want to know from the record-set, how many of each type of browser there are. So, I need to end up with something like this: Total Records: 10; Internet Explorer 8: 2; Chrome 25: 4; Firefox 20: 4. (All adding up to 10)

Here's my two pence:

```<code>$user_info = Usermeta::groupBy('browser')->get();
</code>```

Of course that just contains the 3 browsers and not the number of each. How can I do this?

答:
Try with this

```<code>->groupBy('state_id','locality')
  ->havingRaw('count > 1 ')
  ->having('items.name','LIKE',"%$keyword%")
  ->orHavingRaw('brand LIKE ?',array("%$keyword%"))
</code>```

Body:
I have a table that contains, amongst other columns, a column of browser versions. And I simply want to know from the record-set, how many of each type of browser there are. So, I need to end up with something like this: Total Records: 10; Internet Explorer 8: 2; Chrome 25: 4; Firefox 20: 4. (All adding up to 10)

Here's my two pence:

$user_info = Usermeta::groupBy('browser')->get();

Of course that just contains the 3 browsers and not the number of each. How can I do this?

Body:
Try with this

->groupBy('state_id','locality')
  ->havingRaw('count > 1 ')
  ->having('items.name','LIKE',"%$keyword%")
  ->orHavingRaw('brand LIKE ?',array("%$keyword%"))


问:
Read latest character sent from Arduino in Python
I'm a beginner in both Arduino and Python, and I have an idea but I can't get it to work. Basically, when in Arduino a button is pressed, it sends "4" through the serial port. What I want in Python is as soon as it reads a 4, it should do something. This is what I got so far:

```<code>import serial
ser = serial.Serial('/dev/tty.usbserial-A900frF6', 9600)
var = 1
while var == 1:
    if ser.inWaiting() > 0:
    ser.readline(1)
    print "hello"
</code>```

But obviously this prints hello no matter what. What I would need is something like this:

```<code>import serial
ser = serial.Serial('/dev/tty.usbserial-A900frF6', 9600)
var = 1
while var == 1:
    if ser.inWaiting() > 0:
    ser.readline(1)
    if last.read == "4":
    print "hello"
</code>```

But how can I define last.read?

答:
I don't know a good way of synchronising the comms with readLine since it's not a blocking call. You can use ser.read(numBytes) which is a blocking call. You will need to know how many bytes Arduino is sending though to decode the byte stream correctly. Here is a simple example that reads 8 bytes and unpacks them into 2 unsigned shorts and a long (the <HHL part) in Python

```<code>try:
  data = [struct.unpack('<HHL', handle.read(8)) for i in range(PACKETS_PER_TRANSMIT)]
except OSError:
  self.emit(SIGNAL("connectionLost()"))
  self.connected = False
</code>```

Here's a reference to the struct.unpack()

The Arduino code that goes with that. It reads two analog sensor values and the micro timestamp and sends them over the serial.

```<code>unsigned int SensA, SensB;
byte out_buffer[64];
unsigned int buffer_head = 0;
unsigned int buffer_size = 64;

SensA = analogRead(SENSOR_A);
SensB = analogRead(SENSOR_B);
micr = micros();
out_buffer[buffer_head++] = (SensA & 0xFF);
out_buffer[buffer_head++] = (SensA >> 8) & 0xFF;

out_buffer[buffer_head++] = (SensB & 0xFF);
out_buffer[buffer_head++] = (SensB >> 8) & 0xFF;

out_buffer[buffer_head++] = (micr & 0xFF);
out_buffer[buffer_head++] = (micr >> 8) & 0xFF;
out_buffer[buffer_head++] = (micr >> 16) & 0xFF;
out_buffer[buffer_head++] = (micr >> 24) & 0xFF;

Serial.write(out_buffer, buffer_size);
</code>```

The Arduino playground and Processing Forums are good places to look around for this sort of code as well.

UPDATE
I think I might have misled you with readLine not blocking. Either way, the above code should work. I also found this other thread on SO regarding the same subject.

UPDATE You don't need to use the analog sensors, that's just what the project I did happened to be using, you are of course free to pass what ever values over the serial. So what the Arduino code is doing is it has a buffer of type byte where the output is being stored before being sent. The sensor values and micros are then written to the buffer and the buffer sent over the serial. The (SensA & 0xFF) is a bit mask operator that takes the bit pattern of the SensA value and masks it with the bit pattern of 0xFF or 255 in decimal. Essetianlly this takes the first 8 bits from the 16 bit value of SensA which is an Arduino short. the next line does the same thing but shifts the bits right by 8 positions, thus taking the last 8 bits.

You'll need to understand bit patterns, bit masking and bit shifting for this. Then the buffer is written to the serial.

The Python code in turn does reads the bits from the serial port 8 bits at a time. Have a look at the struct.unpack docs. The for comprehension is just there to allow sending more than one set of values. Because the Arduino board and the Python code are running out of sync I added that to be able to send more than one "lines" per transmit. You can just replace that with struct.unpack('<HHL',handle.read(8)). Remember that the ´handle.read()´ takes a number of bytes where as the Arduino send code is dealing with bits.

Body:
I'm a beginner in both Arduino and Python, and I have an idea but I can't get it to work. Basically, when in Arduino a button is pressed, it sends "4" through the serial port. What I want in Python is as soon as it reads a 4, it should do something. This is what I got so far:

import serial
ser = serial.Serial('/dev/tty.usbserial-A900frF6', 9600)
var = 1
while var == 1:
    if ser.inWaiting() > 0:
    ser.readline(1)
    print "hello"

But obviously this prints hello no matter what. What I would need is something like this:

import serial
ser = serial.Serial('/dev/tty.usbserial-A900frF6', 9600)
var = 1
while var == 1:
    if ser.inWaiting() > 0:
    ser.readline(1)
    if last.read == "4":
    print "hello"

But how can I define last.read?

Body:
I don't know a good way of synchronising the comms with readLine since it's not a blocking call. You can use ser.read(numBytes) which is a blocking call. You will need to know how many bytes Arduino is sending though to decode the byte stream correctly. Here is a simple example that reads 8 bytes and unpacks them into 2 unsigned shorts and a long (the <HHL part) in Python

try:
  data = [struct.unpack('<HHL', handle.read(8)) for i in range(PACKETS_PER_TRANSMIT)]
except OSError:
  self.emit(SIGNAL("connectionLost()"))
  self.connected = False

Here's a reference to the struct.unpack()

The Arduino code that goes with that. It reads two analog sensor values and the micro timestamp and sends them over the serial.

unsigned int SensA, SensB;
byte out_buffer[64];
unsigned int buffer_head = 0;
unsigned int buffer_size = 64;

SensA = analogRead(SENSOR_A);
SensB = analogRead(SENSOR_B);
micr = micros();
out_buffer[buffer_head++] = (SensA & 0xFF);
out_buffer[buffer_head++] = (SensA >> 8) & 0xFF;

out_buffer[buffer_head++] = (SensB & 0xFF);
out_buffer[buffer_head++] = (SensB >> 8) & 0xFF;

out_buffer[buffer_head++] = (micr & 0xFF);
out_buffer[buffer_head++] = (micr >> 8) & 0xFF;
out_buffer[buffer_head++] = (micr >> 16) & 0xFF;
out_buffer[buffer_head++] = (micr >> 24) & 0xFF;

Serial.write(out_buffer, buffer_size);

The Arduino playground and Processing Forums are good places to look around for this sort of code as well.

UPDATE
I think I might have misled you with readLine not blocking. Either way, the above code should work. I also found this other thread on SO regarding the same subject.

UPDATE You don't need to use the analog sensors, that's just what the project I did happened to be using, you are of course free to pass what ever values over the serial. So what the Arduino code is doing is it has a buffer of type byte where the output is being stored before being sent. The sensor values and micros are then written to the buffer and the buffer sent over the serial. The (SensA & 0xFF) is a bit mask operator that takes the bit pattern of the SensA value and masks it with the bit pattern of 0xFF or 255 in decimal. Essetianlly this takes the first 8 bits from the 16 bit value of SensA which is an Arduino short. the next line does the same thing but shifts the bits right by 8 positions, thus taking the last 8 bits.

You'll need to understand bit patterns, bit masking and bit shifting for this. Then the buffer is written to the serial.

The Python code in turn does reads the bits from the serial port 8 bits at a time. Have a look at the struct.unpack docs. The for comprehension is just there to allow sending more than one set of values. Because the Arduino board and the Python code are running out of sync I added that to be able to send more than one "lines" per transmit. You can just replace that with struct.unpack('<HHL',handle.read(8)). Remember that the ´handle.read()´ takes a number of bytes where as the Arduino send code is dealing with bits.


问:
c++ wait_until strange timeout behaviour
I'm trying to write a kind of thread pool in C++. The code works fine in OSX, but under Linux I'm experiencing a strange behavior.
After a bit of debugging, I found the problem is due to a call to std::condition_variable::wait_until that I must be doing in a wrong way.

With the code below I expect the loop to be looped once every three seconds:

```<code>#include <mutex>
#include <chrono>
#include <iostream>
#include <memory>
#include <condition_variable>
#include <thread>

using namespace std;

typedef std::chrono::steady_clock                           my_clock;
typedef std::chrono::duration<float, std::ratio<1> >        seconds_duration;
typedef std::chrono::time_point<my_clock, seconds_duration> timepoint;

timepoint my_begin = my_clock::now();

float timepointToFloat(timepoint time) {
  return time.time_since_epoch().count() - my_begin.time_since_epoch().count();
}

void printNow(std::string mess) {
  timepoint now = my_clock::now();
  cout << timepointToFloat(now) << " " << mess  << endl;;
};

void printNow(std::string mess, timepoint time ) {
  timepoint now = my_clock::now();
  cout << timepointToFloat(now) << " " << mess  << " " << timepointToFloat(time) << endl;;
};

int main() {
  mutex _global_mutex;
  condition_variable _awake_global_execution;
  auto check_predicate = [](){
    cout << "predicate called" << endl;
    return false;
  };

  while (true) {
    { // Expected to loop every three seconds
      unique_lock<mutex> lock(_global_mutex);
      timepoint planned_awake = my_clock::now() + seconds_duration(3);
      printNow("wait until", planned_awake);
      _awake_global_execution.wait_until(lock, planned_awake, check_predicate);
    }
    printNow("finish wait, looping");
  }

  return 0;
}
</code>```

However, sometimes I get as output:

```<code><X> wait until <X+3>
predicate called
(...hangs here for a long time)
</code>```

(where X is a number), so it seems the timeout is not scheduled after three seconds. Sometimes instead I get:

```<code><X> wait until <X+3>
predicate called
predicate called
<X> finish wait, looping
<X> wait until <X+3> (another loop)
predicate called
predicate called
<X> finish wait, looping
(...continue looping without waiting)
</code>```

so it seems the timeout is scheduled after a small fraction of seconds. I think I'm messing up something with the timeout timepoint, but I cannot figure out what I'm doing wrong.

If it may be relevant, this code works fine in OSX, while in Linux (Ubuntu 16.04, gcc 5.4, compiled with "g++ main.cc -std=c++11 -pthread") I'm experiencing the strange behavior.

How can I get it work?

答:
Try to cast your timeout to your clock's duration:</p>

```<code>auto planned_awake = my_clock::now() +
                     std::chrono::duration_cast<my_clock::duration>(seconds_duration(3));
</code>```

Body:
I'm trying to write a kind of thread pool in C++. The code works fine in OSX, but under Linux I'm experiencing a strange behavior.
After a bit of debugging, I found the problem is due to a call to std::condition_variable::wait_until that I must be doing in a wrong way.

With the code below I expect the loop to be looped once every three seconds:

#include <mutex>
#include <chrono>
#include <iostream>
#include <memory>
#include <condition_variable>
#include <thread>

using namespace std;

typedef std::chrono::steady_clock                           my_clock;
typedef std::chrono::duration<float, std::ratio<1> >        seconds_duration;
typedef std::chrono::time_point<my_clock, seconds_duration> timepoint;

timepoint my_begin = my_clock::now();

float timepointToFloat(timepoint time) {
  return time.time_since_epoch().count() - my_begin.time_since_epoch().count();
}

void printNow(std::string mess) {
  timepoint now = my_clock::now();
  cout << timepointToFloat(now) << " " << mess  << endl;;
};

void printNow(std::string mess, timepoint time ) {
  timepoint now = my_clock::now();
  cout << timepointToFloat(now) << " " << mess  << " " << timepointToFloat(time) << endl;;
};

int main() {
  mutex _global_mutex;
  condition_variable _awake_global_execution;
  auto check_predicate = [](){
    cout << "predicate called" << endl;
    return false;
  };

  while (true) {
    { // Expected to loop every three seconds
      unique_lock<mutex> lock(_global_mutex);
      timepoint planned_awake = my_clock::now() + seconds_duration(3);
      printNow("wait until", planned_awake);
      _awake_global_execution.wait_until(lock, planned_awake, check_predicate);
    }
    printNow("finish wait, looping");
  }

  return 0;
}

However, sometimes I get as output:

<X> wait until <X+3>
predicate called
(...hangs here for a long time)

(where X is a number), so it seems the timeout is not scheduled after three seconds. Sometimes instead I get:

<X> wait until <X+3>
predicate called
predicate called
<X> finish wait, looping
<X> wait until <X+3> (another loop)
predicate called
predicate called
<X> finish wait, looping
(...continue looping without waiting)

so it seems the timeout is scheduled after a small fraction of seconds. I think I'm messing up something with the timeout timepoint, but I cannot figure out what I'm doing wrong.

If it may be relevant, this code works fine in OSX, while in Linux (Ubuntu 16.04, gcc 5.4, compiled with "g++ main.cc -std=c++11 -pthread") I'm experiencing the strange behavior.

How can I get it work?

Body:
Try to cast your timeout to your clock's duration:

auto planned_awake = my_clock::now() +
                     std::chrono::duration_cast<my_clock::duration>(seconds_duration(3));


问:
Python 3.6 startup error
I am very new to python, I have installed Python 3.6 on my Windows 10 machine ( and I believe it has version 2.7 installed ). The installation was ok but when I try to start up it gives me error as shown below

```<code>Fatal Python error: Py_Initialize: unable to load the file system codec
  File "C:\csvn\Python25\\lib\encodings\__init__.py", line 123
    raise CodecRegistryError,\
                            ^
SyntaxError: invalid syntax

Current thread 0x00002c78 (most recent call first):
</code>```

Please someone would help me to identify this error and how to fix it.
Thank you so much in advance for any help.

答:
It may be because you have different versions of Python installed, so when you try to use the newest installed, it may be use the old interpreter instead, to solve the problem you absolutely need to change the PYTHONPATH.

Changing PYTHONPATH in shell [closed]

Title: Python 3.6 startup error

Body:
I am very new to python, I have installed Python 3.6 on my Windows 10 machine ( and I believe it has version 2.7 installed ). The installation was ok but when I try to start up it gives me error as shown below

Fatal Python error: Py_Initialize: unable to load the file system codec
  File "C:\csvn\Python25\\lib\encodings\__init__.py", line 123
    raise CodecRegistryError,\
                            ^
SyntaxError: invalid syntax

Current thread 0x00002c78 (most recent call first):

Please someone would help me to identify this error and how to fix it.
Thank you so much in advance for any help.


问:
Could not write JSON: Infinite recursion (StackOverflowError); nested exception spring boot
This is my District Controller, when I try to fetch data after saving I get the error, even when I try get object form getDistrict(Long id) the same strikes please suggest some way, am very new at spring environment:

```<code>    package com.gad.services;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.gad.repositories.DistrictMasterRepositories;
    import com.gad.rmodels.Districtmaster;
    import com.gad.rmodels.Statemaster;

    @Service
    public class DistricMasterServices {

        @Autowired
        DistrictMasterRepositories districtMasterRepositories;
        @Autowired
        StateMasterServices stateMasterServices;
        List<Districtmaster> districtmaster;

        public Iterable<Districtmaster> savenewdistrict(Long id,Districtmaster districtmaster_rec){
             System.out.println(id);
             Statemaster statemaster=null;
             statemaster = stateMasterServices.getStateById(id);
             System.out.println("savenewdistrict");

                districtmaster_rec.setStatemaster(statemaster);
                districtMasterRepositories.save(districtmaster_rec);
                    Iterable<Districtmaster>districtmaster2 = districtMasterRepositories.findAll();
                    return  districtmaster2;

        }

        public Districtmaster  getDistrict(Long id){
            Districtmaster districtmaster =  districtMasterRepositories.findOne(id);
            return districtmaster;

        }
    }
</code>```

The model class for state:

```<code> package com.gad.rmodels;
    import static javax.persistence.GenerationType.SEQUENCE;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;

    /**
     * Statemaster generated by hbm2java
     */
    @Entity
    @Table(name="statemaster"
        ,schema="aop_gad_v1"
    )
    public class Statemaster  implements java.io.Serializable {

         private long id;
         private String stateName;
         private Set<Districtmaster> districtmasters = new HashSet<Districtmaster>(0);

        public Statemaster() {
        }

        public Statemaster(long id) {
            this.id = id;
        }
        public Statemaster(long id, String stateName, Set<Districtmaster> districtmasters) {
           this.id = id;
           this.stateName = stateName;
           this.districtmasters = districtmasters;
        }

        @SequenceGenerator(name="generator_statemasterid", sequenceName="aop_gad_v1.gad_statemaster_seq")
        @Id
        @GeneratedValue(strategy=SEQUENCE, generator="generator_statemasterid")
        @Column(name="id", unique=true, nullable=false)
        public long getId() {
            return this.id;
        }

        public void setId(long id) {
            this.id = id;
        }

        @Column(name="state_name", length=20)
        public String getStateName() {
            return this.stateName;
        }

        public void setStateName(String stateName) {
            this.stateName = stateName;
        }

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
        public Set<Districtmaster> getDistrictmasters() {
            return this.districtmasters;
        }

        public void setDistrictmasters(Set<Districtmaster> districtmasters) {
            this.districtmasters = districtmasters;
        }

    }
</code>```

Distric model:

```<code>package com.gad.rmodels;

import static javax.persistence.GenerationType.SEQUENCE;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Districtmaster generated by hbm2java
 */
@SuppressWarnings("serial")
@Entity
@Table(name="districtmaster",schema="aop_gad_v1")
public class Districtmaster  implements java.io.Serializable {

     private long id;
     private Statemaster statemaster;
     private String districtName;
     private Set<GadGuestHouseMaster> gadGuestHouseMasters = new HashSet<GadGuestHouseMaster>(0);

    public Districtmaster() {
    }

    public Districtmaster(long id) {
        this.id = id;
    }
    public Districtmaster(long id, Statemaster statemaster, String districtName, Set<GadGuestHouseMaster> gadGuestHouseMasters) {
       this.id = id;
       this.statemaster = statemaster;
       this.districtName = districtName;
       this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

     @SequenceGenerator(name="generator_districtmasterid", sequenceName="aop_gad_v1.gad_districtmasterid_seq")
     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="generator_districtmasterid")
     @Column(name="id", unique=true, nullable=false)
    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }
@ManyToOne(fetch=FetchType.LAZY)

    @JoinColumn(name="district_of_state")
    public Statemaster getStatemaster() {
        return this.statemaster;
    }

    public void setStatemaster(Statemaster statemaster) {
        this.statemaster = statemaster;
    }

    @Column(name="district_name", length=20)
    public String getDistrictName() {
        return this.districtName;
    }

    public void setDistrictName(String districtName) {
        this.districtName = districtName;
    }
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="districtmaster")
    public Set<GadGuestHouseMaster> getGadGuestHouseMasters() {
        return this.gadGuestHouseMasters;
    }

    public void setGadGuestHouseMasters(Set<GadGuestHouseMaster> gadGuestHouseMasters) {
        this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

}
</code>```

The Error I get:

[{"timestamp":1512641978311,"status":200,"error":"OK","exception":"org.springframework.http.converter.HttpMessageNotWritableException","message":"Could
  not write JSON: Infinite recursion (StackOverflowError); nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  Infinite recursion (StackOverflowError) (through reference chain:
  com.gad.rmodels.Statemaster[\"districtmasters\"]->org.hibernate.collection.internal.PersistentSet[0]-

答:
That's because for Statemaster in json the set of Districtmaster's is put.
And each Districtmaster has the Statemaster in itself, so it's also put into the json. So that you get the infinite recursion

```<code>    @JsonIgnore
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY,
    mappedBy="statemaster")
    public Set<Districtmaster> getDistrictmasters() {
        return this.districtmasters;
    }
</code>```

Adding @JsonIgnore annotation on Set<Districtmaster> will prevent that recursion.
You can put the @JsonIgnore at public Statemaster getStatemaster() either.

Body:
This is my District Controller, when I try to fetch data after saving I get the error, even when I try get object form getDistrict(Long id) the same strikes please suggest some way, am very new at spring environment:

    package com.gad.services;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.gad.repositories.DistrictMasterRepositories;
    import com.gad.rmodels.Districtmaster;
    import com.gad.rmodels.Statemaster;

    @Service
    public class DistricMasterServices {

        @Autowired
        DistrictMasterRepositories districtMasterRepositories;
        @Autowired
        StateMasterServices stateMasterServices;
        List<Districtmaster> districtmaster;

        public Iterable<Districtmaster> savenewdistrict(Long id,Districtmaster districtmaster_rec){
             System.out.println(id);
             Statemaster statemaster=null;
             statemaster = stateMasterServices.getStateById(id);
             System.out.println("savenewdistrict");

                districtmaster_rec.setStatemaster(statemaster);
                districtMasterRepositories.save(districtmaster_rec);
                    Iterable<Districtmaster>districtmaster2 = districtMasterRepositories.findAll();
                    return  districtmaster2;

        }

        public Districtmaster  getDistrict(Long id){
            Districtmaster districtmaster =  districtMasterRepositories.findOne(id);
            return districtmaster;

        }
    }

The model class for state:

 package com.gad.rmodels;
    import static javax.persistence.GenerationType.SEQUENCE;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;

    /**
     * Statemaster generated by hbm2java
     */
    @Entity
    @Table(name="statemaster"
        ,schema="aop_gad_v1"
    )
    public class Statemaster  implements java.io.Serializable {

         private long id;
         private String stateName;
         private Set<Districtmaster> districtmasters = new HashSet<Districtmaster>(0);

        public Statemaster() {
        }

        public Statemaster(long id) {
            this.id = id;
        }
        public Statemaster(long id, String stateName, Set<Districtmaster> districtmasters) {
           this.id = id;
           this.stateName = stateName;
           this.districtmasters = districtmasters;
        }

        @SequenceGenerator(name="generator_statemasterid", sequenceName="aop_gad_v1.gad_statemaster_seq")
        @Id
        @GeneratedValue(strategy=SEQUENCE, generator="generator_statemasterid")
        @Column(name="id", unique=true, nullable=false)
        public long getId() {
            return this.id;
        }

        public void setId(long id) {
            this.id = id;
        }

        @Column(name="state_name", length=20)
        public String getStateName() {
            return this.stateName;
        }

        public void setStateName(String stateName) {
            this.stateName = stateName;
        }

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
        public Set<Districtmaster> getDistrictmasters() {
            return this.districtmasters;
        }

        public void setDistrictmasters(Set<Districtmaster> districtmasters) {
            this.districtmasters = districtmasters;
        }

    }

Distric model:

package com.gad.rmodels;

import static javax.persistence.GenerationType.SEQUENCE;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Districtmaster generated by hbm2java
 */
@SuppressWarnings("serial")
@Entity
@Table(name="districtmaster",schema="aop_gad_v1")
public class Districtmaster  implements java.io.Serializable {

     private long id;
     private Statemaster statemaster;
     private String districtName;
     private Set<GadGuestHouseMaster> gadGuestHouseMasters = new HashSet<GadGuestHouseMaster>(0);

    public Districtmaster() {
    }

    public Districtmaster(long id) {
        this.id = id;
    }
    public Districtmaster(long id, Statemaster statemaster, String districtName, Set<GadGuestHouseMaster> gadGuestHouseMasters) {
       this.id = id;
       this.statemaster = statemaster;
       this.districtName = districtName;
       this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

     @SequenceGenerator(name="generator_districtmasterid", sequenceName="aop_gad_v1.gad_districtmasterid_seq")
     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="generator_districtmasterid")
     @Column(name="id", unique=true, nullable=false)
    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }
@ManyToOne(fetch=FetchType.LAZY)

    @JoinColumn(name="district_of_state")
    public Statemaster getStatemaster() {
        return this.statemaster;
    }

    public void setStatemaster(Statemaster statemaster) {
        this.statemaster = statemaster;
    }

    @Column(name="district_name", length=20)
    public String getDistrictName() {
        return this.districtName;
    }

    public void setDistrictName(String districtName) {
        this.districtName = districtName;
    }
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="districtmaster")
    public Set<GadGuestHouseMaster> getGadGuestHouseMasters() {
        return this.gadGuestHouseMasters;
    }

    public void setGadGuestHouseMasters(Set<GadGuestHouseMaster> gadGuestHouseMasters) {
        this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

}

The Error I get:

[{"timestamp":1512641978311,"status":200,"error":"OK","exception":"org.springframework.http.converter.HttpMessageNotWritableException","message":"Could
  not write JSON: Infinite recursion (StackOverflowError); nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  Infinite recursion (StackOverflowError) (through reference chain:
  com.gad.rmodels.Statemaster[\"districtmasters\"]->org.hibernate.collection.internal.PersistentSet[0]-

Body:
That's because for Statemaster in json the set of Districtmaster's is put.
And each Districtmaster has the Statemaster in itself, so it's also put into the json. So that you get the infinite recursion

    @JsonIgnore
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY,
    mappedBy="statemaster")
    public Set<Districtmaster> getDistrictmasters() {
        return this.districtmasters;
    }

Adding @JsonIgnore annotation on Set<Districtmaster> will prevent that recursion.
You can put the @JsonIgnore at public Statemaster getStatemaster() either.


问:
Contract doesn't work
I am stuck on a problem with System.Diagnostics.Contracts.

If I use Contract.Requires(condition), then all works as expected.
But I need a custom Exception, so I tried Contract.Requires<ToShortException>(condition).

When condition was false, I expected a ToShortException but I got nothing. In the debugger I can see, that this line was ignored.

ToShortException is a public class which implements Exception and has 3 public constructors.

Has anyone an idea what I am doing wrong?

The Exception class:

```<code>public class ToShortException : Exception
{
    public ToShortException()
    {
    }

    public ToShortException(string message) : base(message)
    {
    }

    public ToShortException(string message, Exception inner) : base(message, inner)
    {

    }
}
</code>```

Method of a class:

```<code>    public IDictionary<string, string> getIncident(string name)
    {
        Contract.Requires(!string.IsNullOrWhiteSpace(name)); //works fine
        Contract.Requires<ToShortException>(name.Length == 7); //got not checked

        return _original.getIncident(name);
    }
</code>```

答:
I found the solution. "Project Settings -> Code Contracts -> Assembly Mode" has to be "Standard Contract Requires".

The default-value was "Custom Parameter Validation".

Title: Contract doesn't work

Body:
I am stuck on a problem with System.Diagnostics.Contracts.

If I use Contract.Requires(condition), then all works as expected.
But I need a custom Exception, so I tried Contract.Requires<ToShortException>(condition).

When condition was false, I expected a ToShortException but I got nothing. In the debugger I can see, that this line was ignored.

ToShortException is a public class which implements Exception and has 3 public constructors.

Has anyone an idea what I am doing wrong?

The Exception class:

public class ToShortException : Exception
{
    public ToShortException()
    {
    }

    public ToShortException(string message) : base(message)
    {
    }

    public ToShortException(string message, Exception inner) : base(message, inner)
    {

    }
}

Method of a class:

    public IDictionary<string, string> getIncident(string name)
    {
        Contract.Requires(!string.IsNullOrWhiteSpace(name)); //works fine
        Contract.Requires<ToShortException>(name.Length == 7); //got not checked

        return _original.getIncident(name);
    }


问:
Setup an SSL certificate on an EC2 instance
I'm having hard time trying to setup an SSL certificate (it's a Comodo PositiveSSL purshased from NameCheap) on my EC2 micro instance (I'm using Amazon Linux AMI 2012.3, which is based on CentOS if I'm not mistaken).

Here's what I did:

I installed mod_ssl & OpenSSL

I enabled port 443 on my EC2's instance security group

I CHMODed the *.key & *.crt files to 777 as Comodo suggested

I'm certain the IP address & files path are correct (put a bunch of
0s in the example but it is correct in my ssl.conf)

I added this VirtualHost entry to ssl.conf

```<code><VirtualHost 00.000.000.00:443>
   ############# I tried both with & without this section ##############
   ServerName www.mydomain.com:443

   ServerAlias www.mydomain.com
   DocumentRoot /var/www
   ServerAdmin webmaster@mydomain.com
   ######################################################################

   SSLEngine on
   SSLCertificateKeyFile /etc/ssl/mydomain_com.key
   SSLCertificateFile /etc/ssl/mydomain_com.crt
   SSLCertificateChainFile /etc/ssl/mydomain_com.ca-bundle
</VirtualHost>
</code>```

Then I restarted apache...but I stil cannot access https://www.mydomain.com/ !!!

I checked with ssltool.com, it says

```<code>The Common Name on the certificate is: ip-00-00-00-000

The certificate chain consists of:
SomeOrganization, ip-00-00-00-000. Expires on: Apr 10 13:39:41 2013 GMT - that's 363 days from today.
The site tested mydomain.com is NOT the same as the Subject CN ip-00-00-00-000!.
</code>```

I even went & copied the VistualHost to httpd.conf instead of ssl.conf & restarted apache, all in vain.

I've been banging my head against the wall for days now. I'm pretty sure I'm missing a tiny something to make this work, I just don't know what exactly.

I'd be infinitely grateful if someone can suggest something to make this work!

答:
Looking at your list, it happens that you forget to enable your configuration with your Virtual host.

```<code>sudo a2enmod ssl
sudo a2ensite default-ssl
sudo /etc/init.d/apache2 restart
</code>```

There is a complete guide on how to install an SSL certificate on your EC2 here https://medium.com/@adnanxteam/how-to-add-ssl-certificate-to-laravel-on-ec2-aws-18104cc036d1

Body:
I'm having hard time trying to setup an SSL certificate (it's a Comodo PositiveSSL purshased from NameCheap) on my EC2 micro instance (I'm using Amazon Linux AMI 2012.3, which is based on CentOS if I'm not mistaken).

Here's what I did:

I installed mod_ssl & OpenSSL

I enabled port 443 on my EC2's instance security group

I CHMODed the *.key & *.crt files to 777 as Comodo suggested

I'm certain the IP address & files path are correct (put a bunch of
0s in the example but it is correct in my ssl.conf)

I added this VirtualHost entry to ssl.conf

<VirtualHost 00.000.000.00:443>
   ############# I tried both with & without this section ##############
   ServerName www.mydomain.com:443

   ServerAlias www.mydomain.com
   DocumentRoot /var/www
   ServerAdmin webmaster@mydomain.com
   ######################################################################

   SSLEngine on
   SSLCertificateKeyFile /etc/ssl/mydomain_com.key
   SSLCertificateFile /etc/ssl/mydomain_com.crt
   SSLCertificateChainFile /etc/ssl/mydomain_com.ca-bundle
</VirtualHost>

Then I restarted apache...but I stil cannot access https://www.mydomain.com/ !!!

I checked with ssltool.com, it says

The Common Name on the certificate is: ip-00-00-00-000

The certificate chain consists of:
SomeOrganization, ip-00-00-00-000. Expires on: Apr 10 13:39:41 2013 GMT - that's 363 days from today.
The site tested mydomain.com is NOT the same as the Subject CN ip-00-00-00-000!.

I even went & copied the VistualHost to httpd.conf instead of ssl.conf & restarted apache, all in vain.

I've been banging my head against the wall for days now. I'm pretty sure I'm missing a tiny something to make this work, I just don't know what exactly.

I'd be infinitely grateful if someone can suggest something to make this work!

Body:
Looking at your list, it happens that you forget to enable your configuration with your Virtual host.

sudo a2enmod ssl
sudo a2ensite default-ssl
sudo /etc/init.d/apache2 restart

There is a complete guide on how to install an SSL certificate on your EC2 here https://medium.com/@adnanxteam/how-to-add-ssl-certificate-to-laravel-on-ec2-aws-18104cc036d1


问:
Strange letter print out from array c programming
I am trying to delete the blank space between a string and print out the first word with isalpha() function.

When I print out, only the first letter prints out. exempel "hello big panda" I get "hhhhh" but I want the hole word "hello" instead

```<code>int main()
{
    char inputString[]={"hello big panda"};
     int k=0;

    int i=0;
    do
    {
    inputString[i];
    i++;
    }
    while (inputString[i]=isalpha(inputString[i]));

    for(i=0; inputString[i] !='\0' ;i++)
    {
        for (k=i; inputString[k] != '\0'; k++)
        {
            inputString[k] =inputString[i];
        }
    }
    printf("%s", inputString);

    return 0;
}
</code>```

done this:

```<code>int printfirstword(char sentence[])
{
    int k=0;
    int i=0;
    while (isalpha(sentence[i])) //checking for the first blank space
    {
        i++;
    }
    sentence[i] = '\0';

    printf("%s\n", sentence);

    return 0;
}
int main()
{

        char sentence[100];
    int wordNumber;
    char answer;

    printfirstword("Hello there")
return0;
}
</code>```

But I don't want to change the string that is passed to it

答:
Your function must do 3 things as it works through the sentence finding words. (1) always check for the end of the string to prevent an attempted read beyond the end of the sentence; and (2) locate and print the requested word at the index given; and (3) handle the condition where the user requests a word index greater than that available.

(you should always test the sentence you are passed in the function to make sure the pointer isn't a NULL pointer, and that the contents of the sentence is simply the '\0' character indicating an empty-string)

An easy way to do this (after you have tested the input string), is to set up a continual loop, that repeatedly read the characters of a word, checks if it is the word to print (if so it prints), and if not read and discard all the non-alpha characters before the next word, and then repeats.

Something simple like the following works. It takes the sentence (or updated position within the sentence) and the index for the word to print zero-indexed, e.g. (0, 1, 2, ...) and then loops a described above.

(note: you can change the zero-index scheme to a 1, 2, 3, ... word-number scheme by initializing n=1; instead of 0 -- but since everything in C is zero indexed, that is left to you)

```<code>#include <stdio.h>
#include <ctype.h>

int prnword (const char *s, int nwrd)
{
    int n = 0;          /* word counter */
    char *p = s;        /* pointer to s */

    if (!s || !*s) {    /* test s not NULL and not empty */
        fprintf (stderr, "error: string NULL, empty or at end.\n");
        return 0;
    }

    for (;;) {      /* loop continually until exit condition reached */
        while (*p && isalpha(*p)) { /* loop over chars in s */
            if (n == nwrd)          /* if requested index */
                putchar (*p);       /* print all chars */
            p++;                    /* increment pointer */
        }

        while (*p && !isalpha(*p))  /* iterate find next alpha */
            p++;
        if (++n > nwrd)             /* if past our word, break */
            break;
        if (!*p)                    /* if end reached, break */
            break;
    }
    if (n <= nwrd) {    /* check request exceeds avaialble words */
        fprintf (stderr, "error: request word '%d' "
                "exceeds available wprds indexes.\n", nwrd);
        return 0;
    }
    putchar ('\n');                 /* tidy up with new line */

    return p - s;                   /* return number of chars to next alpha */
}
int main (void) {

    char str[] = "hello big panda";
    int nchars = 0;

    /* example -- all words in order
     * passing update string position
     */
    nchars = prnword (str, 0);
    nchars += prnword (str + nchars, 0);
    nchars += prnword (str + nchars, 0);
    putchar ('\n');

    /* request exceed available zero-based word indexes */
    nchars = 0;
    nchars += prnword (str, 3);
    putchar ('\n');

    /* print 2nd word only */
    nchars = 0;
    nchars = prnword (str, 1);
    putchar ('\n');

    return 0;
}
</code>```

Example Use/Output

Note the first block of calls to prnword print each of the words in the sentence, saving the number of characters returned by prior calls and using that to start the function reading the 1st character of the desired word, meaning you are always looking for word index 0.

The second call intentionally gives an index one past the last word to force handling the error.

And finally, the last call simply says "Go print word 2" (index 1) starting from scratch.

Example Use/Output

```<code>$ ./bin/words
hello
big
panda

error: request word '3' exceeds available wprds indexes.

big
</code>```

Look things over and let me know if you have questions.

Body:
I am trying to delete the blank space between a string and print out the first word with isalpha() function.

When I print out, only the first letter prints out. exempel "hello big panda" I get "hhhhh" but I want the hole word "hello" instead

int main()
{
    char inputString[]={"hello big panda"};
     int k=0;

    int i=0;
    do
    {
    inputString[i];
    i++;
    }
    while (inputString[i]=isalpha(inputString[i]));

    for(i=0; inputString[i] !='\0' ;i++)
    {
        for (k=i; inputString[k] != '\0'; k++)
        {
            inputString[k] =inputString[i];
        }
    }
    printf("%s", inputString);

    return 0;
}

done this:

int printfirstword(char sentence[])
{
    int k=0;
    int i=0;
    while (isalpha(sentence[i])) //checking for the first blank space
    {
        i++;
    }
    sentence[i] = '\0';

    printf("%s\n", sentence);

    return 0;
}
int main()
{

        char sentence[100];
    int wordNumber;
    char answer;

    printfirstword("Hello there")
return0;
}

But I don't want to change the string that is passed to it

Body:
Your function must do 3 things as it works through the sentence finding words. (1) always check for the end of the string to prevent an attempted read beyond the end of the sentence; and (2) locate and print the requested word at the index given; and (3) handle the condition where the user requests a word index greater than that available.

(you should always test the sentence you are passed in the function to make sure the pointer isn't a NULL pointer, and that the contents of the sentence is simply the '\0' character indicating an empty-string)

An easy way to do this (after you have tested the input string), is to set up a continual loop, that repeatedly read the characters of a word, checks if it is the word to print (if so it prints), and if not read and discard all the non-alpha characters before the next word, and then repeats.

Something simple like the following works. It takes the sentence (or updated position within the sentence) and the index for the word to print zero-indexed, e.g. (0, 1, 2, ...) and then loops a described above.

(note: you can change the zero-index scheme to a 1, 2, 3, ... word-number scheme by initializing n=1; instead of 0 -- but since everything in C is zero indexed, that is left to you)

#include <stdio.h>
#include <ctype.h>

int prnword (const char *s, int nwrd)
{
    int n = 0;          /* word counter */
    char *p = s;        /* pointer to s */

    if (!s || !*s) {    /* test s not NULL and not empty */
        fprintf (stderr, "error: string NULL, empty or at end.\n");
        return 0;
    }

    for (;;) {      /* loop continually until exit condition reached */
        while (*p && isalpha(*p)) { /* loop over chars in s */
            if (n == nwrd)          /* if requested index */
                putchar (*p);       /* print all chars */
            p++;                    /* increment pointer */
        }

        while (*p && !isalpha(*p))  /* iterate find next alpha */
            p++;
        if (++n > nwrd)             /* if past our word, break */
            break;
        if (!*p)                    /* if end reached, break */
            break;
    }
    if (n <= nwrd) {    /* check request exceeds avaialble words */
        fprintf (stderr, "error: request word '%d' "
                "exceeds available wprds indexes.\n", nwrd);
        return 0;
    }
    putchar ('\n');                 /* tidy up with new line */

    return p - s;                   /* return number of chars to next alpha */
}
int main (void) {

    char str[] = "hello big panda";
    int nchars = 0;

    /* example -- all words in order
     * passing update string position
     */
    nchars = prnword (str, 0);
    nchars += prnword (str + nchars, 0);
    nchars += prnword (str + nchars, 0);
    putchar ('\n');

    /* request exceed available zero-based word indexes */
    nchars = 0;
    nchars += prnword (str, 3);
    putchar ('\n');

    /* print 2nd word only */
    nchars = 0;
    nchars = prnword (str, 1);
    putchar ('\n');

    return 0;
}

Example Use/Output

Note the first block of calls to prnword print each of the words in the sentence, saving the number of characters returned by prior calls and using that to start the function reading the 1st character of the desired word, meaning you are always looking for word index 0.

The second call intentionally gives an index one past the last word to force handling the error.

And finally, the last call simply says "Go print word 2" (index 1) starting from scratch.

Example Use/Output

$ ./bin/words
hello
big
panda

error: request word '3' exceeds available wprds indexes.

big

Look things over and let me know if you have questions.


问:
Get reply from remote server using C# and PHP
I'm trying to get data from a remote server using C#. I tried using a simple script to see if "it works", but I'm not getting a response. The same script works on a local server, so I'd like to know how I can do it.

This is my C# code:

```<code>IEnumerator Sayhi()
{
    WWWForm sendInfo = new WWWForm();
    sendInfo.AddField("function", function);

    WWW www = new WWW(bl_LoginDataBase.Instance.GetUrl(bl_LoginDataBase.URLType.CallFunction), sendInfo);
    yield return www;
    Debug.Log(www.text);
}
</code>```

And the PHP code:

```<code><?php
echo "Hi";
</code>```

I expected the Debug.Log(www.text); to print Hi, which it does if I use a local machine (http://192.168.0.whatever), but the remote server (http://whatever.example.com) doesn't return anything. I tried making the php fail so it returns an error, make a database and return some values from there, but nothing. I'd like to point out it does work on a local server, and works as intended.

What am I doing wrong?

Edit: By the way, if I access http://www.whatever.example.com/Function.php via browser, it shows the echo result.

答:
C# has built in classes and methods to help you perform such tasks.You can use the WebClient class to connect to web servers (using GET or POST) and even send form values to it easily. See below:

```<code>string url ="http://www.whatever.example.com/Function.php";

var reqparam = new System.Collections.Specialized.NameValueCollection();

reqparam.Add("name", "John Doe");

try
{
    using (System.Net.WebClient client = new System.Net.WebClient())
    {

     byte[] responsebytes = client.UploadValues(url, "POST", parameters);

     string output = System.Text.Encoding.UTF8.GetString(responsebytes);

     }
}
catch (Exception x)
{
   //an error occured
}
</code>```

The variable output will contain the response you want "Hi".

Body:
I'm trying to get data from a remote server using C#. I tried using a simple script to see if "it works", but I'm not getting a response. The same script works on a local server, so I'd like to know how I can do it.

This is my C# code:

IEnumerator Sayhi()
{
    WWWForm sendInfo = new WWWForm();
    sendInfo.AddField("function", function);

    WWW www = new WWW(bl_LoginDataBase.Instance.GetUrl(bl_LoginDataBase.URLType.CallFunction), sendInfo);
    yield return www;
    Debug.Log(www.text);
}

And the PHP code:

<?php
echo "Hi";

I expected the Debug.Log(www.text); to print Hi, which it does if I use a local machine (http://192.168.0.whatever), but the remote server (http://whatever.example.com) doesn't return anything. I tried making the php fail so it returns an error, make a database and return some values from there, but nothing. I'd like to point out it does work on a local server, and works as intended.

What am I doing wrong?

Edit: By the way, if I access http://www.whatever.example.com/Function.php via browser, it shows the echo result.

Body:
C# has built in classes and methods to help you perform such tasks.You can use the WebClient class to connect to web servers (using GET or POST) and even send form values to it easily. See below:

string url ="http://www.whatever.example.com/Function.php";

var reqparam = new System.Collections.Specialized.NameValueCollection();

reqparam.Add("name", "John Doe");

try
{
    using (System.Net.WebClient client = new System.Net.WebClient())
    {

     byte[] responsebytes = client.UploadValues(url, "POST", parameters);

     string output = System.Text.Encoding.UTF8.GetString(responsebytes);

     }
}
catch (Exception x)
{
   //an error occured
}

The variable output will contain the response you want "Hi".


问:
Custom Field Validator Client Side on Yii2
I have some trouble when i try to add a custom Validator rule for my input.
This is my code.

MODEL

```<code>class Category extends \yii\db\ActiveRecord{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cat';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cat_cod','cat_deep','cat_father'], 'required'],
            //other rules
            [['cat_cod'], 'test'],

        ];
    }
    public function test($attribute){
        $cat_cod = $this->$attribute;
        if($cat_cod == 'test'){
            $this->addError($attribute,"Error Test");
        }
    }
</code>```

So, this is only a test, but it works fine when i submit my form, but it doesn't work in client side validaton.

if cat_cod is empty:

if i write test in the input field

In the 2 image when i write test doesn't validate on client side

UPDATE
Afte Yupik Comment, server side validation works fine, so if i want to add client side validation i must implement an AjaxValidation.
So i've activated ajax validation in only one field like this

```<code>$form->field($model, 'cat_cod',['enableAjaxValidation' => true])->textInput();
</code>```

Now in my controller how can i handle this? Documentation is not very clear.
This is What i've try

```<code>if($model->load(Yii::$app->request->post()) && $model->validate()){
        if (Yii::$app->request->isAjax ) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
   //something else
</code>```

答:
Because this is server side validator. To add client side validator use whenClient to check whether rule should be applied.
Read more docs

Body:
I have some trouble when i try to add a custom Validator rule for my input.
This is my code.

MODEL

class Category extends \yii\db\ActiveRecord{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cat';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cat_cod','cat_deep','cat_father'], 'required'],
            //other rules
            [['cat_cod'], 'test'],

        ];
    }
    public function test($attribute){
        $cat_cod = $this->$attribute;
        if($cat_cod == 'test'){
            $this->addError($attribute,"Error Test");
        }
    }

So, this is only a test, but it works fine when i submit my form, but it doesn't work in client side validaton.

if cat_cod is empty:

if i write test in the input field

In the 2 image when i write test doesn't validate on client side

UPDATE
Afte Yupik Comment, server side validation works fine, so if i want to add client side validation i must implement an AjaxValidation.
So i've activated ajax validation in only one field like this

$form->field($model, 'cat_cod',['enableAjaxValidation' => true])->textInput();

Now in my controller how can i handle this? Documentation is not very clear.
This is What i've try

if($model->load(Yii::$app->request->post()) && $model->validate()){
        if (Yii::$app->request->isAjax ) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
   //something else


问:
How can I encode a string to Base64 in Swift?
I want to convert a string to Base64. I found answers in several places, but it does not work anymore in Swift. I am using Xcode 6.2. I believe the answer might be work in previous Xcode versions and not Xcode 6.2.

Could someone please guide me to do this in Xcode 6.2?

The answer I found was this, but it does not work in my version of Xcode:

```<code>var str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")

// UTF 8 str from original
// NSData! type returned (optional)
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)

// Base64 encode UTF 8 string
// fromRaw(0) is equivalent to objc 'base64EncodedStringWithOptions:0'
// Notice the unwrapping given the NSData! optional
// NSString! returned (optional)
let base64Encoded = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println("Encoded:  \(base64Encoded)")

// Base64 Decode (go back the other way)
// Notice the unwrapping given the NSString! optional
// NSData returned
let data = NSData(base64EncodedString: base64Encoded, options:   NSDataBase64DecodingOptions.fromRaw(0)!)

// Convert back to a string
let base64Decoded = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Decoded:  \(base64Decoded)")
</code>```

ref: http://iosdevelopertips.com/swift-code/base64-encode-decode-swift.html

答:
Swift 4.0.3

```<code>import UIKit

extension String {

func fromBase64() -> String? {
    guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else {
        return nil
    }

    return String(data: data as Data, encoding: String.Encoding.utf8)
}

func toBase64() -> String? {
    guard let data = self.data(using: String.Encoding.utf8) else {
        return nil
    }

    return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
    }
}
</code>```

Body:
I want to convert a string to Base64. I found answers in several places, but it does not work anymore in Swift. I am using Xcode 6.2. I believe the answer might be work in previous Xcode versions and not Xcode 6.2.

Could someone please guide me to do this in Xcode 6.2?

The answer I found was this, but it does not work in my version of Xcode:

var str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")

// UTF 8 str from original
// NSData! type returned (optional)
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)

// Base64 encode UTF 8 string
// fromRaw(0) is equivalent to objc 'base64EncodedStringWithOptions:0'
// Notice the unwrapping given the NSData! optional
// NSString! returned (optional)
let base64Encoded = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println("Encoded:  \(base64Encoded)")

// Base64 Decode (go back the other way)
// Notice the unwrapping given the NSString! optional
// NSData returned
let data = NSData(base64EncodedString: base64Encoded, options:   NSDataBase64DecodingOptions.fromRaw(0)!)

// Convert back to a string
let base64Decoded = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Decoded:  \(base64Decoded)")

ref: http://iosdevelopertips.com/swift-code/base64-encode-decode-swift.html

Body:
Swift 4.0.3

import UIKit

extension String {

func fromBase64() -> String? {
    guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else {
        return nil
    }

    return String(data: data as Data, encoding: String.Encoding.utf8)
}

func toBase64() -> String? {
    guard let data = self.data(using: String.Encoding.utf8) else {
        return nil
    }

    return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
    }
}


问:
Google Assistant changing the surface not working

Hi guys,

I'm currently trying to build an app for the Google Assistant with Dialogflow. During a particular intent I want to redirect the user to his phone (when using a speaker) as the intent requires precise keyboard input.
As said in the docs, I'm calling askForNewSurface() in my webhook. In the actions simulator, this is what shows up (truncated)

```<code>"agentToAssistantJson": {
  "conversationToken": "[\"_actions_on_google_\",\"some-context\"]",
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "PLACEHOLDER_FOR_NEW_SURFACE"
              }
            }
          ]
        }
      },
      "possibleIntents": [
        {
          "intent": "actions.intent.NEW_SURFACE",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.NewSurfaceValueSpec",
            "context": "To show you an image",
            "notificationTitle": "Check out this image",
            "capabilities": [
              "actions.capability.SCREEN_OUTPUT"
            ]
          }
        }
      ]
    }
  ],
  "responseMetadata": {
    "status": {},
    "queryMatchInfo": {
      "queryMatched": true,
      "intent": "####",
      "parameterNames": [
        "date"
      ]
    }
  },
  "expectedInput": {
    "requestedIntent": {
      "intent": "####"
    }
  }
}
</code>```

}

This seems valid according to the docs, however the Google Assistant just comes back with 'Sorry, I didn't get any response' (on both the simulator and on actual devices).

So how do I get the assistant to actually ask the user to change the surface?

Is this method maybe not supported at all in german? Also the docs are somewhat inconsistent regarding the existence of actions.intent.NEW_SURFACE as a system intent...

Thanks in advance guys, any hints appreciated :)

EDIT: Noticed the question has already been asked here

答:
Okay, I got in touch with AoG support. Turns out we'll need a little patience.

Hi Jan,

Thank you for your interest in Actions on Google. askForNewSurface is indeed only available for English locales. We are in the process of changing the documentation to reflect those restrictions.
  Sorry for the confusion.
  We do not have any set date for the release of this feature in other locales.

Kind Regards,

Jean-Charles,

Actions on Google Support Team.

Body:
Hi guys,

I'm currently trying to build an app for the Google Assistant with Dialogflow. During a particular intent I want to redirect the user to his phone (when using a speaker) as the intent requires precise keyboard input.
As said in the docs, I'm calling askForNewSurface() in my webhook. In the actions simulator, this is what shows up (truncated)

"agentToAssistantJson": {
  "conversationToken": "[\"_actions_on_google_\",\"some-context\"]",
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "PLACEHOLDER_FOR_NEW_SURFACE"
              }
            }
          ]
        }
      },
      "possibleIntents": [
        {
          "intent": "actions.intent.NEW_SURFACE",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.NewSurfaceValueSpec",
            "context": "To show you an image",
            "notificationTitle": "Check out this image",
            "capabilities": [
              "actions.capability.SCREEN_OUTPUT"
            ]
          }
        }
      ]
    }
  ],
  "responseMetadata": {
    "status": {},
    "queryMatchInfo": {
      "queryMatched": true,
      "intent": "####",
      "parameterNames": [
        "date"
      ]
    }
  },
  "expectedInput": {
    "requestedIntent": {
      "intent": "####"
    }
  }
}

}

This seems valid according to the docs, however the Google Assistant just comes back with 'Sorry, I didn't get any response' (on both the simulator and on actual devices).

So how do I get the assistant to actually ask the user to change the surface?

Is this method maybe not supported at all in german? Also the docs are somewhat inconsistent regarding the existence of actions.intent.NEW_SURFACE as a system intent...

Thanks in advance guys, any hints appreciated :)

EDIT: Noticed the question has already been asked here


问:
Doesn't run this commands on mautic cron job
Hi guys i have the next problem(sorry for my english):

I want to executate a command in Mautic cron job, i put the next comands:

*/1 * * * * /usr/local/bin/php /apps/mautic/htdocs/app/console  mautic:segments:update

*/1 * * * * /usr/local/bin/php /apps/mautic/htdocs/app/console mautic:campaigns:update

*/1 * * * * /usr/local/bin/php /apps/mautic/htdocs/app/console mautic:campaigns:trigger

I try a lot of things but no one of them work, like:

```<code>*/1 * * * *  root /usr/local/bin/php /apps/mautic/htdocs/app/console  mautic:segments:update
</code>```

or

```<code>*/1 * * * * bitnami php /apps/mautic/htdocs/app/console  mautic:segments:update
</code>```

But i don't know what fail's,if it's the user name,the route to php,the comand,if they doesn't have permission...

If i put this manually work perfectly

```<code>php /apps/mautic/htdocs/app/console  mautic:segments:update
</code>```

ty so much

答:
You should check whether the path of the php program correct. You can check the the full path of the php program in terminal output by this command:

```<code>which php
</code>```

To create a cron job, should always use the full path of the program. The crontab default environment is not like the logged in user. The program may not be found  if the path is not defined to the crontab environment.

The crontab syntax composed of two parts, datetime to execute & command to be executed. User is not required to add before the command.

```<code>*     *     *   *    *        command to be executed
-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of        month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)
</code>```

Body:
Hi guys i have the next problem(sorry for my english):

I want to executate a command in Mautic cron job, i put the next comands:

*/1 * * * * /usr/local/bin/php /apps/mautic/htdocs/app/console  mautic:segments:update

*/1 * * * * /usr/local/bin/php /apps/mautic/htdocs/app/console mautic:campaigns:update

*/1 * * * * /usr/local/bin/php /apps/mautic/htdocs/app/console mautic:campaigns:trigger

I try a lot of things but no one of them work, like:

*/1 * * * *  root /usr/local/bin/php /apps/mautic/htdocs/app/console  mautic:segments:update

or

*/1 * * * * bitnami php /apps/mautic/htdocs/app/console  mautic:segments:update

But i don't know what fail's,if it's the user name,the route to php,the comand,if they doesn't have permission...

If i put this manually work perfectly

php /apps/mautic/htdocs/app/console  mautic:segments:update

ty so much

Body:
You should check whether the path of the php program correct. You can check the the full path of the php program in terminal output by this command:

which php

To create a cron job, should always use the full path of the program. The crontab default environment is not like the logged in user. The program may not be found  if the path is not defined to the crontab environment.

The crontab syntax composed of two parts, datetime to execute & command to be executed. User is not required to add before the command.

*     *     *   *    *        command to be executed
-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of        month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)