答:
As pointed out in comments by BLUEPIXY, *b[j] should be changed to (*b)[j], as you have passed b to fibo  as double pointer, b stores address of pointer variable from main function which in turn stores address where array is present.

*b[j] will get evaluated to *(*(b+j)) address stored in b is valid(address of pointer variable b from main), b+j takes you to invalid address, accessing it might be leading to segment fault

You need j'th element from array whose address is stored in b, right way to access will be  (*b)[j] where (*b) gets you the base address of your array

Title: undefined behaviour on dynamic allocated arrays (segmentation fault)

Body:
This program calculates Fibonacci series of the form: t1, t2, t3 = t1 + t^2, t4 = t2+t3^2 ...

It takes three inputs t1, t2 and nth number in the series you want to calculate.

Since the numbers increase exponentially, i used arrays to display and perform manipulations on large numbers.

PROBLEM:

I'm stuck with some weird error on:

bsquare[j] = *b[j]

use inputs 0 1 8 to recreate the error, it works fine for inputs upto 7. also i tried debugging using gdb, but the debugger shows that memory is accessible when i use p **b@50 and bn also seems to be valid. Is there some undefined behaviour i'm missing out on?

Code

#include<stdio.h>
#include<stdlib.h>

int carry = 0;
int fibo( int **a, int **b, int **c, int n);
void sum(int *a, int *b, int *c, int *an, int *bn, int *cn);
void sqr(int *b, int *bn);
int main()
{

    int *a, *b, *c;
    int t1, t2, n, i, bn;

    scanf("%d%d%d",&t1, &t2,&n);

    a = (int * ) calloc(100, sizeof(int));
    b = (int * ) calloc(100, sizeof(int));
    c = (int * ) calloc(100, sizeof(int));
    a[0] = t1; b[0] = t2;

    bn = fibo(&a,&b,&c,n);

    printf("\nNumber is: ");
    for(i = bn-1; i>=0; i--)
    printf("%d",b[i]);

    free(a);free(b);free(c);
    return 0;
}
void sqr(int *b, int *bn)
{   int c[50] = {0};
    int i , j ,k = 0;
    int temp = 0;
    for(i = 0; i < *bn; i++)
    {    k = i;
        carry = 0;
        for(j = 0; j < *bn ;j++)
        {
            temp = c[k] + b[i] * b[j] + carry;
            if(temp>9)
            {
                carry = temp / 10;
                c[k] = temp % 10;

            }
            else
            {
                c[k] =  temp;
                carry = 0;
            }
            k++;
        }
        if(carry !=0)
        {c[k++] = carry;
        }

    }

    for(i = 0; i<k; i++)
    {
        b[i] = c[i];

    }

    *bn = k;

}

void sum(int *a, int *b, int *c, int *an, int *bn, int *cn)
{

    int i=0 , j ,k = 0;
    int *temp1;
    int temp = 0;
    for(j=0; j<*cn; j++)
     c[j] = 0;
            *cn = 0;
     carry = 0;
    for(; i < *bn && i < *an; i++)
    {
        temp = a[i] + b[i] + carry;

        if(temp>9)
        {
            c[k] = temp % 10;
            carry = temp/10;

        }
        else
        {
            c[k] = temp;
            carry = 0;
        }
        k++;
    }

    while(i<*an)
    {
        temp = carry + a[i];
        if(temp>9)
        {
            c[k] = temp % 10;
            carry = temp/10;

        }
        else
        {
            c[k] = temp;
            carry = 0;
        }
        k++;i++;
    }

    while(i<*bn)
    {
        temp = carry + b[i];
        if(temp>9)
        {
            c[k] = temp % 10;
            carry = temp/10;

        }
        else
        {
            c[k] = temp;
            carry = 0;
        }
        k++;i++;
    }
    if(carry!=0)
    {
        c[k++] = carry;
    }

    *cn = k;

}

int fibo( int **a, int **b, int **c, int n)
{
    int i, j,*tmpdb;

    int bn = 1, an = 1, cn = 0, bsn = 0, temp;
    int bsquare[100] = {0};

    for(i = 3; i<= n; i++)
        {
            for(j = 0; j<bn; j++)
                bsquare[j] = *b[j];

            bsn = bn;

            sqr(bsquare,&bsn);
            sum(*a,bsquare,*c,&an,&bsn,&cn);

            tmpdb = *a;
            *a = *b;
            *b = *c;
            *c = tmpdb;

            temp = an;
            an = bn;
            bn = cn;
            cn = temp;

        }
    return bn;

}


来源: stackexchange

问:
No more quick help in Xcode editor
Quick help has gone away in my Xcode 5 (5.0.2 on OS X 10.8.5):

Instead of the little popup window that's supposed to pop up for the Opt - Click shortcut all that ever shows is the arrow image:

Been like this since the Xcode 5 upgrade.
Any ideas how to fix it..?

FWIW: The doc sets are in fact properly installed - 'Opt' + Double-Click brings up the correct documentation as usual. Even removing the doc sets manually and re-downloadig didn't help.

The hovering Quick Help window is still gone..

答:
I just had this issue yesterday. It happened after I disconnected my iPhone from my computer, the target device switched to "Generic iOS Devices". All of a sudden, quick help stopped working, the symbols lost their icons in the auto-completion pop-up.

I just tried select any of the simulator device to get it working again. Or you can just reconnect your iOS device.

ContentLicense: CC BY-SA 3.0

Title: No more quick help in Xcode editor


问:
Trying to pass SqlCommand in SqlDataAdapter as parameters
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();

I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.

Running code (aspx page code)

```<code>if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
        // username & password logic
        DataTable dt = new DataTable();
        string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD";

        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
        cmd.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();

        DBConnection conn_ = new DBConnection();

        dt = conn_.SelectData(cmd);

        if (conn_.SQL_dt.Rows.Count > 0)
        {
            Response.Redirect("Home.aspx", false);
        }
    }
</code>```

Successful connection class code

```<code>public DataTable SelectData(SqlCommand command)
{
    try
    {
       conn.Open();

       SqlDataAdapter DA = new SqlDataAdapter();

       command.CommandType = CommandType.Text;
       command.Connection = conn;

       DA.SelectCommand = command;
       DA.Fill(SQL_dt);

       return SQL_dt;
   }
   catch (Exception ex)
   {
       return null;
   }
   finally
   {
       conn.Close();
   }
}
</code>```

How can I pass CommandType.Text as parameters for SqlDataAdapter?

Error code

```<code>public DataTable SelectData(SqlCommand command)
{
    try
    {
        conn.Open();

        SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);

        // command.CommandType = CommandType.Text;
        // command.Connection = conn;
        DA.SelectCommand = command;
        DA.Fill(SQL_dt);

        return SQL_dt;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }
}
</code>```

I am getting this error:

System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

  at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...

答:
```<code>public DataTable SelectData(string query)
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection("Your Connection String here"))
            {
                con.Open();
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = query;
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
                    {
                        adp.Fill(dt);
                        return dt;
                    }
                }
            }
        }
</code>```

To use:

```<code>SelectData("select * from yourTable");
</code>```

Body:
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();

I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.

Running code (aspx page code)

if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
        // username & password logic
        DataTable dt = new DataTable();
        string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD";

        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
        cmd.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();

        DBConnection conn_ = new DBConnection();

        dt = conn_.SelectData(cmd);

        if (conn_.SQL_dt.Rows.Count > 0)
        {
            Response.Redirect("Home.aspx", false);
        }
    }

Successful connection class code

public DataTable SelectData(SqlCommand command)
{
    try
    {
       conn.Open();

       SqlDataAdapter DA = new SqlDataAdapter();

       command.CommandType = CommandType.Text;
       command.Connection = conn;

       DA.SelectCommand = command;
       DA.Fill(SQL_dt);

       return SQL_dt;
   }
   catch (Exception ex)
   {
       return null;
   }
   finally
   {
       conn.Close();
   }
}

How can I pass CommandType.Text as parameters for SqlDataAdapter?

Error code

public DataTable SelectData(SqlCommand command)
{
    try
    {
        conn.Open();

        SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);

        // command.CommandType = CommandType.Text;
        // command.Connection = conn;
        DA.SelectCommand = command;
        DA.Fill(SQL_dt);

        return SQL_dt;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }
}

I am getting this error:

System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

  at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...

Body:
public DataTable SelectData(string query)
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection("Your Connection String here"))
            {
                con.Open();
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = query;
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
                    {
                        adp.Fill(dt);
                        return dt;
                    }
                }
            }
        }

To use:

SelectData("select * from yourTable");


问:
Selection formula for capturing previous month data only in lotus notes
what selection formula we have to used for capturing previous month data only in a view in lotus notes 7.0 version</p>

答:
You'll need to compare the date field in your documents to @Today minus one month, and select all documents with a date greater than or equal to that calculated date.

Use the @Adjust formula to calculate the current date minus one month:

