问:
Unable to access the Index value inside template Ref
I'm unable to access the index inside the templateRef, It throws undefined in console.

```<code>  <ng-container *ngFor="let notification of notifications; let i = index">
    <ng-template
      *ngTemplateOutlet="notificatioPageContent; context: { notification: notification, index: i  }">
    </ng-template>
  </ng-container>

  <ng-template #notificatioPageContent let-notification=notification let-index=i>
</code>```

I'm able to access the notification value, but not the index value. Please help

****Update**

```<code><ng-template #notificationPageContent let-notification=notification let-index=i>
          <notification
          (notificationClosed)="notificationCloseHandler($event, i)"
          >
</code>```

When the button is clicked, I'm calling the notificationClosed function. But here still the i is undefined. Please tell me what i'm doing wrong here

答:
Try this : We are taking index value incorrectly check line #1 for correct syntax, you will be getting 'i' as index now that we are passing o TemplateOutlet as index that you will get as index at ng-template.

```<code><ng-container *ngFor="let notification of notifications;index as i">
    <ng-template
      *ngTemplateOutlet="notificatioPageContent; context: { notification: notification, index: i  }">
    </ng-template>
  </ng-container>

  <ng-template #notificatioPageContent let-notification=notification let-index=i>
</code>```

Hope it helps... Happy coding :)

Body:
I'm unable to access the index inside the templateRef, It throws undefined in console.

  <ng-container *ngFor="let notification of notifications; let i = index">
    <ng-template
      *ngTemplateOutlet="notificatioPageContent; context: { notification: notification, index: i  }">
    </ng-template>
  </ng-container>

  <ng-template #notificatioPageContent let-notification=notification let-index=i>

I'm able to access the notification value, but not the index value. Please help

****Update**

<ng-template #notificationPageContent let-notification=notification let-index=i>
          <notification
          (notificationClosed)="notificationCloseHandler($event, i)"
          >

When the button is clicked, I'm calling the notificationClosed function. But here still the i is undefined. Please tell me what i'm doing wrong here

Body:
Try this : We are taking index value incorrectly check line #1 for correct syntax, you will be getting 'i' as index now that we are passing o TemplateOutlet as index that you will get as index at ng-template.

<ng-container *ngFor="let notification of notifications;index as i">
    <ng-template
      *ngTemplateOutlet="notificatioPageContent; context: { notification: notification, index: i  }">
    </ng-template>
  </ng-container>

  <ng-template #notificatioPageContent let-notification=notification let-index=i>

Hope it helps... Happy coding :)


来源: stackexchange

问:
Polybase: Azure Sql DB cannot import blob storage
Is it true that Azure SQL cannot import blob storage? (SQLDW can and also stand alone instance)

as given in this document, it cannot. But the document is from 2018. Has things changed after that?

答: It is true. PolyBase is not part of Azure SQL DB . And the document in your question is the latest.</p>

ContentLicense: CC BY-SA 4.0


问:
qt opengl stl render error with normal vector
I get triangle vertex data and Normal vector data from a stl file, but when I render it with code like this

for(uint32_t i = 0 ;i < mVertexCnt - 9;){
    int z = i/9;
    glBegin(GL_TRIANGLES);
    glNormal3f(mNorm[3*z], mNorm[3*z+1], mNorm[3*z+2]);

    glVertex3f(mVertix[i]/100,mVertix[i+1]/100,mVertix[i+2]/100); //1
    glVertex3f(mVertix[i+3]/100,mVertix[i+4]/100,mVertix[i+5]/100); //1
    glVertex3f(mVertix[i+6]/100,mVertix[i+7]/100,mVertix[i+8]/100); //1
    i += 9;
    glEnd();
}
```

<p>the result is like </p>

<p><img src="https://i.stack.imgur.com/155er.png" alt="">
<br></p>

<p>I think it is because the because normal vector direction is opposite to light direction.</p>

<p>my question is does OpenGL can handle itself. Ignore this direction issue and show the right light in every direction.
anyone know about it?</p>

<p>The light setting is like this:</p>

<pre class="lang-cpp prettyprint-override"><code>glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glMaterialfv(GL_BACK, GL_SPECULAR, mat_specular);
glMaterialfv(GL_BACK, GL_SHININESS, mat_shininess);

//灯光设置
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light);   //散射光属性
glLightfv(GL_LIGHT0, GL_SPECULAR, white_light);  //镜面反射光
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, Light_Model_Ambient);  //环境光参数

glEnable(GL_LIGHTING);   //开关:使用光
glEnable(GL_LIGHT0);     //打开0#灯
</code>```

答:
When the light model should be applied to both sides of a polygon, then you have to enable  GL_LIGHT_MODEL_TWO_SIDE (see glLightModel) By default GL_LIGHT_MODEL_TWO_SIDE is 0.

glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
```

But note this does not cause that the best fitting direction normal vector is found magically. It just causes that the normal vector of back facing polygons is inverted. Whether a polygon (triangle) is back face, is determined by the Winding order  of the vertices in the projection on the viewport. Whether clockwise or counterclockwise polygons are meant to be front facing, can be set by glFrontFace.

Body:
I get triangle vertex data and Normal vector data from a stl file, but when I render it with code like this

for(uint32_t i = 0 ;i < mVertexCnt - 9;){
    int z = i/9;
    glBegin(GL_TRIANGLES);
    glNormal3f(mNorm[3*z], mNorm[3*z+1], mNorm[3*z+2]);

    glVertex3f(mVertix[i]/100,mVertix[i+1]/100,mVertix[i+2]/100); //1
    glVertex3f(mVertix[i+3]/100,mVertix[i+4]/100,mVertix[i+5]/100); //1
    glVertex3f(mVertix[i+6]/100,mVertix[i+7]/100,mVertix[i+8]/100); //1
    i += 9;
    glEnd();
}

the result is like

I think it is because the because normal vector direction is opposite to light direction.

my question is does OpenGL can handle itself. Ignore this direction issue and show the right light in every direction.
anyone know about it?

The light setting is like this:

glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glMaterialfv(GL_BACK, GL_SPECULAR, mat_specular);
glMaterialfv(GL_BACK, GL_SHININESS, mat_shininess);

//灯光设置
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light);   //散射光属性
glLightfv(GL_LIGHT0, GL_SPECULAR, white_light);  //镜面反射光
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, Light_Model_Ambient);  //环境光参数

glEnable(GL_LIGHTING);   //开关:使用光
glEnable(GL_LIGHT0);     //打开0#灯

Body:
When the light model should be applied to both sides of a polygon, then you have to enable  GL_LIGHT_MODEL_TWO_SIDE (see glLightModel) By default GL_LIGHT_MODEL_TWO_SIDE is 0.

glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);

But note this does not cause that the best fitting direction normal vector is found magically. It just causes that the normal vector of back facing polygons is inverted. Whether a polygon (triangle) is back face, is determined by the Winding order  of the vertices in the projection on the viewport. Whether clockwise or counterclockwise polygons are meant to be front facing, can be set by glFrontFace.


问:
What is the preferred way to load data from an API into BigQuery?
I am trying to get data from a REST API into BigQuery on the Google Cloud Platform (GCP). What is the best way to achieve that (without using any third party tools such as Funnel.io or Supermetrics)?

Most tutorials I could find suggest to write the data as CSV files to Cloud Storage and then use DataFlow to load the data into BigQuery. This however seems to be a bit cumbersome. There should be a way to do that without the intermediate step to write to CSV. Can this be achieved (within GCP) and if so, what is the best way?

PS: If the size of the data is relevant for the answer: I'm trying to load a total of about 10,000 rows of data (one-off) with about 100 new columns coming in every day - ideally updating every hour.

答:
According to the documentation:

Currently, you can load data into BigQuery only from Cloud Storage or
a readable data source (such as your local machine).

Therefore, unless you are loading Datastore or Firestore exports, it is required that the files are in Google Cloud Storage. There are the following available readable formats from GCS:

Avro

CSV

JSON (newline delimited only)

ORC

Parquet

Datastore exports

Firestore exports

You should be aware of the limitations for each format. In addition, there are also limitations for load jobs, they are described here.

I would advice you to fetch the data from your Rest API, in one of the readable formats, store it in Google Cloud Storage then use Google Transfer Service to load it into BigQuery. Thus, it would not be necessary to use DataFlow.

Cloud Storage Transfer is used to schedule recurring data loads directly into BigQuery. According to the documentation, the minimum load interval is 1 hour, which I believe suits your need. You can read more about this service here.

I hope it helps.


问:
how to export datagridview into excel
How do I fix the error System.InvalidCastException? I don't find the solution, if I change the code with another code but the errors still same System.InvalidCastException:

```<code>Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
worksheet = workbook.ActiveSheet;
worksheet.Name = "RekapPerangkatZTE";

for (int i = 1; i < dgvperangkat.Columns.Count + 1; i++)
{
    worksheet.Cells[i, 1] = dgvperangkat.Columns[i - 1].HeaderText;
}

for (int i = 0; i < dgvperangkat.Rows.Count; i++)
{
    for (int j = 0; j < dgvperangkat.Columns.Count; j++)
    {
        worksheet.Cells[i + 2, j + 1] = dgvperangkat.Rows[i].Cells[j].Value.ToString();
    }
}

