问:
Git: with uncommited work, how to make changes in another branch and come back?
My team is using a very simple Git workflow. Everybody develops in the same branch. I'd like to know which are the series of commands I should do when I'm in the middle of the work and need to fix a bug.

Here is my situation:

Unpushed commited changes in my local master branch

Uncommited modified files

need to fix a bug in origin/master branch

I don't have another branch attached to master

need to push just these files that fix the problem

go back to work

Se that I'm working in the same branch of my coworkers.

Some users pointed that git stash would solve it and so this is a duplicate question. I dispute it, since I didn't even know that this feature existed. The feature solves my problem, but I believe the question is valid since I ask it from another point of view.

答:
Other answers have used git stash, which I agree is the standard technique, but here's another which "simulates" a stash (and has a backup since stashes aren't saved in your reflog; plus your main branch will not have your untracked files).

Here are the steps you should do:

```<code>1. git add .; git commit -m "All files saved" // commit your work in current branch
2. git checkout main // go to main branch
3. git add .; git commit -m "Finished fixing bug" // fix bug and commit
4. git push remote main // push your main branch to remote; do a fetch and merge, etc if needed
5. git checkout my_branch // come back to your branch
6. git reset HEAD^ // go back from your dummy commit
</code>```

This will also save your untracked files.

Alternatively, use git stash -u, which also stashes untracked files.

Body:
Other answers have used git stash, which I agree is the standard technique, but here's another which "simulates" a stash (and has a backup since stashes aren't saved in your reflog; plus your main branch will not have your untracked files).

Here are the steps you should do:

1. git add .; git commit -m "All files saved" // commit your work in current branch
2. git checkout main // go to main branch
3. git add .; git commit -m "Finished fixing bug" // fix bug and commit
4. git push remote main // push your main branch to remote; do a fetch and merge, etc if needed
5. git checkout my_branch // come back to your branch
6. git reset HEAD^ // go back from your dummy commit

This will also save your untracked files.

Alternatively, use git stash -u, which also stashes untracked files.


来源: stackexchange

问:
Abstract types and type inference
Suppose I have a module that hides some type:

```<code>module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end
</code>```

And I also have a function that operates on optioms:

```<code>let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"
</code>```

Not surprisingly, when I call do_work on t instance I get a type error:

```<code>let () =
  do_work @@ Test.make_t ()
</code>```

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

答:
In addition to the good answers already present here, if you only care whether something is Some _ or None, you can add this to your interface:

```<code>module Test : sig
  type t
  val make_t : unit -> t
  val is_some : t -> bool
end = struct
  type t = int option
  let make_t () = Some 42
  let is_some = Option.is_some
end
</code>```

(of course you can rename is_some to something that matches your abstraction)

ContentLicense: CC BY-SA 4.0

Title: Abstract types and type inference

Body:
Suppose I have a module that hides some type:

module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end

And I also have a function that operates on optioms:

let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"

Not surprisingly, when I call do_work on t instance I get a type error:

let () =
  do_work @@ Test.make_t ()

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

Body:
In addition to the good answers already present here, if you only care whether something is Some _ or None, you can add this to your interface:

module Test : sig
  type t
  val make_t : unit -> t
  val is_some : t -> bool
end = struct
  type t = int option
  let make_t () = Some 42
  let is_some = Option.is_some
end

(of course you can rename is_some to something that matches your abstraction)


问:
Java - access to variable within inner class or assign a value to final variable
I need to create several buttons and upload files. So I want to create a function to set these buttons. However, I'm getting a compilation error inside of my setNewButton.

My code is shown as below:

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format, File file) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                file = selectedFile;  // compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }
}
```

<p>The error is: <code>Variable file is accessed from within inner class, needs to be declared final</code></p>

<p>I have checked some similar questions in stackoverflow. I know <code>file</code> has to be final like <code>label</code> and <code>fileName</code> here.</p>

<p>However <code>file</code> here could be <code>final</code> since I would like to assign <code>selectedFile</code> to it.</p>

<p>I would like to know if there is any walkaround for this problem.</p>

<p>Any help would be appreciated. :)</p>

<p>Thanks to @M. Prokhorov and @Chang Liu.
According to  JLS 8.1.3. Inner Classes and Enclosing Instances</p>

<blockquote>
  <p>Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.</p>
</blockquote>

<p>So when I tried to send a parameter <code>file</code> inside <code>FileSlectionListener</code>, there will be a compile error. However, the member <code>file1</code> inside Solution is not local variable, so if I delete the <code>file</code> from my method, there will be no error. So @talex 's anwser is right in this case.</p>

<p>However since my problem is to find a method to pass a <code>File</code> to inner class and assign the variable with <code>selectedFile</code>, I couldn't find a way for it. My workaround is based on @Chang Liu's answer.</p>

<p>My revised code is as below:</p>

<pre class="lang-java prettyprint-override"><code>public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                setFile(selectedFile, fileName);  // no compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }

    private void setFile(File file, String fileName) {
        switch (fileName) {
            case FILE_NAME_1:
                sollFile = file;
                break;
            default:
                throw new AssertionError("Unknown File");
        }
    }
}
</code>```

Still, welcome to give me any advise if you have a better answer. :)

答:
You can create yourself a mutable wrapper class for the file:

```<code>public class FileWrapper {

    /** The file. */
    private File file;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }
}
</code>```

Then you can use a final instance of that class:

```<code>final private FileWrapper fileWrapper = new FileWrapper();

// ...

selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
        @Override
        protected void setSelection(File selectedFile) {
            fileWrapper.setFile(selectedFile);
            label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
        }
    });
</code>```

And get the last selected file by calling fileWrapper.getFile() outside of your inner class.

ContentLicense: CC BY-SA 3.0

Body:
I need to create several buttons and upload files. So I want to create a function to set these buttons. However, I'm getting a compilation error inside of my setNewButton.

My code is shown as below:

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format, File file) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                file = selectedFile;  // compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }
}

The error is: Variable file is accessed from within inner class, needs to be declared final

I have checked some similar questions in stackoverflow. I know file has to be final like label and fileName here.

However file here could be final since I would like to assign selectedFile to it.

I would like to know if there is any walkaround for this problem.

Any help would be appreciated. :)

Thanks to @M. Prokhorov and @Chang Liu.
According to  JLS 8.1.3. Inner Classes and Enclosing Instances

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.

So when I tried to send a parameter file inside FileSlectionListener, there will be a compile error. However, the member file1 inside Solution is not local variable, so if I delete the file from my method, there will be no error. So @talex 's anwser is right in this case.

However since my problem is to find a method to pass a File to inner class and assign the variable with selectedFile, I couldn't find a way for it. My workaround is based on @Chang Liu's answer.

My revised code is as below:

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                setFile(selectedFile, fileName);  // no compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }

    private void setFile(File file, String fileName) {
        switch (fileName) {
            case FILE_NAME_1:
                sollFile = file;
                break;
            default:
                throw new AssertionError("Unknown File");
        }
    }
}

Still, welcome to give me any advise if you have a better answer. :)

Body:
You can create yourself a mutable wrapper class for the file:

public class FileWrapper {

    /** The file. */
    private File file;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }
}

Then you can use a final instance of that class:

final private FileWrapper fileWrapper = new FileWrapper();

// ...

selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
        @Override
        protected void setSelection(File selectedFile) {
            fileWrapper.setFile(selectedFile);
            label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
        }
    });

And get the last selected file by calling fileWrapper.getFile() outside of your inner class.


问:
Manage dynamic routes with AngularJS
I have an AngularJS app (Angular v1) that is all working with a secure login. Users not authenticated can can only see the login page, the forgotten password page and the cookie policy.

I am using ngRoute like this:

```<code>    $routeProvider
    .when('/login:param', {
        templateUrl: 'app/login/login.html',
        controller: 'loginCtrl',
        controllerAs: 'vm'
    })

    /* ... other routes ... */

    .otherwise({
        redirectTo: '/login'
    });
</code>```

Now, I would like to redirect the users to dashboard if they are logged in without the ability to see all the "public routes" (== routes that users can see without authentication); and redirect them to the login page if they are not logged in.

To do so, I am performing a check in Angular run function and listening to the $locationChangeStart event:

```<code>    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        if (routeClean($location.path()) && AuthenticationService.isLoggedIn()) {
            $location.url(DASHBOARD);
        } else {
            $location.url(LOGIN);
        }
    });
</code>```

where DASHBOARD is a constant that contains the route to /dashboard and LOGIN is a constant that contains the route to /login.

Before proceeding, I have a couple of questions:

is run the correct place to perform this check? (even if it is working, maybe this check should be placed elsewhere)

what is the best practice to achieve this?

In this check, AuthenticationService is a service that is authenticating the users, whilst routeClean is a function that is checking if the route is inside an array:

```<code>    var routeClean = function (route) {
        for (var i = 0; i < CLEAN_ROUTES.length; i++) {
            var pattern = new RegExp(CLEAN_ROUTES[i]);
            var bool = pattern.test(route);
            if (bool)
                return true;
        }
        return false;
    };
</code>```