```<code>SELECT @Adjust(@Today, 0;-1;0;0;0;0) >= YOURDATEFIELD
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You'll need to compare the date field in your documents to @Today minus one month, and select all documents with a date greater than or equal to that calculated date.

Use the @Adjust formula to calculate the current date minus one month:

SELECT @Adjust(@Today, 0;-1;0;0;0;0) >= YOURDATEFIELD


问:
convert the columns into Horizontal PIVOT
I have 3 column file with ID,name and value .

```<code>1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running
</code>```

I'm trying to convert this into a horizontal format based on the column 1 and column 2.

It's similar to the Pivot table with text values printed, it can't be done using Excel pivot it will allow only sum/count of values.

Can this be generated in UNIX?

```<code>,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue/white,,,,,shoe,blue,
5,Sports/Running,,,,,,,,M
</code>```

答:
Input

```<code>akshay@db-3325:/tmp$ cat data.txt
1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,primarycolor,blue
5,size,M
5,Brand,Running
</code>```

Script

```<code>akshay@db-3325:/tmp$ cat pivot.awk
{
     id=$1; name=$2; value=$3
     ids[id];
     # this is to retain order
     if(!(name in tmp)){ tmp[name]; names[++c]=name; }
     values[id,name] = value
}
END {
     # comment below line if you hide "id"
     printf "id"

     for (name in names) {
         printf "%s%s",OFS,names[name]
     }
     print ""
     for (id in ids) {
         printf "%s",id
         for (name in names) {
             printf "%s%s",OFS,values[id,names[name]]
         } print ""
     }
}
</code>```

Execution and Output

```<code>akshay@db-3325:/tmp$ awk -v FS=, -v OFS=, -f pivot.awk data.txt
id,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
3,,blue,,,,,shoe,blue,
4,Running,,,,12,Lose,,,
5,Running,,,,,,,,M
</code>```

This produces o/p same as expected o/p including order

```<code>akshay@db-3325:/tmp$ cat pivot_with_order.awk
{
     id=$1; name=$2; value=$3

     # this is to retain order
     if(!(id in itmp)){ itmp[id]; ids[++i]=id; }
     if(!(name in tmp)){ tmp[name]; names[++c]=name; }

     values[id,name] = value
}
END {
     # uncomment below line if you want to display "id"
     # printf "id"

     for (name in names) {
         printf "%s%s",OFS,names[name]
     }
     print ""
     for (id in ids) {
         printf "%s",ids[id]
         for (name in names) {
             printf "%s%s",OFS,values[ids[id],names[name]]
         } print ""
     }
}
</code>```

Output

```<code>akshay@db-3325:/tmp$ awk -v FS=, -v OFS=, -f pivot_with_order.awk data.txt
,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue,,,,,shoe,blue,
5,Running,,,,,,,,M
</code>```

Body:
I have 3 column file with ID,name and value .

1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running

I'm trying to convert this into a horizontal format based on the column 1 and column 2.

It's similar to the Pivot table with text values printed, it can't be done using Excel pivot it will allow only sum/count of values.

Can this be generated in UNIX?

,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue/white,,,,,shoe,blue,
5,Sports/Running,,,,,,,,M

Body:
Input

akshay@db-3325:/tmp$ cat data.txt
1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,primarycolor,blue
5,size,M
5,Brand,Running

Script

akshay@db-3325:/tmp$ cat pivot.awk
{
     id=$1; name=$2; value=$3
     ids[id];
     # this is to retain order
     if(!(name in tmp)){ tmp[name]; names[++c]=name; }
     values[id,name] = value
}
END {
     # comment below line if you hide "id"
     printf "id"

     for (name in names) {
         printf "%s%s",OFS,names[name]
     }
     print ""
     for (id in ids) {
         printf "%s",id
         for (name in names) {
             printf "%s%s",OFS,values[id,names[name]]
         } print ""
     }
}

Execution and Output

akshay@db-3325:/tmp$ awk -v FS=, -v OFS=, -f pivot.awk data.txt
id,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
3,,blue,,,,,shoe,blue,
4,Running,,,,12,Lose,,,
5,Running,,,,,,,,M

This produces o/p same as expected o/p including order

akshay@db-3325:/tmp$ cat pivot_with_order.awk
{
     id=$1; name=$2; value=$3

     # this is to retain order
     if(!(id in itmp)){ itmp[id]; ids[++i]=id; }
     if(!(name in tmp)){ tmp[name]; names[++c]=name; }

     values[id,name] = value
}
END {
     # uncomment below line if you want to display "id"
     # printf "id"

     for (name in names) {
         printf "%s%s",OFS,names[name]
     }
     print ""
     for (id in ids) {
         printf "%s",ids[id]
         for (name in names) {
             printf "%s%s",OFS,values[ids[id],names[name]]
         } print ""
     }
}

Output

akshay@db-3325:/tmp$ awk -v FS=, -v OFS=, -f pivot_with_order.awk data.txt
,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue,,,,,shoe,blue,
5,Running,,,,,,,,M


问:
VBA Error occurs when set a range - 1004 Application Defined Error
Hi I'm working on my VBA code to set a range based on the last row in my source data and then create a pivot table on that range. However the last line here goes wrong when I run the code with error 1004 (application defined error). I feel all the variables have been defined and should be alright. The messagebox also gives me the right last row number in source data. Could you please help me to fix? thanks.

```<code>    Dim PvtTbl As pivotTable
    Dim wsData As Worksheet
    Dim rngData As Range
    Dim PvtTblCache As PivotCache
    Dim wsPvtTbl As Worksheet
    Dim pvtFld As PivotField

    Set wsData = Worksheets("Task List Data Export")
    Set wsPvtTbl = Worksheets("Summary")

    wsPvtTbl.Cells.Clear
    wsPvtTbl.Cells.ColumnWidth = 10

    For Each PvtTbl In wsPvtTbl.PivotTables
    If MsgBox("Delete existing PivotTable!", vbYesNo) = vbYes Then
    PvtTbl.TableRange2.Clear
    End If
    Next PvtTbl

    Dim last As Long

    With Worksheets("Task List Data Export")
        last = .Cells(.Rows.Count, "A").End(xlUp).Row

    End With
    MsgBox last
    Set rngData = Worksheets("Task List Data Export").Range(Cells(1, 1), Cells(last, 15))
</code>```

************************Update************************
Hi I applied Dy.Lee's code and this error finally disappeared. However my next line goes wrong again (Error type mismatch)

```<code>ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData, Version:=xlPivotTableVersion12).CreatePivotTable TableDestination:=wsPvtTbl.Range("B25"), TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
</code>```

Any Ideas? Thanks again

答:
the code would be like this</p>

```<code>With Worksheets("Task List Data Export")
    Set rngData = .Range(.Cells(1, 1), .Cells(last, 15))
End With
</code>```

Body:
Hi I'm working on my VBA code to set a range based on the last row in my source data and then create a pivot table on that range. However the last line here goes wrong when I run the code with error 1004 (application defined error). I feel all the variables have been defined and should be alright. The messagebox also gives me the right last row number in source data. Could you please help me to fix? thanks.

    Dim PvtTbl As pivotTable
    Dim wsData As Worksheet
    Dim rngData As Range
    Dim PvtTblCache As PivotCache
    Dim wsPvtTbl As Worksheet
    Dim pvtFld As PivotField

    Set wsData = Worksheets("Task List Data Export")
    Set wsPvtTbl = Worksheets("Summary")

    wsPvtTbl.Cells.Clear
    wsPvtTbl.Cells.ColumnWidth = 10

    For Each PvtTbl In wsPvtTbl.PivotTables
    If MsgBox("Delete existing PivotTable!", vbYesNo) = vbYes Then
    PvtTbl.TableRange2.Clear
    End If
    Next PvtTbl

    Dim last As Long

    With Worksheets("Task List Data Export")
        last = .Cells(.Rows.Count, "A").End(xlUp).Row

    End With
    MsgBox last
    Set rngData = Worksheets("Task List Data Export").Range(Cells(1, 1), Cells(last, 15))

************************Update************************
Hi I applied Dy.Lee's code and this error finally disappeared. However my next line goes wrong again (Error type mismatch)

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData, Version:=xlPivotTableVersion12).CreatePivotTable TableDestination:=wsPvtTbl.Range("B25"), TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12

Any Ideas? Thanks again

Body:
the code would be like this

With Worksheets("Task List Data Export")
    Set rngData = .Range(.Cells(1, 1), .Cells(last, 15))
End With


问:
Proper method to remove www from address using IIS URL Rewrite
What is the optimal way to remove the www subdomain from a url using IIS URL Rewrite?</p>

答:
IIS does it automatically for you:

Select site > URL rewrite > new rule > Canonical Host Name :)


问:
Change mapped source path for assembly in VS Debugger
When trying to debug into asp.net identity source, I cloned the source from codeplex and when stepping into the code mapped the Microsoft.AspNet.Identity.EntityFramework to my /code/aspnetidentity directory.

I think I made a mistake however in cloning that repo - it seems incomplete. I found a different one on github and have it at /code/Identity. However, I have no idea where the mapping from assembly to source code directory is stored so that I can change it.

Where is it?

答:
Not very sure that why it was empty, but the symbol file contains the original location of the source files, so one idea is that you could use certain tool like Windbg or others to really find and read the source file:

How do I change the locations of source files in a symbols file (pdb)

Get the original source code location for an assembly


问:
How would I go about making this error message appear when form field is not right?
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

```<code>if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}
</code>```

In the form, I have a span class like so:

```<code><span class="error">'.$error.'</span>
</code>```

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!

答:
In order to process the form while staying on the page, you will need to incorporate some AJAX. The easiest way to do this is to use a framework of some sort (recommend jQuery). This should give you some insight into how to develop such functionality. If you get stuck, we're here to help.
http://api.jquery.com/jQuery.post/</p>

Body:
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}

In the form, I have a span class like so:

'.$error.'

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!


问:
xamarin UWP masterdetailpage width How to set
I have a program with xamairn forms, One client project is UWP. The Master of

MasterDetailPage control has normal appearance  within Android and IOS platform , But it looks unfriendly within UWP platform. I know I can use Grid to replace. But, I am not sure there are some issues in the Masterdetailpageor I miss some key procedure to use it.

at UWP like this：

答:
But it looks unfriendly within UWP platform. I know I can use Grid to replace. But, I am not sure there are some issues in the Masterdetailpageor I miss some key procedure to use it.

If you have not set MasterBehavior for MasterDetailPage. The Master will split open by default as you mentioned. Please set MasterBehavior according to  the following code. And you will get normal appearance.

```<code><MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:local="clr-namespace:MasterDetailPageNavigation;assembly=MasterDetailPageNavigation"
                  x:Class="MasterDetailPageNavigation.MainPage" MasterBehavior="SplitOnPortrait">
</MasterDetailPage>
</code>```

Body:
But it looks unfriendly within UWP platform. I know I can use Grid to replace. But, I am not sure there are some issues in the Masterdetailpageor I miss some key procedure to use it.

If you have not set MasterBehavior for MasterDetailPage. The Master will split open by default as you mentioned. Please set MasterBehavior according to  the following code. And you will get normal appearance.

<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:local="clr-namespace:MasterDetailPageNavigation;assembly=MasterDetailPageNavigation"
                  x:Class="MasterDetailPageNavigation.MainPage" MasterBehavior="SplitOnPortrait">
</MasterDetailPage>


问:
How to check more than one year in 'leap year'
Just recently started learning C# and did in class the 'leap year'. We came up with this solution. But it only allows to check one year at a time. Is there a nice way to check more at once? Let's say I need to check 10 different years if they are leap or not. All I could think of is copying the block and giving new variable. </p>

```<code>int a = int.Parse(Console.ReadLine());

bool div1 = a % 4 == 0;
bool div2 = a % 100 != 0;
bool div3 = a % 400 == 0;

