问:
Git branch names are OS dependent?
So I noticed that since git names folders based on the branch names in the file system (in the refs folder specifically i.e. remotes) this can cause issues since the allowed characters in the folder names are OS dependent.

For example you can create a branch on MAC OS like:

```<code>feature/my_special_"Splash Screen"_feature
</code>```

If I fetch this on Windows, it's gonna fail with a message like:

```<code>Fetch failed: fatal: Unable to create 'C:/AndroidStudioProjects/MyProject/.git/refs/remotes/origin/feature/my_special_"Splash Screen"_feature.lock': Invalid argument
</code>```

Since the file name contains aposthropes which are not allowed on Windows, while allowed on MAC OS.

When you try to create the same branch on windows, git will simply remove the aposthropes.

Does anyone know any official documentation on this? Also, do we need to rename this branch or is there a workaround?

答:
One non-official policy is mentioned in "Legal Git branch names", referencing this thread:

A Git branch name can not:

Have a path component that begins with "."

Have a double dot ".."

Have an ASCII control character, "~", "^", ":" or SP, anywhere

End with a "/"

End with ".lock"

Contain a "\" (backslash)

That patch (for a better error message on invalid branch name) was not implemented, and it does not include double-quotes at the time.

But still, it is a good idea to avoid any special character in branch names.

This comment in refs.c remains the closest of an official policy:

```<code>/*
 * Try to read one refname component from the front of refname.
 * Return the length of the component found, or -1 if the component is
 * not legal.  It is legal if it is something reasonable to have under
 * ".git/refs/"; We do not like it if:
 *
 * - any path component of it begins with ".", or
 * - it has double dots "..", or
 * - it has ASCII control characters, or
 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
 * - it ends with a "/", or
 * - it ends with ".lock", or
 * - it contains a "@{" portion
 */
</code>```

Title: Git branch names are OS dependent?

Body:
So I noticed that since git names folders based on the branch names in the file system (in the refs folder specifically i.e. remotes) this can cause issues since the allowed characters in the folder names are OS dependent.

For example you can create a branch on MAC OS like:

feature/my_special_"Splash Screen"_feature

If I fetch this on Windows, it's gonna fail with a message like:

Fetch failed: fatal: Unable to create 'C:/AndroidStudioProjects/MyProject/.git/refs/remotes/origin/feature/my_special_"Splash Screen"_feature.lock': Invalid argument

Since the file name contains aposthropes which are not allowed on Windows, while allowed on MAC OS.

When you try to create the same branch on windows, git will simply remove the aposthropes.

Does anyone know any official documentation on this? Also, do we need to rename this branch or is there a workaround?

Body:
One non-official policy is mentioned in "Legal Git branch names", referencing this thread:

A Git branch name can not:

Have a path component that begins with "."

Have a double dot ".."

Have an ASCII control character, "~", "^", ":" or SP, anywhere

End with a "/"

End with ".lock"

Contain a "\" (backslash)

That patch (for a better error message on invalid branch name) was not implemented, and it does not include double-quotes at the time.

But still, it is a good idea to avoid any special character in branch names.

This comment in refs.c remains the closest of an official policy:

/*
 * Try to read one refname component from the front of refname.
 * Return the length of the component found, or -1 if the component is
 * not legal.  It is legal if it is something reasonable to have under
 * ".git/refs/"; We do not like it if:
 *
 * - any path component of it begins with ".", or
 * - it has double dots "..", or
 * - it has ASCII control characters, or
 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
 * - it ends with a "/", or
 * - it ends with ".lock", or
 * - it contains a "@{" portion
 */


来源: stackexchange

问:
How to show just notification count on appview android
I'm new to android. And to show notification on android phones I got this below code

```<code>Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0  /*Request code*/ , intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.mytune_default)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);

        notificationManager.notify(m  /*ID of notification*/ , notificationBuilder.build());
</code>```

But the thing is I just want that notification unread count on code appview on system, but dont want other things loke message, title etc that appear on notification tray of system. How come this be acheived>

答: It's not possible to replace launcher icon with widget. You can say to user to place your widget on the home screen, but not in application list. Users must do that in their own. Nevertheless, it's iOs pattern. It's not good idea to bring iOS design elements to android. Android have great notification bar, where user expect to see notification from your app. Android users don't expect to see it over the icon.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm new to android. And to show notification on android phones I got this below code

Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0  /*Request code*/ , intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.mytune_default)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);

        notificationManager.notify(m  /*ID of notification*/ , notificationBuilder.build());

But the thing is I just want that notification unread count on code appview on system, but dont want other things loke message, title etc that appear on notification tray of system. How come this be acheived>


问:
PHP: Find last occurence of string in array
I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.

```<code>$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );

$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.
</code>```

I want $key = 3 which is the last matched element.

Any suggestion appreciated.

答:
We can use array_reverse to reverse array.

```<code>$key = array_search('bike', array_reverse($Data,true));
</code>```

It will return 3.

Body:
I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.

$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );

$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.

I want $key = 3 which is the last matched element.

Any suggestion appreciated.

Body:
We can use array_reverse to reverse array.

$key = array_search('bike', array_reverse($Data,true));

It will return 3.


问:
How can I ensure that my variable is not available directly outside the angular factory?
I have an angular factory which includes methods to manage a list of objects. One of those methods helps to make an ajax call and load more items into the list. When that method is called, I have a need to show the "in progress" state of the ajax call (i.e. loading of items). Now, I can just use a simple variable like service.isLoading = ... and set it to true or false depending on the state. However, the problem is that this variable becomes visible to the outside and any controllers that use this factory.

```<code>angular.module('myApp')
    .factory('appFactory', function QuestionsServ(...) {

        var service = {
            list: []
        };

        // loading state to help show if system is busy loading ajax data
        service.isBusy = false;

        service.loadItems = function () {
            service.isBusy = true;

            // make ajax call here
            var request = ...

            return request.then( function(res) {
                 // after successful loading show state is not busy
                 service.isBusy = false;
                 ...
            }

        ...
</code>```

But I would like to be able to keep this variable visible within the factory only. So I can change isBusy to something similar to the following.

```<code>        service.isBusy = function () {
            return false;
        }
</code>```

But now it is apparently busy from the factory as well. I am no longer able to access isBusy from within loadItems. What is the proper way to go around this issue?

答:
You can make isBusy a var local to the module and manipulate it directly from within your code.  Then, to expose it to the outside world, make a function that returns it-- that way other modules or constructs have access to the boolean's value for display purposes but can't manipulate its value inside your service:

```<code>angular.module('myApp')
    .factory('appFactory', function QuestionsServ(...) {

        var service = {
            list: []
        };

        // loading state to help show if system is busy loading ajax data
        var isBusy = false;

        service.isLoading = function () {
            return isBusy;
        };

        service.loadItems = function () {
            isBusy = true;

            // make ajax call here
            var request = ...

            return request.then( function(res) {
                 // after successful loading show state is not busy
                 isBusy = false;
                 ...
            }
</code>```

Body:
I have an angular factory which includes methods to manage a list of objects. One of those methods helps to make an ajax call and load more items into the list. When that method is called, I have a need to show the "in progress" state of the ajax call (i.e. loading of items). Now, I can just use a simple variable like service.isLoading = ... and set it to true or false depending on the state. However, the problem is that this variable becomes visible to the outside and any controllers that use this factory.

