问:
Writing a large resultset to an .xlsx file using Apache POI and JDBC
I'm trying to write a large(Total no of rows can be up to 2 million) resultset to an .xlsx file.
To over come heap space or memory errors, I decided to fetch some limited set of records from table in each call and append the same to the file.
Those limited set of records are all ordered by rownum. AT each call to table I'm fetching 50K records and at last after all the records are being fetched from table appending the same to an .xlsx file.
At present I'm putting only 600000 records into each sheet. And my current logic is as below.

But the below logic takes lot of time for creating the .xlsx file. Is there anything which can be done to decrease the time??
And it also fails after creating second sheet.

```<code>    String query="select count(*) from employee";
    String actquery="";
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    conn = DriverManager.getConnection(jdbcURL,user,passwd);
    stmt = conn.createStatement();
    rs = stmt.executeQuery(query);
    stmt.setFetchSize(1000);
    int rowcounter;
    int increaseCount=50000;
    int jdbclimit=50000;//jdbc
    int excelrowlimit=600000;
    int excellimit=600000;
    int rownumStartCnt=0;
    int rownumEndCnt=0;
    if(rs.next()){
    outStream = new FileOutputStream("D:\\Test.xlsx",true);
    int count=rs.getInt(1);

    System.out.println("Total records"+count);
    if(count>0)
    {
    int sheets= count/excelrowlimit;
    if(count%excelrowlimit>0){
           sheets = sheets+1;
    }
    for(int scount=1;scount<=sheets;scount++){
    sheet =  workbook.createSheet("GapHistory-"+scount);
    rowcounter=1;
    System.out.println("Sheet:"+scount);
    System.out.println("limit is "+jdbclimit);
    while(rowcounter<excelrowlimit)
    {
    rownumStartCnt=rownumEndCnt+1;
    rownumEndCnt=jdbclimit;
    jdbclimit=jdbclimit+increaseCount;
    if(rownumEndCnt>excellimit){
           rownumEndCnt=excellimit;
    }
    if(rownumStartCnt>count){
     break;
    }
    PreparedStatement stmt2 = null;
    ResultSet rs2 =null;
    ResultSetMetaData rsmd=null;

    actquery=actquery+"SELECT * FROM (SELECT t.*, ROW_NUMBER() OVER (ORDER BY employee_number) rnum  FROM employee t) WHERE rnum BETWEEN ? and ?";
    stmt2 = conn.prepareStatement(actquery);
    stmt2.setInt(1,rownumStartCnt);
    stmt2.setInt(2,rownumEndCnt);
    rs2 = stmt2.executeQuery();
    System.out.println("Start row-->"+rownumStartCnt+"End row--->"+rownumEndCnt);
    rsmd = rs2.getMetaData();
    stmt2.setFetchSize(1000);
    rs2.setFetchDirection(ResultSet.FETCH_FORWARD);
    while(rs2.next())
    {

    if(rowcounter==1)
    {
           row = sheet.createRow(rowcounter);
           for(int i=1;i<=68;i++)
           {
            cell = row.createCell(i);
            cell.setCellValue(rsmd.getColumnName(i));

           }

    }
    rowcounter++;

    for(int i=1;i<=68;i++)
    {
           if(i==1)
           {
           row = sheet.createRow(rowcounter);
           }

           cell = row.createCell(i);
           cell.setCellValue(rs2.getString(i));

    }
    }
    actquery="";

                        }
 excellimit = excellimit+excelrowlimit;// Got rid with exception after adding this line
                        }
          }
    }
</code>```

答:
```<code>java.sql.SQLException: ORA-01000: maximum open cursors exceeded
</code>```

This means you are opening many ResultSets and not closing any of them. Eventually you run out of driver resources.  You must close each ResultSet when you are done with it.

And BTW, XLSX has a maximum row count of 2^20, or 1,048,576.  You cannot store 2 million rows in an XLSX worksheet.

Body:
I'm trying to write a large(Total no of rows can be up to 2 million) resultset to an .xlsx file.
To over come heap space or memory errors, I decided to fetch some limited set of records from table in each call and append the same to the file.
Those limited set of records are all ordered by rownum. AT each call to table I'm fetching 50K records and at last after all the records are being fetched from table appending the same to an .xlsx file.
At present I'm putting only 600000 records into each sheet. And my current logic is as below.

But the below logic takes lot of time for creating the .xlsx file. Is there anything which can be done to decrease the time??
And it also fails after creating second sheet.

    String query="select count(*) from employee";
    String actquery="";
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    conn = DriverManager.getConnection(jdbcURL,user,passwd);
    stmt = conn.createStatement();
    rs = stmt.executeQuery(query);
    stmt.setFetchSize(1000);
    int rowcounter;
    int increaseCount=50000;
    int jdbclimit=50000;//jdbc
    int excelrowlimit=600000;
    int excellimit=600000;
    int rownumStartCnt=0;
    int rownumEndCnt=0;
    if(rs.next()){
    outStream = new FileOutputStream("D:\\Test.xlsx",true);
    int count=rs.getInt(1);

    System.out.println("Total records"+count);
    if(count>0)
    {
    int sheets= count/excelrowlimit;
    if(count%excelrowlimit>0){
           sheets = sheets+1;
    }
    for(int scount=1;scount<=sheets;scount++){
    sheet =  workbook.createSheet("GapHistory-"+scount);
    rowcounter=1;
    System.out.println("Sheet:"+scount);
    System.out.println("limit is "+jdbclimit);
    while(rowcounter<excelrowlimit)
    {
    rownumStartCnt=rownumEndCnt+1;
    rownumEndCnt=jdbclimit;
    jdbclimit=jdbclimit+increaseCount;
    if(rownumEndCnt>excellimit){
           rownumEndCnt=excellimit;
    }
    if(rownumStartCnt>count){
     break;
    }
    PreparedStatement stmt2 = null;
    ResultSet rs2 =null;
    ResultSetMetaData rsmd=null;

    actquery=actquery+"SELECT * FROM (SELECT t.*, ROW_NUMBER() OVER (ORDER BY employee_number) rnum  FROM employee t) WHERE rnum BETWEEN ? and ?";
    stmt2 = conn.prepareStatement(actquery);
    stmt2.setInt(1,rownumStartCnt);
    stmt2.setInt(2,rownumEndCnt);
    rs2 = stmt2.executeQuery();
    System.out.println("Start row-->"+rownumStartCnt+"End row--->"+rownumEndCnt);
    rsmd = rs2.getMetaData();
    stmt2.setFetchSize(1000);
    rs2.setFetchDirection(ResultSet.FETCH_FORWARD);
    while(rs2.next())
    {

    if(rowcounter==1)
    {
           row = sheet.createRow(rowcounter);
           for(int i=1;i<=68;i++)
           {
            cell = row.createCell(i);
            cell.setCellValue(rsmd.getColumnName(i));

           }

    }
    rowcounter++;

    for(int i=1;i<=68;i++)
    {
           if(i==1)
           {
           row = sheet.createRow(rowcounter);
           }

           cell = row.createCell(i);
           cell.setCellValue(rs2.getString(i));

    }
    }
    actquery="";

                        }
 excellimit = excellimit+excelrowlimit;// Got rid with exception after adding this line
                        }
          }
    }

Body:
java.sql.SQLException: ORA-01000: maximum open cursors exceeded

This means you are opening many ResultSets and not closing any of them. Eventually you run out of driver resources.  You must close each ResultSet when you are done with it.

And BTW, XLSX has a maximum row count of 2^20, or 1,048,576.  You cannot store 2 million rows in an XLSX worksheet.


来源: stackexchange

问:
Access Denied Connecting to MySQL with PHP
I know there are a lot of threads asking this question already, but I have been at this for hours and am at wits end.  I am attempting to connect to a MySQL database that I am running of my MacBook with the following PHP:

```<code><?php
DEFINE('DB_USER', 'webuser');
DEFINE('DB_PASSWORD', 'thispassword');
DEFINE('DB_HOST', '127.0.0.1:3306');
DEFINE('DB_NAME', 'learning_accounts');

$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Error connecting: ' .
mysqli_connect_error()
);

?>
</code>```

That returns the following error:

```<code>Error connecting: Access denied for user 'webuser'@'localhost' (using password: YES)
</code>```

I can connect fine through the terminal, even trying to connect with PHP and root does not work.  I am new to both PHP and MySQL so any guidance and insight would be appreciated!

I have tried tons of solutions such as granting privileges, flushing privileges, creating new users, using PDO, nothing has been working - please help!

Thanks so much, I hate learning new languages because then I'm a lost fish when it comes to debugging at first!

Update

I have a password set for my root account, but changing the DB_PASSWORD variable to '' changes the error to: Error connecting: Unknown database 'learning_accounts'

Update 2
I have fixed the issue, check my answer to see how, if you are having this problem then I hope you found this thread quickly!

Zach L

答:
Try changing "DB_HOST" to "localhost".
If it did no solve the problem, then  reinstall your mysql server</p>

ContentLicense: CC BY-SA 3.0

Body:
I know there are a lot of threads asking this question already, but I have been at this for hours and am at wits end.  I am attempting to connect to a MySQL database that I am running of my MacBook with the following PHP:

<?php
DEFINE('DB_USER', 'webuser');
DEFINE('DB_PASSWORD', 'thispassword');
DEFINE('DB_HOST', '127.0.0.1:3306');
DEFINE('DB_NAME', 'learning_accounts');

$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Error connecting: ' .
mysqli_connect_error()
);

?>

That returns the following error:

Error connecting: Access denied for user 'webuser'@'localhost' (using password: YES)

I can connect fine through the terminal, even trying to connect with PHP and root does not work.  I am new to both PHP and MySQL so any guidance and insight would be appreciated!

I have tried tons of solutions such as granting privileges, flushing privileges, creating new users, using PDO, nothing has been working - please help!

Thanks so much, I hate learning new languages because then I'm a lost fish when it comes to debugging at first!

Update

I have a password set for my root account, but changing the DB_PASSWORD variable to '' changes the error to: Error connecting: Unknown database 'learning_accounts'

Update 2
I have fixed the issue, check my answer to see how, if you are having this problem then I hope you found this thread quickly!

Zach L


问:
Macro to export Excel Doc as PDF for all Users
I need to create a macro that will save an excel document as a PDF file to any user's desktop (i.e. multiple people will be using this document/macro).

Here is VBA code I have so far:

```<code>Sub CreatePDF()
'
' CreatePDF Macro
'

'
    ChDir "C:\Users\Public\Desktop"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\Users\Public\Desktop\QuickView Update Dec_2017.pdf", Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub
</code>```