if ((div1 && div2) || div3)
{
    Console.WriteLine($"{a} is a leap year");
}
else
{
    Console.WriteLine($"{a} is not a leap year");
}
</code>```

答:
First of all, if you are using int.Parse(), you should use it in try-catch block. Otherwise your program will crash everytime when user enters nonsense.

Second, if you want to implement your own method for studying purposes - it`s okay, but you can use DateTime structure, which has IsLeapYear():

```<code>    // Summary:
    //     Returns an indication whether the specified year is a leap year.
    //
    // Parameters:
    //   year:
    //     A 4-digit year.
    //
    // Returns:
    //     true if year is a leap year; otherwise, false.
    //
    // Exceptions:
    //   T:System.ArgumentOutOfRangeException:
    //     year is less than 1 or greater than 9999.
</code>```

So, the implementation is:

```<code>class LeapYear
{
    static void Main(string[] args)
    {
        for (int input = 0; input < 10;) // Ask user until he enters year 10 times correctly
        {

            Console.Write("Please enter a year: ");

            try
            {
                int year = int.Parse(Console.ReadLine());

                if (DateTime.IsLeapYear(year))
                {
                    Console.WriteLine($"{year} is leap");
                    input++;
                }
                else
                    Console.WriteLine($"{year} is not leap");
            }

            catch (ArgumentOutOfRangeException)
            {
                Console.WriteLine("Argument Out Of Range");
            }

            catch (FormatException)
            {
                Console.WriteLine("Bad Format");
            }

            catch (OverflowException)
            {
                Console.WriteLine("Overflow");
            }

        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();

    }
}
</code>```

Body:
Just recently started learning C# and did in class the 'leap year'. We came up with this solution. But it only allows to check one year at a time. Is there a nice way to check more at once? Let's say I need to check 10 different years if they are leap or not. All I could think of is copying the block and giving new variable.

int a = int.Parse(Console.ReadLine());

bool div1 = a % 4 == 0;
bool div2 = a % 100 != 0;
bool div3 = a % 400 == 0;

if ((div1 && div2) || div3)
{
    Console.WriteLine($"{a} is a leap year");
}
else
{
    Console.WriteLine($"{a} is not a leap year");
}

Body:
First of all, if you are using int.Parse(), you should use it in try-catch block. Otherwise your program will crash everytime when user enters nonsense.

Second, if you want to implement your own method for studying purposes - it`s okay, but you can use DateTime structure, which has IsLeapYear():

    // Summary:
    //     Returns an indication whether the specified year is a leap year.
    //
    // Parameters:
    //   year:
    //     A 4-digit year.
    //
    // Returns:
    //     true if year is a leap year; otherwise, false.
    //
    // Exceptions:
    //   T:System.ArgumentOutOfRangeException:
    //     year is less than 1 or greater than 9999.

So, the implementation is:

class LeapYear
{
    static void Main(string[] args)
    {
        for (int input = 0; input < 10;) // Ask user until he enters year 10 times correctly
        {

            Console.Write("Please enter a year: ");

            try
            {
                int year = int.Parse(Console.ReadLine());

                if (DateTime.IsLeapYear(year))
                {
                    Console.WriteLine($"{year} is leap");
                    input++;
                }
                else
                    Console.WriteLine($"{year} is not leap");
            }

            catch (ArgumentOutOfRangeException)
            {
                Console.WriteLine("Argument Out Of Range");
            }

            catch (FormatException)
            {
                Console.WriteLine("Bad Format");
            }

            catch (OverflowException)
            {
                Console.WriteLine("Overflow");
            }

        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();

    }
}


问:
How to color specific area on mayavi 2d array plotting
I'm using mayavi python library for plotting my 2d elevation array (Extracted from Raster DEM) and its generating 3d visualization using my elevation data perfectly. but i want to show some specific areas on different color.

I'm calculating risky slope areas and i want to show those areas on map using different color.

```<code>dataset = gdal.Open("elevation.tif", GA_ReadOnly)
band = dataset.GetRasterBand(1)
demArray =  band.ReadAsArray()

mlab.figure(size=(640, 800) , bgcolor=(1, 1, 1))
surf = mlab.surf(demArray, warp_scale=0.1 )
mlab.show()
</code>```

generated dem using mayavi

Could anyone can tell my how to mark specific area using different color in mayavi or any other alternative solution to my problem.

答:
Here I have a link for you. I think you will learn more from it.
 (http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#mayavi.mlab.contour3d)
Good luck!</p>

Body:
I'm using mayavi python library for plotting my 2d elevation array (Extracted from Raster DEM) and its generating 3d visualization using my elevation data perfectly. but i want to show some specific areas on different color.

I'm calculating risky slope areas and i want to show those areas on map using different color.

dataset = gdal.Open("elevation.tif", GA_ReadOnly)
band = dataset.GetRasterBand(1)
demArray =  band.ReadAsArray()

mlab.figure(size=(640, 800) , bgcolor=(1, 1, 1))
surf = mlab.surf(demArray, warp_scale=0.1 )
mlab.show()

generated dem using mayavi

Could anyone can tell my how to mark specific area using different color in mayavi or any other alternative solution to my problem.


问:
Problem when trying to set status using gigya php sdk
I am using gigya javascript sdk for authentication purposes on my site. It works well. But I recently decided to try the php sdk, I was able to set status to twitter and linkedin using the php sdk but this I am able to retrieve the uid using the javascript api and when i use to setstatus using php sdk i get an error unauthorised user.

I appreciate any help.

Thanks.

答:
Have you enabled wall updates in the Gigya site setup page? This is required for using setStatus. Just to be sure, take a quick look at the notes under "Supporting Providers":

http://wiki.gigya.com/030_API_reference/020_REST_API/socialize.setStatus


问:
Get JavaScript reference to element created in ng-repeat
I'm trying to obtain a
 created inside ng-repeat so that I can add content inside generated by a third-party library.

Attempt 1:

```<code><div ng-init="init()">
  <div ng-repeat="item in items">
    <div id="{{ item.id }}"></div>
  </div>
</div>

$scope.init = function() {
  for (var i in items) {
    var element = document.getElementById(items[i].id);
    generateInnerHtml(element);
  }
};
</code>```

Attempt 2:

```<code><div ng-init="init()">
  <div ng-repeat="item in items">
    <div id="{{ item.id }}" ng-init="addContent(item.id)"></div>
  </div>
</div>

$scope.addContent = function(id) {
  var element = document.getElementById(id);
  generateInnerHtml(element);
};
</code>```

Attempt 3:

```<code><div ng-init="init()">
  <div ng-repeat="item in items">
    <div id="{{ item.id }}" ng-init="addContent(this)"></div>
  </div>
</div>

$scope.addContent = function(element) {
  generateInnerHtml(element);
};
</code>```

For all three attempts, element is always null or undefined. What's wrong?

答:
As already pointed out, your functions are running before the rendering has completed. But leave DOM manipulation to be in a directive as @anied has mentioned. This way, you decouple it from the controller and you can easily re-use it.

See plunker

Markup:

```<code><div ng-repeat="item in items" data-generated="item"></div>
</code>```

Directive:

```<code>app.directive('generated', ['$compile', function($compile) {
  var generateInnerHtml = function(e) {
    e.innerHTML = '```item = {{vm.item}}```'
  };
  return {
    restrict: 'AE',
    scope: {
      item: '=generated'
    },
    controllerAs: 'vm',
    bindToController: true,
    controller: [function() {
    }],
    compile: function(element, attr) {
      generateInnerHtml(element[0]);
      return function(scope, element, attr) {
        // Only do this if you need access to scope variables
        $compile(element.contents())(scope);
      }
    }
  };
}]);
</code>```

Body:
I'm trying to obtain a
 created inside ng-repeat so that I can add content inside generated by a third-party library.

Attempt 1:

$scope.init = function() {
  for (var i in items) {
    var element = document.getElementById(items[i].id);
    generateInnerHtml(element);
  }
};

Attempt 2:

$scope.addContent = function(id) {
  var element = document.getElementById(id);
  generateInnerHtml(element);
};

Attempt 3:

$scope.addContent = function(element) {
  generateInnerHtml(element);
};

For all three attempts, element is always null or undefined. What's wrong?

Body:
As already pointed out, your functions are running before the rendering has completed. But leave DOM manipulation to be in a directive as @anied has mentioned. This way, you decouple it from the controller and you can easily re-use it.

See plunker

Markup:

<div ng-repeat="item in items" data-generated="item"></div>

Directive:

app.directive('generated', ['$compile', function($compile) {
  var generateInnerHtml = function(e) {
    e.innerHTML = '<pre>item = {{vm.item}}</pre>'
  };
  return {
    restrict: 'AE',
    scope: {
      item: '=generated'
    },
    controllerAs: 'vm',
    bindToController: true,
    controller: [function() {
    }],
    compile: function(element, attr) {
      generateInnerHtml(element[0]);
      return function(scope, element, attr) {
        // Only do this if you need access to scope variables
        $compile(element.contents())(scope);
      }
    }
  };
}]);


问:
How to enable live reload in react native on android?
How can I enable live reload in the android emulator?

The documentation for android wasn't very helpful for a android noob.

答:
I am using Redmi note 3 for debugging purpose and was facing similar issue. The solution was that MIUI by default disables popup permission for apps, which is needed in this case to get the reload screen. After enabling the popup permission for my app it works perfect.
Hope it helps someone.</p>


问:
Approach to load testing a Geolocation iOS app
I created an iOS app in Swift, and utilized Firebase Auth and DB for the backend. I can't get super detailed on the specifics, but it involves Geolocation services, and is similar (although much simpler) to Uber/Lyft. Both drivers/riders share the same app. You have to click on a another button to get to the driver interface.

I need to create a simulation where multiple virtual users (both drivers/riders) are using the application at the same time (I would like to measure success/failure of each action, as well as response time). I don't need to randomize the simulation, but I do have to account for the fact that there is an interaction between two users. In other words, it's not the usual performance test where you log-in, view profile, update profile, log-out, etc. There is a dependence on one part of the test to complete before the other can start.

I'd like to see if I could get any ideas on the best approach to handle this. I can provide more details/context, if needed.

答:
There is something called bluepill https://github.com/linkedin/bluepill, but it is only used to launch simultaneous XCTest cases and Simulators, it doesn't guarantee the order of the tests, so it won't work for you

You can create UI tests and run them on two different macs, but you need to figure out how test are going to interact and it seems difficult.

I would suggest to use   -only-testing feature of the xcodebuild

You can create a UI Test Target for Rider and Another Test target for Driver and then use the -only-testing flag for xcode tests.

If tests are dependent on each other you can do

```<code>-only-testing:RiderUITests/Test1
-only-testing:DriverUITests/Test1

