问:
Consume Service method in View-Model [WPF-MVVM]
Hi try port my Winform app to WPF with MVVM. I use Caliburn Micro and MEF as IoC. I have service in external dll -> Pokec_Toolki.dll and this services use other external dll such as JSON.NET, HtmlAgilityPack..etc (third party libraries).

My service look like this:

```<code>public interface IPokecConnection
{
    PokecAccount LogOn(string nick, string password);
    bool LogOff(PokecAccount account);
}

[Export(typeof(IPokecConnection))]
public class PokecConnection : IPokecConnection
{
}
</code>```

For my Service I create consumer for class PokecConnection, it is in the same assembly as Service:

```<code>[Export]
public class PokecConnectionConsumer
{
    private readonly IPokecConnection _pokecConn;

    [ImportingConstructor]
    public PokecConnectionConsumer(IPokecConnection pokecConn)
    {
        _pokecConn = pokecConn;
    }

    public PokecAccount MethodWrapperForLogOn(string name, string  password)
    {
        return _pokecConn.LogOn(name, password);
    }

}
</code>```

I have simple view with 2 textbox  and 1 button. I bind event click of button with caliburn convention on view-model.

View:

```<code><Button Micro:Message.Attach="[Event Click]=[Action LogOn(tbNick.Text,tbPassword.Text)]"
        Content="Prihlás ma"
        Width="100"
        Grid.Row="2"
        Height="25" Margin="4,4,4,4" />
</code>```

I need consume service method in my view model.  So in view-model I have this:

```<code>[Export(typeof(IShellViewModel))]
public class ShellViewModel : Screen, IShellViewModel, IDataErrorInfo
{

    private PokecConnectionConsumer _connConsumer;

    protected override void OnInitialize()
    {
        base.OnInitialize();

        var mycatalog = new AssemblyCatalog(System.Reflection.Assembly.LoadFrom("Pokec_Toolkit.dll"));

        var container = new CompositionContainer(mycatalog);
        container.ComposeParts(this);

        _connConsumer = container.GetExportedValue<PokecConnectionConsumer>();
    }

    //this method is bind on event click of button in view
    public void LogOn(string nick, string password)
    {
        //call method LogOn from class PokecConnection in external dll through PokecConnectionConsumer

        var accout = _connConsumer.MethodWrapperForLogOn(nick, password);

        // in this place if account is not null, I need close this view and create new view MainView
        //a send to the MainViewModel constructor as argument variable account

        //some test
        MessageBox.Show(accout.SessionId);
    }

}
</code>```

I have these question:

First, It is good create consumer
for service class in external dll?
In my case PokecConnectionConsumer
**and this class is in  same assembly
as service class PokecConnection?

It is correct way to load external
    assembly in view-model in method
    OnInitialize?

It is correct call service method in
    view-model?

It exist more suitable way how bind
    method from external dll on view
    control ? I need simple load external dll in wpf app with MVVM
and bind service method on controls
in views. What is the best way?

How can I close actual view and create new view, also activate this view. I need send as argument variable from view-model to another vie-model constructor.**

MY SOLUTION:

I create interface assembly and refer this assembly in external service dll and also in wpf app.

In bootstraper I load this assembly with reflection:

```<code>    var catalog =
    new AggregateCatalog(
        AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());

catalog.Catalogs.Add(
    new AssemblyCatalog(string.Format(
        CultureInfo.InvariantCulture, "{0}{1}", System.IO.Directory.GetCurrentDirectory(), @"\Pokec_Toolkit.dll")));

_container = new CompositionContainer(catalog);
</code>```

Than I create conductor class:

```<code>public interface IShellViewModel
{
    void ShowLogOnView();
    void ShowMessengerView();
}

[Export(typeof(IShellViewModel))]
public class ShellViewModel : Conductor<IScreen>, IShellViewModel
{
    public ShellViewModel()
    {
        ShowLogOnView();
    }

    public void ShowLogOnView()
    {
        ActivateItem(IoC.Get<LogOnViewModel>());
    }

    public void ShowMessengerView()
    {
        ActivateItem(IoC.Get<MessengerViewModel>());
    }
}
</code>```

And in view-model I have this:

```<code>  [Export]
    public class LogOnViewModel : Screen, IDataErrorInfo, ILogOnViewModel
    {

        [Import]
        private IShellViewModel _shellViewModel;

        [Import]
        private IPokecConnection _pokecConn;

//this method is bind on event click of button
        public void LogOn(string nick, string password)
        {
            //SHOW NEW WIEW
           _shellViewModel.ShowMessengerView();
        }
    }
</code>```

答:
1) Yes, so that if the external dependency changes, you do not have to recompile your UI. Also it must be outside View/VM logic.

2) Not I am afraid. Create a separate service class for it.

3) Same, Create a separate service class for it and use within VM.

4) Well, you have to load a DLL anyway. So load it in the service class.

Body:
Hi try port my Winform app to WPF with MVVM. I use Caliburn Micro and MEF as IoC. I have service in external dll -> Pokec_Toolki.dll and this services use other external dll such as JSON.NET, HtmlAgilityPack..etc (third party libraries).

My service look like this:

public interface IPokecConnection
{
    PokecAccount LogOn(string nick, string password);
    bool LogOff(PokecAccount account);
}

[Export(typeof(IPokecConnection))]
public class PokecConnection : IPokecConnection
{
}

For my Service I create consumer for class PokecConnection, it is in the same assembly as Service:

[Export]
public class PokecConnectionConsumer
{
    private readonly IPokecConnection _pokecConn;

    [ImportingConstructor]
    public PokecConnectionConsumer(IPokecConnection pokecConn)
    {
        _pokecConn = pokecConn;
    }

    public PokecAccount MethodWrapperForLogOn(string name, string  password)
    {
        return _pokecConn.LogOn(name, password);
    }

}

I have simple view with 2 textbox  and 1 button. I bind event click of button with caliburn convention on view-model.

View:

<Button Micro:Message.Attach="[Event Click]=[Action LogOn(tbNick.Text,tbPassword.Text)]"
        Content="Prihlás ma"
        Width="100"
        Grid.Row="2"
        Height="25" Margin="4,4,4,4" />

I need consume service method in my view model.  So in view-model I have this:

[Export(typeof(IShellViewModel))]
public class ShellViewModel : Screen, IShellViewModel, IDataErrorInfo
{

    private PokecConnectionConsumer _connConsumer;

    protected override void OnInitialize()
    {
        base.OnInitialize();

        var mycatalog = new AssemblyCatalog(System.Reflection.Assembly.LoadFrom("Pokec_Toolkit.dll"));

        var container = new CompositionContainer(mycatalog);
        container.ComposeParts(this);

        _connConsumer = container.GetExportedValue<PokecConnectionConsumer>();
    }

    //this method is bind on event click of button in view
    public void LogOn(string nick, string password)
    {
        //call method LogOn from class PokecConnection in external dll through PokecConnectionConsumer

        var accout = _connConsumer.MethodWrapperForLogOn(nick, password);

        // in this place if account is not null, I need close this view and create new view MainView
        //a send to the MainViewModel constructor as argument variable account

        //some test
        MessageBox.Show(accout.SessionId);
    }

}

I have these question:

First, It is good create consumer
for service class in external dll?
In my case PokecConnectionConsumer
**and this class is in  same assembly
as service class PokecConnection?

It is correct way to load external
    assembly in view-model in method
    OnInitialize?

It is correct call service method in
    view-model?

It exist more suitable way how bind
    method from external dll on view
    control ? I need simple load external dll in wpf app with MVVM
and bind service method on controls
in views. What is the best way?

How can I close actual view and create new view, also activate this view. I need send as argument variable from view-model to another vie-model constructor.**

MY SOLUTION:

I create interface assembly and refer this assembly in external service dll and also in wpf app.

In bootstraper I load this assembly with reflection:

    var catalog =
    new AggregateCatalog(
        AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());

catalog.Catalogs.Add(
    new AssemblyCatalog(string.Format(
        CultureInfo.InvariantCulture, "{0}{1}", System.IO.Directory.GetCurrentDirectory(), @"\Pokec_Toolkit.dll")));

_container = new CompositionContainer(catalog);

Than I create conductor class:

public interface IShellViewModel
{
    void ShowLogOnView();
    void ShowMessengerView();
}

[Export(typeof(IShellViewModel))]
public class ShellViewModel : Conductor<IScreen>, IShellViewModel
{
    public ShellViewModel()
    {
        ShowLogOnView();
    }

    public void ShowLogOnView()
    {
        ActivateItem(IoC.Get<LogOnViewModel>());
    }