Where CLEAN_ROUTES is an array where there are all the "public routes".

```<code>    CLEAN_ROUTES = [
        '/login',
        '/forgotten-password',
        '/verify-code',
        '/reset-password',
        '/cookie-policy'
    ]
</code>```

So, here the final questions:

Is there a smarter way to check the "public routes" with Angular?

If, for example, I want to show a different login template for the users, something like:

```<code>/login?user=client
/login?user=seller
/login?user=editor
/login?user=admin
</code>```

is there a way where ngRoute can do that dynamically?

What I mean with this latest question is: if, for example, when the users log out the app, I redirect them to the LOGIN constant (that is the general route for the login page /login), is there a way where I can differentiate the seller, the client, etc so I can redirect them to the proper login template/page?

答:
IMO $httpProvider.interceptors is the most efficient way.

In ngRoute you can use -

$routeProvider -> 'route' -> resolve property

Title: Manage dynamic routes with AngularJS

Body:
I have an AngularJS app (Angular v1) that is all working with a secure login. Users not authenticated can can only see the login page, the forgotten password page and the cookie policy.

I am using ngRoute like this:

    $routeProvider
    .when('/login:param', {
        templateUrl: 'app/login/login.html',
        controller: 'loginCtrl',
        controllerAs: 'vm'
    })

    /* ... other routes ... */

    .otherwise({
        redirectTo: '/login'
    });

Now, I would like to redirect the users to dashboard if they are logged in without the ability to see all the "public routes" (== routes that users can see without authentication); and redirect them to the login page if they are not logged in.

To do so, I am performing a check in Angular run function and listening to the $locationChangeStart event:

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        if (routeClean($location.path()) && AuthenticationService.isLoggedIn()) {
            $location.url(DASHBOARD);
        } else {
            $location.url(LOGIN);
        }
    });

where DASHBOARD is a constant that contains the route to /dashboard and LOGIN is a constant that contains the route to /login.

Before proceeding, I have a couple of questions:

is run the correct place to perform this check? (even if it is working, maybe this check should be placed elsewhere)

what is the best practice to achieve this?

In this check, AuthenticationService is a service that is authenticating the users, whilst routeClean is a function that is checking if the route is inside an array:

    var routeClean = function (route) {
        for (var i = 0; i < CLEAN_ROUTES.length; i++) {
            var pattern = new RegExp(CLEAN_ROUTES[i]);
            var bool = pattern.test(route);
            if (bool)
                return true;
        }
        return false;
    };

Where CLEAN_ROUTES is an array where there are all the "public routes".

    CLEAN_ROUTES = [
        '/login',
        '/forgotten-password',
        '/verify-code',
        '/reset-password',
        '/cookie-policy'
    ]

So, here the final questions:

Is there a smarter way to check the "public routes" with Angular?

If, for example, I want to show a different login template for the users, something like:

/login?user=client
/login?user=seller
/login?user=editor
/login?user=admin

is there a way where ngRoute can do that dynamically?

What I mean with this latest question is: if, for example, when the users log out the app, I redirect them to the LOGIN constant (that is the general route for the login page /login), is there a way where I can differentiate the seller, the client, etc so I can redirect them to the proper login template/page?


问:
Detect OpenFileDialog
For a very peculiar requirement of a DLP software, I'm trying to detect OpenFileDialogs and cancel the file selection action, after capturing the selected file.

How am I trying to do this?

I put a global hook on the mouse and keyboard. I detect all actions that the user can perform to select a file in the OpenFileDialog window.

What I could not do until now is to detect if the window is an OpenFileDialog by hwnd.

Why am I trying this way?

I am a high level programmer and tried initially with windows hooks, without success. I tried with easyhook and deviare2. There seems to be no simpler way to put a global hook in a COM (IFileDialog) component call.

Is there any way to detect if a window is the default Windows OpenFileDialog window by hwnd?

```<code>public bool IsOpenFileDialog(IntPtr hwnd)
{
    return ?
}
</code>```

答:
As a partial solution (an adversary can mimic such a dialog), I suggest checking if the window a standard dialog and if it is, does it have "Save" in the caption (you can well put a better ctriterium here):

First, let's check class:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms633574(v=vs.85).aspx

```<code> using System.Runtime.InteropServices;

 ...

 [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  private static extern int GetClassName(IntPtr hWnd,
    StringBuilder lpClassName,
    int nMaxCount);

  private static String WndClassName(IntPtr handle) {
    int length = 1024;

    StringBuilder sb = new StringBuilder(length);

    GetClassName(handle, sb, length);

    return sb.ToString();
  }

  public static bool IsDialogClassName(IntPtr handle) {
    // Standard windows dialogs like OpenFileDialog, SaveFileDialog have #32770 class name
    return "#32770".Equals(WndClassName(handle));
  }
</code>```

However, it's too wide criterium: both Save File Dialog and Open File Dialog pass it. Let's check window's caption:

```<code>  [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
   private static extern int GetWindowTextLength(IntPtr hWnd);

  [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
   static extern int GetWindowText(IntPtr hWnd,
     StringBuilder text,
     int length);

   private static String WindowText(IntPtr handle) {
     int length = GetWindowTextLength(handle);

     StringBuilder sb = new StringBuilder(length + 1);

     GetWindowText(handle, sb, length + 1);

     return sb.ToString();
   }

   public static bool IsSaveCaption(IntPtr handle) {
     //TODO: put a better check for dialog's caption here
     return WindowText(handle).IndexOf("Save", StringComparison.OrdinalIgnoreCase) >= 0;
   }
</code>```

Finally:

```<code>  public bool IsOpenFileDialog(IntPtr hwnd) {
    return IsDialogClassName(hwnd) &&
           !IsSaveCaption(hwnd);
  }
</code>```

Sure you may want some other criteria, but I hope these two will be enough

Title: Detect OpenFileDialog

Body:
For a very peculiar requirement of a DLP software, I'm trying to detect OpenFileDialogs and cancel the file selection action, after capturing the selected file.

How am I trying to do this?

I put a global hook on the mouse and keyboard. I detect all actions that the user can perform to select a file in the OpenFileDialog window.

What I could not do until now is to detect if the window is an OpenFileDialog by hwnd.

Why am I trying this way?

I am a high level programmer and tried initially with windows hooks, without success. I tried with easyhook and deviare2. There seems to be no simpler way to put a global hook in a COM (IFileDialog) component call.

Is there any way to detect if a window is the default Windows OpenFileDialog window by hwnd?

public bool IsOpenFileDialog(IntPtr hwnd)
{
    return ?
}

Body:
As a partial solution (an adversary can mimic such a dialog), I suggest checking if the window a standard dialog and if it is, does it have "Save" in the caption (you can well put a better ctriterium here):