-only-testing:RiderUITests/Test2
-only-testing:DriverUITests/Test2
</code>```

You get the idea.

Basically, you can write a script or use fastlane https://github.com/fastlane/fastlane and run only one test at a time, one by one.

Body:
There is something called bluepill https://github.com/linkedin/bluepill, but it is only used to launch simultaneous XCTest cases and Simulators, it doesn't guarantee the order of the tests, so it won't work for you

You can create UI tests and run them on two different macs, but you need to figure out how test are going to interact and it seems difficult.

I would suggest to use   -only-testing feature of the xcodebuild

You can create a UI Test Target for Rider and Another Test target for Driver and then use the -only-testing flag for xcode tests.

If tests are dependent on each other you can do

-only-testing:RiderUITests/Test1
-only-testing:DriverUITests/Test1

-only-testing:RiderUITests/Test2
-only-testing:DriverUITests/Test2

You get the idea.

Basically, you can write a script or use fastlane https://github.com/fastlane/fastlane and run only one test at a time, one by one.


问:
Matlab: using scatter3 to draw horizontal squares

```<code>h1 = scatter3(X_Horiz,Y_Horiz,Z_Horiz,200,'s','filled',...
                           'MarkerEdgeColor','b','MarkerFaceColor',[0 .75 .75]);
hold on;

h2 = scatter3(X_Vert,Y_Vert,Z_Vert,200,'s','filled',...
                           'MarkerEdgeColor','g','MarkerFaceColor',[0 .75 .75]);
hold on;
</code>```

I know scatter3 can draw vertical square, however, I want to draw horizontal square which is parallel with the light red two interfaces. I try the rotate function, but it does not work.

答:
You can proceed, by drawing your own squares by specifying the length of side. You may follow something like below:

```<code>function myscatter3()
N = 10 ;
data = rand(N,2) ;
x = data(:,1) ; y = data(:,2) ; z = zeros(size(x)) ;

dx = 0.05 ;
figure
hold on
for i = 1:N
    coor = MakeSquare(x(i),y(i),dx) ;
    patch(coor(:,1),coor(:,2),coor(:,3),'w','edgecolor','k') ;
end
view(3)
end

function coor = MakeSquare(x,y,dx)

coor = zeros(4,3) ;

coor(1,:) = [x-dx/2,y-dx/2,0] ;
coor(2,:) = [x+dx/2,y-dx/2,0] ;
coor(3,:) = [x+dx/2,y+dx/2,0] ;
coor(4,:) = [x-dx/2,y+dx/2,0] ;
end
</code>```

Note that, that code can be fine tuned. It draws squares in the xy plane. It can be generalized to any plane.

Body:
h1 = scatter3(X_Horiz,Y_Horiz,Z_Horiz,200,'s','filled',...
                           'MarkerEdgeColor','b','MarkerFaceColor',[0 .75 .75]);
hold on;

h2 = scatter3(X_Vert,Y_Vert,Z_Vert,200,'s','filled',...
                           'MarkerEdgeColor','g','MarkerFaceColor',[0 .75 .75]);
hold on;

I know scatter3 can draw vertical square, however, I want to draw horizontal square which is parallel with the light red two interfaces. I try the rotate function, but it does not work.

Body:
You can proceed, by drawing your own squares by specifying the length of side. You may follow something like below:

function myscatter3()
N = 10 ;
data = rand(N,2) ;
x = data(:,1) ; y = data(:,2) ; z = zeros(size(x)) ;

dx = 0.05 ;
figure
hold on
for i = 1:N
    coor = MakeSquare(x(i),y(i),dx) ;
    patch(coor(:,1),coor(:,2),coor(:,3),'w','edgecolor','k') ;
end
view(3)
end

function coor = MakeSquare(x,y,dx)

coor = zeros(4,3) ;

coor(1,:) = [x-dx/2,y-dx/2,0] ;
coor(2,:) = [x+dx/2,y-dx/2,0] ;
coor(3,:) = [x+dx/2,y+dx/2,0] ;
coor(4,:) = [x-dx/2,y+dx/2,0] ;
end

Note that, that code can be fine tuned. It draws squares in the xy plane. It can be generalized to any plane.


问:
Adding global exception handling to ASP.NET
I work on a rather large web site. We currently have 4 web servers and an active passive db cluster running ASP.NET 2.0 with C#. Currently our exception handling is not trapping the correct exception being thrown. I have heard it is because Server.GetLastError() is not thread safe (note: we currently do not use Server.GetLastError().GetBaseException() which might be why we are not getting the correct error).

We are starting a project to trap exact exceptions so we can actually see the root cause of the error and I’m trying to find the best way to do it.

Our options are:

Go through all of our classes/methods(hundreds, if not thousands) to add try/catch/finally blocks to trap the correct exception.

Figure out a way to properly handle the exceptions in the global.asax.

So I guess my questions are:

Is Server.GetLastError() thread safe?

If two exceptions are thrown at the same time, will both be logged?

Is there a better way to handle this than what I have listed?

答:
You should take a look at Steven A. Lowe's CALM product.

It's a really nice 'plug-in' solution.

(Disclaimer: I was one of the beta-testers)

OwnerDisplayName: Andrew Rollings


问:
How to provide a plugin with data capabilities?
I have an application in which i want to provide the people who write plugins to it (plugins are made by implementing a basic interface, then i load the .dll). I want to give them the possibility to create settings and save data in my existing database. I would like to do this without having to create a table for each plugin - but if its required im willing to do it. I have come up with two basic scenarios:

Give the plugin an interface, where it can get a Dictionary  and serialize it to xml and save it in my database.

The plugin must be contained within a .zip file with a manifest file (my own invention) where it has a create sql script and a drop script for tables.

The first has limitations towards complex data types. The second has a larger complexity in the plugin, since it needs to be within a .zip file and unpacked etc...

Please advice on either of these approaces, or alternatives.

Cheers

答:
Your plugin constructor should recieve SettingRepository object, which provide methods for storing the setting and save them back

```<code>public MyCustomPlugin(PluginId id, SettingsRepostiory settingsRepository)
{
    _id = id;
    _settingsRepository = settings;
}

public void SomePluginMethod()
{
    PluginSettings setting = settingsRepository.Settings.WithId(_id);
    //...
}
</code>```

where PluginSettings indeed could be a dictionary, that serialized to XML

Body:
Your plugin constructor should recieve SettingRepository object, which provide methods for storing the setting and save them back

public MyCustomPlugin(PluginId id, SettingsRepostiory settingsRepository)
{
    _id = id;
    _settingsRepository = settings;
}

public void SomePluginMethod()
{
    PluginSettings setting = settingsRepository.Settings.WithId(_id);
    //...
}

where PluginSettings indeed could be a dictionary, that serialized to XML


问:
how to divide a string, I mean convert 0123456789 into "01","12","23","34","45","56","67","78","89"
I want to know how to split numbers, such as we fill 0123456789 data as the processing.
I want the results to come out.
 "01","12","23","34","45","56","67","78","89"
I found the problem is Bad Request (#400)
Unable to verify your data submission.
mycontroller

```<code>public function actionAbout() {
    $datas = yii::$app->request->post();
    $n = isset($datas['n']) ? $datas['n'] : NULL;
    $m = $n;

    return $this->render('about', [
                'n' => $n,
                'm' => $m,
    ]);
}
</code>```

view

```<code><form method="POST">
<div class="col-md-2">
    <?php echo Html::textInput('n', $n); ?>
</div>
<button class='btn-danger btn-md'>ตกลง »</button>
</code>```

```<code><?php
$data = $m;
$substr = null;
for ($i = 0; $i < strlen($data) - 1; $i++) {
    $substr = substr($data, $i, 2);
    echo $substr . ", ";}?>
</code>```

答:
Try this,

```<code>$data = '0123456789';
$substr = null;
for ($i = 0; $i < strlen($data) - 1; $i++) {
    $substr[]= substr($data, $i, 2);
}
var_dump($substr);
</code>```

just a few change in your code

Body:
I want to know how to split numbers, such as we fill 0123456789 data as the processing.
I want the results to come out.
 "01","12","23","34","45","56","67","78","89"
I found the problem is Bad Request (#400)
Unable to verify your data submission.
mycontroller

public function actionAbout() {
    $datas = yii::$app->request->post();
    $n = isset($datas['n']) ? $datas['n'] : NULL;
    $m = $n;

    return $this->render('about', [
                'n' => $n,
                'm' => $m,
    ]);
}

view

<form method="POST">

    <?php echo Html::textInput('n', $n); ?>

<button class='btn-danger btn-md'>ตกลง »</button>

<?php
$data = $m;
$substr = null;
for ($i = 0; $i < strlen($data) - 1; $i++) {
    $substr = substr($data, $i, 2);
    echo $substr . ", ";}?>

Body:
Try this,

$data = '0123456789';
$substr = null;
for ($i = 0; $i < strlen($data) - 1; $i++) {
    $substr[]= substr($data, $i, 2);
}
var_dump($substr);

just a few change in your code


问:
include? not working rails
So, what I'm trying to do is test if an input has a greater than sign, but the include? isnt working. Even when I just test if the if is "true" it doesnt work. The code is below

```<code>if @search.select.instance_of?(Integer)
  if @search.search.include?(">")
    @gsearch = @search.search.gsub(">","")
    @results = @model.where("#{@param} > ?", @newsearch.to_i)
  else
    @results = @model.where("#{@param}": @search.search)
  end
end
</code>```

So, first, it is testing if the "select" is an integer (it is in my tests), next it is testing if there is a ">" sign (there is, but it isnt found) Then it is displaying the results of the search. I have no idea whats wrong, and Im sorry for bad question asking, its late, and Im tired of this lol. Any help is appreciated!

EDIT: No error comes up, it just shows a blank page...

答:
```<code>2.3.1 :001 > "asdf>".include?(">")
 => true
2.3.1 :002 > "asdf".include?(">")
 => false