I think the issue is with the directory it's saving to (in the instances where this code says "Public" in the file path, I had changed that from my username which was initially populated).

Does anyone know a way to specify a generic path to save this document as a PDF to any users' desktop?

答:
Use .specialfolders("Desktop") to save to the desktop. Set to a string variable and add the path separator

Example

```<code>Option Explicit
Sub CreatePDF()
    Dim FilePath As String

    FilePath = CreateObject("WScript.Shell").specialfolders("Desktop")

    Debug.Print FilePath

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                    FileName:=FilePath & "\" & "QuickView Update Dec_2017.pdf", _
                    Quality:=xlQualityStandard, _
                    IncludeDocProperties:=True, _
                    IgnorePrintAreas:=False, _
                    OpenAfterPublish:=True

End Sub
</code>```

The following special folders are available:

AllUsersDesktop

AllUsersStartMenu

AllUsersPrograms

AllUsersStartup

Desktop

Favorites

Fonts

MyDocuments

NetHood

PrintHood

Programs

Recent

SendTo

StartMenu

Startup

Templates

The SpecialFolders property returns an empty string if the requested folder (strFolderName) is not available. For example, Windows 95 does not have an AllUsersDesktop folder and returns an empty string if strFolderNameis AllUsersDesktop.

Here is another example
https://stackoverflow.com/a/31694603/4539709

Body:
I need to create a macro that will save an excel document as a PDF file to any user's desktop (i.e. multiple people will be using this document/macro).

Here is VBA code I have so far:

Sub CreatePDF()
'
' CreatePDF Macro
'

'
    ChDir "C:\Users\Public\Desktop"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\Users\Public\Desktop\QuickView Update Dec_2017.pdf", Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

I think the issue is with the directory it's saving to (in the instances where this code says "Public" in the file path, I had changed that from my username which was initially populated).

Does anyone know a way to specify a generic path to save this document as a PDF to any users' desktop?

Body:
Use .specialfolders("Desktop") to save to the desktop. Set to a string variable and add the path separator

Example

Option Explicit
Sub CreatePDF()
    Dim FilePath As String

    FilePath = CreateObject("WScript.Shell").specialfolders("Desktop")

    Debug.Print FilePath

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                    FileName:=FilePath & "\" & "QuickView Update Dec_2017.pdf", _
                    Quality:=xlQualityStandard, _
                    IncludeDocProperties:=True, _
                    IgnorePrintAreas:=False, _
                    OpenAfterPublish:=True

End Sub

The following special folders are available:

AllUsersDesktop

AllUsersStartMenu

AllUsersPrograms

AllUsersStartup

Desktop

Favorites

Fonts

MyDocuments

NetHood

PrintHood

Programs

Recent

SendTo

StartMenu

Startup

Templates

The SpecialFolders property returns an empty string if the requested folder (strFolderName) is not available. For example, Windows 95 does not have an AllUsersDesktop folder and returns an empty string if strFolderNameis AllUsersDesktop.

Here is another example
https://stackoverflow.com/a/31694603/4539709

ContentLicense: CC BY-SA 4.0


问:
Need help to extract a data with Label using XSLT
```<code><ws:Address_Line_Data ws:PriorValue="" ws:Label="Address Line 1" ws:Type="ADDRESS_LINE_1">8925 Lietner lWay</ws:Address_Line_Data>
<ws:Address_Line_Data ws:PriorValue="" ws:Label="Address Line " ws:Type="ADDRESS_LINE_2">#504</ws:Address_Line_Data>
</code>```

I have two feed for the address. I need the value only with "label Address Line 1" also I need to normalize the space.

答:
You can use the following</p>

```<code><xsl:value-of select="normalize-space(ws:Address_Line_Data[@ws:Label='Address Line 1'])" />
</code>```

Body:
<ws:Address_Line_Data ws:PriorValue="" ws:Label="Address Line 1" ws:Type="ADDRESS_LINE_1">8925 Lietner lWay</ws:Address_Line_Data>
<ws:Address_Line_Data ws:PriorValue="" ws:Label="Address Line " ws:Type="ADDRESS_LINE_2">#504</ws:Address_Line_Data>

I have two feed for the address. I need the value only with "label Address Line 1" also I need to normalize the space.

Body:
You can use the following

<xsl:value-of select="normalize-space(ws:Address_Line_Data[@ws:Label='Address Line 1'])" />


问:
How can I get the width of ExpandableListView's group indicator drawable on Android?
If I use the default group indicator (not setting a new one), how can I know the padding width for the layout of groupview?

So can let my layout won't overlap with the group indicator.

Is that possible? Because I can't find a method to getGroupIndicator.
Or I must have to set a new one that I know its size.

答:
I found the attribute here:</p>

```<code>android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
</code>```

Body:
I found the attribute here:

android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"


问:
How to retrieve data into textbox
MY VIEW::

```<code> foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
            {

 foreach (TSM.Models.TimeSheetData itemm in ViewBag.HoursData)
 {
 foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
                {

     <td><input class="txtTaskHours date@(Date.AddDays(i).ToString("MMddyyy"))"
                style="width:50px;" value="@itemm.Hours" type="number"
                id="@(itm.ID.ToString() + ':' + Date.AddDays(i).ToString("MMddyyy"))" />
     </td>
 }
</code>```

My Controller:

```<code>var query = (from ts in db.TimeSheets join tsd in db.TimesheetData on ts.ID
             equals tsd.TimeSheet.ID where ts.StartDate == thisWeekStart
             && ts.EndDate == thisWeekEnd select new{ tsd.Hours, tsd.Date, tsd.TaskID }).ToList();

ViewBag.HoursData = query;
return PartialView("~/Views/TimeSheet/_TimeSheet.cshtml", ViewBag);
</code>```

I want to show data into the Textbox. To show data, I am using ViewBag by using foreach loop to show hours in the Textbox.

My Textbox data is saved in json.
This is my json value :

```<code>"TaskHours" : [{
                 "ID":"f2886ec7-47d3-e711-9666-000c297c9306:12042017",
                 "Value":"25"
               }]
</code>```

I am getting this error:

```<code>   'Unable to cast object of type
  '<>f__AnonymousType9`3[System.Double,System.DateTime,System.Guid]' to type
  'TSM.Models.TimeSheetData'.
</code>```

答:
This is your code and pay attention to select new:

```<code>var query = (from ts in db.TimeSheets join tsd in db.TimesheetData on ts.ID
    equals tsd.TimeSheet.ID where ts.StartDate == thisWeekStart
    && ts.EndDate == thisWeekEnd
    select new{ tsd.Hours, tsd.Date, tsd.TaskID }).ToList();
</code>```

You are selecting a bunch of anonymous objects and then calling ToList() so you end up with a list of anonymous objects. Then you do this:

```<code>ViewBag.HoursData = query;
</code>```

So now ViewBag.HoursData has a list of anonymous types. Then you do this in the view:

```<code>foreach (TSM.Models.TimeSheetData itemm in ViewBag.HoursData)
</code>```

My question to you is this:

How do you expect the runtime to convert anonymous type to TimeSheetData? It cannot so it give you this clear error:

Unable to cast object of type<>f__AnonymousType9`3[System.Double,System.DateTime,System.Guid]' to type
  TSM.Models.TimeSheetData'.

Do yourself a big favor: I cannot see all your code but create a model specifically for your view and then put everything you need into it and pass it to your view. Some people call this View Model. Your code will be cleaner, easier to read and less buggy. Stop hacking your way by sending anonymous types, custom types and ViewBag and this and that. Even if it was to work, it will still look ugly. So go and create a model as shown in the link.

Title: How to retrieve data into textbox