First, let's check class:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms633574(v=vs.85).aspx

 using System.Runtime.InteropServices;

 ...

 [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  private static extern int GetClassName(IntPtr hWnd,
    StringBuilder lpClassName,
    int nMaxCount);

  private static String WndClassName(IntPtr handle) {
    int length = 1024;

    StringBuilder sb = new StringBuilder(length);

    GetClassName(handle, sb, length);

    return sb.ToString();
  }

  public static bool IsDialogClassName(IntPtr handle) {
    // Standard windows dialogs like OpenFileDialog, SaveFileDialog have #32770 class name
    return "#32770".Equals(WndClassName(handle));
  }

However, it's too wide criterium: both Save File Dialog and Open File Dialog pass it. Let's check window's caption:

  [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
   private static extern int GetWindowTextLength(IntPtr hWnd);

  [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
   static extern int GetWindowText(IntPtr hWnd,
     StringBuilder text,
     int length);

   private static String WindowText(IntPtr handle) {
     int length = GetWindowTextLength(handle);

     StringBuilder sb = new StringBuilder(length + 1);

     GetWindowText(handle, sb, length + 1);

     return sb.ToString();
   }

   public static bool IsSaveCaption(IntPtr handle) {
     //TODO: put a better check for dialog's caption here
     return WindowText(handle).IndexOf("Save", StringComparison.OrdinalIgnoreCase) >= 0;
   }

Finally:

  public bool IsOpenFileDialog(IntPtr hwnd) {
    return IsDialogClassName(hwnd) &&
           !IsSaveCaption(hwnd);
  }

Sure you may want some other criteria, but I hope these two will be enough


问:
laravel in subdirectory but route points to parent directory
i have a problem in laravel route i don't know how to fix it!

well first of all i should say my webserver is lighttpd and there's no way to change it to nginx or apache if you want to say use another webserver... :D

well, my project was in "/path/to/some-where/htdocs" and my domain was "example.com"

and in "lighttpd.conf" i pointed "example.com" to "/path/to/some-where/htdocs/public/" and everything worked well and laravel worked fine, but because of some reasons i made some changes cause we needed "example.com" domain for some other projects

i moved project to "foo" subdirectory so now my project path is "/path/to/some-where/htdocs/foo/" and also i made some changes in lighttpd and pointed "example.com/foo" to "/path/to/some-where/htdocs/foo/public/"

also i changed APP_URI in .env to "http://example.com/foo"
but when i open "example.com/foo" it shows me "route not found" error, laravel it's working but it doesn't recognize "/foo" as base directory and when i put all of routes in a route group with "foo" prefix it works fine!

for testing i made these routes

```<code>    Route::get("/", function(}{return "sweet home!";));
    Route::get("/{slug}", function($slug}{return $slug;));
</code>```

when i open "example.com/foo" it should show me "sweet home" but instead, it shows me "foo" cause as i said laravel doesn't recognize "foo" as base directory
it seems i should change base directory or base uri of project but i couldn't find anything

as i said i changed APP_URI, and also i put

```<code>    RewriteBase /foo/
</code>```

in .htacess but no result!

答:
You should prefix your routes this way :</p>

```<code>Route::group(['prefix' => 'foo'], function() {
   Route::get("/", function(}{return "sweet home!";));
   Route::get("/{slug}", function($slug}{return $slug;));
});
</code>```

Body:
i have a problem in laravel route i don't know how to fix it!

well first of all i should say my webserver is lighttpd and there's no way to change it to nginx or apache if you want to say use another webserver... :D

well, my project was in "/path/to/some-where/htdocs" and my domain was "example.com"

and in "lighttpd.conf" i pointed "example.com" to "/path/to/some-where/htdocs/public/" and everything worked well and laravel worked fine, but because of some reasons i made some changes cause we needed "example.com" domain for some other projects

i moved project to "foo" subdirectory so now my project path is "/path/to/some-where/htdocs/foo/" and also i made some changes in lighttpd and pointed "example.com/foo" to "/path/to/some-where/htdocs/foo/public/"

also i changed APP_URI in .env to "http://example.com/foo"
but when i open "example.com/foo" it shows me "route not found" error, laravel it's working but it doesn't recognize "/foo" as base directory and when i put all of routes in a route group with "foo" prefix it works fine!

for testing i made these routes

    Route::get("/", function(}{return "sweet home!";));
    Route::get("/{slug}", function($slug}{return $slug;));

when i open "example.com/foo" it should show me "sweet home" but instead, it shows me "foo" cause as i said laravel doesn't recognize "foo" as base directory
it seems i should change base directory or base uri of project but i couldn't find anything

as i said i changed APP_URI, and also i put

    RewriteBase /foo/

in .htacess but no result!

Body:
You should prefix your routes this way :

Route::group(['prefix' => 'foo'], function() {
   Route::get("/", function(}{return "sweet home!";));
   Route::get("/{slug}", function($slug}{return $slug;));
});


问:
Custom URL in the entries wordpress
Currently when creating an entry in this wordpres the URL is :

http://www.sitio.com/entrada1

But you could customize it so that it reads:

http://www.sitio.com/blogs/entrada1

PS : Making it does not affect my other URLs Custom Post Type Created or Pages, only want to change the default entries for wordpress

Thank you

答:
Add following code at the end of your theme functions.php file. If your theme functions.php file has ?> at the end then paste the code just before ?> Otherwise just paste it. After that update permalink from wordpress admin.</p>

```<code>    /**
     * Add new rewrite rule
     */
    function create_new_url_querystring() {
        add_rewrite_rule(
            'blog/([^/]*)$',
            'index.php?name=$matches[1]',
            'top'
        );
        add_rewrite_tag('%blog%','([^/]*)');
    }
    add_action('init', 'create_new_url_querystring', 999 );
    /**
     * Modify post link
     * This will print /blog/post-name instead of /post-name
     */
    function append_query_string( $url, $post, $leavename ) {
        if ( $post->post_type == 'post' ) {
            $url = home_url( user_trailingslashit( "blog/$post->post_name" ) );
        }
        return $url;
    }
    add_filter( 'post_link', 'append_query_string', 10, 3 );
    /**
     * Redirect all posts to new url
     * If you get error 'Too many redirects' or 'Redirect loop', then delete everything below
     */
    function redirect_old_urls() {
        if ( is_singular('post') ) {
            global $post;
            if ( strpos( $_SERVER['REQUEST_URI'], '/blog/') === false) {
               wp_redirect( home_url( user_trailingslashit( "blog/$post->post_name" ) ), 301 );
               exit();
            }
        }
    }
    add_filter( 'template_redirect', 'redirect_old_urls' );
</code>```

Title: Custom URL in the entries wordpress

Body:
Add following code at the end of your theme functions.php file. If your theme functions.php file has ?> at the end then paste the code just before ?> Otherwise just paste it. After that update permalink from wordpress admin.

    /**
     * Add new rewrite rule
     */
    function create_new_url_querystring() {
        add_rewrite_rule(
            'blog/([^/]*)$',
            'index.php?name=$matches[1]',
            'top'
        );
        add_rewrite_tag('%blog%','([^/]*)');
    }
    add_action('init', 'create_new_url_querystring', 999 );
    /**
     * Modify post link
     * This will print /blog/post-name instead of /post-name
     */
    function append_query_string( $url, $post, $leavename ) {
        if ( $post->post_type == 'post' ) {
            $url = home_url( user_trailingslashit( "blog/$post->post_name" ) );
        }
        return $url;
    }
    add_filter( 'post_link', 'append_query_string', 10, 3 );
    /**
     * Redirect all posts to new url
     * If you get error 'Too many redirects' or 'Redirect loop', then delete everything below
     */
    function redirect_old_urls() {
        if ( is_singular('post') ) {
            global $post;
            if ( strpos( $_SERVER['REQUEST_URI'], '/blog/') === false) {
               wp_redirect( home_url( user_trailingslashit( "blog/$post->post_name" ) ), 301 );
               exit();
            }
        }
    }
    add_filter( 'template_redirect', 'redirect_old_urls' );


问:
Post Increment and assigning to same variable
```<code>int b = 2;

c= b++;
System.out.Println("C :"+c+"B"+b);
</code>```

c will be 2 and b will be 3.

```<code>int b = 2;

b= b++;
System.out.Println("B:"+b);
</code>```

Here I wonder what is getting incremented. and where does that incremented value goes.

答:
```<code>int b=2
b = b++
</code>```

Is like you are running this code

```<code>int b = 2;
int temp = b;
b = b + 1;
b = temp;
</code>```

Body:
int b = 2;

c= b++;
System.out.Println("C :"+c+"B"+b);

c will be 2 and b will be 3.

int b = 2;

b= b++;
System.out.Println("B:"+b);

Here I wonder what is getting incremented. and where does that incremented value goes.

Body:
int b=2
b = b++

Is like you are running this code

int b = 2;
int temp = b;
b = b + 1;
b = temp;


问:
Full code completion with inline resources
When I have inline stylesheet tag  in a file, code completion shows only the specific styles that are defined in the file.

If I delete this style section the code completion will work fine and shows all the external resources(i.e bootstrap styles,...).

Is it possible to have all external and inline resources at the same time?

答: Not currently possible, please vote for WEB-2223 ans linked tickets</p>


问:
visual studio 13 ssrs expression builder seems disabled
Can anyone tell me why the expression builder seems disabled and how to fix it?

答: Reinstalling VS seemed to be the only fix.</p>


问:
How can i get display column value in sql

This is the output of the query "select * from FindNthHighestNumber order by ProductAmount desc"

I want the individual value of bordered green portion of the above image. How can i do that? something like row = '2'

答:
```<code>Select *,Row_number(PARTITION BY ID ORDER BY (SELECT NULL)) from  Table
</code>```


问:
How to differentiate multiple GUI?
My GUI brings up other GUIs once a button is pressed (works correctly).

But when I interact with the pop-up GUI, the main GUI reacts as well (an embedded IE browser; when it receives input it messes everything up). Here is the code:

```<code>#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <StaticConstants.au3>
#include <ComboConstants.au3>
#include <WinHttp.au3>
#include <IE.au3>
#include <GUIConstantsEx.au3>
#include <GuiEdit.au3>
#include <WinAPIFiles.au3>
#include <ImageSearch2015.au3>

Opt('SendKeyDelay', Random(16, 80)); default 5. higher number = slower
Global $nameInfo = IniRead('Userinfo.ini', 'Name', 'Name', 'No username on file')
Global $passInfo = IniRead('Userinfo.ini', 'Pass', 'Pass', 'No password on file')
Global $slpMed = Random(2000, 2500)
Global $slpLow = Random(100, 350)
;Not in use ATM, will be used in future builds.
Global $en = '....' ;Need to find out how to login through world #
Global $mainUrl = 'https://' & $en & '.******'
Global $testUrl = 'https://*********'

Main_GUI()

Func Main_GUI()
    AutoItSetOption("MouseCoordMode", 0)
    $EzTw = GUICreate("Ez Tw", 885, 513, -1, -1)
    GUISetBkColor(0xA0A0A0)
    $Username = GUICtrlCreateInput($nameInfo, 8, 32, 105, 21)
    GUICtrlSetBkColor(-1, 0xFFFFFF)
    $Password = GUICtrlCreateInput($passInfo, 120, 32, 105, 21)
    GUICtrlSetBkColor(-1, 0xFFFFFF)
    $LogBtn = GUICtrlCreateButton("Login", 24, 56, 75, 17)
    GUICtrlSetBkColor(-1, 0xFFFFFF)
    $UserT = GUICtrlCreateLabel("User name", 40, 8, 55, 17)
    $PassT = GUICtrlCreateLabel("Password", 144, 8, 50, 17)
    $SaveBtn = GUICtrlCreateButton("Save Info", 136, 56, 75, 17)
    GUICtrlSetBkColor(-1, 0xFFFFFF)
    $Group1 = GUICtrlCreateGroup("Group1", -16, -40, 257, 129)
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    $Group2 = GUICtrlCreateGroup("Group2", 240, -16, 265, 105)
    $btnAxeLc = GUICtrlCreateButton("Axe/LC", 248, 32, 75, 17)
    $btnLcHc = GUICtrlCreateButton("Lc/Hc", 248, 8, 75, 17)
    $btnSpHc = GUICtrlCreateButton("Sp/Hc", 248, 56, 75, 17)
    $btnSwAc = GUICtrlCreateButton("Sw/Ac", 336, 8, 75, 17)
    $btnAxe = GUICtrlCreateButton("Axe Only", 336, 32, 75, 17)
    $btnSpear = GUICtrlCreateButton("Spear Only", 336, 56, 75, 17)
    $btnArcher = GUICtrlCreateButton("Archer Only", 424, 8, 75, 17)
    $btnSword = GUICtrlCreateButton("Sword Only", 424, 32, 75, 17)
    $btnMounted = GUICtrlCreateButton("MA Only", 424, 56, 75, 17)
    Global $ie = _IECreateEmbedded()
    Global $inIW = GUICtrlCreateObj($ie, 10, 100, 865, 405)
    With $ie
        .navigate("*******")
    EndWith
    GUISetState(@SW_SHOW)

    While 1
        $nMsg = GUIGetMsg()
        Switch $nMsg
            Case $GUI_EVENT_CLOSE
                Exit
            Case $SaveBtn
                $User = GUICtrlRead($Username)
                IniWrite("Userinfo.ini", "Name", "Name", $User)
                $Pass = GUICtrlRead($Password)
                IniWrite("Userinfo.ini", "Pass", "Pass", $Pass)
            Case $LogBtn
                $User = GUICtrlRead($Username)
                $Pass = GUICtrlRead($Password)
                With $ie
                    While ($ie.busy)
                    WEnd
                    Sleep($slpLow)
                    $txtUser = .document.getElementById('user')
                    $txtUser.value = $User
                    Sleep($slpLow)
                    $txtPass = .document.getElementById('password')
                    $txtPass.value = $Pass
                    Sleep($slpLow)
                    For $a In _IETagNameGetCollection($ie, "a")
                        If StringInStr(_IEPropertyGet($a, "innerText"), "Login") Then
                            $a.fireEvent("onmousedown")
                            Sleep($slpLow)
                            $a.fireEvent("onmouseup")
                            _IEAction($a, "click")
                        EndIf
                    Next
                    Sleep($slpMed)
                EndWith
            Case $btnAxeLc
                Call('AxeLcGUI')
            Case $btnLcHc

            Case $btnSpHc

            Case $btnSwAc

            Case $btnArcher

            Case $btnAxe

            Case $btnSpear

            Case $btnSword

            Case $btnMounted

        EndSwitch
    WEnd
EndFunc

Func AxeLcGUI()
    $axeInfo = IniRead('Userinfo.ini', 'AxeLC', 'Axe', 'Not on file')
    $lcInfo = IniRead('Userinfo.ini', 'AxeLC', 'LC', 'Not on file')
    $LcForm = GUICreate("Axe / Lc", 315, 134, -1, -1)
    $AxNum = GUICtrlCreateInput($axeInfo, 32, 40, 73, 21)
    $AxNumT = GUICtrlCreateLabel("How Many Ax/run?", 24, 16, 96, 17)
    $LcNum = GUICtrlCreateInput($lcInfo, 176, 40, 73, 21)
    $LcNumT = GUICtrlCreateLabel("How many LC/run?", 168, 16, 96, 17)
    $LootAssist = GUICtrlCreateButton("Loot Assist", 32, 88, 75, 25)
    $btnSave = GUICtrlCreateButton("Save Info", 176, 88, 75, 25)
    GUISetState(@SW_SHOW)
    While 1
        $nMsg = GUIGetMsg()
        Switch $nMsg
            Case $GUI_EVENT_CLOSE
                GUIDelete(AxeLcGUI)
                ExitLoop
            Case $btnSave
                Global $axeReal = GUICtrlRead($AxNum)
                IniWrite("Userinfo.ini", "AxeLC", "Axe", $axeReal)
                Global $lcReal = GUICtrlRead($LcNum)
                IniWrite("Userinfo.ini", "AxeLC", "LC", $lcReal)
            Case $LootAssist
                $axeReal = GUICtrlRead($AxNum)
                $lcReal = GUICtrlRead($LcNum)
                Call("AxeLCFarm")
        EndSwitch
    WEnd
EndFunc

Func AxeLCFarm()
    With $ie
        Local $oInputs = _IETagNameGetCollection($ie, "input")
        For $oInput In $oInputs
            If $oInput.name == "axe" Then
                $oInput.value = $axeReal
            EndIf
        Next
        Local $oInputs = _IETagNameGetCollection($ie, "input")
        For $oInput In $oInputs
            If $oInput.name == "light" Then
                $oInput.value = $lcReal
            EndIf
        Next
    EndWith
EndFunc

Func LootAssist()
    With $ie
        Local $oInputs = _IETagNameGetCollection($ie, "a")
        For $oInput In $oInputs
            If $oInput.title == "Loot Assistant" Then
                $oInput.fireEvent("onmousedown")
                Sleep($slpLow)
                $oInput.fireEvent("onmouseup")
                _IEAction($oInput, "click")
            EndIf
        Next
    EndWith
EndFunc

Func Farm()
    WinActivate('001')
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
EndFunc

Func Terminate()
    Exit 0
EndFunc
</code>```

Input to AxeLcGUI() also goes to the main GUI, which is undesired.

答:
… when you put any info into the pop up GUI, the main GUI reacts as well …

As per documentation:

When using the "advanced" parameter the information is returned in an array with extended information:

  $aArray[0] = 0 or Event ID or Control ID

  $aArray[1] = The window handle the event is from

  $aArray[2] = The control handle the event is from (if applicable)

  $aArray[3] = The current X position of the mouse cursor (relative to the GUI window)

  $aArray[4] = The current Y position of the mouse cursor (relative to the GUI window)

GUIGetMsg($GUI_EVENT_ARRAY) enables identification of window from which the message originates. Example:

```<code>If $aArray[0] = $GUI_EVENT_CLOSE And $aArray[1] = $hGUI2 Then

    ; Your code

EndIf
</code>```

Title: How to differentiate multiple GUI?

Body:
My GUI brings up other GUIs once a button is pressed (works correctly).

But when I interact with the pop-up GUI, the main GUI reacts as well (an embedded IE browser; when it receives input it messes everything up). Here is the code:

#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <StaticConstants.au3>
#include <ComboConstants.au3>
#include <WinHttp.au3>
#include <IE.au3>
#include <GUIConstantsEx.au3>
#include <GuiEdit.au3>
#include <WinAPIFiles.au3>
#include <ImageSearch2015.au3>

Opt('SendKeyDelay', Random(16, 80)); default 5. higher number = slower
Global $nameInfo = IniRead('Userinfo.ini', 'Name', 'Name', 'No username on file')
Global $passInfo = IniRead('Userinfo.ini', 'Pass', 'Pass', 'No password on file')
Global $slpMed = Random(2000, 2500)
Global $slpLow = Random(100, 350)
;Not in use ATM, will be used in future builds.
Global $en = '....' ;Need to find out how to login through world #
Global $mainUrl = 'https://' & $en & '.******'
Global $testUrl = 'https://*********'

Main_GUI()

Func Main_GUI()
    AutoItSetOption("MouseCoordMode", 0)
    $EzTw = GUICreate("Ez Tw", 885, 513, -1, -1)
    GUISetBkColor(0xA0A0A0)
    $Username = GUICtrlCreateInput($nameInfo, 8, 32, 105, 21)
    GUICtrlSetBkColor(-1, 0xFFFFFF)
    $Password = GUICtrlCreateInput($passInfo, 120, 32, 105, 21)
    GUICtrlSetBkColor(-1, 0xFFFFFF)
    $LogBtn = GUICtrlCreateButton("Login", 24, 56, 75, 17)
    GUICtrlSetBkColor(-1, 0xFFFFFF)
    $UserT = GUICtrlCreateLabel("User name", 40, 8, 55, 17)
    $PassT = GUICtrlCreateLabel("Password", 144, 8, 50, 17)
    $SaveBtn = GUICtrlCreateButton("Save Info", 136, 56, 75, 17)
    GUICtrlSetBkColor(-1, 0xFFFFFF)
    $Group1 = GUICtrlCreateGroup("Group1", -16, -40, 257, 129)
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    $Group2 = GUICtrlCreateGroup("Group2", 240, -16, 265, 105)
    $btnAxeLc = GUICtrlCreateButton("Axe/LC", 248, 32, 75, 17)
    $btnLcHc = GUICtrlCreateButton("Lc/Hc", 248, 8, 75, 17)
    $btnSpHc = GUICtrlCreateButton("Sp/Hc", 248, 56, 75, 17)
    $btnSwAc = GUICtrlCreateButton("Sw/Ac", 336, 8, 75, 17)
    $btnAxe = GUICtrlCreateButton("Axe Only", 336, 32, 75, 17)
    $btnSpear = GUICtrlCreateButton("Spear Only", 336, 56, 75, 17)
    $btnArcher = GUICtrlCreateButton("Archer Only", 424, 8, 75, 17)
    $btnSword = GUICtrlCreateButton("Sword Only", 424, 32, 75, 17)
    $btnMounted = GUICtrlCreateButton("MA Only", 424, 56, 75, 17)
    Global $ie = _IECreateEmbedded()
    Global $inIW = GUICtrlCreateObj($ie, 10, 100, 865, 405)
    With $ie
        .navigate("*******")
    EndWith
    GUISetState(@SW_SHOW)

    While 1
        $nMsg = GUIGetMsg()
        Switch $nMsg
            Case $GUI_EVENT_CLOSE
                Exit
            Case $SaveBtn
                $User = GUICtrlRead($Username)
                IniWrite("Userinfo.ini", "Name", "Name", $User)
                $Pass = GUICtrlRead($Password)
                IniWrite("Userinfo.ini", "Pass", "Pass", $Pass)
            Case $LogBtn
                $User = GUICtrlRead($Username)
                $Pass = GUICtrlRead($Password)
                With $ie
                    While ($ie.busy)
                    WEnd
                    Sleep($slpLow)
                    $txtUser = .document.getElementById('user')
                    $txtUser.value = $User
                    Sleep($slpLow)
                    $txtPass = .document.getElementById('password')
                    $txtPass.value = $Pass
                    Sleep($slpLow)
                    For $a In _IETagNameGetCollection($ie, "a")
                        If StringInStr(_IEPropertyGet($a, "innerText"), "Login") Then
                            $a.fireEvent("onmousedown")
                            Sleep($slpLow)
                            $a.fireEvent("onmouseup")
                            _IEAction($a, "click")
                        EndIf
                    Next
                    Sleep($slpMed)
                EndWith
            Case $btnAxeLc
                Call('AxeLcGUI')
            Case $btnLcHc

            Case $btnSpHc

            Case $btnSwAc

            Case $btnArcher

            Case $btnAxe

            Case $btnSpear

            Case $btnSword

            Case $btnMounted

        EndSwitch
    WEnd
EndFunc

Func AxeLcGUI()
    $axeInfo = IniRead('Userinfo.ini', 'AxeLC', 'Axe', 'Not on file')
    $lcInfo = IniRead('Userinfo.ini', 'AxeLC', 'LC', 'Not on file')
    $LcForm = GUICreate("Axe / Lc", 315, 134, -1, -1)
    $AxNum = GUICtrlCreateInput($axeInfo, 32, 40, 73, 21)
    $AxNumT = GUICtrlCreateLabel("How Many Ax/run?", 24, 16, 96, 17)
    $LcNum = GUICtrlCreateInput($lcInfo, 176, 40, 73, 21)
    $LcNumT = GUICtrlCreateLabel("How many LC/run?", 168, 16, 96, 17)
    $LootAssist = GUICtrlCreateButton("Loot Assist", 32, 88, 75, 25)
    $btnSave = GUICtrlCreateButton("Save Info", 176, 88, 75, 25)
    GUISetState(@SW_SHOW)
    While 1
        $nMsg = GUIGetMsg()
        Switch $nMsg
            Case $GUI_EVENT_CLOSE
                GUIDelete(AxeLcGUI)
                ExitLoop
            Case $btnSave
                Global $axeReal = GUICtrlRead($AxNum)
                IniWrite("Userinfo.ini", "AxeLC", "Axe", $axeReal)
                Global $lcReal = GUICtrlRead($LcNum)
                IniWrite("Userinfo.ini", "AxeLC", "LC", $lcReal)
            Case $LootAssist
                $axeReal = GUICtrlRead($AxNum)
                $lcReal = GUICtrlRead($LcNum)
                Call("AxeLCFarm")
        EndSwitch
    WEnd
EndFunc

Func AxeLCFarm()
    With $ie
        Local $oInputs = _IETagNameGetCollection($ie, "input")
        For $oInput In $oInputs
            If $oInput.name == "axe" Then
                $oInput.value = $axeReal
            EndIf
        Next
        Local $oInputs = _IETagNameGetCollection($ie, "input")
        For $oInput In $oInputs
            If $oInput.name == "light" Then
                $oInput.value = $lcReal
            EndIf
        Next
    EndWith
EndFunc

Func LootAssist()
    With $ie
        Local $oInputs = _IETagNameGetCollection($ie, "a")
        For $oInput In $oInputs
            If $oInput.title == "Loot Assistant" Then
                $oInput.fireEvent("onmousedown")
                Sleep($slpLow)
                $oInput.fireEvent("onmouseup")
                _IEAction($oInput, "click")
            EndIf
        Next
    EndWith
EndFunc

Func Farm()
    WinActivate('001')
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
    Sleep(100)
    Send('A')
EndFunc

Func Terminate()
    Exit 0
EndFunc

Input to AxeLcGUI() also goes to the main GUI, which is undesired.

Body:
… when you put any info into the pop up GUI, the main GUI reacts as well …

As per documentation:

When using the "advanced" parameter the information is returned in an array with extended information:

  $aArray[0] = 0 or Event ID or Control ID

  $aArray[1] = The window handle the event is from

  $aArray[2] = The control handle the event is from (if applicable)

  $aArray[3] = The current X position of the mouse cursor (relative to the GUI window)

  $aArray[4] = The current Y position of the mouse cursor (relative to the GUI window)

GUIGetMsg($GUI_EVENT_ARRAY) enables identification of window from which the message originates. Example:

If $aArray[0] = $GUI_EVENT_CLOSE And $aArray[1] = $hGUI2 Then

    ; Your code

EndIf


问:
Ajax request not firing in new version of jquery
I have a small script that checks the username in the database if it is taken it will say taken if its available it will say available. currently the below code works perfectly in jQuery v1.7.2

How ever I need to update it to work with the current version of jQuery v3.2.1,
but trying to use the current jquery version it just says checking availability and nothing else.

```<code>$(document).ready(function() {
  $("#username").keyup(function() {
    var username = $("#username").val();
    var msgbox = $("#status");

    if (username.length > 3) {
      $("#status").html('');

      $.ajax({
        type: "POST",
        url: "includes/user_check.php",
        data: "username=" + username,
        success: function(msg) {
          $("#status").ajaxComplete(function(event, request) {
            if (msg == 'OK') {

              $("#username").removeClass("red");
              $("#username").addClass("green");
              msgbox.html('Available');
            } else {
              $("#username").removeClass("green");
              $("#username").addClass("red");
              msgbox.html(msg);
            }

          });
        }
      });
    } else {
      $("#username").addClass("red");
      $("#status").html('<font color="#cc0000">To Short</font>');
    }
    return false;
  });
});
</code>```

答:
This answer might not be quite correct as it depends on the versions of jQuery you are referring to, however as of 3.0 the success, error and complete callbacks are removed. And should be replaced with done, fail & always.

http://api.jquery.com/jquery.ajax/

i.e.

```<code>$.ajax({
    type: method,
    url: url,
    data: ""
}).done(function (resp) {

}).fail(function (resp) {

}).always(function () {

});
</code>```

Body:
I have a small script that checks the username in the database if it is taken it will say taken if its available it will say available. currently the below code works perfectly in jQuery v1.7.2

How ever I need to update it to work with the current version of jQuery v3.2.1,
but trying to use the current jquery version it just says checking availability and nothing else.

$(document).ready(function() {
  $("#username").keyup(function() {
    var username = $("#username").val();
    var msgbox = $("#status");

    if (username.length > 3) {
      $("#status").html('');

      $.ajax({
        type: "POST",
        url: "includes/user_check.php",
        data: "username=" + username,
        success: function(msg) {
          $("#status").ajaxComplete(function(event, request) {
            if (msg == 'OK') {

              $("#username").removeClass("red");
              $("#username").addClass("green");
              msgbox.html('Available');
            } else {
              $("#username").removeClass("green");
              $("#username").addClass("red");
              msgbox.html(msg);
            }

          });
        }
      });
    } else {
      $("#username").addClass("red");
      $("#status").html('To Short');
    }
    return false;
  });
});

Body:
This answer might not be quite correct as it depends on the versions of jQuery you are referring to, however as of 3.0 the success, error and complete callbacks are removed. And should be replaced with done, fail & always.

http://api.jquery.com/jquery.ajax/

i.e.

$.ajax({
    type: method,
    url: url,
    data: ""
}).done(function (resp) {

}).fail(function (resp) {

}).always(function () {

});


问:
Hibernate Cache error
Employee.java

```<code>    public class Employee {
    private int id;
    private String firstName;
    private String lastName;
    private int salary;
    public Employee() {}
    public Employee(String fname, String lname, int salary) {
    this.firstName = fname;
    this.lastName = lname;
    this.salary = salary;
    }
    public int getId() {
    return id;
    }
    public void setId( int id ) {
    this.id = id;
    }
    public String getFirstName() {
    return firstName;
    }
    public void setFirstName( String first_name ) {
    this.firstName = first_name;
    }
    public String getLastName() {
    return lastName;
    }
    public void setLastName( String last_name ) {
    this.lastName = last_name;
    }
    public int getSalary() {
    return salary;
    }
    public void setSalary( int salary ) {
    this.salary = salary;
    }
    }
</code>```

ManageEmployee.java (Main)

```<code>import java.util.List;

import org.hibernate.cache.*;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);
/* List down all the employees */
//ME.listEmployees();
/* Update employee's records */
ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */
//ME.deleteEmployee(empID2);
/* List down new list of the employees */
ME.listEmployees();
}

/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}

/* Method to READ all the employees */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}

/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}

/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
</code>```

hibernate.cfg.xml

```<code><?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC  "-//Hibernate/Hibernate Configuration DTD .0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver<property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">********</property>
        <property name="connection.password">********</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable/Disable the second-level cache  -->
        <property name="cache.use_second_level_cache">true</property>

        <!-- Specify 2nd level cache class_provider -->
        <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider </property>

        <!-- Echo all executed SQL to stdout -->
         <property name="show_sql">true</property>

        <!-- Drop the existing tables and create new one -->
        <property name="hbm2ddl.auto">create</property>

        <!-- Mention here all the model classes along with their package name -->
        <mapping resource="Employee.hbm.xml"/>

    </session-factory>
</hibernate-configuration>
</code>```

Employee.hbm.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<cache usage="read-write"/>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>

</hibernate-mapping>
</code>```

ehcache.xml

```<code><?xml version="1.0" encoding="UTF-8"?>

<diskStore path="java.io.tmpdir"/>

<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>

<cache name="Employee"
maxElementsInMemory="500"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
</code>```

ERROR```
Failed to create sessionFactory object.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory]
Exception in thread "main" java.lang.ExceptionInInitializerError
    at ManageEmployee.main(ManageEmployee.java:17)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:261)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:225)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:295)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2442)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2438)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1855)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
    at ManageEmployee.main(ManageEmployee.java:14)
