问:
SomeObject is an interface, and JAXB can't handle interfaces
In my application there is a tree of objects. To constitute that tree every object has a parent reference.  Since certain object types can be child of several parent object types all potential parent object types are unified by implementing a common interface.
I narrowed down the problem (JAXB complains about the parent member variable (annotated @XmlIDREF and @XmlAttribute) being an interface) as much as I could:

```<code>public interface Parent{
    @XmlID
    @XmlAttribute( name = "oid" )
    public String getID();
    public void setID( String id );
}

@XmlRootElement
@XmlAccessorType( XmlAccessType.NONE )
public class ChildObject implements Parent{
    @XmlTransient
    private UUID id = UUID.randomUUID();

    @XmlIDREF
    @XmlAttribute
    protected Parent parent = null;

    public ChildObject() {}

    public ChildObject( Parent parent ){
        this.parent = parent;
    }

    @XmlID
    @XmlAttribute
    @Override
    public String getID(){ return( id.toString() ); }

    @Override
    public void setID( String id ){ this.id = UUID.fromString( id ); }
}

@XmlRootElement
@XmlAccessorType( XmlAccessType.NONE )
public class Repository{

    @XmlElement
    private List<ChildObject> objects = new ArrayList<>();

    public Repository() {}

    public ChildObject addObject( ChildObject o ){
        objects.add( o );
        return( o );
    }

    public static void main( String[] args ){
        Repository r = new Repository();
        ChildObject root = r.addObject( new ChildObject() );
        ChildObject c0 = r.addObject( new ChildObject( root ) );
        ChildObject c1 = r.addObject( new ChildObject( root ) );
        ChildObject c11 = r.addObject( new ChildObject( c1 ) );
        ChildObject c12 = r.addObject( new ChildObject( c1 ) );
        try{
            JAXBContext context = JAXBContext.newInstance( Repository.class );
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
            marshaller.marshal( r, System.out );
        }catch( Exception ex ){ ex.printStackTrace(); }
    }
}
</code>```

This is the exception I get, when trying to run it:

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1
  counts of IllegalAnnotationExceptions Parent is an interface, and JAXB
  can't handle interfaces.  this problem is related to the following
  location:         at Parent       at protected Parent ChildObject.parent      at
  ChildObject       at private java.util.List Repository.objects        at
  Repository

at
  com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:91)
    at
  com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:445)
    at
  com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:277)
    at
  com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:124)
    at
  com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1123)
    at
  com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:147)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:247)  at
  javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:234)  at
  javax.xml.bind.ContextFinder.find(ContextFinder.java:462)     at
  javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641)  at
  javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)  at
  Repository.main(Repository.java:33)

Is this the intended behavior of JAXB (or is it a bug) and  what am I supposed to do to get around it?

答:
I solved the problem by adding a dummy @XmlJavaTypeAdapter to the interface like so:

```<code>@XmlAccessorType( XmlAccessType.NONE )
@XmlJavaTypeAdapter(ChildObject.ParentAdapter.class)
public interface Parent{
    @XmlID
    @XmlAttribute( name = "oid" )
    public abstract String getID();
    public abstract void setID( String id );
}

@XmlRootElement
@XmlAccessorType( XmlAccessType.NONE )
public class ChildObject implements Parent{

    @XmlTransient
    private UUID id = UUID.randomUUID();

    @XmlIDREF
    @XmlAttribute
    protected Parent parent = null;

    public ChildObject() {}

    public ChildObject( Parent parent ){
        this.parent = parent;
    }

    @XmlID
    @XmlAttribute( name = "oid" )
    @Override
    public String getID(){ return( id.toString() ); }

    @Override
    public void setID( String id ){ this.id = UUID.fromString( id ); }

    public static class ParentAdapter extends XmlAdapter<Object,Object>{
        @Override
        public Object marshal( Object arg0 ) throws Exception{ return arg0; }

        @Override
        public Object unmarshal( Object arg0 ) throws Exception{ return arg0; }
    }
}
</code>```

Still, I'm not sure whether this is a bug or the intended behavior of JAXB (Oracle JDK 8u121)

Body:
In my application there is a tree of objects. To constitute that tree every object has a parent reference.  Since certain object types can be child of several parent object types all potential parent object types are unified by implementing a common interface.
I narrowed down the problem (JAXB complains about the parent member variable (annotated @XmlIDREF and @XmlAttribute) being an interface) as much as I could:

public interface Parent{
    @XmlID
    @XmlAttribute( name = "oid" )
    public String getID();
    public void setID( String id );
}

@XmlRootElement
@XmlAccessorType( XmlAccessType.NONE )
public class ChildObject implements Parent{
    @XmlTransient
    private UUID id = UUID.randomUUID();

    @XmlIDREF
    @XmlAttribute
    protected Parent parent = null;

    public ChildObject() {}

    public ChildObject( Parent parent ){
        this.parent = parent;
    }

    @XmlID
    @XmlAttribute
    @Override
    public String getID(){ return( id.toString() ); }

    @Override
    public void setID( String id ){ this.id = UUID.fromString( id ); }
}

@XmlRootElement
@XmlAccessorType( XmlAccessType.NONE )
public class Repository{

    @XmlElement
    private List<ChildObject> objects = new ArrayList<>();

    public Repository() {}

    public ChildObject addObject( ChildObject o ){
        objects.add( o );
        return( o );
    }

    public static void main( String[] args ){
        Repository r = new Repository();
        ChildObject root = r.addObject( new ChildObject() );
        ChildObject c0 = r.addObject( new ChildObject( root ) );
        ChildObject c1 = r.addObject( new ChildObject( root ) );
        ChildObject c11 = r.addObject( new ChildObject( c1 ) );
        ChildObject c12 = r.addObject( new ChildObject( c1 ) );
        try{
            JAXBContext context = JAXBContext.newInstance( Repository.class );
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
            marshaller.marshal( r, System.out );
        }catch( Exception ex ){ ex.printStackTrace(); }
    }
}

This is the exception I get, when trying to run it:

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1
  counts of IllegalAnnotationExceptions Parent is an interface, and JAXB
  can't handle interfaces.  this problem is related to the following
  location:         at Parent       at protected Parent ChildObject.parent      at
  ChildObject       at private java.util.List Repository.objects        at
  Repository

at
  com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:91)
    at
  com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:445)
    at
  com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:277)
    at
  com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:124)
    at
  com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1123)
    at
  com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:147)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:247)  at
  javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:234)  at
  javax.xml.bind.ContextFinder.find(ContextFinder.java:462)     at
  javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641)  at
  javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)  at
  Repository.main(Repository.java:33)

Is this the intended behavior of JAXB (or is it a bug) and  what am I supposed to do to get around it?

Body:
I solved the problem by adding a dummy @XmlJavaTypeAdapter to the interface like so:

@XmlAccessorType( XmlAccessType.NONE )
@XmlJavaTypeAdapter(ChildObject.ParentAdapter.class)
public interface Parent{
    @XmlID
    @XmlAttribute( name = "oid" )
    public abstract String getID();
    public abstract void setID( String id );
}

@XmlRootElement
@XmlAccessorType( XmlAccessType.NONE )
public class ChildObject implements Parent{

    @XmlTransient
    private UUID id = UUID.randomUUID();

    @XmlIDREF
    @XmlAttribute
    protected Parent parent = null;

    public ChildObject() {}

    public ChildObject( Parent parent ){
        this.parent = parent;
    }

    @XmlID
    @XmlAttribute( name = "oid" )
    @Override
    public String getID(){ return( id.toString() ); }

    @Override
    public void setID( String id ){ this.id = UUID.fromString( id ); }

    public static class ParentAdapter extends XmlAdapter<Object,Object>{
        @Override
        public Object marshal( Object arg0 ) throws Exception{ return arg0; }

        @Override
        public Object unmarshal( Object arg0 ) throws Exception{ return arg0; }
    }
}

Still, I'm not sure whether this is a bug or the intended behavior of JAXB (Oracle JDK 8u121)


来源: stackexchange

问:
Return mulitple string is not working
I want to return multiple string from the below function. How to do that</p>

```<code>public static string GETSTATE_SAP(string SAP)
    {
        string strState = "";
        string strSiteAdd = "";
        string strLatitude = "";
        string strLongtiude = "";
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);
            strState = Convert.ToString(dtSap.Rows[0][0]);
            strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return strState, strSiteAdd, strLatitude, strLongtiude;
    }
</code>```

答:
You are using Public method.
Personally I don't like using out parameter for public method.

But If you don't want to create new class, then you can try below method.