</code>```

Seems to work to me. My guess is you need to check what @search.search is, and see if it actually has a > in it.

If it does, the only other explanation I can think of is perhaps there are multiple > characters with fancy unicode versions.

Title: include? not working rails

Body:
So, what I'm trying to do is test if an input has a greater than sign, but the include? isnt working. Even when I just test if the if is "true" it doesnt work. The code is below

if @search.select.instance_of?(Integer)
  if @search.search.include?(">")
    @gsearch = @search.search.gsub(">","")
    @results = @model.where("#{@param} > ?", @newsearch.to_i)
  else
    @results = @model.where("#{@param}": @search.search)
  end
end

So, first, it is testing if the "select" is an integer (it is in my tests), next it is testing if there is a ">" sign (there is, but it isnt found) Then it is displaying the results of the search. I have no idea whats wrong, and Im sorry for bad question asking, its late, and Im tired of this lol. Any help is appreciated!

EDIT: No error comes up, it just shows a blank page...

Body:
2.3.1 :001 > "asdf>".include?(">")
 => true
2.3.1 :002 > "asdf".include?(">")
 => false

Seems to work to me. My guess is you need to check what @search.search is, and see if it actually has a > in it.

If it does, the only other explanation I can think of is perhaps there are multiple > characters with fancy unicode versions.


问:
Django Rest Framework: Unclear error message
my views.py:

```<code>class user_password(generics.UpdateAPIView):
    authentication_classes = ([JSONWebTokenAuthentication])
    serializer_class = user_password_serializer

    def get_queryset(self):
        return User.objects.get(id=self.request.user.id)
</code>```

But I'm getting this when running it:

AssertionError: Expected view user_password to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.

I know the serializer is okay because when I use a different type of View for the same thing. It works:

```<code>class user_password(APIView):

    authentication_classes = ([JSONWebTokenAuthentication])

    def put(self, request, format=None):

        serializer = user_password_serializer(data=request.data)
        if serializer.is_valid():
            if request.user.check_password(serializer.validated_data[
                                                'old_password']):
                request.user.set_password(serializer.validated_data[
                                          'new_password'])
                request.user.save()

                return Response({'success': True,
                                'result': serializer.validated_data},
                                status=status.HTTP_200_OK)
            else:
                    return Response({'success': False,
                                    'result': "credential mismatch"},
                                    status=status.HTTP_401_UNAUTHORIZED)

        return Response({'success': False,
                        'result': serializer.errors},
                        status=status.HTTP_400_BAD_REQUEST)
</code>```

I do not wish to change the way an endpoint is constructed. I do have a JWT authenticated call, and I wish /user/password would simply be able to PUT the 'old password' and 'new password' into that very same user.

What am I doing wrong in my generics.UpdateAPIView class? what is that .lookup_field it's talking about?

答:
.lookup_feild is the field (capture group) the UpdateAPIView expects in your url pattern (pk by default), like:

```<code>r'^user/(?P<pk>\d+)/password/?$'
</code>```

However, you should be able to override get_object instead of get_queryset and it should work without any changes to the url.

```<code>class user_password(generics.UpdateAPIView):
    authentication_classes = ([JSONWebTokenAuthentication])
    serializer_class = user_password_serializer

    def get_object(self):
        return User.objects.get(id=self.request.user.id)
</code>```

Also, simply returning self.request.user will work just fine (I don't know how exactly JWT authentication implemented in your project, but most of the time Django pulls the user model in request.user anyway).

Body:
my views.py:

class user_password(generics.UpdateAPIView):
    authentication_classes = ([JSONWebTokenAuthentication])
    serializer_class = user_password_serializer

    def get_queryset(self):
        return User.objects.get(id=self.request.user.id)

But I'm getting this when running it:

AssertionError: Expected view user_password to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.

I know the serializer is okay because when I use a different type of View for the same thing. It works:

class user_password(APIView):

    authentication_classes = ([JSONWebTokenAuthentication])

    def put(self, request, format=None):

        serializer = user_password_serializer(data=request.data)
        if serializer.is_valid():
            if request.user.check_password(serializer.validated_data[
                                                'old_password']):
                request.user.set_password(serializer.validated_data[
                                          'new_password'])
                request.user.save()

                return Response({'success': True,
                                'result': serializer.validated_data},
                                status=status.HTTP_200_OK)
            else:
                    return Response({'success': False,
                                    'result': "credential mismatch"},
                                    status=status.HTTP_401_UNAUTHORIZED)

        return Response({'success': False,
                        'result': serializer.errors},
                        status=status.HTTP_400_BAD_REQUEST)

I do not wish to change the way an endpoint is constructed. I do have a JWT authenticated call, and I wish /user/password would simply be able to PUT the 'old password' and 'new password' into that very same user.

What am I doing wrong in my generics.UpdateAPIView class? what is that .lookup_field it's talking about?

Body:
.lookup_feild is the field (capture group) the UpdateAPIView expects in your url pattern (pk by default), like:

r'^user/(?P<pk>\d+)/password/?$'

However, you should be able to override get_object instead of get_queryset and it should work without any changes to the url.

class user_password(generics.UpdateAPIView):
    authentication_classes = ([JSONWebTokenAuthentication])
    serializer_class = user_password_serializer

    def get_object(self):
        return User.objects.get(id=self.request.user.id)

Also, simply returning self.request.user will work just fine (I don't know how exactly JWT authentication implemented in your project, but most of the time Django pulls the user model in request.user anyway).


问:
unity3d OnMouseDown function
I am new to Unity3D. I am trying to do a simple thing. But not able to do this. I have a .obj file which is a 3d key file. I do the followings:

Import this key (to assets) in unity3D

Add this key to scene (from assets to hierarchy)

Add a script to this key

Add the OnMouseDown() function to this script as  follows -

```<code>void OnMouseDown()
{
    Debug.Log ("clicked...");
}
</code>```

But when I click the key no message is showing in console. Please tell me what is the problem?

答:
You need to assign a collider to the 3d object if you want to fire it with OnMouseDown:

OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.

This event is sent to all scripts of the Collider or GUIElement.

Title: unity3d OnMouseDown function

Body:
I am new to Unity3D. I am trying to do a simple thing. But not able to do this. I have a .obj file which is a 3d key file. I do the followings:

Import this key (to assets) in unity3D

Add this key to scene (from assets to hierarchy)

Add a script to this key

Add the OnMouseDown() function to this script as  follows -

void OnMouseDown()
{
    Debug.Log ("clicked...");
}

But when I click the key no message is showing in console. Please tell me what is the problem?


问:
Detect whether current Windows version is 32 bit or 64 bit
Believe it or not, my installer is so old that it doesn't have an option to detect the 64-bit version of Windows.

Is there a Windows DLL call or (even better) an environment variable that would give that information for Windows XP and Windows Vista?

One possible solution

I see that Wikipedia states that the 64-bit version of Windows XP and Windows Vista have a unique environment variable: %ProgramW6432%, so I'm guessing that'd be empty on 32-bit Windows.

This variable points to Program Files directory, which stores all the installed program of Windows and others. The default on English-language systems is C:\Program Files. In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)% which defaults to C:\Program Files (x86) and %ProgramW6432% which defaults to C:\Program Files. The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).

答: For a VBScript / WMI one-liner that retrieves the actuals bits number (32 or 64) of the OS or the Hardware, take a look at http://csi-windows.com/toolkit/csi-getosbits</p>

OwnerDisplayName: Clay Nichols

LastEditorDisplayName: Clay Nichols


问:
How can I update NodeJS and NPM to their latest versions?

I just installed Node.js & NPM (Node Package Manager)

I installed NPM for access to additional Node.js Modules.

After I installed Node.js & NPM I noticed that neither were the latest versions available.

I would like to know: How do I upgrade Node.js, NPM, and my Node.js Modules to their latest versions?

Do I need to uninstall Node.js & NPM and reinstall the latest versions?

Here is the link to what I have tried so far. This link is a section from npm.

答:
SIMPLY USE THIS

```<code>npm i -g npm
</code>```

This is what i get promped on my console from npm when new update/bug-fix are released:

ContentLicense: CC BY-SA 4.0

Body:
SIMPLY USE THIS

npm i -g npm

This is what i get promped on my console from npm when new update/bug-fix are released:


问:
Deleting only the content of the two sub folders
I have my codes here that will delete but It will delete including the two subfolders. I want to delete only the content of the two sub folders.

```<code>          Array.ForEach(Directory.GetFiles(txtfilename.Text), File.Delete);
          System.IO.DirectoryInfo di = new DirectoryInfo(txtfilename.Text);

            foreach (FileInfo file in di.GetFiles())
            {
                file.Delete();
            }
            foreach (DirectoryInfo dir in di.GetDirectories())
            {
                dir.Delete(true);
            }
</code>```

If someone can debug or show some solutions, Thank you so much.

答:
Alright. I solved my own problem. I used this code. After searching some codes and combine each Idea and that's the reason I come up this kind of code but I don't totally understand what I'm doing.

```<code>   string local = txtfilename.Text;
   string[] dirs = Directory.GetFiles(local,
                   "*.csv*", SearchOption.AllDirectories);

   List<string> singleDirNames = dirs.Select(x => new
   FileInfo(x).Directory.Name).Distinct().ToList();

   foreach (string filePath in dirs)
      {
      if (filePath.Contains(".csv"))
      File.Delete(filePath);
      }