var saveFileDialoge = new SaveFileDialog();
saveFileDialoge.FileName = "output";
saveFileDialoge.DefaultExt = ".xlsx";
if (saveFileDialoge.ShowDialog() == DialogResult.OK)
{
    workbook.SaveAs(saveFileDialoge.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
app.Quit();
</code>```

答:
you can use EPPlus . Fistly add your solution a helper class, that's name can be helper.cs, add static method ExportToExcel method. if you want to use in another code block, only you can call this methods.

System.InvalidCastException may be can be caused your data. I sent detailed code for your solutions, only call ExportToExcel method with datatable, directory info and file name, i hope it will be fix your problem. Dont forget adding EPPlus library on references. It's works all datatables, that is flexable all data.

```<code>//Usage example code
  DataTable table = new DataTable(); //Get or set your data to DataTable
  table = db.SampleResult.ToDataTable(); // This is sample, your data result can be here and it's must be datatable
  DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Upload/ExportedFiles"));
  string fileName = "Sample_List;
  Helpers.ExportToExcel(table, di, fileName);
</code>```

-Helper.cs

```<code>//Usings
using System.IO;
using OfficeOpenXml;
Using OfficeOpenXml.Style;
</code>```

```<code>public static string ExportToExcel(DataTable dt, DirectoryInfo outputDir, string fileName)
    {
        FileInfo newFile = new FileInfo(outputDir.FullName + @"\" + fileName + ".xlsx");
        string ReportName = "Sample Report";
        // If any file exists in this directory having name 'Sample1.xlsx', then delete it
        if (newFile.Exists)
        {
            //If you want to delete OR rename
            //newFile.Delete(); // ensures we create a new workbook
            //Random rnd = new Random();
            //string random = rnd.Next(100, 999).ToString();
            //newFile = new FileInfo(outputDir.FullName + @"\" + fileName + random + ".xlsx");
        }
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            // Add a worksheet to the empty workbook
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(ReportName);
            worksheet.Row(1).Height = 20;

            int columnCount = dt.Columns.Count;

            // Add the headers
            worksheet.Cells[1, 1, 1, columnCount].Merge = true;
            worksheet.Cells[1, 1].Value = fileName + " Sample List Title - " + DateTime.Now.ToShortDateString();
            worksheet.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            worksheet.Cells[1, 1].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            worksheet.Cells[1, 1].Style.Font.Size = 15;
            worksheet.Cells[1, 1].Style.Font.Bold = true;

            int intColumn = 1;

            foreach (DataColumn column in dt.Columns)
            {
                worksheet.Cells[2, intColumn].Value = column.ColumnName;

            string[] alphabet = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ", "EA", "EB", "EC", "ED", "EE", "EF", "EG", "EH", "EI", "EJ", "EK", "EL", "EM", "EN", "EO", "EP", "EQ", "ER", "ES", "ET", "EU", "EV", "EW", "EX", "EY", "EZ", "FA", "FB", "FC", "FD", "FE", "FF", "FG", "FH", "FI", "FJ", "FK", "FL", "FM", "FN", "FO", "FP", "FQ", "FR", "FS", "FT", "FU", "FV", "FW", "FX", "FY", "FZ", "GA", "GB", "GC", "GD", "GE", "GF", "GG", "GH", "GI", "GJ", "GK", "GL", "GM", "GN", "GO", "GP", "GQ", "GR", "GS", "GT", "GU", "GV", "GW", "GX", "GY", "GZ", "HA", "HB", "HC", "HD", "HE", "HF", "HG", "HH", "HI", "HJ", "HK", "HL", "HM", "HN", "HO", "HP", "HQ", "HR", "HS", "HT", "HU", "HV", "HW", "HX", "HY", "HZ", "IA", "IB", "IC", "ID", "IE", "IF", "IG", "IH", "II", "IJ", "IK", "IL", "IM", "IN", "IO", "IP", "IQ", "IR", "IS", "IT", "IU", "IV", "IW", "IX", "IY", "IZ", "JA", "JB", "JC", "JD", "JE", "JF", "JG", "JH", "JI", "JJ", "JK", "JL", "JM", "JN", "JO", "JP", "JQ", "JR", "JS", "JT", "JU", "JV", "JW", "JX", "JY", "JZ", "KA", "KB", "KC", "KD", "KE", "KF", "KG", "KH", "KI", "KJ", "KK", "KL", "KM", "KN", "KO", "KP", "KQ", "KR", "KS", "KT", "KU", "KV", "KW", "KX", "KY", "KZ", "LA", "LB", "LC", "LD", "LE", "LF", "LG", "LH", "LI", "LJ", "LK", "LL", "LM", "LN", "LO", "LP", "LQ", "LR", "LS", "LT", "LU", "LV", "LW", "LX", "LY", "LZ", "MA", "MB", "MC", "MD", "ME", "MF", "MG", "MH", "MI", "MJ", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NB", "NC", "ND", "NE", "NF", "NG", "NH", "NI", "NJ", "NK", "NL", "NM", "NN", "NO", "NP", "NQ", "NR", "NS", "NT", "NU", "NV", "NW", "NX", "NY", "NZ", "OA", "OB", "OC", "OD", "OE", "OF", "OG", "OH", "OI", "OJ", "OK", "OL", "OM", "ON", "OO", "OP", "OQ", "OR", "OS", "OT", "OU", "OV", "OW", "OX", "OY", "OZ", "PA", "PB", "PC", "PD", "PE", "PF", "PG", "PH", "PI", "PJ", "PK", "PL", "PM", "PN", "PO", "PP", "PQ", "PR", "PS", "PT", "PU", "PV", "PW", "PX", "PY", "PZ", "QA", "QB", "QC", "QD", "QE", "QF", "QG", "QH", "QI", "QJ", "QK", "QL", "QM", "QN", "QO", "QP", "QQ", "QR", "QS", "QT", "QU", "QV", "QW", "QX", "QY", "QZ", "RA", "RB", "RC", "RD", "RE", "RF", "RG", "RH", "RI", "RJ", "RK", "RL", "RM", "RN", "RO", "RP", "RQ", "RR", "RS", "RT", "RU", "RV", "RW", "RX", "RY", "RZ", "SA", "SB", "SC", "SD", "SE", "SF", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SP", "SQ", "SR", "SS", "ST", "SU", "SV", "SW", "SX", "SY", "SZ", "TA", "TB", "TC", "TD", "TE", "TF", "TG", "TH", "TI", "TJ", "TK", "TL", "TM", "TN", "TO", "TP", "TQ", "TR", "TS", "TT", "TU", "TV", "TW", "TX", "TY", "TZ", "UA", "UB", "UC", "UD", "UE", "UF", "UG", "UH", "UI", "UJ", "UK", "UL", "UM", "UN", "UO", "UP", "UQ", "UR", "US", "UT", "UU", "UV", "UW", "UX", "UY", "UZ", "VA", "VB", "VC", "VD", "VE", "VF", "VG", "VH", "VI", "VJ", "VK", "VL", "VM", "VN", "VO", "VP", "VQ", "VR", "VS", "VT", "VU", "VV", "VW", "VX", "VY", "VZ", "WA", "WB", "WC", "WD", "WE", "WF", "WG", "WH", "WI", "WJ", "WK", "WL", "WM", "WN", "WO", "WP", "WQ", "WR", "WS", "WT", "WU", "WV", "WW", "WX", "WY", "WZ", "XA", "XB", "XC", "XD", "XE", "XF", "XG", "XH", "XI", "XJ", "XK", "XL", "XM", "XN", "XO", "XP", "XQ", "XR", "XS", "XT", "XU", "XV", "XW", "XX", "XY", "XZ", "YA", "YB", "YC", "YD", "YE", "YF", "YG", "YH", "YI", "YJ", "YK", "YL", "YM", "YN", "YO", "YP", "YQ", "YR", "YS", "YT", "YU", "YV", "YW", "YX", "YY", "YZ", "ZA", "ZB", "ZC", "ZD", "ZE", "ZF", "ZG", "ZH", "ZI", "ZJ", "ZK", "ZL", "ZM", "ZN", "ZO", "ZP", "ZQ", "ZR", "ZS", "ZT", "ZU", "ZV", "ZW", "ZX", "ZY", "ZZ" };

            int rowStartNumber = 3;

            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    worksheet.Cells[alphabet[i].ToString() + rowStartNumber].Value = dr[i].ToString();
                }
                rowStartNumber++;
            }

            using (var range = worksheet.Cells[2, 1, 2, columnCount])
            {
                // Setting bold font
                range.Style.Font.Bold = true;
                // Setting fill type solid
                range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                // Setting background color dark blue
                range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
                // Setting font color
                range.Style.Font.Color.SetColor(Color.White);
            }

            // Setting AutoFit for all cells
            worksheet.Cells.AutoFitColumns(0);

            // Lets set the header text
            worksheet.HeaderFooter.OddHeader.CenteredText = ReportName;

            // Add the page number to the right of the footer + total number of pages
            worksheet.HeaderFooter.OddFooter.RightAlignedText = string.Format("Page {0} of {1}", ExcelHeaderFooter.PageNumber, ExcelHeaderFooter.NumberOfPages);

            // Add the sheet name to center of the footer
            worksheet.HeaderFooter.OddFooter.CenteredText = ExcelHeaderFooter.SheetName;

            // Add the filepath to the left of the footer
            worksheet.HeaderFooter.OddFooter.LeftAlignedText = ExcelHeaderFooter.FileName;

            // At the time of printing, when page page breaks, then the header will come in the next page by enabling this settings...
            worksheet.PrinterSettings.RepeatRows = worksheet.Cells["1:1"];
            worksheet.PrinterSettings.RepeatColumns = worksheet.Cells["A:" + alphabet[columnCount - 1].ToString()];
            //worksheet.PrinterSettings.PrintArea = worksheet.Cells["A,I"];
            worksheet.PrinterSettings.PaperSize = ePaperSize.A4;
            worksheet.PrinterSettings.Orientation = eOrientation.Landscape;
            worksheet.PrinterSettings.Scale = 100;

            // Change the sheet view to show it in page layout mode
            worksheet.View.PageLayoutView = false;

            // Setting some document properties
            package.Workbook.Properties.Title = ReportName;
            package.Workbook.Properties.Author = "Omer Mollamehmetoglu";
            package.Workbook.Properties.Comments = "This document created by ACME Co.Ltd.";

            // set some extended property values
            package.Workbook.Properties.Company = "ACME Co.Ltd.";

            // set some custom property values
            package.Workbook.Properties.SetCustomPropertyValue("Checked by", "Omer Mollamehmetoglu");
            package.Workbook.Properties.SetCustomPropertyValue("AssemblyName", "ACME Co.Ltd.");
            // save our new workbook and we are done!

            package.Save();
        }

        return newFile.FullName;
    }
</code>```

Title: how to export datagridview into excel

Body:
How do I fix the error System.InvalidCastException? I don't find the solution, if I change the code with another code but the errors still same System.InvalidCastException:

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
worksheet = workbook.ActiveSheet;
worksheet.Name = "RekapPerangkatZTE";

for (int i = 1; i < dgvperangkat.Columns.Count + 1; i++)
{
    worksheet.Cells[i, 1] = dgvperangkat.Columns[i - 1].HeaderText;
}

for (int i = 0; i < dgvperangkat.Rows.Count; i++)
{
    for (int j = 0; j < dgvperangkat.Columns.Count; j++)
    {
        worksheet.Cells[i + 2, j + 1] = dgvperangkat.Rows[i].Cells[j].Value.ToString();
    }
}

var saveFileDialoge = new SaveFileDialog();
saveFileDialoge.FileName = "output";
saveFileDialoge.DefaultExt = ".xlsx";
if (saveFileDialoge.ShowDialog() == DialogResult.OK)
{
    workbook.SaveAs(saveFileDialoge.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
app.Quit();

Body:
you can use EPPlus . Fistly add your solution a helper class, that's name can be helper.cs, add static method ExportToExcel method. if you want to use in another code block, only you can call this methods.

System.InvalidCastException may be can be caused your data. I sent detailed code for your solutions, only call ExportToExcel method with datatable, directory info and file name, i hope it will be fix your problem. Dont forget adding EPPlus library on references. It's works all datatables, that is flexable all data.

//Usage example code
  DataTable table = new DataTable(); //Get or set your data to DataTable
  table = db.SampleResult.ToDataTable(); // This is sample, your data result can be here and it's must be datatable
  DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Upload/ExportedFiles"));
  string fileName = "Sample_List;
  Helpers.ExportToExcel(table, di, fileName);

-Helper.cs

//Usings
using System.IO;
using OfficeOpenXml;
Using OfficeOpenXml.Style;

public static string ExportToExcel(DataTable dt, DirectoryInfo outputDir, string fileName)
    {
        FileInfo newFile = new FileInfo(outputDir.FullName + @"\" + fileName + ".xlsx");
        string ReportName = "Sample Report";
        // If any file exists in this directory having name 'Sample1.xlsx', then delete it
        if (newFile.Exists)
        {
            //If you want to delete OR rename
            //newFile.Delete(); // ensures we create a new workbook
            //Random rnd = new Random();
            //string random = rnd.Next(100, 999).ToString();
            //newFile = new FileInfo(outputDir.FullName + @"\" + fileName + random + ".xlsx");
        }
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            // Add a worksheet to the empty workbook
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(ReportName);
            worksheet.Row(1).Height = 20;

            int columnCount = dt.Columns.Count;

            // Add the headers
            worksheet.Cells[1, 1, 1, columnCount].Merge = true;
            worksheet.Cells[1, 1].Value = fileName + " Sample List Title - " + DateTime.Now.ToShortDateString();
            worksheet.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            worksheet.Cells[1, 1].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            worksheet.Cells[1, 1].Style.Font.Size = 15;
            worksheet.Cells[1, 1].Style.Font.Bold = true;

            int intColumn = 1;

            foreach (DataColumn column in dt.Columns)
            {
                worksheet.Cells[2, intColumn].Value = column.ColumnName;

            string[] alphabet = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ", "EA", "EB", "EC", "ED", "EE", "EF", "EG", "EH", "EI", "EJ", "EK", "EL", "EM", "EN", "EO", "EP", "EQ", "ER", "ES", "ET", "EU", "EV", "EW", "EX", "EY", "EZ", "FA", "FB", "FC", "FD", "FE", "FF", "FG", "FH", "FI", "FJ", "FK", "FL", "FM", "FN", "FO", "FP", "FQ", "FR", "FS", "FT", "FU", "FV", "FW", "FX", "FY", "FZ", "GA", "GB", "GC", "GD", "GE", "GF", "GG", "GH", "GI", "GJ", "GK", "GL", "GM", "GN", "GO", "GP", "GQ", "GR", "GS", "GT", "GU", "GV", "GW", "GX", "GY", "GZ", "HA", "HB", "HC", "HD", "HE", "HF", "HG", "HH", "HI", "HJ", "HK", "HL", "HM", "HN", "HO", "HP", "HQ", "HR", "HS", "HT", "HU", "HV", "HW", "HX", "HY", "HZ", "IA", "IB", "IC", "ID", "IE", "IF", "IG", "IH", "II", "IJ", "IK", "IL", "IM", "IN", "IO", "IP", "IQ", "IR", "IS", "IT", "IU", "IV", "IW", "IX", "IY", "IZ", "JA", "JB", "JC", "JD", "JE", "JF", "JG", "JH", "JI", "JJ", "JK", "JL", "JM", "JN", "JO", "JP", "JQ", "JR", "JS", "JT", "JU", "JV", "JW", "JX", "JY", "JZ", "KA", "KB", "KC", "KD", "KE", "KF", "KG", "KH", "KI", "KJ", "KK", "KL", "KM", "KN", "KO", "KP", "KQ", "KR", "KS", "KT", "KU", "KV", "KW", "KX", "KY", "KZ", "LA", "LB", "LC", "LD", "LE", "LF", "LG", "LH", "LI", "LJ", "LK", "LL", "LM", "LN", "LO", "LP", "LQ", "LR", "LS", "LT", "LU", "LV", "LW", "LX", "LY", "LZ", "MA", "MB", "MC", "MD", "ME", "MF", "MG", "MH", "MI", "MJ", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NB", "NC", "ND", "NE", "NF", "NG", "NH", "NI", "NJ", "NK", "NL", "NM", "NN", "NO", "NP", "NQ", "NR", "NS", "NT", "NU", "NV", "NW", "NX", "NY", "NZ", "OA", "OB", "OC", "OD", "OE", "OF", "OG", "OH", "OI", "OJ", "OK", "OL", "OM", "ON", "OO", "OP", "OQ", "OR", "OS", "OT", "OU", "OV", "OW", "OX", "OY", "OZ", "PA", "PB", "PC", "PD", "PE", "PF", "PG", "PH", "PI", "PJ", "PK", "PL", "PM", "PN", "PO", "PP", "PQ", "PR", "PS", "PT", "PU", "PV", "PW", "PX", "PY", "PZ", "QA", "QB", "QC", "QD", "QE", "QF", "QG", "QH", "QI", "QJ", "QK", "QL", "QM", "QN", "QO", "QP", "QQ", "QR", "QS", "QT", "QU", "QV", "QW", "QX", "QY", "QZ", "RA", "RB", "RC", "RD", "RE", "RF", "RG", "RH", "RI", "RJ", "RK", "RL", "RM", "RN", "RO", "RP", "RQ", "RR", "RS", "RT", "RU", "RV", "RW", "RX", "RY", "RZ", "SA", "SB", "SC", "SD", "SE", "SF", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SP", "SQ", "SR", "SS", "ST", "SU", "SV", "SW", "SX", "SY", "SZ", "TA", "TB", "TC", "TD", "TE", "TF", "TG", "TH", "TI", "TJ", "TK", "TL", "TM", "TN", "TO", "TP", "TQ", "TR", "TS", "TT", "TU", "TV", "TW", "TX", "TY", "TZ", "UA", "UB", "UC", "UD", "UE", "UF", "UG", "UH", "UI", "UJ", "UK", "UL", "UM", "UN", "UO", "UP", "UQ", "UR", "US", "UT", "UU", "UV", "UW", "UX", "UY", "UZ", "VA", "VB", "VC", "VD", "VE", "VF", "VG", "VH", "VI", "VJ", "VK", "VL", "VM", "VN", "VO", "VP", "VQ", "VR", "VS", "VT", "VU", "VV", "VW", "VX", "VY", "VZ", "WA", "WB", "WC", "WD", "WE", "WF", "WG", "WH", "WI", "WJ", "WK", "WL", "WM", "WN", "WO", "WP", "WQ", "WR", "WS", "WT", "WU", "WV", "WW", "WX", "WY", "WZ", "XA", "XB", "XC", "XD", "XE", "XF", "XG", "XH", "XI", "XJ", "XK", "XL", "XM", "XN", "XO", "XP", "XQ", "XR", "XS", "XT", "XU", "XV", "XW", "XX", "XY", "XZ", "YA", "YB", "YC", "YD", "YE", "YF", "YG", "YH", "YI", "YJ", "YK", "YL", "YM", "YN", "YO", "YP", "YQ", "YR", "YS", "YT", "YU", "YV", "YW", "YX", "YY", "YZ", "ZA", "ZB", "ZC", "ZD", "ZE", "ZF", "ZG", "ZH", "ZI", "ZJ", "ZK", "ZL", "ZM", "ZN", "ZO", "ZP", "ZQ", "ZR", "ZS", "ZT", "ZU", "ZV", "ZW", "ZX", "ZY", "ZZ" };

            int rowStartNumber = 3;

            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    worksheet.Cells[alphabet[i].ToString() + rowStartNumber].Value = dr[i].ToString();
                }
                rowStartNumber++;
            }

            using (var range = worksheet.Cells[2, 1, 2, columnCount])
            {
                // Setting bold font
                range.Style.Font.Bold = true;
                // Setting fill type solid
                range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                // Setting background color dark blue
                range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
                // Setting font color
                range.Style.Font.Color.SetColor(Color.White);
            }

            // Setting AutoFit for all cells
            worksheet.Cells.AutoFitColumns(0);

            // Lets set the header text
            worksheet.HeaderFooter.OddHeader.CenteredText = ReportName;

            // Add the page number to the right of the footer + total number of pages
            worksheet.HeaderFooter.OddFooter.RightAlignedText = string.Format("Page {0} of {1}", ExcelHeaderFooter.PageNumber, ExcelHeaderFooter.NumberOfPages);

            // Add the sheet name to center of the footer
            worksheet.HeaderFooter.OddFooter.CenteredText = ExcelHeaderFooter.SheetName;

            // Add the filepath to the left of the footer
            worksheet.HeaderFooter.OddFooter.LeftAlignedText = ExcelHeaderFooter.FileName;

            // At the time of printing, when page page breaks, then the header will come in the next page by enabling this settings...
            worksheet.PrinterSettings.RepeatRows = worksheet.Cells["1:1"];
            worksheet.PrinterSettings.RepeatColumns = worksheet.Cells["A:" + alphabet[columnCount - 1].ToString()];
            //worksheet.PrinterSettings.PrintArea = worksheet.Cells["A,I"];
            worksheet.PrinterSettings.PaperSize = ePaperSize.A4;
            worksheet.PrinterSettings.Orientation = eOrientation.Landscape;
            worksheet.PrinterSettings.Scale = 100;

            // Change the sheet view to show it in page layout mode
            worksheet.View.PageLayoutView = false;

            // Setting some document properties
            package.Workbook.Properties.Title = ReportName;
            package.Workbook.Properties.Author = "Omer Mollamehmetoglu";
            package.Workbook.Properties.Comments = "This document created by ACME Co.Ltd.";

            // set some extended property values
            package.Workbook.Properties.Company = "ACME Co.Ltd.";

            // set some custom property values
            package.Workbook.Properties.SetCustomPropertyValue("Checked by", "Omer Mollamehmetoglu");
            package.Workbook.Properties.SetCustomPropertyValue("AssemblyName", "ACME Co.Ltd.");
            // save our new workbook and we are done!

            package.Save();
        }

        return newFile.FullName;
    }


问:
Accessing elements of series object without using index python, accessing values of correlation or other matrices
I have a dataframe df. I have taken its correlation and then found out the first four highly correlated values. These values I have named as relevant features. I wish to access the values of these relevant features (relevant features is series object)

```<code>correlation_matrix=df.corr()    #taking correlation of the df
cor_target=abs(correlation_matrix['median_house_value'])  #finding the correlation of all variables\
#against median housing value

#Selecting 4 of the most correlated features
relevant_features = cor_target.sort_values(ascending=False).head(4)
relevant_features
</code>```

Output:

```<code>median_house_value    1.000000
median_income         0.688075
income_cat            0.553377
latitude              0.144160
Name: median_house_value, dtype: float64
:,4
</code>```

I am getting above 4 features which have max correlation with median housing value as above. Now I want to access the values 1.000,0.688075, 0.553377 etc., basically the first column.

I tried below codes:

```<code>[IN] relevant_features[:,4]
[OUT]ValueError: Can only tuple-index with a MultiIndex

[IN] relevant_features.iloc[:,1]
[OUT]IndexingError: Too many indexers

[IN] relevant_features.loc[[0,1,2,3]]
[OUT]KeyError: "None of [Int64Index([0, 1, 2, 3], dtype='int64')] are in the [index]"

[IN] relevant_features[:,3]
[OUT]ValueError: Can only tuple-index with a MultiIndex
</code>```

I read many questions and answers and articles but it is not helping me.

```<code>[IN]type(relevant_features)
[OUT]pandas.core.series.Series
</code>```

答:
You are really close, need:</p>

```<code>relevant_features.iloc[:4].to_numpy()
</code>```

Body:
I have a dataframe df. I have taken its correlation and then found out the first four highly correlated values. These values I have named as relevant features. I wish to access the values of these relevant features (relevant features is series object)

correlation_matrix=df.corr()    #taking correlation of the df
cor_target=abs(correlation_matrix['median_house_value'])  #finding the correlation of all variables\
#against median housing value

#Selecting 4 of the most correlated features
relevant_features = cor_target.sort_values(ascending=False).head(4)
relevant_features

Output:

median_house_value    1.000000
median_income         0.688075
income_cat            0.553377
latitude              0.144160
Name: median_house_value, dtype: float64
:,4

I am getting above 4 features which have max correlation with median housing value as above. Now I want to access the values 1.000,0.688075, 0.553377 etc., basically the first column.

I tried below codes:

[IN] relevant_features[:,4]
[OUT]ValueError: Can only tuple-index with a MultiIndex

[IN] relevant_features.iloc[:,1]
[OUT]IndexingError: Too many indexers

[IN] relevant_features.loc[[0,1,2,3]]
[OUT]KeyError: "None of [Int64Index([0, 1, 2, 3], dtype='int64')] are in the [index]"

[IN] relevant_features[:,3]
[OUT]ValueError: Can only tuple-index with a MultiIndex

I read many questions and answers and articles but it is not helping me.

[IN]type(relevant_features)
[OUT]pandas.core.series.Series

Body:
You are really close, need:

relevant_features.iloc[:4].to_numpy()


问:
Way to create indexedDB index in IDBObjectSore with keyPath like this: 'location:location._id'
I have some data in an indexedDB store that looks like this:

```<code>{
    "assetNo" : "00045455",
    "location:location" : {
        "title" : "19100003BRMA2879",
        "_id" : "5e2727cbc38a923f5826efb7"
    }
}
</code>```

I'd like to create an index on the _id inside that location, but it seems like indexedDB does not like that colon in between location:location.  I'm getting an error:
DOMException: Failed to execute 'createIndex' on 'IDBObjectStore': The keyPath argument contains an invalid key path

The colon is a convention that is used through thousands and thousands of lines of code, so just changing it would be a problem.  Is there some way around this?  A way to escape the colon for instance?

答:
Looking at https://www.w3.org/TR/IndexedDB-2/#key-path-construct I see that it states that:

A valid key path is one of:

An empty string.

An identifier, which is a string matching the IdentifierName production from the ECMAScript Language Specification [ECMA-262].

A string consisting of two or more identifiers separated by periods (U+002E FULL STOP).

A non-empty list containing only strings conforming to the above requirements.

Spaces are not allowed within a key path.

Looks like the colon violates the second bullet point.

Would it be ok for you to change the data as it is written to and read from the database? This is a pretty common thing to occur when storing data, sometimes you need to modify what is actually persisted.

Something like:

function write(db, object) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('mystore', 'readwrite');
    transaction.oncomplete = resolve;
    transaction.onerror = event => reject(event.target.error);
    const store = transaction.objectStore('mystore');

    // what i am suggesting, modify just before write
    // the extra cloning is to avoid side effects on input

    const clone = { ...object };
    clone.location_location = clone['location:location'];
    delete clone['location:location'];

    store.put(clone);
  });
}

function onupgradeneeded(event) {
  const db = event.target.result;
  const store = db.createObjectStore('mystore');
  db.createIndex('location_id', 'location_location._id');
}

function getByLocationId(db, id) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('mystore');
    const store = transaction.objectStore('mystore');
    const index = store.index('location_id');
    const request = index.get(id);
    request.onerror = event => reject(request.error);
    request.onsuccess = event => {
      const result = event.target.result;
      // if we found something, project output as if we stored
      // it with a colon. we do not need to clone here.
      if (result) {
        result['location:location'] = result.location_location;
        delete result.location_location;
      }
      resolve(result);
    };
  });
}

```

Body:
I have some data in an indexedDB store that looks like this:

{
    "assetNo" : "00045455",
    "location:location" : {
        "title" : "19100003BRMA2879",
        "_id" : "5e2727cbc38a923f5826efb7"
    }
}

I'd like to create an index on the _id inside that location, but it seems like indexedDB does not like that colon in between location:location.  I'm getting an error:
DOMException: Failed to execute 'createIndex' on 'IDBObjectStore': The keyPath argument contains an invalid key path

The colon is a convention that is used through thousands and thousands of lines of code, so just changing it would be a problem.  Is there some way around this?  A way to escape the colon for instance?


问:
Progress bar in uploading Xml file
i want to use a background thread for the process of loading the XML data, possibly with a progress bar to let the user know that the application is actively doing something.
i have written this code through searching the net.

i want to load a XML tree in treeview on winform when a user cliks a Browse button.
In case of a large XML file the winform freezes.So to let the user know that in background the work is going on i want to add a progress bar.i have used a background worker here.

But it is raising an exception of  System.ArgumentException showing this message "The URL cannot be empty.\r\nParameter name: url" on     xmlDocument.Load(txtFileName.Text);  this line.

My xml file is in correct format and is at the proper location where i selected.
But i am unable to find the cause of this exception.
Can you please help out or tell me the correction in my code?

Thanks....

```<code>       private void btnBrowse_Click(object sender,EventArgs e)
        {
            bgWorker1.RunWorkerAsync();
            StripProgressBar.Value = 0;
            toolStripStatusLabel1.Text = "Browsing for a  Xml file";

            if (open.ShowDialog(this) == DialogResult.OK)
            {
                txtFileName.Text = open.FileName;
                initiatingTree(open.FileName); //this variable gives the name of selected file
            }
            while (this.bgWorker1.IsBusy)
            {
                StripProgressBar.Increment(1);
                // Keep UI messages moving, so the form remains
                // responsive during the asynchronous operation.
                Application.DoEvents();
            }
        }//Browse button
        private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            xmlDocument = new XmlDocument();
            Thread.Sleep(5000);
            xmlDocument.Load(txtFileName.Text);
            btnBrowse.Enabled = false;
        }
        private void bgworker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
         {
             // Set progress bar to 100% in case it's not already there.
             StripProgressBar.Value = 100;
             if (e.Error == null)
             {
                 MessageBox.Show(xmlDocument.InnerXml, "Download Complete");
             }
             else
             {
                 MessageBox.Show("Failed to download file");
             }
             // Enable the Browse button and reset the progress bar.
             this.btnBrowse.Enabled = true;
             StripProgressBar.Value = 0;
             toolStripStatusLabel1.Text = "work finished processing request.";
         }//workerCompleted
</code>```

答:
You're starting the asynchronous process immediately when the user clicks "Browse", by calling

```<code>bgWorker1.RunWorkerAsync();
</code>```

This calls the DoWork method of your background worker, which sleeps for 5 seconds, and pulls the value from txtFileName.Text whether or not the user has completed their entry in the FileOpenDialog.

You'd be better off moving the byWorker1.RunWorkerAsync() (and the busy waiting) into the if (open.ShowDialog(this) == DialogResult.OK) block.

```<code>    private void btnBrowse_Click(object sender,EventArgs e)
    {
        StripProgressBar.Value = 0;
        toolStripStatusLabel1.Text = "Browsing for a  Xml file";

        if (open.ShowDialog(this) == DialogResult.OK)
        {
            txtFileName.Text = open.FileName;
            initiatingTree(open.FileName);

            bgWorker1.RunWorkerAsync();

            while (this.bgWorker1.IsBusy)
            {
                StripProgressBar.Increment(1);
                // Keep UI messages moving, so the form remains
                // responsive during the asynchronous operation.
                Application.DoEvents();
            }
        }
    }
</code>```

For these kinds of problems, it can be helpful to put a breakpoint right where the file is going to get loaded, and see what the value is when that happens... you might notice that it's getting called with an empty string.

You might also consider the version of RunWorkerAsync that takes a parameter; you could pass the file in that way, instead of trying to read it asynchronously from the textbox.

And personally, I wouldn't use a loop that calls Application.DoEvents(); instead I'd return control back to the UI thread and then Invoke() onto it from the asynchronous thread to effect the progressbar updates.

ContentLicense: CC BY-SA 2.5

Title: Progress bar in uploading Xml file

Body:
i want to use a background thread for the process of loading the XML data, possibly with a progress bar to let the user know that the application is actively doing something.
i have written this code through searching the net.

i want to load a XML tree in treeview on winform when a user cliks a Browse button.
In case of a large XML file the winform freezes.So to let the user know that in background the work is going on i want to add a progress bar.i have used a background worker here.

But it is raising an exception of  System.ArgumentException showing this message "The URL cannot be empty.\r\nParameter name: url" on     xmlDocument.Load(txtFileName.Text);  this line.

My xml file is in correct format and is at the proper location where i selected.
But i am unable to find the cause of this exception.
Can you please help out or tell me the correction in my code?

Thanks....

       private void btnBrowse_Click(object sender,EventArgs e)
        {
            bgWorker1.RunWorkerAsync();
            StripProgressBar.Value = 0;
            toolStripStatusLabel1.Text = "Browsing for a  Xml file";

            if (open.ShowDialog(this) == DialogResult.OK)
            {
                txtFileName.Text = open.FileName;
                initiatingTree(open.FileName); //this variable gives the name of selected file
            }
            while (this.bgWorker1.IsBusy)
            {
                StripProgressBar.Increment(1);
                // Keep UI messages moving, so the form remains
                // responsive during the asynchronous operation.
                Application.DoEvents();
            }
        }//Browse button
        private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            xmlDocument = new XmlDocument();
            Thread.Sleep(5000);
            xmlDocument.Load(txtFileName.Text);
            btnBrowse.Enabled = false;
        }
        private void bgworker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
         {
             // Set progress bar to 100% in case it's not already there.
             StripProgressBar.Value = 100;
             if (e.Error == null)
             {
                 MessageBox.Show(xmlDocument.InnerXml, "Download Complete");
             }
             else
             {
                 MessageBox.Show("Failed to download file");
             }
             // Enable the Browse button and reset the progress bar.
             this.btnBrowse.Enabled = true;
             StripProgressBar.Value = 0;
             toolStripStatusLabel1.Text = "work finished processing request.";
         }//workerCompleted