    public void ShowMessengerView()
    {
        ActivateItem(IoC.Get<MessengerViewModel>());
    }
}

And in view-model I have this:

  [Export]
    public class LogOnViewModel : Screen, IDataErrorInfo, ILogOnViewModel
    {

        [Import]
        private IShellViewModel _shellViewModel;

        [Import]
        private IPokecConnection _pokecConn;

//this method is bind on event click of button
        public void LogOn(string nick, string password)
        {
            //SHOW NEW WIEW
           _shellViewModel.ShowMessengerView();
        }
    }


来源: stackexchange

问:
Can Kotlin data class have more than one constructor?
I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

```<code>data class User(val name: String, val age: Int)
</code>```

Is it possible to declare a second constructor for that data class?

答:
Updated answer for data classes:

Yes you can, but you will need to delegate everything to the primary constructor

```<code>data class User(val name: String, val age: Int)
{
    constructor(name: String): this(name, -1) {
    }

    constructor(age: Int): this("Anon", age) {
    }
}

// Anon name: Anon
println("Anon name: " + User(30).name)

// No age: -1
println("No age: " + User("Name").age)

// Name: Name age: 20
val u = User("Name", 20)
println("Name: " + u.name + " age: " + u.age)
</code>```

You can also set default values in your primary constructor as Alexey did.

ContentLicense: CC BY-SA 3.0

Body:
I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

data class User(val name: String, val age: Int)

Is it possible to declare a second constructor for that data class?

Body:
Updated answer for data classes:

Yes you can, but you will need to delegate everything to the primary constructor

data class User(val name: String, val age: Int)
{
    constructor(name: String): this(name, -1) {
    }

    constructor(age: Int): this("Anon", age) {
    }
}

// Anon name: Anon
println("Anon name: " + User(30).name)

// No age: -1
println("No age: " + User("Name").age)

// Name: Name age: 20
val u = User("Name", 20)
println("Name: " + u.name + " age: " + u.age)

You can also set default values in your primary constructor as Alexey did.


问:
Pass in multiple cursors as variables to GitHub GraphQL API?
I'm looking up organization members based on a list of organization ids.  Each org has a paged list of members with an endCursor.  Since each endCursor will be different and each org has different numbers of members (and different number of pages), how can I pass in different cursors back as variables?  If so, how would each cursor be associated to the org ID from the previous query?

```<code>query($orgIds:[ID!]!, $page_cursor:String) { // not sure how to pass in the cursor when different length lists are returned
    nodes(ids:$orgIds) {
        ... on Organization {
            id
            members(first: 100, after: $page_cursor) {
            edges {
                node {
                    id
                }
            }
            pageInfo {
                endCursor
                hasNextPage
            }
        }
    }
}
</code>```

I've read http://graphql.org/learn/pagination/ but I'm not seeing anything related to passing in multiple cursors for the same edge list.

答:
I haven't found any details in the graphql specs on how supply an array of cursors for the same edge list. GitHub would have to come up with a custom feature for that. Though I have a feeling it is not quite what you are looking for.

A cursor exist per node, so if you add cursor field to your edges request, you will get the cursors for all nodes within your request.

```<code>edges {
    cursor
    node {
        id
    }
}
</code>```

Response would become something like this:

```<code>"edges": [
    {
      "cursor": "Y3Vyc29yOnYyOpLOAANaVM4AA1pU",
      "node": {
        "id": "MDQ6VXNlcjIxOTczMg=="
      }
    },
</code>```

Please note that endCursor is not the same if you  change the "first:100" parameter to let's say "first:5", because endCursor would be the last cursor of the last node of the 5 first results.

The only reference you will have from your cursor ID to your orginazation ID, would be that the structure of the object being returned from GitHub's graphql API. Any cursor in your example is a child of a specific organisation.

From my point of view, It would be up to your client to remember that reference if needed afterwards. With that in mind, you might want to simply iterate through the pages of a single organisation, before you go to the next. (supplying only 1 organisation pr request, and not an array).

Body:
I'm looking up organization members based on a list of organization ids.  Each org has a paged list of members with an endCursor.  Since each endCursor will be different and each org has different numbers of members (and different number of pages), how can I pass in different cursors back as variables?  If so, how would each cursor be associated to the org ID from the previous query?

