问:
Laravel 5.4 change password
I am currently working on the profile page wherein the user can change its password. I created a new function changePassword() in the UserController

```<code>public function changePassword(Request $request, User $employee) {
    $validator = Validator::make($data, [
        'password' => 'required|string|min:6|confirmed',
        'password_confirmation' => 'required|string|min:6|same:password'
    ]);

    if ($validator->fails()) {
        Session::flash('error', "Fill-out the form correctly. Try again!");
        return redirect()->back()->withErrors($validator);
    }

    $employee->password = bcrypt($request->password);
    $employee->save();
    return view('users.show', ['employee'=>$employee]);
}
</code>```

I created this new route in web.php above the resource route of the User model

```<code>Route::put('users/{user}', 'UserController@changePassword')->name('users.changePassword');
</code>```

I am getting a MethodNotAllowedHttpException every time I click the submit button. I think the problem is the route but I am not sure. Is there a Laravel functionality aside the one that sends email, because I want the users to change its password without using email. Thanks!

Here is my form

```<code>{!! Form::model($employee, ['method'=>'PUT', 'route'=>['users.changePassword', $employee]]) !!}
</code>```

答:
try this....

this code work in my project using laravel 5.3

ubahprofilecontroller.php

```<code>public function updatePwd($id, Request $request)
       {
         //cek password lama
           $messages = array(
               'password_lama.required'=>'Harap masukkan password',
               'password_baru.required' => 'Password baru tidak boleh kosong',
               'ulangi_password.required' => 'Harap ketikkan ulang password baru',
               'ulangi_password.same' => 'Password baru dan konfirmasi password tidak cocok'
           );

           $rules = array (
             'password_lama'=> 'required',
             'password_baru'=> 'required',
             'ulangi_password'=> 'required|same:password_baru'
           );
           $validator = Validator::make ( Input::all (), $rules, $messages );

           if($validator->fails())
             {
                 /*return Redirect('edit_password')
                     ->withErrors($validator);*/
                     $password ='password';
                     return redirect('ubahPwd')->withErrors($validator)->withInput();
             }
           else
             {
               $check = User::where('id',$id)->first();
               if (Input::get('password_lama') == $check->value)
               {
                       if(Input::get('password_baru') == Input::get('ulangi_password'))
                         {
                           $check -> password = bcrypt(Input::get('password_baru'));
                           $check -> salt_password = Input::get('password_baru');
                           // save our duck
                           $check->save();

                             /*$msg = array('msg' => 'Password changed Successfully');*/
                             return redirect('ubahPwd')->with('success','Password berhasil diubah');
                         }
                         else
                         {
                             /*$msg = array('msg' => 'New password and Confirm password did not match');*/
                             return redirect('ubahPwd')->with('salah','Password baru dan konfirmasi password tidak sama');
                         }
               }
               else
               {
                 /*$msg = array('msg' => 'Current password is incorrect');*/
                 /*return Redirect('edit_password')
                               ->with('status-failed', 'Current password is incorrect');*/
                    return redirect('ubahPwd')->with('salah','Password lama salah');
               }
             }
      }
</code>```

profile.blade.php

```<code> <form class="form-horizontal" action="{{ url('/ubahPassword/update',Auth::user()->id )}}" method="POST">
              <<div class="content" style="padding-left:50px;padding-right:50px">

                <div class="form-group">
                    {{ csrf_field() }}
                  <label for="id" class="col-sm-3 control-label">ID</label>
                  <div class="col-sm-2">
                    <input type="text" class="form-control" id="id"  name="id" value="{{ Auth::user()->id }}" readonly>
                  </div>
                </div>

                <div class="form-group">
                  <label for="username" class="col-sm-3 control-label">Password Lama</label>
                  <div class="col-sm-6">
                    <input type="password" class="form-control" id="username" name="password_lama">
                    @if ($errors->has('password_lama')) <p class="help-block" style="color:red;">{{ $errors->first('password_lama') }}</p> @endif
                  </div>
                </div>

                <div class="form-group">
                  <label for="inputEmail3" class="col-sm-3 control-label">Password baru</label>
                  <div class="col-sm-5">
                    <input type="password" class="form-control" id="email" name="password_baru">
                    @if ($errors->has('password_baru')) <p class="help-block" style="color:red;">{{ $errors->first('password_baru') }}</p> @endif
                  </div>
                </div>

                <div class="form-group">
                  <label for="inputEmail3" class="col-sm-3 control-label">Ulangi Password</label>
                  <div class="col-sm-5">
                    <input type="password" class="form-control" id="email" name="ulangi_password">
                    @if ($errors->has('ulangi_password')) <p class="help-block" style="color:red;">{{ $errors->first('ulangi_password') }}</p> @endif
                  </div>
                </div>

              <div class="form-group">
                <button type="submit" class="btn btn-info pull-right col-sm-3">Simpan</button>
              </div>
            </div>
          </form>
</code>```

i hope my answer helping you....

Title: Laravel 5.4 change password

Body:
I am currently working on the profile page wherein the user can change its password. I created a new function changePassword() in the UserController

public function changePassword(Request $request, User $employee) {
    $validator = Validator::make($data, [
        'password' => 'required|string|min:6|confirmed',
        'password_confirmation' => 'required|string|min:6|same:password'
    ]);

    if ($validator->fails()) {
        Session::flash('error', "Fill-out the form correctly. Try again!");
        return redirect()->back()->withErrors($validator);
    }

    $employee->password = bcrypt($request->password);
    $employee->save();
    return view('users.show', ['employee'=>$employee]);
}

I created this new route in web.php above the resource route of the User model

Route::put('users/{user}', 'UserController@changePassword')->name('users.changePassword');

I am getting a MethodNotAllowedHttpException every time I click the submit button. I think the problem is the route but I am not sure. Is there a Laravel functionality aside the one that sends email, because I want the users to change its password without using email. Thanks!

Here is my form

{!! Form::model($employee, ['method'=>'PUT', 'route'=>['users.changePassword', $employee]]) !!}

Body:
try this....

this code work in my project using laravel 5.3

ubahprofilecontroller.php

public function updatePwd($id, Request $request)
       {
         //cek password lama
           $messages = array(
               'password_lama.required'=>'Harap masukkan password',
               'password_baru.required' => 'Password baru tidak boleh kosong',
               'ulangi_password.required' => 'Harap ketikkan ulang password baru',
               'ulangi_password.same' => 'Password baru dan konfirmasi password tidak cocok'
           );

           $rules = array (
             'password_lama'=> 'required',
             'password_baru'=> 'required',
             'ulangi_password'=> 'required|same:password_baru'
           );
           $validator = Validator::make ( Input::all (), $rules, $messages );

           if($validator->fails())
             {
                 /*return Redirect('edit_password')
                     ->withErrors($validator);*/
                     $password ='password';
                     return redirect('ubahPwd')->withErrors($validator)->withInput();
             }
           else
             {
               $check = User::where('id',$id)->first();
               if (Input::get('password_lama') == $check->value)
               {
                       if(Input::get('password_baru') == Input::get('ulangi_password'))
                         {
                           $check -> password = bcrypt(Input::get('password_baru'));
                           $check -> salt_password = Input::get('password_baru');
                           // save our duck
                           $check->save();

                             /*$msg = array('msg' => 'Password changed Successfully');*/
                             return redirect('ubahPwd')->with('success','Password berhasil diubah');
                         }
                         else
                         {
                             /*$msg = array('msg' => 'New password and Confirm password did not match');*/
                             return redirect('ubahPwd')->with('salah','Password baru dan konfirmasi password tidak sama');
                         }
               }
               else
               {
                 /*$msg = array('msg' => 'Current password is incorrect');*/
                 /*return Redirect('edit_password')
                               ->with('status-failed', 'Current password is incorrect');*/
                    return redirect('ubahPwd')->with('salah','Password lama salah');
               }
             }
      }

profile.blade.php

 <form class="form-horizontal" action="{{ url('/ubahPassword/update',Auth::user()->id )}}" method="POST">
              <<div class="content" style="padding-left:50px;padding-right:50px">

                <div class="form-group">
                    {{ csrf_field() }}
                  <label for="id" class="col-sm-3 control-label">ID</label>
                  <div class="col-sm-2">
                    <input type="text" class="form-control" id="id"  name="id" value="{{ Auth::user()->id }}" readonly>
                  </div>
                </div>

                <div class="form-group">
                  <label for="username" class="col-sm-3 control-label">Password Lama</label>
                  <div class="col-sm-6">
                    <input type="password" class="form-control" id="username" name="password_lama">
                    @if ($errors->has('password_lama')) <p class="help-block" style="color:red;">{{ $errors->first('password_lama') }}</p> @endif
                  </div>
                </div>

                <div class="form-group">
                  <label for="inputEmail3" class="col-sm-3 control-label">Password baru</label>
                  <div class="col-sm-5">
                    <input type="password" class="form-control" id="email" name="password_baru">
                    @if ($errors->has('password_baru')) <p class="help-block" style="color:red;">{{ $errors->first('password_baru') }}</p> @endif
                  </div>
                </div>

                <div class="form-group">
                  <label for="inputEmail3" class="col-sm-3 control-label">Ulangi Password</label>
                  <div class="col-sm-5">
                    <input type="password" class="form-control" id="email" name="ulangi_password">
                    @if ($errors->has('ulangi_password')) <p class="help-block" style="color:red;">{{ $errors->first('ulangi_password') }}</p> @endif
                  </div>
                </div>

              <div class="form-group">
                <button type="submit" class="btn btn-info pull-right col-sm-3">Simpan</button>
              </div>
            </div>
          </form>

i hope my answer helping you....


来源: stackexchange

问:
Count unique values based on criteria given in another column
I have a list of machines with respective batches and part number being manufactured.