```<code>    public static bool GETSTATE_SAP(string SAP, out string strState, out string strSiteAdd, out string strLatitude, out string strLongtiude)
        {
            strState = string.Empty;
            strSiteAdd = string.Empty;
            strLatitude = string.Empty;
            strLongtiude = string.Empty;
            try
            {
                OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
                Oraconn.Open();
                OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
                OracleDataAdapter da = new OracleDataAdapter(cmd);
                DataTable dtSap = new DataTable();
                da.Fill(dtSap);
if(dtSap.Rows.Count > 0){
                strState = Convert.ToString(dtSap.Rows[0][0]);
                strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
                strLatitude = Convert.ToString(dtSap.Rows[0][0]);
                strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
return true;
}
            }
            catch (Exception)
            {
            }
            return false;
        }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Return mulitple string is not working

Body:
I want to return multiple string from the below function. How to do that

public static string GETSTATE_SAP(string SAP)
    {
        string strState = "";
        string strSiteAdd = "";
        string strLatitude = "";
        string strLongtiude = "";
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);
            strState = Convert.ToString(dtSap.Rows[0][0]);
            strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return strState, strSiteAdd, strLatitude, strLongtiude;
    }

Body:
You are using Public method.
Personally I don't like using out parameter for public method.

But If you don't want to create new class, then you can try below method.

    public static bool GETSTATE_SAP(string SAP, out string strState, out string strSiteAdd, out string strLatitude, out string strLongtiude)
        {
            strState = string.Empty;
            strSiteAdd = string.Empty;
            strLatitude = string.Empty;
            strLongtiude = string.Empty;
            try
            {
                OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
                Oraconn.Open();
                OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
                OracleDataAdapter da = new OracleDataAdapter(cmd);
                DataTable dtSap = new DataTable();
                da.Fill(dtSap);
if(dtSap.Rows.Count > 0){
                strState = Convert.ToString(dtSap.Rows[0][0]);
                strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
                strLatitude = Convert.ToString(dtSap.Rows[0][0]);
                strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
return true;
}
            }
            catch (Exception)
            {
            }
            return false;
        }


问:
Checking if there is any validation error when using custom form request class
I am using Laravel 5.4. I have a custom form request class where I have my validation rules and messages and I use it in my controller like following :

```<code>public function store(CustomFormRequest $request)
{
  //
}
</code>```

I am using ajax to send the request and when there is any validation error, Laravel throws an error with an HTTP response with a 422 status code including a JSON representation of the validation errors.

But I don't want that. Instead, inside my controller's method, I want to find out if there is any validation error and if there is any then I want to return a response with some additional data along with the validation messages, like this:

```<code>// Inside my Controller
public function store(CustomFormRequest $request)
{
   if ($validator->fails())
   {
        $errors = $validator->errors();

        return response()->json(array('status' => 2, 'msg' => $errors->all() ));
    }
}
</code>```

Could you please help ?
Thanks in advance.

答:
The easiest way to do this would be to override the response() method for the Form Request class.

To do this you can simply add something like the following to your class:

```<code>public function response(array $errors)
{
    if ($this->expectsJson()) {
        return new JsonResponse(['status' => 2, 'msg' => $errors], 422);
    }

    return parent::response($errors);
}
</code>```

Don't for get to import Illuminate\Http\JsonResponse

Hope this helps!

Body:
I am using Laravel 5.4. I have a custom form request class where I have my validation rules and messages and I use it in my controller like following :

public function store(CustomFormRequest $request)
{
  //
}

I am using ajax to send the request and when there is any validation error, Laravel throws an error with an HTTP response with a 422 status code including a JSON representation of the validation errors.

But I don't want that. Instead, inside my controller's method, I want to find out if there is any validation error and if there is any then I want to return a response with some additional data along with the validation messages, like this:

// Inside my Controller
public function store(CustomFormRequest $request)
{
   if ($validator->fails())
   {
        $errors = $validator->errors();

        return response()->json(array('status' => 2, 'msg' => $errors->all() ));
    }
}

Could you please help ?
Thanks in advance.

Body:
The easiest way to do this would be to override the response() method for the Form Request class.

To do this you can simply add something like the following to your class:

public function response(array $errors)
{
    if ($this->expectsJson()) {
        return new JsonResponse(['status' => 2, 'msg' => $errors], 422);
    }

    return parent::response($errors);
}

Don't for get to import Illuminate\Http\JsonResponse

Hope this helps!


问:
Directly accessing nested dictionary values in Objective-C
Is there a way to directly access an inner-array of an an outer array in Objective-C?  For example, a call to an external data source returns the following object:

```<code>{
bio = "this is the profile.bio data";
"first_name" = John;
"last_name" = Doe;
location =     {
    name = "Any Town, Any State";
};
metadata =    {
    pictures =    {
        picture = "https://picture.mysite.com/picture.jpeg";
    }
}
}
</code>```

I want to be able to access, for example, the location.name or the metadata.pictures.picture data.  Dot notation, however, does not seem to work.  For example:

```<code>_gfbLocation = [result objectForKey:@"location.name"];
_gfbPicture = [result objectForKey:@"metadata.pictures.picture"];
</code>```

The only way I have been able to access this data is by first setting the contents of the inner arrays to objects.  Thoughts?

答:
For nested keys like that you can use a keyPath. A keyPath is just a series of keys joined with dots. You can use them to retrieve nested values from objects that support Key-Value Coding - including NSDictionary objects like yours. So in your case this should work:

```<code>[result valueForKeyPath:@"location.name"];
</code>```

For more detail on Key-Value Coding, see Apple's Key-Value Coding Programming Guide.

See also this related StackOverflow question.

Body:
Is there a way to directly access an inner-array of an an outer array in Objective-C?  For example, a call to an external data source returns the following object:

{
bio = "this is the profile.bio data";
"first_name" = John;
"last_name" = Doe;
location =     {
    name = "Any Town, Any State";
};
metadata =    {
    pictures =    {
        picture = "https://picture.mysite.com/picture.jpeg";
    }
}
}

I want to be able to access, for example, the location.name or the metadata.pictures.picture data.  Dot notation, however, does not seem to work.  For example:

_gfbLocation = [result objectForKey:@"location.name"];
_gfbPicture = [result objectForKey:@"metadata.pictures.picture"];

The only way I have been able to access this data is by first setting the contents of the inner arrays to objects.  Thoughts?

Body:
For nested keys like that you can use a keyPath. A keyPath is just a series of keys joined with dots. You can use them to retrieve nested values from objects that support Key-Value Coding - including NSDictionary objects like yours. So in your case this should work:

[result valueForKeyPath:@"location.name"];

For more detail on Key-Value Coding, see Apple's Key-Value Coding Programming Guide.

See also this related StackOverflow question.

ContentLicense: CC BY-SA 2.5


问:
Lower Case Certain Words R
I need to convert certain words to lower case. I am working with a list of movie titles, where prepositions and articles are normally lower case if they are not the first word in the title. If I have the vector:

movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace', 'Me And Earl And The Dying Girl')

What I need is this:

movies_updated = c('The Kings of Summer', 'The Words', 'Out of the Furnace', 'Me and Earl and the Dying Girl')

Is there an elegant way to do this without using a long series of gsub(), as in:

```<code>movies_updated = gsub(' In ', ' in ', movies)
movies_updated = gsub(' In', ' in', movies_updated)
movies_updated = gsub(' Of ', ' of ', movies)
movies_updated = gsub(' Of', ' of', movies_updated)
movies_updated = gsub(' The ', ' the ', movies)
movies_updated = gsub(' the', ' the', movies_updated)
</code>```

And so on.

答:
Another example of how to turn certain words to lower case with gsub (with a PCRE regex):

```<code>movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace', 'Me And Earl And The Dying Girl')
gsub("(?!^)\\b(Of|In|The)\\b", "\\L\\1", movies, perl=TRUE)
</code>```

See the R demo

Details:

(?!^) - not at the start of the string (it does not matter if we use a lookahead or lookbehind here since the pattern inside is a zero-width assertion)

\\b - find leading word boundary

(Of|In|The) - capture Of or In or The into Group 1

\\b - assure there is a trailing word boundary.

The replacement contains the lowercasing operator \L that turns all the chars in the first backreference value (the text captured into Group 1) to lower case.

Note it can turn out a more flexible approach than using tools::toTitleCase. The code part that keeps specific words in lower case is:

```<code>## These should be lower case except at the beginning (and after :)
lpat <- "^(a|an|and|are|as|at|be|but|by|en|for|if|in|is|nor|not|of|on|or|per|so|the|to|v[.]?|via|vs[.]?|from|into|than|that|with)$"
</code>```

If you only need to apply lowercasing and do not care about the other logic in the function, it might be enough to add these alternatives (do not use ^ and $ anchors) to the regex at the top of the post.

Title: Lower Case Certain Words R

Body:
I need to convert certain words to lower case. I am working with a list of movie titles, where prepositions and articles are normally lower case if they are not the first word in the title. If I have the vector:

movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace', 'Me And Earl And The Dying Girl')

What I need is this:

movies_updated = c('The Kings of Summer', 'The Words', 'Out of the Furnace', 'Me and Earl and the Dying Girl')

Is there an elegant way to do this without using a long series of gsub(), as in:

movies_updated = gsub(' In ', ' in ', movies)
movies_updated = gsub(' In', ' in', movies_updated)
movies_updated = gsub(' Of ', ' of ', movies)
movies_updated = gsub(' Of', ' of', movies_updated)
movies_updated = gsub(' The ', ' the ', movies)
movies_updated = gsub(' the', ' the', movies_updated)

And so on.

Body:
Another example of how to turn certain words to lower case with gsub (with a PCRE regex):

movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace', 'Me And Earl And The Dying Girl')
gsub("(?!^)\\b(Of|In|The)\\b", "\\L\\1", movies, perl=TRUE)

See the R demo

Details:

(?!^) - not at the start of the string (it does not matter if we use a lookahead or lookbehind here since the pattern inside is a zero-width assertion)

\\b - find leading word boundary

(Of|In|The) - capture Of or In or The into Group 1

\\b - assure there is a trailing word boundary.

The replacement contains the lowercasing operator \L that turns all the chars in the first backreference value (the text captured into Group 1) to lower case.

Note it can turn out a more flexible approach than using tools::toTitleCase. The code part that keeps specific words in lower case is:

## These should be lower case except at the beginning (and after :)
lpat <- "^(a|an|and|are|as|at|be|but|by|en|for|if|in|is|nor|not|of|on|or|per|so|the|to|v[.]?|via|vs[.]?|from|into|than|that|with)$"

If you only need to apply lowercasing and do not care about the other logic in the function, it might be enough to add these alternatives (do not use ^ and $ anchors) to the regex at the top of the post.


问:
Intersection of final lines
I have a simple Point object

```<code>public class Point {
private double x;
private double y;
}
</code>```

and simple Line object

```<code>public class Line {
private Point start;
private Point end;
}
</code>```

Now I need to find the intersection of two lines, and it's not that simple because the lines have start point and end point....

```<code>public boolean isIntersecting(Line other) {
....
}