query($orgIds:[ID!]!, $page_cursor:String) { // not sure how to pass in the cursor when different length lists are returned
    nodes(ids:$orgIds) {
        ... on Organization {
            id
            members(first: 100, after: $page_cursor) {
            edges {
                node {
                    id
                }
            }
            pageInfo {
                endCursor
                hasNextPage
            }
        }
    }
}

I've read http://graphql.org/learn/pagination/ but I'm not seeing anything related to passing in multiple cursors for the same edge list.

Body:
I haven't found any details in the graphql specs on how supply an array of cursors for the same edge list. GitHub would have to come up with a custom feature for that. Though I have a feeling it is not quite what you are looking for.

A cursor exist per node, so if you add cursor field to your edges request, you will get the cursors for all nodes within your request.

edges {
    cursor
    node {
        id
    }
}

Response would become something like this:

"edges": [
    {
      "cursor": "Y3Vyc29yOnYyOpLOAANaVM4AA1pU",
      "node": {
        "id": "MDQ6VXNlcjIxOTczMg=="
      }
    },

Please note that endCursor is not the same if you  change the "first:100" parameter to let's say "first:5", because endCursor would be the last cursor of the last node of the 5 first results.

The only reference you will have from your cursor ID to your orginazation ID, would be that the structure of the object being returned from GitHub's graphql API. Any cursor in your example is a child of a specific organisation.

From my point of view, It would be up to your client to remember that reference if needed afterwards. With that in mind, you might want to simply iterate through the pages of a single organisation, before you go to the next. (supplying only 1 organisation pr request, and not an array).


问:
how to implement single sign on in .Net?
What is the best solution to implement single sign on in a .net application? I have googled and found few solutions but I am not very convinced with those solutions.

User logs on website1 and then moves to website2. How website2 will know user has logged in? I guess by passing some token in the url which will be checked by website2 in database for validity. That means I need to marshall all the urls in website1 which takes to website2?

Secondly if user continue to browse website2 for say 1 hour and then move to website1. By that time website1 session has timed out so user will see a login page, isn't it? But this behavior is wrong as per single sign on functionality.

答:
Check out this link with using OAuth and Social providers, it offers a multitude of authentication capabilities already cooked into .Net
Microsoft training video on OAuth and single sign on with social providers</p>

ContentLicense: CC BY-SA 2.5


问:
How to associate load balancer with ACL in AWS?
I read this http://docs.aws.amazon.com/waf/latest/developerguide/web-acl.html

I read that ACL can be associated with a cloudfront as well as with load balancer.

I could find the tutorial for cloudfront http://docs.aws.amazon.com/waf/latest/developerguide/tutorials-rate-based-blocking.html

But i am unable to find any tutorial for associating ACL with load balancer. Nor i could find any option on AWS console UI for the same.

Any help.

答: It's exactly the same as the process for CloudFront that you linked. In the WAF console it will list all your CloudFront distributions and load balancers that you can associate the WAF with.</p>


问:
How to find normalisation constant for a pdf in Matlab?
I have a pdf with sample space from [-v,v] where 0 <= v < 1
and the pdf is, with c as normalization constant

```<code>f(v) = c*v^2 for v in [-v,v]
f(v) = 0 otherwise
</code>```

Now is there a way to tell matlab to find my c for a given v?
I know I could integrate it and it should equal one and then find c, but this seems like it should be available somewhere here, but I can't find it

答:
I do not believe that such a function exists, but I could be wrong. However, you can use a numeric integration function in Matlab like:

```<code>I = integrate(function, xmin, xmax);
c = 1/I; % your normalization constant
</code>```

This way you can always integrate your pdf, even more complex ones.

Body:
I have a pdf with sample space from [-v,v] where 0 <= v < 1
and the pdf is, with c as normalization constant

f(v) = c*v^2 for v in [-v,v]
f(v) = 0 otherwise

Now is there a way to tell matlab to find my c for a given v?
I know I could integrate it and it should equal one and then find c, but this seems like it should be available somewhere here, but I can't find it

Body:
I do not believe that such a function exists, but I could be wrong. However, you can use a numeric integration function in Matlab like:

I = integrate(function, xmin, xmax);
c = 1/I; % your normalization constant

This way you can always integrate your pdf, even more complex ones.


问:
ES6 Classes ability to perform polymorphism
I am trying to emulate polymorphism through ES6 Classes, in order to be able to better understand this theory.

Concept is clear (designing objects to share behaviors and to be able to override shared behaviors with specific ones) but I am afraid my code above is not a valid polymorphism example.

Due to my lack of experience, I appreciate if you answer these questions in a comprehensive way:

The fact that both Classes have an equally named method, and that instances made from each Class get access correctly to their respective methods, makes this a polymorphic example?

In case this does not emulate polimorphism, what changes should be
done in the code for it?

I've tried removing the Employee.prototype = new Person(); line, and it still works. This is why I am afraid I'm not getting this concept.

class Person {
  constructor (name, age) {
    this._name = name;
    this._age = age;
  }
}

Person.prototype.showInfo = function(){
  return "Im " + this._name + ", aged " + this._age;
};

class Employee {
  constructor (name, age, sex) {
    this._name = name;
    this._age = age;
    this._sex = sex;
  }
}

Employee.prototype = new Person();

Employee.prototype.showInfo = function(){
  return "Im " + this._sex + ", named " + this._name + ", aged " + this._age;
};

var myPerson = new Person('Jon', 20);
var myEmployee = new Employee('Doe', 10, 'men');

document.write(myPerson.showInfo() + "

");   // Im Jon, aged 20
document.write(myEmployee.showInfo() + "

"); // Im men, named Doe, aged 10```

答:
Every JavaScript object has an internal "prototype" property, often called [[prototype]], which points to the object from which it directly inherits.

Every JavaScript function [object] has a property prototype, which is initialized with an [nearly] empty object. When you create a new instance of this function by calling it as a constructor, the [[prototype]] of that new object will point to the constructor's prototype object.

So, when you write this var myPerson = new Person('Jon', 20);,you have the method showInfo because you have this

```<code>Person.prototype.showInfo = function(){
    return "Im " + this._name + ", aged " + this._age;
};
</code>```

With ES6 if you want to see the polymorphism you could do that :

class Person {
    constructor (name, age) {
        this._name = name;
        this._age = age;
    }

    showInfo () {
        return "Im " + this._name + ", aged " + this._age;
    }
}

class Employee extends Person {
    constructor (name, age, sex) {
        super(name,age);
        this._sex = sex;
    }

    showInfo(){
        return "Im " + this._sex + ", named " + this._name + ", aged " + this._age;
    }
}

var myPerson = new Person('Jon', 20);
var myEmployee = new Employee('Doe', 10, 'men');

document.write(myPerson.showInfo() + "

");   // Im Jon, aged 20
document.write(myEmployee.showInfo() + "

"); // Im men, named Doe, aged 10```

ContentLicense: CC BY-SA 4.0

Body:
Every JavaScript object has an internal "prototype" property, often called [[prototype]], which points to the object from which it directly inherits.

Every JavaScript function [object] has a property prototype, which is initialized with an [nearly] empty object. When you create a new instance of this function by calling it as a constructor, the [[prototype]] of that new object will point to the constructor's prototype object.

So, when you write this var myPerson = new Person('Jon', 20);,you have the method showInfo because you have this

Person.prototype.showInfo = function(){
    return "Im " + this._name + ", aged " + this._age;
};

With ES6 if you want to see the polymorphism you could do that :

class Person {
    constructor (name, age) {
        this._name = name;
        this._age = age;
    }

    showInfo () {
        return "Im " + this._name + ", aged " + this._age;
    }
}

class Employee extends Person {
    constructor (name, age, sex) {
        super(name,age);
        this._sex = sex;
    }

    showInfo(){
        return "Im " + this._sex + ", named " + this._name + ", aged " + this._age;
    }
}

var myPerson = new Person('Jon', 20);
var myEmployee = new Employee('Doe', 10, 'men');

document.write(myPerson.showInfo() + "<br><br>");   // Im Jon, aged 20
document.write(myEmployee.showInfo() + "<br><br>"); // Im men, named Doe, aged 10


问:
Laravel clicking on link adds to url
Okay I have a small problem.

When user clicks on a link it goes to website/create/business which is fine however if nothing is done but the link is clicked again, it goes to website/create/business/create/business for whatever reason.

```<code><li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
        {{ Auth::user()->name }} <span class="caret"></span>
    </a>
    <ul class="dropdown-menu" role="menu">
        <li>
            <a href="profile/{{Auth::user()->id}}">Profile</a>
            <a href="create/business/">Add Business</a>
            <a href="{{ url('/logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                Logout
            </a>
            <form id="logout-form" <a href="{{ url('home') }}" action="{{ url('/logout') }}" method="POST" style="display: none;">
                {{ csrf_field() }}
            </form>
        </li>
    </ul>
</li>
</code>```

Routes:

```<code>Route::get('profile/{user_id}', 'ProfileController@checkid');
Route::post('update', 'ProfileController@updateProfile');
Route::get('create/business', 'BusinessController@addBusiness');
Route::post('create', 'BusinessController@createBusiness');
</code>```

ProfileController:

```<code>public function checkid($user_id) {
    if (Auth::check())
    {
        $user_id = Auth::id();
        return view('profile', [
            'id' => $user_id
        ]);
    }
}
function updateProfile(Request $request) {
    $user = $request->user();
    $twitter = $request->input('twitter');
    $facebook = $request->input('facebook');
    $instagram = $request->input('instagram');
    $telephone = $request->input('telephone');
    $user->twitter_personal = $twitter;
    $user->facebook_personal = $facebook;
    $user->instagram_personal = $instagram;
    $user->telephone = $telephone;
    $result = $user->save();
    if($result) {
        $message = 'success';
    }else{
        $message = 'error';
    }
   return redirect()->back()->withInput()->with('message', $message);
}
</code>```

BusinessController:

```<code>function addBusiness() {
    return view('addBusiness');
}

function createBusiness(Request $request) {
    $name = $request->input('name');
    $type = $request->input('type');
    $email = $request->input('email');
    $user_id = Auth::id();
    $business = new Business();
    $business->name = $name;
    $business->type = $type;
    $business->email = $email;
    $business->user_id = $user_id;
    $business->save();
    $address1 = $request->input('address1');
    $address2 = $request->input('address2');
    $town = $request->input('town');
    $city = $request->input('city');
    $postcode = $request->input('postcode');
    $telephone = $request->input('telephone');
    $address = new Address();
    $address->firstline_address = $address1;
    $address->secondline_address = $address2;
    $address->town = $town;
    $address->city = $city;
    $address->postcode = $postcode;
    $address->telephone = $telephone;
    $address->save();
    $result = $business->save();
    $result2 = $address->save();

    $business_id = $business->id;
    $address_id = $address->id;
    DB::table('business_address')->insert(array('business_id' =>  $business_id, 'address_id' => $address_id));
    DB::table('user_business')->insert(array('user_id' => $user_id, 'business_id' => $business_id));

    if($result && $result2) {
        $message = 'success';
    }else{
        $message = 'error';
    }
    return redirect()->back()->withInput()->with('message', $message);
}
</code>```

答:
href="create/business/"> must be href="/create/business/"> to solve this, because your current link is relative, not absolute, so when you click it again, the same reference is added at the end of your current URL.

Anyway, you should generate links in the Laravel way to avoid other issues in the future:

```<code>Route::get('create/business', 'BusinessController@addBusiness');

<a href="{{ url('create/business') }}">
</code>```

or

```<code>Route::get('create/business', 'BusinessController@addBusiness')->name('createBusiness');

<a href="{{ route('createBusiness') }}">
</code>```

Personally I prefer the second one, so if I change the route URL the links will still work, but it requires to add name('yourRoute') on your route definition.

Title: Laravel clicking on link adds to url

Body:
Okay I have a small problem.

When user clicks on a link it goes to website/create/business which is fine however if nothing is done but the link is clicked again, it goes to website/create/business/create/business for whatever reason.

        {{ Auth::user()->name }}

            id}}">Profile
            Add Business

                Logout

            <form id="logout-form"
                {{ csrf_field() }}
            </form>

Routes:

Route::get('profile/{user_id}', 'ProfileController@checkid');
Route::post('update', 'ProfileController@updateProfile');
Route::get('create/business', 'BusinessController@addBusiness');
Route::post('create', 'BusinessController@createBusiness');

ProfileController:

public function checkid($user_id) {
    if (Auth::check())
    {
        $user_id = Auth::id();
        return view('profile', [
            'id' => $user_id
        ]);
    }
}
function updateProfile(Request $request) {
    $user = $request->user();
    $twitter = $request->input('twitter');
    $facebook = $request->input('facebook');
    $instagram = $request->input('instagram');
    $telephone = $request->input('telephone');
    $user->twitter_personal = $twitter;
    $user->facebook_personal = $facebook;
    $user->instagram_personal = $instagram;
    $user->telephone = $telephone;
    $result = $user->save();
    if($result) {
        $message = 'success';
    }else{
        $message = 'error';
    }
   return redirect()->back()->withInput()->with('message', $message);
}

BusinessController:

function addBusiness() {
    return view('addBusiness');
}

function createBusiness(Request $request) {
    $name = $request->input('name');
    $type = $request->input('type');
    $email = $request->input('email');
    $user_id = Auth::id();
    $business = new Business();
    $business->name = $name;
    $business->type = $type;
    $business->email = $email;
    $business->user_id = $user_id;
    $business->save();
    $address1 = $request->input('address1');
    $address2 = $request->input('address2');
    $town = $request->input('town');
    $city = $request->input('city');
    $postcode = $request->input('postcode');
    $telephone = $request->input('telephone');
    $address = new Address();
    $address->firstline_address = $address1;
    $address->secondline_address = $address2;
    $address->town = $town;
    $address->city = $city;
    $address->postcode = $postcode;
    $address->telephone = $telephone;
    $address->save();
    $result = $business->save();
    $result2 = $address->save();

    $business_id = $business->id;
    $address_id = $address->id;
    DB::table('business_address')->insert(array('business_id' =>  $business_id, 'address_id' => $address_id));
    DB::table('user_business')->insert(array('user_id' => $user_id, 'business_id' => $business_id));

    if($result && $result2) {
        $message = 'success';
    }else{
        $message = 'error';
    }
    return redirect()->back()->withInput()->with('message', $message);
}

Body:
<a href="create/business/"> must be <a href="/create/business/"> to solve this, because your current link is relative, not absolute, so when you click it again, the same reference is added at the end of your current URL.

Anyway, you should generate links in the Laravel way to avoid other issues in the future:

Route::get('create/business', 'BusinessController@addBusiness');

<a href="{{ url('create/business') }}">

or

Route::get('create/business', 'BusinessController@addBusiness')->name('createBusiness');

<a href="{{ route('createBusiness') }}">

Personally I prefer the second one, so if I change the route URL the links will still work, but it requires to add name('yourRoute') on your route definition.


问:
Cannot Read a file from HDFS using Spark
I have installed cloudera CDH 5 by using cloudera manager.

I can easily do

```<code>hadoop fs -ls /input/war-and-peace.txt
hadoop fs -cat /input/war-and-peace.txt
</code>```

this above command will print the whole txt file on the console.

now I start the spark shell and say

```<code>val textFile = sc.textFile("hdfs://input/war-and-peace.txt")
textFile.count
</code>```

Now I get an error

Spark context available as sc.

```<code>scala> val textFile = sc.textFile("hdfs://input/war-and-peace.txt")
2014-12-14 15:14:57,874 INFO  [main] storage.MemoryStore (Logging.scala:logInfo(59)) - ensureFreeSpace(177621) called with curMem=0, maxMem=278302556
2014-12-14 15:14:57,877 INFO  [main] storage.MemoryStore (Logging.scala:logInfo(59)) - Block broadcast_0 stored as values in memory (estimated size 173.5 KB, free 265.2 MB)
textFile: org.apache.spark.rdd.RDD[String] = hdfs://input/war-and-peace.txt MappedRDD[1] at textFile at <console>:12

scala> textFile.count
2014-12-14 15:15:21,791 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 0 time(s); maxRetries=45
2014-12-14 15:15:41,905 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 1 time(s); maxRetries=45
2014-12-14 15:16:01,925 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 2 time(s); maxRetries=45
2014-12-14 15:16:21,983 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 3 time(s); maxRetries=45
2014-12-14 15:16:42,001 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 4 time(s); maxRetries=45
2014-12-14 15:17:02,062 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 5 time(s); maxRetries=45
2014-12-14 15:17:22,082 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 6 time(s); maxRetries=45
2014-12-14 15:17:42,116 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 7 time(s); maxRetries=45
2014-12-14 15:18:02,138 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 8 time(s); maxRetries=45
2014-12-14 15:18:22,298 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 9 time(s); maxRetries=45
2014-12-14 15:18:42,319 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 10 time(s); maxRetries=45
2014-12-14 15:19:02,354 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 11 time(s); maxRetries=45
2014-12-14 15:19:22,373 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 12 time(s); maxRetries=45
2014-12-14 15:19:42,424 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 13 time(s); maxRetries=45
2014-12-14 15:20:02,446 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 14 time(s); maxRetries=45
2014-12-14 15:20:22,512 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 15 time(s); maxRetries=45
2014-12-14 15:20:42,515 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 16 time(s); maxRetries=45
2014-12-14 15:21:02,550 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 17 time(s); maxRetries=45
2014-12-14 15:21:22,558 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 18 time(s); maxRetries=45
2014-12-14 15:21:42,683 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 19 time(s); maxRetries=45
2014-12-14 15:22:02,702 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 20 time(s); maxRetries=45
2014-12-14 15:22:22,832 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 21 time(s); maxRetries=45
2014-12-14 15:22:42,852 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 22 time(s); maxRetries=45
2014-12-14 15:23:02,974 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 23 time(s); maxRetries=45
2014-12-14 15:23:22,995 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 24 time(s); maxRetries=45
2014-12-14 15:23:43,109 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 25 time(s); maxRetries=45
2014-12-14 15:24:03,128 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 26 time(s); maxRetries=45
2014-12-14 15:24:23,250 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 27 time(s); maxRetries=45
java.net.ConnectException: Call From dn1home/192.168.1.21 to input:8020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:783)
        at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:730)
        at org.apache.hadoop.ipc.Client.call(Client.java:1415)
</code>```

Why did I get this error? I am able to read the same file by using hadoop commands?

答:
You are not passing a proper url string.

hdfs://   - protocol type

localhost - ip address(may be different for you eg. - 127.56.78.4)

54310     - port number

/input/war-and-peace.txt - Complete path to the file you want to load.

Finally the URL should be like this

```<code>hdfs://localhost:54310/input/war-and-peace.txt
</code>```

Body:
I have installed cloudera CDH 5 by using cloudera manager.

I can easily do

hadoop fs -ls /input/war-and-peace.txt
hadoop fs -cat /input/war-and-peace.txt

this above command will print the whole txt file on the console.

now I start the spark shell and say

val textFile = sc.textFile("hdfs://input/war-and-peace.txt")
textFile.count

Now I get an error

Spark context available as sc.

scala> val textFile = sc.textFile("hdfs://input/war-and-peace.txt")
2014-12-14 15:14:57,874 INFO  [main] storage.MemoryStore (Logging.scala:logInfo(59)) - ensureFreeSpace(177621) called with curMem=0, maxMem=278302556
2014-12-14 15:14:57,877 INFO  [main] storage.MemoryStore (Logging.scala:logInfo(59)) - Block broadcast_0 stored as values in memory (estimated size 173.5 KB, free 265.2 MB)
textFile: org.apache.spark.rdd.RDD[String] = hdfs://input/war-and-peace.txt MappedRDD[1] at textFile at <console>:12

scala> textFile.count
2014-12-14 15:15:21,791 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 0 time(s); maxRetries=45
2014-12-14 15:15:41,905 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 1 time(s); maxRetries=45
2014-12-14 15:16:01,925 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 2 time(s); maxRetries=45
2014-12-14 15:16:21,983 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 3 time(s); maxRetries=45
2014-12-14 15:16:42,001 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 4 time(s); maxRetries=45
2014-12-14 15:17:02,062 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 5 time(s); maxRetries=45
2014-12-14 15:17:22,082 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 6 time(s); maxRetries=45
2014-12-14 15:17:42,116 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 7 time(s); maxRetries=45
2014-12-14 15:18:02,138 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 8 time(s); maxRetries=45
2014-12-14 15:18:22,298 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 9 time(s); maxRetries=45
2014-12-14 15:18:42,319 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 10 time(s); maxRetries=45
2014-12-14 15:19:02,354 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 11 time(s); maxRetries=45
2014-12-14 15:19:22,373 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 12 time(s); maxRetries=45
2014-12-14 15:19:42,424 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 13 time(s); maxRetries=45
2014-12-14 15:20:02,446 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 14 time(s); maxRetries=45
2014-12-14 15:20:22,512 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 15 time(s); maxRetries=45
2014-12-14 15:20:42,515 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 16 time(s); maxRetries=45
2014-12-14 15:21:02,550 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 17 time(s); maxRetries=45
2014-12-14 15:21:22,558 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 18 time(s); maxRetries=45
2014-12-14 15:21:42,683 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 19 time(s); maxRetries=45
2014-12-14 15:22:02,702 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 20 time(s); maxRetries=45
2014-12-14 15:22:22,832 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 21 time(s); maxRetries=45
2014-12-14 15:22:42,852 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 22 time(s); maxRetries=45
2014-12-14 15:23:02,974 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 23 time(s); maxRetries=45
2014-12-14 15:23:22,995 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 24 time(s); maxRetries=45
2014-12-14 15:23:43,109 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 25 time(s); maxRetries=45
2014-12-14 15:24:03,128 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 26 time(s); maxRetries=45
2014-12-14 15:24:23,250 INFO  [main] ipc.Client (Client.java:handleConnectionTimeout(814)) - Retrying connect to server: input/92.242.140.21:8020. Already tried 27 time(s); maxRetries=45
java.net.ConnectException: Call From dn1home/192.168.1.21 to input:8020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:783)
        at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:730)
        at org.apache.hadoop.ipc.Client.call(Client.java:1415)

Why did I get this error? I am able to read the same file by using hadoop commands?

Body:
You are not passing a proper url string.

hdfs://   - protocol type

localhost - ip address(may be different for you eg. - 127.56.78.4)

54310     - port number

/input/war-and-peace.txt - Complete path to the file you want to load.

Finally the URL should be like this

hdfs://localhost:54310/input/war-and-peace.txt


问:
Why are the input boxes completely overflowing their bounding divs?
I intend to line up 4 input text boxes housed in 4 equal sized columns in one row of the form. Making use of Bootstrap's grid column classes, I assigned  col--3 for medium and large screen sizes to those four input divs.
Likewise for small and extra small sizes, I assigned them col--12  so that the inputs occupy their own whole row. Then my guide wanted those input boxes sizes reduced. I added offset class to the four input and reduced their column span to 6 columns. These were centered appropriately.

However, this change screwed up my small screen layout. Now there are only two inputs in each row, while the other two in the next row.

/* button modification*/

#button-wrapper {
  width: 40%;
  min-width: 200px;
  margin: 0 auto;
}

#ebook-download-button {
  margin: auto 0.5em;
}