LastEditorDisplayName: Daniel L

Body:
You're starting the asynchronous process immediately when the user clicks "Browse", by calling

bgWorker1.RunWorkerAsync();

This calls the DoWork method of your background worker, which sleeps for 5 seconds, and pulls the value from txtFileName.Text whether or not the user has completed their entry in the FileOpenDialog.

You'd be better off moving the byWorker1.RunWorkerAsync() (and the busy waiting) into the if (open.ShowDialog(this) == DialogResult.OK) block.

    private void btnBrowse_Click(object sender,EventArgs e)
    {
        StripProgressBar.Value = 0;
        toolStripStatusLabel1.Text = "Browsing for a  Xml file";

        if (open.ShowDialog(this) == DialogResult.OK)
        {
            txtFileName.Text = open.FileName;
            initiatingTree(open.FileName);

            bgWorker1.RunWorkerAsync();

            while (this.bgWorker1.IsBusy)
            {
                StripProgressBar.Increment(1);
                // Keep UI messages moving, so the form remains
                // responsive during the asynchronous operation.
                Application.DoEvents();
            }
        }
    }

For these kinds of problems, it can be helpful to put a breakpoint right where the file is going to get loaded, and see what the value is when that happens... you might notice that it's getting called with an empty string.

You might also consider the version of RunWorkerAsync that takes a parameter; you could pass the file in that way, instead of trying to read it asynchronously from the textbox.