angular.module('myApp')
    .factory('appFactory', function QuestionsServ(...) {

        var service = {
            list: []
        };

        // loading state to help show if system is busy loading ajax data
        service.isBusy = false;

        service.loadItems = function () {
            service.isBusy = true;

            // make ajax call here
            var request = ...

            return request.then( function(res) {
                 // after successful loading show state is not busy
                 service.isBusy = false;
                 ...
            }

        ...

But I would like to be able to keep this variable visible within the factory only. So I can change isBusy to something similar to the following.

        service.isBusy = function () {
            return false;
        }

But now it is apparently busy from the factory as well. I am no longer able to access isBusy from within loadItems. What is the proper way to go around this issue?

Body:
You can make isBusy a var local to the module and manipulate it directly from within your code.  Then, to expose it to the outside world, make a function that returns it-- that way other modules or constructs have access to the boolean's value for display purposes but can't manipulate its value inside your service:

angular.module('myApp')
    .factory('appFactory', function QuestionsServ(...) {

        var service = {
            list: []
        };

        // loading state to help show if system is busy loading ajax data
        var isBusy = false;

        service.isLoading = function () {
            return isBusy;
        };

        service.loadItems = function () {
            isBusy = true;

            // make ajax call here
            var request = ...

            return request.then( function(res) {
                 // after successful loading show state is not busy
                 isBusy = false;
                 ...
            }


问:
Sum values of multidimensional array by key without loop
I have this:

```<code>Array (
    [0] => Array ( [f_count] => 1 [uid] => 105 )
    [1] => Array ( [f_count] => 0 [uid] => 106 )
    [2] => Array ( [f_count] => 2 [uid] => 107 )
    [3] => Array ( [f_count] => 0 [uid] => 108 )
    [4] => Array ( [f_count] => 1 [uid] => 109 )
    [5] => Array ( [f_count] => 0 [uid] => 110 )
    [6] => Array ( [f_count] => 3 [uid] => 111 )
)
</code>```

What I need is: 7", which is the the sum of the f_count column.

I've been trying to figure this out for a couple hours. I thought array_sum() would work, but not with a multidimensional array. So, I've tried figuring out how to isolate the f_counts by unset() or splicing or anything else, but every solution seems to involve a foreach loop. I've messed with array_map, array_walk, and others to no avail. I haven't found a function that works well with multidimensional arrays.

I'm running PHP 5.4.

Can someone please show me how to sum that column without a foreach loop?

If it helps, the f_count values will never be higher than 100, and the uid values will always be greater than 100.

Alternatively, if there's a way to run my query differently such that the array is not multidimensional, that would obviously work as well.

```<code>$query = "SELECT f_count, uid FROM users WHERE gid=:gid";
...
$array = $stmt->fetchAll();
</code>```

I'm using PDO.

答:
Since you are using PHP 5.4 with PDO, there could be one more way to do it (available in PHP 5.1+):

use the PDO fetchAll() function with the PDO::FETCH_COLUMN as the fetch_style, and the 0-indexed column number as the fetch_argument.

As per your example, it could be:

```<code>$query = "SELECT f_count, uid FROM users WHERE gid=:gid";
...
$array_fcount = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
</code>```

Now use the array_sum function to sum the values of the array:

```<code>$fcount_sum = array_sum($array_fcount);
</code>```

You could also consult the PHP documentation at http://php.net/manual/en/pdostatement.fetchall.php

Hope this helps, and the performance could be better than looping! As already mentioned in other answers, in PHP 5.5 onwards you have the array_column() function to get $array_fcount directly from another array.

Body:
I have this:

Array (
    [0] => Array ( [f_count] => 1 [uid] => 105 )
    [1] => Array ( [f_count] => 0 [uid] => 106 )
    [2] => Array ( [f_count] => 2 [uid] => 107 )
    [3] => Array ( [f_count] => 0 [uid] => 108 )
    [4] => Array ( [f_count] => 1 [uid] => 109 )
    [5] => Array ( [f_count] => 0 [uid] => 110 )
    [6] => Array ( [f_count] => 3 [uid] => 111 )
)

What I need is: 7", which is the the sum of the f_count column.

I've been trying to figure this out for a couple hours. I thought array_sum() would work, but not with a multidimensional array. So, I've tried figuring out how to isolate the f_counts by unset() or splicing or anything else, but every solution seems to involve a foreach loop. I've messed with array_map, array_walk, and others to no avail. I haven't found a function that works well with multidimensional arrays.

I'm running PHP 5.4.

Can someone please show me how to sum that column without a foreach loop?

If it helps, the f_count values will never be higher than 100, and the uid values will always be greater than 100.

Alternatively, if there's a way to run my query differently such that the array is not multidimensional, that would obviously work as well.

$query = "SELECT f_count, uid FROM users WHERE gid=:gid";
...
$array = $stmt->fetchAll();

I'm using PDO.

Body:
Since you are using PHP 5.4 with PDO, there could be one more way to do it (available in PHP 5.1+):

use the PDO fetchAll() function with the PDO::FETCH_COLUMN as the fetch_style, and the 0-indexed column number as the fetch_argument.

As per your example, it could be:

$query = "SELECT f_count, uid FROM users WHERE gid=:gid";
...
$array_fcount = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

Now use the array_sum function to sum the values of the array:

$fcount_sum = array_sum($array_fcount);

You could also consult the PHP documentation at http://php.net/manual/en/pdostatement.fetchall.php

Hope this helps, and the performance could be better than looping! As already mentioned in other answers, in PHP 5.5 onwards you have the array_column() function to get $array_fcount directly from another array.


问:
Worksheet Change to run macro
My workbook contains several sheets, each with multiple checkboxes.  All checkboxes in all worksheets have the linked cell in row 80.  In a worksheet called "Info" I am using countif to count the total number of times the text "TRUE" occurs in row(s) 80 for all worksheets.  The total is in Info!B8.

I need to call a macro each time cell Info!b8 changes.  So in other words; every time a checkbox is clicked, the linked cell changes, cell Info!b8 goes up or down and I need a macro to run.

This is the code I am using, but it doesn't do anything.  I have researched this and from what I can tell it should work??

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$8" Then
        Call CreateFinalWorksheet
    End If
End Sub
</code>```

答:
Assuming all your CheckBoxes are of Form Controls, with a bit of altering the CheckBox Creation, you can achieve what you want without the need of LinkedCell and CountIfs etc.

Example: CreateCheckBoxes() below will create a check box for each cell in Range("D1:D5"), Name it with a prefix and the cell address, assigns the Sub CheckBoxClicked when clicked.

In Sub CheckBoxClicked(), it will go through all worksheets (except named "Info"), then increment a counter if the value of checkbox named ending D3 is 1 (ticked). After that, if threshold is met, it calls the Sub CreateFinalWorksheet().

```<code>Option Explicit

Private Const ChkBoxPrefix As String = "cbx_"
Private Const ThresholdToCreateFinalWorksheet As Long = 3

Sub CreateChkBoxes()
    Dim myCBX As CheckBox, c As Range
    For Each c In Range("D1:D5") 'rngCB
        With c
            Set myCBX = ActiveSheet.CheckBoxes.Add(Top:=.Top, Width:=.Width, Height:=.Height, Left:=.Left)
        End With
        With myCBX
            .Name = ChkBoxPrefix & c.Address(0, 0)
            .Caption = "Check Box " & c.Address(0, 0) 'strCap
            .OnAction = "CheckBoxClicked" ' "CheckBox_Click"
        End With
    Next c
End Sub

Sub CheckBoxClicked() ' CheckBox_Click()
    Dim oWS As Worksheet, lChecked As Long

    On Error Resume Next ' Just in case the named CheckBox does not exist
    lChecked = 0
    For Each oWS In ThisWorkbook.Worksheets
        If oWS.Name <> "Info" Then
            ' If you need to keep track of more than 1 checkbox in each worksheet, go through them
            ' If you need all of them to be checked before CreateFinalWorksheet, exit when a checkbox.value = 0
            With oWS.CheckBoxes(ChkBoxPrefix & "D3") ' <-- Change to what you need to keep track of
                lChecked = lChecked + IIf(.Value = 1, 1, 0)
            End With
        End If
    Next
    On Error GoTo 0
    If lChecked >= ThresholdToCreateFinalWorksheet Then CreateFinalWorksheet
End Sub

Private Sub CreateFinalWorksheet()
    Debug.Print "CreateFinalWorksheet()"
End Sub
</code>```

Alternatively you put the event Sub Worksheet_Calculate() into Info module, and check if the Info!B8 is large enough to call CreateFinalWorksheet.

Title: Worksheet Change to run macro

Body:
My workbook contains several sheets, each with multiple checkboxes.  All checkboxes in all worksheets have the linked cell in row 80.  In a worksheet called "Info" I am using countif to count the total number of times the text "TRUE" occurs in row(s) 80 for all worksheets.  The total is in Info!B8.

I need to call a macro each time cell Info!b8 changes.  So in other words; every time a checkbox is clicked, the linked cell changes, cell Info!b8 goes up or down and I need a macro to run.

This is the code I am using, but it doesn't do anything.  I have researched this and from what I can tell it should work??

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$8" Then
        Call CreateFinalWorksheet
    End If
End Sub

Body:
Assuming all your CheckBoxes are of Form Controls, with a bit of altering the CheckBox Creation, you can achieve what you want without the need of LinkedCell and CountIfs etc.

Example: CreateCheckBoxes() below will create a check box for each cell in Range("D1:D5"), Name it with a prefix and the cell address, assigns the Sub CheckBoxClicked when clicked.

In Sub CheckBoxClicked(), it will go through all worksheets (except named "Info"), then increment a counter if the value of checkbox named ending D3 is 1 (ticked). After that, if threshold is met, it calls the Sub CreateFinalWorksheet().

Option Explicit

Private Const ChkBoxPrefix As String = "cbx_"
Private Const ThresholdToCreateFinalWorksheet As Long = 3

Sub CreateChkBoxes()
    Dim myCBX As CheckBox, c As Range
    For Each c In Range("D1:D5") 'rngCB
        With c
            Set myCBX = ActiveSheet.CheckBoxes.Add(Top:=.Top, Width:=.Width, Height:=.Height, Left:=.Left)
        End With
        With myCBX
            .Name = ChkBoxPrefix & c.Address(0, 0)
            .Caption = "Check Box " & c.Address(0, 0) 'strCap
            .OnAction = "CheckBoxClicked" ' "CheckBox_Click"
        End With
    Next c
End Sub

Sub CheckBoxClicked() ' CheckBox_Click()
    Dim oWS As Worksheet, lChecked As Long

    On Error Resume Next ' Just in case the named CheckBox does not exist
    lChecked = 0
    For Each oWS In ThisWorkbook.Worksheets
        If oWS.Name <> "Info" Then
            ' If you need to keep track of more than 1 checkbox in each worksheet, go through them
            ' If you need all of them to be checked before CreateFinalWorksheet, exit when a checkbox.value = 0
            With oWS.CheckBoxes(ChkBoxPrefix & "D3") ' <-- Change to what you need to keep track of
                lChecked = lChecked + IIf(.Value = 1, 1, 0)
            End With
        End If
    Next
    On Error GoTo 0
    If lChecked >= ThresholdToCreateFinalWorksheet Then CreateFinalWorksheet
End Sub

Private Sub CreateFinalWorksheet()
    Debug.Print "CreateFinalWorksheet()"
End Sub

Alternatively you put the event Sub Worksheet_Calculate() into Info module, and check if the Info!B8 is large enough to call CreateFinalWorksheet.


问:
How to convert this python code to Javascript
I don't want to run the Python code inside Javascript, I want to turn it completely into JS code. I have no idea about python, Can body can help me on this. Thank you. </p>

```<code>print ("Please input the # of books you've read this year")
BooksAlready=int(input())
print ("Please input the # of weeks that have already passed this year")
WeeksAlready=int(input())
x=(78/52)
c=x*WeeksAlready-BooksAlready
if (BooksAlready/WeeksAlready)>x:
  print ("You're on point, go have some fun!")
else:
  print ("Go read, you piece of uneducated crap")
  print ("You have")
  print (c)
  print ("books left to read this week to get on point")
</code>```

答:
This will run in the browser's js console.  prompt will not work in node.js, you can access a commandline argument with process.argv.

```<code>console.log("Please input the # of books you've read this year");
console.log("Please input the # of weeks that have already passed this year");

var WeeksAlready=parseInt(prompt()),
BooksAlready=parseInt(prompt()),
x=(78/52),
c=x*WeeksAlready-BooksAlready;

if (BooksAlready/WeeksAlready>x){
    console.log("You're on point, go have some fun!");
}
else{
   console.log ("Go read, you piece of uneducated crap");
   console.log ("You have");
   console.log (c);
   console.log ("books left to read this week to get on point");
}
</code>```

Body:
I don't want to run the Python code inside Javascript, I want to turn it completely into JS code. I have no idea about python, Can body can help me on this. Thank you.

print ("Please input the # of books you've read this year")
BooksAlready=int(input())
print ("Please input the # of weeks that have already passed this year")
WeeksAlready=int(input())
x=(78/52)
c=x*WeeksAlready-BooksAlready
if (BooksAlready/WeeksAlready)>x:
  print ("You're on point, go have some fun!")
else:
  print ("Go read, you piece of uneducated crap")
  print ("You have")
  print (c)
  print ("books left to read this week to get on point")

Body:
This will run in the browser's js console.  prompt will not work in node.js, you can access a commandline argument with process.argv.

console.log("Please input the # of books you've read this year");
console.log("Please input the # of weeks that have already passed this year");

var WeeksAlready=parseInt(prompt()),
BooksAlready=parseInt(prompt()),
x=(78/52),
c=x*WeeksAlready-BooksAlready;

if (BooksAlready/WeeksAlready>x){
    console.log("You're on point, go have some fun!");
}
else{
   console.log ("Go read, you piece of uneducated crap");
   console.log ("You have");
   console.log (c);
   console.log ("books left to read this week to get on point");
}


问:
Photoshop Action to fill image to make a certain ratio
I am looking to make a photoshop action (maybe this isn't possible, any other application recommendations would be helpful as well). I want to take a collection of photos and make them a certain aspect ration, ex: 4:3.

So I have an image that is 150px wide by 200px high. What I would like to happen is the image's canvas is made to be 267px wide, with the new area filled with a certain color.

So there are two possibilities I can think of:

1) Photoshop actions could do this, but I would have to pull current height, multiply by 1.333333 and then put that value in the width box of the canvas resize. Is it possible to have calculated values in Photoshop actions?

2) Some other application has this feature built in.

Any help is greatly appreciated.

答:
What languages do you know?  ImageMagick has command line tools that can do this, but you'd need to know a scripting language to get the values and calculate the new ones.

For .NET, my company's product, DotImage Photo, is free and can do this (need to know C# or VB.NET)

ContentLicense: CC BY-SA 2.5


问:
How to handle changeover from ASP MVC version 4.0.0.0 to 4.0.0.1
This is a followup to Windows update caused MVC3 and MVC4 stop working

I also had the issue where windows update on my development machine caused my MVC 4 project to stop working.  I changed the assembly reference to target version 4.0.0.1 and it started working.  For me.

My problem is that the application is then deployed on a number of web servers.  Actually we have a build server where the customer versions are built and then a number of web servers.

First question: When we run windows update on the production servers are the old versions of the app going to stop working? I am guessing that the answer is "yes".  We have not yet run windows update on either the build or production machines.

Changing the reference meant that it no longer could be built on the build machine.  I can get around this by setting the Specific Version flag to false and Copy Local to true.  Then it builds on both my development environment and on the build server.

Question: How lax is the check if I have Specific Version false?  Does it allow 4.0.0.x? 4.0.x.x? 4.x.x.x? or x.x.x.x?

However, it even thoguh it builds in thsi configuration it then fails to run (cannot find assembly) on the test web server.  The problem here is that I have the following in my web.config (as per Microsofts instructions when I upgraded from MVC 2 to MVC 4):

```<code><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity culture="neutral" name="System.Web.Mvc" publicKeyToken="31BF3856AD364E35"/>
    <bindingRedirect newVersion="4.0.0.1" oldVersion="0.0.0.0-4.0.0.1"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect newVersion="2.0.0.0" oldVersion="1.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect newVersion="4.0.0.0" oldVersion="1.0.0.0-3.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect newVersion="2.0.0.0" oldVersion="1.0.0.0"/>
  </dependentAssembly>
</assemblyBinding>
</code>```

The problem is the line

```<code><bindingRedirect newVersion="4.0.0.1" oldVersion="0.0.0.0-4.0.0.1"/>
</code>```

for the System.Web.Mvc assembly.  (It used to say 4.0.0.0 not 4.0.0.1 in that row of course.)  If I change back to 4.0.0.0 on the test server then it works.

My problem is two-fold.  Partly it is just that I want to be able to build and run both locally and on our build/production servers.  However, we have a situation where we host a number of customers running different versions of our application on the same server.  We cannot force all our customers to upgrade to latest version at once just because of this windows update fix - apart from anything else the web application is just part of a larger suite of applications so we would have to force them to upgrade the lot!

I suppose one option is to checkout each of the old version still in use, update the MVC version number and create a new version.  Then when we update the web server we have to update all the customers on that server to a new (4.0.0.1 compatible) version of their current version.  I'd really like to avoid having to update, commit and rebuild that many versions if possible.

Another option would be to not run the windows update on the web server and try and install both 4.0.0.0 and 4.0.0.1 dlls on the build machine.  Then we could build both old and new version. Since any new versions (using 4.0.0.1) have CopyLocal set to true on the MVC assembly (the old ones do not) they should be able to be deployed to the web servers without the web servers themselves being updated.

Questions:

Does anyone know if it is possible to have both versions installed simultaneously? I am hoping I could simply save the 4.0.0.0 dll, run windows update then copy to old dll back to GAC alongside the new.

How serious is the security risk fixed by this patch?  Is it a problem to allow people to run the old versions a while longer?  Is just having the old .dll on the web server a security risk or only for the applications which use it?

Is there any way of doing a bindingRedirect to 4.0.0.x?  or is it possible to simply remove the binding redirect altogether?

I cannot believe I am the only one in this situation and would also welcome any suggestions for solutions I haven't thought of at all.

答: I was a member of a team that encountered this same problem from a slightly different angle.  The error message that it posts when the security update is wrong can be misleading and hard to interpret. We ran into deployment and build errors when we tried to publish our apps to different environments.  The root cause was that this patch was applied via windows update on some test environments but not on other servers.  Any server that did not have the patch would crash when we deployed our application.  I would recommend having your systems team apply the patch and upgrade all of your applications to reference this DLL. Security updates Because the library referenced is ignored in source control, but still spelled out verbosely in web configs it needs to be addressed quickly. Some environments will allow you to right click and choose which MVC dll version to use locally and still deploy your application without issues.  If you are using web deploy, and MUST have the ability to switch, you could write web config transforms for each Transforms web config.  One thing i noticed when fixing this issue (upgrading to 4.0.0.1) is that upgrading to the latest version of MVC.dll in my project allowed me to get the latest versions of nuget packages.  If you do not upgrade and stay with the old versions, you will be stuck with old versions of the MVC javascript, jquery, and other libraries.  </p>

Body:
This is a followup to Windows update caused MVC3 and MVC4 stop working

I also had the issue where windows update on my development machine caused my MVC 4 project to stop working.  I changed the assembly reference to target version 4.0.0.1 and it started working.  For me.

My problem is that the application is then deployed on a number of web servers.  Actually we have a build server where the customer versions are built and then a number of web servers.

First question: When we run windows update on the production servers are the old versions of the app going to stop working? I am guessing that the answer is "yes".  We have not yet run windows update on either the build or production machines.

Changing the reference meant that it no longer could be built on the build machine.  I can get around this by setting the Specific Version flag to false and Copy Local to true.  Then it builds on both my development environment and on the build server.

Question: How lax is the check if I have Specific Version false?  Does it allow 4.0.0.x? 4.0.x.x? 4.x.x.x? or x.x.x.x?

However, it even thoguh it builds in thsi configuration it then fails to run (cannot find assembly) on the test web server.  The problem here is that I have the following in my web.config (as per Microsofts instructions when I upgraded from MVC 2 to MVC 4):

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity culture="neutral" name="System.Web.Mvc" publicKeyToken="31BF3856AD364E35"/>
    <bindingRedirect newVersion="4.0.0.1" oldVersion="0.0.0.0-4.0.0.1"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect newVersion="2.0.0.0" oldVersion="1.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect newVersion="4.0.0.0" oldVersion="1.0.0.0-3.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect newVersion="2.0.0.0" oldVersion="1.0.0.0"/>
  </dependentAssembly>
</assemblyBinding>

The problem is the line

<bindingRedirect newVersion="4.0.0.1" oldVersion="0.0.0.0-4.0.0.1"/>

for the System.Web.Mvc assembly.  (It used to say 4.0.0.0 not 4.0.0.1 in that row of course.)  If I change back to 4.0.0.0 on the test server then it works.

My problem is two-fold.  Partly it is just that I want to be able to build and run both locally and on our build/production servers.  However, we have a situation where we host a number of customers running different versions of our application on the same server.  We cannot force all our customers to upgrade to latest version at once just because of this windows update fix - apart from anything else the web application is just part of a larger suite of applications so we would have to force them to upgrade the lot!

I suppose one option is to checkout each of the old version still in use, update the MVC version number and create a new version.  Then when we update the web server we have to update all the customers on that server to a new (4.0.0.1 compatible) version of their current version.  I'd really like to avoid having to update, commit and rebuild that many versions if possible.

Another option would be to not run the windows update on the web server and try and install both 4.0.0.0 and 4.0.0.1 dlls on the build machine.  Then we could build both old and new version. Since any new versions (using 4.0.0.1) have CopyLocal set to true on the MVC assembly (the old ones do not) they should be able to be deployed to the web servers without the web servers themselves being updated.

Questions:

Does anyone know if it is possible to have both versions installed simultaneously? I am hoping I could simply save the 4.0.0.0 dll, run windows update then copy to old dll back to GAC alongside the new.

How serious is the security risk fixed by this patch?  Is it a problem to allow people to run the old versions a while longer?  Is just having the old .dll on the web server a security risk or only for the applications which use it?

Is there any way of doing a bindingRedirect to 4.0.0.x?  or is it possible to simply remove the binding redirect altogether?

I cannot believe I am the only one in this situation and would also welcome any suggestions for solutions I haven't thought of at all.


问:
how can i query where clause using between date in sphinx
I have this query:

```<code>select * from tabel where last_purchase_categories = 'flight'
 and last_purchase_date between '2016-10-23 11:06:47' and '2016-10-23 11:06:49';
</code>```

it is didnt work in sphinx. i use fulltext search using mysql query browser.
do anyone know how to using date format in sphinx ?

答:
let's try this

it will work.

```<code>SELECT count(*) FROM `tabel`
where last_purchase_categories = 'flight' and
    last_purchase_date between '2017-03-27 02:13:11' and '2017-03-27 02:13:20'
</code>```

Body:
I have this query:

select * from tabel where last_purchase_categories = 'flight'
 and last_purchase_date between '2016-10-23 11:06:47' and '2016-10-23 11:06:49';

it is didnt work in sphinx. i use fulltext search using mysql query browser.
do anyone know how to using date format in sphinx ?

Body:
let's try this

it will work.

SELECT count(*) FROM `tabel`
where last_purchase_categories = 'flight' and
    last_purchase_date between '2017-03-27 02:13:11' and '2017-03-27 02:13:20'


问:
Trim whitespaces on a String
How can I trim whitespaces on strings from their left and right sides?

For example,

```<code>___abc_d__
</code>```

will be:

```<code>abc_d
</code>```

答:
A single regular expression would work as well. This expression captures all leading spaces, the rest of the string's content until the trailing spaces, and the trailing spaces. It then substitutes those with the length of the first group (in parentheses), the second group, and the length of the third group (in parentheses), respectively.

```<code>import re

def replace(s):
    return '({}){}({})'.format(len(s.group(1)), s.group(2), len(s.group(3)))
    # or, with Python 3.6 f-strings:
    # return f'({len(s.group(1))}){s.group(2)}({len(s.group(3))})'

expression = re.compile(r'^( *)(.*?)( *)$')
</code>```

Results:

```<code>>>> expression.sub(replace, '   abc d  ') #  becomes (3)abc d(2)
'(3)abc d(2)'
>>> expression.sub(replace, ' abc    ') # becomes (1)abc(4)
'(1)abc(4)'
</code>```

Note that this only replaces spaces, not all whitespace characters - use \s for that instead. Also, your desired output showed parentheses around the lengths, while your sample code didn't appear to be trying to do that. You can easily alter the format string in the replace function. Finally, the underscore character, '_', is different from the space character, ' '. I assume your actual strings have spaces, and you only used underscores to give us a visible character. Once again, you can easily change this behavior, this time by replacing expression's spaces with underscores (or any character you like).

ContentLicense: CC BY-SA 4.0

Title: Trim whitespaces on a String

Body:
How can I trim whitespaces on strings from their left and right sides?

For example,

___abc_d__

will be:

abc_d

Body:
A single regular expression would work as well. This expression captures all leading spaces, the rest of the string's content until the trailing spaces, and the trailing spaces. It then substitutes those with the length of the first group (in parentheses), the second group, and the length of the third group (in parentheses), respectively.

import re

def replace(s):
    return '({}){}({})'.format(len(s.group(1)), s.group(2), len(s.group(3)))
    # or, with Python 3.6 f-strings:
    # return f'({len(s.group(1))}){s.group(2)}({len(s.group(3))})'

expression = re.compile(r'^( *)(.*?)( *)$')

Results:

>>> expression.sub(replace, '   abc d  ') #  becomes (3)abc d(2)
'(3)abc d(2)'
>>> expression.sub(replace, ' abc    ') # becomes (1)abc(4)
'(1)abc(4)'

Note that this only replaces spaces, not all whitespace characters - use \s for that instead. Also, your desired output showed parentheses around the lengths, while your sample code didn't appear to be trying to do that. You can easily alter the format string in the replace function. Finally, the underscore character, '_', is different from the space character, ' '. I assume your actual strings have spaces, and you only used underscores to give us a visible character. Once again, you can easily change this behavior, this time by replacing expression's spaces with underscores (or any character you like).


问:
"Scroll to the element" javascript won't work on my website. JQuery
I took this bootstrap template below to develop my own website. Everything worked but the "scroll to the element script". I keep getting this error:
Uncaught Error: Syntax error, unrecognized expression: [href=#],[data-toggle],[data-target],[data-slide]
I think this particular piece of code is deprecated, it woos good with JQuery 2x but not with the new ones. Could someone help me change this script to make it work?

// Scrolls to the selected menu item on the page
      $(function() {
          $('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() {
              if (location.pathname.replace(/^//, '') == this.pathname.replace(/^//, '') || location.hostname == this.hostname) {
                  var target = $(this.hash);
                  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                  if (target.length) {
                      $('html,body').animate({
                          scrollTop: target.offset().top
                      }, 1000);
                      return false;
                  }
              }
          });
      });
  `

Here's the whole soursecode:

```<code><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<title>Stylish Portfolio - Start Bootstrap Theme</title>

<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">

<!-- Custom CSS -->
<link href="css/stylish-portfolio.css" rel="stylesheet">

<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</code>```

```<code><!-- Navigation -->
<a id="menu-toggle" href="#" class="btn btn-dark btn-lg toggle"><i class="fa fa-bars"></i></a>
<nav id="sidebar-wrapper">
    <ul class="sidebar-nav">
        <a id="menu-close" href="#" class="btn btn-light btn-lg pull-right toggle"><i class="fa fa-times"></i></a>
        <li class="sidebar-brand">
            <a href="#top" onclick=$("#menu-close").click();>Start Bootstrap</a>
        </li>
        <li>
            <a href="#top" onclick=$("#menu-close").click();>Home</a>
        </li>
        <li>
            <a href="#about" onclick=$("#menu-close").click();>About</a>
        </li>
        <li>
            <a href="#services" onclick=$("#menu-close").click();>Services</a>
        </li>
        <li>
            <a href="#portfolio" onclick=$("#menu-close").click();>Portfolio</a>
        </li>
        <li>
            <a href="#contact" onclick=$("#menu-close").click();>Contact</a>
        </li>
    </ul>
</nav>

<!-- Header -->
<header id="top" class="header">
    <div class="text-vertical-center">
        <h1>Start Bootstrap</h1>
        <h3>Free Bootstrap Themes & Templates</h3>
        <br>
        <a href="#about" class="btn btn-dark btn-lg">Find Out More</a>
    </div>
</header>

<!-- About -->
<section id="about" class="about">
    <div class="container">
        <div class="row">
            <div class="col-lg-12 text-center">
                <h2>Stylish Portfolio is the perfect theme for your next project!</h2>
                <p class="lead">This theme features some wonderful photography courtesy of <a target="_blank" href="http://join.deathtothestockphoto.com/">Death to the Stock Photo</a>.</p>
            </div>
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container -->
</section>

<!-- Services -->
<!-- The circle icons use Font Awesome's stacked icon classes. For more information, visit http://fontawesome.io/examples/ -->
<section id="services" class="services bg-primary">
    <div class="container">
        <div class="row text-center">
            <div class="col-lg-10 col-lg-offset-1">
                <h2>Our Services</h2>
                <hr class="small">
                <div class="row">
                    <div class="col-md-3 col-sm-6">
                        <div class="service-item">
                            <span class="fa-stack fa-4x">
                            <i class="fa fa-circle fa-stack-2x"></i>
                            <i class="fa fa-cloud fa-stack-1x text-primary"></i>
                        </span>
                            <h4>
                                <strong>Service Name</strong>
                            </h4>
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
                            <a href="#" class="btn btn-light">Learn More</a>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-6">
                        <div class="service-item">
                            <span class="fa-stack fa-4x">
                            <i class="fa fa-circle fa-stack-2x"></i>
                            <i class="fa fa-compass fa-stack-1x text-primary"></i>
                        </span>
                            <h4>
                                <strong>Service Name</strong>
                            </h4>
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
                            <a href="#" class="btn btn-light">Learn More</a>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-6">
                        <div class="service-item">
                            <span class="fa-stack fa-4x">
                            <i class="fa fa-circle fa-stack-2x"></i>
                            <i class="fa fa-flask fa-stack-1x text-primary"></i>
                        </span>
                            <h4>
                                <strong>Service Name</strong>
                            </h4>
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
                            <a href="#" class="btn btn-light">Learn More</a>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-6">
                        <div class="service-item">
                            <span class="fa-stack fa-4x">
                            <i class="fa fa-circle fa-stack-2x"></i>
                            <i class="fa fa-shield fa-stack-1x text-primary"></i>
                        </span>
                            <h4>
                                <strong>Service Name</strong>
                            </h4>
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
                            <a href="#" class="btn btn-light">Learn More</a>
                        </div>
                    </div>
                </div>
                <!-- /.row (nested) -->
            </div>
            <!-- /.col-lg-10 -->
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container -->
</section>

<!-- Callout -->
<aside class="callout">
    <div class="text-vertical-center">
        <h1>Vertically Centered Text</h1>
    </div>
</aside>

<!-- Portfolio -->
<section id="portfolio" class="portfolio">
    <div class="container">
        <div class="row">
            <div class="col-lg-10 col-lg-offset-1 text-center">
                <h2>Our Work</h2>
                <hr class="small">
                <div class="row">
                    <div class="col-md-6">
                        <div class="portfolio-item">
                            <a href="#">
                                <img class="img-portfolio img-responsive" src="img/portfolio-1.jpg">
                            </a>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="portfolio-item">
                            <a href="#">
                                <img class="img-portfolio img-responsive" src="img/portfolio-2.jpg">
                            </a>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="portfolio-item">
                            <a href="#">
                                <img class="img-portfolio img-responsive" src="img/portfolio-3.jpg">
                            </a>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="portfolio-item">
                            <a href="#">
                                <img class="img-portfolio img-responsive" src="img/portfolio-4.jpg">
                            </a>
                        </div>
                    </div>
                </div>
                <!-- /.row (nested) -->
                <a href="#" class="btn btn-dark">View More Items</a>
            </div>
            <!-- /.col-lg-10 -->
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container -->
</section>

<!-- Call to Action -->
<aside class="call-to-action bg-primary">
    <div class="container">
        <div class="row">
            <div class="col-lg-12 text-center">
                <h3>The buttons below are impossible to resist.</h3>
                <a href="#" class="btn btn-lg btn-light">Click Me!</a>
                <a href="#" class="btn btn-lg btn-dark">Look at Me!</a>
            </div>
        </div>
    </div>
</aside>

<!-- Map -->
<section id="contact" class="map">
    <iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=Twitter,+Inc.,+Market+Street,+San+Francisco,+CA&aq=0&oq=twitter&sll=28.659344,-81.187888&sspn=0.128789,0.264187&ie=UTF8&hq=Twitter,+Inc.,+Market+Street,+San+Francisco,+CA&t=m&z=15&iwloc=A&output=embed"></iframe>
    <br />
    <small>
        <a href="https://maps.google.com/maps?f=q&source=embed&hl=en&geocode=&q=Twitter,+Inc.,+Market+Street,+San+Francisco,+CA&aq=0&oq=twitter&sll=28.659344,-81.187888&sspn=0.128789,0.264187&ie=UTF8&hq=Twitter,+Inc.,+Market+Street,+San+Francisco,+CA&t=m&z=15&iwloc=A"></a>
    </small>
</section>

<!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-10 col-lg-offset-1 text-center">
                <h4><strong>Start Bootstrap</strong>
                </h4>
                <p>3481 Melrose Place
                    <br>Beverly Hills, CA 90210</p>
                <ul class="list-unstyled">
                    <li><i class="fa fa-phone fa-fw"></i> (123) 456-7890</li>
                    <li><i class="fa fa-envelope-o fa-fw"></i> <a href="mailto:name@example.com">name@example.com</a>
                    </li>
                </ul>
                <br>
                <ul class="list-inline">
                    <li>
                        <a href="#"><i class="fa fa-facebook fa-fw fa-3x"></i></a>
                    </li>
                    <li>
                        <a href="#"><i class="fa fa-twitter fa-fw fa-3x"></i></a>
                    </li>
                    <li>
                        <a href="#"><i class="fa fa-dribbble fa-fw fa-3x"></i></a>
                    </li>
                </ul>
                <hr class="small">
                <p class="text-muted">Copyright © Your Website 2014</p>
            </div>
        </div>
    </div>
    <a id="to-top" href="#top" class="btn btn-dark btn-lg"><i class="fa fa-chevron-up fa-fw fa-1x"></i></a>
</footer>

<!-- jQuery -->
<script src="js/jquery.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script>
// Closes the sidebar menu
$("#menu-close").click(function(e) {
    e.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
});
// Opens the sidebar menu
$("#menu-toggle").click(function(e) {
    e.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
});
// Scrolls to the selected menu item on the page
$(function() {
    $('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});
//#to-top button appears after scrolling
var fixed = false;
$(document).scroll(function() {
    if ($(this).scrollTop() > 250) {
        if (!fixed) {
            fixed = true;
            // $('#to-top').css({position:'fixed', display:'block'});
            $('#to-top').show("slow", function() {
                $('#to-top').css({
                    position: 'fixed',
                    display: 'block'
                });
            });
        }
    } else {
        if (fixed) {
            fixed = false;
            $('#to-top').hide("slow", function() {
                $('#to-top').css({
                    display: 'none'
                });
            });
        }
    }
});
// Disable Google Maps scrolling
// See http://stackoverflow.com/a/25904582/1607849
// Disable scroll zooming and bind back the click event
var onMapMouseleaveHandler = function(event) {
    var that = $(this);
    that.on('click', onMapClickHandler);
    that.off('mouseleave', onMapMouseleaveHandler);
    that.find('iframe').css("pointer-events", "none");
}
var onMapClickHandler = function(event) {
        var that = $(this);
        // Disable the click handler until the user leaves the map area
        that.off('click', onMapClickHandler);
        // Enable scrolling zoom
        that.find('iframe').css("pointer-events", "auto");
        // Handle the mouse leave event
        that.on('mouseleave', onMapMouseleaveHandler);
    }
    // Enable map zooming with mouse scroll when the user clicks the map
$('.map').on('click', onMapClickHandler);
</script>
</code>```

`

答:
Try escaping # with \\ infront of it, as it is a special character.

```<code>$('a[href*=\\#]:not([href=\\#][data-toggle][data-target][data-slide])')
</code>```

This will work!

Body:
I took this bootstrap template below to develop my own website. Everything worked but the "scroll to the element script". I keep getting this error:
Uncaught Error: Syntax error, unrecognized expression: [href=#],[data-toggle],[data-target],[data-slide]
I think this particular piece of code is deprecated, it woos good with JQuery 2x but not with the new ones. Could someone help me change this script to make it work?

// Scrolls to the selected menu item on the page
      $(function() {
          $('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() {
              if (location.pathname.replace(/^//, '') == this.pathname.replace(/^//, '') || location.hostname == this.hostname) {
                  var target = $(this.hash);
                  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                  if (target.length) {
                      $('html,body').animate({
                          scrollTop: target.offset().top
                      }, 1000);
                      return false;
                  }
              }
          });
      });
  `

Here's the whole soursecode:

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<title>Stylish Portfolio - Start Bootstrap Theme</title>

<link href="css/bootstrap.min.css" rel="stylesheet">

<link href="css/stylish-portfolio.css" rel="stylesheet">

<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

            Start Bootstrap

            Home

            About

            Services

            Portfolio

            Contact

Start Bootstrap

Free Bootstrap Themes & Templates

        Find Out More

Stylish Portfolio is the perfect theme for your next project!

This theme features some wonderful photography courtesy of Death to the Stock Photo.

Our Services

                                Service Name

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                            Learn More

                                Service Name

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                            Learn More

                                Service Name

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                            Learn More

                                Service Name

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                            Learn More

Vertically Centered Text

Our Work

                View More Items

The buttons below are impossible to resist.

                Click Me!
                Look at Me!

Start Bootstrap

3481 Melrose Place

Beverly Hills, CA 90210

 (123) 456-7890

 name@example.com

Copyright © Your Website 2014

`

Body:
Try escaping # with \\ infront of it, as it is a special character.

$('a[href*=\\#]:not([href=\\#][data-toggle][data-target][data-slide])')

This will work!


问:
How to Map a string and char pair to a string using a std::map?
I am trying to take a std::pair and map it to a std::string using a std::map. The way it works being given a pair consisting of a char and a string, map it to a particular string.

This setup so far works just fine(compiler accepts it):

```<code>std::map<std::pair<char, std::string>, std::string> mymap;
std::map<std::pair<char, std::string>, std::string>::iterator it;
</code>```

But when i try to do this:

```<code>mymap['a', "Q1"] = "Q4";
mymap['b', "Q2"] = "Q3";
mymap['c', "Q3"] = "Q2";
mymap['d', "Q4"] = "Q1";
</code>```

it comes back as this error which I do not understand:

```<code>Error   1   error C2679: binary '[' : no operator found which takes a right-hand operand of type 'const char [3]' (or there is no acceptable conversion)
</code>```

which is the error associated under the left bracket of each of the four lines of code(where a red squiggly appears)

can someone help me to understand what I am doing wrong?

答:
the [] operator for the std::map accepts only one argument, whereas you provided two. Since you want to use an object of type std::pair, you should make an std::pair object with your char and std::string. You can do it by enclosing them in {}:

```<code>mymap[{'a', "Q1"}] = "Q4";
mymap[{'b', "Q2"}] = "Q3";
mymap[{'c', "Q3"}] = "Q2";
mymap[{'d', "Q4"}] = "Q1";
</code>```

You could also provide an object definition each time you try yo access the elements:

```<code>mymap[std::pair<char, std::string>('a', "Q1")] = "Q4";
mymap[std::pair<char, std::string>('b', "Q2")] = "Q3";
mymap[std::pair<char, std::string>('c', "Q3")] = "Q2";
mymap[std::pair<char, std::string>('d', "Q4")] = "Q1";
</code>```

But the first option in my opinion is better and less errorprone.

Body:
I am trying to take a std::pair and map it to a std::string using a std::map. The way it works being given a pair consisting of a char and a string, map it to a particular string.

This setup so far works just fine(compiler accepts it):

std::map<std::pair<char, std::string>, std::string> mymap;
std::map<std::pair<char, std::string>, std::string>::iterator it;

But when i try to do this:

mymap['a', "Q1"] = "Q4";
mymap['b', "Q2"] = "Q3";
mymap['c', "Q3"] = "Q2";
mymap['d', "Q4"] = "Q1";

it comes back as this error which I do not understand:

Error   1   error C2679: binary '[' : no operator found which takes a right-hand operand of type 'const char [3]' (or there is no acceptable conversion)

which is the error associated under the left bracket of each of the four lines of code(where a red squiggly appears)

can someone help me to understand what I am doing wrong?

Body:
the [] operator for the std::map accepts only one argument, whereas you provided two. Since you want to use an object of type std::pair, you should make an std::pair object with your char and std::string. You can do it by enclosing them in {}:

mymap[{'a', "Q1"}] = "Q4";
mymap[{'b', "Q2"}] = "Q3";
mymap[{'c', "Q3"}] = "Q2";
mymap[{'d', "Q4"}] = "Q1";

You could also provide an object definition each time you try yo access the elements:

mymap[std::pair<char, std::string>('a', "Q1")] = "Q4";
mymap[std::pair<char, std::string>('b', "Q2")] = "Q3";
mymap[std::pair<char, std::string>('c', "Q3")] = "Q2";
mymap[std::pair<char, std::string>('d', "Q4")] = "Q1";

But the first option in my opinion is better and less errorprone.


问:
Google Analytics with a fixed URL site
I have a issue to track the user navigation in a site with FIXED URLs

No matter where the user is the URL will always be http://www.myurl.com

And so in my report the user stay always be at the on http://www.myurl.com

I would like to know if i can add something to the tracking script to improve the user tracking data

```<code><!-- default google tacking code -->
<script>
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

        ga('create', $cod, 'auto');
        ga('send', 'pageview');

</script>
</code>```

UPDATE

My solution:

Main page

```<code>    <!-- default google tacking code -->

    $this->response->insertScript($this->_minify("

                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

                ga('create', '" . $cod . "', 'auto');
                ga('set', 'page', '" . $page . "');
                ga('send', 'pageview');

    "));
</code>```

Forms, reports, windows

```<code>    <!-- additional information -->

    $this->response->insertScript($this->_minify("

                ga('set', 'page', '" . $page . "');
                ga('send', 'pageview');

    "));
</code>```

答:
As I understand your site is a Single Page App so the URL does not change through the user's visit. The is a specific guide for SPA's here

All in all what you want to do is implement 'virtual' pageviews each time a user navigates to a new section of your site. You can set the 'page' attribute on the tracker and send a pageview using the command below

```<code>ga('set', 'page', '/new-page.html');
ga('send', 'pageview');
</code>```

Title: Google Analytics with a fixed URL site

Body:
I have a issue to track the user navigation in a site with FIXED URLs

No matter where the user is the URL will always be http://www.myurl.com

And so in my report the user stay always be at the on http://www.myurl.com

I would like to know if i can add something to the tracking script to improve the user tracking data

UPDATE

My solution:

Main page

    $this->response->insertScript($this->_minify("

                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

                ga('create', '" . $cod . "', 'auto');
                ga('set', 'page', '" . $page . "');
                ga('send', 'pageview');

    "));

Forms, reports, windows

    $this->response->insertScript($this->_minify("

                ga('set', 'page', '" . $page . "');
                ga('send', 'pageview');

    "));

Body:
As I understand your site is a Single Page App so the URL does not change through the user's visit. The is a specific guide for SPA's here

All in all what you want to do is implement 'virtual' pageviews each time a user navigates to a new section of your site. You can set the 'page' attribute on the tracker and send a pageview using the command below

ga('set', 'page', '/new-page.html');
ga('send', 'pageview');


问:
Angular-material ng-click strange border highlight
I have a problem with using AngularJS and Angular-Material.

Take a look at the following code:

```<code><div flex="100">
   <ul class="list-group">
       <li class="list-group-item cursorPointer"
        ng-repeat="item in array" ng-click="selectItem(item)">
          {{item.name}}
       </li>
    </ul>
</div>
</code>```

The li tag has a ng-click function attach to it that contains some business logic. The problem is that there appears a strange border when you click on it (similar to user-selection highlight) and  I can't seem to figure out where is it coming from.

This seems to appear only when I have an ng-click directive on an element (same behavior on span element)

Versions used:

AngularJS - 1.4.1

Angular-Material - 0.9.4

Angular-Aria - 1.4.0

Angular-Animate - 1.4.1

Angular-UI-Boostrap - 0.9.0

Bootstrap - 3.2.0

JQuery - 2.1.4

Any ideas? See this plnkr for example: http://plnkr.co/edit/60u8Ur?p=preview

答:
this may be easy :

add nofocus class to that elements,

and add css to that class on :focus

```<code>.nofocus:focus {
    outline: none;
}
</code>```

Body:
I have a problem with using AngularJS and Angular-Material.

Take a look at the following code:

          {{item.name}}

The li tag has a ng-click function attach to it that contains some business logic. The problem is that there appears a strange border when you click on it (similar to user-selection highlight) and  I can't seem to figure out where is it coming from.

This seems to appear only when I have an ng-click directive on an element (same behavior on span element)

Versions used:

AngularJS - 1.4.1

Angular-Material - 0.9.4

Angular-Aria - 1.4.0

Angular-Animate - 1.4.1

Angular-UI-Boostrap - 0.9.0

Bootstrap - 3.2.0

JQuery - 2.1.4

Any ideas? See this plnkr for example: http://plnkr.co/edit/60u8Ur?p=preview

Body:
this may be easy :

add nofocus class to that elements,

and add css to that class on :focus

.nofocus:focus {
    outline: none;
}


问:
How to remove escaped double-quotes inside a string in Common Lisp?
Running (cl-json:encode-json-to-string 'ctx) gives "\"ctx\""

I need "ctx" not "\"ctx\"".

I could use cl-ppcre and remove matching double-quotes inside the string.
However, this seems like overkill. Is there any other way to do this?

答:
What does gives "\"ctx\"" mean?

Common Lisp uses the \ as a escape character during printing results.

The string itself has five characters:

```<code>CL-USER 12 > (describe "\"ctx\"")

"\"ctx\"" is a SIMPLE-BASE-STRING
0      #\"
1      #\c
2      #\t
3      #\x
4      #\"
</code>```

You can print the string contents:

```<code>CL-USER 11 > (write-string "\"ctx\"")
"ctx"
"\"ctx\""
</code>```

You can also remove the first and last characters:

```<code>CL-USER 10 > (subseq "\"ctx\"" 1 (- 6 2))
"ctx"
</code>```

You can also trim all surrounding " characters:

```<code>CL-USER 13 > (string-trim "\"" "\"ctx\"")
"ctx"

CL-USER 14 > (string-trim '(#\") "\"ctx\"")
"ctx"
</code>```

String trim takes a sequence of characters as the first argument: the characters to remove. The second argument is the string.

Note that it will remove all such characters from front and back:

```<code>CL-USER 15 > (string-trim "\"" "\"\"\"\"ctx\"\"\"\"\"\"\"")
"ctx"
</code>```

Body:
What does gives "\"ctx\"" mean?

Common Lisp uses the \ as a escape character during printing results.

The string itself has five characters:

CL-USER 12 > (describe "\"ctx\"")

"\"ctx\"" is a SIMPLE-BASE-STRING
0      #\"
1      #\c
2      #\t
3      #\x
4      #\"

You can print the string contents:

CL-USER 11 > (write-string "\"ctx\"")
"ctx"
"\"ctx\""

You can also remove the first and last characters:

CL-USER 10 > (subseq "\"ctx\"" 1 (- 6 2))
"ctx"

You can also trim all surrounding " characters:

CL-USER 13 > (string-trim "\"" "\"ctx\"")
"ctx"

CL-USER 14 > (string-trim '(#\") "\"ctx\"")
"ctx"

String trim takes a sequence of characters as the first argument: the characters to remove. The second argument is the string.

Note that it will remove all such characters from front and back:

CL-USER 15 > (string-trim "\"" "\"\"\"\"ctx\"\"\"\"\"\"\"")
"ctx"


问:
Button click background image bigger animation and load new page
On a site's blog section there is a nice effect for opening new blogs.

On the blogpost, there is a link to next blogpost at the bottom. If you click on the read more button the background gets bigger and automatically loads the content of that blog post. Example can be found here -

https://www.odoo.com/blog/odoo-news-5/post/odoo-10-released-337

How to implement this effect?

答:
You can make the a link as READ MORE and write a route and controller to open the current blog with that link.
eg:
in view:

```<code><a t-att-href="'/blog/custom?id='+blog.id"/>
<!-- give proper style to display as a button -->
</code>```

in controller

```<code>@http.route('/blog/custom', csrf=False, type="http", methods=['POST', 'GET'], auth="public", website=True)
def custom_blog(self, **kw):
    data = request.env['blog.blog'].browse(kw and kw.get('id'))
    return request.render('your_template', {'data':data }) #use dict key as per your custom template
</code>```

Body:
You can make the a link as READ MORE and write a route and controller to open the current blog with that link.
eg:
in view:

<a t-att-href="'/blog/custom?id='+blog.id"/>
<!-- give proper style to display as a button -->

in controller

@http.route('/blog/custom', csrf=False, type="http", methods=['POST', 'GET'], auth="public", website=True)
def custom_blog(self, **kw):
    data = request.env['blog.blog'].browse(kw and kw.get('id'))
    return request.render('your_template', {'data':data }) #use dict key as per your custom template


问:
check if row already exists if does not exist insert row otherwise show message
```<code>String sql2="if not exists(select * FROM stock where productCode=?)\n" +
                    "Begin\n" +
                    "insert into stock "
                  + "(productName,quantity,currentQuantity,price,companyName,categoryName,productCode) "
                  + "values(?,?,?,?,?,?,?)\n" +
                    "End";
            PreparedStatement pst2 = con.prepareStatement(sql2);
            pst2.setString(1,productCodeTextField.getText());
            pst2.setString(2,productNameTextField.getText());
            pst2.setString(3,quantityTextField.getText());
            pst2.setString(4,quantityTextField.getText());
            pst2.setString(5,priceTextField.getText());
            pst2.setString(6, (String) companyNameJComboBox.getSelectedItem());
            pst2.setString(7, (String) categoryNameJComboBox.getSelectedItem());
            pst2.setString(8,productCodeTextField.getText());
            int x=pst2.executeUpdate();
            if(x!=0){
                productCodeTextField.setText("");
                productNameTextField.setText("");
                quantityTextField.setText("");
                priceTextField.setText("");
                JOptionPane.showMessageDialog(null,"Product entered");
            }else{
                JOptionPane.showMessageDialog(null,"Product already exists");
            }
</code>```

I am successfully able to check for for already existing products before insertion but i am not able to populate the correct message on the basis of the query executed. The executeUpdate is always returning some value even when the insertion is not being done. How to fix this.

答:
There is an easier solution that may work for you:

Throw away the first query that checks whether the entry already exists

Rewrite sql2 as follows:

```<code>INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
VALUES (?,?,?,?,?,?)
WHERE NOT EXISTS
    (SELECT * FROM stock WHERE productCode = ?)
</code>```

Add:  pst.setString(7, productCodeTextField.getText());

executeUpdate() returns an int indicating the number of rows affected by the query.  Use this variable to determine if a row was added.  If the variable != 0 display success message.

Body:
String sql2="if not exists(select * FROM stock where productCode=?)\n" +
                    "Begin\n" +
                    "insert into stock "
                  + "(productName,quantity,currentQuantity,price,companyName,categoryName,productCode) "
                  + "values(?,?,?,?,?,?,?)\n" +
                    "End";
            PreparedStatement pst2 = con.prepareStatement(sql2);
            pst2.setString(1,productCodeTextField.getText());
            pst2.setString(2,productNameTextField.getText());
            pst2.setString(3,quantityTextField.getText());
            pst2.setString(4,quantityTextField.getText());
            pst2.setString(5,priceTextField.getText());
            pst2.setString(6, (String) companyNameJComboBox.getSelectedItem());
            pst2.setString(7, (String) categoryNameJComboBox.getSelectedItem());
            pst2.setString(8,productCodeTextField.getText());
            int x=pst2.executeUpdate();
            if(x!=0){
                productCodeTextField.setText("");
                productNameTextField.setText("");
                quantityTextField.setText("");
                priceTextField.setText("");
                JOptionPane.showMessageDialog(null,"Product entered");
            }else{
                JOptionPane.showMessageDialog(null,"Product already exists");
            }

I am successfully able to check for for already existing products before insertion but i am not able to populate the correct message on the basis of the query executed. The executeUpdate is always returning some value even when the insertion is not being done. How to fix this.

Body:
There is an easier solution that may work for you:

Throw away the first query that checks whether the entry already exists

Rewrite sql2 as follows:

INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
VALUES (?,?,?,?,?,?)
WHERE NOT EXISTS
    (SELECT * FROM stock WHERE productCode = ?)

Add:  pst.setString(7, productCodeTextField.getText());

executeUpdate() returns an int indicating the number of rows affected by the query.  Use this variable to determine if a row was added.  If the variable != 0 display success message.


问:
Return-Path overwritten by Exim?
I have a VPS with cPanel and I'm using PHPMailer to send email through the local SMTP server which is run by exim, the problem is that I actually add:

```<code>$mail->AddCustomHeader('Return-Path: sender@domain.com');
</code>```

But it's being overwritten with the default one, I know that I can do it with the -f 5th parameter in mail() but I want to do it using PHPMailer dynamically..

Appreciating any help.

Thanks

答:
The PHPMailer class has a Sender variable which sets the -f parameter (or constructs the appropriate MAIL FROM: command when using SMTP) as necessary. From the source code:

```<code>/**
 * Sets the Sender email (Return-Path) of the message.  If not empty,
 * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
 * @var string
 */
public $Sender            = '';
</code>```

so you can presumably do something like:

```<code>$mail->Sender = 'sender@domain.com';
</code>```

Outgoing mail servers tend to ignore Return-Path since they have the address from the SMTP MAIL FROM: line. The Return-Path header is inserted by the recipient's mail server for use in filters or other downstream processing.

Title: Return-Path overwritten by Exim?

Body:
I have a VPS with cPanel and I'm using PHPMailer to send email through the local SMTP server which is run by exim, the problem is that I actually add:

$mail->AddCustomHeader('Return-Path: sender@domain.com');

But it's being overwritten with the default one, I know that I can do it with the -f 5th parameter in mail() but I want to do it using PHPMailer dynamically..

Appreciating any help.

Thanks

Body:
The PHPMailer class has a Sender variable which sets the -f parameter (or constructs the appropriate MAIL FROM: command when using SMTP) as necessary. From the source code:

/**
 * Sets the Sender email (Return-Path) of the message.  If not empty,
 * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
 * @var string
 */
public $Sender            = '';

so you can presumably do something like:

$mail->Sender = 'sender@domain.com';

Outgoing mail servers tend to ignore Return-Path since they have the address from the SMTP MAIL FROM: line. The Return-Path header is inserted by the recipient's mail server for use in filters or other downstream processing.


问:
MVC post data from form after login redirect on submit button click
How can you have a form that doesn't require the user to be logged in until they click submit, and at that point submits the form if the user is logged in, and otherwise redirects to the login page. Then after the user logs in successfully, submits the original form? The original form has an <input type="file"> element also, and the file shouldn't be uploaded unless the user successfully logs in.</p>

答:
I know this is an old post, hopefully, my experience will help someone:

I have two submit buttons and a common method that gets called for handling form submission from both of them - conditional statements inspect which button is submitting the form.

On the button that requires the user to be authenticated, it was returning HttpUnauthorizedResult() to force the user back to the login page.
After login, the user will just be sent back to the form with field values filled in because they were being stored in a TempData entry, but the user still needed to click the button again to submit the data.

So, I added a boolean TempData variable called AutoSave that will be set right before returning the HttpUnauthorizedResult().
I check it before loading the form again and if AutoSave == true I just redirect to the method that handles the submission.
Works like a charm.

Here's the sample code:

```<code>private ActionResult ProcessOnlineApplication(OnlineApplicationViewModel application){

        //if not submit make sure it's save.
        if (application.SubmitAction == "Save")))
        {
             if(!User.Identity.IsAuthenticated)
             {
                    //Keep a copy of the application until logged in
                    TempData["PendingOnlineApplication"] = application;
                    TempData["AutoSave"] = true;
                    return new HttpUnauthorizedResult();
             }
             else{
                   //Everything goes here
             }
        }
}
public ActionResult OnlineApplicationForm(){
        var viewModel = TempData["PendingOnlineApplication"] as OnlineApplicationViewModel;
        if (TempData.ContainsKey("AutoSave") && Convert.ToBoolean(TempData["AutoSave"]) && viewModel != null)
        {
            TempData["AutoSave"] = false;
            return ProcessOnlineApplication(viewModel);
        }
        if (viewModel == null)
        {
            viewModel = CreateModel();
        }
        return GetOnlineApplicationAction(viewModel);
}
</code>```

Body:
I know this is an old post, hopefully, my experience will help someone:

I have two submit buttons and a common method that gets called for handling form submission from both of them - conditional statements inspect which button is submitting the form.

On the button that requires the user to be authenticated, it was returning HttpUnauthorizedResult() to force the user back to the login page.
After login, the user will just be sent back to the form with field values filled in because they were being stored in a TempData entry, but the user still needed to click the button again to submit the data.

So, I added a boolean TempData variable called AutoSave that will be set right before returning the HttpUnauthorizedResult().
I check it before loading the form again and if AutoSave == true I just redirect to the method that handles the submission.
Works like a charm.

Here's the sample code:

private ActionResult ProcessOnlineApplication(OnlineApplicationViewModel application){

        //if not submit make sure it's save.
        if (application.SubmitAction == "Save")))
        {
             if(!User.Identity.IsAuthenticated)
             {
                    //Keep a copy of the application until logged in
                    TempData["PendingOnlineApplication"] = application;
                    TempData["AutoSave"] = true;
                    return new HttpUnauthorizedResult();
             }
             else{
                   //Everything goes here
             }
        }
}
public ActionResult OnlineApplicationForm(){
        var viewModel = TempData["PendingOnlineApplication"] as OnlineApplicationViewModel;
        if (TempData.ContainsKey("AutoSave") && Convert.ToBoolean(TempData["AutoSave"]) && viewModel != null)
        {
            TempData["AutoSave"] = false;
            return ProcessOnlineApplication(viewModel);
        }
        if (viewModel == null)
        {
            viewModel = CreateModel();
        }
        return GetOnlineApplicationAction(viewModel);
}


问:
Getting error in button position change in swift 3
I'm using the below-mentioned code for changing the position of button in swift 3 for 6s but I got the error like this Value of type '(Any) -> ()' has no member 'frame'. I'm stuck here</p>

```<code>if screenHeight == 667{

  //  self.forgetPasswordBtn.frame = CGRect(x: 0, y: 25, width: screenWidth, height: 30)
        nextBtn.frame.origin = CGRect(x:0,y:0)

    }
</code>```

答:
CGRect used when want to change frame in view.

When want to change origin use CGPoint because origin is position in view.

Code for that is below.

```<code>if screenHeight == 667{
        nextBtn.frame.origin = CGPoint(x: 0, y: 0)
    }
</code>```

Body:
I'm using the below-mentioned code for changing the position of button in swift 3 for 6s but I got the error like this Value of type '(Any) -> ()' has no member 'frame'. I'm stuck here

if screenHeight == 667{

  //  self.forgetPasswordBtn.frame = CGRect(x: 0, y: 25, width: screenWidth, height: 30)
        nextBtn.frame.origin = CGRect(x:0,y:0)

    }

Body:
CGRect used when want to change frame in view.

When want to change origin use CGPoint because origin is position in view.

Code for that is below.

if screenHeight == 667{
        nextBtn.frame.origin = CGPoint(x: 0, y: 0)
    }


问:
Generic Observer Pattern in Swift using Protocols gives Segmentation Fault
```<code>import Foundation
class IProtocol {
     func meth1(arg: Int){}
}
class IObserver: IProtocol {
    private var className: String
    init(name: String) {
        className = name
    }
    override func meth1(arg: Int) {
        print(className, ":", arg)
    }
}
class Notifier<T> {
    private var listOfObservers = NSMutableArray()
    func addObserver(observer: T) {
        listOfObservers.add(observer)
    }
    func callObservers<ARG, RET>(function: (T)->(ARG)->RET, arg: ARG) {
        for obj in listOfObservers {
            let observer = obj as! T
            _ = function(observer)(arg)
        }
    }
}
let a = IObserver(name: "First I Observer")
let b = IObserver(name: "Second I Observer")
let n = Notifier<IProtocol>()
n.addObserver(observer: a)
n.addObserver(observer: b)
n.callObservers(function: IProtocol.meth1, arg: Int(1))
</code>```

OUTPUT

First I Observer: 1

Second I Observer: 1

The above example fails and does not build giving Command failed due to signal: Segmentation Fault: 11, when I change IProtocol to protocol from class. I have different protocols and different observer classes confirming those protocols. I am trying to implement a Notifier class that notifies the observers by taking the method from the protocol and arguments to be passed for that method.
It will be great, if someone can explain what am I doing wrong!

I am using Swift 3 and Xcode 8.2

答:
As of today, Swift does not handle direct references to protocol methods:

```<code>protocol IProtocol {
    func meth1()
}
class IObserver: IProtocol {
    func meth1() { print("success") }
}
let x = IProtocol.meth1 // This causes the compiler crash
x(IObserver())()
</code>```

And coming to the solution for my problem was to pass a closure instead of the method. This is how it looks:

```<code>import Foundation
protocol IProtocol {
    func meth1(arg: Int)
}
class IObserver: IProtocol {
    private var className: String
    init(name: String) {
        className = name
    }
    func meth1(arg: Int) {
        print(className, ":", arg)
    }
}
class Notifier<T> {
    private var listOfObservers = NSMutableArray()
    func addObserver(observer: T) {
        listOfObservers.add(observer)
    }
    func callObservers<ARG>(function: (T, ARG) -> (), arg: ARG) {
        for obj in listOfObservers {
            let observer = obj as! T
            function(observer, arg)
        }
    }
}
let a = IObserver(name: "First I Observer")
let b = IObserver(name: "Second I Observer")
let n = Notifier<IProtocol>()
n.addObserver(observer: a)
n.addObserver(observer: b)
n.callObservers(function: {obs, ar in
    obs.meth1(arg: ar)
}, arg: Int(1))
</code>```

Body:
import Foundation
class IProtocol {
     func meth1(arg: Int){}
}
class IObserver: IProtocol {
    private var className: String
    init(name: String) {
        className = name
    }
    override func meth1(arg: Int) {
        print(className, ":", arg)
    }
}
class Notifier<T> {
    private var listOfObservers = NSMutableArray()
    func addObserver(observer: T) {
        listOfObservers.add(observer)
    }
    func callObservers<ARG, RET>(function: (T)->(ARG)->RET, arg: ARG) {
        for obj in listOfObservers {
            let observer = obj as! T
            _ = function(observer)(arg)
        }
    }
}
let a = IObserver(name: "First I Observer")
let b = IObserver(name: "Second I Observer")
let n = Notifier<IProtocol>()
n.addObserver(observer: a)
n.addObserver(observer: b)
n.callObservers(function: IProtocol.meth1, arg: Int(1))

OUTPUT

First I Observer: 1

Second I Observer: 1

The above example fails and does not build giving Command failed due to signal: Segmentation Fault: 11, when I change IProtocol to protocol from class. I have different protocols and different observer classes confirming those protocols. I am trying to implement a Notifier class that notifies the observers by taking the method from the protocol and arguments to be passed for that method.
It will be great, if someone can explain what am I doing wrong!

I am using Swift 3 and Xcode 8.2

Body:
As of today, Swift does not handle direct references to protocol methods:

protocol IProtocol {
    func meth1()
}
class IObserver: IProtocol {
    func meth1() { print("success") }
}
let x = IProtocol.meth1 // This causes the compiler crash
x(IObserver())()

And coming to the solution for my problem was to pass a closure instead of the method. This is how it looks:

import Foundation
protocol IProtocol {
    func meth1(arg: Int)
}
class IObserver: IProtocol {
    private var className: String
    init(name: String) {
        className = name
    }
    func meth1(arg: Int) {
        print(className, ":", arg)
    }
}
class Notifier<T> {
    private var listOfObservers = NSMutableArray()
    func addObserver(observer: T) {
        listOfObservers.add(observer)
    }
    func callObservers<ARG>(function: (T, ARG) -> (), arg: ARG) {
        for obj in listOfObservers {
            let observer = obj as! T
            function(observer, arg)
        }
    }
}
let a = IObserver(name: "First I Observer")
let b = IObserver(name: "Second I Observer")
let n = Notifier<IProtocol>()
n.addObserver(observer: a)
n.addObserver(observer: b)
n.callObservers(function: {obs, ar in
    obs.meth1(arg: ar)
}, arg: Int(1))


问:
Should I use a Guid and Guid.Empty or a nullable Guid?
I have certain scenarios (e.g. a custom class to hold Sql parameters) in which a variable may or may not be required. Traditionally I have always defined these being of type Guid? and used myGuid.HasValue to check for a valid value before using.

Of course in practice I could also use regular Guids and perform the check for valid value with myGuid == Guid.Empty.

For readability I prefer the first usage as it feels cleaner but I would appreciate it if someone could advise on whether one of these methods is better (faster, quicker or more correct) than the other?

答:
I usually use declaring like the followings:

```<code>Guid? objGuidStudent = null;
objGuidStudent = Students.FindByName('Oscar');
Classrooms.Add(x, y, z, objGuidStudent);
</code>```

It works perfectly, either with or without NULL value.

Body:
I usually use declaring like the followings:

Guid? objGuidStudent = null;
objGuidStudent = Students.FindByName('Oscar');
Classrooms.Add(x, y, z, objGuidStudent);

It works perfectly, either with or without NULL value.


问:
default input border shows differently on div
If I create an input box without any styles (<input>) and then inspect the computed css in devtools I see it has border 2px inset rgb(238, 238, 238)

However if I create a div with the same border it looks very different:

<input>

```

Why is that ? and what kind of border will give me the same one as the input ?

答:
This is more likely identical to your <input> style

```<code>border: 1px solid rgba(0,0,0,0.4);
height: 19px;
width: 171px;
</code>```

inset - Defines a 3D inset border.

solid - Defines a solid border.

This is the main different in your style.

Body:
If I create an input box without any styles (<input>) and then inspect the computed css in devtools I see it has border 2px inset rgb(238, 238, 238)

However if I create a div with the same border it looks very different:

<input>

Why is that ? and what kind of border will give me the same one as the input ?

Body:
This is more likely identical to your <input> style

border: 1px solid rgba(0,0,0,0.4);
height: 19px;
width: 171px;

inset - Defines a 3D inset border.

solid - Defines a solid border.

This is the main different in your style.


问:
PHP: Find last occurence of string in array
I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.

```<code>$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );

$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.
</code>```

I want $key = 3 which is the last matched element.

Any suggestion appreciated.

答:
PHP code demo</p>

```<code><?php
ini_set("display_errors", 1);
$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );
$toSearch="bike";
$index=null;
while($key=array_search($toSearch, $Data))
{
    $index=$key;
    unset($Data[$key]);
}
echo $index;
</code>```

Body:
I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.

$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );

$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.

I want $key = 3 which is the last matched element.

Any suggestion appreciated.

Body:
PHP code demo

<?php
ini_set("display_errors", 1);
$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );
$toSearch="bike";
$index=null;
while($key=array_search($toSearch, $Data))
{
    $index=$key;
    unset($Data[$key]);
}
echo $index;


问:
How to remove items from a slice while ranging over it?
What is the best way to remove items from a slice while ranging over it?

For example:

```<code>type MultiDataPoint []*DataPoint

func (m MultiDataPoint) Json() ([]byte, error) {
    for i, d := range m {
        err := d.clean()
        if ( err != nil ) {
            //Remove the DP from m
        }
    }
    return json.Marshal(m)
}
</code>```

答:
One other option is to use a normal for loop using the length of the slice and subtract 1 from the index each time a value is removed. See the following example:

```<code>m := []int{3, 7, 2, 9, 4, 5}

for i := 0; i < len(m); i++ {
    if m[i] < 5 {
        m = append(m[:i], m[i+1:]...)
        i-- // -1 as the slice just got shorter
    }
}
</code>```

I don't know if len() uses enough resources to make any difference but you could also run it just once and subtract from the length value too:

```<code>m := []int{3, 7, 2, 9, 4, 5}

for i, s := 0, len(m); i < s; i++ {
    if m[i] < 5 {
        m = append(m[:i], m[i+1:]...)
        s--
        i--
    }
}
</code>```

Body:
What is the best way to remove items from a slice while ranging over it?

For example:

type MultiDataPoint []*DataPoint

func (m MultiDataPoint) Json() ([]byte, error) {
    for i, d := range m {
        err := d.clean()
        if ( err != nil ) {
            //Remove the DP from m
        }
    }
    return json.Marshal(m)
}

Body:
One other option is to use a normal for loop using the length of the slice and subtract 1 from the index each time a value is removed. See the following example:

m := []int{3, 7, 2, 9, 4, 5}

for i := 0; i < len(m); i++ {
    if m[i] < 5 {
        m = append(m[:i], m[i+1:]...)
        i-- // -1 as the slice just got shorter
    }
}

I don't know if len() uses enough resources to make any difference but you could also run it just once and subtract from the length value too:

m := []int{3, 7, 2, 9, 4, 5}

for i, s := 0, len(m); i < s; i++ {
    if m[i] < 5 {
        m = append(m[:i], m[i+1:]...)
        s--
        i--
    }
}


问:
mongoDB eval command is deprecated error Version 3.4
I'm getting an error the eval command is deprecated while using mongo command in shell. How to get rid of it? It wasn't there few days back

答:
MongoDB db.eval() command has been in deprecation mode since MongoDB v3.0.

Unless you really need to use eval(), please try other alternatives to it. Post a new question with your use case of the eval and others may be able to point you an alternative for it.


答:
you can use krsort to sort the array by key.

```<code> krsort($Data);
 $key = array_search('bike', $Data);
 echo $key;
</code>```

Working example: https://3v4l.org/fYOgN

Title: PHP: Find last occurence of string in array

Body:
you can use krsort to sort the array by key.

 krsort($Data);
 $key = array_search('bike', $Data);
 echo $key;

Working example: https://3v4l.org/fYOgN


问:
Unity Multiple displays not working
I am using Unity 5.4.1f1 personal edition and working on Windows standalone build. I want to use multiple displays in my game. I have 2 cameras and set the target display of one camera to display 1 and target display of second camera to display 2.

Also, I have activated the display but Display.displays.Length is always one on editor as well as on build.

So it does not display anything on the second screen. What should I do to display on second screen?

答:
What you see is actually bug. Don't waste your time trying to fix it. Go to Help --> Report a Bug... then report the problem. There are many bug reports open for this problem but it's a good idea to file for another one to remind them that this is still not fixed.

Here are bug reports on this. Unity claims to have fixed this on some of them but that's not true because I was able to reproduce this problem with my computer with Unity 5.6. Bug Report 1, Bug Report 2 and Bug Report 3.

Title: Unity Multiple displays not working