.inner {
  margin: 0 auto 0 auto;
  width: 150px;
  padding: 0;
  /* center the block element*/
}

img {
  min-width: 100%;
}

input {
  height: 60%;
  margin: 0px;
}

/* square boxes*/

.square-elem {
  border-radius: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<body>

  <form id="registration-form" class="">
    <!--<div class="col-md-12 col-sm-12">-->
    <div class="row">
      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3 ">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">
        </div>
      </div>

      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">
        </div>
      </div>

      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="company" placeholder="Company">
        </div>
      </div>

      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="email" placeholder="Email">
        </div>
      </div>
    </div>
    <div class="row">
      <div id="button-wrapper" style="">
        <div id="ebook-download-button" class="col-md-12 col-sm-12 col-xs-12 text-center">
           DOWNLOAD EBOOK
        </div>
      </div>
    </div>
    <!-- </div>
  -->
  </form>

</body></code>```

Here's the JSFiddle(Drag the frame) too. It seems the inputs(in each form group div) have completely positioned outside their bounding div box.The intended output should be the four inputs lined side by side in one row.
What can possibly be the issue here?

答:
Is this what you were wanting? You just needed to disable the offset for the larger widths and make the offset smaller for xs widths.

#button-wrapper {
  width: 40%;
  min-width: 200px;
  margin: 0 auto;
}

#ebook-download-button {
  margin: auto 0.5em;
}

.inner {
  margin: 0 auto 0 auto;
  width: 150px;
  padding: 0;
  /* center the block element*/
}

img {
  min-width: 100%;
}

input {
  height: 60%;
  margin: 0px;
}

/* square boxes*/

.square-elem {
  border-radius: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="ebook-registration-box" class="row">
  <div class="col-md-12" >

  <div id="registration-header" class="row">
     <div class="col-md-12">
        <p class="text-center">
           Register to download the device launch guide
        </p>
     </div>
  </div>
   <!-- 4 form elements-->

 <form id="registration-form" class="" >
   <!--<div class="col-md-12 col-sm-12">-->
     <div class="row">
        <div class="col-lg-3 col-md-3 col-md-offset-0 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1 ">
   <div class="form-group">
   <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">
            </div>
        </div>

         <div class="col-lg-3 col-md-3 col-md-offset-0 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
           <div class="form-group">
            <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">
     </div>
         </div>

         <div class="col-lg-3 col-md-3 col-md-offset-0 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
           <div class="form-group">
   <input type="input" class="form-control square-elem" id="company" placeholder="Company">
     </div>
         </div>

        <div class="col-lg-3 col-md-3 col-md-offset-0 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
           <div class="form-group">
      <input type="input" class="form-control square-elem" id="email" placeholder="Email">
           </div>
        </div>
      </div>
      <div class="row">
        <div id="button-wrapper"  style="">
         <div id="ebook-download-button" class="col-md-12 col-sm-12 col-xs-12 text-center">
           DOWNLOAD EBOOK
         </div>
        </div>
      </div>  <!-- </div>-->

  </form>
    </div>
 </div></code>```

Body:
I intend to line up 4 input text boxes housed in 4 equal sized columns in one row of the form. Making use of Bootstrap's grid column classes, I assigned  col--3 for medium and large screen sizes to those four input divs.
Likewise for small and extra small sizes, I assigned them col--12  so that the inputs occupy their own whole row. Then my guide wanted those input boxes sizes reduced. I added offset class to the four input and reduced their column span to 6 columns. These were centered appropriately.

However, this change screwed up my small screen layout. Now there are only two inputs in each row, while the other two in the next row.

/* button modification*/

#button-wrapper {
  width: 40%;
  min-width: 200px;
  margin: 0 auto;
}