And personally, I wouldn't use a loop that calls Application.DoEvents(); instead I'd return control back to the UI thread and then Invoke() onto it from the asynchronous thread to effect the progressbar updates.

OwnerDisplayName: Daniel L


问:
fopen (php) from remote server works only for reading
I need to open a text file from a remote server and to write some information in it, using PHP fopen().

allow_url_fopen is ON (in my php.ini).

I can read this remote file, but can't write in it.

Code:

```<code><?php
$data = 'some text';
$filename = 'ftp://admin:password@192.168.254.1/web/domain.com/public_html/test2.txt';
$fh = fopen($filename, 'r');
echo fread($fh, filesize($filename));
fclose($fh);

$fh = fopen($filename, 'w+');
if ($fh) {
  echo 'remote file is opened, writing data';
  fwrite($fh, $data);
  fclose($fh);
} else {
  echo 'remote file not opened';
}
?>
</code>```

Shows:
some text
remote file not opened

What can i do make in write to file?

答:
PHP FTP URL wrapper does not support opening the file simultaneously for reading and writing. So you cannot use w+ mode (reading and writing). Use w mode (writing only).

Additionally, FTP URL wrapper does not allow overwriting of an existing file by default, you need to enable it using overwrite FTP context option.

```<code>$context = stream_context_create(['ftp' => ['overwrite' => true]]);
$fh = fopen($filename, 'w', false, $context);
</code>```