I need a unique count of a batches running in a machine. This long list is updated daily. I have attached an example here.

I have this rough code.

```<code>last_row = ws.Cells(Rows.Count,1).End(xlUp).Row
For Each M_cCell in M_cRange
    Counter = 0
    For i = 2 to last_row
        If Cells(1, 1).Value = M_cCell Then
            Counter = Counter + (1/(WorksheetFunction.CountIF _
            (Range(Cells(2,2),Cells(Last_row,2),M_ccell.Value)))
        End If
    Next i
Next M_cCell
</code>```

This gives an undesired result in decimal figures.

答:
Not the very cleanest either, but you can avoid loops altogether and just use COUNTIF after using AdvancedFilter - When dealing with a big load of data this is quite efficient compared to loops.

```<code>Public Sub Test()
    Dim TargetSheet As Worksheet

    Set TargetSheet = Worksheets("Sheet2")

    With ActiveSheet
        .Range("A1:B20").AdvancedFilter xlFilterCopy, CopyToRange:=TargetSheet.Range("A1"), Unique:=True 'Get unique combinations
    End With

    With TargetSheet
        .Range("A1:A" & .Range("A1").End(xlDown).Row).AdvancedFilter xlFilterCopy, CopyToRange:=.Range("C1"), Unique:=True 'Get unique machines
        .Range("D2").Value = "=countif(A:A, C2)" 'Count batches per machine
        .Range("D2").AutoFill .Range("D2:D" & .Range("C2").End(xlDown).Row)

        .Range("D1").Value = "Count of batches:" 'Add count header
        .Range("D:D").value = .Range("D:D").value 'replace formula's by values.
        .Range("A:B").Delete shift:=xlToLeft 'Get rid of helper columns from first advanced filter.
    End With

    Set TargetSheet = Nothing
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of machines with respective batches and part number being manufactured.

I need a unique count of a batches running in a machine. This long list is updated daily. I have attached an example here.

I have this rough code.

last_row = ws.Cells(Rows.Count,1).End(xlUp).Row
For Each M_cCell in M_cRange
    Counter = 0
    For i = 2 to last_row
        If Cells(1, 1).Value = M_cCell Then
            Counter = Counter + (1/(WorksheetFunction.CountIF _
            (Range(Cells(2,2),Cells(Last_row,2),M_ccell.Value)))
        End If
    Next i
Next M_cCell

This gives an undesired result in decimal figures.

Body:
Not the very cleanest either, but you can avoid loops altogether and just use COUNTIF after using AdvancedFilter - When dealing with a big load of data this is quite efficient compared to loops.

Public Sub Test()
    Dim TargetSheet As Worksheet

    Set TargetSheet = Worksheets("Sheet2")

    With ActiveSheet
        .Range("A1:B20").AdvancedFilter xlFilterCopy, CopyToRange:=TargetSheet.Range("A1"), Unique:=True 'Get unique combinations
    End With

    With TargetSheet
        .Range("A1:A" & .Range("A1").End(xlDown).Row).AdvancedFilter xlFilterCopy, CopyToRange:=.Range("C1"), Unique:=True 'Get unique machines
        .Range("D2").Value = "=countif(A:A, C2)" 'Count batches per machine
        .Range("D2").AutoFill .Range("D2:D" & .Range("C2").End(xlDown).Row)

        .Range("D1").Value = "Count of batches:" 'Add count header
        .Range("D:D").value = .Range("D:D").value 'replace formula's by values.
        .Range("A:B").Delete shift:=xlToLeft 'Get rid of helper columns from first advanced filter.
    End With

    Set TargetSheet = Nothing
End Sub

ContentLicense: CC BY-SA 3.0


问:
No route matches [POST] "parent/id/child/new" error on nested association
Companies has_many Quotes, trying to create a new Quote in the Quotes controller, nested routes in place, yet i get a;

No route matches [POST] "/companies/123/quotes/new"

routes.rb

```<code>resources :companies do
    resources :quotes, only: [ :new, :create, :show, :index]
    resources :employees, only: [:show, :index]
end
</code>```

rake routes

```<code>                  Prefix Verb   URI Pattern                                    Controller#Action

          company_quotes GET    /companies/:company_id/quotes(.:format)        quotes#index
                         POST   /companies/:company_id/quotes(.:format)        quotes#create
       new_company_quote GET    /companies/:company_id/quotes/new(.:format)    quotes#new
           company_quote GET    /companies/:company_id/quotes/:id(.:format)    quotes#show
       company_employees GET    /companies/:company_id/employees(.:format)     employees#index
        company_employee GET    /companies/:company_id/employees/:id(.:format) employees#show
               companies GET    /companies(.:format)                           companies#index
                         POST   /companies(.:format)                           companies#create
             new_company GET    /companies/new(.:format)                       companies#new
            edit_company GET    /companies/:id/edit(.:format)                  companies#edit
                 company GET    /companies/:id(.:format)                       companies#show
                         PATCH  /companies/:id(.:format)                       companies#update
                         PUT    /companies/:id(.:format)                       companies#update
                         DELETE /companies/:id(.:format)                       companies#destroy
                    root GET    /                                              companies#new
</code>```

new.html.erb

```<code><div class='form-group col-md-6 quote-form'>
    <%= simple_form_for [@company, @quote] do |quote| %>
        <%= render 'quote_fields', :f => quote %>
        <%= quote.submit "Get Quote", class: 'btn btn-primary' %>
    <% end %>
</div>
</code>```

_quote_fields.html.erb

```<code><%= f.input :lives_overseas, as: :radio_buttons, collection: [['Yes', true],
            ['No', false]], readonly: nil %>
<%= f.input :payment_frequency, collection: Quote.payment_frequencies.map { |k,v| [ k.humanize, k ] } %>
<%= params.inspect %>
</code>```

quotes_controller.rb

```<code>class QuotesController < ApplicationController
before_action :authenticate_user!, only: [ :new, :create, :show, :index ]

  def new
    @company = Company.find(params[:company_id])
    @quote = @company.quotes.build
    end

    def create
    @company = Company.find(params[:company_id])
    @quote = @company.quotes.build(params[:quote])
    if @quote.save
      render 'show'
    end
    end

  def show
    @company = Company.find(params[:company_id])
    @quote = @company.quotes.find(params[:id])
    @employees = @company.employees.all
    # puts debug(params)
  end

  def index
    @company = Company.find(params[:company_id])
    @quotes = @company.quotes.all
    @employees = @company.employees.all
  end
end
</code>```

Shouldn't the submit action on the quote form be posting to; POST   /companies/:company_id/quotes(.:format), which is clearly present from rake routes?

Any ideas what I'm doing wrong here? Thanks for the guidance.

答:
No route matches [POST] "/companies/123/quotes/new"

You are having nested resources, so you need to change

```<code><%= simple_form_for @quote do |quote| %>
</code>```

to

```<code><%= simple_form_for [@comapny,@quote] do |quote| %>
</code>```

And change @quote = @company.quotes.build to just @quote = Quote.new in quotes#new method

Body:
Companies has_many Quotes, trying to create a new Quote in the Quotes controller, nested routes in place, yet i get a;

No route matches [POST] "/companies/123/quotes/new"

routes.rb

resources :companies do
    resources :quotes, only: [ :new, :create, :show, :index]
    resources :employees, only: [:show, :index]
end

rake routes

                  Prefix Verb   URI Pattern                                    Controller#Action

          company_quotes GET    /companies/:company_id/quotes(.:format)        quotes#index
                         POST   /companies/:company_id/quotes(.:format)        quotes#create
       new_company_quote GET    /companies/:company_id/quotes/new(.:format)    quotes#new
           company_quote GET    /companies/:company_id/quotes/:id(.:format)    quotes#show
       company_employees GET    /companies/:company_id/employees(.:format)     employees#index
        company_employee GET    /companies/:company_id/employees/:id(.:format) employees#show
               companies GET    /companies(.:format)                           companies#index
                         POST   /companies(.:format)                           companies#create
             new_company GET    /companies/new(.:format)                       companies#new
            edit_company GET    /companies/:id/edit(.:format)                  companies#edit
                 company GET    /companies/:id(.:format)                       companies#show
                         PATCH  /companies/:id(.:format)                       companies#update
                         PUT    /companies/:id(.:format)                       companies#update
                         DELETE /companies/:id(.:format)                       companies#destroy
                    root GET    /                                              companies#new

new.html.erb

    <%= simple_form_for [@company, @quote] do |quote| %>
        <%= render 'quote_fields', :f => quote %>
        <%= quote.submit "Get Quote", class: 'btn btn-primary' %>
    <% end %>

_quote_fields.html.erb

<%= f.input :lives_overseas, as: :radio_buttons, collection: [['Yes', true],
            ['No', false]], readonly: nil %>
<%= f.input :payment_frequency, collection: Quote.payment_frequencies.map { |k,v| [ k.humanize, k ] } %>
<%= params.inspect %>

quotes_controller.rb

class QuotesController < ApplicationController
before_action :authenticate_user!, only: [ :new, :create, :show, :index ]

  def new
    @company = Company.find(params[:company_id])
    @quote = @company.quotes.build
    end

    def create
    @company = Company.find(params[:company_id])
    @quote = @company.quotes.build(params[:quote])
    if @quote.save
      render 'show'
    end
    end

  def show
    @company = Company.find(params[:company_id])
    @quote = @company.quotes.find(params[:id])
    @employees = @company.employees.all
    # puts debug(params)
  end

  def index
    @company = Company.find(params[:company_id])
    @quotes = @company.quotes.all
    @employees = @company.employees.all
  end
end

Shouldn't the submit action on the quote form be posting to; POST   /companies/:company_id/quotes(.:format), which is clearly present from rake routes?

Any ideas what I'm doing wrong here? Thanks for the guidance.

Body:
No route matches [POST] "/companies/123/quotes/new"

You are having nested resources, so you need to change

<%= simple_form_for @quote do |quote| %>

to

<%= simple_form_for [@comapny,@quote] do |quote| %>

And change @quote = @company.quotes.build to just @quote = Quote.new in quotes#new method


问:
Directory lock error with Lucene.Net usage in an ASP.NET MVC site
I'm building an ASP.NET MVC site where I want to use Lucene.Net for search. I've already built a SearchController and all of its methods, but I'm getting an error at runtime that occurs when the SearchController is first initialized.

In SearchController, here's how I'm creating an IndexWriter:

```<code>public static string IndexLocation = HostingEnvironment.MapPath("~/lucene");
public static Lucene.Net.Analysis.Standard.StandardAnalyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer();
public static IndexWriter writer = new IndexWriter(IndexLocation,analyzer);
</code>```

The error occurs on the last line. Here's the message that I'm getting:

Lucene.Net.Store.LockObtainFailedException:
  Lock obtain timed out:
  SimpleFSLock@C:\Users\Username\Desktop\SiteSolution\Site\lucene\write.lock

Furthermore, here's the stack trace:

```<code>[LockObtainFailedException: Lock obtain timed out: SimpleFSLock@C:\Users\Username\Desktop\SiteSolution\Site\lucene\write.lock]
   Lucene.Net.Store.Lock.Obtain(Int64 lockWaitTimeout) in C:\Users\Username\Desktop\Lucene.Net_2_9_2\src\Lucene.Net\Store\Lock.cs:107
   Lucene.Net.Index.IndexWriter.Init(Directory d, Analyzer a, Boolean create, Boolean closeDir, IndexDeletionPolicy deletionPolicy, Boolean autoCommit, Int32 maxFieldLength, IndexingChain indexingChain, IndexCommit commit) in C:\Users\Username\Desktop\Lucene.Net_2_9_2\src\Lucene.Net\Index\IndexWriter.cs:1827
   Lucene.Net.Index.IndexWriter.Init(Directory d, Analyzer a, Boolean closeDir, IndexDeletionPolicy deletionPolicy, Boolean autoCommit, Int32 maxFieldLength, IndexingChain indexingChain, IndexCommit commit) in C:\Users\Username\Desktop\Lucene.Net_2_9_2\src\Lucene.Net\Index\IndexWriter.cs:1801
   Lucene.Net.Index.IndexWriter..ctor(String path, Analyzer a) in C:\Users\Username\Desktop\Lucene.Net_2_9_2\src\Lucene.Net\Index\IndexWriter.cs:1350
   Site.Controllers.SearchController..cctor() in C:\Users\Username\Desktop\SiteSolution\Site\Controllers\SearchController.cs:95