#ebook-download-button {
  margin: auto 0.5em;
}

.inner {
  margin: 0 auto 0 auto;
  width: 150px;
  padding: 0;
  /* center the block element*/
}

img {
  min-width: 100%;
}

input {
  height: 60%;
  margin: 0px;
}

/* square boxes*/

.square-elem {
  border-radius: 0px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  <form id="registration-form" class="">

          <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">

          <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">

          <input type="input" class="form-control square-elem" id="company" placeholder="Company">

          <input type="input" class="form-control square-elem" id="email" placeholder="Email">

           DOWNLOAD EBOOK

  </form>

Here's the JSFiddle(Drag the frame) too. It seems the inputs(in each form group div) have completely positioned outside their bounding div box.The intended output should be the four inputs lined side by side in one row.
What can possibly be the issue here?

Body:
Is this what you were wanting? You just needed to disable the offset for the larger widths and make the offset smaller for xs widths.

#button-wrapper {
  width: 40%;
  min-width: 200px;
  margin: 0 auto;
}

#ebook-download-button {
  margin: auto 0.5em;
}

.inner {
  margin: 0 auto 0 auto;
  width: 150px;
  padding: 0;
  /* center the block element*/
}

img {
  min-width: 100%;
}

input {
  height: 60%;
  margin: 0px;
}

/* square boxes*/

.square-elem {
  border-radius: 0px;
}

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="ebook-registration-box" class="row">
  <div class="col-md-12" >

  <div id="registration-header" class="row">
     <div class="col-md-12">
        <p class="text-center">
           Register to download the device launch guide
        </p>
     </div>
  </div>
   <!-- 4 form elements-->

 <form id="registration-form" class="" >
   <!--<div class="col-md-12 col-sm-12">-->
     <div class="row">
        <div class="col-lg-3 col-md-3 col-md-offset-0 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1 ">
   <div class="form-group">
   <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">
            </div>
        </div>

         <div class="col-lg-3 col-md-3 col-md-offset-0 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
           <div class="form-group">
            <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">
     </div>
         </div>

         <div class="col-lg-3 col-md-3 col-md-offset-0 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
           <div class="form-group">
   <input type="input" class="form-control square-elem" id="company" placeholder="Company">
     </div>
         </div>

        <div class="col-lg-3 col-md-3 col-md-offset-0 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
           <div class="form-group">
      <input type="input" class="form-control square-elem" id="email" placeholder="Email">
           </div>
        </div>
      </div>
      <div class="row">
        <div id="button-wrapper"  style="">
         <div id="ebook-download-button" class="col-md-12 col-sm-12 col-xs-12 text-center">
          <a href="#" role="button" class="btn btn-danger btn-download form-control square-elem"  value=""> DOWNLOAD EBOOK </a>
         </div>
        </div>
      </div>  <!-- </div>-->

  </form>
    </div>
 </div>


问:
driver.get on selenium giving error
I have tried running the following command after I've imported everything I need (selenium, webdriver, keys):