Though this will be all quite inefficient, as you will be opening whole FTP session twice. Once for reading and once for writing. You better use FTP functions ftp_get and ftp_put over one session.

Body:
I need to open a text file from a remote server and to write some information in it, using PHP fopen().

allow_url_fopen is ON (in my php.ini).

I can read this remote file, but can't write in it.

Code:

<?php
$data = 'some text';
$filename = 'ftp://admin:password@192.168.254.1/web/domain.com/public_html/test2.txt';
$fh = fopen($filename, 'r');
echo fread($fh, filesize($filename));
fclose($fh);

$fh = fopen($filename, 'w+');
if ($fh) {
  echo 'remote file is opened, writing data';
  fwrite($fh, $data);
  fclose($fh);
} else {
  echo 'remote file not opened';
}
?>

Shows:
some text
remote file not opened

What can i do make in write to file?

Body:
PHP FTP URL wrapper does not support opening the file simultaneously for reading and writing. So you cannot use w+ mode (reading and writing). Use w mode (writing only).

Additionally, FTP URL wrapper does not allow overwriting of an existing file by default, you need to enable it using overwrite FTP context option.

$context = stream_context_create(['ftp' => ['overwrite' => true]]);
$fh = fopen($filename, 'w', false, $context);

Though this will be all quite inefficient, as you will be opening whole FTP session twice. Once for reading and once for writing. You better use FTP functions ftp_get and ftp_put over one session.


问:
Separating expression in chaining comparison operator python
Can anyone explain, What exactly the exp1 and exp2 are doing? Kindly separate each case so it can understandable.</p>

```<code>a, b, c, d, e, f = 0, 5, 12, 0, 15, 15

exp1 = a <= b < c > d is not e is f
exp2 = a is d > f is not c

print(exp1)
print(exp2)
</code>```

答:
exp1 = a <= b < c > d is not e is f is evaluated as a<=b and b<c and c>d and d is not e and e is f.

Byte-code for both expressions is the same (dis module reference).

```<code>In [8]: import dis

In [9]: dis.dis('a <= b < c > d is not e is f')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 DUP_TOP
              6 ROT_THREE
              8 COMPARE_OP               1 (<=)
             10 JUMP_IF_FALSE_OR_POP    48
             12 LOAD_NAME                2 (c)
             14 DUP_TOP
             16 ROT_THREE
             18 COMPARE_OP               0 (<)
             20 JUMP_IF_FALSE_OR_POP    48
             22 LOAD_NAME                3 (d)
             24 DUP_TOP
             26 ROT_THREE
             28 COMPARE_OP               4 (>)
             30 JUMP_IF_FALSE_OR_POP    48
             32 LOAD_NAME                4 (e)
             34 DUP_TOP
             36 ROT_THREE
             38 COMPARE_OP               9 (is not)
             40 JUMP_IF_FALSE_OR_POP    48
             42 LOAD_NAME                5 (f)
             44 COMPARE_OP               8 (is)
             46 RETURN_VALUE
        >>   48 ROT_TWO
             50 POP_TOP
             52 RETURN_VALUE

In [10]: dis.dis('a<=b and b<c and c>d and d is not e and e is f')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 COMPARE_OP               1 (<=)
              6 JUMP_IF_FALSE_OR_POP    38
              8 LOAD_NAME                1 (b)
             10 LOAD_NAME                2 (c)
             12 COMPARE_OP               0 (<)
             14 JUMP_IF_FALSE_OR_POP    38
             16 LOAD_NAME                2 (c)
             18 LOAD_NAME                3 (d)
             20 COMPARE_OP               4 (>)
             22 JUMP_IF_FALSE_OR_POP    38
             24 LOAD_NAME                3 (d)
             26 LOAD_NAME                4 (e)
             28 COMPARE_OP               9 (is not)
             30 JUMP_IF_FALSE_OR_POP    38
             32 LOAD_NAME                4 (e)
             34 LOAD_NAME                5 (f)
             36 COMPARE_OP               8 (is)
        >>   38 RETURN_VALUE
</code>```

exp2 = a is d > f is not c is evaluated as a is d and d>f and f is not c. They both would produce the same byte-code.

Body:
Can anyone explain, What exactly the exp1 and exp2 are doing? Kindly separate each case so it can understandable.

a, b, c, d, e, f = 0, 5, 12, 0, 15, 15

exp1 = a <= b < c > d is not e is f
exp2 = a is d > f is not c

print(exp1)
print(exp2)

Body:
exp1 = a <= b < c > d is not e is f is evaluated as a<=b and b<c and c>d and d is not e and e is f.

Byte-code for both expressions is the same (dis module reference).

In [8]: import dis

In [9]: dis.dis('a <= b < c > d is not e is f')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 DUP_TOP
              6 ROT_THREE
              8 COMPARE_OP               1 (<=)
             10 JUMP_IF_FALSE_OR_POP    48
             12 LOAD_NAME                2 (c)
             14 DUP_TOP
             16 ROT_THREE
             18 COMPARE_OP               0 (<)
             20 JUMP_IF_FALSE_OR_POP    48
             22 LOAD_NAME                3 (d)
             24 DUP_TOP
             26 ROT_THREE
             28 COMPARE_OP               4 (>)
             30 JUMP_IF_FALSE_OR_POP    48
             32 LOAD_NAME                4 (e)
             34 DUP_TOP
             36 ROT_THREE
             38 COMPARE_OP               9 (is not)
             40 JUMP_IF_FALSE_OR_POP    48
             42 LOAD_NAME                5 (f)
             44 COMPARE_OP               8 (is)
             46 RETURN_VALUE
        >>   48 ROT_TWO
             50 POP_TOP
             52 RETURN_VALUE

In [10]: dis.dis('a<=b and b<c and c>d and d is not e and e is f')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 COMPARE_OP               1 (<=)
              6 JUMP_IF_FALSE_OR_POP    38
              8 LOAD_NAME                1 (b)
             10 LOAD_NAME                2 (c)
             12 COMPARE_OP               0 (<)
             14 JUMP_IF_FALSE_OR_POP    38
             16 LOAD_NAME                2 (c)
             18 LOAD_NAME                3 (d)
             20 COMPARE_OP               4 (>)
             22 JUMP_IF_FALSE_OR_POP    38
             24 LOAD_NAME                3 (d)
             26 LOAD_NAME                4 (e)
             28 COMPARE_OP               9 (is not)
             30 JUMP_IF_FALSE_OR_POP    38
             32 LOAD_NAME                4 (e)
             34 LOAD_NAME                5 (f)
             36 COMPARE_OP               8 (is)
        >>   38 RETURN_VALUE

exp2 = a is d > f is not c is evaluated as a is d and d>f and f is not c. They both would produce the same byte-code.


问:
Why is "" being injected into my HTML?
EDIT: You can see the issue here (look in source).

EDIT2: Interesting, it is not an issue in source. Only with the console (Firebug as well).

I have the following markup in a file called test.html:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Test Harness</title>
    <link href='/css/main.css' rel='stylesheet' type='text/css' />
</head>
<body>
    <h3>Test Harness</h3>
</body>
</html>
</code>```

But in Chrome, I see:

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
    "

        "
    <title>Test Harness</title>
    <link href='/css/main.css' rel='stylesheet' type='text/css' />
    <h3>Test Harness</h3>
</body>
</html>
</code>```

It looks like &#802 is a zero width space, but what is causing it? I am using Sublime Text 2 with UTF-8 encoding and Google App Engine with Jinja2 (but Jinja is simply loading test.html). Any thoughts?

Thanks in advance.

答:
This “8203;” HTML character is a no width break control.
It can easily find in the Google Chrome Browser inspect elements section. And When you try to remove it from your code, most of the Major IDE not showing to me...(Maybe by my preference).

I found the new text editor Brackets download it and open my code in the editor. It shows the character with red dots. Just remove it check everything is working well.