public Point intersectionWith(Line other) {
.....
</code>```

Any ideias?

答:
First， I think you mean line segment， line has no start and end.
Then,
take start points and end points into equation y = kx + b;
you would get (k1, b1) and (k2, b2),

if k1 == k2 and b1 != b2
  two lines are parallel

if k1 == k2 and b1 == b2
  two lines are same line

if k1 != k2
using y=k1x+b1 and y=k2x+b2 to get point of the intersection(x, y)

finally compare (x, y) with start points and end points to see if there is a intersection.

Title: Intersection of final lines

Body:
I have a simple Point object

public class Point {
private double x;
private double y;
}

and simple Line object

public class Line {
private Point start;
private Point end;
}

Now I need to find the intersection of two lines, and it's not that simple because the lines have start point and end point....

public boolean isIntersecting(Line other) {
....
}

public Point intersectionWith(Line other) {
.....

Any ideias?


问:
In general, does replacing AND with a pair of nested IFs speed things up?
I'm weighing the differences between

```<code>If[condition1 AND condition2, A, B]
</code>```

and

```<code>If[condition1, If[condition2, A, B], B]
</code>```

My thinking: the nested IFs will be faster.

My reasoning: By nesting the IFs, condition2 is evaluated only when condition1 is true. In what I'm doing, that means condition2 will be evaluated fewer times than in the first option above.

AND is the usual logical "and" (true if and only if both premises are true). By IF, I mean IF[condition, when condition is true, when condition is false].

I hope my question is not too ill-posed; I'm sure there are examples where the first option will run faster. I was just hoping that something is true in general.

Thank you.

答:
Mathematica will short-circuit the evaluation of And and Or if the result becomes known before evaluating all the conditions.

You can see this by using a condition that (artificially) takes a long time:

```<code>Timing[If[False && (Pause[10]; True), True, False]]
Timing[If[False, If[(Pause[10]; True), True, False], False]]
</code>```

and seeing that both return in a fraction of a second instead of in ten seconds.

Body:
I'm weighing the differences between

If[condition1 AND condition2, A, B]

and

If[condition1, If[condition2, A, B], B]

My thinking: the nested IFs will be faster.

My reasoning: By nesting the IFs, condition2 is evaluated only when condition1 is true. In what I'm doing, that means condition2 will be evaluated fewer times than in the first option above.

AND is the usual logical "and" (true if and only if both premises are true). By IF, I mean IF[condition, when condition is true, when condition is false].

I hope my question is not too ill-posed; I'm sure there are examples where the first option will run faster. I was just hoping that something is true in general.

Thank you.

Body:
Mathematica will short-circuit the evaluation of And and Or if the result becomes known before evaluating all the conditions.

You can see this by using a condition that (artificially) takes a long time:

Timing[If[False && (Pause[10]; True), True, False]]
Timing[If[False, If[(Pause[10]; True), True, False], False]]

and seeing that both return in a fraction of a second instead of in ten seconds.


问:
Android Error in Text_Input_Layout Edittext

Does anyone know how I can change the position of the mentioned part of error floating label (as in the attached image) ? In the picture it is on the left but I want it to be on the right side of the edittext (because of my native language) . I tried gravity and layout gravity but none of them worked out . Thanks in advance .

```<code> <android.support.design.widget.TextInputLayout
android:id="@+id/numid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
app:errorEnabled="true"
app:errorTextAppearance="@style/myerror"
android:layout_gravity="center"
    app:hintTextAppearance="@style/TextAppearance.AppCompat.TextInputLayout"
style="@style/EditScreenTextInputLayoutStyle">

 <android.support.v7.widget.AppCompatEditText
    android:id="@+id/tie"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:gravity="right"
    android:textAlignment="gravity"
    android:hint="@string/hint2"
    android:textDirection="rtl"
    />
</code>```

```<code>  <style name="TextAppearance.AppCompat.TextInputLayout" parent="@android:style/TextAppearance">
<item name="android:textColor">#ff0000</item>
<item name="android:layout_gravity">right</item>
<item name="android:textColorHint">#736f6e</item>
<item name="android:gravity">right</item>
</code>```

```<code><style name="EditScreenTextInputLayoutStyle" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">#000</item>
<item name="colorControlActivated">#000</item>
<item name="colorControlHighlight">#ff0000</item>
<item name="colorAccent">#ffff02</item>
<item name="android:textColorHint">#0000ff</item>
  </style>

<style name="myerror" parent="TextAppearance.Design.Error">
    <item name="android:textColor">#ff0000</item>
    <item name="android:background">#000000</item>
    <item name="android:gravity">center</item>

</style>
</code>```

答:
The code below works for u

```<code>public class MainActivity extends Activity {
    EditText use, pass;

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        use = (EditText) findViewById(R.id.edituse);
        pass = (EditText) findViewById(R.id.editpas);

        button = (Button) findViewById(R.id.click);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                final String use1 = use.getText().toString();
                final String pass1 = pass.getText().toString();

                if (!use1.matches("") && !pass1.matches("")) {
                    Toast.makeText(getApplicationContext(), "Succes",
                            Toast.LENGTH_SHORT).show();

                    use.setError(null);
                    pass.setError(null);

                } else if (use1.matches("")) {
                    use.setError("This field can not be blank");
                } else if (pass1.matches("")) {
                    pass.setError("This field can not be blank");
                }
            }
        });

    }
}
</code>```

And the Xml file

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/test"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Test"
        android:textSize="25sp"
        android:gravity="center" />

    <EditText
        android:layout_below="@+id/test"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edituse"/>
     <EditText
        android:layout_below="@+id/edituse"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editpas"
         />
<Button
    android:id="@+id/click"
    android:layout_below="@+id/editpas"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Click"/>

</RelativeLayout>
</code>```

Hope this helps...and for English this works.For ur language its a right to left writing,then it may be the problem for the left alignment of the error msg.... ...Don't worry try this.

Body:
Does anyone know how I can change the position of the mentioned part of error floating label (as in the attached image) ? In the picture it is on the left but I want it to be on the right side of the edittext (because of my native language) . I tried gravity and layout gravity but none of them worked out . Thanks in advance .

 <android.support.design.widget.TextInputLayout
android:id="@+id/numid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
app:errorEnabled="true"
app:errorTextAppearance="@style/myerror"
android:layout_gravity="center"
    app:hintTextAppearance="@style/TextAppearance.AppCompat.TextInputLayout"
style="@style/EditScreenTextInputLayoutStyle">

 <android.support.v7.widget.AppCompatEditText
    android:id="@+id/tie"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:gravity="right"
    android:textAlignment="gravity"
    android:hint="@string/hint2"
    android:textDirection="rtl"
    />

Body:
The code below works for u

public class MainActivity extends Activity {
    EditText use, pass;

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        use = (EditText) findViewById(R.id.edituse);
        pass = (EditText) findViewById(R.id.editpas);

        button = (Button) findViewById(R.id.click);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                final String use1 = use.getText().toString();
                final String pass1 = pass.getText().toString();

                if (!use1.matches("") && !pass1.matches("")) {
                    Toast.makeText(getApplicationContext(), "Succes",
                            Toast.LENGTH_SHORT).show();

                    use.setError(null);
                    pass.setError(null);

                } else if (use1.matches("")) {
                    use.setError("This field can not be blank");
                } else if (pass1.matches("")) {
                    pass.setError("This field can not be blank");
                }
            }
        });

    }
}

And the Xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/test"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Test"
        android:textSize="25sp"
        android:gravity="center" />

    <EditText
        android:layout_below="@+id/test"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edituse"/>
     <EditText
        android:layout_below="@+id/edituse"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editpas"
         />
<Button
    android:id="@+id/click"
    android:layout_below="@+id/editpas"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Click"/>

</RelativeLayout>

Hope this helps...and for English this works.For ur language its a right to left writing,then it may be the problem for the left alignment of the error msg.... ...Don't worry try this.


问:
how does a font tell the OS that "I AM a MONSPACED / FIXED-WIDTH FONT"?
at the very first, i only want to know, why in IDE PYCHARM on Windows 10, while "show only monospaced fonts" checked, many fonts will not be listed in the editor's font selecting dialog-box[settings/editor/colors and fonts/font], also in mintty.

I don't know how does the pycharm do, but the mintty uses the win32 API "LOGFONT".

then, how did the windows OS know whether the font is monospaced(fixed-width)?

i.e.:
"source code pro" is listed, "source code pro black / extralight / light ... are not;

"fira code" is listed, but fira code light/medium/retina are not;

and, some other monospaced fonts are not listed there if "show only monospaced".

it seems that pycharm only recognize the font family name when checked "show only monospced fonts"

in OSX(Mavericks) it's a little complicated : if the 'show only monospaced fonts' was checked, pycharm could still get the family name, but it could not know which font-weight is default if the rugular weighted font version was installed.

then, i tried to modify some fonts, and by the way having a glance to the original font's 'file-info' in font forge, but i don't know which part really effects the WINDOWS or PYCHARM(IDEA/INTELIJ/by JDK in fact?) to know which font is monospaced.

in "OS/2" part, any parameters mentioned fixed-width/monospace/monospaced are checked, but not helped any, and in windows pycharm still can't detect them.

so, at last, i really wonder, which parameter do TTF files or any other font file types use to tell the [windows/osx/mac os/linux] OS that 'i am monospaced'?