```<code>>>> driver.get('https://steemit.com/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'selenium.webdriver.chrome' has no attribute 'get'
</code>```

I can't find any solution.

答:
You are trying to call .get() method on a module. Instead, you need to instantiate a webdriver:

```<code>In [1]: from selenium import webdriver

In [2]: driver = webdriver.Chrome()

In [3]: driver.get('https://steemit.com/')

In [4]: print(driver.title)
Trending posts — Steemit
</code>```

To avoid further selenium module usage confusion, please go through the "Get Started" section of the Python/Selenium documentation.

Title: driver.get on selenium giving error

Body:
I have tried running the following command after I've imported everything I need (selenium, webdriver, keys):

>>> driver.get('https://steemit.com/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'selenium.webdriver.chrome' has no attribute 'get'

I can't find any solution.

Body:
You are trying to call .get() method on a module. Instead, you need to instantiate a webdriver:

In [1]: from selenium import webdriver

In [2]: driver = webdriver.Chrome()

In [3]: driver.get('https://steemit.com/')

In [4]: print(driver.title)
Trending posts — Steemit

To avoid further selenium module usage confusion, please go through the "Get Started" section of the Python/Selenium documentation.


问:
How can I write a piece of Java an code that checks if any character of a string is convertible to an integer between 0 and 9?
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

```<code>String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}
</code>```

where IntegerFormat Exception is something like

```<code>public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}
</code>```

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

```<code>at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)
</code>```

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

答:
You should refer to the documentation for the Integer.parseInt(String s) method.  The full header for this method is public static int valueOf(String s) throws NumberFormatException and the documentation states that the NumberFormatException is thrown when the string does not contain a parsable integer.

To obtain the functionality you described, you should consider that passing a single char into the function will always result in an integer from 0 to 9 (inclusive) if the char is parsable to an int, so, your if statement is probably unecessary.  To make your implementation work, you should catch the NumberFormatException and use that to determine if the char parsed correctly.

Also, to simplify your code, you can also use the s.charAt(i) method rather than s.substring(i, i + 1).  You might also want to look into regex to obtain the behavior you explained.

Body:
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}

where IntegerFormat Exception is something like

public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.


问:
js nest try in catch block
I have a promise that awaits promises (getCookie). if getCookie('key') is rejected I try to get the key from another cookie (scope). I thought of it like this:

```<code>  new Promise((resolve, reject) => {
         var key, scope;
         try {
             key = await getCookie('key');
             resolve(key)
         }
         catch(err){
             try {
                 scope = await getCookie('scope');
                 key = getKeyFromScope(scope);
                 resolve(key)
             } catch(err) {
                 reject(err);
             }
         }
    }
</code>```

However, nesting is only allowed within the try block. Is there a better way to write it with try/catch?

答:
There is a better (simpler) way to write it without try-catch at all. And without the async/await stuff that also revolves around Promises. Only using the Promises themselves.

```<code>var yourPromise = getCookie('key').catch(() => getCookie('scope').then(getKeyFromScope));
</code>```

yourPromise resolves either to the key, or to the error thrown by getCookie('scope')

Title: js nest try in catch block

Body:
I have a promise that awaits promises (getCookie). if getCookie('key') is rejected I try to get the key from another cookie (scope). I thought of it like this:

  new Promise((resolve, reject) => {
         var key, scope;
         try {
             key = await getCookie('key');
             resolve(key)
         }
         catch(err){
             try {
                 scope = await getCookie('scope');
                 key = getKeyFromScope(scope);
                 resolve(key)
             } catch(err) {
                 reject(err);
             }
         }
    }

However, nesting is only allowed within the try block. Is there a better way to write it with try/catch?

Body:
There is a better (simpler) way to write it without try-catch at all. And without the async/await stuff that also revolves around Promises. Only using the Promises themselves.

var yourPromise = getCookie('key').catch(() => getCookie('scope').then(getKeyFromScope));

yourPromise resolves either to the key, or to the error thrown by getCookie('scope')


问:
SQL returning aggregated results from one table as a column in a query
Say I have the following setup

```<code>---Posts---
|id
|Title
-----------

---Comments---
|id
|postid
|comment
-----------
</code>```

Some Mock Data

```<code>Posts
ID        Title
1         Hello World
2         Good Bye
3         Pepsi

Comments
ID      postid      comment
 1        1         comment 1
 2        2         comment 2
 3        2         comment 3
</code>```

I want to return back the Title from the Posts table and all the comments related to it via the id in the comments Table.

Something like.

```<code>Title           Comment
Hello World     comment1
Good Bye        comment2
                comment3
Pepsi           null
</code>```

Is this possible just using SQL?

答:
```<code> Select Title, Comment
 from Posts p LEFT Join Comments c on c.PostId = p.id
 Order by 1
</code>```

However Title will be repeated, i.e. result will be:

```<code> Title           Comment
 ------------------------
 Hello World     comment1
 Good Bye        comment2
 Good Bye        comment3
 Pepsi           null
</code>```

Body:
Say I have the following setup

---Posts---
|id
|Title
-----------

---Comments---
|id
|postid
|comment
-----------

Some Mock Data

Posts
ID        Title
1         Hello World
2         Good Bye
3         Pepsi

Comments
ID      postid      comment
 1        1         comment 1
 2        2         comment 2
 3        2         comment 3

I want to return back the Title from the Posts table and all the comments related to it via the id in the comments Table.

Something like.

Title           Comment
Hello World     comment1
Good Bye        comment2
                comment3
Pepsi           null

Is this possible just using SQL?

Body:
 Select Title, Comment
 from Posts p LEFT Join Comments c on c.PostId = p.id
 Order by 1

However Title will be repeated, i.e. result will be:

 Title           Comment
 ------------------------
 Hello World     comment1
 Good Bye        comment2
 Good Bye        comment3
 Pepsi           null


问:
Remove last numbers in rows in R
This is a fragment of my data.frame:

```<code>MC0_1_N.1   a   c
MC0_1_N.2   d   b
MC0_5_N.1   b   c
MC0_5_N.2   c   d
MC0_5_N.3   a   b
MC0_5_N.4   e   f
MC0_5_N.5   a   h
MC0_5_N.6   k   m
MC0_5_N.7   s   z
MC0_5_N.8   o   p
MC0_5_N.9   p   r
MC0_5_N.10  r   t
</code>```

Is there any way to remove the last numbers of rows (1,2,3,4...) which formed after creating data.frame?

答:
For the given example this would work quite fine:

```<code>df1$col1 <- strtrim(df1$col1,7)
</code>```

Of course this only works when

column variables are strings

there are no items like MC0_10_N.1 in the dataframe (mind the two digit 10 in the middle)

Note, this also removes the . before the number.

Title: Remove last numbers in rows in R

Body:
This is a fragment of my data.frame:

MC0_1_N.1   a   c
MC0_1_N.2   d   b
MC0_5_N.1   b   c
MC0_5_N.2   c   d
MC0_5_N.3   a   b
MC0_5_N.4   e   f
MC0_5_N.5   a   h
MC0_5_N.6   k   m
MC0_5_N.7   s   z
MC0_5_N.8   o   p
MC0_5_N.9   p   r
MC0_5_N.10  r   t

Is there any way to remove the last numbers of rows (1,2,3,4...) which formed after creating data.frame?

Body:
For the given example this would work quite fine:

df1$col1 <- strtrim(df1$col1,7)

Of course this only works when

column variables are strings

there are no items like MC0_10_N.1 in the dataframe (mind the two digit 10 in the middle)

Note, this also removes the . before the number.


问:
How do I replace all occurrences of a string in JavaScript?
Given a string:

```<code>s = "Test abc test test abc test test test abc test test abc";
</code>```

This seems to only remove the first occurrence of abc in the string above:

```<code>s = s.replace('abc', '');
</code>```

How do I replace all occurrences of it?

答:
Using RegExp in JavaScript could do the job for you. Just simply do something like below code, and don't forget the /g after which standout for global:

```<code>var str ="Test abc test test abc test test test abc test test abc";
str = str.replace(/abc/g, '');
</code>```

If you think of reuse, create a function to do that for you, but it's not recommended as it's only one line function. But again, if you heavily use this, you can write something like this:

```<code>String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
  return this.replace(new RegExp(string, 'g'), replaced);
};
</code>```

And simply use it in your code over and over like below:

```<code>var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');
</code>```

But as I mention earlier, it won't make a huge difference in terms of lines to be written or performance. Only caching the function may affect some faster performance on long strings and is also a good practice of DRY code if you want to reuse.

Body:
Given a string:

s = "Test abc test test abc test test test abc test test abc";

This seems to only remove the first occurrence of abc in the string above:

s = s.replace('abc', '');

How do I replace all occurrences of it?

Body:
Using RegExp in JavaScript could do the job for you. Just simply do something like below code, and don't forget the /g after which standout for global:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replace(/abc/g, '');

If you think of reuse, create a function to do that for you, but it's not recommended as it's only one line function. But again, if you heavily use this, you can write something like this:

String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
  return this.replace(new RegExp(string, 'g'), replaced);
};