[TypeInitializationException: The type initializer for 'Site.Controllers.SearchController' threw an exception.]

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
   System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80

[InvalidOperationException: An error occurred when trying to create a controller of type 'Site.Controllers.SearchController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +190
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +68
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +118
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +46
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +63
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +13
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8682818
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code>```

How can I resolve this issue?

UPDATE: I've started working on this particular project again, and it seems that I haven't fully resolved this issue yet.

The real issue is that the write.lock file isn't being removed after index usage ends. Based on the answer I have accepted, I understand the basic implementation logic, but I'm not sure if I have implemented it correctly. Here are some other methods in my class that are probably invalid:

```<code>    public ActionResult Search(string query)
    {

        var reader = writer.GetReader(); // Get reader from writer
        var searcher = new IndexSearcher(reader); // Build IndexSearch

        //Execute search...

        // Dispose of objects
        searcher = null;
        reader = null;

        return View();
    }

    public void AddToIndex(Document doc)
    {
        writer.AddDocument(doc);
        writer.Flush();
        writer.Optimize();
        writer.Flush();
    }

    private bool disposed = false;

    protected override void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Release managed resources.
            }
            try
            {
                writer.Close();
                writer = null;
            }
            catch
            {

            }
            // Release unmanaged resources.
            // Set large fields to null.
            // Call Dispose on your base class.
            disposed = true;
        }
        base.Dispose(disposing);
    }
</code>```

Any thoughts?

答:
I encountered the same issue and I was using an IProviderContext. In my case I had to:
Optimize,Commit and Dispose the ProviderContext.

```<code>providerContext.Optimize();
providerContext.Commit();
providerContext.Dispose();
</code>```

I hope this helps. After implementing the above snippet, my index rebuilt successfully.

ContentLicense: CC BY-SA 2.5

Body:
I'm building an ASP.NET MVC site where I want to use Lucene.Net for search. I've already built a SearchController and all of its methods, but I'm getting an error at runtime that occurs when the SearchController is first initialized.

In SearchController, here's how I'm creating an IndexWriter:

public static string IndexLocation = HostingEnvironment.MapPath("~/lucene");
public static Lucene.Net.Analysis.Standard.StandardAnalyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer();
public static IndexWriter writer = new IndexWriter(IndexLocation,analyzer);

The error occurs on the last line. Here's the message that I'm getting:

Lucene.Net.Store.LockObtainFailedException:
  Lock obtain timed out:
  SimpleFSLock@C:\Users\Username\Desktop\SiteSolution\Site\lucene\write.lock

Furthermore, here's the stack trace:

[LockObtainFailedException: Lock obtain timed out: SimpleFSLock@C:\Users\Username\Desktop\SiteSolution\Site\lucene\write.lock]
   Lucene.Net.Store.Lock.Obtain(Int64 lockWaitTimeout) in C:\Users\Username\Desktop\Lucene.Net_2_9_2\src\Lucene.Net\Store\Lock.cs:107
   Lucene.Net.Index.IndexWriter.Init(Directory d, Analyzer a, Boolean create, Boolean closeDir, IndexDeletionPolicy deletionPolicy, Boolean autoCommit, Int32 maxFieldLength, IndexingChain indexingChain, IndexCommit commit) in C:\Users\Username\Desktop\Lucene.Net_2_9_2\src\Lucene.Net\Index\IndexWriter.cs:1827
   Lucene.Net.Index.IndexWriter.Init(Directory d, Analyzer a, Boolean closeDir, IndexDeletionPolicy deletionPolicy, Boolean autoCommit, Int32 maxFieldLength, IndexingChain indexingChain, IndexCommit commit) in C:\Users\Username\Desktop\Lucene.Net_2_9_2\src\Lucene.Net\Index\IndexWriter.cs:1801
   Lucene.Net.Index.IndexWriter..ctor(String path, Analyzer a) in C:\Users\Username\Desktop\Lucene.Net_2_9_2\src\Lucene.Net\Index\IndexWriter.cs:1350
   Site.Controllers.SearchController..cctor() in C:\Users\Username\Desktop\SiteSolution\Site\Controllers\SearchController.cs:95

[TypeInitializationException: The type initializer for 'Site.Controllers.SearchController' threw an exception.]

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
   System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80

[InvalidOperationException: An error occurred when trying to create a controller of type 'Site.Controllers.SearchController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +190
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +68
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +118
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +46
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +63
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +13
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8682818
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

How can I resolve this issue?

UPDATE: I've started working on this particular project again, and it seems that I haven't fully resolved this issue yet.

The real issue is that the write.lock file isn't being removed after index usage ends. Based on the answer I have accepted, I understand the basic implementation logic, but I'm not sure if I have implemented it correctly. Here are some other methods in my class that are probably invalid:

    public ActionResult Search(string query)
    {

        var reader = writer.GetReader(); // Get reader from writer
        var searcher = new IndexSearcher(reader); // Build IndexSearch

        //Execute search...

        // Dispose of objects
        searcher = null;
        reader = null;

        return View();
    }

    public void AddToIndex(Document doc)
    {
        writer.AddDocument(doc);
        writer.Flush();
        writer.Optimize();
        writer.Flush();
    }

    private bool disposed = false;

    protected override void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Release managed resources.
            }
            try
            {
                writer.Close();
                writer = null;
            }
            catch
            {

            }
            // Release unmanaged resources.
            // Set large fields to null.
            // Call Dispose on your base class.
            disposed = true;
        }
        base.Dispose(disposing);
    }

Any thoughts?

Body:
I encountered the same issue and I was using an IProviderContext. In my case I had to:
Optimize,Commit and Dispose the ProviderContext.

providerContext.Optimize();
providerContext.Commit();
providerContext.Dispose();

I hope this helps. After implementing the above snippet, my index rebuilt successfully.


问:
Plugin init failure for [schema.xml] fieldType "pfloat": Error loading class 'solr.FloatField'
```<code>nutch:arg.apache.solr.common.SolrException:org.apache.solr.common.SolrException:
Could not load conf for core nutch: Can't load schema D:\solr-6.5.0\server\solr\nutch\conf\schema.xml:
    Plugin init failure for [schema.xml] fieldType "pfloat": Error loading class 'solr.FloatField'
</code>```

I'm finding this error, can anyone help to fix it?

答: FloatField was removed in Solr 5. Use solr.TrieFloatField instead.

Body:
nutch:arg.apache.solr.common.SolrException:org.apache.solr.common.SolrException:
Could not load conf for core nutch: Can't load schema D:\solr-6.5.0\server\solr\nutch\conf\schema.xml:
    Plugin init failure for [schema.xml] fieldType "pfloat": Error loading class 'solr.FloatField'

I'm finding this error, can anyone help to fix it?


问:
how can we show/hide div tags using value of radio buttons in jquery or javascript?
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

```

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

答:
try this one