I found this solution from a blog. What is “8203” HTML character? Why is being injected into my HTML?

Thank You for saving me hours.

ContentLicense: CC BY-SA 3.0

Title: Why is "" being injected into my HTML?

Body:
EDIT: You can see the issue here (look in source).

EDIT2: Interesting, it is not an issue in source. Only with the console (Firebug as well).

I have the following markup in a file called test.html:

<!DOCTYPE html>

    <title>Test Harness</title>
    <link href='/css/main.css' rel='stylesheet' type='text/css' />

Test Harness

But in Chrome, I see:

<!DOCTYPE html>

    "

        "
    <title>Test Harness</title>
    <link href='/css/main.css' rel='stylesheet' type='text/css' />

Test Harness

It looks like &#802 is a zero width space, but what is causing it? I am using Sublime Text 2 with UTF-8 encoding and Google App Engine with Jinja2 (but Jinja is simply loading test.html). Any thoughts?

Thanks in advance.


问:
location of .htaccess in bitnami wordpress
i am not able to find the location of .htaccess file in bitnami wordpress. Need to enable content scripting policy in .htaccess file. But this file doesnot exits in nginx bitnami wordpress. Could anyone please help to resolve.</p>

答:
Bitnami Engineer here,

The .htaccess files are used by Apache to modify the configuration of the application per directory. We do not suggest any user use them because of security and performance reasons. However, you are asking about the WordPress with NGINX solution. NGINX doesn't make use of the .htaccess files so if your plugin/theme needs any custom configuration, you will need to include it inside the NGINX conf. There is a specific configuration file for WordPress at /opt/bitnami/apps/wordpress/conf/nginx-app.conf.

I hope this information helps.


问:
Higher order FRP with React - why is it not happening?
Redux is a kind of first order FRP, like Elm used to be.

It seems however that higher order FRP is not really being used together with react.

Why is first order FRP useful with React and higher order not so useful ?

Maybe higher-order-ism is not needed with React ? So in return one can keep the time travelling debugger ?

In other words:

React is a function that takes a state and gives back a view.

FRP is a way to declare and execute a state machine.

These are orthogonal concerns, so why not combine them ?

EDIT:

If i compare this https://github.com/ochrons/diode/tree/master/examples/todomvc/src/main/scala/example

with this https://github.com/lihaoyi/workbench-example-app/blob/todomvc/src/main/scala/example/ScalaJSExample.scala

Then it seems that the same application using scala.rx is half as many lines of code... than with Diode (Redux like uni-directional data-flow library).

EDIT 2:

My guess - why it is not happening - is that most of the higher order frp folks (who want to use higher order FRP in web development) use reflex-frp, and they use reflex-dom instead of react. Probably reflex-dom makes react unnecessary.

答:
It is happening now, it is here. I wrote a super simple, experimental, "web framework", which combines Sodium FRP, React and Scala.js.

I like it. I write code, I compile it, it works. Very experimental tech though, cutting edge FP stuff. It's the real deal. No compromises FRP.


问:
Running as user 'root' is a security risk, aborting
I was following this link:

http://www.mindissoftware.com/2014/09/11/Run-Odoo-in-PyCharm-Ubuntu/

I changed the openerp-server.conf file and run the Database located at another machine using host address.

When I run the odoo in Pycharm it throws the error as

Running as user 'root' is a security risk, aborting.

Please help me

答:
SnippetBucket Expert for Odoo

```<code>Running as user 'root' is a security risk, aborting.
</code>```

Odoo rules:
1. Odoo can't run with root user, Its because of good govern of ERP Security
2. Odoo - Postgresql, You should not use "postgres" user to run odoo, instead create superuser of postgresql and connect it.

For pycharm, make sure you not run pycharm with root or pycharm don't operate terminal under root. Desktop specific stuff.

Its better to create desktop user, with same name create postgresql super user.
than with newly created desktop user use pycharm. make better to work with odoo.

G-Edit editor and plugins are my favoite editor, keep less memory and works faster. G-Edit Odoo Snippets gives faster to work.

Thanks

SnippetBucket.com

Body:
SnippetBucket Expert for Odoo

Running as user 'root' is a security risk, aborting.

Odoo rules:
1. Odoo can't run with root user, Its because of good govern of ERP Security
2. Odoo - Postgresql, You should not use "postgres" user to run odoo, instead create superuser of postgresql and connect it.

For pycharm, make sure you not run pycharm with root or pycharm don't operate terminal under root. Desktop specific stuff.

Its better to create desktop user, with same name create postgresql super user.
than with newly created desktop user use pycharm. make better to work with odoo.

G-Edit editor and plugins are my favoite editor, keep less memory and works faster. G-Edit Odoo Snippets gives faster to work.

Thanks

SnippetBucket.com


问:
Gradle DSL method not found when updating application version
I want to update my app on google play store, it can't accept the updated file with the same version.

Do I've changed the version from build.gradle file :

```<code>android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "net.koorasudan.app"
    minSdkVersion 14
    targetSdkVersion 21
    versionCode 5.1
    versionName "5.1"
}
buildTypes {
    release {
           minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
</code>```

But when I sync the gradle it shows me this error :

Error:(23, 0) Gradle DSL method not found: 'versionCode()'
  Possible causes:
The project 'SmartView 3' may be using a version of Gradle that does not contain the method.
  Open Gradle wrapper file

The build file may be missing a Gradle plugin.
  Apply Gradle plugin

How to solve this problem?

答:
just use version code 2, do not use version code 2.0 or any float value

versionCode 2

```<code>    versionName "2.0"
</code>```

like this and rebuild the app, it will solve your problem

Body:
I want to update my app on google play store, it can't accept the updated file with the same version.

Do I've changed the version from build.gradle file :

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "net.koorasudan.app"
    minSdkVersion 14
    targetSdkVersion 21
    versionCode 5.1
    versionName "5.1"
}
buildTypes {
    release {
           minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

But when I sync the gradle it shows me this error :

Error:(23, 0) Gradle DSL method not found: 'versionCode()'
  Possible causes:
The project 'SmartView 3' may be using a version of Gradle that does not contain the method.
  Open Gradle wrapper file

The build file may be missing a Gradle plugin.
  Apply Gradle plugin

How to solve this problem?

Body:
just use version code 2, do not use version code 2.0 or any float value

versionCode 2

    versionName "2.0"

like this and rebuild the app, it will solve your problem


问:
Finding all instances of a string within a string
What is a way that I can find (and loop through) all instances of a string within another string in lua? For example, if I have the string

```<code>"honewaidoneaeifjoneaowieone"
</code>```

And I want to loop through all instances (and by this, I mean indexes) of "one" within that string, well, I can see that it appears four times, but I have no clue how to actually find them. I know that string.find() can find the first instance, but that doesn't help me very much.

答:
local str = "honewaidoneaeifjoneaowieone"

-- This one only gives you the substring;
-- it doesn't tell you where it starts or ends
for substring in str:gmatch 'one' do
   print(substring)
end

-- This loop tells you where the substrings
-- start and end. You can use these values in
-- string.find to get the matched string.
local first, last = 0
while true do
   first, last = str:find("one", first+1)
   if not first then break end
   print(str:sub(first, last), first, last)
end

-- Same as above, but as a recursive function
-- that takes a callback and calls it on the
-- result so it can be reused more easily
local function find(str, substr, callback, init)
   init = init or 1
   local first, last = str:find(substr, init)
   if first then
       callback(str, first, last)
       return find(str, substr, callback, last+1)
   end
end

find(str, 'one', print)
```

Body:
What is a way that I can find (and loop through) all instances of a string within another string in lua? For example, if I have the string

"honewaidoneaeifjoneaowieone"

And I want to loop through all instances (and by this, I mean indexes) of "one" within that string, well, I can see that it appears four times, but I have no clue how to actually find them. I know that string.find() can find the first instance, but that doesn't help me very much.


问:
Complex collection to use as a datasource for a gridview
I'm deserializing data from an XML file in order to show the data in a gridview.
Here is the XML file content:

```<code><Params>
   <Param name="Paramètre #1">
      <Value> 1.1 </Value>
      <Value> 1.2 </Value>
      <Value> 1.3 </Value>
   </Param>
   <Param name="Paramètre #2">
      <Value> 2.1 </Value>
      <Value> 2.2 </Value>
   </Param>
   <Param name="Paramètre #3">
      <Value> 3.1 </Value>
      <Value> 3.2 </Value>
      <Value> 3.3 </Value>
      <Value> 3.4 </Value>
   </Param>
</Params>
</code>```

I would like the gridview to rend like this:

All i've been able to do is this:

Is there a way to store any value of a parameter in a column whatever the number of values of a parameter?

Here is the Markup:

```<code><html lang="fr">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
    <form runat="server">
        <asp:Label runat="server" ID="Lb" ></asp:Label>
        <asp:GridView runat="server" ID="Gdv" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField HeaderText="Parameters" DataField="Name"></asp:BoundField>
                <asp:TemplateField HeaderText="Values">
                    <ItemTemplate>
                        <asp:Label ID="LbGrid" runat="server" Text="<%# GetValues(Container.DataItem) %>"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>
</body>
</html>
</code>```

And here is the code-behind:

```<code>public partial class SiteMaster : MasterPage
{
    List<Param> Parameters { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(@"D:\Utilisateurs\valen\Desktop\ParamsTab\XML\Main.xml");
        XmlSerializer deserializer = new XmlSerializer(typeof(List<Param>), new XmlRootAttribute("Params"));
        Parameters = (List<Param>)deserializer.Deserialize(sr);
        Gdv.DataSource = Parameters;
        Gdv.DataBind();
        sr.Close();
    }
    public string GetValues(object param)
    {
        Param parameter = (Param)param;
        string values = string.Empty;
        values += string.Join(",", parameter.Values);
        return values;
    }
}
</code>```

And here is the class used as a datasource:

```<code>public class Param
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlElement("Value")]
    public List<string> Values { get; set; }
}
</code>```

答:
First, thank you very much for the reply.
All your solutions work well for a Datagrid. But not in case of a Gridview.
Actually, i continued to search and i found that i just had to add ItemTemplate in the code-behind. I haven't find how to do it yet, so if you have a solution, i'd be glad to take it.
Thank you all</p>

Body:
I'm deserializing data from an XML file in order to show the data in a gridview.
Here is the XML file content:

<Params>
   <Param name="Paramètre #1">
      <Value> 1.1 </Value>
      <Value> 1.2 </Value>
      <Value> 1.3 </Value>
   </Param>
   <Param name="Paramètre #2">
      <Value> 2.1 </Value>
      <Value> 2.2 </Value>
   </Param>
   <Param name="Paramètre #3">
      <Value> 3.1 </Value>
      <Value> 3.2 </Value>
      <Value> 3.3 </Value>
      <Value> 3.4 </Value>
   </Param>
</Params>

I would like the gridview to rend like this:

All i've been able to do is this:

Is there a way to store any value of a parameter in a column whatever the number of values of a parameter?

Here is the Markup:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <form runat="server">
        <asp:Label runat="server" ID="Lb" ></asp:Label>
        <asp:GridView runat="server" ID="Gdv" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField HeaderText="Parameters" DataField="Name"></asp:BoundField>
                <asp:TemplateField HeaderText="Values">
                    <ItemTemplate>
                        <asp:Label ID="LbGrid" runat="server" Text="<%# GetValues(Container.DataItem) %>"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>

And here is the code-behind:

public partial class SiteMaster : MasterPage
{
    List<Param> Parameters { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(@"D:\Utilisateurs\valen\Desktop\ParamsTab\XML\Main.xml");
        XmlSerializer deserializer = new XmlSerializer(typeof(List<Param>), new XmlRootAttribute("Params"));
        Parameters = (List<Param>)deserializer.Deserialize(sr);
        Gdv.DataSource = Parameters;
        Gdv.DataBind();
        sr.Close();
    }
    public string GetValues(object param)
    {
        Param parameter = (Param)param;
        string values = string.Empty;
        values += string.Join(",", parameter.Values);
        return values;
    }
}

And here is the class used as a datasource:

public class Param
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlElement("Value")]
    public List<string> Values { get; set; }
}


问:
In Rails, execute block for both conditions: first_or_create
Anybody know a Rails method that will allow me to look for an existing record or create a new one AND execute a subsequent block of code?

Example:

```<code>Model.where(parameters).first_or_create do |m|
  # execute this regardless of whether record exists or not