And simply use it in your code over and over like below:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');

But as I mention earlier, it won't make a huge difference in terms of lines to be written or performance. Only caching the function may affect some faster performance on long strings and is also a good practice of DRY code if you want to reuse.


问:
How to set Authorization Header in ng2-signalr?
I am using library ng2-signalrin ionic 2. Issue is that i don't know how to set authorization header. I have search but didn't find any example.

My code for connecting to server hub.

```<code>   let options: IConnectionOptions = { qs:{userId:1}, url: "http://192.168.0.211:44337"};

        console.log("Stage 1");
            //Header for 'this.singalR.connect'
        this.signalR.connect(options)
            .then((connection) => {

                console.log("Client Id: " + connection.id);
             }, (err) => {
                console.log("SignalR Error: " + JSON.stringify(err));
            });
</code>```

How to set below header ?

```<code>  var headers = new Headers({
            'Content-Type': "application/json",
            "Authorization": 'Bearer ' + accessToken  //accessToken contain bearer value.
        });
</code>```

Library: ng2-signalr

Update 1

Here on link Query String Solution. A workaround is mention to pass authorization token in qs and handle accordingly. But i want to set in header so this solution does not suit me . One more reason as i have one another client(Simple angularjs signalr) which is working fine when i set header just like below.

```<code> $.signalR.ajaxDefaults.headers = { Authorization: //here set header};
</code>```

Note: Before implementing Authorization same code working fine as i don't need to set authorization header.

答:
It is currently (v2.0.4) not implemented in ng2-signalr. <br>
As a workaround,  you can try: </p>

```<code>declare var $: any;
$.signalR.ajaxDefaults.headers = new Headers({
        'Content-Type': "application/json",
        "Authorization": 'Bearer ' + accessToken  //accessToken contain bearer value.
});
</code>```

Body:
I am using library ng2-signalrin ionic 2. Issue is that i don't know how to set authorization header. I have search but didn't find any example.

My code for connecting to server hub.

   let options: IConnectionOptions = { qs:{userId:1}, url: "http://192.168.0.211:44337"};

        console.log("Stage 1");
            //Header for 'this.singalR.connect'
        this.signalR.connect(options)
            .then((connection) => {

                console.log("Client Id: " + connection.id);
             }, (err) => {
                console.log("SignalR Error: " + JSON.stringify(err));
            });

How to set below header ?

  var headers = new Headers({
            'Content-Type': "application/json",
            "Authorization": 'Bearer ' + accessToken  //accessToken contain bearer value.
        });

Library: ng2-signalr

Update 1

Here on link Query String Solution. A workaround is mention to pass authorization token in qs and handle accordingly. But i want to set in header so this solution does not suit me . One more reason as i have one another client(Simple angularjs signalr) which is working fine when i set header just like below.

 $.signalR.ajaxDefaults.headers = { Authorization: //here set header};

Note: Before implementing Authorization same code working fine as i don't need to set authorization header.

Body:
It is currently (v2.0.4) not implemented in ng2-signalr.

As a workaround,  you can try:

declare var $: any;
$.signalR.ajaxDefaults.headers = new Headers({
        'Content-Type': "application/json",
        "Authorization": 'Bearer ' + accessToken  //accessToken contain bearer value.
});


问:
Why does .weekday date component start at 1 in swift?
The .weekday component starts at 1 (sunday = 1, monday = 2 etc...) and I'm interested if anyone knows why. It seems that usually in programming things start at 0.</p>

答:
The reason for zero based indexing in programming dates back to the time when programs were written in machine language or assembly code.  It is a reflexion of the base+displacement capability of memory access from CPU registers.   It was maintained in low level programming languages (such as C) that were essentially a bridge to assembly code. Zero based indexing also provides much simpler index manipulation when processing a one dimensional array (or memory block) as a multidimensional matrix. That being said, it is still just a convention. Some languages (such as Pascal) use one based indexing and normal human beings don't start numbering things at zero.

I don't know the fundamental reason for the numbering of weekdays being based on 1 but I strongly suspect that it is more consistant (and practical) to use with calendars where day numbers within a month, and months with a year are also 1 based. It would be very confusing to manipulate days and months as zero based indexes.  Given this, weekdays should follow the same conventions.


问:
Strip the last hyphen(-) from phone number
Strip the last hyphen(-) from phone number

I want 647-484-3839 to become 647-4843839

```<code>var phoneNumberInput = "647-484-3839";

var newStr = phoneNumberInput .replace(/[^-]+-$/,"");
</code>```

答:
Use positive look-ahead assertion to get - which doesn't follow string contains -.

var phoneNumberInput = "647-484-3839";

var newStr = phoneNumberInput.replace(/-(?=[^-]+$)/, "");

console.log(newStr);```

Where [^-]+ matches any combination which doesn't include hyphen.

Body:
Strip the last hyphen(-) from phone number

I want 647-484-3839 to become 647-4843839

var phoneNumberInput = "647-484-3839";

var newStr = phoneNumberInput .replace(/[^-]+-$/,"");

Body:
Use positive look-ahead assertion to get - which doesn't follow string contains -.

var phoneNumberInput = "647-484-3839";

var newStr = phoneNumberInput.replace(/-(?=[^-]+$)/, "");

console.log(newStr);

Where [^-]+ matches any combination which doesn't include hyphen.


问:
Magento index.php required with SSL for login and checkout pages [HTTP 404]
I am using magento 1.9, I've got installed SSL which is working just fine.

The problem is when I am switching my secure link to https:// - all pages are working correctly, but pages such as checkout, register and login are throwing error 404, unless I manually add prefix with index.php

These links are working correctly when I am working with non-secure connections.

For example this links are working correctly:

http://myshop.com/customer/account/login/

http://myshop.com/customer/account/create/

But my links

https://myshop.com/customer/account/login/

https://myshop.com/customer/account/create/

are throwing HTTP 404 - Not Found - In order to make it work I have to manually add index.php prefix so my links look like this:

http://myshop.com/index.php/customer/account/login/

http://myshop.com/index.php/customer/account/create/

I have changed my .htaccess file, and I think the problem lies in this file. How can I edit this file so it fits my purposes ?

Any other solutions are more then welcome also.

答:
The SSL has its own configuration files and sometimes when SSL does not work well, it may give the error of 404 (Page not found). Normally, the file name  is  http.conf or  ssl.conf or default-ssl file which depends on your OS

Find here:

```<code><Directory "path to your directory">
    SSLOptions +StdEnvVars
    AllowOverride All
</Directory>
</code>```

make sure that AllowOverride All is present in your config

if it does not help attach what OS and web server you are using

Body:
The SSL has its own configuration files and sometimes when SSL does not work well, it may give the error of 404 (Page not found). Normally, the file name  is  http.conf or  ssl.conf or default-ssl file which depends on your OS

Find here:

<Directory "path to your directory">
    SSLOptions +StdEnvVars
    AllowOverride All
</Directory>

make sure that AllowOverride All is present in your config

if it does not help attach what OS and web server you are using


问:
How can I view all ng-init content?
I am doing the progress bar for each object equipment.

Here is my AngularJS code:

```<code>$scope.progressBarEquipements=function(idEquipement) {

     $http.get(url+"/RestResponseCheckLists?idEq="+idEquipement)
     .success(function(data) {
             $scope.Pourcentage = data;
      }).error(function(err, data) {
            console.log("error : " +data);
    });
};
</code>```

This function returns $scope.progressBarEquipements=function(idEquipement):

```<code>console.log("data "+Pourcentage);
/**
* [{'NB_Resp':2,'NB_checks':154}]  //For the first object And the others not
*/
</code>```

Here is my HTML code:

```<code><div class="col-md-4" ng-repeat="eq in Checksf" ng-init="progressBarEquipements(eq.idEquipements)">
          <h4 class="list-group-item-heading" >{{eq.nomEq}} </h4>
        <div class="progress progress-lg m-b-5" >
               <div class="progress-bar progress-bar-purple" role="progressbar" ng-repeat="p in Pourcentage" ng-style="{width:{{((p.NB_Resp/p.NB_checks) * 100)}} + '%'}">
                  {{((p.NB_Resp/p.NB_checks) * 100) | number:0}}%
           </div>
     </div>
</div>
</code>```

So I have four items of equipment are displayed in the html page.

The $scope.Percentage displays the progress bar calculation for the
  first object only.

How to display for each object its calculation in the progress bar?

thank you in advance

答:
Although, I don't like the way you are using ng-init, the following should work :

```<code>$scope.progressBarEquipements=function(eq) {

     $http.get(url+"/RestResponseCheckLists?idEq="+ eq.idEquipement)
     .success(function(data) {
         eq.Pourcentage = data;
      }).error(function(err, data) {
            console.log("error : " +data);
    });
};

<div class="col-md-4" ng-repeat="eq in Checksf" ng-init="progressBarEquipements(eq)">
          <h4 class="list-group-item-heading" >{{eq.nomEq}} </h4>
        <div class="progress progress-lg m-b-5" >
               <div class="progress-bar progress-bar-purple" role="progressbar" ng-repeat="p in eq.Pourcentage"  ng-style="{width:{{((p.NB_Resp/p.NB_checks) * 100)}} + '%'}">
                  {{((p.NB_Resp/p.NB_checks) * 100) | number:0}}%
           </div>
     </div>
</div>
</code>```

The idea was to send your function "progressBarEquipements" the full equipment object. In that way, you are able to update it when the server responds.

I don't like the approach of using ng-init because
 - the behaviour of your view is kinda hidden between your controller, and your template.
 - If I had to do it, my API would give the viewmodel containing every information I need to display.

Title: How can I view all ng-init content?

Body:
I am doing the progress bar for each object equipment.

Here is my AngularJS code:

$scope.progressBarEquipements=function(idEquipement) {

     $http.get(url+"/RestResponseCheckLists?idEq="+idEquipement)
     .success(function(data) {
             $scope.Pourcentage = data;
      }).error(function(err, data) {
            console.log("error : " +data);
    });
};

This function returns $scope.progressBarEquipements=function(idEquipement):

console.log("data "+Pourcentage);
/**
* [{'NB_Resp':2,'NB_checks':154}]  //For the first object And the others not
*/

Here is my HTML code:

{{eq.nomEq}}

                  {{((p.NB_Resp/p.NB_checks) * 100) | number:0}}%

So I have four items of equipment are displayed in the html page.

The $scope.Percentage displays the progress bar calculation for the
  first object only.

How to display for each object its calculation in the progress bar?

thank you in advance

Body:
Although, I don't like the way you are using ng-init, the following should work :

$scope.progressBarEquipements=function(eq) {

     $http.get(url+"/RestResponseCheckLists?idEq="+ eq.idEquipement)
     .success(function(data) {
         eq.Pourcentage = data;
      }).error(function(err, data) {
            console.log("error : " +data);
    });
};

<div class="col-md-4" ng-repeat="eq in Checksf" ng-init="progressBarEquipements(eq)">
          <h4 class="list-group-item-heading" >{{eq.nomEq}} </h4>
        <div class="progress progress-lg m-b-5" >
               <div class="progress-bar progress-bar-purple" role="progressbar" ng-repeat="p in eq.Pourcentage"  ng-style="{width:{{((p.NB_Resp/p.NB_checks) * 100)}} + '%'}">
                  {{((p.NB_Resp/p.NB_checks) * 100) | number:0}}%
           </div>
     </div>
</div>

The idea was to send your function "progressBarEquipements" the full equipment object. In that way, you are able to update it when the server responds.

I don't like the approach of using ng-init because
 - the behaviour of your view is kinda hidden between your controller, and your template.
 - If I had to do it, my API would give the viewmodel containing every information I need to display.


问:
setLayoutParams of a layout inside a Fragment from an Activity
I have an Activity that has many fragment inside. When on a particular fragment I inflate a menu and when clicking on the inflated MenuItem I should call a method of the Fragment class that change the layout params of a Constraint Layout inside the fragment. The problem is that I get a NPE on the Constraint Layout I'm trying to change.

These are the methods I'm trying to call:

```<code>public void searcherOpen() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT));
    searchText.setFocusable(true);
}
public void searcherClose() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(0, 0));
    searchText.setFocusable(false);
}
</code>```

These are the MenuItem that are calling the methods:

```<code>getMenuInflater().inflate(R.menu.patient_fragment_menu, menu);
        final MenuItem search = menu.findItem(R.id.menu_search);
        final MenuItem close_search = menu.findItem(R.id.menu_search_close);
        search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherOpen();
                search.setVisible(false);
                close_search.setVisible(true);
                return true;
            }
        });
        close_search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherClose();
                search.setVisible(true);
                close_search.setVisible(false);
                return true;
            }
        });