Caused by: org.hibernate.HibernateException: could not instantiate RegionFactory [net.sf.ehcache.hibernate.EhCacheRegionFactory]
    at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:101)
    at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:46)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:105)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:251)
    ... 8 more
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [net.sf.ehcache.hibernate.EhCacheRegionFactory] as strategy [org.hibernate.cache.spi.RegionFactory]
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128)
    at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:87)
    ... 11 more</p>

<p>```

NOTE: The XML file couldnt be posted so I had to leave space between < and > and sorry for this thing.

Looking forward to get this error cleared.

Thanks in advance :-)

答:
The first step is to add these required jars in your project:

ehcache-2.10.3.jar, slf4j-api-1.7.7.jar and hibernate-ehcache-5.2.10.Final.jar

and add these to your build path using following steps:
Select all the jar files, then right click on selection and select Build Path -> Add to Build Path.

After that check for

```<code><property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
</code>```

Set the second level cache property to false if you are not using it because then also, it throws the same error i.e. ExceptionInInitializerError.

And, if you're implementing second-level cache, then try to use this annotation

```<code>@Cache(usage= CacheConcurrencyStrategy.READ_ONLY)
public class Employee{
      ...
      .....
}
</code>```

Title: Hibernate Cache error

Body:
Employee.java

    public class Employee {
    private int id;
    private String firstName;
    private String lastName;
    private int salary;
    public Employee() {}
    public Employee(String fname, String lname, int salary) {
    this.firstName = fname;
    this.lastName = lname;
    this.salary = salary;
    }
    public int getId() {
    return id;
    }
    public void setId( int id ) {
    this.id = id;
    }
    public String getFirstName() {
    return firstName;
    }
    public void setFirstName( String first_name ) {
    this.firstName = first_name;
    }
    public String getLastName() {
    return lastName;
    }
    public void setLastName( String last_name ) {
    this.lastName = last_name;
    }
    public int getSalary() {
    return salary;
    }
    public void setSalary( int salary ) {
    this.salary = salary;
    }
    }

ManageEmployee.java (Main)

import java.util.List;

import org.hibernate.cache.*;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);
/* List down all the employees */
//ME.listEmployees();
/* Update employee's records */
ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */
//ME.deleteEmployee(empID2);
/* List down new list of the employees */
ME.listEmployees();
}

/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}

/* Method to READ all the employees */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}

/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}

/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC  "-//Hibernate/Hibernate Configuration DTD .0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver<property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">********</property>
        <property name="connection.password">********</property>

        <property name="connection.pool_size">1</property>

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="cache.use_second_level_cache">true</property>

        <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider </property>

         <property name="show_sql">true</property>

        <property name="hbm2ddl.auto">create</property>

        <mapping resource="Employee.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

Employee.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<cache usage="read-write"/>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>

</hibernate-mapping>

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>

<diskStore path="java.io.tmpdir"/>

<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>

<cache name="Employee"
maxElementsInMemory="500"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>

ERROR

Failed to create sessionFactory object.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory]
Exception in thread "main" java.lang.ExceptionInInitializerError
    at ManageEmployee.main(ManageEmployee.java:17)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:261)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:225)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:295)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2442)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2438)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1855)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
    at ManageEmployee.main(ManageEmployee.java:14)
Caused by: org.hibernate.HibernateException: could not instantiate RegionFactory [net.sf.ehcache.hibernate.EhCacheRegionFactory]
    at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:101)
    at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:46)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:105)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:251)
    ... 8 more
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [net.sf.ehcache.hibernate.EhCacheRegionFactory] as strategy [org.hibernate.cache.spi.RegionFactory]
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128)
    at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:87)
    ... 11 more

NOTE: The XML file couldnt be posted so I had to leave space between < and > and sorry for this thing.

Looking forward to get this error cleared.

Thanks in advance :-)

Body:
The first step is to add these required jars in your project:

ehcache-2.10.3.jar, slf4j-api-1.7.7.jar and hibernate-ehcache-5.2.10.Final.jar

and add these to your build path using following steps:
Select all the jar files, then right click on selection and select Build Path -> Add to Build Path.

After that check for

<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

Set the second level cache property to false if you are not using it because then also, it throws the same error i.e. ExceptionInInitializerError.

And, if you're implementing second-level cache, then try to use this annotation

@Cache(usage= CacheConcurrencyStrategy.READ_ONLY)
public class Employee{
      ...
      .....
}


问:
Android: Detect long press on the whole activity
How can i detect a long press on the whole activity? since onLongClickListener is only for individual views.I want to run a method everytime the user longpress the screen</p>

答: A long press is actually multiple registers of the key. So you could do a while loop on the input and as long as input is not NULL run the method you want. If I understood you correctly this should do the trick...


问:
Grid of Checkboxes in WPF
I have a WPF UserControl's datacontext tied to a class like this:

```<code>public class CheckBoxGridViewModel
{
  public List<List<bool>> Checkboxes {get; set;}
}
</code>```

I want it to display a grid of checkboxes. I'm assuming I can use an Itemscontrol, but don't know exactly how to do it with a dynamic set of columns for each row.

This question seems to answer mine, except the answer didn't give the example and I can't figure how to write it out.

So the question is, how would I write the xaml to display the checkboxes of the Checkboxes property so that they are lined up in a nice grid?

The outer list would be each row and the inner list would be each column of the row.

答:
How exactly do you want this grid arranged? This will influence which ItemsControl.ItemsPanel to use. A couple of ideas...

Use a UniformGrid, or the WPF Toolkit WrapPanel.

ContentLicense: CC BY-SA 2.5

Title: Grid of Checkboxes in WPF

Body:
I have a WPF UserControl's datacontext tied to a class like this:

public class CheckBoxGridViewModel
{
  public List<List<bool>> Checkboxes {get; set;}
}

I want it to display a grid of checkboxes. I'm assuming I can use an Itemscontrol, but don't know exactly how to do it with a dynamic set of columns for each row.

This question seems to answer mine, except the answer didn't give the example and I can't figure how to write it out.

So the question is, how would I write the xaml to display the checkboxes of the Checkboxes property so that they are lined up in a nice grid?

The outer list would be each row and the inner list would be each column of the row.


问:
Taking inputs with BufferedReader in Java
I have a bit of an annoying case here; wherein I am not able to take the input properly. I have always taken input via Scanner, and am not used to the BufferedReader.

INPUT FORMAT

```<code>First line contains T, which is an integer representing the number of test cases.
T cases follow. Each case consists of two lines.