function fuelList(val) {
  var val = parseInt(val);
  if (val == 1) {
    $('#FourWheeler').hide();
    $('#TwoWheeler').show();
  } else {
    $('#TwoWheeler').hide();
    $('#FourWheeler').show();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="OwnVehicle">
  <label>
     <input type="radio" name="vehicleList" id="two" onclick="fuelList(this.value)" value="1" />Two Wheeler
  </label>
  <label>
    <input type="radio" name="vehicleList" id="four" onclick="fuelList(this.value)" value="2" />Four Wheeler
  </label>
</div>

<div id="TwoWheeler" style="display:none">
  <label>
      <input type="radio" name="TwoWheeler" value="6" />Electric
  </label>
  <label>
    <input type="radio" name="TwoWheeler" value="7" />Petrol
  </label>
</div>
<div id="FourWheeler" style="display:none">
  <label>
    <input type="radio" name="FourWheeler" value="1" />Electric
  </label>
  <label>
      <input type="radio" name="FourWheeler" value="2" />Petrol
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="3" />Diesel
  </label>
  <label>
     <input type="radio" name="FourWheeler" value="4" />CNG
  </label>
  <label>
     <input type="radio" name="FourWheeler" value="5" />LPG
  </label>
</div></code>```

Body:
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

Body:
try this one

function fuelList(val) {
  var val = parseInt(val);
  if (val == 1) {
    $('#FourWheeler').hide();
    $('#TwoWheeler').show();
  } else {
    $('#TwoWheeler').hide();
    $('#FourWheeler').show();
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="OwnVehicle">
  <label>
     <input type="radio" name="vehicleList" id="two" onclick="fuelList(this.value)" value="1" />Two Wheeler
  </label>
  <label>
    <input type="radio" name="vehicleList" id="four" onclick="fuelList(this.value)" value="2" />Four Wheeler
  </label>
</div>

<div id="TwoWheeler" style="display:none">
  <label>
      <input type="radio" name="TwoWheeler" value="6" />Electric
  </label>
  <label>
    <input type="radio" name="TwoWheeler" value="7" />Petrol
  </label>
</div>
<div id="FourWheeler" style="display:none">
  <label>
    <input type="radio" name="FourWheeler" value="1" />Electric
  </label>
  <label>
      <input type="radio" name="FourWheeler" value="2" />Petrol
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="3" />Diesel
  </label>
  <label>
     <input type="radio" name="FourWheeler" value="4" />CNG
  </label>
  <label>
     <input type="radio" name="FourWheeler" value="5" />LPG
  </label>
</div>


问:
Unit of work in Nhibernate
I am using NHibernate for persistence, but i read somewhere that NHibernate acts as unitofwork container. So do i need to create a separate UnitOfWork implementation. ?

Or continue with Nhibernate's unitofwork.

答:
You don't need to create separate UoW implementation.

I suggest you to read  this post: nhibernate.info

Title: Unit of work in Nhibernate


问:
Nil pointer to struct not deep equal to nil?
If I have a struct containing a nil pointer of type A, using reflect.DeepEqual to check if that property is nil will result in false, which strikes me as odd behaviour.

type Container struct {
    O *Obj
}

type Obj struct {
    Message string
}

var c Container
eq := reflect.DeepEqual(c.O, nil)
fmt.Printf("O value: %v, is nil: %t", c.O, eq)
// Prints: "O value: <nil>, is nil: false"
```

Specifically, I am marshaling a JSON object into a struct, where I would like to test that a specific property is nil when the corresponding JSON structure does not contain it. If reflect.DeepEqual is not the way to go, how should I do this?

答:
Everything you pass to reflect.DeepEqual() is wrapped in an interface{} value (if it's not already that):

```<code>func DeepEqual(x, y interface{}) bool
</code>```

interface{} values will be compared, where the first parameter value is not nil, only the value wrapped in it.

An interface value is represented as a (type; value) pair. The first value you pass to reflect.DeepEqual() is a pair of (type; value) being (*Obj, nil), and the 2nd value is nil. They are not equal. The second value lacks type information.

If you compare it to a "typed" nil, it will be true:

```<code>reflect.DeepEqual(c.O, (*Obj)(nil)) // This is true
</code>```

See this example:

```<code>fmt.Println("c.O:", c.O)
fmt.Println("c.O == nil:", c.O == nil)
fmt.Println("c.O deep equal to nil:", reflect.DeepEqual(c.O, nil))
fmt.Println("c.O deep equal to (*Obj)(nil):", reflect.DeepEqual(c.O, (*Obj)(nil)))
</code>```

Output (try it on the Go Playground):

```<code>c.O: <nil>
c.O == nil: true
c.O deep equal to nil: false
c.O deep equal to (*Obj)(nil): true
</code>```

See this question for a deeper insight:

Hiding nil values, understanding why golang fails here

If you want to check if the value wrapped inside a non-nil interface is nil, you can use reflection: reflect.Value.IsNil().

For more details see: Why interface type doesn't provide an "IsNil" method?

Body:
If I have a struct containing a nil pointer of type A, using reflect.DeepEqual to check if that property is nil will result in false, which strikes me as odd behaviour.

type Container struct {
    O *Obj
}

type Obj struct {
    Message string
}

var c Container
eq := reflect.DeepEqual(c.O, nil)
fmt.Printf("O value: %v, is nil: %t", c.O, eq)
// Prints: "O value: <nil>, is nil: false"

Specifically, I am marshaling a JSON object into a struct, where I would like to test that a specific property is nil when the corresponding JSON structure does not contain it. If reflect.DeepEqual is not the way to go, how should I do this?

Body:
Everything you pass to reflect.DeepEqual() is wrapped in an interface{} value (if it's not already that):

func DeepEqual(x, y interface{}) bool

interface{} values will be compared, where the first parameter value is not nil, only the value wrapped in it.

An interface value is represented as a (type; value) pair. The first value you pass to reflect.DeepEqual() is a pair of (type; value) being (*Obj, nil), and the 2nd value is nil. They are not equal. The second value lacks type information.

If you compare it to a "typed" nil, it will be true:

reflect.DeepEqual(c.O, (*Obj)(nil)) // This is true

See this example:

fmt.Println("c.O:", c.O)
fmt.Println("c.O == nil:", c.O == nil)
fmt.Println("c.O deep equal to nil:", reflect.DeepEqual(c.O, nil))
fmt.Println("c.O deep equal to (*Obj)(nil):", reflect.DeepEqual(c.O, (*Obj)(nil)))

Output (try it on the Go Playground):

c.O: <nil>
c.O == nil: true
c.O deep equal to nil: false
c.O deep equal to (*Obj)(nil): true

See this question for a deeper insight:

Hiding nil values, understanding why golang fails here

If you want to check if the value wrapped inside a non-nil interface is nil, you can use reflection: reflect.Value.IsNil().

For more details see: Why interface type doesn't provide an "IsNil" method?


问:
How to export excel file in GWT?
My requirement is to export an excel from GWT application on click of export button. In my case There is no need to send data from client to server as I can directly obtain data from database(same data is being populated on the client that is being exported).
All I tried to send a RPC call from Client site . but I am not able to figure out how to export excel on receiving the RPC call at server site.</p>

答:
This is certainly possilbe 100% client side.

You can use an Excel JavaScript builder like https://github.com/stephenliberty/excel-builder.js and call it from GWT with jsni or jsinterop.

Later you can save the file by

For Internet explorer for example filesaver.js https://github.com/eligrey/FileSaver.js/ in the same way.

For other browsers using HTML5 downloadv (using FileDownloadBuilder.createFileDownload().generateTextDownloadLink()) from https://github.com/akjava/html5gwt

Note for the generating an Excem file you could also just create an html file with table tags and save it as .xls, it with filesaver.js.

I use the html solution and filesaver.js/html5 download in my project and this works without a problem, and without the need for any serverside code, or any plugin on the client. 100% HTML5/javascript.

Title: How to export excel file in GWT?


问:
How to display JSON array
So i have written this code to get a json from API.AI. i want to know how to echo out the decoded JSON file on this form. Currently the decoded JSON is being saved in a new file JSON.php, but instead of saving i want to know how to view it?</p>

```<code>$data = json_decode(file_get_contents("php://input"), true);
file_put_contents("JSON.php", print_r($data, true));
</code>```

答:
do like this:-

$postdata = file_get_contents("php://input");

$request = json_decode($postdata);

print_r($request);

or you can do :-  $request->indexname

Title: How to display JSON array

Body:
So i have written this code to get a json from API.AI. i want to know how to echo out the decoded JSON file on this form. Currently the decoded JSON is being saved in a new file JSON.php, but instead of saving i want to know how to view it?

$data = json_decode(file_get_contents("php://input"), true);
file_put_contents("JSON.php", print_r($data, true));


问:
how to open a webpage using Jmeter
How to resolve the below error in jmeter
1.) Request to open Google.com

2.)

P.S: I have just started learning jmeter.
Which is the best way to learn it, please advice.

答:
JMeter is not a browser

See first page of Jmeter

JMeter does not execute the Javascript found in HTML pages. Nor does
  it render the HTML pages as a browser does

Title: how to open a webpage using Jmeter


问:
Chef: Provision certificates and private keys
Is there any best-practice in order to provide a certificate with a cookbook: We need to configure an nginx instance, and we want to configure an https channel. In order to get it we need to provision the machine with an certificate and a private key.

I don't quite get how to deal with that safely, or if there's any best-practice to get it.

Any ideas?

答:
There are many options, none conclusive enough to call "best". If you're on AWS, look at the SSM parameter store or S3 w/ bucket policies, otherwise look at things like Hashicorp Vault, Keywhiz, ecfg, etc.

I've got a talk up covering the general space at https://coderanger.net/talks/secrets/. Feel free to ping me on Slack if you have specific questions.


问:
Scrapy a hidden content in source code
Hi I want to crawl some contents which I cannot see from the page source code while they are there by seeing the page.
A example site : https://bangumi.bilibili.com/anime/index#p=1&v=1&area=2&stat=0&y=0&q=0&tag=&t=1&sort=0
(I want to get the anime info)

Could anyone can give me any hint to do this?

Thanks

答:
It seems the website loads the content dynamically, therefor you need to render the page completely (which also means you have to parse the JavaScript).
Due to that fact, you should consider using an headless browser.</p>

Title: Scrapy a hidden content in source code


问:
FXML Initialize() throws InvocationTargetException
Im trying to set the text of a button on the initialize() method but it throws me InvocationTargetException, its the same if I try to get any items on the FXML.

FXML:

```<code><VBox fx:id="vbox" alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="450.0" spacing="40.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="instaj.LoginController">
   <children>
      <ImageView fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="img/logo.png" />
         </image>
      </ImageView>
      <TextField id="user" maxWidth="200.0" prefHeight="35.0" promptText="Usuario" style="-fx-focus-color: #9a3bab; -fx-faint-focus-color: transparent;" />
      <javafx.scene.control.PasswordField id="pass" maxWidth="200.0" prefHeight="35.0" promptText="Contraseña" style="-fx-focus-color: #9a3bab; -fx-faint-focus-color: transparent;" />
      <Button fx:id="loginBtn" minHeight="30.0" minWidth="150.0" mnemonicParsing="false" onAction="#loginBtnBehavior" style="-fx-background-radius: 30; -fx-background-color: #9a3bab;" text="Iniciar" textFill="WHITE">
         <font>
            <Font size="16.0" />
         </font>
         <cursor>
            <Cursor fx:constant="HAND" />
         </cursor>
      </Button>
      <Label alignment="CENTER" onMouseClicked="#localAccountLinkBehavior" style="-fx-underline: true;" text="Iniciar con perfil abierto de Instagram dentro de Google Chrome." textFill="#0000ee">
         <cursor>
            <Cursor fx:constant="HAND" />
         </cursor>
      </Label>
   </children>
</VBox>
</code>```

LoginController.java:

```<code>public class LoginController implements Initializable {

    @FXML
    Button loginBtn;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Utils utils = new Utils();
        loginBtn.setText("test");
        //vbox.requestFocus();
        //utils.removeInitialFocus(user, vbox, firstTime);
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
</code>```

答:
You ask your program to launch an Exception : </p>

```<code>throw new UnsupportedOperationException("Not supported yet.");
</code>```

<p>So it's normal that it crashes :  remove it ! </p>

Body:
Im trying to set the text of a button on the initialize() method but it throws me InvocationTargetException, its the same if I try to get any items on the FXML.

FXML:

<VBox fx:id="vbox" alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="450.0" spacing="40.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="instaj.LoginController">
   <children>
      <ImageView fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="img/logo.png" />
         </image>
      </ImageView>
      <TextField id="user" maxWidth="200.0" prefHeight="35.0" promptText="Usuario" style="-fx-focus-color: #9a3bab; -fx-faint-focus-color: transparent;" />
      <javafx.scene.control.PasswordField id="pass" maxWidth="200.0" prefHeight="35.0" promptText="Contraseña" style="-fx-focus-color: #9a3bab; -fx-faint-focus-color: transparent;" />
      <Button fx:id="loginBtn" minHeight="30.0" minWidth="150.0" mnemonicParsing="false" onAction="#loginBtnBehavior" style="-fx-background-radius: 30; -fx-background-color: #9a3bab;" text="Iniciar" textFill="WHITE">

         <cursor>
            <Cursor fx:constant="HAND" />
         </cursor>
      </Button>

         <cursor>
            <Cursor fx:constant="HAND" />
         </cursor>

   </children>
</VBox>

LoginController.java:

public class LoginController implements Initializable {

    @FXML
    Button loginBtn;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Utils utils = new Utils();
        loginBtn.setText("test");
        //vbox.requestFocus();
        //utils.removeInitialFocus(user, vbox, firstTime);
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

Body:
You ask your program to launch an Exception :

throw new UnsupportedOperationException("Not supported yet.");

So it's normal that it crashes :  remove it !


答:
Assuming I understood the question correctly, and you want to hide a div when you check a radio button?

Here is an example of how that can be achieved:

HTML:

```<code><input type="radio" name="euResident" id="euResidentYes" value="Yes" checked />
<label for="euResidentYes" class="radio">yes</label>
<input type="radio" name="euResident" id="euResidentNo" value="No" />
<label for="euResidentNo" class="radio">no</label>

<div id='div'>Hello World</div>
</code>```

Javascript:

```<code>function switchVar() {
    if($("#euResidentNo").prop("checked"))
        $("#div").show();
     else
        $("#div").hide();
}

$(document).ready(function() {
    switchVar();
    $("input[name=euResident]").change(switchVar);
});
</code>```

It is an example using Javascript as this is perfect to use for this.
Demo: http://jsfiddle.net/2Uj9F/169/

Title: how can we show/hide div tags using value of radio buttons in jquery or javascript?

Body:
Assuming I understood the question correctly, and you want to hide a div when you check a radio button?

Here is an example of how that can be achieved:

HTML:

<input type="radio" name="euResident" id="euResidentYes" value="Yes" checked />
<label for="euResidentYes" class="radio">yes</label>
<input type="radio" name="euResident" id="euResidentNo" value="No" />
<label for="euResidentNo" class="radio">no</label>

<div id='div'>Hello World</div>

Javascript:

function switchVar() {
    if($("#euResidentNo").prop("checked"))
        $("#div").show();
     else
        $("#div").hide();
}

$(document).ready(function() {
    switchVar();
    $("input[name=euResident]").change(switchVar);
});

It is an example using Javascript as this is perfect to use for this.
Demo: http://jsfiddle.net/2Uj9F/169/


答:
Here you go with jsfiddle https://jsfiddle.net/ym10add9/</p>

```<code>$("input[type='radio']").change(function() {
    $('div').hide();
    $( '#' + $(this).attr('value')).show();
});
</code>```

Body:
Here you go with jsfiddle https://jsfiddle.net/ym10add9/

$("input[type='radio']").change(function() {
    $('div').hide();
    $( '#' + $(this).attr('value')).show();
});


问:
This page is trying to load scripts from unauthenticated sources after ssl from sslforfree
I am getting error that

This page is trying to load scripts from unauthenticated sources

after doing SSL from SSL for free

how to solve please help

答:
This usually happens when your page has link href tag connected to a website which doesn't have SSL.

If you want to check these href links:-

On your computer, open Chrome.

Go to your website.

At the top right, click More (vertical triple dots).

Click More tools and then Developer tools.

In the right sidebar, at the top, click Console.

Here you'll see which scripts are trying to load from unauthenticated sources.


问:
explain these how the conditional operator helps in counting the negative and positive numbers in an array?
my confusion is that how in the program the number of positive and negative numbers are calculated by writing that piece of code shown.
explain these code please!</p>

```<code>int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();
</code>```

答:
Since, most answers have explained the ternary operator, I need not do it again.
The neg++ post-increments the previous value of neg variable. And the same goes for pos++.
Here's a link on post/pre increments.

Body:
my confusion is that how in the program the number of positive and negative numbers are calculated by writing that piece of code shown.
explain these code please!

int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();


问:
Is there any way to colorize a white PNG image with CSS only?
I know there are many css filters out there especially for webkit, but I can't find a solution for colorize a white (#FFFFFF) image. I've tried some combination of the filters, but none of them make my image colorized. I can only change the image in the range of grayscale, or sepia.

So my question is:
Is there any way to change my totally white png to (for example) red using css only?

Like shown on this image:

答:
I recently have the same question and I think this approach is worth sharing for future readers.
Try this

```<code>filter: brightness(50%) sepia(100) saturate(100) hue-rotate(25deg);
</code>```

Brightness will darken the image, sepia will make it a bit yellowish, saturate to increase the color, and lastly hue-rotate to change the color.
It's not cross browser friendly though:

It's not supported on IE

On chrome, hue-rotate(25deg) will make any image red, but you need
negative value in firefox e.g. hue-rotate(-25deg) to make it red.
You can use this to target mozilla browsers:
https://css-tricks.com/snippets/css/css-hacks-targeting-firefox/

Here are some useful tips and tools that I've used when I work with images/icons using css:

If you have the svg version of the image, you can convert them to
font icons using this tool https://icomoon.io/ . To change color you just need color:#f00; just like font colors.

If you need to achieve this effect for hover state, Use red image with filter: brightness(0) invert(); on NON-hover state, and filter: brightness(1); on hover state. Hovever this will still won't work on IE

Use sprite sheet. You can create yourself using image editing tool or use sprite sheet generators available online. Then, you can use SpriteCow to get the css for every sub-image of your spritesheet.

Body:
I recently have the same question and I think this approach is worth sharing for future readers.
Try this

filter: brightness(50%) sepia(100) saturate(100) hue-rotate(25deg);

Brightness will darken the image, sepia will make it a bit yellowish, saturate to increase the color, and lastly hue-rotate to change the color.
It's not cross browser friendly though:

It's not supported on IE

On chrome, hue-rotate(25deg) will make any image red, but you need
negative value in firefox e.g. hue-rotate(-25deg) to make it red.
You can use this to target mozilla browsers:
https://css-tricks.com/snippets/css/css-hacks-targeting-firefox/

Here are some useful tips and tools that I've used when I work with images/icons using css:

If you have the svg version of the image, you can convert them to
font icons using this tool https://icomoon.io/ . To change color you just need color:#f00; just like font colors.

If you need to achieve this effect for hover state, Use red image with filter: brightness(0) invert(); on NON-hover state, and filter: brightness(1); on hover state. Hovever this will still won't work on IE

Use sprite sheet. You can create yourself using image editing tool or use sprite sheet generators available online. Then, you can use SpriteCow to get the css for every sub-image of your spritesheet.


问:
Python: remove complex multiline string
I have a file that contains a lot of different text that looks like:

```<code>Family number: 1
    Names: Bob, Linda, Dave
    Message: Some message here.

...
</code>```

...with hundreds of entries.

Some of them looks like this:

```<code>Family number: 1
    Names: Bob, Linda,\
    \ Dave
    Message: Some message here.
</code>```

This is due to some upstream formatting issues that is done by some other information gathering module that I cannot affect (or rather should not be fiddling with).

I would like the entries that look like the latter to look like the former.

From what I can gather, the pattern I want to remove occurs on multiple lines. My initial strategy is to search for the pattern

```<code>,\\n    \
</code>```

and replace this with a ',' because I am not sure that there is some other place in the file that might have the pattern without the first comma.

Usually I do something like this:

```<code>for line in fileinput.input(['file.txt'], inplace=True):
    print(line.replace(',\\n    \',','), end='')
</code>```

...but this only works for single lines. I also tried:

```<code>with open('file.txt', 'r') as in_file:
    with open('file.txt.tmp', 'w') as out_file:
       content = in_file.read()
       pattern = re.compile(r',\\n    \')
       to_be_printed = re.sub(pattern, ",", to_be_printed)
       out.write(to_be_printed)
</code>```

This does not work and does not appear to be that memory efficient since it involves reading the entire file into memory.

Is there a way this can be done neatly?

答:
```<code>import re
text =  open(path).read()

# Replace multiline delimited by \
pattern = r'\\\n+[ \t]*\\'
new_text = re.sub(pattern, ",", text)

# Replace 2+ commas in a row (if that's an issue)
pattern = r',{2,}'
new_text = re.sub(pattern, ",", new_text)
</code>```

Will do the job providing all the matches are the same as your example. For hundreds of entries memory efficiency isn't something that you should need to worry about.

Title: Python: remove complex multiline string

Body:
I have a file that contains a lot of different text that looks like:

Family number: 1
    Names: Bob, Linda, Dave
    Message: Some message here.

...

...with hundreds of entries.

Some of them looks like this:

Family number: 1
    Names: Bob, Linda,\
    \ Dave
    Message: Some message here.

This is due to some upstream formatting issues that is done by some other information gathering module that I cannot affect (or rather should not be fiddling with).

I would like the entries that look like the latter to look like the former.

From what I can gather, the pattern I want to remove occurs on multiple lines. My initial strategy is to search for the pattern

,\\n    \

and replace this with a ',' because I am not sure that there is some other place in the file that might have the pattern without the first comma.

Usually I do something like this:

for line in fileinput.input(['file.txt'], inplace=True):
    print(line.replace(',\\n    \',','), end='')

...but this only works for single lines. I also tried:

with open('file.txt', 'r') as in_file:
    with open('file.txt.tmp', 'w') as out_file:
       content = in_file.read()
       pattern = re.compile(r',\\n    \')
       to_be_printed = re.sub(pattern, ",", to_be_printed)
       out.write(to_be_printed)

This does not work and does not appear to be that memory efficient since it involves reading the entire file into memory.

Is there a way this can be done neatly?

Body:
import re
text =  open(path).read()

# Replace multiline delimited by \
pattern = r'\\\n+[ \t]*\\'
new_text = re.sub(pattern, ",", text)

# Replace 2+ commas in a row (if that's an issue)
pattern = r',{2,}'
new_text = re.sub(pattern, ",", new_text)

Will do the job providing all the matches are the same as your example. For hundreds of entries memory efficiency isn't something that you should need to worry about.


问:
Android Webview not triggering a href download file
I have added the Download Manager , but it is not triggering the download event , can any body help . When user goes to webview download option and click a link to download a file nothing happens. I have gone through many of the post in stackoverflow but nothing works for me.

```<code> public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

    // boolean thread_running = true;
    private static final String TAG = "MainActivity";
    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

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

        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.setWebViewClient(new MyAppWebViewClient(this));

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);
        webSettings.setDomStorageEnabled(true);

        // creating connection detector class instance
        cd = new ConnectionDetector(getApplicationContext());
        /**
         * Check Internet status button click event
         * */
        isInternetPresent = cd.isConnectingToInternet();
        // check for Internet status
        if (isInternetPresent) {
            // Internet Connection is Present
            // make HTTP requests
            mWebView.loadUrl("http://url");
        } else {
            // Internet connection is not present
            // Ask user to connect to Internet
            //showAlertDialog(MainActivity.this, "No Internet Connection",
            //"You don't have internet connection.", false);
            Toast.makeText(this, "No Internet connection, Please SwitchOn Connection", Toast.LENGTH_LONG).show();
            finish();
        }

    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    public class MyAppWebViewClient extends WebViewClient {

        private Context context;

        public MyAppWebViewClient(Context context) {
            this.context = context;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (!cd.isConnectingToInternet()) {

                //internet is not present
                Toast.makeText(getApplicationContext(), "Internet Stopped Working", Toast.LENGTH_SHORT).show();
                finish();
            }

            if(url.contains(".JPG")){

                DownloadManager mdDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));
                File destinationFile = new File(Environment.getExternalStorageDirectory(),getFileName(url));
                request.setDescription("Downloading ...");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationUri(Uri.fromFile(destinationFile));
                mdDownloadManager.enqueue(request);

                return true;

            }

            view.loadUrl(url);
            return true;
        }

        public String getFileName(String url) {
            String filenameWithoutExtension = "";
            filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
                    + ".jpg");
            return filenameWithoutExtension;
        }

    }
    }
</code>```

Can someone help me out here? The page loads without issue but the link to a image file in the HTML page is not working...

I am getting this following error when click on link

```<code> Writing exception to parcel
                                                                java.lang.SecurityException: No permission to write to /storage/emulated/0/1499148267411.jpg: Neither user 10109 nor current process has android.permission.WRITE_EXTERNAL_STORAGE.
                                                                    at android.app.ContextImpl.enforce(ContextImpl.java:1438)
                                                                    at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1470)
                                                                    at com.android.providers.downloads.DownloadProvider.checkFileUriDestination(DownloadProvider.java:724)
                                                                    at com.android.providers.downloads.DownloadProvider.insert(DownloadProvider.java:558)
                                                                    at android.content.ContentProvider$Transport.insert(ContentProvider.java:263)
                                                                    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:163)
                                                                    at android.os.Binder.execTransact(Binder.java:453)
</code>```

答:
add these two lines in your mainfest file </p>

```<code> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Body:
I have added the Download Manager , but it is not triggering the download event , can any body help . When user goes to webview download option and click a link to download a file nothing happens. I have gone through many of the post in stackoverflow but nothing works for me.

 public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

    // boolean thread_running = true;
    private static final String TAG = "MainActivity";
    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

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

        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.setWebViewClient(new MyAppWebViewClient(this));

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);
        webSettings.setDomStorageEnabled(true);

        // creating connection detector class instance
        cd = new ConnectionDetector(getApplicationContext());
        /**
         * Check Internet status button click event
         * */
        isInternetPresent = cd.isConnectingToInternet();
        // check for Internet status
        if (isInternetPresent) {
            // Internet Connection is Present
            // make HTTP requests
            mWebView.loadUrl("http://url");
        } else {
            // Internet connection is not present
            // Ask user to connect to Internet
            //showAlertDialog(MainActivity.this, "No Internet Connection",
            //"You don't have internet connection.", false);
            Toast.makeText(this, "No Internet connection, Please SwitchOn Connection", Toast.LENGTH_LONG).show();
            finish();
        }

    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    public class MyAppWebViewClient extends WebViewClient {

        private Context context;

        public MyAppWebViewClient(Context context) {
            this.context = context;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (!cd.isConnectingToInternet()) {

                //internet is not present
                Toast.makeText(getApplicationContext(), "Internet Stopped Working", Toast.LENGTH_SHORT).show();
                finish();
            }

            if(url.contains(".JPG")){

                DownloadManager mdDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));
                File destinationFile = new File(Environment.getExternalStorageDirectory(),getFileName(url));
                request.setDescription("Downloading ...");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationUri(Uri.fromFile(destinationFile));
                mdDownloadManager.enqueue(request);

                return true;

            }

            view.loadUrl(url);
            return true;
        }

        public String getFileName(String url) {
            String filenameWithoutExtension = "";
            filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
                    + ".jpg");
            return filenameWithoutExtension;
        }

    }
    }

Can someone help me out here? The page loads without issue but the link to a image file in the HTML page is not working...

I am getting this following error when click on link

 Writing exception to parcel
                                                                java.lang.SecurityException: No permission to write to /storage/emulated/0/1499148267411.jpg: Neither user 10109 nor current process has android.permission.WRITE_EXTERNAL_STORAGE.
                                                                    at android.app.ContextImpl.enforce(ContextImpl.java:1438)
                                                                    at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1470)
                                                                    at com.android.providers.downloads.DownloadProvider.checkFileUriDestination(DownloadProvider.java:724)
                                                                    at com.android.providers.downloads.DownloadProvider.insert(DownloadProvider.java:558)
                                                                    at android.content.ContentProvider$Transport.insert(ContentProvider.java:263)
                                                                    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:163)
                                                                    at android.os.Binder.execTransact(Binder.java:453)

Body:
add these two lines in your mainfest file

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


答:
It's ok to read entire file, since you're trying to catch a multiline occurence, hence re is ok option, if you ask me.

I assume, that you need some sort of this pattern. And as @jadsq mentioned in comment section - your mistake is incorrect escape for \ character!

Let's look what we can do with it:

```<code>import re

#   input block
input_data = r'''
Family number: 1
    Names: Bob, Linda,\
    \ Dave
    Message: Some message here.
'''
print('*** Input data: ***\n%s' % input_data)

#   re-place block
pattern = re.compile(r',\\\n\s+\\', re.M | re.I)
output_data = re.sub(pattern, ",", input_data)

#   output block
print('*** Output data: ***\n%s' % output_data)
</code>```

Output:

```<code>*** Input data: ***

Family number: 1
    Names: Bob, Linda,\
    \ Dave
    Message: Some message here.

*** Output data: ***

Family number: 1
    Names: Bob, Linda, Dave
    Message: Some message here.
</code>```

Explanation:

```<code>,                matches the character , literally.
\\               matches the character \ literally (another \ for eascape purpose).
\n               matches a line-feed (newline) character (to ensure that there is a newline).
\s+              matches any whitespace character (one or more).
\\               matches the character \ literally (another \ for eascape purpose).
</code>```

If you're stuck even with that - play on regex101 by yourself first, and if there's a problem - update your question with more data and add the regex tag to spawn some regex guru.

Some links:

regex101 - One of many regex site to play with

rexegg - Newbie-friendly regex site with common patterns

reginfo - Another great site about regex

Hope it helps!

Title: Python: remove complex multiline string

Body:
It's ok to read entire file, since you're trying to catch a multiline occurence, hence re is ok option, if you ask me.

I assume, that you need some sort of this pattern. And as @jadsq mentioned in comment section - your mistake is incorrect escape for \ character!

Let's look what we can do with it:

import re

#   input block
input_data = r'''
Family number: 1
    Names: Bob, Linda,\
    \ Dave
    Message: Some message here.
'''
print('*** Input data: ***\n%s' % input_data)

#   re-place block
pattern = re.compile(r',\\\n\s+\\', re.M | re.I)
output_data = re.sub(pattern, ",", input_data)

#   output block
print('*** Output data: ***\n%s' % output_data)

Output:

*** Input data: ***

Family number: 1
    Names: Bob, Linda,\
    \ Dave
    Message: Some message here.

*** Output data: ***

Family number: 1
    Names: Bob, Linda, Dave
    Message: Some message here.

Explanation:

,                matches the character , literally.
\\               matches the character \ literally (another \ for eascape purpose).
\n               matches a line-feed (newline) character (to ensure that there is a newline).
\s+              matches any whitespace character (one or more).
\\               matches the character \ literally (another \ for eascape purpose).

If you're stuck even with that - play on regex101 by yourself first, and if there's a problem - update your question with more data and add the regex tag to spawn some regex guru.

Some links:

regex101 - One of many regex site to play with

rexegg - Newbie-friendly regex site with common patterns

reginfo - Another great site about regex

Hope it helps!


问:
Use Upper-Case letter for the first and second characters of controller name Yii2
I am using Yii2 framework and based on some standards I have to customize my controller name.

As you know the standard for controller name in yii2 is like this:

If you name your controller like this :DServicesController, The route in pretty url for accessing this controller's actions is /d-services/[actionName].

But I want to name my controller in a way that I can access it like this in the url:

/DServices/[action name]

I added the following code to my urlManager rules but didn't work:

```<code>'urlManager' => [
    'rules' => [
        'manage/DServices/*' => 'manage/d-services/<action>'
     ],
]
</code>```

How can I name my controller class or define specific rule to access it like this.

P.S: As Yii2 standard the first letter of your controller name always changes to Lower-Case.

答:
Actually upper case letters works fine in Yii2 routing rules. But I see two strange things in Your snippet:

Asterisk in route template. Did You want to pass parameters this way?

manage/ prefix in action route. It will work if your controller is in manage module.

I tried to use Your template with these things fixed:

```<code>'urlManager' => [
    'rules' => [
        'manage/DServices' => 'd-services/<action>'
     ],
]
</code>```

and it works as expected.

See this section of Yii2 docs for details: http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html#routing

Body:
I am using Yii2 framework and based on some standards I have to customize my controller name.

As you know the standard for controller name in yii2 is like this:

If you name your controller like this :DServicesController, The route in pretty url for accessing this controller's actions is /d-services/[actionName].

But I want to name my controller in a way that I can access it like this in the url:

/DServices/[action name]

I added the following code to my urlManager rules but didn't work:

'urlManager' => [
    'rules' => [
        'manage/DServices/*' => 'manage/d-services/<action>'
     ],
]

How can I name my controller class or define specific rule to access it like this.

P.S: As Yii2 standard the first letter of your controller name always changes to Lower-Case.

Body:
Actually upper case letters works fine in Yii2 routing rules. But I see two strange things in Your snippet:

Asterisk in route template. Did You want to pass parameters this way?

manage/ prefix in action route. It will work if your controller is in manage module.

I tried to use Your template with these things fixed:

'urlManager' => [
    'rules' => [
        'manage/DServices' => 'd-services/<action>'
     ],
]

and it works as expected.

See this section of Yii2 docs for details: http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html#routing


问:
limit number of editors windows in STS (eclipse)
I know how to limit the number of editor windows in IntelliJ but I can't find the setting in STS (Eclipse).

Please advise as I want to set it to 1 editor window.

答: To limit the number of opened editor windows, go to Window -> Preferences -> General -> Editors. Select Close editors automatically and set the value of Number of opened editors before closing to 1, as shown below:


问:
Getting lmer output to word/excel
I am working in R, with a package called lme4.

Performing a model:

```<code>lmer.rasch <- lmer(Response ~ item -1 + (1|STIDSTD),family=binomial, data=exampledata)
</code>```

gets me output in the console as shown at the end of the post. I wanted to copy this, what appears to be a table, to excel, or ultimately word, recognising the separate columns and rows. Ctrl-C/Ctrl-V to excel does recognise the rows, yet not the columns.

Using write.csv(lmer.rasch) gives the error:

Error in as.data.frame.default(x[[i]], optional = TRUE) :    cannot
  coerce class 'structure("mer", package = "lme4")' into a data.frame

Is this a problem within the package, or just a general problem with me using the write function wrongly, or R not actually separating this output into columns?

```<code>    Fixed effects:
                        Estimate Std. Error z value Pr(>|z|)
    variableamoeba       -2.7529     0.3000  -9.175  < 2e-16 ***
    variablebacterium    -2.3937     0.2244 -10.668  < 2e-16 ***
    variableleech         0.5578     0.1693   3.294 0.000987 ***
    variablecentipede     1.7012     0.1909   8.911  < 2e-16 ***
    variablelizard       -4.1836     0.4090 -10.229  < 2e-16 ***
    variabletapeworm     -1.3697     0.1841  -7.439 1.01e-13 ***
    variablehead lice     1.1803     0.1777   6.643 3.07e-11 ***
    variablemaggot        0.8819     0.1740   5.068 4.03e-07 ***
    variableant           2.5971     0.2332  11.137  < 2e-16 ***
    variablemoth          2.5389     0.2305  11.016  < 2e-16 ***
    variablemosquito      4.1270     0.3984  10.359  < 2e-16 ***
    variableearthworm    -0.3113     0.1675  -1.858 0.063106 .
    variablecaterpillar   0.7278     0.1706   4.265 2.00e-05 ***
    variablescorpion     -3.1011     0.2748 -11.286  < 2e-16 ***
    variablesnail        -1.4499     0.1861  -7.791 6.66e-15 ***
    variablespider        0.4913     0.1681   2.923 0.003469 **
    variablegrasshopper   1.9167     0.1986   9.650  < 2e-16 ***
    variabledust mite     0.5767     0.1701   3.391 0.000696 ***
    variabletarantula    -0.7640     0.1734  -4.406 1.05e-05 ***
    variabletermite       1.8333     0.2007   9.136  < 2e-16 ***
    variablebat          -5.2427     0.6486  -8.083 6.33e-16 ***
    variablewasp          3.0696     0.2687  11.423  < 2e-16 ***
    variablesilkworm      1.1310     0.1792   6.313 2.74e-10 ***
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
</code>```

答:
This works form me (using lme4):</p>

```<code>    coeffs <- coef(summary(your.model)) # get estimates, etc...
    p <- pnorm(abs(coeffs[, "t value"]), lower.tail = FALSE) * 2 # add the much disputed p-values

    coeffsp <- cbind(coeffs, "p value" = round(p,3)) # combine it into one object
    write.csv(coeffsp, "coeffsp.csv") # export
</code>```

Title: Getting lmer output to word/excel

Body:
I am working in R, with a package called lme4.

Performing a model:

lmer.rasch <- lmer(Response ~ item -1 + (1|STIDSTD),family=binomial, data=exampledata)

gets me output in the console as shown at the end of the post. I wanted to copy this, what appears to be a table, to excel, or ultimately word, recognising the separate columns and rows. Ctrl-C/Ctrl-V to excel does recognise the rows, yet not the columns.

Using write.csv(lmer.rasch) gives the error:

Error in as.data.frame.default(x[[i]], optional = TRUE) :    cannot
  coerce class 'structure("mer", package = "lme4")' into a data.frame

Is this a problem within the package, or just a general problem with me using the write function wrongly, or R not actually separating this output into columns?

    Fixed effects:
                        Estimate Std. Error z value Pr(>|z|)
    variableamoeba       -2.7529     0.3000  -9.175  < 2e-16 ***
    variablebacterium    -2.3937     0.2244 -10.668  < 2e-16 ***
    variableleech         0.5578     0.1693   3.294 0.000987 ***
    variablecentipede     1.7012     0.1909   8.911  < 2e-16 ***
    variablelizard       -4.1836     0.4090 -10.229  < 2e-16 ***
    variabletapeworm     -1.3697     0.1841  -7.439 1.01e-13 ***
    variablehead lice     1.1803     0.1777   6.643 3.07e-11 ***
    variablemaggot        0.8819     0.1740   5.068 4.03e-07 ***
    variableant           2.5971     0.2332  11.137  < 2e-16 ***
    variablemoth          2.5389     0.2305  11.016  < 2e-16 ***
    variablemosquito      4.1270     0.3984  10.359  < 2e-16 ***
    variableearthworm    -0.3113     0.1675  -1.858 0.063106 .
    variablecaterpillar   0.7278     0.1706   4.265 2.00e-05 ***
    variablescorpion     -3.1011     0.2748 -11.286  < 2e-16 ***
    variablesnail        -1.4499     0.1861  -7.791 6.66e-15 ***
    variablespider        0.4913     0.1681   2.923 0.003469 **
    variablegrasshopper   1.9167     0.1986   9.650  < 2e-16 ***
    variabledust mite     0.5767     0.1701   3.391 0.000696 ***
    variabletarantula    -0.7640     0.1734  -4.406 1.05e-05 ***
    variabletermite       1.8333     0.2007   9.136  < 2e-16 ***
    variablebat          -5.2427     0.6486  -8.083 6.33e-16 ***
    variablewasp          3.0696     0.2687  11.423  < 2e-16 ***
    variablesilkworm      1.1310     0.1792   6.313 2.74e-10 ***
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Body:
This works form me (using lme4):

    coeffs <- coef(summary(your.model)) # get estimates, etc...
    p <- pnorm(abs(coeffs[, "t value"]), lower.tail = FALSE) * 2 # add the much disputed p-values

    coeffsp <- cbind(coeffs, "p value" = round(p,3)) # combine it into one object
    write.csv(coeffsp, "coeffsp.csv") # export


问:
Query to insert data in mysql table contains foreign key
I am very new to Mysql and dumping a file in db using python. I'm having 2 tables
The file format is:

```<code>id name sports
1 john baseball
2 mary Football
</code>```

like  student & Sports
Student table

```<code>id    name
 1     John
 2     Mary
</code>```

here id is primary key

& in sports table

```<code>stu_id sports_title

1      Baseball
2      Football
</code>```

and here stu_id is foreign key  reference with student table

and my problem is

```<code>query="insert into sports (stu_id,name)VALUES (%d,%s)"
            ("select id from student where id=%d,%s")
#words[0]=1 ,words[2]=Baseball

args=(words[0],words[2])
cursor.execute(query,args)
</code>```

upon executing this code, I'm facing

```<code>  "Not all parameters were used in the SQL statement")
ProgrammingError: Not all parameters were used in the SQL statement
</code>```

答:
You can't use both VALUES and SELECT as the source of the data in INSERT. You use VALUES if the data is literals, you use SELECT if you're getting it from another table. If it's a mix of both, you use SELECT and put the literals into the SELECT list.

```<code>query = """
    INSERT INTO sports (stu_id, sports_title)
    SELECT id, %s
    FROM student
    WHERE name = %s
"""
args = (words[2], words[1])
cursor.execute(args)
</code>```

Or, since the file contains the student ID, you don't need SELECT at all.

```<code>query = "INSERT INTO sports(stu_id, sports_title) VALUES (%d, %s)"
args = (words[0], words[1])
cursor.execute(args)
</code>```

Body:
I am very new to Mysql and dumping a file in db using python. I'm having 2 tables
The file format is:

id name sports
1 john baseball
2 mary Football

like  student & Sports
Student table

id    name
 1     John
 2     Mary

here id is primary key

& in sports table

stu_id sports_title

1      Baseball
2      Football

and here stu_id is foreign key  reference with student table

and my problem is

query="insert into sports (stu_id,name)VALUES (%d,%s)"
            ("select id from student where id=%d,%s")
#words[0]=1 ,words[2]=Baseball

args=(words[0],words[2])
cursor.execute(query,args)

upon executing this code, I'm facing

  "Not all parameters were used in the SQL statement")
ProgrammingError: Not all parameters were used in the SQL statement

Body:
You can't use both VALUES and SELECT as the source of the data in INSERT. You use VALUES if the data is literals, you use SELECT if you're getting it from another table. If it's a mix of both, you use SELECT and put the literals into the SELECT list.

query = """
    INSERT INTO sports (stu_id, sports_title)
    SELECT id, %s
    FROM student
    WHERE name = %s
"""
args = (words[2], words[1])
cursor.execute(args)

Or, since the file contains the student ID, you don't need SELECT at all.

query = "INSERT INTO sports(stu_id, sports_title) VALUES (%d, %s)"
args = (words[0], words[1])
cursor.execute(args)


问:
SourceTree very slow with many repositories
I work on a lot of small projects on daily basis and need to switch often.

I have over 50 Git Repositories in Sourcetree.

Usually 5 projects are open in "Tabs".

Switching from "Tab" in SourceTree is very slow. Sometimes up to 15 seconds. How can I improve this behaviour?

答:
Latest version currently 2.1.2.5 released June 2017 was running dog slow for me even after trying all the answers here prior to today (even with just 1 project).

Apparently, .gitconfig was written to a network drive (H:) when SourceTree was first installed. This is what got the performance to instantaneous for me:

Move .gitconfig to local SSD (C:)

Set HOME variable. In Environment Variables (specifically User variable), set HOME to the value of C: (or whatever other path you decide to set).


问:
Setting the last value of each matrix in a cell array in Matlab
I have a cell array where each cell contains a matrix of identical size. How do I efficiently set the last entry of each matrix in the array? I was trying to make use of cellfun but it doesn't look like assignment is possible.

Minimal working example (the most efficient implementation I could come up with):

```<code>C = cell(5, 6, 7);
[C{:}] = deal(ones(10, 1));
for i = 1:5
    for j = 1:6
        for k = 1:7
            C{i,j,k}(end) = 0;
        end
    end
end
</code>```

答:
Option 1

Create a function (e.g. in a separate file)

```<code>function x = assignAtEnd(x, v)
  x(end) = v;
end
</code>```

and perform cellfun as follows

```<code>B = cellfun(@(x) assignAtEnd(x, 0), C, 'UniformOutput', false);
</code>```

This will give you a B cell array with all the values at the end changed to 0.

However, I do not think this is a lot faster than the for loop. It might, in fact, be slower. I did a test with 1.000.000 cell elements (100, 100, 100), and the result on my machine was the following

```<code>for-loop (3D): 3.48 sec
for-loop (1D as per @mikkola): 2.67 sec
cellfun: 3.06 sec
</code>```

Option 2

If each cell contains a matrix of identical size and your application is time critical, it turns out it is faster to convert the cell array to a numeric array, do the operation, and convert it back to a cell array.

```<code>% creating the cell
cellDim = 100;
matrixDim = 10;
C = cell(cellDim, cellDim, cellDim);
[C{:}] = deal(1:matrixDim);

% converting to a 4D numeric matrix
A = reshape(cell2mat(C), cellDim, matrixDim, cellDim, cellDim);
% assigning the 0s
A(:,end,:,:) = 0;
% converting back to a cell
B = squeeze(num2cell(A, 2));
</code>```

In fact, the last line of converting back to a cell takes most of the time. The operation in total takes

```<code>with numeric conversion: 1.93 sec
</code>```

However, 1.40 sec out of this is taken for conversion back to a cell array, therefore your operation takes only 0.5 sec, 5 times faster!

For completeness, I also did a time test on @LuisMendo's great answer, and the result is

```<code>with numeric conversion (@LuisMendo): 1.66 sec
</code>```

Takeaway message

Avoid cell arrays if you have data of same dimensions! Use numeric arrays of higher dimensions.

Body:
I have a cell array where each cell contains a matrix of identical size. How do I efficiently set the last entry of each matrix in the array? I was trying to make use of cellfun but it doesn't look like assignment is possible.

Minimal working example (the most efficient implementation I could come up with):

C = cell(5, 6, 7);
[C{:}] = deal(ones(10, 1));
for i = 1:5
    for j = 1:6
        for k = 1:7
            C{i,j,k}(end) = 0;
        end
    end
end

Body:
Option 1

Create a function (e.g. in a separate file)

function x = assignAtEnd(x, v)
  x(end) = v;
end

and perform cellfun as follows

B = cellfun(@(x) assignAtEnd(x, 0), C, 'UniformOutput', false);

This will give you a B cell array with all the values at the end changed to 0.

However, I do not think this is a lot faster than the for loop. It might, in fact, be slower. I did a test with 1.000.000 cell elements (100, 100, 100), and the result on my machine was the following

for-loop (3D): 3.48 sec
for-loop (1D as per @mikkola): 2.67 sec
cellfun: 3.06 sec

Option 2

If each cell contains a matrix of identical size and your application is time critical, it turns out it is faster to convert the cell array to a numeric array, do the operation, and convert it back to a cell array.

% creating the cell
cellDim = 100;
matrixDim = 10;
C = cell(cellDim, cellDim, cellDim);
[C{:}] = deal(1:matrixDim);

% converting to a 4D numeric matrix
A = reshape(cell2mat(C), cellDim, matrixDim, cellDim, cellDim);
% assigning the 0s
A(:,end,:,:) = 0;
% converting back to a cell
B = squeeze(num2cell(A, 2));

In fact, the last line of converting back to a cell takes most of the time. The operation in total takes

with numeric conversion: 1.93 sec

However, 1.40 sec out of this is taken for conversion back to a cell array, therefore your operation takes only 0.5 sec, 5 times faster!

For completeness, I also did a time test on @LuisMendo's great answer, and the result is

with numeric conversion (@LuisMendo): 1.66 sec

Takeaway message

Avoid cell arrays if you have data of same dimensions! Use numeric arrays of higher dimensions.


问:
Global hotkeys in WPF?
I've build a WPF application and want to add global hotkey support.
I want to be able to execute a method in my application from anywhere in windows, even when my application is minimized or running in tray. For example, execute the method with ctrl + alt + t.

Is this possible in WPF, and if so, how?

答: You need to take a look at RegisterHotKey in user32.dll. Here's a good example at pinvoke.net: http://www.pinvoke.net/default.aspx/user32/RegisterHotKey.html</p>

Title: Global hotkeys in WPF?