Body:
MY VIEW::

 foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
            {

 foreach (TSM.Models.TimeSheetData itemm in ViewBag.HoursData)
 {
 foreach (TSM.Models.Tasks itm in lstTasks.Where(x => x.Project.ID == item.ID).ToList())
                {

     <input class="txtTaskHours date@(Date.AddDays(i).ToString("MMddyyy"))"
                style="width:50px;" value="@itemm.Hours" type="number"
                id="@(itm.ID.ToString() + ':' + Date.AddDays(i).ToString("MMddyyy"))" />

 }

My Controller:

var query = (from ts in db.TimeSheets join tsd in db.TimesheetData on ts.ID
             equals tsd.TimeSheet.ID where ts.StartDate == thisWeekStart
             && ts.EndDate == thisWeekEnd select new{ tsd.Hours, tsd.Date, tsd.TaskID }).ToList();

ViewBag.HoursData = query;
return PartialView("~/Views/TimeSheet/_TimeSheet.cshtml", ViewBag);

I want to show data into the Textbox. To show data, I am using ViewBag by using foreach loop to show hours in the Textbox.

My Textbox data is saved in json.
This is my json value :

"TaskHours" : [{
                 "ID":"f2886ec7-47d3-e711-9666-000c297c9306:12042017",
                 "Value":"25"
               }]

I am getting this error:

   'Unable to cast object of type
  '<>f__AnonymousType9`3[System.Double,System.DateTime,System.Guid]' to type
  'TSM.Models.TimeSheetData'.

Body:
This is your code and pay attention to select new:

var query = (from ts in db.TimeSheets join tsd in db.TimesheetData on ts.ID
    equals tsd.TimeSheet.ID where ts.StartDate == thisWeekStart
    && ts.EndDate == thisWeekEnd
    select new{ tsd.Hours, tsd.Date, tsd.TaskID }).ToList();

You are selecting a bunch of anonymous objects and then calling ToList() so you end up with a list of anonymous objects. Then you do this:

ViewBag.HoursData = query;

So now ViewBag.HoursData has a list of anonymous types. Then you do this in the view:

foreach (TSM.Models.TimeSheetData itemm in ViewBag.HoursData)

My question to you is this:

How do you expect the runtime to convert anonymous type to TimeSheetData? It cannot so it give you this clear error:

Unable to cast object of type<>f__AnonymousType9`3[System.Double,System.DateTime,System.Guid]' to type
  TSM.Models.TimeSheetData'.

Do yourself a big favor: I cannot see all your code but create a model specifically for your view and then put everything you need into it and pass it to your view. Some people call this View Model. Your code will be cleaner, easier to read and less buggy. Stop hacking your way by sending anonymous types, custom types and ViewBag and this and that. Even if it was to work, it will still look ugly. So go and create a model as shown in the link.


问:
Extend an axis limit to -1 when that axis is logarithmic in R
I am doing the following:

```<code>x = c(0, 1, 2, 3, 4, 5)
y = x ^ 2
plot(x, y, log="y")
</code>```

What I want is that the graph also show me the scatter point at (x, y)=(0, 0).

I know that log(0) = -Inf. This will be the case when I am doing log(x) but here I am not doing log(x). Rather, I am just changing the scale of y-axis to be logarithmic. Therefore, I need to know if there is some way for me to display the scatter point (x, y) = (0, 0) as well.

答:
No, what you are asking is mathematically impossible, because log(0) = -Inf. The point (0, 0) cannot be shown on a log-scale plot.

A log-scale is produced by log-transforming the data values and exponentiating the values at the axis ticks. For example, to plot the value 100 in a log-10 scale, you first log-transform 100 to log10(100) = 2, and then you transform the corresponding axis tick from 2 to 10^2 = 100. Thus, to plot the value 0 in a log-scale plot, you still need to calculate log10(0), even if the corresponding axis tick would be 10^-Inf = 0.

Body:
I am doing the following:

x = c(0, 1, 2, 3, 4, 5)
y = x ^ 2
plot(x, y, log="y")

What I want is that the graph also show me the scatter point at (x, y)=(0, 0).

I know that log(0) = -Inf. This will be the case when I am doing log(x) but here I am not doing log(x). Rather, I am just changing the scale of y-axis to be logarithmic. Therefore, I need to know if there is some way for me to display the scatter point (x, y) = (0, 0) as well.


问:
select products from specific category codeigniter
Products are available in following categories

```<code>product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5
</code>```

I want to select products of specific category e.g. all products from category 2. what will be sql syntax

答:
You can use FIND_IN_SET for seach in comma separated values.

```<code> $this->db->where("FIND_IN_SET( '$category_id' , category_ids) ");
</code>```

So your whole query be like

```<code>$this->db->select();
$this->db->from('table_name');
$this->db->where("FIND_IN_SET( '$category_id' , category_ids) ");
$query = $this->db->get();
return $query->result();
</code>```

Body:
Products are available in following categories

product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5

I want to select products of specific category e.g. all products from category 2. what will be sql syntax

Body:
You can use FIND_IN_SET for seach in comma separated values.

 $this->db->where("FIND_IN_SET( '$category_id' , category_ids) ");

So your whole query be like

$this->db->select();
$this->db->from('table_name');
$this->db->where("FIND_IN_SET( '$category_id' , category_ids) ");
$query = $this->db->get();
return $query->result();


答:
Just replace the predict() line in your code with this:

```<code>import numpy as np
model.predict(np.array(x[10], dtype=np.int32).reshape(1,-1))
</code>```

The error message says that you need to provide a 2-d array of X to predict() method.
Currently x[10] will give a single dimension array:

```<code>[1 2 3 4 5]
</code>```

But we need to do it like:

```<code>[[1 2 3 4 5]]
</code>```

So according to the hint in error message you can reshape the data to have 1 row and multiple columns. This is achieved by reshape(1,-1).

Or else as stated in the comments by @furas, just wrap your data into a list again like this:

```<code>model.predict([array(x[10])])
</code>```

Title: sklearn model and fit for a list

Body:
I have 2 arrays x and y which are :

x=    [['1', '2', '3', '4', '5'], ['3', '6', '9', '12', '24'],
       ['1', '2', '3', '4', '5'], ['3', '6', '9', '12', '24'],
       ['1', '2', '3', '4', '5'], ['3', '6', '9', '12', '24'],
       ['1', '2', '3', '4', '5'], ['3', '6', '9', '12', '24'],
       ['1', '2', '3', '4', '5'], ['3', '6', '9', '12', '24'],
       ['1', '2', '3', '4', '5'], ['3', '6', '9', '12', '24'],
       ['1', '2', '3', '4', '5'], ['3', '6', '9', '12', '24']]

y=    [['2', '4', '6', '8', '10\n'], ['6', '12', '18', '24', '48\n'],
       ['2', '4', '6', '8', '10\n'], ['6', '12', '18', '24', '48\n'],
       ['2', '4', '6', '8', '10\n'], ['6', '12', '18', '24', '48\n'],
       ['2', '4', '6', '8', '10\n'], ['6', '12', '18', '24', '48\n'],
       ['2', '4', '6', '8', '10\n'], ['6', '12', '18', '24', '48\n'],
       ['2', '4', '6', '8', '10\n'], ['6', '12', '18', '24', '48\n'],
       ['2', '4', '6', '8', '10\n'], ['6', '12', '18', '24', '48']]

trying to get the prediction by:

model.fit(array(x),array(y))

model.predict(array(x[10]))

getting Error:

Traceback (most recent call last):
  File "test.py", line 29, in <module>
    model.predict(array(x[10]))
  File "C:\U.....\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\linear_model\base.py", line 256, in predict
    return self._decision_function(X)
  File "C:\U....\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\linear_model\base.py", line 239, in _decision_function
    X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
  File "C:....\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\utils\validation.py", line 441, in check_array
    "if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=['1' '2' '3' '4' '5'].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1)

so I am looking for linear regression for a model where the input is a array and output is also array ..

can you please correct me what I am missing

Body:
Just replace the predict() line in your code with this:

import numpy as np
model.predict(np.array(x[10], dtype=np.int32).reshape(1,-1))

The error message says that you need to provide a 2-d array of X to predict() method.
Currently x[10] will give a single dimension array:

[1 2 3 4 5]

But we need to do it like:

[[1 2 3 4 5]]

So according to the hint in error message you can reshape the data to have 1 row and multiple columns. This is achieved by reshape(1,-1).

Or else as stated in the comments by @furas, just wrap your data into a list again like this:

model.predict([array(x[10])])


问:
how to use subtotal in SQL

I have a table with following data

```<code> CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110     1
  08   test2    0     0      0      1
  05   test3   10     0      0      2
  03   test4    0     0      0      2
</code>```

I want a query which give the following output.
(Subtotal according to FLAG)

```<code> CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110      1
  08   test2    0     0      0       1
 NULL SUBTOTAL 100    10    110    NULL
  05   test3   10     0      0       2
  03   test4    0     0      0       2
 NULL SUBTOTAL  10    0     10     NULL
TOTAL          110    10    120    NULL
</code>```

答:
Try this</p>

```<code>;with cte
as
(
 select
  CODE,
  NAME,
  AMOUNT,
  VAT,
  TOTALAMT,
  FLAG
  from t1

  union aLL

  select
  CODE=NULL,
  NAME='SUBTOTAL',
  AMOUNT = SUM(AMOUNT),
  VAT = SUM(VAT),
  TOTALAMT = SUM(TOTALAMT),
  FLAG
  from T1
  GROUP BY FLAG
)
SELECT
*
FROM CTE
ORDER BY FLAG,CODE DESC
</code>```

Title: how to use subtotal in SQL

Body:
I have a table with following data

 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110     1
  08   test2    0     0      0      1
  05   test3   10     0      0      2
  03   test4    0     0      0      2

I want a query which give the following output.
(Subtotal according to FLAG)

 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110      1
  08   test2    0     0      0       1
 NULL SUBTOTAL 100    10    110    NULL
  05   test3   10     0      0       2
  03   test4    0     0      0       2
 NULL SUBTOTAL  10    0     10     NULL
TOTAL          110    10    120    NULL

Body:
Try this

;with cte
as
(
 select
  CODE,
  NAME,
  AMOUNT,
  VAT,
  TOTALAMT,
  FLAG
  from t1

  union aLL

  select
  CODE=NULL,
  NAME='SUBTOTAL',
  AMOUNT = SUM(AMOUNT),
  VAT = SUM(VAT),
  TOTALAMT = SUM(TOTALAMT),
  FLAG
  from T1
  GROUP BY FLAG
)
SELECT
*
FROM CTE
ORDER BY FLAG,CODE DESC


问:
Why is that my $wpdb->delete value is FALSE, And won't execute properly?
I'm going to delete a row in a table using the $wpdb object

here's my code:

```<code>function delete_variation($variation_ID){
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = 'wp-posts';
    $wpdb->delete( $table_name , $where);
}
</code>```

every arguments are fine, I've got results.. But the

```<code>$wpdb->delete( $table_name , $where);
</code>```

returned FALSE and won't execute?

no errors has been found, everything seems okay, just that it returned FALSE.

Thanks!

答: Try wp_posts rather than wp-posts as your table name.

Body:
I'm going to delete a row in a table using the $wpdb object

here's my code:

function delete_variation($variation_ID){
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = 'wp-posts';
    $wpdb->delete( $table_name , $where);
}

every arguments are fine, I've got results.. But the

$wpdb->delete( $table_name , $where);

returned FALSE and won't execute?

no errors has been found, everything seems okay, just that it returned FALSE.

Thanks!


问:
SQL to return all records 18 months ahead of another date (to end of month)
I have a table with two DATETIME fields, OpeningDate and FinishingDate.

I am trying to write a query that returns all records that have a FinishingDate that is exactly 16 months ahead of the OpeningDate.

I have tried:

```<code>SELECT * FROM Sales
WHERE FinishingDate = DATEADD(MONTH, 16, OpeningDate)
</code>```

But it appears to give me all records that fall between those dates (only up to the day in the month), I need it to get all records up until the end of the month.

So lets say I have an OpeningDate of 2017-10-6 (year, month, day) 18 months ahead would be 2019-04-06. This will only include records up to the 6th of April, I need it to include records up until the end of April.

What modifications can I make to the query to achieve this?

Any help would be great.

Thanks!

答:
You can use this code,

```<code>SELECT * FROM Sales
WHERE FinishingDate between OpeningDate AND
DATEADD(MONTH, 18, EOMONTH(OpeningDate))
</code>```

Note :

```<code>DATEADD(MONTH, 18, EOMONTH(OpeningDate))
</code>```

EOMONTH find the end of the OpeningDate and then DATEADD will add 18 months to that date. That will give exactly the end date of 18th month from that date.

Body:
I have a table with two DATETIME fields, OpeningDate and FinishingDate.

I am trying to write a query that returns all records that have a FinishingDate that is exactly 16 months ahead of the OpeningDate.

I have tried:

SELECT * FROM Sales
WHERE FinishingDate = DATEADD(MONTH, 16, OpeningDate)

But it appears to give me all records that fall between those dates (only up to the day in the month), I need it to get all records up until the end of the month.

So lets say I have an OpeningDate of 2017-10-6 (year, month, day) 18 months ahead would be 2019-04-06. This will only include records up to the 6th of April, I need it to include records up until the end of April.

What modifications can I make to the query to achieve this?

Any help would be great.

Thanks!

Body:
You can use this code,

SELECT * FROM Sales
WHERE FinishingDate between OpeningDate AND
DATEADD(MONTH, 18, EOMONTH(OpeningDate))

Note :

DATEADD(MONTH, 18, EOMONTH(OpeningDate))

EOMONTH find the end of the OpeningDate and then DATEADD will add 18 months to that date. That will give exactly the end date of 18th month from that date.


问:
Aggregate function in mongodb
I have a db Data as follows

```<code>{
"_id" : ObjectId("5a2109572222085be93ef10d"),
"name" : "data1",
"date" : "2017-12-01T00:00.0Z",
"status" : "COMPLETED"},{
"_id" : ObjectId("5a2109572222085be93ef10d"),
"name" : "data1",
"date" : "2017-12-01T00:00.0Z",
"status" : "FAILED"}
</code>```

and I want an aggreagate output as follows

{ date:"2017-12-01T00:00:0Z", total:"2", completed:1, failed:1 }

I have tried this code but didn't produce the result as above

```<code>db.test.aggregate([
{$group: {_id : {date : '$date',status:'$status'}, total:{$sum :1}}},
{$project : {date : '$_id.date', status : '$_id.status', total : '$total', _id : 0}}
])
</code>```

答:
```<code>db.test.aggregate(

// Pipeline
[
    // Stage 1
    {
        $group: {
         _id:"$date",
         total:{$sum:1},
         failed:{$sum:{$cond:[{$eq:["$status","FAILED"]},1,0]}},
         completed:{$sum:{$cond:[{$eq:["$status","COMPLETED"]},1,0]}}
        }
    },

    // Stage 2
    {
        $project: {
            date : '$_id',
            total : 1,
            failed : 1,
            completed : 1,
            _id : 0,
        }
    },

]
);
</code>```

Title: Aggregate function in mongodb

Body:
I have a db Data as follows

{
"_id" : ObjectId("5a2109572222085be93ef10d"),
"name" : "data1",
"date" : "2017-12-01T00:00.0Z",
"status" : "COMPLETED"},{
"_id" : ObjectId("5a2109572222085be93ef10d"),
"name" : "data1",
"date" : "2017-12-01T00:00.0Z",
"status" : "FAILED"}

and I want an aggreagate output as follows

{ date:"2017-12-01T00:00:0Z", total:"2", completed:1, failed:1 }

I have tried this code but didn't produce the result as above

db.test.aggregate([
{$group: {_id : {date : '$date',status:'$status'}, total:{$sum :1}}},
{$project : {date : '$_id.date', status : '$_id.status', total : '$total', _id : 0}}
])


问:
When should we use Observer and Observable?
An interviewer asked me:

What is Observer and Observable and when should we use them?

I wasn't aware of these terms, so when I got back home and started Googling about Observer and Observable, I found some points from different resources:

1) Observable is a class and Observer is an interface.

2) The Observable class maintains a list of Observers.

3) When an Observable object is updated, it invokes the update() method of each of its Observers to notify that, it is changed.

I found this example:

```<code>import java.util.Observable;
import java.util.Observer;

class MessageBoard extends Observable
{
    public void changeMessage(String message)
    {
        setChanged();
        notifyObservers(message);
    }
}

class Student implements Observer
{
    @Override
    public void update(Observable o, Object arg)
    {
        System.out.println("Message board changed: " + arg);
    }
}

public class MessageBoardTest
{
    public static void main(String[] args)
    {
        MessageBoard board = new MessageBoard();
        Student bob = new Student();
        Student joe = new Student();
        board.addObserver(bob);
        board.addObserver(joe);
        board.changeMessage("More Homework!");
    }
}
</code>```

But I don't understand why we need Observer and Observable? What are the setChanged() and notifyObservers(message) methods for?

答:
Since Java9, both interfaces are deprecated, meaning you should not use them anymore. See Observer is deprecated in Java 9. What should we use instead of it?

However, you might still get interview questions about them...

Body:
An interviewer asked me:

What is Observer and Observable and when should we use them?

I wasn't aware of these terms, so when I got back home and started Googling about Observer and Observable, I found some points from different resources:

1) Observable is a class and Observer is an interface.

2) The Observable class maintains a list of Observers.

3) When an Observable object is updated, it invokes the update() method of each of its Observers to notify that, it is changed.

I found this example:

import java.util.Observable;
import java.util.Observer;

class MessageBoard extends Observable
{
    public void changeMessage(String message)
    {
        setChanged();
        notifyObservers(message);
    }
}

class Student implements Observer
{
    @Override
    public void update(Observable o, Object arg)
    {
        System.out.println("Message board changed: " + arg);
    }
}

public class MessageBoardTest
{
    public static void main(String[] args)
    {
        MessageBoard board = new MessageBoard();
        Student bob = new Student();
        Student joe = new Student();
        board.addObserver(bob);
        board.addObserver(joe);
        board.changeMessage("More Homework!");
    }
}

But I don't understand why we need Observer and Observable? What are the setChanged() and notifyObservers(message) methods for?


问:
Polymer v2.0: how to write reusable mixin code
Lets say I want to write set of mixins. As I understand it, each mixin should provide some piece of functionality and don't affect or rely any other mixins (except when it extends another mixin directly).

So i write something like this:

```<code>const MixinA = superClass => class extends superClass {
  connectedCallback() {
    this.addEventListener('click', this.handleClick_);
  }

  /**
   * @return {Array.<string>}
   */
  static get observers() {
    return [
      'handleMyPropChange_(myProp)',
    ];
  }
}
</code>```

Then I add something like this:

```<code>const MixinB = superClass => class extends superClass {
  /**
   * @return {Array.<string>}
   */
  static get observers() {
    return [
      'handleMyPropChange_(myProp)',
    ];
  }
}
</code>```

If i apply both of this mixins to same element, then one of handleMyPropChange_ will be hidden and second will be triggered two times.

Same problem is possible with and handleClick_ in this example.

There were no such problem with Polymer v1 behaviors.

The only way i've found is to add some mixin specific prefix to each private class member to give them unique names, but it looks not very handyю What is the best option to handle this problem?

答:
In Polymer 2, you are extending a class. This means that only there can only be one function of any given name. You are basically overriding the previously defined function with the latest. The function is firing twice because each mixin is registering an observer, these don't de-dupe.

If the function is the same logically, I would abstract it out. If they are different logically I would provide different more clear names based on what the function is doing.

Body:
Lets say I want to write set of mixins. As I understand it, each mixin should provide some piece of functionality and don't affect or rely any other mixins (except when it extends another mixin directly).

So i write something like this:

const MixinA = superClass => class extends superClass {
  connectedCallback() {
    this.addEventListener('click', this.handleClick_);
  }

  /**
   * @return {Array.<string>}
   */
  static get observers() {
    return [
      'handleMyPropChange_(myProp)',
    ];
  }
}

Then I add something like this:

const MixinB = superClass => class extends superClass {
  /**
   * @return {Array.<string>}
   */
  static get observers() {
    return [
      'handleMyPropChange_(myProp)',
    ];
  }
}

If i apply both of this mixins to same element, then one of handleMyPropChange_ will be hidden and second will be triggered two times.

Same problem is possible with and handleClick_ in this example.

There were no such problem with Polymer v1 behaviors.

The only way i've found is to add some mixin specific prefix to each private class member to give them unique names, but it looks not very handyю What is the best option to handle this problem?


问:
Exception from sub books id dMBTck6CaSupWbEna TypeError: Cannot read property ‘emails’ of null
I am getting an Exception whenever a user logged in into his account, and I cant see the collection data until the page is been refreshed… **[but I am not getting any exception if I use it like

```<code>Books.find({“customer_name”:this.userId);
</code>```

instead of

```<code>Books.find({“customer_name”:Meteor.user().emails[0].address);
</code>```

and I don't need that step because in my app users collection finding should be based on their email id, not by userId…]**
my code is shown below :
Someone, please help me out:frowning_face:

server - main.js:

```<code>var My_collection;
Meteor.publish(‘books’, function() {
My_collection =
Books.find({“customer_name”:Meteor.user().emails[0].address);
return My_collection;
</code>```

client -main.js:

```<code>Template.viewBooks.helpers({
books() {
return Books.find({}, { sort: { books_order: -1 } }).fetch();
},
});
</code>```

client - main.html

```<code>{{#each books}}
{{books_id}}
{{/each}}
</code>```

ERROR:

App running at: http://localhost:3000/ I20171205-16:06:49.773(5.5)?
  Exception from sub transactions id wQ9DpjjABEiPzMZ9P TypeError: Cannot
  read property ‘emails’ of null I20171205-16:06:49.872(5.5)? at
  Subscription._handler (server/main.js:16:75)
  I20171205-16:06:49.873(5.5)? at maybeAuditArgumentChecks
  (packages/ddp-server/livedata_server.js:1768:12)
  I20171205-16:06:49.873(5.5)? at
  DDP.CurrentPublicationInvocation.withValue
  (packages/ddp-server/livedata_server.js:1043:15)
  I20171205-16:06:49.873(5.5)? at
  Meteor.EnvironmentVariable.EVp.withValue (packages/meteor.js:1134:15)
  I20171205-16:06:49.873(5.5)? at Subscription.runHandler
  (packages/ddp-server/livedata_server.js:1041:51)
  I20171205-16:06:49.873(5.5)? at
  packages/ddp-server/livedata_server.js:826:41
  I20171205-16:06:49.874(5.5)? at Function..each..forEach
  (packages/underscore.js:147:22) I20171205-16:06:49.874(5.5)? at
  packages/ddp-server/livedata_server.js:822:9
  I20171205-16:06:49.874(5.5)? at
  Meteor.EnvironmentVariable.EVp.withValue (packages/meteor.js:1134:15)
  I20171205-16:06:49.874(5.5)? at Session._setUserId
  (packages/ddp-server/livedata_server.js:816:34)

答:
It’s generally bad practice to use Meteor.user() on the server. Without having enough information surrounding how you’re publishing and subscribing to your collections, and since you’re saying you aren’t getting any errors when you use this.userId, you can find the email address the following way:

```<code>var currentUser = Meteor.users.findOne(this.userId);
var userEmail = currentUser.emails[0].address;
</code>```

Then use it in Books.find

If you can provide more information about the subscription and the publication, i’d be able to help out more

Body:
I am getting an Exception whenever a user logged in into his account, and I cant see the collection data until the page is been refreshed… **[but I am not getting any exception if I use it like

Books.find({“customer_name”:this.userId);

instead of

Books.find({“customer_name”:Meteor.user().emails[0].address);

and I don't need that step because in my app users collection finding should be based on their email id, not by userId…]**
my code is shown below :
Someone, please help me out:frowning_face:

server - main.js:

var My_collection;
Meteor.publish(‘books’, function() {
My_collection =
Books.find({“customer_name”:Meteor.user().emails[0].address);
return My_collection;

client -main.js:

Template.viewBooks.helpers({
books() {
return Books.find({}, { sort: { books_order: -1 } }).fetch();
},
});

client - main.html

{{#each books}}
{{books_id}}
{{/each}}

ERROR:

App running at: http://localhost:3000/ I20171205-16:06:49.773(5.5)?
  Exception from sub transactions id wQ9DpjjABEiPzMZ9P TypeError: Cannot
  read property ‘emails’ of null I20171205-16:06:49.872(5.5)? at
  Subscription._handler (server/main.js:16:75)
  I20171205-16:06:49.873(5.5)? at maybeAuditArgumentChecks
  (packages/ddp-server/livedata_server.js:1768:12)
  I20171205-16:06:49.873(5.5)? at
  DDP.CurrentPublicationInvocation.withValue
  (packages/ddp-server/livedata_server.js:1043:15)
  I20171205-16:06:49.873(5.5)? at
  Meteor.EnvironmentVariable.EVp.withValue (packages/meteor.js:1134:15)
  I20171205-16:06:49.873(5.5)? at Subscription.runHandler
  (packages/ddp-server/livedata_server.js:1041:51)
  I20171205-16:06:49.873(5.5)? at
  packages/ddp-server/livedata_server.js:826:41
  I20171205-16:06:49.874(5.5)? at Function..each..forEach
  (packages/underscore.js:147:22) I20171205-16:06:49.874(5.5)? at
  packages/ddp-server/livedata_server.js:822:9
  I20171205-16:06:49.874(5.5)? at
  Meteor.EnvironmentVariable.EVp.withValue (packages/meteor.js:1134:15)
  I20171205-16:06:49.874(5.5)? at Session._setUserId
  (packages/ddp-server/livedata_server.js:816:34)

Body:
It’s generally bad practice to use Meteor.user() on the server. Without having enough information surrounding how you’re publishing and subscribing to your collections, and since you’re saying you aren’t getting any errors when you use this.userId, you can find the email address the following way:

var currentUser = Meteor.users.findOne(this.userId);
var userEmail = currentUser.emails[0].address;

Then use it in Books.find

If you can provide more information about the subscription and the publication, i’d be able to help out more


问:
Append table data from controller in blade through ajax
My table is designed for the controller, I want to append this table to the table in the blade of laravel.

This is my table in controller:

```<code>        $subLaws='';
          $n=1;
          foreach($sublaw as $sLaw)
          {
             $govt_no='';
             $eventType='';
             $status='Inactive';
             $url=url('admin/sublawmaster/'.$sLaw->id);
             $lmsid=$sLaw->lms_id;
             $view_url=url('admin/sublawmaster/view/' .$sLaw->id);
             if($sLaw->status=='1'){$status='Active';}
             $subLaws .= '<tr class="odd">
                          <td></td>
                          <td><a href="'.$view_url.'">'.$lmsid.'</a></td>
                          <td>'.$sLaw->sub_law_name.'</td>
                          <td>'.$eventType.'</td>
                          <td><span class="label label-success
 btn_status">'.$status.'</span></td>
           $n++;
    }
           return json_encode($subLaws);
</code>```

this is my ajax code:

```<code>$.ajax({
                type: 'GET',
                dataType: "json",
                data: {law_id:id},
                url: "{{ URL::to('admin/postlawid/') }}",
                success: function (data) {

                }
            });
</code>```

this is my table in blade file:

```<code><table class="table table-striped table-bordered table-hover" id="sublawmasterdata">
<thead>
            <tr id="header">
            <th align="center" width="80" style="text-align:center;">S NO</th>
                 <th>LMS ID</th>
                 <th>LMS Name</th>
                 <th>LMS Type</th>
                 <th>Status</th>
                 <th>Action</th>
             </tr>
             </thead>
             <tbody>

             </tbody>
            </table>
</code>```

I have a dropdown when the value is selected from this dropdown the table in the controller should get appended to the table in blade file.
how should I append the table in the controller to the table in blade file?

答:
You may replace table content like as following.</p>

```<code>$.ajax({
     type: 'GET',
     dataType: "json",
     data: {law_id:id},
     url: "{{ URL::to('admin/postlawid/') }}",
     success: function (data) {
         $("#sublawmasterdata tbody").innerHtml(data.table_html);
     }
});
</code>```

Body:
My table is designed for the controller, I want to append this table to the table in the blade of laravel.

This is my table in controller:

        $subLaws='';
          $n=1;
          foreach($sublaw as $sLaw)
          {
             $govt_no='';
             $eventType='';
             $status='Inactive';
             $url=url('admin/sublawmaster/'.$sLaw->id);
             $lmsid=$sLaw->lms_id;
             $view_url=url('admin/sublawmaster/view/' .$sLaw->id);
             if($sLaw->status=='1'){$status='Active';}
             $subLaws .= '

                          '.$lmsid.'
                          '.$sLaw->sub_law_name.'
                          '.$eventType.'
                          '.$status.'
           $n++;
    }
           return json_encode($subLaws);

this is my ajax code:

$.ajax({
                type: 'GET',
                dataType: "json",
                data: {law_id:id},
                url: "{{ URL::to('admin/postlawid/') }}",
                success: function (data) {

                }
            });

this is my table in blade file:

            S NO
                 LMS ID
                 LMS Name
                 LMS Type
                 Status
                 Action

I have a dropdown when the value is selected from this dropdown the table in the controller should get appended to the table in blade file.
how should I append the table in the controller to the table in blade file?

Body:
You may replace table content like as following.

$.ajax({
     type: 'GET',
     dataType: "json",
     data: {law_id:id},
     url: "{{ URL::to('admin/postlawid/') }}",
     success: function (data) {
         $("#sublawmasterdata tbody").innerHtml(data.table_html);
     }
});


问:
Why is my output equaling zero? (student)
I am a student in my first year of CIS courses, so I am a begineer. We are supposed to get input from a text file with an employee, the employee's department, hourly salary, and hours worked in given week, that looks like:

```<code>EID001, 1, 10.00, 40
EID002, 2, 10.50, 35
EID003, 3, 11.00, 30
EID004, 4, 11.50, 25
EID005, 5, 12.00, 20
EID006, 6, 12.50, 40
EID007, 7, 11.00, 25
.
.
.
(Employee ID, Department, Hourly Salary, Hours Worked)
</code>```

Then separate each field into elements of an array, validate each field, and calculate the total gross pay (Hourly Salary * Hours Worked) for each of the 7 departments.

My code:

```<code>    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Project_3_rev
{
    class Program
    {
        const int DEPARTMENTS = 7;
        const int FIELDS = 4;
        static void Main(string[] args)
        {
            FileStream fStream = new FileStream("project3data.txt", FileMode.Open, FileAccess.Read);
            StreamReader inFile = new StreamReader(fStream);
            string input = "";
            string[] fields = new string[FIELDS];
            string employee = "";
            int department = 0;
            double salary = 0.00;
            int hours = 0;

            double totalSalary = 0.00;
            int totalHours = 0;
            double[] grossPayArray = new double[DEPARTMENTS];

            input = inFile.ReadLine();
            while(input != null)
            {
                fields = input.Split(',');

                checkEmployee(input, fields, employee);
                checkDepartment(input, fields, department);

                for(int x = 1; x <= DEPARTMENTS; x++)
                {
                    totalSalary = 0.00;
                    totalHours = 0;
                    while (department == x)
                    {

                        checkSalary(input, fields, salary, department, totalSalary);
                        checkHours(input, fields, hours, department, totalHours);
                        grossPayArray[x - 1] = totalSalary * totalHours;
                    }
                }

                input = inFile.ReadLine();
            }

            displayOutput(grossPayArray);

        }

        static void checkEmployee(string inp, string[] fieldsArray, string emp)
        {
            if(fieldsArray[0] == null)
                Console.WriteLine("An Employee ID is invalid.");
        }

        static void checkDepartment(string inp, string[] fieldsArray, int dept)
        {
            if((!int.TryParse(fieldsArray[1], out dept)) || dept < 0 || dept > DEPARTMENTS)
            {
                Console.WriteLine("Department field is invalid: " + fieldsArray[1]);
            }

        }

        static void checkSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
        {

                    if ((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
                        totSal = totSal * sal;
                    else
                        Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);

        }

        static void checkHours(string inp, string[] fieldsArray, int hrs, int dept, int totHrs)
        {

                    if ((int.TryParse(fieldsArray[3], out hrs)) && hrs >= 0)
                        totHrs = totHrs * hrs;

                    else
                        Console.WriteLine("Hours field is invalid: " +  fieldsArray[3]);

        }

        static void displayOutput(double[] grossArray)
        {
            for(int x = 1; x <= DEPARTMENTS; x++)
            {
                Console.WriteLine("Department " + x + ": Gross Pay = " + grossArray[x-1]);
            }
        }

    }
}
</code>```

My output:

```<code>Department 1: Gross Pay = 0
Department 2: Gross Pay = 0
Department 3: Gross Pay = 0
Department 4: Gross Pay = 0
Department 5: Gross Pay = 0
Department 6: Gross Pay = 0
Department 7: Gross Pay = 0
</code>```

Why are the Gross Pays equaling zero?

Please keep in mind that I am in my first year of computer science. I am only allowed to use what we have learned and I only know the basics. Please cut me a little slack if this code is messy or my logic is way off. Thanks ahead of time.

答:
This type of question might be better in the Code Review section of StackExchange.

Nonetheless, for your reference later in the year, here's an example solution using classes and LINQ:

To run:

var app = new App_DepartmentPay();
app.Run();

Output:

```<code>using System;
using System.IO;
using System.Linq;

namespace StackOverflow
{
    public class App_DepartmentPay
    {
        public void Run()
        {
            var lines = File.ReadAllLines(@"d:\temp\payments.txt");

            var payStubs = lines.Select(l => new PayStub(l)).ToList();

            var departmentTotals = payStubs.GroupBy(p => p.Department).Select(g => new DepartmentTotal(g.Key, g.Sum(w => w.Pay))).ToList();

            departmentTotals.ForEach(t => Console.WriteLine(t.ToString()));
        }
    }

    public class PayStub
    {
        public string EmployeeId { get; private set; }

        public int Department { get; private set; }

        public decimal HourlyWage { get; private set; }

        public decimal HoursWorked { get; private set; }

        public decimal Pay
        {
            get
            {
                return HourlyWage * HoursWorked;
            }
        }

        public PayStub(string payLine)
        {
            var contents = payLine.Split(',');

            EmployeeId = contents[0];

            Department = int.Parse(contents[1]);

            HourlyWage = decimal.Parse(contents[2]);

            HoursWorked = decimal.Parse(contents[3]);
        }
    }

    public class DepartmentTotal
    {
        public int Department { get; set; }

        public decimal TotalPay { get;  set; }

        public DepartmentTotal(int department, decimal pay)
        {
            Department = department;
            TotalPay = pay;
        }

        public override string ToString()
        {
            return $"Department: {Department} \tGross Pay: {TotalPay}";
        }
    }
}
</code>```

Body:
I am a student in my first year of CIS courses, so I am a begineer. We are supposed to get input from a text file with an employee, the employee's department, hourly salary, and hours worked in given week, that looks like:

EID001, 1, 10.00, 40
EID002, 2, 10.50, 35
EID003, 3, 11.00, 30
EID004, 4, 11.50, 25
EID005, 5, 12.00, 20
EID006, 6, 12.50, 40
EID007, 7, 11.00, 25
.
.
.
(Employee ID, Department, Hourly Salary, Hours Worked)

Then separate each field into elements of an array, validate each field, and calculate the total gross pay (Hourly Salary * Hours Worked) for each of the 7 departments.

My code:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Project_3_rev
{
    class Program
    {
        const int DEPARTMENTS = 7;
        const int FIELDS = 4;
        static void Main(string[] args)
        {
            FileStream fStream = new FileStream("project3data.txt", FileMode.Open, FileAccess.Read);
            StreamReader inFile = new StreamReader(fStream);
            string input = "";
            string[] fields = new string[FIELDS];
            string employee = "";
            int department = 0;
            double salary = 0.00;
            int hours = 0;

            double totalSalary = 0.00;
            int totalHours = 0;
            double[] grossPayArray = new double[DEPARTMENTS];

            input = inFile.ReadLine();
            while(input != null)
            {
                fields = input.Split(',');

                checkEmployee(input, fields, employee);
                checkDepartment(input, fields, department);

                for(int x = 1; x <= DEPARTMENTS; x++)
                {
                    totalSalary = 0.00;
                    totalHours = 0;
                    while (department == x)
                    {

                        checkSalary(input, fields, salary, department, totalSalary);
                        checkHours(input, fields, hours, department, totalHours);
                        grossPayArray[x - 1] = totalSalary * totalHours;
                    }
                }

                input = inFile.ReadLine();
            }

            displayOutput(grossPayArray);

        }

        static void checkEmployee(string inp, string[] fieldsArray, string emp)
        {
            if(fieldsArray[0] == null)
                Console.WriteLine("An Employee ID is invalid.");
        }

        static void checkDepartment(string inp, string[] fieldsArray, int dept)
        {
            if((!int.TryParse(fieldsArray[1], out dept)) || dept < 0 || dept > DEPARTMENTS)
            {
                Console.WriteLine("Department field is invalid: " + fieldsArray[1]);
            }

        }

        static void checkSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
        {

                    if ((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
                        totSal = totSal * sal;
                    else
                        Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);

        }

        static void checkHours(string inp, string[] fieldsArray, int hrs, int dept, int totHrs)
        {

                    if ((int.TryParse(fieldsArray[3], out hrs)) && hrs >= 0)
                        totHrs = totHrs * hrs;

                    else
                        Console.WriteLine("Hours field is invalid: " +  fieldsArray[3]);

        }

        static void displayOutput(double[] grossArray)
        {
            for(int x = 1; x <= DEPARTMENTS; x++)
            {
                Console.WriteLine("Department " + x + ": Gross Pay = " + grossArray[x-1]);
            }
        }

    }
}

My output:

Department 1: Gross Pay = 0
Department 2: Gross Pay = 0
Department 3: Gross Pay = 0
Department 4: Gross Pay = 0
Department 5: Gross Pay = 0
Department 6: Gross Pay = 0
Department 7: Gross Pay = 0

Why are the Gross Pays equaling zero?

Please keep in mind that I am in my first year of computer science. I am only allowed to use what we have learned and I only know the basics. Please cut me a little slack if this code is messy or my logic is way off. Thanks ahead of time.

Body:
This type of question might be better in the Code Review section of StackExchange.

Nonetheless, for your reference later in the year, here's an example solution using classes and LINQ:

To run:

var app = new App_DepartmentPay();
app.Run();

Output:

using System;
using System.IO;
using System.Linq;

namespace StackOverflow
{
    public class App_DepartmentPay
    {
        public void Run()
        {
            var lines = File.ReadAllLines(@"d:\temp\payments.txt");

            var payStubs = lines.Select(l => new PayStub(l)).ToList();

            var departmentTotals = payStubs.GroupBy(p => p.Department).Select(g => new DepartmentTotal(g.Key, g.Sum(w => w.Pay))).ToList();

            departmentTotals.ForEach(t => Console.WriteLine(t.ToString()));
        }
    }

    public class PayStub
    {
        public string EmployeeId { get; private set; }

        public int Department { get; private set; }

        public decimal HourlyWage { get; private set; }

        public decimal HoursWorked { get; private set; }

        public decimal Pay
        {
            get
            {
                return HourlyWage * HoursWorked;
            }
        }

        public PayStub(string payLine)
        {
            var contents = payLine.Split(',');

            EmployeeId = contents[0];

            Department = int.Parse(contents[1]);

            HourlyWage = decimal.Parse(contents[2]);

            HoursWorked = decimal.Parse(contents[3]);
        }
    }

    public class DepartmentTotal
    {
        public int Department { get; set; }

        public decimal TotalPay { get;  set; }

        public DepartmentTotal(int department, decimal pay)
        {
            Department = department;
            TotalPay = pay;
        }

        public override string ToString()
        {
            return $"Department: {Department} \tGross Pay: {TotalPay}";
        }
    }
}


问:
PyTorch reshape tensor dimension
I want to reshape a vector of shape (5,) into a matrix of shape (1, 5).

With numpy, I can do:

```<code>>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5])
>>> a.shape
(5,)
>>> a = np.reshape(a, (1, 5))
>>> a.shape
(1, 5)
>>> a
array([[1, 2, 3, 4, 5]])
</code>```

But how do I do this with PyTorch?

答:
For in-place modification of the shape of the tensor, you should use
 tensor.resize_():

```<code>In [23]: a = torch.Tensor([1, 2, 3, 4, 5])

In [24]: a.shape
Out[24]: torch.Size([5])

# tensor.resize_((`new_shape`))
In [25]: a.resize_((1,5))
Out[25]:

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

In [26]: a.shape
Out[26]: torch.Size([1, 5])
</code>```

In PyTorch, if there's an underscore at the end of an operation (like tensor.resize_()) then that operation does in-place modification to the original tensor.

Also, you can simply use np.newaxis in a torch Tensor to increase the dimension. Here is an example:

```<code>In [34]: list_ = range(5)
In [35]: a = torch.Tensor(list_)
In [36]: a.shape
Out[36]: torch.Size([5])

In [37]: new_a = a[np.newaxis, :]
In [38]: new_a.shape
Out[38]: torch.Size([1, 5])
</code>```

Title: PyTorch reshape tensor dimension

Body:
I want to reshape a vector of shape (5,) into a matrix of shape (1, 5).

With numpy, I can do:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5])
>>> a.shape
(5,)
>>> a = np.reshape(a, (1, 5))
>>> a.shape
(1, 5)
>>> a
array([[1, 2, 3, 4, 5]])

But how do I do this with PyTorch?

Body:
For in-place modification of the shape of the tensor, you should use
 tensor.resize_():

In [23]: a = torch.Tensor([1, 2, 3, 4, 5])

In [24]: a.shape
Out[24]: torch.Size([5])

# tensor.resize_((`new_shape`))
In [25]: a.resize_((1,5))
Out[25]:

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

In [26]: a.shape
Out[26]: torch.Size([1, 5])

In PyTorch, if there's an underscore at the end of an operation (like tensor.resize_()) then that operation does in-place modification to the original tensor.

Also, you can simply use np.newaxis in a torch Tensor to increase the dimension. Here is an example:

In [34]: list_ = range(5)
In [35]: a = torch.Tensor(list_)
In [36]: a.shape
Out[36]: torch.Size([5])

In [37]: new_a = a[np.newaxis, :]
In [38]: new_a.shape
Out[38]: torch.Size([1, 5])


问:
Vuforia and Unity multi scene
I have to make an augmented reality book app using Vuforia and Unity. My Android apps size is 108mb. It's not working with 1GB RAM devices. I want to split the scene into different scenes and load the corresponding scene when a specific image target is found.

Main problem is, that one scene load is huge*. So I need to split the scene and load each scene when an image target is found.

*Editors Note: I don't know wether he means huge perfomance-wise or storage size. Latter means, that he apparently wants to load the scene in runtime from another location.

答:
You need to know the names of each of the image target prefabs  -</p>

```<code>using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class loadNewScene : MonoBehaviour, ITrackableEventHandler {

    private TrackableBehaviour mTrackableBehaviour;

    void Start () {
        mTrackableBehaviour = GetComponent<TrackableBehaviour>();
        if (mTrackableBehaviour)
        {
            mTrackableBehaviour.RegisterTrackableEventHandler(this);
        }
    }

    public void OnTrackableStateChanged(
                                    TrackableBehaviour.Status previousStatus,
                                    TrackableBehaviour.Status newStatus)
    {
        if (newStatus == TrackableBehaviour.Status.DETECTED ||
            newStatus == TrackableBehaviour.Status.TRACKED)
        {
            switch( mTrackableBehaviour.TrackableName ){
                case "Railway" :
                Application.LoadLevel( "rail" );
                break;

                case "Tree" :
                Application.LoadLevel( "tree" );
                break;
            }
        }
    }

}
</code>```

Title: Vuforia and Unity multi scene

Body:
You need to know the names of each of the image target prefabs  -

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class loadNewScene : MonoBehaviour, ITrackableEventHandler {

    private TrackableBehaviour mTrackableBehaviour;

    void Start () {
        mTrackableBehaviour = GetComponent<TrackableBehaviour>();
        if (mTrackableBehaviour)
        {
            mTrackableBehaviour.RegisterTrackableEventHandler(this);
        }
    }

    public void OnTrackableStateChanged(
                                    TrackableBehaviour.Status previousStatus,
                                    TrackableBehaviour.Status newStatus)
    {
        if (newStatus == TrackableBehaviour.Status.DETECTED ||
            newStatus == TrackableBehaviour.Status.TRACKED)
        {
            switch( mTrackableBehaviour.TrackableName ){
                case "Railway" :
                Application.LoadLevel( "rail" );
                break;

                case "Tree" :
                Application.LoadLevel( "tree" );
                break;
            }
        }
    }

}


问:
where the build happens in Jenkins and how we can reduce build time?
Where does the build happen? I know it is triggered by Jenkins, but what physical location is the compilation and packaging executed at?</p>

答:
By default jenkins home directory is ~/.jenkins , that can also be changed by setting JENKINS_HOME.

To understand jenkins directory structure refer below link

https://wiki.jenkins.io/display/JENKINS/Administering+Jenkins


问:
How can I change column comments in existing Hive table without including new column name and type?
I want to change the column comments on an existing hive table using hive 0.13. This works:

create table test (mycolumn int);
alter table test change mycolumn mycolumn int comment 'hello';

But I can't find a way to do this without repeating the name of the column and the type, both of which are irrelevant to the change. For example:

alter table test change mycolumn comment 'hello'; leads to an error.

If this was for one column it would not be a big deal but I want to do this for large numbers of columns in tables that were not commented. I know this could be done with a script that simply copies the column name and its type but would be nice to know if there were something simpler. Thanks

答:
ALTER TABLE test_change CHANGE a1 a1 INT COMMENT 'this is column a1';
```


问:
MPAndroidChart line graph remove only top border android
I am using MPAndroidChart for line graph. I have some 5 points. Below is my code.

```<code> LineChart lineChart = (LineChart) findViewById(R.id.chart);
    lineChart.setDrawBorders(true);
    lineChart.getDescription().setEnabled(false);
    lineChart.fitScreen();
    lineChart.setPadding(0,0,0,0);
    lineChart.getLegend().setEnabled(false);
    lineChart.setDoubleTapToZoomEnabled(false);

    lineChart.getAxisLeft().setEnabled(false);
    lineChart.getAxisRight().setEnabled(true);
    lineChart.getAxisLeft().setStartAtZero(true);

    lineChart.getAxisRight().setDrawAxisLine(true);
    lineChart.getAxisRight().setDrawLabels(true);
    lineChart.getAxisRight().setDrawGridLines(false);

    lineChart.getXAxis().setEnabled(true);
    lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

    lineChart.getXAxis().setDrawAxisLine(true);
    lineChart.getXAxis().setDrawGridLines(true);
    lineChart.setScaleMinima(3f, 0f);
    lineChart.setBackgroundColor(Color.TRANSPARENT); //set whatever color you prefer
    lineChart.setDrawGridBackground(false);
    lineChart.setTouchEnabled(true);
    lineChart.setDragEnabled(true);
    lineChart.setScaleEnabled(true);
    lineChart.setPinchZoom(false);
    Legend l = lineChart.getLegend();
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(true);
    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

    ArrayList<Entry> values = new ArrayList<Entry>();
    values.add(new Entry(Float.parseFloat("1"), 5));
    values.add(new Entry(Float.parseFloat("2"), 2));
    values.add(new Entry(Float.parseFloat("3"), 6));
    values.add(new Entry(Float.parseFloat("4"), 8));
    values.add(new Entry(Float.parseFloat("5"), 2));

    LineDataSet d = new LineDataSet(values, "Actual kWh ");
    d.setMode(LineDataSet.Mode.CUBIC_BEZIER);
    d.setLineWidth(2.5f);
    d.setCircleRadius(3f);
    d.setCircleColorHole(Color.BLACK);
    d.setValueTextSize(10f);
    d.setValueTextColor(Color.WHITE);
    dataSets.add(d);
    LineData data = new LineData(dataSets);
    lineChart.setData(data);
    lineChart.invalidate();
</code>```

I am able to do most of the customization. My question is how to remove only the topborder ? Also in the X Axis I am getting decimal values like 1, 1.2, 1.3 and it goes on. I want the X Axis to have values like 1, 2, 3, 4 , 5. How can I do this ?

答:
```<code> LineChart lineChart = (LineChart) findViewById(R.id.chart);
        lineChart.setDrawBorders(false);
        lineChart.getDescription().setEnabled(false);
        lineChart.fitScreen();
        lineChart.setPadding(0, 0, 0, 0);
        lineChart.getLegend().setEnabled(false);
        lineChart.setDoubleTapToZoomEnabled(false);

        lineChart.getAxisLeft().setEnabled(true);
        lineChart.getAxisRight().setEnabled(true);
        lineChart.getAxisLeft().setStartAtZero(false);

        lineChart.getAxisRight().setDrawAxisLine(true);
        lineChart.getAxisRight().setDrawLabels(true);
        lineChart.getAxisRight().setDrawGridLines(false);

        lineChart.getXAxis().setEnabled(true);
        lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

        XAxis xLabels = lineChart.getXAxis();
        xLabels.setGranularity(1f);

        lineChart.getXAxis().setDrawAxisLine(true);
        lineChart.getXAxis().setDrawGridLines(true);
        lineChart.setScaleMinima(3f, 0f);
        lineChart.setBackgroundColor(Color.TRANSPARENT); //set whatever color you prefer
        lineChart.setDrawGridBackground(false);
        lineChart.setTouchEnabled(false);
        lineChart.setDragEnabled(false);
        lineChart.setScaleEnabled(false);
        lineChart.setPinchZoom(false);
        Legend l = lineChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(true);
        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

        ArrayList<Entry> values = new ArrayList<Entry>();
        values.add(new Entry(Float.parseFloat("1"), 5));
        values.add(new Entry(Float.parseFloat("2"), 2));
        values.add(new Entry(Float.parseFloat("3"), 6));
        values.add(new Entry(Float.parseFloat("4"), 8));
        values.add(new Entry(Float.parseFloat("5"), 2));

        LineDataSet d = new LineDataSet(values, "Actual kWh ");
        d.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        d.setLineWidth(2.5f);
        d.setCircleRadius(3f);
        d.setCircleColorHole(Color.BLACK);
        d.setValueTextSize(10f);
        d.setValueTextColor(Color.WHITE);
        dataSets.add(d);
        LineData data = new LineData(dataSets);
        lineChart.setData(data);
        lineChart.invalidate();
</code>```

Update

```<code> //to hide x-axis line
 xLabels.setAxisLineColor(Color.TRANSPARENT);
</code>```

Body:
I am using MPAndroidChart for line graph. I have some 5 points. Below is my code.

 LineChart lineChart = (LineChart) findViewById(R.id.chart);
    lineChart.setDrawBorders(true);
    lineChart.getDescription().setEnabled(false);
    lineChart.fitScreen();
    lineChart.setPadding(0,0,0,0);
    lineChart.getLegend().setEnabled(false);
    lineChart.setDoubleTapToZoomEnabled(false);

    lineChart.getAxisLeft().setEnabled(false);
    lineChart.getAxisRight().setEnabled(true);
    lineChart.getAxisLeft().setStartAtZero(true);

    lineChart.getAxisRight().setDrawAxisLine(true);
    lineChart.getAxisRight().setDrawLabels(true);
    lineChart.getAxisRight().setDrawGridLines(false);

    lineChart.getXAxis().setEnabled(true);
    lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

    lineChart.getXAxis().setDrawAxisLine(true);
    lineChart.getXAxis().setDrawGridLines(true);
    lineChart.setScaleMinima(3f, 0f);
    lineChart.setBackgroundColor(Color.TRANSPARENT); //set whatever color you prefer
    lineChart.setDrawGridBackground(false);
    lineChart.setTouchEnabled(true);
    lineChart.setDragEnabled(true);
    lineChart.setScaleEnabled(true);
    lineChart.setPinchZoom(false);
    Legend l = lineChart.getLegend();
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(true);
    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

    ArrayList<Entry> values = new ArrayList<Entry>();
    values.add(new Entry(Float.parseFloat("1"), 5));
    values.add(new Entry(Float.parseFloat("2"), 2));
    values.add(new Entry(Float.parseFloat("3"), 6));
    values.add(new Entry(Float.parseFloat("4"), 8));
    values.add(new Entry(Float.parseFloat("5"), 2));

    LineDataSet d = new LineDataSet(values, "Actual kWh ");
    d.setMode(LineDataSet.Mode.CUBIC_BEZIER);
    d.setLineWidth(2.5f);
    d.setCircleRadius(3f);
    d.setCircleColorHole(Color.BLACK);
    d.setValueTextSize(10f);
    d.setValueTextColor(Color.WHITE);
    dataSets.add(d);
    LineData data = new LineData(dataSets);
    lineChart.setData(data);
    lineChart.invalidate();

I am able to do most of the customization. My question is how to remove only the topborder ? Also in the X Axis I am getting decimal values like 1, 1.2, 1.3 and it goes on. I want the X Axis to have values like 1, 2, 3, 4 , 5. How can I do this ?

Body:
 LineChart lineChart = (LineChart) findViewById(R.id.chart);
        lineChart.setDrawBorders(false);
        lineChart.getDescription().setEnabled(false);
        lineChart.fitScreen();
        lineChart.setPadding(0, 0, 0, 0);
        lineChart.getLegend().setEnabled(false);
        lineChart.setDoubleTapToZoomEnabled(false);

        lineChart.getAxisLeft().setEnabled(true);
        lineChart.getAxisRight().setEnabled(true);
        lineChart.getAxisLeft().setStartAtZero(false);

        lineChart.getAxisRight().setDrawAxisLine(true);
        lineChart.getAxisRight().setDrawLabels(true);
        lineChart.getAxisRight().setDrawGridLines(false);

        lineChart.getXAxis().setEnabled(true);
        lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

        XAxis xLabels = lineChart.getXAxis();
        xLabels.setGranularity(1f);

        lineChart.getXAxis().setDrawAxisLine(true);
        lineChart.getXAxis().setDrawGridLines(true);
        lineChart.setScaleMinima(3f, 0f);
        lineChart.setBackgroundColor(Color.TRANSPARENT); //set whatever color you prefer
        lineChart.setDrawGridBackground(false);
        lineChart.setTouchEnabled(false);
        lineChart.setDragEnabled(false);
        lineChart.setScaleEnabled(false);
        lineChart.setPinchZoom(false);
        Legend l = lineChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(true);
        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

        ArrayList<Entry> values = new ArrayList<Entry>();
        values.add(new Entry(Float.parseFloat("1"), 5));
        values.add(new Entry(Float.parseFloat("2"), 2));
        values.add(new Entry(Float.parseFloat("3"), 6));
        values.add(new Entry(Float.parseFloat("4"), 8));
        values.add(new Entry(Float.parseFloat("5"), 2));

        LineDataSet d = new LineDataSet(values, "Actual kWh ");
        d.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        d.setLineWidth(2.5f);
        d.setCircleRadius(3f);
        d.setCircleColorHole(Color.BLACK);
        d.setValueTextSize(10f);
        d.setValueTextColor(Color.WHITE);
        dataSets.add(d);
        LineData data = new LineData(dataSets);
        lineChart.setData(data);
        lineChart.invalidate();

Update

 //to hide x-axis line
 xLabels.setAxisLineColor(Color.TRANSPARENT);


问:
Making transparent view over semitransparent view (Android)
I want to make one transparent rectangle view over one semitransparent rectangle view.

Desired:

┌──────────────┐

│　　　　　　　　　　│

│　┌─────────┐　│

│　│transparent　 │　│

│　└─────────┘　│

│ 50% transparent　　│

└──────────────┘

Actual:

┌────────────────┐

│　　　　　　　　 　　　│

│　┌───────────┐　│

│　│50% transparent　│　│

│　└───────────┘　│

│ 50% transparent 　　　│

└────────────────┘

Code:

```<code>    <View
    android:id="@+id/overlay_half_shade"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/overlay_textguide"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center"
    android:background="#80FFFFFF" /> // 50% transparent

<View
    android:id="@+id/overlay_transparent"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_below="@+id/overlay_textguide"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center"
    android:background="@drawable/focus_thumbnail_slide" /> // custom drawable: transparent rectangle with stroke
</code>```

I guess that the whole transparency of the center region considers transparencies of both two overlapped boxes; resulting 50% transparency there. How can I solve this?

答:
You can try like this and get your expected output

inner_shape.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <stroke android:width="70dp" android:height="70dp" android:color="#80B22222" />
</shape>
</code>```

in your xml layout

```<code><RelativeLayout
    android:id="@+id/overlay_half_shade"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_below="@+id/overlay_textguide"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center"
    android:alpha="0.5"
    android:background="@drawable/inner_shape">
</code>```

Body:
I want to make one transparent rectangle view over one semitransparent rectangle view.

Desired:

┌──────────────┐

│　　　　　　　　　　│

│　┌─────────┐　│

│　│transparent　 │　│

│　└─────────┘　│

│ 50% transparent　　│

└──────────────┘

Actual:

┌────────────────┐

│　　　　　　　　 　　　│

│　┌───────────┐　│

│　│50% transparent　│　│

│　└───────────┘　│

│ 50% transparent 　　　│

└────────────────┘

Code:

    <View
    android:id="@+id/overlay_half_shade"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/overlay_textguide"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center"
    android:background="#80FFFFFF" /> // 50% transparent

<View
    android:id="@+id/overlay_transparent"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_below="@+id/overlay_textguide"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center"
    android:background="@drawable/focus_thumbnail_slide" /> // custom drawable: transparent rectangle with stroke

I guess that the whole transparency of the center region considers transparencies of both two overlapped boxes; resulting 50% transparency there. How can I solve this?

Body:
You can try like this and get your expected output

inner_shape.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <stroke android:width="70dp" android:height="70dp" android:color="#80B22222" />
</shape>

in your xml layout

<RelativeLayout
    android:id="@+id/overlay_half_shade"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_below="@+id/overlay_textguide"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center"
    android:alpha="0.5"
    android:background="@drawable/inner_shape">


问:
Python. Detect changes in vector direction
I have a vector y that either increments or decrements by 1. What I want is to create a another vector y2 that shows when y1 changed direction.

I can't figure out how to do this in numpy.

EDIT updated plot, due to missing comma in y

```<code>import matplotlib.pyplot as plt
import numpy as np
</code>```

EDIT: Fixed missing comma in y

```<code>import matplotlib.pyplot as plt
import numpy as np

y = np.array([0,0,1,1,2,2,1,0,-1,-1,0,0,1])

x = np.arange(len(y))

y2 = np.array([0,0,1,0,0,0,-1,0,0,0,1,0,0])

plt.plot(x, y, label='y - Actual')
plt.plot(x, y2, label='y2 - Desired')
plt.legend()
plt.show()
</code>```

答:
Edit: Now also handles out of spec inputs (increments outside -1, 0, 1).

Here's a slightly faster (for the time being) way (pp is me, D is @Divakar):

```<code># n = 10
# pp                    0.02363790 ms
# D                     0.03705720 ms
# n = 1000
# pp                    0.03609150 ms
# D                     0.05877410 ms
# n = 1000000
# pp                   22.63471480 ms
# D                    36.92147740 ms
</code>```

Code including benchmarking:

```<code>import numpy as np

import types
from timeit import timeit

def setup_data(n, allow_out_of_spec=True):
    if allow_out_of_spec:
        data = {'y': np.cumsum(np.random.randint(0, 10, (n,))
                               * np.random.randint(-1, 2, (n,)))}
    else:
        data = {'y': np.cumsum(np.random.randint(-1, 2, (n,)))}
    return data

# mine
def f_pp(y, allow_out_of_spec=True):
    if allow_out_of_spec:
        d = np.sign(np.diff(y))
    else:
        d = np.diff(y)
    ud = np.flatnonzero(d)
    uds = d[ud]
    chng = ud[np.r_[True, uds[1:] != uds[:-1]]]

    out = np.zeros(len(y), dtype=int)
    out[1:][chng] = d[chng]
    return out

# @Divakar's
def f_D(y):
    s0 = np.flatnonzero(y[1:] > y[:-1])+1
    s1 = np.flatnonzero(y[1:] < y[:-1])+1

    idx0 = np.searchsorted(s1,s0,'right')
    s0c = s0[np.r_[True,idx0[1:] > idx0[:-1]]]

    idx1 = np.searchsorted(s0c,s1,'right')
    s1c = s1[np.r_[True,idx1[1:] > idx1[:-1]]]

    out = np.zeros(len(y),dtype=int)
    out[s0c] = 1
    out[s1c] = -1
    return out

for n in (10, 1000, 1000000):
    data = setup_data(n)
    ref = np.array(f_pp(**data))
    print(f'n = {n}')
    for name, func in list(globals().items()):
        if not name.startswith('f_') or not isinstance(func, types.FunctionType):
            continue
        try:
            assert np.allclose(ref, func(**data))
            print("{:16s}{:16.8f} ms".format(name[2:], timeit(
                'f(**data)', globals={'f':func, 'data':data}, number=10)*100))
        except:
            print("{:16s} apparently failed".format(name[2:]))
</code>```

Body:
I have a vector y that either increments or decrements by 1. What I want is to create a another vector y2 that shows when y1 changed direction.

I can't figure out how to do this in numpy.

EDIT updated plot, due to missing comma in y

import matplotlib.pyplot as plt
import numpy as np

EDIT: Fixed missing comma in y

import matplotlib.pyplot as plt
import numpy as np

y = np.array([0,0,1,1,2,2,1,0,-1,-1,0,0,1])

x = np.arange(len(y))

y2 = np.array([0,0,1,0,0,0,-1,0,0,0,1,0,0])

plt.plot(x, y, label='y - Actual')
plt.plot(x, y2, label='y2 - Desired')
plt.legend()
plt.show()

Body:
Edit: Now also handles out of spec inputs (increments outside -1, 0, 1).

Here's a slightly faster (for the time being) way (pp is me, D is @Divakar):

# n = 10
# pp                    0.02363790 ms
# D                     0.03705720 ms
# n = 1000
# pp                    0.03609150 ms
# D                     0.05877410 ms
# n = 1000000
# pp                   22.63471480 ms
# D                    36.92147740 ms

Code including benchmarking:

import numpy as np

import types
from timeit import timeit

def setup_data(n, allow_out_of_spec=True):
    if allow_out_of_spec:
        data = {'y': np.cumsum(np.random.randint(0, 10, (n,))
                               * np.random.randint(-1, 2, (n,)))}
    else:
        data = {'y': np.cumsum(np.random.randint(-1, 2, (n,)))}
    return data

# mine
def f_pp(y, allow_out_of_spec=True):
    if allow_out_of_spec:
        d = np.sign(np.diff(y))
    else:
        d = np.diff(y)
    ud = np.flatnonzero(d)
    uds = d[ud]
    chng = ud[np.r_[True, uds[1:] != uds[:-1]]]

    out = np.zeros(len(y), dtype=int)
    out[1:][chng] = d[chng]
    return out

# @Divakar's
def f_D(y):
    s0 = np.flatnonzero(y[1:] > y[:-1])+1
    s1 = np.flatnonzero(y[1:] < y[:-1])+1

    idx0 = np.searchsorted(s1,s0,'right')
    s0c = s0[np.r_[True,idx0[1:] > idx0[:-1]]]

    idx1 = np.searchsorted(s0c,s1,'right')
    s1c = s1[np.r_[True,idx1[1:] > idx1[:-1]]]

    out = np.zeros(len(y),dtype=int)
    out[s0c] = 1
    out[s1c] = -1
    return out

for n in (10, 1000, 1000000):
    data = setup_data(n)
    ref = np.array(f_pp(**data))
    print(f'n = {n}')
    for name, func in list(globals().items()):
        if not name.startswith('f_') or not isinstance(func, types.FunctionType):
            continue
        try:
            assert np.allclose(ref, func(**data))
            print("{:16s}{:16.8f} ms".format(name[2:], timeit(
                'f(**data)', globals={'f':func, 'data':data}, number=10)*100))
        except:
            print("{:16s} apparently failed".format(name[2:]))


问:
Please explain Get and Post in ASP.net
I am new to ASP.net . Can any one please explain what is the difference between Get and Post method in asp.Net.

Thanks
Pradeep.A

答:
The Wikipedia article on HTTP would be a good place to start.

It's better to understand the underlying protocol before learning ASP.NET

ContentLicense: CC BY-SA 2.5

Title: Please explain Get and Post in ASP.net