First line has the string S.
The second line contains two integers M, P separated by a space.
</code>```

EXAMPLE

```<code>Input:
2
AbcDef
1 2
abcabc
1 1
</code>```

My code so far:

```<code>public static void main (String[] args) throws java.lang.Exception
{
    BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
    int T= Integer.parseInt(inp.readLine());

    for(int i=0;i<T;i++) {
        String s= inp.readLine();
        int[] m= new int[2];
        m[0]=inp.read();
        m[1]=inp.read();

        // Checking whether I am taking the inputs correctly
        System.out.println(s);
        System.out.println(m[0]);
        System.out.println(m[1]);
    }
}
</code>```

When inputting to the above example shown, I get the following output:

```<code>AbcDef
9
49
2
9
97
</code>```

答:
You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass.
 Although, you can do something like this in regard to your query :

```<code>import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}
</code>```

I hope this will help you.

Body:
I have a bit of an annoying case here; wherein I am not able to take the input properly. I have always taken input via Scanner, and am not used to the BufferedReader.

INPUT FORMAT

First line contains T, which is an integer representing the number of test cases.
T cases follow. Each case consists of two lines.

First line has the string S.
The second line contains two integers M, P separated by a space.

EXAMPLE

Input:
2
AbcDef
1 2
abcabc
1 1

My code so far:

public static void main (String[] args) throws java.lang.Exception
{
    BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
    int T= Integer.parseInt(inp.readLine());

    for(int i=0;i<T;i++) {
        String s= inp.readLine();
        int[] m= new int[2];
        m[0]=inp.read();
        m[1]=inp.read();

        // Checking whether I am taking the inputs correctly
        System.out.println(s);
        System.out.println(m[0]);
        System.out.println(m[1]);
    }
}

When inputting to the above example shown, I get the following output:

AbcDef
9
49
2
9
97

Body:
You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass.
 Although, you can do something like this in regard to your query :

import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}

I hope this will help you.


问:
jquery.validate validation for non active tabs
I've a form which uses jQuery UI based tab to organize different fields. I'm using jquery.validate.min.js for validation. For example some fields have class = "required" which informs the plugin for required field validation. Finally, before form submit I validate the form to ensure all inputs are correct. A simple usage like -

```<code>HTML