end
</code>```

Similarly, the method find_or_create_by does not execute a block in either scenario.

I could use if-else statements but that will duplicate my code...

答:
@eric you need to save data before closing the block.

Model.where(parameters).first_or_create.tap do |m|
   # execute this regardless of whether record exists or not

   m.save
end
```

Body:
Anybody know a Rails method that will allow me to look for an existing record or create a new one AND execute a subsequent block of code?

Example:

Model.where(parameters).first_or_create do |m|
  # execute this regardless of whether record exists or not
end

Similarly, the method find_or_create_by does not execute a block in either scenario.

I could use if-else statements but that will duplicate my code...


问:
What is the correct way to set State according to fetch data?
I did search about this but I could not find explanation which way should be valid and followed.

If we want to add new data our state , for sure we are using immutable way like map the entire data to create new array or filter to delete and so on. However I cannot figure out which way is appropriate when data is fetched from server and why? Do I really need to iterate entire array or create deep copy of object?

Way 1

```<code>const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        const newData = [];
        myJson.forEach(item => newData.push(item));
        setData(newData);
      });
  }, []);
</code>```

Way 2

```<code>const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        setData(myJson);
      });
  }, []);
</code>```

答:
In class components, we have state object which we are updating and getting values from. In that case, immutable state could be a concern.

In functional components, you can get over immutable state because we are referring to a single entity/value at a time. So, your second code sample would be a good way to go.

```<code>const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        setData(myJson);
      });
  }, []);
</code>```

Body:
I did search about this but I could not find explanation which way should be valid and followed.

If we want to add new data our state , for sure we are using immutable way like map the entire data to create new array or filter to delete and so on. However I cannot figure out which way is appropriate when data is fetched from server and why? Do I really need to iterate entire array or create deep copy of object?

Way 1

const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        const newData = [];
        myJson.forEach(item => newData.push(item));
        setData(newData);
      });
  }, []);

Way 2

const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        setData(myJson);
      });
  }, []);

Body:
In class components, we have state object which we are updating and getting values from. In that case, immutable state could be a concern.

In functional components, you can get over immutable state because we are referring to a single entity/value at a time. So, your second code sample would be a good way to go.

const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        setData(myJson);
      });
  }, []);


问:
Extending JOOQ Record
Does Jooq generator supports extending custom class as provided to generator?

I would like to generate Records that extend custom provided class which will extend TableRecordImpl.

I would like to get into the inheritance chain where UpdatableRecordImpl will extend MyRecord and MyRecord will extend TableRecordImpl?

答:
For most such cases, you can specify a generator strategy:

Programmatic

Configurative

However, this isn't currently possible for TableRecordImpl subtypes. It probably should be possible. I've created a feature request: https://github.com/jOOQ/jOOQ/issues/9844.

You can, however, let the records implement your own set of interfaces (see again above links for details), and generate the interface implementation in your records using a custom code section.

Title: Extending JOOQ Record


问:
Does a pointer need to be nulled after it is freed?
```<code>int main(){

(int*) pointer = (int*) malloc(sizeof(int));
free(pointer);

}
</code>```

I learned from 'Prata, Stephen. C Primer Plus (Developer's Library)' that
"When the function terminates, the pointer, being an automatic variable, disappears."  so simply, i don't need to null the pointer

however, I also learned from school that the pointer becomes a dangling pointer if it doesn't get nulled after it free.

Two ideas are contradicting each other. Which one is the right one?

答:
According to the docs:

The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

Therefore, you don't need to set pointer to nullptr (in C++11) or NULL (in C and before C++11) if it goes out of scope immediately after you free it because then you have no chance to dereference a dangling pointer.

However, if the pointer is still in the scope after a call to free, than the good practice would be to set it to nullptr or NULL so that the following checks would work:

C++:

if (nullptr != ptr) {...}
```

<p><strong>C:</strong></p>

<pre class="lang-c prettyprint-override"><code>if (NULL != ptr) {...}
</code>```

C and C++:

if (!ptr) {...}
```

Body:
int main(){

(int*) pointer = (int*) malloc(sizeof(int));
free(pointer);

}

I learned from 'Prata, Stephen. C Primer Plus (Developer's Library)' that
"When the function terminates, the pointer, being an automatic variable, disappears."  so simply, i don't need to null the pointer

however, I also learned from school that the pointer becomes a dangling pointer if it doesn't get nulled after it free.

Two ideas are contradicting each other. Which one is the right one?

Body:
According to the docs:

The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

Therefore, you don't need to set pointer to nullptr (in C++11) or NULL (in C and before C++11) if it goes out of scope immediately after you free it because then you have no chance to dereference a dangling pointer.

However, if the pointer is still in the scope after a call to free, than the good practice would be to set it to nullptr or NULL so that the following checks would work:

C++:

if (nullptr != ptr) {...}

C:

if (NULL != ptr) {...}

C and C++:

if (!ptr) {...}


问:
How to apply multiple functions to a dataframe efficiently?
I'm trying to apply multiple functions to my pandas dataframes, which is being called from other internal scripts. However, when applying them, the code get really long and I think that isn't a good engineering practice in general:

```<code>df['data_udo_product_brand_mode'] = df['data_udo_product_brand'].fillna(
        '[]').apply(think_preprocessing.create_list).apply(think_math.get_mode).apply(lambda x: x.strip('"').lower())
</code>```

Is there a more efficient and better way to apply multiple functions to a dataframe/dataframe columns than the above way?

Thanks in advance!

答:
Possibly there may be a way, but one thing can be done here that the lambda function can be separated out so to get rid from the code getting long .For example:</p>

```<code>#Lowering character and removing spaces
strip_lower = lambda x: x.strip('"').lower()