</code>```

Because the content of the two sub folders are csv file. I specifically target the file extension to delete. I less my want into a certain extension to be delete. I really want to delete everything inside the two sub folders. Can Anyone improve my anwswer?

Body:
I have my codes here that will delete but It will delete including the two subfolders. I want to delete only the content of the two sub folders.

          Array.ForEach(Directory.GetFiles(txtfilename.Text), File.Delete);
          System.IO.DirectoryInfo di = new DirectoryInfo(txtfilename.Text);

            foreach (FileInfo file in di.GetFiles())
            {
                file.Delete();
            }
            foreach (DirectoryInfo dir in di.GetDirectories())
            {
                dir.Delete(true);
            }

If someone can debug or show some solutions, Thank you so much.

Body:
Alright. I solved my own problem. I used this code. After searching some codes and combine each Idea and that's the reason I come up this kind of code but I don't totally understand what I'm doing.

   string local = txtfilename.Text;
   string[] dirs = Directory.GetFiles(local,
                   "*.csv*", SearchOption.AllDirectories);

   List<string> singleDirNames = dirs.Select(x => new
   FileInfo(x).Directory.Name).Distinct().ToList();

   foreach (string filePath in dirs)
      {
      if (filePath.Contains(".csv"))
      File.Delete(filePath);
      }

Because the content of the two sub folders are csv file. I specifically target the file extension to delete. I less my want into a certain extension to be delete. I really want to delete everything inside the two sub folders. Can Anyone improve my anwswer?


问:
Intellij - Unable to use newer Java 8 classes - Error : "Usage of API documented as @since 1.6+.."
I'm trying to use a java.lang.function.Function in my java 8 code base, but i keep getting the following error in Intellij.

Usage of API documented as @since 1.6+  This inspection finds all
  usages of methods that have @since tag in their documentation.  This
  may be useful when development is performed under newer SDK version as
  the target platform for production

I seem to have the correct Project and Compiler settings

Project Settings: (File -> Project Structure)

```<code>Project Settings -> Project -> Project SDK = Java 1.8
Project Settings -> Project -> Project Language Level = 8 - Lambdas, Type Annotations etc
</code>```

Compiler Settings: (File -> Settings)

```<code>Build, Execution, Deployment -> Compiler -> Java Compiler -> Project Bytecode Version : 1.8
Build, Execution, Deployment -> Compiler -> Java Compiler -> Per module Bytecode Version -> Target Bytecode Version : 1.8
</code>```

What is the problem?

答:
Maybe your config of repository has properties include compiler Version. examine
settings.xml file.

```<code><jdk>1.8</jdk>
</activation>
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</code>```

Body:
I'm trying to use a java.lang.function.Function in my java 8 code base, but i keep getting the following error in Intellij.

Usage of API documented as @since 1.6+  This inspection finds all
  usages of methods that have @since tag in their documentation.  This
  may be useful when development is performed under newer SDK version as
  the target platform for production

I seem to have the correct Project and Compiler settings

Project Settings: (File -> Project Structure)

Project Settings -> Project -> Project SDK = Java 1.8
Project Settings -> Project -> Project Language Level = 8 - Lambdas, Type Annotations etc

Compiler Settings: (File -> Settings)

Build, Execution, Deployment -> Compiler -> Java Compiler -> Project Bytecode Version : 1.8
Build, Execution, Deployment -> Compiler -> Java Compiler -> Per module Bytecode Version -> Target Bytecode Version : 1.8

What is the problem?

Body:
Maybe your config of repository has properties include compiler Version. examine
settings.xml file.

<jdk>1.8</jdk>
</activation>
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>


问:
why there is a empty area in the upside of my UITableViewCell?
enter image description here

enter image description here

Hi guys, I need some help to solve problems
i do not know why there is an empty area in my UITableViewCell like in the picture
and when I continnue to drop up the table, the blue UITextView will disappear，then the next cell appears.Anyone know Why?

```<code>    @implementation TableCellModel
+(UITableViewCell *) getCellOfFreeChampionsList
{
    UITableViewCell * tableCell = [[super alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NULL];
    UITextView * textView = [[UITextView alloc] init];
    textView.tag = 11;
    textView.text = @"1qaz2wsxE";
    textView.frame = CGRectMake(5, 5, 70, 20);
    textView.backgroundColor = [UIColor blueColor];
    [tableCell.contentView addSubview:textView];

//    UILabel * la = [[UILabel alloc] init];
//    la.frame = CGRectMake(5, 50, 70, 20);
//    la.tag = 12;
//    [tableCell.contentView addSubview:la];

    NSLog(@"%@", textView.text);
    NSLog(@"count is %lu", (unsigned long)tableCell.subviews.count);

    return tableCell;
}

    @implementation TableViewDataSource

@synthesize tableView;
@synthesize tableCell;
@synthesize LHfetchedResultsController;
@synthesize numberOfRows;
@synthesize dataTemp;
@synthesize paused;

-(id)initWithTableView:(UITableView *) tableView
{
    self = [super init];
    if (self) {
        self.tableView = tableView;
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
    }
    return self;
}

-(void)dateSourceWithChineseNewestVideos:(NSArray *)videosResults
{
    self.dataTemp = videosResults;
    self.tableCell = [TableCellModel getCellOfFreeChampionsList];
    self.numberOfRows = videosResults.count;
    NSInteger n = self.numberOfRows;
    if (self.numberOfRows == 0) {
        self.numberOfRows = 1;
    }
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

//    [self configCellData:indexPath cell:self.tableCell];
    if (self.dataTemp.count < 0) {
        NSArray * arr = self.dataTemp;
        NSInteger n = arr.count;
        NSInteger indexNum = indexPath.row;
        ChineseNewestVideos * re1 = [self.dataTemp objectAtIndex:indexNum];
        UITextView * textView = [tableCell viewWithTag:11];
        textView.text = re1.title;

        NSLog(@"text is %lu",(unsigned long)tableCell.subviews.count);
        NSLog(@"text is %@",textView.text);

//        UILabel * la = [tableCell viewWithTag:12];
//        la.text = [NSString stringWithFormat:@"%lD",(long)n];
    }

    return self.tableCell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    id<NSFetchedResultsSectionInfo> sectionInfo = self.LHfetchedResultsController.sections[section];
//    self.numberOfRows = sectionInfo.numberOfObjects;
    return self.numberOfRows;
}
</code>```

答: because i declare UITableViewCell outside of cellForRowAtIndexPath after i move it in it works

Body:
enter image description here

enter image description here

Hi guys, I need some help to solve problems
i do not know why there is an empty area in my UITableViewCell like in the picture
and when I continnue to drop up the table, the blue UITextView will disappear，then the next cell appears.Anyone know Why?

    @implementation TableCellModel
+(UITableViewCell *) getCellOfFreeChampionsList
{
    UITableViewCell * tableCell = [[super alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NULL];
    UITextView * textView = [[UITextView alloc] init];
    textView.tag = 11;
    textView.text = @"1qaz2wsxE";
    textView.frame = CGRectMake(5, 5, 70, 20);
    textView.backgroundColor = [UIColor blueColor];
    [tableCell.contentView addSubview:textView];

//    UILabel * la = [[UILabel alloc] init];
//    la.frame = CGRectMake(5, 50, 70, 20);
//    la.tag = 12;
//    [tableCell.contentView addSubview:la];

    NSLog(@"%@", textView.text);
    NSLog(@"count is %lu", (unsigned long)tableCell.subviews.count);

    return tableCell;
}

    @implementation TableViewDataSource

@synthesize tableView;
@synthesize tableCell;
@synthesize LHfetchedResultsController;
@synthesize numberOfRows;
@synthesize dataTemp;
@synthesize paused;

-(id)initWithTableView:(UITableView *) tableView
{
    self = [super init];
    if (self) {
        self.tableView = tableView;
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
    }
    return self;
}

-(void)dateSourceWithChineseNewestVideos:(NSArray *)videosResults
{
    self.dataTemp = videosResults;
    self.tableCell = [TableCellModel getCellOfFreeChampionsList];
    self.numberOfRows = videosResults.count;
    NSInteger n = self.numberOfRows;
    if (self.numberOfRows == 0) {
        self.numberOfRows = 1;
    }
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

//    [self configCellData:indexPath cell:self.tableCell];
    if (self.dataTemp.count < 0) {
        NSArray * arr = self.dataTemp;
        NSInteger n = arr.count;
        NSInteger indexNum = indexPath.row;
        ChineseNewestVideos * re1 = [self.dataTemp objectAtIndex:indexNum];
        UITextView * textView = [tableCell viewWithTag:11];
        textView.text = re1.title;

        NSLog(@"text is %lu",(unsigned long)tableCell.subviews.count);
        NSLog(@"text is %@",textView.text);

//        UILabel * la = [tableCell viewWithTag:12];
//        la.text = [NSString stringWithFormat:@"%lD",(long)n];
    }

    return self.tableCell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    id<NSFetchedResultsSectionInfo> sectionInfo = self.LHfetchedResultsController.sections[section];
//    self.numberOfRows = sectionInfo.numberOfObjects;
    return self.numberOfRows;
}


问:
Laravel getQueryString() without &
I'm trying to output a variable containing part of a URL into Javascript on my page. When I do this, it changes any & into &, which breaks the URL.

I've tried using str_replace, html_entity_decode, htmlspecialchars_decode but the result was always same & instead of &.

How i can get it with & instead of & ?

This is my controller:

```<code>//here we catch the query
public function index(Request $request)
    {
        $input   = $request->getQueryString();

        return view('lots.browse')->withInput($input);
    }

// here we filter the ajax request
public function indexData(LotFilters $filters)
    {
       $lots  = Lot::filter($filters);

        return Datatables::eloquent($lots)->make(true);
    }
</code>```

This is my view:

```<code><!-- Datatables -->
    <script type="text/javascript">
        $(document).ready(function(){
            $('#table').DataTable({
                searching: false,
                processing: true,
                serverSide: true,
                ajax: '{{  url("/data") . "?" .  html_entity_decode($input) }}',
                columns: [
                    { data: 'date', name: 'date' },
                    { data: 'bid', name: 'bid' },
                    { data: 'auction_name', name: 'auction_name' },
                    { data: 'pics_urls', name: 'pics_urls' },
                    { data: 'company', name: 'company' },
                    { data: 'model_name_en', name: 'model_name_en' },
                    { data: 'model_type_en', name: 'model_type_en' },
                    { data: 'grade_en', name: 'grade_en' },
                    { data: 'mileage_en', name: 'mileage_en' },
                    { data: 'model_year_en', name: 'model_year_en' },
                    { data: 'color_en', name: 'color_en' },
                    { data: 'displacement', name: 'displacement' },
                    { data: 'transmission_en', name: 'transmission_en' },
                    { data: 'scores_en', name: 'scores_en' },
                    { data: 'start_price_en', name: 'start_price_en' },
                    { data: 'result_en', name: 'result_en' }
                ]
            });
        });
    </script>
</code>```

And this is the result:

答: try using rawurldecode it should fixe it.</p>

Title: Laravel getQueryString() without &

Body:
I'm trying to output a variable containing part of a URL into Javascript on my page. When I do this, it changes any & into &, which breaks the URL.

I've tried using str_replace, html_entity_decode, htmlspecialchars_decode but the result was always same & instead of &.

How i can get it with & instead of & ?

This is my controller:

//here we catch the query
public function index(Request $request)
    {
        $input   = $request->getQueryString();

        return view('lots.browse')->withInput($input);
    }

// here we filter the ajax request
public function indexData(LotFilters $filters)
    {
       $lots  = Lot::filter($filters);

        return Datatables::eloquent($lots)->make(true);
    }

This is my view:

And this is the result:


问:
fatal: early EOF fatal: index-pack failed
I have googled and found many solutions but none work for me.

I am trying to clone from one machine by connecting to the remote server which is in the LAN network.

Running this command from another machine cause error.

But running the SAME clone command using git://192.168.8.5 ... at the server it's okay and successful.

Any ideas ?

```<code>user@USER ~
$ git clone  -v git://192.168.8.5/butterfly025.git
Cloning into 'butterfly025'...
remote: Counting objects: 4846, done.
remote: Compressing objects: 100% (3256/3256), done.
fatal: read error: Invalid argument, 255.05 MiB | 1.35 MiB/s
fatal: early EOF
fatal: index-pack failed
</code>```

I have added this config in .gitconfig but no help also.

Using the git version 1.8.5.2.msysgit.0

```<code>[core]
    compression = -1
</code>```

答:
If you're on Windows, you may want to check git clone fails with "index-pack" failed?.

Basically, after running your git.exe daemon ... command, select some text from that console window. Retry pulling/cloning, it might just work now!

See this answer for more info.

Body:
I have googled and found many solutions but none work for me.

I am trying to clone from one machine by connecting to the remote server which is in the LAN network.

Running this command from another machine cause error.

But running the SAME clone command using git://192.168.8.5 ... at the server it's okay and successful.

Any ideas ?

user@USER ~
$ git clone  -v git://192.168.8.5/butterfly025.git
Cloning into 'butterfly025'...
remote: Counting objects: 4846, done.
remote: Compressing objects: 100% (3256/3256), done.
fatal: read error: Invalid argument, 255.05 MiB | 1.35 MiB/s
fatal: early EOF
fatal: index-pack failed

I have added this config in .gitconfig but no help also.

Using the git version 1.8.5.2.msysgit.0

[core]
    compression = -1


问:
Website can not access MongoDB on AWS
I've deployed MEAN Stack website on AWS. And website runs well on my local.
But it shows POST/xxx/register 500(Internal Server Error) after deploying it, when I am trying to access DB(MongoDB).

I've deployed this like below flow.

Project Published Github

Installed instance on AWS by using MEAN powered Bitnami.

Added protocols for website and mongoDB (8080, 27017).

Cloned from Git by using Putty.

And it seems that DB access problem.
For example, when I've tired to register a user on live server Putty shows like below

POST /api/v1/register 500 35.645 ms - 1675

app.js

```<code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var https = require('https');

var mongoose = require('mongoose');
var passport = require('passport');

mongoose.connect('mongodb://localhost/news');
require('./models/Users');
require('./config/passport');

var index = require('./routes/index');
var authenticate_api = require('./routes/authenticate_api');

app.use('/', index);
app.use('/api/v1/', authenticate_api);
</code>```

and the route/authenticate_api.js file

```<code>var mongoose = require('mongoose');
var passport = require('passport');
var User = mongoose.model('User');

require('../config/passport');
var express = require('express');
var router = express.Router();

var jwt = require('express-jwt');
var auth = jwt({secret: 'SECRET', userProperty: 'payload'});

router.post('/register', function(req, res, next) {
    if (!req.body.username || !req.body.password) {
        return res.status(400).json({message: 'Please fill out all fields'});
    }
    var user = new User();
    user.username = req.body.username;
    user.setPassword(req.body.password);
    user.save(function(err, user) {
        if(err) {
            return next(err);
        }
        return res.json({token: user.generateJWT()});
    });
})

module.exports = router;
</code>```

What's the matter with that?
Cheers.

答:
I've just solved it myself.
It was a mongoDB permission problem
I could find out mongodb status always stop/waiting.
So I solved it like below.

```<code>/var/log/mongodb/  sudo chown -R mongodb:mongodb .
/var/lib/mongodb/  sudo chown -R mongodb:mongodb .
/stack/mongodb/tmp/   sudo chown mongodb mongodb-27017.sock
$/ ps -ef | grep mongo      {get for mongo PID}
$/ kill -9 PID
$/ sudo service mongodb start
</code>```

It works well now. Thanks for your consideration.

Title: Website can not access MongoDB on AWS

Body:
I've deployed MEAN Stack website on AWS. And website runs well on my local.
But it shows POST/xxx/register 500(Internal Server Error) after deploying it, when I am trying to access DB(MongoDB).

I've deployed this like below flow.

Project Published Github

Installed instance on AWS by using MEAN powered Bitnami.

Added protocols for website and mongoDB (8080, 27017).

Cloned from Git by using Putty.

And it seems that DB access problem.
For example, when I've tired to register a user on live server Putty shows like below

POST /api/v1/register 500 35.645 ms - 1675

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var https = require('https');

var mongoose = require('mongoose');
var passport = require('passport');

mongoose.connect('mongodb://localhost/news');
require('./models/Users');
require('./config/passport');

var index = require('./routes/index');
var authenticate_api = require('./routes/authenticate_api');

app.use('/', index);
app.use('/api/v1/', authenticate_api);

and the route/authenticate_api.js file

var mongoose = require('mongoose');
var passport = require('passport');
var User = mongoose.model('User');

require('../config/passport');
var express = require('express');
var router = express.Router();

var jwt = require('express-jwt');
var auth = jwt({secret: 'SECRET', userProperty: 'payload'});

router.post('/register', function(req, res, next) {
    if (!req.body.username || !req.body.password) {
        return res.status(400).json({message: 'Please fill out all fields'});
    }
    var user = new User();
    user.username = req.body.username;
    user.setPassword(req.body.password);
    user.save(function(err, user) {
        if(err) {
            return next(err);
        }
        return res.json({token: user.generateJWT()});
    });
})

module.exports = router;

What's the matter with that?
Cheers.

Body:
I've just solved it myself.
It was a mongoDB permission problem
I could find out mongodb status always stop/waiting.
So I solved it like below.

/var/log/mongodb/  sudo chown -R mongodb:mongodb .
/var/lib/mongodb/  sudo chown -R mongodb:mongodb .
/stack/mongodb/tmp/   sudo chown mongodb mongodb-27017.sock
$/ ps -ef | grep mongo      {get for mongo PID}
$/ kill -9 PID
$/ sudo service mongodb start

It works well now. Thanks for your consideration.


问:
Calculate performance based on rating in another table
There is a table for Sales with revenue each day and another table for Rating which is used to calculate the performance based on revenue milestone

```<code>CREATE TABLE #Rating(
    [Revenue] int NULL,
    [Percentage] float NULL
) ON [PRIMARY]