...
<input type="text" class = "required" ...

SCRIPT

...
$("#frmClaim").validate();//to initilize validation
...
$('#frmClaim').submit(function () {
             if($(this).valid())
                { ... }
         });
...
</code>```

The issue I'm facing is that if I'm on tab 3 and there's a "required" field on tab 2 which the user has not populated, the validation is NOT performed. The validation triggers only for the fields which are visible - that is the active. Is this possible or am I missing something?

For now, on submit I manually activate each tab, perform .valid and proceed. Is there a better work around?

答:
I found a solution that worked for me. The idea is to iterate for all tabs, calling validate on the form and stop when you find an invalid tab or submit the form if there is no invalid fields.</p>

```<code>$("#my_form").validate({
        submitHandler: function (form, evt) {
            var f = $(form);
            var tab = $("#my_tab_id");
            var tabs_count = tab.children('ul').children('li').length;
            var active = tab.tabs('option', 'active');
            var invalid = false;
            var validated = 0;

            while (validated < tabs_count && !invalid) {
                if (!f.valid()) {
                    invalid = true;
                    break;
                }

                active++;
                active = active % tabs_count;
                tab.tabs('option', 'active', active);

                validated++;
            }

            if (!invalid)
                form.submit();
            else
                evt.preventDefault();
        },
        rules: {
            ...
        },
        messages: {
            ...
        }
    });