</code>```

This is how I define the fragment inside the activity in onCreate:

```<code>patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");
</code>```

And this is the error:

```<code>06-06 14:52:23.314 3682-3682/com.medishare.zeeromed E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.medishare.zeeromed, PID: 3682
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'void com.medishare.zeeromed.fragments.PatientFragment.searcherOpen()' on a null object reference
                                                                      at com.medishare.zeeromed.DrawerActivity$3.onMenuItemClick(DrawerActivity.java:255)
                                                                      at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
                                                                      at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
                                                                      at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22393)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:173)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
</code>```

答:
First of all, and obviously, this line code is not finding any fragment:

```<code>patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");
</code>```

Secondly, when you try to find a fragment with findFragmentByTag you should always verify if the fragment exists, i.e., is not null

```<code>if(patientFragment != null) { patientFragment.myMethod(); }
</code>```

Third, you also should verify if your fragment is Added to the activity, or you might end up in some other kind of NPE

```<code>if(patientFragment != null && patientFragment.isAdded()){ patientFragment.myMethod(); }
</code>```

Finally, and probably the reason why you are getting this error lies where you create your fragment, or in this case, how you create it. I assume you are creating it inside you Activity which extends FragmentActivity, therefore you should be using getSupportFragmentManager() to create it. In other words, to retrieve the fragment you should also call getSupportFragmentManager like @CODER pointed out:

```<code>patientFragment = (PatientFragment)getSupportFragmentManager().findFragmentByTag("patientFragment");
if(patientFragment != null && patientFragment.isAdded()){
    patientFragment.myMethod();
}
</code>```

Body:
I have an Activity that has many fragment inside. When on a particular fragment I inflate a menu and when clicking on the inflated MenuItem I should call a method of the Fragment class that change the layout params of a Constraint Layout inside the fragment. The problem is that I get a NPE on the Constraint Layout I'm trying to change.

These are the methods I'm trying to call:

public void searcherOpen() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT));
    searchText.setFocusable(true);
}
public void searcherClose() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(0, 0));
    searchText.setFocusable(false);
}

These are the MenuItem that are calling the methods:

getMenuInflater().inflate(R.menu.patient_fragment_menu, menu);
        final MenuItem search = menu.findItem(R.id.menu_search);
        final MenuItem close_search = menu.findItem(R.id.menu_search_close);
        search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherOpen();
                search.setVisible(false);
                close_search.setVisible(true);
                return true;
            }
        });
        close_search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherClose();
                search.setVisible(true);
                close_search.setVisible(false);
                return true;
            }
        });

This is how I define the fragment inside the activity in onCreate:

patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");

And this is the error:

06-06 14:52:23.314 3682-3682/com.medishare.zeeromed E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.medishare.zeeromed, PID: 3682
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'void com.medishare.zeeromed.fragments.PatientFragment.searcherOpen()' on a null object reference
                                                                      at com.medishare.zeeromed.DrawerActivity$3.onMenuItemClick(DrawerActivity.java:255)
                                                                      at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
                                                                      at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
                                                                      at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22393)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:173)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)

Body:
First of all, and obviously, this line code is not finding any fragment:

patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");

Secondly, when you try to find a fragment with findFragmentByTag you should always verify if the fragment exists, i.e., is not null

if(patientFragment != null) { patientFragment.myMethod(); }

Third, you also should verify if your fragment is Added to the activity, or you might end up in some other kind of NPE

if(patientFragment != null && patientFragment.isAdded()){ patientFragment.myMethod(); }

Finally, and probably the reason why you are getting this error lies where you create your fragment, or in this case, how you create it. I assume you are creating it inside you Activity which extends FragmentActivity, therefore you should be using getSupportFragmentManager() to create it. In other words, to retrieve the fragment you should also call getSupportFragmentManager like @CODER pointed out:

patientFragment = (PatientFragment)getSupportFragmentManager().findFragmentByTag("patientFragment");
if(patientFragment != null && patientFragment.isAdded()){
    patientFragment.myMethod();
}