答:
A TrueType font can contain a post table. The post table contains a 32-bit field named isFixedPitch. If this contains a 0, it indicates a proportional font. A monospaced font should have this set to 1 (but its normally recommended that a font engine should accept any non-zero value as indicating a monospaced font, since that's what early versions of the TT spec required).

A monospaced font should also have the numberOfHMetrics in the hhea and hmtx tables set to 3.

There's also data in the panose font matching data (in the OS/2 table) to specify whether a font is monospaced or not.

If I had to guess, I'd say Apple is more likely to use the post table, while Microsoft is more likely to use the Panose data (but I could easily be wrong about either or both of those).

References:

Apple documentation of 'post' table

Microsoft OpenType Recommendations

Panose Classification Metrics Guide


问:
destruction es6 default value in react's props
<ComponentB from="3/1/2016" to="12/1/2016" />

and in componentB's constructor I can do

const { from, to } = this.props but my from to value is optional. I can't do

this.state = { from, to } if they are or null. Any way to set default value for destruction?

I can do if(from && to) {} but just curious what's the best way to handle optional props in react.

答:
Consider Using typechecking and  defaultProps to set up the defaults for the props you are expecting see the docs here.
https://facebook.github.io/react/docs/typechecking-with-proptypes.html

In your case you could define.

```<code>//declare default Props expected by app
ComponentB.propTypes =  {
 from: PropTypes.string,
 to: PropTypes.string.isRequired
};

//set our default values
ComponentB.defaultProps = {
 to:"0/0/0"
 from:"0/0/0"
};
</code>```

Consider here I used string and I declared that the to prop is required but the from doesn't have the isRequired flag. NB I used string here but there is numerous other types you can use.

Body:
Consider Using typechecking and  defaultProps to set up the defaults for the props you are expecting see the docs here.
https://facebook.github.io/react/docs/typechecking-with-proptypes.html

In your case you could define.

//declare default Props expected by app
ComponentB.propTypes =  {
 from: PropTypes.string,
 to: PropTypes.string.isRequired
};

//set our default values
ComponentB.defaultProps = {
 to:"0/0/0"
 from:"0/0/0"
};

Consider here I used string and I declared that the to prop is required but the from doesn't have the isRequired flag. NB I used string here but there is numerous other types you can use.


问:
How to run Quarz Cron Job between specific time?
I want to execute cron job between specific time. i.e. Cron job should execute every 15 minutes between 7:03 to 21:04?

I can manage between 7 to 9 but can't schedule between 7:03 to 9:05.

答:
Try with below cron expression</p>

```<code>0 3/15 7-21 * * ?
</code>```

Body:
Try with below cron expression

0 3/15 7-21 * * ?


答:
I know you want the logic in your controller, but you can still leverage your Request file for this. In the Laravel documentation (assuming you are using the latest version) it is described as Adding After Hooks To Form Requests:

If you would like to add an "after" hook to a form request, you may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

```<code>/**
 * Configure the validator instance.
 *
 * @param  \Illuminate\Validation\Validator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}
</code>```

Title: Checking if there is any validation error when using custom form request class

Body:
I know you want the logic in your controller, but you can still leverage your Request file for this. In the Laravel documentation (assuming you are using the latest version) it is described as Adding After Hooks To Form Requests:

If you would like to add an "after" hook to a form request, you may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

/**
 * Configure the validator instance.
 *
 * @param  \Illuminate\Validation\Validator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}


问:
Precisely IP geolocation
Can I get users latitude and longitude with 6 digits after decimal point from his IP (like 52.229676 and 21.012229)? I've already tried some Geo-IP services but it gave me only 4 digits after decimal point.</p>

答:
IP Geolocation doesn't have the 6 decimals accuracy. If you need this precision you have to use some GPS-based solution.

If you need one solution more precise, IP Vigilante has 5 decimals of accuracy. You can take a look at this JSON output example https://ipvigilante.com/8.8.8.8 and in the documentation https://www.ipvigilante.com/api-developer-docs/

Disclosure: I am the developer of IP Vigilante.

Title: Precisely IP geolocation


问:
What are the rules for strict mode changes?
I have several Node JS modules, some use strict mode, others don't.

How does the mode change when calling from a strict-mode module into a non-strict mode module? How does the mode change during such a call?

And vice-versa, what is the logic of changing the mode when calling a method in a strict-mode module from a non-strict mode module?

What are the rules for changing strict mode in general and for NodeJS in particular? How does it work?

答:
Code is parsed, compiled (where relevant), and executed in the mode in which it's written, regardless of what mode it's called from. The only time you can cross a boundary between the two modes is when calling a function, which raises the question, which mode is used to do the work of making that call? (Since strict mode affects several aspects of calling functions.) The answer is: The mode of the function being called. So when a loose function calls a strict one, the strict rules for function calls are used; when a strict function calls a loose one, the loose rules for function calls are used.

When you call a function, strict mode comes into play in several ways:

In strict mode, the call can specify that this be a non-object value; in loose mode, any non-object is coerced to object.

In strict mode, the default this for calls that don't specify it (e.g.: foo()) is undefined instead of the global object as it is in loose mode.

In strict mode, the called function's arguments object has caller and callee properties that throw a TypeError when accessed; in loose mode, the spec defines arguments.callee as a reference to the called function; there's no arguments.caller in the spec, but some implementations provide a reference to the calling function on it.

In fact, in strict mode code, implementation-specific extensions (like caller) to arguments are forbidden, while in loose mode they're allowed.

The arguments object created by the call for use by the called function is complete disassociated from the named parameters of the function in strict mode, instead of being dynamically linked to them as in loose mode.

Here's an example of a loose function calling a strict one and vice-versa, demonstrating that it's the rules of the function called are the ones that are followed:

// Loose calling strict
const strictFunction1 = (function() {
  "use strict";
  return function(a, b) {
    console.log("=== strict function called:");
    console.log("#1 and #2", typeof this); // undefined
    console.log("#2", this === window); // false
    try {
      const x = arguments.callee;
      console.log("#3", "result of trying to access `arguments.callee`: got a " + typeof x);
    } catch (e) {
      console.log("#3", "result of trying to access `arguments.callee`: " + e.message);
    }
    // #5:
    a = 42; // Setting 'a'
    console.log("#5", a === arguments[0]); // false
  };
})();
function looseFunction1() {
  strictFunction1(67);
}
looseFunction1();

// Strict calling loose
const looseFunction2 = (function() {
  return function(a, b) {
    console.log("=== loose function called:");
    console.log("#1 and #2", typeof this); // object
    console.log("#2", this === window); // true
    try {
      const x = arguments.callee;
      console.log("#3", "result of trying to access `arguments.callee`: got a " + typeof x);
    } catch (e) {
      console.log("#3", "result of trying to access `arguments.callee`: " + e.message);
    }
    // #5:
    a = 42; // Setting 'a'
    console.log("#5", a === arguments[0]); // true
  };
})();
function strictFunction2() {
  looseFunction2(67);
}
strictFunction2();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
}</code>```

Body:
Code is parsed, compiled (where relevant), and executed in the mode in which it's written, regardless of what mode it's called from. The only time you can cross a boundary between the two modes is when calling a function, which raises the question, which mode is used to do the work of making that call? (Since strict mode affects several aspects of calling functions.) The answer is: The mode of the function being called. So when a loose function calls a strict one, the strict rules for function calls are used; when a strict function calls a loose one, the loose rules for function calls are used.

When you call a function, strict mode comes into play in several ways:

In strict mode, the call can specify that this be a non-object value; in loose mode, any non-object is coerced to object.

In strict mode, the default this for calls that don't specify it (e.g.: foo()) is undefined instead of the global object as it is in loose mode.

In strict mode, the called function's arguments object has caller and callee properties that throw a TypeError when accessed; in loose mode, the spec defines arguments.callee as a reference to the called function; there's no arguments.caller in the spec, but some implementations provide a reference to the calling function on it.

In fact, in strict mode code, implementation-specific extensions (like caller) to arguments are forbidden, while in loose mode they're allowed.

The arguments object created by the call for use by the called function is complete disassociated from the named parameters of the function in strict mode, instead of being dynamically linked to them as in loose mode.

Here's an example of a loose function calling a strict one and vice-versa, demonstrating that it's the rules of the function called are the ones that are followed:

// Loose calling strict
const strictFunction1 = (function() {
  "use strict";
  return function(a, b) {
    console.log("=== strict function called:");
    console.log("#1 and #2", typeof this); // undefined
    console.log("#2", this === window); // false
    try {
      const x = arguments.callee;
      console.log("#3", "result of trying to access `arguments.callee`: got a " + typeof x);
    } catch (e) {
      console.log("#3", "result of trying to access `arguments.callee`: " + e.message);
    }
    // #5:
    a = 42; // Setting 'a'
    console.log("#5", a === arguments[0]); // false
  };
})();
function looseFunction1() {
  strictFunction1(67);
}
looseFunction1();

// Strict calling loose
const looseFunction2 = (function() {
  return function(a, b) {
    console.log("=== loose function called:");
    console.log("#1 and #2", typeof this); // object
    console.log("#2", this === window); // true
    try {
      const x = arguments.callee;
      console.log("#3", "result of trying to access `arguments.callee`: got a " + typeof x);
    } catch (e) {
      console.log("#3", "result of trying to access `arguments.callee`: " + e.message);
    }
    // #5:
    a = 42; // Setting 'a'
    console.log("#5", a === arguments[0]); // true
  };
})();
function strictFunction2() {
  looseFunction2(67);
}
strictFunction2();

.as-console-wrapper {
  max-height: 100% !important;
}


问:
angular2 ngClass not setting background color for the form
Im trying to set the background color using ngClass but ngClass cannot set the background inside the form.When try out set the background color outside the form it is working fine.

The below code is not working

```<code><div [ngClass]="{bgcolor:true}">
<div class="container">

    <form class="register-form" (ngSubmit)="onsubmit(f)" #f="ngForm" novalidate>
   <div class="row">
       <div class="col-md-4 col-sm-4 col-lg-4">
       <h1>Registration</h1>
       </div>
   </div>
        <div class="row">
            <div class="col-md-4 col-sm-4 col-lg-4">
                <label for="firstName">FIRST NAME</label>
                <input name="firstName" id="firstname" class="form-control" type="text" [(ngModel)]="user.firstname" required pattern="[A-Za-z]+" #firstName="ngModel">
                <div *ngIf="!firstName?.valid && (firstName?.dirty ||firstName?.touched)" class="calert alert-danger">
                    <div [hidden]="!firstName.errors.required">
                        First Name is required
                    </div>
                    <div [hidden]="!firstName.errors.pattern">
                        Only alphabets are allowed
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 col-sm-4 col-lg-4">
                <label for="lastname">LAST NAME</label>
                <input name="lastname" id="lastname" [(ngModel)]="user.lastname" class="form-control" type="text" pattern="[A-Za-z]+" required #lastname="ngModel">
                <div *ngIf="!lastname?.valid && (lastname?.dirty ||lastname?.touched)" class="calert alert-danger">
                    <div [hidden]="!lastname.errors.required">
                        Last Name is required
                    </div>
                    <div [hidden]="!lastname.errors.pattern">
                        Only alphabets are allowed
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 col-sm-4 col-lg-4">
                <label for="email">EMAIL ADDRESS</label>
                <input name="email" id="email" [(ngModel)]="user.email" class="form-control" type="email" #email="ngModel" required pattern="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?">
                <div *ngIf="!email?.valid && (email?.dirty ||email?.touched)" class="calert alert-danger">
                    <div [hidden]="!email.errors.required">
                        Email is required
                    </div>
                    <div [hidden]="!email.errors.pattern">
                        Enter valid email id
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 col-sm-4 col-lg-4">
                <label for="mobile">MOBILE NUMBER</label>
                <input name="mobile" id="mobile" #mobile="ngModel" [(ngModel)]="user.mobile" class="form-control" type="text" required pattern="[789][0-9]{9}">
                <div *ngIf="!mobile?.valid && (mobile?.dirty ||mobile?.touched)" class="calert alert-danger">
                    <div [hidden]="!mobile.errors.required">
                        Mobile number is required
                    </div>
                    <div [hidden]="!mobile.errors.pattern">
                        Enter valid mobile number
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 col-sm-4 col-lg-4">
                <label for="gender">GENDER</label>
                <div class="radio" *ngFor="let g of genders">
                    <label>
                    <input type="radio" name="gender" required class="form-control radioheight" [(ngModel)]="user.gender"  [value]="g" >{{g}}
                    </label>
                    <div *ngIf="!gender?.valid && (gender?.dirty ||gender?.touched)" class="calert alert-danger">
                        <div [hidden]="!gender.errors.required">
                            Gender is required
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 col-sm-4 col-lg-4">
                <label for="password">PASSWORD</label>
                <input name="password" id="password" #password="ngModel" [(ngModel)]="user.password" class="form-control" type="password" required pattern=".{5,10}">
                <div *ngIf="!password?.valid && (password?.dirty ||password?.touched)" class="calert alert-danger">
                    <div [hidden]="!password.errors.required">
                        Password is required
                    </div>
                    <div [hidden]="!password.errors.pattern">
                        Contain 5 to 10 characters
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <input type="hidden" name="role" id="role" [(ngModel)]="user.role" class="form-control">
        </div>
        <hr>
        <div class="row">
            <div class="col-md-6 col-sm-6 col-xs-6 col-lg-6">
                <button type="submit" [disabled]="!f.valid" class="btn btn-default regbutton">Register</button>
            </div>
            <div class="col-md-6 col-sm-6 col-xs-6 col-lg-6">
           <button (click)="onclick()" class="btn btn-default logbutton">Sign in</button>
          </div>
        </div>
    </form>
</div>
</div>
</code>```

But when i try to set outside the form like below it is working

```<code><div [ngClass]="{bgcolor:true}">
<p>test</p>
</div>
</code>```

component.css

```<code>    .bgcolor{
         background-color:#194c4f;
        font-family: 'Open Sans Condensed', sans-serif;
        font-size: 18px;

    }
.register-form{
    font-size: 16px;
   left: 50%;
    top: 50%;
    position: absolute;
    -webkit-transform: translate3d(-50%, -50%, 0);
    -moz-transform: translate3d(-50%, -50%, 0);
    transform: translate3d(-50%, -50%, 0);
}

.regbutton{
    height: 50px;
    width: 100px;
    background-color:tomato;
    border-radius: 0px;
    font-size: 18px;
    color:white;
    border: none !important;
    margin-bottom: 5px;
    margin-left: 110px;
}
.regbutton:hover{
    color: white;
    background-color:#aa422f;
}
.regbutton:active{
    color: white;
    background-color:#aa422f;
}
.logbutton{
    height: 50px;
    width: 100px;
    background-color:yellowgreen;
    border-radius: 0px;
    font-size: 18px;
    color:white;
    border: none !important;
    margin-bottom: 5px;
}
.logbutton:hover{
    color: white;
    background-color:darkolivegreen;
}
.logbutton:active{
    color: white;
    background-color:darkolivegreen;
}

.register-form label,h1{
    color: aliceblue;

}
.register-form input{
    margin-bottom: 5px;
    width: 430px;
    height: 40px;
    border-radius: 0px;
}

.radioheight
{
  height: 15px !important;
  margin-left: 10px;
}
</code>```

I dnt know whats worng help me thanks in advance

答:
First, your div with ngClass didn't have a size property.

Then, the form element has a property of position: absolute;.

Above two reason will make your form been positioned outside the div in some situation.

take a look at this plunker.

Body:
Im trying to set the background color using ngClass but ngClass cannot set the background inside the form.When try out set the background color outside the form it is working fine.

The below code is not working

    <form class="register-form" (ngSubmit)="onsubmit(f)" #f="ngForm" novalidate>

Registration

                FIRST NAME
                <input name="firstName" id="firstname" class="form-control" type="text" [(ngModel)]="user.firstname" required pattern="[A-Za-z]+" #firstName="ngModel">

                        First Name is required

                        Only alphabets are allowed

                LAST NAME
                <input name="lastname" id="lastname" [(ngModel)]="user.lastname" class="form-control" type="text" pattern="[A-Za-z]+" required #lastname="ngModel">

                        Last Name is required

                        Only alphabets are allowed

                EMAIL ADDRESS
                <input name="email" id="email" [(ngModel)]="user.email" class="form-control" type="email" #email="ngModel" required pattern="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?">

                        Email is required

                        Enter valid email id

                MOBILE NUMBER
                <input name="mobile" id="mobile" #mobile="ngModel" [(ngModel)]="user.mobile" class="form-control" type="text" required pattern="[789][0-9]{9}">

                        Mobile number is required

                        Enter valid mobile number

                GENDER

                    <input type="radio" name="gender" required class="form-control radioheight" [(ngModel)]="user.gender"  [value]="g" >{{g}}

                            Gender is required

                PASSWORD
                <input name="password" id="password" #password="ngModel" [(ngModel)]="user.password" class="form-control" type="password" required pattern=".{5,10}">

                        Password is required

                        Contain 5 to 10 characters

            <input type="hidden" name="role" id="role" [(ngModel)]="user.role" class="form-control">

                <button type="submit" [disabled]="!f.valid" class="btn btn-default regbutton">Register</button>

           <button (click)="onclick()" class="btn btn-default logbutton">Sign in</button>

    </form>

But when i try to set outside the form like below it is working

test

component.css

    .bgcolor{
         background-color:#194c4f;
        font-family: 'Open Sans Condensed', sans-serif;
        font-size: 18px;

    }
.register-form{
    font-size: 16px;
   left: 50%;
    top: 50%;
    position: absolute;
    -webkit-transform: translate3d(-50%, -50%, 0);
    -moz-transform: translate3d(-50%, -50%, 0);
    transform: translate3d(-50%, -50%, 0);
}

.regbutton{
    height: 50px;
    width: 100px;
    background-color:tomato;
    border-radius: 0px;
    font-size: 18px;
    color:white;
    border: none !important;
    margin-bottom: 5px;
    margin-left: 110px;
}
.regbutton:hover{
    color: white;
    background-color:#aa422f;
}
.regbutton:active{
    color: white;
    background-color:#aa422f;
}
.logbutton{
    height: 50px;
    width: 100px;
    background-color:yellowgreen;
    border-radius: 0px;
    font-size: 18px;
    color:white;
    border: none !important;
    margin-bottom: 5px;
}
.logbutton:hover{
    color: white;
    background-color:darkolivegreen;
}
.logbutton:active{
    color: white;
    background-color:darkolivegreen;
}

.register-form label,h1{
    color: aliceblue;

}
.register-form input{
    margin-bottom: 5px;
    width: 430px;
    height: 40px;
    border-radius: 0px;
}

.radioheight
{
  height: 15px !important;
  margin-left: 10px;
}

I dnt know whats worng help me thanks in advance


问:
MYSQL where x in all
I am running a query like this

```<code>SELECT .......  WHERE column_name IN (1,2,3)
</code>```

How can I use the same query and say

```<code>SELECT ........WHERE column_name IN (*)
</code>```

and select all rows?

Edit: The reason I need to do this is because of a bad database design and bad coding in general, for now I need to hack it. If I don't pass the query 1,2,3 .. I need to pass it something so it will return me all records. Is there a way to do it without changing the query? If you don't think this is possible then you should say that it is not possible in your answer.

答: Just remove the WHERE clause alltogether.

Title: MYSQL where x in all

Body:
I am running a query like this

SELECT .......  WHERE column_name IN (1,2,3)

How can I use the same query and say

SELECT ........WHERE column_name IN (*)

and select all rows?

Edit: The reason I need to do this is because of a bad database design and bad coding in general, for now I need to hack it. If I don't pass the query 1,2,3 .. I need to pass it something so it will return me all records. Is there a way to do it without changing the query? If you don't think this is possible then you should say that it is not possible in your answer.


问:
Exception in thread "main" 0: No such file or directory: hadoop map reduce
I am trying to run the basic word count job using map reduce. The source code is available on official website.

```<code>import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.log4j.BasicConfigurator;

public class TestDriver {

  public static class TokenizerMapper
       extends Mapper<Object, Text, Text, IntWritable>{

    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }

  public static class IntSumReducer
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<IntWritable> values,
                       Context context
                       ) throws IOException, InterruptedException {
      int sum = 0;
      for (IntWritable val : values) {
        sum += val.get();
      }
      result.set(sum);
      context.write(key, result);
    }
  }

  public static void main(String[] args) throws Exception {
      BasicConfigurator.configure();
    Configuration conf = new Configuration();
    Job job = Job.getInstance(conf, "word count");
    job.setJarByClass(TestDriver.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
}
</code>```

my console output is:

```<code>log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@73d16e93.
log4j: Trying to find [log4j.xml] using sun.misc.Launcher$AppClassLoader@73d16e93 class loader.
log4j: Trying to find [log4j.xml] using ClassLoader.getSystemResource().
log4j: Trying to find [log4j.properties] using context classloader sun.misc.Launcher$AppClassLoader@73d16e93.
log4j: Trying to find [log4j.properties] using sun.misc.Launcher$AppClassLoader@73d16e93 class loader.
log4j: Trying to find [log4j.properties] using ClassLoader.getSystemResource().
log4j: Could not find resource: [null].
1 [main] DEBUG org.apache.hadoop.metrics2.lib.MutableMetricsFactory  - field org.apache.hadoop.metrics2.lib.MutableRate org.apache.hadoop.security.UserGroupInformation$UgiMetrics.loginSuccess with annotation @org.apache.hadoop.metrics2.annotation.Metric(always=false, sampleName=Ops, about=, type=DEFAULT, value=[Rate of successful kerberos logins and latency (milliseconds)], valueName=Time)
39 [main] DEBUG org.apache.hadoop.metrics2.lib.MutableMetricsFactory  - field org.apache.hadoop.metrics2.lib.MutableRate org.apache.hadoop.security.UserGroupInformation$UgiMetrics.loginFailure with annotation @org.apache.hadoop.metrics2.annotation.Metric(always=false, sampleName=Ops, about=, type=DEFAULT, value=[Rate of failed kerberos logins and latency (milliseconds)], valueName=Time)
40 [main] DEBUG org.apache.hadoop.metrics2.lib.MutableMetricsFactory  - field org.apache.hadoop.metrics2.lib.MutableRate org.apache.hadoop.security.UserGroupInformation$UgiMetrics.getGroups with annotation @org.apache.hadoop.metrics2.annotation.Metric(always=false, sampleName=Ops, about=, type=DEFAULT, value=[GetGroups], valueName=Time)
46 [main] DEBUG org.apache.hadoop.metrics2.impl.MetricsSystemImpl  - UgiMetrics, User and group related metrics
416 [main] DEBUG org.apache.hadoop.security.authentication.util.KerberosName  - Kerberos krb5 configuration not found, setting default realm to empty
429 [main] DEBUG org.apache.hadoop.security.Groups  -  Creating new Groups object
439 [main] DEBUG org.apache.hadoop.util.NativeCodeLoader  - Trying to load the custom-built native-hadoop library...
449 [main] DEBUG org.apache.hadoop.util.NativeCodeLoader  - Loaded the native-hadoop library
451 [main] DEBUG org.apache.hadoop.security.JniBasedUnixGroupsMapping  - Using JniBasedUnixGroupsMapping for Group resolution
451 [main] DEBUG org.apache.hadoop.security.JniBasedUnixGroupsMappingWithFallback  - Group mapping impl=org.apache.hadoop.security.JniBasedUnixGroupsMapping
545 [main] DEBUG org.apache.hadoop.security.Groups  - Group mapping impl=org.apache.hadoop.security.JniBasedUnixGroupsMappingWithFallback; cacheTimeout=300000; warningDeltaMs=5000
558 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - hadoop login
560 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - hadoop login commit
577 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - using local user:NTUserPrincipal: Arunaabh
577 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - Using user: "NTUserPrincipal: Arunaabh" with name Arunaabh
578 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - User entry: "Arunaabh"
579 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - UGI loginUser:Arunaabh (auth:SIMPLE)
862 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - PrivilegedAction as:Arunaabh (auth:SIMPLE) from:org.apache.hadoop.mapreduce.Job.connect(Job.java:1255)
878 [main] DEBUG org.apache.hadoop.mapreduce.Cluster  - Trying ClientProtocolProvider : org.apache.hadoop.mapred.YarnClientProtocolProvider
879 [main] DEBUG org.apache.hadoop.mapreduce.Cluster  - Cannot pick org.apache.hadoop.mapred.YarnClientProtocolProvider as the ClientProtocolProvider - returned null protocol
884 [main] DEBUG org.apache.hadoop.mapreduce.Cluster  - Trying ClientProtocolProvider : org.apache.hadoop.mapred.LocalClientProtocolProvider
913 [main] INFO org.apache.hadoop.conf.Configuration.deprecation  - session.id is deprecated. Instead, use dfs.metrics.session-id
916 [main] INFO org.apache.hadoop.metrics.jvm.JvmMetrics  - Initializing JVM Metrics with processName=JobTracker, sessionId=
1000 [main] DEBUG org.apache.hadoop.mapreduce.Cluster  - Picked org.apache.hadoop.mapred.LocalClientProtocolProvider as the ClientProtocolProvider
1002 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - PrivilegedAction as:Arunaabh (auth:SIMPLE) from:org.apache.hadoop.mapreduce.Cluster.getFileSystem(Cluster.java:162)
1014 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - PrivilegedAction as:Arunaabh (auth:SIMPLE) from:org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
1044 [main] DEBUG org.apache.hadoop.mapreduce.JobSubmitter  - Configuring job job_local545640952_0001 with file:/tmp/hadoop-Arunaabh/mapred/staging/Arunaabh545640952/.staging/job_local545640952_0001 as the submit dir
1044 [main] DEBUG org.apache.hadoop.mapreduce.JobSubmitter  - adding the following namenodes' delegation tokens:[file:///]
2292 [main] WARN org.apache.hadoop.mapreduce.JobResourceUploader  - Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
2293 [main] DEBUG org.apache.hadoop.mapreduce.JobResourceUploader  - default FileSystem: file:///
2392 [main] DEBUG org.apache.hadoop.io.nativeio.NativeIO  - Initialized cache for IDs to User/Group mapping with a  cache timeout of 14400 seconds.
2400 [main] INFO org.apache.hadoop.mapreduce.JobSubmitter  - Cleaning up the staging area file:/tmp/hadoop-Arunaabh/mapred/staging/Arunaabh545640952/.staging/job_local545640952_0001
2401 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - PrivilegedActionException as:Arunaabh (auth:SIMPLE) cause:0: No such file or directory
Exception in thread "main" 0: No such file or directory
    at org.apache.hadoop.io.nativeio.NativeIO$POSIX.chmod(NativeIO.java:236)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:724)
    at org.apache.hadoop.fs.FilterFileSystem.setPermission(FilterFileSystem.java:502)
    at org.apache.hadoop.fs.FileSystem.mkdirs(FileSystem.java:600)
    at org.apache.hadoop.mapreduce.JobResourceUploader.uploadFiles(JobResourceUploader.java:94)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:95)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:190)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1290)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1287)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Unknown Source)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1308)
    at TestDriver.main(TestDriver.java:62)
</code>```

My configurations for single node cluster is from official website:
    https://wiki.apache.org/hadoop/Hadoop2OnWindows

I have passed the following as arguments:

```<code>C:\Users\Arunaabh\workspace\TestHadoop\hadooptest.txt
C:\Users\Arunaabh\workspace\TestHadoop\output
</code>```

The error does not seem to be a java input or io exception. Additionally my yarn and namenode and datanodes are working properly.

I am running hadoop on WINDOWS please do not post linux answers.

答:
you have passed local file system's input and output file as parameter to mapreduced job

```<code>C:\Users\Arunaabh\workspace\TestHadoop\hadooptest.txt
C:\Users\Arunaabh\workspace\TestHadoop\output
</code>```

You need to provide input and output file parameter from hdfs file system

Body:
I am trying to run the basic word count job using map reduce. The source code is available on official website.

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.log4j.BasicConfigurator;

public class TestDriver {

  public static class TokenizerMapper
       extends Mapper<Object, Text, Text, IntWritable>{

    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }

  public static class IntSumReducer
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<IntWritable> values,
                       Context context
                       ) throws IOException, InterruptedException {
      int sum = 0;
      for (IntWritable val : values) {
        sum += val.get();
      }
      result.set(sum);
      context.write(key, result);
    }
  }

  public static void main(String[] args) throws Exception {
      BasicConfigurator.configure();
    Configuration conf = new Configuration();
    Job job = Job.getInstance(conf, "word count");
    job.setJarByClass(TestDriver.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
}

my console output is:

log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@73d16e93.
log4j: Trying to find [log4j.xml] using sun.misc.Launcher$AppClassLoader@73d16e93 class loader.
log4j: Trying to find [log4j.xml] using ClassLoader.getSystemResource().
log4j: Trying to find [log4j.properties] using context classloader sun.misc.Launcher$AppClassLoader@73d16e93.
log4j: Trying to find [log4j.properties] using sun.misc.Launcher$AppClassLoader@73d16e93 class loader.
log4j: Trying to find [log4j.properties] using ClassLoader.getSystemResource().
log4j: Could not find resource: [null].
1 [main] DEBUG org.apache.hadoop.metrics2.lib.MutableMetricsFactory  - field org.apache.hadoop.metrics2.lib.MutableRate org.apache.hadoop.security.UserGroupInformation$UgiMetrics.loginSuccess with annotation @org.apache.hadoop.metrics2.annotation.Metric(always=false, sampleName=Ops, about=, type=DEFAULT, value=[Rate of successful kerberos logins and latency (milliseconds)], valueName=Time)
39 [main] DEBUG org.apache.hadoop.metrics2.lib.MutableMetricsFactory  - field org.apache.hadoop.metrics2.lib.MutableRate org.apache.hadoop.security.UserGroupInformation$UgiMetrics.loginFailure with annotation @org.apache.hadoop.metrics2.annotation.Metric(always=false, sampleName=Ops, about=, type=DEFAULT, value=[Rate of failed kerberos logins and latency (milliseconds)], valueName=Time)
40 [main] DEBUG org.apache.hadoop.metrics2.lib.MutableMetricsFactory  - field org.apache.hadoop.metrics2.lib.MutableRate org.apache.hadoop.security.UserGroupInformation$UgiMetrics.getGroups with annotation @org.apache.hadoop.metrics2.annotation.Metric(always=false, sampleName=Ops, about=, type=DEFAULT, value=[GetGroups], valueName=Time)
46 [main] DEBUG org.apache.hadoop.metrics2.impl.MetricsSystemImpl  - UgiMetrics, User and group related metrics
416 [main] DEBUG org.apache.hadoop.security.authentication.util.KerberosName  - Kerberos krb5 configuration not found, setting default realm to empty
429 [main] DEBUG org.apache.hadoop.security.Groups  -  Creating new Groups object
439 [main] DEBUG org.apache.hadoop.util.NativeCodeLoader  - Trying to load the custom-built native-hadoop library...
449 [main] DEBUG org.apache.hadoop.util.NativeCodeLoader  - Loaded the native-hadoop library
451 [main] DEBUG org.apache.hadoop.security.JniBasedUnixGroupsMapping  - Using JniBasedUnixGroupsMapping for Group resolution
451 [main] DEBUG org.apache.hadoop.security.JniBasedUnixGroupsMappingWithFallback  - Group mapping impl=org.apache.hadoop.security.JniBasedUnixGroupsMapping
545 [main] DEBUG org.apache.hadoop.security.Groups  - Group mapping impl=org.apache.hadoop.security.JniBasedUnixGroupsMappingWithFallback; cacheTimeout=300000; warningDeltaMs=5000
558 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - hadoop login
560 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - hadoop login commit
577 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - using local user:NTUserPrincipal: Arunaabh
577 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - Using user: "NTUserPrincipal: Arunaabh" with name Arunaabh
578 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - User entry: "Arunaabh"
579 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - UGI loginUser:Arunaabh (auth:SIMPLE)
862 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - PrivilegedAction as:Arunaabh (auth:SIMPLE) from:org.apache.hadoop.mapreduce.Job.connect(Job.java:1255)
878 [main] DEBUG org.apache.hadoop.mapreduce.Cluster  - Trying ClientProtocolProvider : org.apache.hadoop.mapred.YarnClientProtocolProvider
879 [main] DEBUG org.apache.hadoop.mapreduce.Cluster  - Cannot pick org.apache.hadoop.mapred.YarnClientProtocolProvider as the ClientProtocolProvider - returned null protocol
884 [main] DEBUG org.apache.hadoop.mapreduce.Cluster  - Trying ClientProtocolProvider : org.apache.hadoop.mapred.LocalClientProtocolProvider
913 [main] INFO org.apache.hadoop.conf.Configuration.deprecation  - session.id is deprecated. Instead, use dfs.metrics.session-id
916 [main] INFO org.apache.hadoop.metrics.jvm.JvmMetrics  - Initializing JVM Metrics with processName=JobTracker, sessionId=
1000 [main] DEBUG org.apache.hadoop.mapreduce.Cluster  - Picked org.apache.hadoop.mapred.LocalClientProtocolProvider as the ClientProtocolProvider
1002 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - PrivilegedAction as:Arunaabh (auth:SIMPLE) from:org.apache.hadoop.mapreduce.Cluster.getFileSystem(Cluster.java:162)
1014 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - PrivilegedAction as:Arunaabh (auth:SIMPLE) from:org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
1044 [main] DEBUG org.apache.hadoop.mapreduce.JobSubmitter  - Configuring job job_local545640952_0001 with file:/tmp/hadoop-Arunaabh/mapred/staging/Arunaabh545640952/.staging/job_local545640952_0001 as the submit dir
1044 [main] DEBUG org.apache.hadoop.mapreduce.JobSubmitter  - adding the following namenodes' delegation tokens:[file:///]
2292 [main] WARN org.apache.hadoop.mapreduce.JobResourceUploader  - Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
2293 [main] DEBUG org.apache.hadoop.mapreduce.JobResourceUploader  - default FileSystem: file:///
2392 [main] DEBUG org.apache.hadoop.io.nativeio.NativeIO  - Initialized cache for IDs to User/Group mapping with a  cache timeout of 14400 seconds.
2400 [main] INFO org.apache.hadoop.mapreduce.JobSubmitter  - Cleaning up the staging area file:/tmp/hadoop-Arunaabh/mapred/staging/Arunaabh545640952/.staging/job_local545640952_0001
2401 [main] DEBUG org.apache.hadoop.security.UserGroupInformation  - PrivilegedActionException as:Arunaabh (auth:SIMPLE) cause:0: No such file or directory
Exception in thread "main" 0: No such file or directory
    at org.apache.hadoop.io.nativeio.NativeIO$POSIX.chmod(NativeIO.java:236)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:724)
    at org.apache.hadoop.fs.FilterFileSystem.setPermission(FilterFileSystem.java:502)
    at org.apache.hadoop.fs.FileSystem.mkdirs(FileSystem.java:600)
    at org.apache.hadoop.mapreduce.JobResourceUploader.uploadFiles(JobResourceUploader.java:94)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:95)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:190)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1290)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1287)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Unknown Source)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1308)
    at TestDriver.main(TestDriver.java:62)

My configurations for single node cluster is from official website:
    https://wiki.apache.org/hadoop/Hadoop2OnWindows

I have passed the following as arguments:

C:\Users\Arunaabh\workspace\TestHadoop\hadooptest.txt
C:\Users\Arunaabh\workspace\TestHadoop\output

The error does not seem to be a java input or io exception. Additionally my yarn and namenode and datanodes are working properly.

I am running hadoop on WINDOWS please do not post linux answers.

Body:
you have passed local file system's input and output file as parameter to mapreduced job

C:\Users\Arunaabh\workspace\TestHadoop\hadooptest.txt
C:\Users\Arunaabh\workspace\TestHadoop\output

You need to provide input and output file parameter from hdfs file system


问:
Iterating values of multiple rows in table in array
I have written a code to fetch the details of the values selected by the user. The code works fine and shows the array. The only problem is that is displays error   for childnodes. Where am I doing it wrong? </p>

```<code>function add_checkout_details(){
           var total = $("#total").val();
           var product_id = new Array();
           var qty = new Array();
           var price = new Array();
           var amount = new Array();

           var table = document.getElementById('myTable');
           var rowCount = table.rows.length;
         for(var i=0; i<rowCount; i++) {

                    var row = table.rows[i];
                    var txtBox0 = row.cells[0].innerHTML;
                    var txtBox1 = row.cells[2].childNodes[0].value;
                    var txtBox2 = row.cells[3].childNodes[0].value;
                    var txtBox3 = row.cells[4].childNodes[0].value;
                    var txtBox4 = row.cells[8].childNodes[0].value;

                     product_id.push(txtBox0);
                     qty.push(txtBox1);
                     price.push(txtBox2);
                     amount.push(txtBox3);
                    }

    $.post('controller/add_checkout_details.php',{'product_id[]':product_id,'qty[]':qty,'price[]':price,'amount[]':amount,total:total}, function(data){

        $('#error').text(data);
    });
    }
</code>```

答:
Nodes do not have a value property. Instead use nodeValue.

```<code>row.cells[2].childNodes[0].nodeValue;
</code>```

Note that you can write this as:

```<code>row.cells[2].firstChild.nodeValue;
</code>```

See also textContent and innerText, which have slightly different behaviour.

Body:
I have written a code to fetch the details of the values selected by the user. The code works fine and shows the array. The only problem is that is displays error   for childnodes. Where am I doing it wrong?

function add_checkout_details(){
           var total = $("#total").val();
           var product_id = new Array();
           var qty = new Array();
           var price = new Array();
           var amount = new Array();

           var table = document.getElementById('myTable');
           var rowCount = table.rows.length;
         for(var i=0; i<rowCount; i++) {

                    var row = table.rows[i];
                    var txtBox0 = row.cells[0].innerHTML;
                    var txtBox1 = row.cells[2].childNodes[0].value;
                    var txtBox2 = row.cells[3].childNodes[0].value;
                    var txtBox3 = row.cells[4].childNodes[0].value;
                    var txtBox4 = row.cells[8].childNodes[0].value;

                     product_id.push(txtBox0);
                     qty.push(txtBox1);
                     price.push(txtBox2);
                     amount.push(txtBox3);
                    }

    $.post('controller/add_checkout_details.php',{'product_id[]':product_id,'qty[]':qty,'price[]':price,'amount[]':amount,total:total}, function(data){

        $('#error').text(data);
    });
    }

Body:
Nodes do not have a value property. Instead use nodeValue.

row.cells[2].childNodes[0].nodeValue;

Note that you can write this as:

row.cells[2].firstChild.nodeValue;

See also textContent and innerText, which have slightly different behaviour.


问:
Focus on new row in a grid in automatic mode
I have a problem when I'm inserting a new row in a grid. The focus is always in up into left of the grid.
The problem is that when I insert more rows... the page returns in up and this is a inconvenient for the user .
My idea is set a focus for every new insert row ... the best mode ... would be to do a tab focus in specific cell of the new row(a field mandatory  Example Qta).

This my code in javascript:

```<code>   self.fromModel(data, self.CodArticolo, self.addingFromOrdineFornitore);
         if (model.details.indexOf(self) == -1) {
             model.details.splice(model.details.length - 1, 0, self);
</code>```

Infact the function "splice" create a new rows popolate with a details of an article in the grid.... and this set the focus in the first cell in up into left

For try a test, I try to insert this code:

```<code>  var data = $("#Movimenti").data("kendoGrid").dataSource.data();
      for (var i = 0; i < data.length; i++) {
           var dataItem = data[i];
                  if (i == model.details.length - 2) {
$("#Movimenti").data("kendoGrid").tbody.find("tr[data-uid=" + dataItem.uid + "]").effect("highlight", { color: "#f35800" }, 3000);
                                   }
                            }
</code>```

And I can confirm that the find the correct rows and launching the effect that it works... but I don't find the solution for set the focus in the correct rows.

Can you help me?

答:
Hi Add this code that resolved my case:

```<code>//Setto il focus all'interno dell'ultima riga inserita
                        var data = $("#Movimenti").data("kendoGrid").dataSource.data();
                        for (var i = 0; i < data.length; i++) {
                            var dataItem = data[i];
                            if (i == model.details.length - 2) {
                                var grid = $("#Movimenti").data("kendoGrid");
                                //var firstCell = grid.tbody.find("tr[data-uid=" + dataItem.uid + "] td:first");
                                var cellName = "Qta";
                                var cellIndex_1 = grid.element.find("th[data-field = '" + cellName + "']").index();
                                var focusCell = grid.tbody.find("tr[data-uid=" + dataItem.uid + "] td:eq(" + cellIndex_1 + ")");

                                grid.current(focusCell);
                                focusCell.focus();
                                focusCell.trigger("click");
</code>```

In this mode, I set a Focus and/or edit the specific cell ("Qta").
For me this case can to be closed

Best regards

Body:
I have a problem when I'm inserting a new row in a grid. The focus is always in up into left of the grid.
The problem is that when I insert more rows... the page returns in up and this is a inconvenient for the user .
My idea is set a focus for every new insert row ... the best mode ... would be to do a tab focus in specific cell of the new row(a field mandatory  Example Qta).

This my code in javascript:

   self.fromModel(data, self.CodArticolo, self.addingFromOrdineFornitore);
         if (model.details.indexOf(self) == -1) {
             model.details.splice(model.details.length - 1, 0, self);

Infact the function "splice" create a new rows popolate with a details of an article in the grid.... and this set the focus in the first cell in up into left

For try a test, I try to insert this code:

  var data = $("#Movimenti").data("kendoGrid").dataSource.data();
      for (var i = 0; i < data.length; i++) {
           var dataItem = data[i];
                  if (i == model.details.length - 2) {
$("#Movimenti").data("kendoGrid").tbody.find("tr[data-uid=" + dataItem.uid + "]").effect("highlight", { color: "#f35800" }, 3000);
                                   }
                            }

And I can confirm that the find the correct rows and launching the effect that it works... but I don't find the solution for set the focus in the correct rows.

Can you help me?

Body:
Hi Add this code that resolved my case:

//Setto il focus all'interno dell'ultima riga inserita
                        var data = $("#Movimenti").data("kendoGrid").dataSource.data();
                        for (var i = 0; i < data.length; i++) {
                            var dataItem = data[i];
                            if (i == model.details.length - 2) {
                                var grid = $("#Movimenti").data("kendoGrid");
                                //var firstCell = grid.tbody.find("tr[data-uid=" + dataItem.uid + "] td:first");
                                var cellName = "Qta";
                                var cellIndex_1 = grid.element.find("th[data-field = '" + cellName + "']").index();
                                var focusCell = grid.tbody.find("tr[data-uid=" + dataItem.uid + "] td:eq(" + cellIndex_1 + ")");

                                grid.current(focusCell);
                                focusCell.focus();
                                focusCell.trigger("click");

In this mode, I set a Focus and/or edit the specific cell ("Qta").
For me this case can to be closed

Best regards


问:
SignalR connection after disconnect
Dears, I need the SingalR to reconnect again after disconnect, is the following code is good, or there is another way:

```<code>Dim Proxy As IHubProxy
Dim Hub As HubConnection

Private Function ConnectToCallCenterHub()

    Try

        Hub = New HubConnection(CallCenterHubAddress)
        Proxy = Hub.CreateHubProxy("CallCenterHub")

        AddHandler Hub.StateChanged, (AddressOf HubConnectionState)

        Hub.Start()

        Catch ex As Exception
    End Try

End Function

Private Sub HubConnectionState(ByVal State As Microsoft.AspNet.SignalR.Client.StateChange)

    Try

        Invoke(New OnConnectionSateChangedDelegate(AddressOf OnConnectionSateChanged), State.NewState)

    Catch ex As Exception
    End Try

End Sub

Public Delegate Function OnConnectionSateChangedDelegate(ByVal State As Microsoft.AspNet.SignalR.Client.ConnectionState)
Public Function OnConnectionSateChanged(ByVal State As Microsoft.AspNet.SignalR.Client.ConnectionState)

    Try
        If State = Microsoft.AspNet.SignalR.Client.ConnectionState.Connected Then
            sbConnectionStatus.Text = "Connected"
            pbConnecting.Visible = False
        End If
        If State = Microsoft.AspNet.SignalR.Client.ConnectionState.Connecting Then
            sbConnectionStatus.Text = "Connecting"
        End If
        If State = Microsoft.AspNet.SignalR.Client.ConnectionState.Reconnecting Then
            sbConnectionStatus.Text = "Reconnecting"
        End If
        If State = Microsoft.AspNet.SignalR.Client.ConnectionState.Disconnected Then
            sbConnectionStatus.Text = "Disconnected"
            ConnectToCallCenterHub()
        End If

    Catch ex As Exception
    End Try

End Function
</code>```

The function ConnectToCallCenterHub is called to connec to the hub, and in case of disconnect I call it again.

答:
I haven't worked in vb.net but according to my knowledge of signalR, to disconnect you'll need to override the disconnect method derived from HubBase.

Here's the code

```<code>public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
    {
        if(stopCalled==true)
        {
           //your code here
        }
        else
        {
           //your code here
        }
        return base.OnDisconnected(stopCalled);
    }
</code>```

Hope it's useful to you.

Title: SignalR connection after disconnect

Body:
Dears, I need the SingalR to reconnect again after disconnect, is the following code is good, or there is another way:

Dim Proxy As IHubProxy
Dim Hub As HubConnection

Private Function ConnectToCallCenterHub()

    Try

        Hub = New HubConnection(CallCenterHubAddress)
        Proxy = Hub.CreateHubProxy("CallCenterHub")

        AddHandler Hub.StateChanged, (AddressOf HubConnectionState)

        Hub.Start()

        Catch ex As Exception
    End Try

End Function

Private Sub HubConnectionState(ByVal State As Microsoft.AspNet.SignalR.Client.StateChange)

    Try

        Invoke(New OnConnectionSateChangedDelegate(AddressOf OnConnectionSateChanged), State.NewState)

    Catch ex As Exception
    End Try

End Sub

Public Delegate Function OnConnectionSateChangedDelegate(ByVal State As Microsoft.AspNet.SignalR.Client.ConnectionState)
Public Function OnConnectionSateChanged(ByVal State As Microsoft.AspNet.SignalR.Client.ConnectionState)

    Try
        If State = Microsoft.AspNet.SignalR.Client.ConnectionState.Connected Then
            sbConnectionStatus.Text = "Connected"
            pbConnecting.Visible = False
        End If
        If State = Microsoft.AspNet.SignalR.Client.ConnectionState.Connecting Then
            sbConnectionStatus.Text = "Connecting"
        End If
        If State = Microsoft.AspNet.SignalR.Client.ConnectionState.Reconnecting Then
            sbConnectionStatus.Text = "Reconnecting"
        End If
        If State = Microsoft.AspNet.SignalR.Client.ConnectionState.Disconnected Then
            sbConnectionStatus.Text = "Disconnected"
            ConnectToCallCenterHub()
        End If

    Catch ex As Exception
    End Try

End Function

The function ConnectToCallCenterHub is called to connec to the hub, and in case of disconnect I call it again.

Body:
I haven't worked in vb.net but according to my knowledge of signalR, to disconnect you'll need to override the disconnect method derived from HubBase.

Here's the code

public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
    {
        if(stopCalled==true)
        {
           //your code here
        }
        else
        {
           //your code here
        }
        return base.OnDisconnected(stopCalled);
    }

Hope it's useful to you.