</code>```

Body:
I've a form which uses jQuery UI based tab to organize different fields. I'm using jquery.validate.min.js for validation. For example some fields have class = "required" which informs the plugin for required field validation. Finally, before form submit I validate the form to ensure all inputs are correct. A simple usage like -

HTML

...
<input type="text" class = "required" ...

SCRIPT

...
$("#frmClaim").validate();//to initilize validation
...
$('#frmClaim').submit(function () {
             if($(this).valid())
                { ... }
         });
...

The issue I'm facing is that if I'm on tab 3 and there's a "required" field on tab 2 which the user has not populated, the validation is NOT performed. The validation triggers only for the fields which are visible - that is the active. Is this possible or am I missing something?

For now, on submit I manually activate each tab, perform .valid and proceed. Is there a better work around?

Body:
I found a solution that worked for me. The idea is to iterate for all tabs, calling validate on the form and stop when you find an invalid tab or submit the form if there is no invalid fields.

$("#my_form").validate({
        submitHandler: function (form, evt) {
            var f = $(form);
            var tab = $("#my_tab_id");
            var tabs_count = tab.children('ul').children('li').length;
            var active = tab.tabs('option', 'active');
            var invalid = false;
            var validated = 0;

            while (validated < tabs_count && !invalid) {
                if (!f.valid()) {
                    invalid = true;
                    break;
                }

                active++;
                active = active % tabs_count;
                tab.tabs('option', 'active', active);

                validated++;
            }

            if (!invalid)
                form.submit();
            else
                evt.preventDefault();
        },
        rules: {
            ...
        },
        messages: {
            ...
        }
    });


问:
Swift - Sort a subset of an array
I currently have a tableview with a lot of users, but I would like to sort the users in a specific order, not just ascending or descending. Let's say I have an array with the following users.

```<code>"User1", "1st grade"
"User2", "1st grade"
"User3", "kids"
"User4", "6th grade"
"User5", "5th grade"
"User6", "2nd grade"
"User7", "kids"
"User8", "juniors"
</code>```

How can I order my array so that all the students who are in kids class are the first to be displayed, followed by all the classes with numbers (in order) and then all the Juniors.

I want an array that can display this

```<code>"User3", "kids"
"User7", "kids"
"User1", "1st grade"
"User2", "1st grade"
"User6", "2nd grade"
"User5", "5th grade"
"User4", "6th grade"
"User8", "juniors"
</code>```

Edit:
Updated the text to make clear that the array has two columns, not just one string.

Was able to achieve it by using the line below

```<code>let sortedArray =
self.userArray.sorted(by: { $0.SchoolGrade!.gradeLongName().contains("Kids") ||
$1.SchoolGrade!.gradeLongName().contains("Juniors") })
</code>```

答: You should create three separate arrays, use filter to get the appropriate results, then sort them individually. After that, you should join the three arrays by a simple additional operation.

Title: Swift - Sort a subset of an array

Body:
I currently have a tableview with a lot of users, but I would like to sort the users in a specific order, not just ascending or descending. Let's say I have an array with the following users.

"User1", "1st grade"
"User2", "1st grade"
"User3", "kids"
"User4", "6th grade"
"User5", "5th grade"
"User6", "2nd grade"
"User7", "kids"
"User8", "juniors"

How can I order my array so that all the students who are in kids class are the first to be displayed, followed by all the classes with numbers (in order) and then all the Juniors.

I want an array that can display this

"User3", "kids"
"User7", "kids"
"User1", "1st grade"
"User2", "1st grade"
"User6", "2nd grade"
"User5", "5th grade"
"User4", "6th grade"
"User8", "juniors"

Edit:
Updated the text to make clear that the array has two columns, not just one string.

Was able to achieve it by using the line below

let sortedArray =
self.userArray.sorted(by: { $0.SchoolGrade!.gradeLongName().contains("Kids") ||
$1.SchoolGrade!.gradeLongName().contains("Juniors") })


问:
Tree of mutable slices
Some algorithms recursively partition an array into smaller pieces. You can build an explicit binary tree that results from such a process, where each leaf holds a disjoint slice of the array. If you need to alter or reorder elements in the leaf, its slice must be mutable.

```<code>enum Tree<'a> {
    Branch(Box<[Tree<'a>; 2]>),
    Leaf(&'a mut[f32]),
}
</code>```

Suppose I need to split all the leaves that are larger than some threshold. Easy: recursively walk down the tree from the root; when I find a leaf with a slice long enough, split it into 2 halves, wrap them into a 2-leaf subtree, and replace the leaf.

```<code>impl<'a> Tree<'a> {
    fn split(&mut self, max: usize) {
        match self {
            &mut Tree::Branch(ref mut trees) => {
                trees[0].split(max);
                trees[1].split(max);
            },
            &mut Tree::Leaf(ref mut leaf) if leaf.len() > max => {
                let mid = leaf.len() / 2;
                let (l, r) = leaf.split_at_mut(mid);
                let trees = [Tree::Leaf(l), Tree::Leaf(r)];
                *self = Tree::Branch(Box::new(trees));
            },
        }
    }
}
</code>```

Unfortunately, the borrow-checker is unable to find a suitable lifetime for the ref mut leaf pattern. It wants it dead before allowing the assignement to *self, but I don't see how to make the assignment out of the match arm.

How to make this work?

答:
You can make it work using two tricks, which are explained in the code.</p>

```<code>use std::mem;

enum Tree<'a> {
    Branch(Box<[Tree<'a>; 2]>),
    Leaf(&'a mut[f32]),
    Placeholder, // it's not very nice hack, but it's required for mem::replace
}

impl<'a> Tree<'a> {
    fn split(&mut self, max: usize) {
        let mut needs_split = false;
        match self {
            &mut Tree::Branch(ref mut trees) => {
                trees[0].split(max);
                trees[1].split(max);
            },
            &mut Tree::Leaf(ref mut leaf) if leaf.len() > max => {
                // Postpone modification of *self. We can't do it now while
                // a part of *self is borrowed
                needs_split = true;
            },
            _ => {}
        }
        if needs_split {
            // move *self into cself, to be able to
            // deconstruct content, while keeping *self not borrowed
            let cself = mem::replace(self, Tree::Placeholder);
            if let Tree::Leaf(leaf) = cself {
                let mid = leaf.len() / 2;
                let (l, r) = leaf.split_at_mut(mid);
                let trees = [Tree::Leaf(l), Tree::Leaf(r)];
                *self = Tree::Branch(Box::new(trees));
            } else {
                unreachable!()
            }
        }
    }
}
</code>```

Title: Tree of mutable slices

Body:
Some algorithms recursively partition an array into smaller pieces. You can build an explicit binary tree that results from such a process, where each leaf holds a disjoint slice of the array. If you need to alter or reorder elements in the leaf, its slice must be mutable.

enum Tree<'a> {
    Branch(Box<[Tree<'a>; 2]>),
    Leaf(&'a mut[f32]),
}

Suppose I need to split all the leaves that are larger than some threshold. Easy: recursively walk down the tree from the root; when I find a leaf with a slice long enough, split it into 2 halves, wrap them into a 2-leaf subtree, and replace the leaf.

impl<'a> Tree<'a> {
    fn split(&mut self, max: usize) {
        match self {
            &mut Tree::Branch(ref mut trees) => {
                trees[0].split(max);
                trees[1].split(max);
            },
            &mut Tree::Leaf(ref mut leaf) if leaf.len() > max => {
                let mid = leaf.len() / 2;
                let (l, r) = leaf.split_at_mut(mid);
                let trees = [Tree::Leaf(l), Tree::Leaf(r)];
                *self = Tree::Branch(Box::new(trees));
            },
        }
    }
}

Unfortunately, the borrow-checker is unable to find a suitable lifetime for the ref mut leaf pattern. It wants it dead before allowing the assignement to *self, but I don't see how to make the assignment out of the match arm.

How to make this work?

Body:
You can make it work using two tricks, which are explained in the code.

use std::mem;

enum Tree<'a> {
    Branch(Box<[Tree<'a>; 2]>),
    Leaf(&'a mut[f32]),
    Placeholder, // it's not very nice hack, but it's required for mem::replace
}

impl<'a> Tree<'a> {
    fn split(&mut self, max: usize) {
        let mut needs_split = false;
        match self {
            &mut Tree::Branch(ref mut trees) => {
                trees[0].split(max);
                trees[1].split(max);
            },
            &mut Tree::Leaf(ref mut leaf) if leaf.len() > max => {
                // Postpone modification of *self. We can't do it now while
                // a part of *self is borrowed
                needs_split = true;
            },
            _ => {}
        }
        if needs_split {
            // move *self into cself, to be able to
            // deconstruct content, while keeping *self not borrowed
            let cself = mem::replace(self, Tree::Placeholder);
            if let Tree::Leaf(leaf) = cself {
                let mid = leaf.len() / 2;
                let (l, r) = leaf.split_at_mut(mid);
                let trees = [Tree::Leaf(l), Tree::Leaf(r)];
                *self = Tree::Branch(Box::new(trees));
            } else {
                unreachable!()
            }
        }
    }
}


问:
How do I disable SQL Reporting Services and remove the Reports directory form IIS?
I'm trying to get rid of the /reports directory which seems to be integrated with SQL reporting services 2008.  I'm unable to uninstall that one element of SQL server and I've had no luck when trying to reconfigure the ReportBuilderLaunchURL.  Does anyone out there know how I can get rid of this stupid feature?  I'd understand if it was just a virtual directory on the localhost instance but when it gets applied to all my site I get really frustrated and wonder who at Microsoft decided that this would be the default setting.</p>

答: We've just been having this issue and the work around we came up with was linking it to one specific host header, rather than having it point to all sites on all IP addresses. (You can do this by clicking on the advanced button in the URL tab that @Luis mentions.) This has, effectively, quarantined the thing to one website and as it's a host header that isn't on any public site in the first place, it's massively limited the number of people who can even find it.</p>


答:
If you're OK with capturing every 10, it's simpler than you think (I assume). Try

```<code>(^\[\s?.{1,15}\s?.{1,15}\s?\]\,$\s?){10}
</code>```

It simply repeats your regex 10 times ({10}). A repeated capture group captures only the last one. Note that it has to "eat" the line feed as well, so a \s at the en of the capture group is necessary.

Needs to be multi line, and using a global flag, it repeats until end of text.

See it here at regex101 (capturing every third for better visibility).

Title: How can i match 1 every 10 results using regex?

Body:
I have the following regex:

(^\[\s?.{1,15}\s?.{1,15}\s?\]\,$)

On my test file, i got 35k matches. I want to make a interval between the matches. In another words, "match" 1 every 10 matches.

Example:

[-51.039,-19.777], (match)
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777], (match)

Body:
If you're OK with capturing every 10, it's simpler than you think (I assume). Try

(^\[\s?.{1,15}\s?.{1,15}\s?\]\,$\s?){10}

It simply repeats your regex 10 times ({10}). A repeated capture group captures only the last one. Note that it has to "eat" the line feed as well, so a \s at the en of the capture group is necessary.

Needs to be multi line, and using a global flag, it repeats until end of text.

See it here at regex101 (capturing every third for better visibility).


问:
Firebase Javascript: Securely store a password inside the database
I was wondering how to securely store a password in Firebase. I'm creating a chatting application that has different chat rooms which are private. A user needs to know the password in order to access the room of course. I was thinking about encrypting the user's inputted password using a JavaScript library, and then sending that encrypted password over to my Firebase database. Is it secure for me to do it this way?</p>

答:
No.

Do not encrypt passwords, when the attacker gets the DB he will also get the encryption key. Just using a hash function is not sufficient and just adding a salt does little to improve the security.  Iterate over an HMAC with a random salt for about a 100ms duration and save the salt with the hash. Use a function such as ehash, PBKDF2, Bcrypt or similar functions. The point is to make the attacker spend a lot of time finding passwords by brute force.


问:
Json.jbuilder merge 2 json data and send it to one key
I am using rails 5 and i am using jbuilder for sending json. The problem i am facing is i want to merge 2 table json and send it to same key..

my json.jbuilder look like this

```<code>json.children env.sites do |site|
  json.nodeId "site_#{site.id}"
  json.type "site"
  json.extract! site,:id, :key, :name
  json.children site.networks do |network|
    json.nodeId "network_#{network.id}"
    json.type "network"
    json.extract! network,:id, :name
    json.children network.vlans do |vlan|
      json.type "vlan"
      json.extract! vlan,:id, :name
    end
  end
  json.children site.instances do |instance|
    json.type "host"
    json.extract! instance,:id, :name
    json.content do
      json.cpu instance.cpu
    end
  end
end
</code>```

Issue i am facing over here is i want to merge site.networks and site.instaces in same key.. How i would achieve this..??

答:
You can use json.array!

Try this,

```<code>json.children env.sites do |site|
  json.nodeId "site_#{site.id}"
  json.type "site"
  json.extract! site,:id, :key, :name
  json.children do
    json.array!(site.networks) do |network|
      json.nodeId "network_#{network.id}"
      json.type "network"
      json.extract! network,:id, :name
      json.children network.vlans do |vlan|
        json.type "vlan"
        json.extract! vlan,:id, :name
      end
    end
    json.array!(site.instances) do |instance|
      json.type "host"
      json.extract! instance,:id, :name
      json.content do
        json.cpu instance.cpu
      end
    end
  end
end
</code>```

Body:
I am using rails 5 and i am using jbuilder for sending json. The problem i am facing is i want to merge 2 table json and send it to same key..

my json.jbuilder look like this

json.children env.sites do |site|
  json.nodeId "site_#{site.id}"
  json.type "site"
  json.extract! site,:id, :key, :name
  json.children site.networks do |network|
    json.nodeId "network_#{network.id}"
    json.type "network"
    json.extract! network,:id, :name
    json.children network.vlans do |vlan|
      json.type "vlan"
      json.extract! vlan,:id, :name
    end
  end
  json.children site.instances do |instance|
    json.type "host"
    json.extract! instance,:id, :name
    json.content do
      json.cpu instance.cpu
    end
  end
end

Issue i am facing over here is i want to merge site.networks and site.instaces in same key.. How i would achieve this..??

Body:
You can use json.array!

Try this,

json.children env.sites do |site|
  json.nodeId "site_#{site.id}"
  json.type "site"
  json.extract! site,:id, :key, :name
  json.children do
    json.array!(site.networks) do |network|
      json.nodeId "network_#{network.id}"
      json.type "network"
      json.extract! network,:id, :name
      json.children network.vlans do |vlan|
        json.type "vlan"
        json.extract! vlan,:id, :name
      end
    end
    json.array!(site.instances) do |instance|
      json.type "host"
      json.extract! instance,:id, :name
      json.content do
        json.cpu instance.cpu
      end
    end
  end
end