insert into [#Rating] select 20000, 1.1
insert into [#Rating] select 30000, 1.2
insert into [#Rating] select 40000, 1.3

CREATE TABLE #Sales(
    [Date] datetime,
    [Revenue] int NULL
) ON [PRIMARY]

insert into #Sales select '2017-01-01', 7000
insert into #Sales select '2017-01-02', 22000
insert into #Sales select '2017-01-03', 33000
insert into #Sales select '2017-01-04', 46000
insert into #Sales select '2017-01-05', 50000
</code>```

We would like to evaluate the sales performance based on rating. For instance,

If Revenue reaches 20000 milestone, performance = revenue * 1.0

If Revenue reaches 30000 milestone, performance = revenue * 1.1

So the final performance should be as follow

```<code>Date, Revenue, Performance
'2017-01-01', 7000, 7000
'2017-01-02', 22000, 24200
'2017-01-03', 33000, 39600
'2017-01-04', 46000, 59800
'2017-01-05', 50000, 65000
</code>```

May I know how to setup the query for the matching? Thanks

[Edited to revise the wordings]

答:
The two simplest ways to achieve this are with a subquery in your select statement or an outer apply. For example:

```<code>SELECT S.[Date],
       S.Revenue,
       Performance = S.Revenue * COALESCE((SELECT TOP 1 R.Percentage FROM #Rating AS R WHERE R.Revenue <= S.Revenue ORDER BY R.Revenue DESC), 1)
FROM #Sales S;
</code>```

Or...

```<code>SELECT S.[Date],
       S.Revenue,
       Performance = S.Revenue * COALESCE(R.Percentage, 1)
FROM #Sales S
OUTER APPLY (SELECT TOP 1 R.Percentage FROM #Rating AS R WHERE R.Revenue <= S.Revenue ORDER BY R.Revenue DESC) AS R;
</code>```

Note: You could probably use MAX(R.Percentage) instead of TOP 1 (leaving out the ORDER BY R.Revenue DESC as well), since it's unlikely the percentage would go down with an increase in revenue.

Body:
There is a table for Sales with revenue each day and another table for Rating which is used to calculate the performance based on revenue milestone

CREATE TABLE #Rating(
    [Revenue] int NULL,
    [Percentage] float NULL
) ON [PRIMARY]

insert into [#Rating] select 20000, 1.1
insert into [#Rating] select 30000, 1.2
insert into [#Rating] select 40000, 1.3

CREATE TABLE #Sales(
    [Date] datetime,
    [Revenue] int NULL
) ON [PRIMARY]

insert into #Sales select '2017-01-01', 7000
insert into #Sales select '2017-01-02', 22000
insert into #Sales select '2017-01-03', 33000
insert into #Sales select '2017-01-04', 46000
insert into #Sales select '2017-01-05', 50000

We would like to evaluate the sales performance based on rating. For instance,

If Revenue reaches 20000 milestone, performance = revenue * 1.0

If Revenue reaches 30000 milestone, performance = revenue * 1.1

So the final performance should be as follow

Date, Revenue, Performance
'2017-01-01', 7000, 7000
'2017-01-02', 22000, 24200
'2017-01-03', 33000, 39600
'2017-01-04', 46000, 59800
'2017-01-05', 50000, 65000

May I know how to setup the query for the matching? Thanks

[Edited to revise the wordings]

Body:
The two simplest ways to achieve this are with a subquery in your select statement or an outer apply. For example:

SELECT S.[Date],
       S.Revenue,
       Performance = S.Revenue * COALESCE((SELECT TOP 1 R.Percentage FROM #Rating AS R WHERE R.Revenue <= S.Revenue ORDER BY R.Revenue DESC), 1)
FROM #Sales S;

Or...

SELECT S.[Date],
       S.Revenue,
       Performance = S.Revenue * COALESCE(R.Percentage, 1)
FROM #Sales S
OUTER APPLY (SELECT TOP 1 R.Percentage FROM #Rating AS R WHERE R.Revenue <= S.Revenue ORDER BY R.Revenue DESC) AS R;

Note: You could probably use MAX(R.Percentage) instead of TOP 1 (leaving out the ORDER BY R.Revenue DESC as well), since it's unlikely the percentage would go down with an increase in revenue.


问:
How do I get these to act on their own in their separate containers?
I am a javascript/jquery novice and what I am trying to figure out is when you click the plus or minus buttons the numbers increase/decrease. However I have two sets of these in different containers but they both change their values when clicking on just one set. How can I separate these?

I looked up this javascript/jquery code on stackoverflow to make the plus/minus buttons to work and now I would like to get insight on how to make these work separately. Please help? Any help is appreciated!

Here is my demo: https://jsfiddle.net/hyona/yerfdkvk/

```<code><div class="container">
  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty' />
  <input type='button' value='+' class='qtyplus' field='quantity' />
</div>

<div class="container">
  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty'/>
  <input type='button' value='+' class='qtyplus' field='quantity' />
</div>

//CSS Styling
.container {
  width: 120px;
  margin: 0 0 10px;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-align: center;
  -moz-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -moz-box-pack: justify;
  -webkit-justify-content: space-between;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.qty {
  width: 50px;
  height: 30px;
  text-align: center;
}

input[type='button'] {
  border: none;
  background: none;
  font-size: 18px;
  outline: none;
  cursor: pointer;
}

$(document).ready(function(){
  $('.qtyplus').click(function(e){
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal)) {
      if (currentVal < 20)
      {
        $('input[name='+fieldName+']').val(currentVal + 1);
        $('.qtyminus').val("-").removeAttr('style');
      }
      else
      {
        $('.qtyplus').val("+").css('color','#aaa');
      }
    } else {
      $('input[name='+fieldName+']').val(1);
    }
  });

  $(".qtyminus").click(function(e) {
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal) && currentVal > 1) {
      $('input[name='+fieldName+']').val(currentVal - 1);
      $('.qtyplus').val("+").removeAttr('style');
    } else {
      $('input[name='+fieldName+']').val(1);
      $('.qtyminus').val("-").css('color','#aaa');
    }
  });
});
</code>```

答:
Within your event handler, you are using selectors like $('.qtyplus') and $('input[name='+fieldName+']'), which select all matching elements. To restrict to just the ones within the clicked element's container, use the .closest() and .find() methods:

```<code>$(this).closest('.container').find('input[name='+fieldName+']')
</code>```

...where this is automatically set to be the clicked element.

(For your current HTML structure you could use .siblings() instead, but I wouldn't recommend it because .closest(...).find(...) will cope better with more complicated nested structures so you're less likely to need to change the JS if you change the HTML.)

In context:

$(document).ready(function(){
  $('.qtyplus').click(function(e){
    var fieldName = $(this).attr('field');
    var container = $(this).closest('.container');
    var field = container.find('input[name='+fieldName+']');
    var currentVal = parseInt(field.val());
    if (!isNaN(currentVal)) {
      if (currentVal < 20) {
        field.val(currentVal + 1);
        container.find('.qtyminus').val("-").removeAttr('style');
      } else {
        container.find('.qtyplus').val("+").css('color','#aaa');
      }
    } else {
      field.val(1);
    }
  });

  $(".qtyminus").click(function(e) {
    var fieldName = $(this).attr('field');
    var container = $(this).closest('.container');
    var field = container.find('input[name='+fieldName+']');
    var currentVal = parseInt(field.val());
    if (!isNaN(currentVal) && currentVal > 1) {
      field.val(currentVal - 1);
      container.find('.qtyplus').val("+").removeAttr('style');
    } else {
      field.val(1);
      container.find('.qtyminus').val("-").css('color','#aaa');
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty' />
  <input type='button' value='+' class='qtyplus' field='quantity' />
</div>

<div class="container">
  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty'/>
  <input type='button' value='+' class='qtyplus' field='quantity' />
</div></code>```

Note that if you find yourself calling jQuery methods with the same selector more than once in the same function it is generally better to use a variable to cache the result, as shown above.

There is no need to call e.preventDefault() in a type="button" element's click handler, because there is no default behaviour, so I've removed that from your code.

(Note also that the logic you are using to set the +/- button styles/colours is incomplete (you don't reset them if the user types a non-numeric value into the field), but that has nothing to do with what you're asking so I'll leave fixing it as an exercise for the reader.)

Body:
I am a javascript/jquery novice and what I am trying to figure out is when you click the plus or minus buttons the numbers increase/decrease. However I have two sets of these in different containers but they both change their values when clicking on just one set. How can I separate these?

I looked up this javascript/jquery code on stackoverflow to make the plus/minus buttons to work and now I would like to get insight on how to make these work separately. Please help? Any help is appreciated!

Here is my demo: https://jsfiddle.net/hyona/yerfdkvk/

  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty' />
  <input type='button' value='+' class='qtyplus' field='quantity' />

  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty'/>
  <input type='button' value='+' class='qtyplus' field='quantity' />

//CSS Styling
.container {
  width: 120px;
  margin: 0 0 10px;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-align: center;
  -moz-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -moz-box-pack: justify;
  -webkit-justify-content: space-between;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.qty {
  width: 50px;
  height: 30px;
  text-align: center;
}

input[type='button'] {
  border: none;
  background: none;
  font-size: 18px;
  outline: none;
  cursor: pointer;
}

$(document).ready(function(){
  $('.qtyplus').click(function(e){
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal)) {
      if (currentVal < 20)
      {
        $('input[name='+fieldName+']').val(currentVal + 1);
        $('.qtyminus').val("-").removeAttr('style');
      }
      else
      {
        $('.qtyplus').val("+").css('color','#aaa');
      }
    } else {
      $('input[name='+fieldName+']').val(1);
    }
  });

  $(".qtyminus").click(function(e) {
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal) && currentVal > 1) {
      $('input[name='+fieldName+']').val(currentVal - 1);
      $('.qtyplus').val("+").removeAttr('style');
    } else {
      $('input[name='+fieldName+']').val(1);
      $('.qtyminus').val("-").css('color','#aaa');
    }
  });
});

Body:
Within your event handler, you are using selectors like $('.qtyplus') and $('input[name='+fieldName+']'), which select all matching elements. To restrict to just the ones within the clicked element's container, use the .closest() and .find() methods:

$(this).closest('.container').find('input[name='+fieldName+']')

...where this is automatically set to be the clicked element.

(For your current HTML structure you could use .siblings() instead, but I wouldn't recommend it because .closest(...).find(...) will cope better with more complicated nested structures so you're less likely to need to change the JS if you change the HTML.)

In context:

$(document).ready(function(){
  $('.qtyplus').click(function(e){
    var fieldName = $(this).attr('field');
    var container = $(this).closest('.container');
    var field = container.find('input[name='+fieldName+']');
    var currentVal = parseInt(field.val());
    if (!isNaN(currentVal)) {
      if (currentVal < 20) {
        field.val(currentVal + 1);
        container.find('.qtyminus').val("-").removeAttr('style');
      } else {
        container.find('.qtyplus').val("+").css('color','#aaa');
      }
    } else {
      field.val(1);
    }
  });

  $(".qtyminus").click(function(e) {
    var fieldName = $(this).attr('field');
    var container = $(this).closest('.container');
    var field = container.find('input[name='+fieldName+']');
    var currentVal = parseInt(field.val());
    if (!isNaN(currentVal) && currentVal > 1) {
      field.val(currentVal - 1);
      container.find('.qtyplus').val("+").removeAttr('style');
    } else {
      field.val(1);
      container.find('.qtyminus').val("-").css('color','#aaa');
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty' />
  <input type='button' value='+' class='qtyplus' field='quantity' />
</div>

<div class="container">
  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty'/>
  <input type='button' value='+' class='qtyplus' field='quantity' />
</div>

Note that if you find yourself calling jQuery methods with the same selector more than once in the same function it is generally better to use a variable to cache the result, as shown above.

There is no need to call e.preventDefault() in a type="button" element's click handler, because there is no default behaviour, so I've removed that from your code.

(Note also that the logic you are using to set the +/- button styles/colours is incomplete (you don't reset them if the user types a non-numeric value into the field), but that has nothing to do with what you're asking so I'll leave fixing it as an exercise for the reader.)


问:
Wrong injection of $modalProvider dependency angujarjs
I'm trying to open a dialog box in angularjs using bootstrap but whenever i try i get this error while injecting the right dependencies.

```<code>.controller('login_ctrl', ['$scope','$http','$window','$modal','$log', function($scope,$http,$window,$modal,$log) {

    var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',

            //size: size,
            resolve: {
                user: function() {
                    return userData;
                },
                selectedProducts: function() {
                    return userData.selectedProducts;
                },
                products: function () {
                    //console.log($scope.selectedProducts);
                    return $scope.products; // get all available products
                }
            }
        });

}])
</code>```

all the files js and css files are in the head section of my document

```<code><link href="/spree/web/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/spree.css">
<script src="/spree/web/lib//angularjs/angular.min.js"></script>
<script src="/spree/web/lib/angularjs/angular-route.min.js"></script>
<script src="/spree/web/js/app.js"></script>
<script src="/spree/web/js/controller.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.js"></script>
</code>```

and this is how the start of the js looks like

```<code>angular.module('controller', ['ui.bootstrap'])
</code>```

when i preview i get this error in the console

Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=%24modalProvider%20%3C-%20%24modal%20%3C-%20login_ctrl

答:
You need to pass your controller's name as dependency in module.

angular.module('controller', ['login_ctrl','ui.bootstrap']);

Body:
I'm trying to open a dialog box in angularjs using bootstrap but whenever i try i get this error while injecting the right dependencies.

.controller('login_ctrl', ['$scope','$http','$window','$modal','$log', function($scope,$http,$window,$modal,$log) {

    var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',

            //size: size,
            resolve: {
                user: function() {
                    return userData;
                },
                selectedProducts: function() {
                    return userData.selectedProducts;
                },
                products: function () {
                    //console.log($scope.selectedProducts);
                    return $scope.products; // get all available products
                }
            }
        });

}])

all the files js and css files are in the head section of my document

<link href="/spree/web/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/spree.css">

and this is how the start of the js looks like

angular.module('controller', ['ui.bootstrap'])

when i preview i get this error in the console

Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=%24modalProvider%20%3C-%20%24modal%20%3C-%20login_ctrl