df['data_udo_product_brand_mode']=df['data_udo_product_brand'].fillna('[]').apply(think_preprocessing.create_list).apply(think_math.get_mode).apply(strip_lower)
</code>```

Body:
I'm trying to apply multiple functions to my pandas dataframes, which is being called from other internal scripts. However, when applying them, the code get really long and I think that isn't a good engineering practice in general:

df['data_udo_product_brand_mode'] = df['data_udo_product_brand'].fillna(
        '[]').apply(think_preprocessing.create_list).apply(think_math.get_mode).apply(lambda x: x.strip('"').lower())

Is there a more efficient and better way to apply multiple functions to a dataframe/dataframe columns than the above way?

Thanks in advance!

Body:
Possibly there may be a way, but one thing can be done here that the lambda function can be separated out so to get rid from the code getting long .For example:

#Lowering character and removing spaces
strip_lower = lambda x: x.strip('"').lower()

df['data_udo_product_brand_mode']=df['data_udo_product_brand'].fillna('[]').apply(think_preprocessing.create_list).apply(think_math.get_mode).apply(strip_lower)


问:
BFS in binary tree
I'm trying to write the codes for breadth-first search in binary tree. I've stored all the data in a queue, but I can't figure out how to travel to all nodes and consume all their children.

Here's my code in C:

```<code>void breadthFirstSearch (btree *bt, queue **q) {
   if (bt != NULL) {

      //store the data to queue if there is

      if (bt->left != NULL) enqueue (q, bt->left->data);
      if (bt->right != NULL) enqueue (q, bt->right->data);

      //recursive

      if (bt->left != NULL) breadthFirstSearch (bt->left, q);
      if (bt->right != NULL) breadthFirstSearch (bt->right, q);
   }
}
</code>```

I've already enqueued the root data, but it's still not working.
Can anyone point out my mistake?

答:
A BFS can be easily written without recursion. Just use a queue to order your expansions:

```<code>void BFS(btree *start)
{
    std::deque<btree *> q;
    q.push_back(start);
    while (q.size() != 0)
    {
        btree *next = q.front();
        // you may want to print the current node here or do other processing
        q.pop_front();
        if (next->left)
            q.push_back(next->left);
        if (next->right)
            q.push_back(next->right);
    }
}
</code>```

The key is that you don't need to traverse the tree recursively; you just let your data structure handle the order in which you visit nodes.

Note that I'm using the C++ deque here, but anything that lets you put items on the back and get them from the front will work fine.

Title: BFS in binary tree

Body:
I'm trying to write the codes for breadth-first search in binary tree. I've stored all the data in a queue, but I can't figure out how to travel to all nodes and consume all their children.

Here's my code in C:

void breadthFirstSearch (btree *bt, queue **q) {
   if (bt != NULL) {

      //store the data to queue if there is

      if (bt->left != NULL) enqueue (q, bt->left->data);
      if (bt->right != NULL) enqueue (q, bt->right->data);

      //recursive

      if (bt->left != NULL) breadthFirstSearch (bt->left, q);
      if (bt->right != NULL) breadthFirstSearch (bt->right, q);
   }
}

I've already enqueued the root data, but it's still not working.
Can anyone point out my mistake?

Body:
A BFS can be easily written without recursion. Just use a queue to order your expansions:

void BFS(btree *start)
{
    std::deque<btree *> q;
    q.push_back(start);
    while (q.size() != 0)
    {
        btree *next = q.front();
        // you may want to print the current node here or do other processing
        q.pop_front();
        if (next->left)
            q.push_back(next->left);
        if (next->right)
            q.push_back(next->right);
    }
}

The key is that you don't need to traverse the tree recursively; you just let your data structure handle the order in which you visit nodes.

Note that I'm using the C++ deque here, but anything that lets you put items on the back and get them from the front will work fine.


问:
Git discard all changes
Hi folks I am new developer trying to learn.

I use git desktop where you right click on a file and select discard changes, if you don't want to add that file into commit. It revert it back to its original state.

Now I am working in terminal how can I do that in terminal?

By mistake I added some changes into a file and I don't want to keep those changes. Please help.

Please, I am not an advanced user therefore kindly keep it as simple as possible. I have not made any commit on that machine yet.

I am only interested in I googled it but could not find a simple layman'ish answer.

答:
You can simply use:

```<code>git checkout -- path/to/file
</code>```

The -- is so that the filename or path cannot be inferred as a branch or remote/branch.

Title: Git discard all changes

Body:
You can simply use:

git checkout -- path/to/file

The -- is so that the filename or path cannot be inferred as a branch or remote/branch.


问:
HTTP Session: how to configure URLs that not change the session expiration?
I have in my application polling HTTP requests that executed each 5 minutes.

I want to configure those URLs not to change the session expiration.
Otherwise my session will never expired (and I do not want it).
Was not able to find it in the web.xml and HttpSession documentation.

How is possible to do it?

Added

Very important clarification: the request should be authenticated.
It means that the request should be attached to JsessionID that is already authenticated.

Clarification (Added 2)

I do not want the session will expire regardless of whether the user stays active or not.  I want the session will expire on the user inactivity and will not be expire if user working on UI. I want the session will expire on the user inactivity in spite of polling requests that come each 5 minutes

答:
This is the updated answer @BalusC. His solution is not fully work for me. Try this solution.</p>

```<code>@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        int expireTimeInSeconds = 60;

        String skippableUrl = "/url";

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        int maxInactiveInterval = session.getMaxInactiveInterval();

        if (request.getRequestURI().equals(request.getContextPath() + skippableUrl )) {

            long lastAccessedTime = session.getLastAccessedTime();
            long currentTime = System.currentTimeMillis();
            int newMaxInactiveInterval = maxInactiveInterval - (int) ((currentTime - lastAccessedTime) / 1000);

            if (newMaxInactiveInterval <= 0 || maxInactiveInterval > expireTimeInSeconds) {
                session.invalidate();
            } else {
                session.setMaxInactiveInterval(newMaxInactiveInterval);
            }

        } else {
            session.setMaxInactiveInterval(expireTimeInSeconds);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
</code>```

Body:
This is the updated answer @BalusC. His solution is not fully work for me. Try this solution.

@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        int expireTimeInSeconds = 60;

        String skippableUrl = "/url";

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        int maxInactiveInterval = session.getMaxInactiveInterval();

        if (request.getRequestURI().equals(request.getContextPath() + skippableUrl )) {

            long lastAccessedTime = session.getLastAccessedTime();
            long currentTime = System.currentTimeMillis();
            int newMaxInactiveInterval = maxInactiveInterval - (int) ((currentTime - lastAccessedTime) / 1000);

            if (newMaxInactiveInterval <= 0 || maxInactiveInterval > expireTimeInSeconds) {
                session.invalidate();
            } else {
                session.setMaxInactiveInterval(newMaxInactiveInterval);
            }

        } else {
            session.setMaxInactiveInterval(expireTimeInSeconds);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }


问:
How to Create Certificate Signing Request on Windows 10 For Apple
Operating System of My Computer is Windows 10. And I am coding with React Native.
I want to Create Certificate Signing Request for download Certificate in Apple Developer System .
How can I create in Windows . I try to;

```<code>#openssl genrsa -out mykey.key 2018

#openssl req -new -key mykey.key -out myCSR.certSigningRequest -subj "/emailAddress=ublablavla@bla.com, CN=Umut, C=TR"
</code>```

and when I want to upload to Apple Developer Account page , system give me a error ;

Invalid Certificate

答: I solved this problem . Before I was using Edge Browser . But Now I am using Firefox Browser and I can upload the file .</p>

Body:
Operating System of My Computer is Windows 10. And I am coding with React Native.
I want to Create Certificate Signing Request for download Certificate in Apple Developer System .
How can I create in Windows . I try to;

#openssl genrsa -out mykey.key 2018

#openssl req -new -key mykey.key -out myCSR.certSigningRequest -subj "/emailAddress=ublablavla@bla.com, CN=Umut, C=TR"

and when I want to upload to Apple Developer Account page , system give me a error ;

Invalid Certificate


问:
NameError: name 'Model' is not defined after importing models in a newly created file
I have created a file called utilities.py within a Django app but I'm getting errors after importing a model from the same app in the file. This is weird because the same file is within the app, I should not be getting that error. Please advise on this.

Here is a screenshot showing where the file is located.

Models

```<code>from django.utils import timezone
from django_smalluuid.models import SmallUUIDField, uuid_default
from django.db import models
import pytz
from .utilities import (calc_expiry_date,convert_date)
from monthdelta import monthdelta

class LiquorCostCentre(models.Model):
    cost_centre_id = models.CharField(max_length=250,null=True,blank=True,default="0304-05-05")
    cost_centre_name = models.CharField(max_length=250,null=True,blank=True)
</code>```

utilities.py

```<code>from .models import *

def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    cost_centre_obj, _ = LiquorCostCentre.objects.get_or_create(cost_centre_id=cost_centre)
    bill = LiqourBillTrack.objects.create(
        fee_choice=schedule_type,
        bill_type=bill_type,
        cost_centre=cost_centre_obj.cost_centre_id,
        balance=float(              amount),
        description=description,
        created_by=user,
        year=CURRENT_YEAR,
        liquor_license= liquor_license

    )
    [bill.accounts.add(account_number) for account_number in account_number_list]
    account_values = []
    account_list = bill.accounts.all()
    account_total = [account_values.append(acc_value.amount) for acc_value in account_list ]

    bill_total =sum(account_values)
    bill.total = bill_total
    bill.balance = bill_total
    bill.ref_no = 'LIQ-' + str(NOW.year) + str(NOW.month)+ str(bill.id)
    bill.bill_no = bill.ref_no
    bill.save()
    return bill
</code>```

Error

```<code>eb_1         |   File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
web_1         |     __import__(module)
web_1         |   File "/app/core/wsgi.py", line 16, in <module>
web_1         |     application = get_wsgi_application()
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
web_1         |     django.setup(set_prefix=False)
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
web_1         |     apps.populate(settings.INSTALLED_APPS)
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate
web_1         |     app_config.import_models()
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models
web_1         |     self.models_module = import_module(models_module_name)
web_1         |   File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
web_1         |     return _bootstrap._gcd_import(name[level:], package, level)
web_1         |   File "/app/liquor/models.py", line 10, in <module>
web_1         |     from .utilities import (calc_expiry_date,convert_date)
web_1         |   File "/app/liquor/utilities.py", line 2, in <module>
web_1         |     from liquor.models import LiquorCostCentre
web_1         | ImportError: cannot import name 'LiquorCostCentre' from 'liquor.models' (/app/liquor/models.py)
web_1         | [2020-02-17 11:19:23 +0300] [17] [INFO] Worker exiting (pid: 17)
web_1         | Sentry is attempting to send 0 pending error messages
web_1         | Waiting up to 2 seconds
web_1         | Press Ctrl-C to quit
web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Shutting down: Master
web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Reason: Worker failed to boot.
</code>```

答:
To fix your trouble(cross imports) you need to make import inside functions:

```<code>def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    from .models import LiquorCostCentre, LiqourBillTrack
    # YOUR CODE HERE
</code>```

and REMOVE import * from top of the utilities.py
and of cause if you need some others models in your utilities code, put they import inside functions.

Body:
I have created a file called utilities.py within a Django app but I'm getting errors after importing a model from the same app in the file. This is weird because the same file is within the app, I should not be getting that error. Please advise on this.

Here is a screenshot showing where the file is located.

Models

from django.utils import timezone
from django_smalluuid.models import SmallUUIDField, uuid_default
from django.db import models
import pytz
from .utilities import (calc_expiry_date,convert_date)
from monthdelta import monthdelta

class LiquorCostCentre(models.Model):
    cost_centre_id = models.CharField(max_length=250,null=True,blank=True,default="0304-05-05")
    cost_centre_name = models.CharField(max_length=250,null=True,blank=True)

utilities.py

from .models import *

def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    cost_centre_obj, _ = LiquorCostCentre.objects.get_or_create(cost_centre_id=cost_centre)
    bill = LiqourBillTrack.objects.create(
        fee_choice=schedule_type,
        bill_type=bill_type,
        cost_centre=cost_centre_obj.cost_centre_id,
        balance=float(              amount),
        description=description,
        created_by=user,
        year=CURRENT_YEAR,
        liquor_license= liquor_license

    )
    [bill.accounts.add(account_number) for account_number in account_number_list]
    account_values = []
    account_list = bill.accounts.all()
    account_total = [account_values.append(acc_value.amount) for acc_value in account_list ]

    bill_total =sum(account_values)
    bill.total = bill_total
    bill.balance = bill_total
    bill.ref_no = 'LIQ-' + str(NOW.year) + str(NOW.month)+ str(bill.id)
    bill.bill_no = bill.ref_no
    bill.save()
    return bill

Error

eb_1         |   File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
web_1         |     __import__(module)
web_1         |   File "/app/core/wsgi.py", line 16, in <module>
web_1         |     application = get_wsgi_application()
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
web_1         |     django.setup(set_prefix=False)
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
web_1         |     apps.populate(settings.INSTALLED_APPS)
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate
web_1         |     app_config.import_models()
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models
web_1         |     self.models_module = import_module(models_module_name)
web_1         |   File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
web_1         |     return _bootstrap._gcd_import(name[level:], package, level)
web_1         |   File "/app/liquor/models.py", line 10, in <module>
web_1         |     from .utilities import (calc_expiry_date,convert_date)
web_1         |   File "/app/liquor/utilities.py", line 2, in <module>
web_1         |     from liquor.models import LiquorCostCentre
web_1         | ImportError: cannot import name 'LiquorCostCentre' from 'liquor.models' (/app/liquor/models.py)
web_1         | [2020-02-17 11:19:23 +0300] [17] [INFO] Worker exiting (pid: 17)
web_1         | Sentry is attempting to send 0 pending error messages
web_1         | Waiting up to 2 seconds
web_1         | Press Ctrl-C to quit
web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Shutting down: Master
web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Reason: Worker failed to boot.

Body:
To fix your trouble(cross imports) you need to make import inside functions:

def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    from .models import LiquorCostCentre, LiqourBillTrack
    # YOUR CODE HERE

and REMOVE import * from top of the utilities.py
and of cause if you need some others models in your utilities code, put they import inside functions.