Example #1
0
        public void Test_Perceptron_Simple_2()
        {
            PerceptronGenerator generator = new PerceptronGenerator();
            Matrix x = new[,]{
                { 1, 4 }, // yes
                { -1, 3 }, // no
                { -1, 2 }, // no
                { -1, 1 }, // no
                { -2, 1 }, // no
                { -2, 2 }, // no
                { 2, 3 }, // yes
                { 3, 2 }, // yes
                { 3, 3 }, // yes
                { 4, 2 }, // yes
                { 4, 1 }, // yes
            };

            var test = x.Copy();

            Vector y = new[] { 1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1 };

            var model = generator.Generate(x, y);

            Vector z = Vector.Zeros(11);

            for (int i = 0; i < test.Rows; i++)
                z[i] = model.Predict((Vector)test.Row(i)) <= 0 ? -1 : 1;

            Assert.AreEqual(y, z);
        }
 public void Copy_CopiesValues()
 {
     int[] a1 = new[] { 1, 2, 3 };
     int[] a2 = a1.Copy();
     Assert.AreEqual(a1[0], a2[0]);
     Assert.AreEqual(a1[1], a2[1]);
     Assert.AreEqual(a1[2], a2[2]);
 }
Example #3
0
        public void CopyTestCase1ArgumentException()
        {
            Array array = new[]
            {
                "0",
                "1",
                "2",
                "3"
            };
            var destinationArray = new String[2];
            Action test = () => array.Copy( 0, destinationArray, 1, 20 );

            test.ShouldThrow<ArgumentException>();
        }
Example #4
0
        public void CopyTestCase1()
        {
            Array array = new[]
            {
                "0",
                "1",
                "2",
                "3"
            };
            var destinationArray = new String[2];
            array.Copy( 1, destinationArray, 0, 2 );

            Assert.AreEqual( "1", destinationArray[0] );
            Assert.AreEqual( "2", destinationArray[1] );
        }
Example #5
0
        public void CopyTestCase()
        {
            Array array = new[]
            {
                "0",
                "1",
                "2"
            };
            var destinationArray = new String[3];
            array.Copy( destinationArray, 3 );

            Assert.AreEqual( "0", destinationArray[0] );
            Assert.AreEqual( "1", destinationArray[1] );
            Assert.AreEqual( "2", destinationArray[2] );
        }
 public PolicyStatement(System.Security.PermissionSet permSet, PolicyStatementAttribute attributes)
 {
     if (permSet == null)
     {
         this.m_permSet = new System.Security.PermissionSet(false);
     }
     else
     {
         this.m_permSet = permSet.Copy();
     }
     if (ValidProperties(attributes))
     {
         this.m_attributes = attributes;
     }
 }
 private PolicyStatement(System.Security.PermissionSet permSet, PolicyStatementAttribute attributes, bool copy)
 {
     if (permSet != null)
     {
         if (copy)
         {
             this.m_permSet = permSet.Copy();
         }
         else
         {
             this.m_permSet = permSet;
         }
     }
     else
     {
         this.m_permSet = new System.Security.PermissionSet(false);
     }
     this.m_attributes = attributes;
 }
 protected CodeGroup(IMembershipCondition membershipCondition, System.Security.Policy.PolicyStatement policy)
 {
     if (membershipCondition == null)
     {
         throw new ArgumentNullException("membershipCondition");
     }
     if (policy == null)
     {
         this.m_policy = null;
     }
     else
     {
         this.m_policy = policy.Copy();
     }
     this.m_membershipCondition = membershipCondition.Copy();
     this.m_children = ArrayList.Synchronized(new ArrayList());
     this.m_element = null;
     this.m_parentLevel = null;
 }
Example #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Cryptkeeper" /> class.
        /// </summary>
        /// <param name="passphrase">The encryption key or passphrase represented in a SecureString. This is the preferred method of instantiating this class because it protects the key in memory.</param>
        public Cryptkeeper(System.Security.SecureString passphrase)
        {
            string err = "Cryptkeeper passphrase must be 16 characters (128-bit encryption) or 32 characters (256-bit) in length.";

            if (passphrase == null) throw new ApplicationException(err);
            if (passphrase.Length == 0) throw new ApplicationException(err);

            if (passphrase.Length > 1 && passphrase.Length <= 16)
            {
                this.keysize = 128; // 128 bits is 16 bytes or 16 characters in UTF8
                this.keyString = passphrase.Copy();
                return;
            }

            if (passphrase.Length > 16 && passphrase.Length <= 32)
            {
                this.keysize = 256; // 256 bits is 32 bytes or 32 characters in UTF8
                this.keyString = passphrase.Copy();
                return;
            }

            if (passphrase.Length > 32) throw new ApplicationException(err);
        }
Example #10
0
        public void Test_Perceptron_Simple()
        {
            PerceptronGenerator generator = new PerceptronGenerator();
            Matrix x =  new[,]
            {
                { 1, 0, 0 },
                { 1, 0, 1 },
                { 1, 1, 0 },
                { 1, 1, 1 }
            };

            var test = x.Copy();

            Vector y = new [] { 1, 1, -1, -1 };

            var model = generator.Generate(x, y);

            Vector z = Vector.Zeros(4);

            for (int i = 0; i < test.Rows; i++)
                z[i] = model.Predict((Vector)test.Row(i)) <= 0 ? -1 : 1;

            Assert.AreEqual(y, z);
        }
Example #11
0
        public void Linear_Regression_Test_House_Predictions_Normal()
        {
            // test house prices based on ft-sq and no# bedrooms
            Matrix x = new [,]
                {
                    {2104, 3},
                    {1600, 3},
                    {2400, 3},
                    {1416, 2},
                    {3000, 4},
                    {1985, 4},
                    {1534, 3},
                    {1427, 3},
                    {1380, 3},
                    {1494, 3}
                };

            Vector y = new[]
                {
                    399900,
                    329900,
                    369000,
                    232000,
                    539900,
                    299900,
                    314900,
                    198999,
                    212000,
                    242500
                };

            LinearRegressionGenerator generator = new LinearRegressionGenerator() { LearningRate = 0.01, MaxIterations = 400, Lambda = 0, NormalizeFeatures = true };
            var model = generator.Generate(x.Copy(), y.Copy());
            var priceEqns = model.Predict(new Vector(new double[] { 1650, 3 }));

            // CK 150929: increased due to improvements in optimisation
            double actualEqns = 295107.0d;

            Almost.Equal(actualEqns, System.Math.Round(priceEqns, 0), 5000);
        }
Example #12
0
        static public System.Data.DataSet BuildDataSet(bool isMainTable, System.Data.DataTable dt, System.Data.DataTable dtDev)
        {
            System.Data.DataSet ds = new System.Data.DataSet();
            if (isMainTable)
            {
                System.Data.DataTable mydt = new System.Data.DataTable();
                System.Data.DataTable mydtDev = new System.Data.DataTable();

                mydt = dt.Copy();
                mydt.TableName = myTable.tblList.ToString();

                mydtDev = dtDev.Copy();
                mydtDev.TableName = myTable.tblDevice.ToString();

                ds.Tables.Add(mydtDev); // 第一個 DataTable,是爸爸
                ds.Tables.Add(mydt);    // 第二個 DataTable,是孩子

                // 關聯性 DataSet
                System.Data.DataRelation Rel = new System.Data.DataRelation("REL", ds.Tables[myTable.tblDevice.ToString()].Columns[myColumn.Devicename.ToString()], ds.Tables[myTable.tblList.ToString()].Columns[myColumn.Devicename.ToString()]);
                ds.Relations.Add(Rel);
            }
            else
            {
                ds.Tables.Add(dt.Copy());
            }
            return ds;
        }
Example #13
0
 public static System.Data.DataTable Join(System.Data.DataTable First, System.Data.DataTable Second)
 {
     int num4;
     System.Data.DataTable table = new System.Data.DataTable();
     using (DataSet set = new DataSet())
     {
         int num3;
         set.Tables.AddRange(new System.Data.DataTable[] { First.Copy(), Second.Copy() });
         List<string> list = new List<string>();
         List<string> list2 = new List<string>();
         int num = First.Columns.Count;
         int num2 = Second.Columns.Count;
         for (num3 = 0; num3 < num; num3++)
         {
             num4 = 0;
             while (num4 < num2)
             {
                 if (First.Columns[num3].ColumnName.Equals(Second.Columns[num4].ColumnName, StringComparison.OrdinalIgnoreCase))
                 {
                     list.Add(First.Columns[num3].ColumnName);
                     list2.Add(Second.Columns[num4].ColumnName);
                 }
                 num4++;
             }
         }
         DataColumn[] parentColumns = new DataColumn[list.Count];
         for (num3 = 0; num3 < parentColumns.Length; num3++)
         {
             parentColumns[num3] = set.Tables[0].Columns[list[num3]];
         }
         DataColumn[] childColumns = new DataColumn[list2.Count];
         for (num3 = 0; num3 < childColumns.Length; num3++)
         {
             childColumns[num3] = set.Tables[1].Columns[list2[num3]];
         }
         DataRelation relation = new DataRelation(string.Empty, parentColumns, childColumns, false);
         set.Relations.Add(relation);
         for (num3 = 0; num3 < First.Columns.Count; num3++)
         {
             table.Columns.Add(First.Columns[num3].ColumnName, First.Columns[num3].DataType);
         }
         for (num3 = 0; num3 < Second.Columns.Count; num3++)
         {
             if (!table.Columns.Contains(Second.Columns[num3].ColumnName))
             {
                 table.Columns.Add(Second.Columns[num3].ColumnName, Second.Columns[num3].DataType);
             }
             else
             {
                 table.Columns.Add(Second.Columns[num3].ColumnName + "_Second7320", Second.Columns[num3].DataType);
             }
         }
         table.BeginLoadData();
         foreach (DataRow row in set.Tables[0].Rows)
         {
             DataRow[] childRows = row.GetChildRows(relation);
             if ((childRows != null) && (childRows.Length > 0))
             {
                 object[] itemArray = row.ItemArray;
                 foreach (DataRow row2 in childRows)
                 {
                     object[] sourceArray = row2.ItemArray;
                     object[] destinationArray = new object[itemArray.Length + sourceArray.Length];
                     Array.Copy(itemArray, 0, destinationArray, 0, itemArray.Length);
                     Array.Copy(sourceArray, 0, destinationArray, itemArray.Length, sourceArray.Length);
                     table.LoadDataRow(destinationArray, true);
                 }
             }
         }
     }
     System.Data.DataTable table2 = table.Copy();
     List<string> list3 = new List<string>();
     foreach (DataColumn column in table2.Columns)
     {
         if (column.ColumnName.Contains("_Second7320"))
         {
             list3.Add(column.ColumnName);
         }
     }
     int count = list3.Count;
     for (num4 = 0; num4 < count; num4++)
     {
         table2.Columns.Remove(list3[num4]);
     }
     return table2;
 }
Example #14
0
 public static System.Data.DataTable mrgCnsPrm(System.Data.DataTable cns, System.Data.DataTable prPrm, System.Data.DataTable nwPrm, string mgOpt)
 {
     string columnName;
     int num3;
     int num = 0;
     int count = cns.Rows.Count;
     System.Data.DataTable first = new System.Data.DataTable();
     List<string> list = new List<string>();
     bool flag = false;
     foreach (DataColumn column in cns.Columns)
     {
         columnName = column.ColumnName;
         if (columnName.Equals("Migration Override", StringComparison.OrdinalIgnoreCase))
         {
             flag = true;
         }
         first.Columns.Add(columnName);
     }
     first = cns.Copy();
     num = prPrm.Columns.Count;
     for (num3 = 0; num3 < num; num3++)
     {
         if (((prPrm.Columns[num3].ColumnName == "Plan / Metallic Level") || (prPrm.Columns[num3].ColumnName == "Prior Carrier")) || ((num3 > 2) && (num3 < (num - 3))))
         {
             list.Add(prPrm.Columns[num3].ColumnName);
         }
     }
     num = list.Count;
     bool[] flagArray = new bool[num];
     for (num3 = 0; num3 < num; num3++)
     {
         columnName = list[num3];
         foreach (DataColumn column in first.Columns)
         {
             if (columnName.Equals(column.ColumnName))
             {
                 flagArray[num3] = true;
                 break;
             }
             flagArray[num3] = false;
         }
     }
     for (num3 = 0; num3 < num; num3++)
     {
         if (!flagArray[num3])
         {
             throw new Exception("Census does not contain all prior premium factors");
         }
     }
     num = nwPrm.Columns.Count;
     list = new List<string>();
     for (num3 = 0; num3 < num; num3++)
     {
         if (num3 < (num - 7))
         {
             list.Add(nwPrm.Columns[num3].ColumnName);
         }
     }
     num = list.Count;
     bool[] flagArray2 = new bool[num];
     for (num3 = 0; num3 < num; num3++)
     {
         columnName = list[num3];
         foreach (DataColumn column in first.Columns)
         {
             if (columnName.Equals(column.ColumnName))
             {
                 flagArray2[num3] = true;
                 break;
             }
             flagArray2[num3] = false;
         }
     }
     for (num3 = 0; num3 < num; num3++)
     {
         if (!flagArray2[num3])
         {
             throw new Exception("Census does not contain all new premium factors");
         }
     }
     System.Data.DataTable table2 = Join(first, prPrm);
     if (table2.Rows.Count < count)
     {
         throw new Exception("A premium factor value in prior premiums does not exist.");
     }
     if (table2.Rows.Count > count)
     {
         throw new Exception("A premium factor value in prior premiums is duplicated");
     }
     table2.Columns["Premium"].ColumnName = "Prior Premium";
     table2.Columns["Subsidy/Employer Contribution"].ColumnName = "Prior Subsidy";
     table2.Columns["EE Contribution"].ColumnName = "Prior EE Contribution";
     table2.Columns["Plan / Metallic Level"].ColumnName = "Prior Plan / Metallic Level";
     table2.Columns["AV"].ColumnName = "Prior AV";
     table2.AcceptChanges();
     System.Data.DataTable table3 = Join(table2, nwPrm);
     System.Data.DataTable table4 = table3.Clone();
     int num4 = table3.Rows.Count;
     if (flag)
     {
         try
         {
             string str2 = null;
             foreach (DataRow row in table3.Rows)
             {
                 str2 = (string) row["Migration Override"];
                 if (row["Metallic Level"].ToString().ToLower().Equals(str2.ToLower()))
                 {
                     table4.ImportRow(row);
                 }
             }
             if (table4.Rows.Count == 0)
             {
                 throw new Exception("Manual override field must be a valid metallic level.");
             }
         }
         catch
         {
             throw new Exception("Manual override field must be a valid metallic level.");
         }
     }
     else if (mgOpt.Equals("Closest AV"))
     {
         System.Data.DataTable second = new System.Data.DataTable();
         second.Columns.Add("Record ID");
         second.Columns.Add("Metallic Level");
         string str3 = null;
         decimal num5 = 0M;
         num = 0;
         string str4 = null;
         foreach (DataRow row in table3.Rows)
         {
             if (num == 0)
             {
                 str4 = row["Record ID"].ToString();
                 str3 = row["Metallic Level"].ToString();
                 num5 = Math.Abs((decimal) (decimal.Parse(row["Prior AV"].ToString()) - decimal.Parse(row["AV"].ToString())));
             }
             else if (str4.Equals(row["Record ID"].ToString()))
             {
                 if (Math.Abs((decimal) (decimal.Parse(row["Prior AV"].ToString()) - decimal.Parse(row["AV"].ToString()))) < num5)
                 {
                     str3 = row["Metallic Level"].ToString();
                     num5 = Math.Abs((decimal) (decimal.Parse(row["Prior AV"].ToString()) - decimal.Parse(row["AV"].ToString())));
                 }
             }
             else
             {
                 second.Rows.Add(new object[] { str4, str3 });
                 str3 = row["Metallic Level"].ToString();
                 num5 = Math.Abs((decimal) (decimal.Parse(row["Prior AV"].ToString()) - decimal.Parse(row["AV"].ToString())));
                 str4 = row["Record ID"].ToString();
             }
             num++;
         }
         second.Rows.Add(new object[] { str4, str3 });
         System.Data.DataTable table6 = Join(table3, second);
         if (table6.Rows.Count < count)
         {
             throw new Exception("A premium factor value in new premiums does not exist, check rating factor tab.");
         }
         if (table6.Rows.Count > count)
         {
             throw new Exception("A premium factor value in new premiums is duplicated");
         }
         table4 = table6.Copy();
     }
     else
     {
         string str5 = mgOpt.Substring(7);
         foreach (DataRow row in table3.Rows)
         {
             if (row["Metallic Level"].ToString().ToLower().Equals(str5.ToLower()))
             {
                 table4.ImportRow(row);
             }
         }
         if (table4.Rows.Count < count)
         {
             throw new Exception("You must enter a metallic level with a corresponding premium");
         }
     }
     table3 = table4.Copy();
     table3.Columns.Remove("AV");
     table3.Columns.Remove("Prior AV");
     table3.Columns.Remove("Factor");
     table3.Columns.Remove("Record ID");
     table3.Columns["Metallic Level"].ColumnName = "New Metallic Level";
     table3.Columns["Carrier"].ColumnName = "New Carrier";
     table3.Columns["Premium"].ColumnName = "New Premium";
     table3.Columns["Subsidy"].ColumnName = "New Subsidy";
     table3.Columns["EE Contribution"].ColumnName = "New EE Contribution";
     table3.AcceptChanges();
     table2.Columns.Remove("Record ID");
     table2.AcceptChanges();
     return table3;
 }
Example #15
0
        //private void UpdateUiFromSelectedItem(CustomizationFunction customizationFunction) {
        //    pnlParameters.Controls.Clear();
        //    txtFunctionName.Text = customizationFunction.localName;
        //    txtDescription.Text = customizationFunction.localDescription;
        //    for (int i = 0; i < customizationFunction.localVariableTypeAndName.Count; i++) {
        //        for (int j = 0; j < customizationFunction.localVariableTypeAndName.ElementAt(i).Value.Count; j++) {
        //            Label lbl = new Label();
        //            lbl.Visible = false;
        //            lbl.Text = customizationFunction.localVariableTypeAndName.ElementAt(i).Value[j].Substring(0, 1).ToUpperInvariant() +
        //            customizationFunction.localVariableTypeAndName.ElementAt(i).Value[j].Substring(1);
        //            lbl.Dock = DockStyle.Top;
        //            if (string.Equals(customizationFunction.localVariableTypeAndName.ElementAt(i).Key, "boolean")) {
        //                ComboBox cbo = new ComboBox();
        //                cbo.Visible = false;
        //                cbo.Items.Add("True");
        //                cbo.Items.Add("False");
        //                cbo.DropDownStyle = ComboBoxStyle.DropDown;
        //                cbo.Name = customizationFunction.localVariableTypeAndName.ElementAt(i).Value[j];
        //                cbo.Dock = DockStyle.Top;
        //                cbo.SelectedIndex = 0;
        //                cbo.ContextMenuStrip = cmsAddPropertyMenu;
        //                pnlParameters.Controls.Add(cbo);
        //                pnlParameters.Controls.Add(lbl);
        //            } else {
        //                TextBox txt = new TextBox();
        //                txt.Visible = false;
        //                txt.Name = customizationFunction.localVariableTypeAndName.ElementAt(i).Value[j];
        //                txt.Dock = DockStyle.Top;
        //                //txt.Text = "\"\"";
        //                txt.ContextMenuStrip = cmsAddPropertyMenu;
        //                pnlParameters.Controls.Add(txt);
        //                pnlParameters.Controls.Add(lbl);
        //            }
        //        }
        //    }
        //    foreach (Control control in pnlParameters.Controls) {
        //        control.Visible = true;
        //    }
        //}
        private System.Data.DataTable getDifferentRecords(System.Data.DataTable FirstDataTable, System.Data.DataTable SecondDataTable)
        {
            //Create Empty Table
            System.Data.DataTable ResultDataTable = new System.Data.DataTable("ResultDataTable");

            //use a Dataset to make use of a DataRelation object
            using (DataSet ds = new DataSet()) {
                //Add tables
                ds.Tables.AddRange(new System.Data.DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() });

                //Get Columns for DataRelation
                DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
                for (int i = 0; i < firstColumns.Length; i++) {
                    firstColumns[i] = ds.Tables[0].Columns[i];
                }

                DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
                for (int i = 0; i < secondColumns.Length; i++) {
                    secondColumns[i] = ds.Tables[1].Columns[i];
                }

                if (firstColumns.Count() == secondColumns.Count()) {
                    //Create DataRelation
                    DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
                    ds.Relations.Add(r1);

                    DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
                    ds.Relations.Add(r2);

                    //Create columns for return table
                    for (int i = 0; i < FirstDataTable.Columns.Count; i++) {
                        ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType);
                    }
                    ResultDataTable.Columns.Add("Added/Removed");

                    //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.
                    ResultDataTable.BeginLoadData();
                    foreach (DataRow parentrow in ds.Tables[0].Rows) {
                        object[] rowItems = new object[parentrow.ItemArray.Length + 1];

                        DataRow[] childrows = parentrow.GetChildRows(r1);
                        if (childrows == null || childrows.Length == 0) {
                            parentrow.ItemArray.CopyTo(rowItems, 0);
                            rowItems[rowItems.Length - 1] = "Removed";
                            ResultDataTable.LoadDataRow(rowItems, true);
                        }
                    }

                    //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.
                    foreach (DataRow parentrow in ds.Tables[1].Rows) {
                        object[] rowItems = new object[parentrow.ItemArray.Length + 1];
                        DataRow[] childrows = parentrow.GetChildRows(r2);
                        if (childrows == null || childrows.Length == 0) {
                            parentrow.ItemArray.CopyTo(rowItems, 0);
                            rowItems[rowItems.Length - 1] = "Added";
                            ResultDataTable.LoadDataRow(rowItems, true);
                        }
                    }
                    ResultDataTable.EndLoadData();
                } else {
                    FrontendUtils.ShowInformation("Excell sheet named [" + ds.Tables[0].TableName + "] is incomparable!", true);
                }
            }
            return ResultDataTable;
        }
Example #16
0
		/// <summary>
		/// 获取不重复列表
		/// </summary>
		/// <param name="dtSrc">源表</param>
		/// <param name="DataColumnNames">列名列表</param>
		/// <returns></returns>
		public static System.Data.DataTable GetDistinct(System.Data.DataTable dtSrc, string[] DataColumnNames)
		{
			if (DataColumnNames == null || DataColumnNames.Length == 0)
			{
				DataColumnNames = GetColNames(dtSrc);
			}

			System.Data.DataTable dt = dtSrc.Copy();
			dt.Constraints.Clear();

			// 去掉多余列
			for (int i = dt.Columns.Count - 1; i >= 0; i--)
			{
				bool NeedDelete = true;
				foreach (string DataColumnName in DataColumnNames)
				{
					if (dt.Columns[i].ColumnName == DataColumnName)
					{
						NeedDelete = false;
						break;
					}
				}
				if (NeedDelete)
				{
					dt.Columns.RemoveAt(i);
				}
			}

			// 去掉重复行
			for (int r = 0; r < dt.Rows.Count; r++)
			{
				for (int f = dt.Rows.Count - 1; f > r; f--)
				{
					if (Apq.Data.DataRow.Equals(dt.Rows[r], dt.Rows[f]))
					{
						dt.Rows.RemoveAt(f);
					}
				}
			}
			return dt;
		}
 public void Copy_ReturnsCopy()
 {
     int[] a1 = new[] { 1, 2, 3 };
     int[] a2 = a1.Copy();
     Assert.AreNotSame(a1, a2);
 }
Example #18
0
        public void CopyTestCase1NullCheck1()
        {
            Array array = new[]
            {
                "0",
                "1",
                "2",
                "3"
            };
            String[] destinationArray = null;
            Action test = () => array.Copy( 1, destinationArray, 0, 2 );

            test.ShouldThrow<ArgumentNullException>();
        }
Example #19
0
        public void Linear_Regression_Test_House_Predictions_Regularized()
        {
            // test house prices based on ft-sq and no# bedrooms
            Matrix x = new [,]
                {
                    {2104, 3},
                    {1600, 3},
                    {2400, 3},
                    {1416, 2},
                    {3000, 4},
                    {1985, 4},
                    {1534, 3},
                    {1427, 3},
                    {1380, 3},
                    {1494, 3}
                };

            Vector y = new[]
                {
                    399900,
                    329900,
                    369000,
                    232000,
                    539900,
                    299900,
                    314900,
                    198999,
                    212000,
                    242500
                };

            LinearRegressionGenerator generator = new LinearRegressionGenerator() { LearningRate = 0.01, MaxIterations = 400, Lambda = 1, NormalizeFeatures = true };
            var model = generator.Generate(x.Copy(), y.Copy());
            var priceGrad = model.Predict(new Vector(new double[] { 1650, 3 }));

            double actualGrad = 296500.0d;

            Almost.Equal(actualGrad, System.Math.Round(priceGrad, 0), 5000);
        }
Example #20
0
 public void Copy()
 {
     var xs = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
     var ys = xs.Copy();
     Assert.IsFalse(ReferenceEquals(xs, ys));
     Assert.AreEqual(xs, ys);
 }
Example #21
0
        public System.IO.Stream Process(IImageProcessorSetting setting, System.IO.Stream imageStream)
        {
            ExceptionHelper.ThrowIfNull(imageStream, "imageStream");

            if (!_Args.IsNeetProcess())
                return imageStream.Copy();

            var image = Image.FromStream(imageStream);

            var height = _Args.Height;
            var width = _Args.Width;
            if (_Args.Multiple.HasValue)
            {
                if (height.HasValue) height = height.Value * _Args.Multiple.Value;
                if (width.HasValue) width = width.Value * _Args.Multiple.Value;
            }

            if (height.HasValue && width.HasValue)
            {
                var heightFirst = _Args.Edge == ZoomProcessArguments.EdgeEnum.Long
                                    ? image.Height >= image.Width
                                    : image.Height <= image.Width;
                if (heightFirst)
                {
                    var e = (double)image.Height / (double)height.Value;
                    width = (int)((double)image.Width / e);
                }
                else
                {
                    var e = (double)image.Width / (double)width.Value;
                    height = (int)((double)image.Height / e);
                }
            }
            else
            {
                var e = (double)image.Height / (double)image.Width;
                if (height.HasValue)
                {
                    width = (int)((double)height.Value / e);
                }
                else if (width.HasValue)
                {
                    height = (int)(width.Value * e);
                }
            }

            var format = String.IsNullOrWhiteSpace(_Args.Format) ? ".jpg" : _Args.Format;
            var mineType = Flh.IO.MimeTypeHelper.GetMimeType(format);
            ExceptionHelper.ThrowIfTrue(!mineType.StartsWith("image/"), "_Args", "输出图片格式设置错误");

            if(height.HasValue && width.HasValue && _Args.Large.HasValue && _Args.Large.Value)
            {
                if(height.Value > image.Height || width.Value > image.Width)
                {
                    height = null;
                    width = null;
                }
            }

            if (height.HasValue && width.HasValue)
            {
                using (var zoomImage = new Bitmap(width.Value, height.Value))
                {
                    using (var graphics = Graphics.FromImage(zoomImage))
                    {
                        graphics.DrawImage(image, 0, 0, width.Value, height.Value);
                        return GetQualityZoomStream(zoomImage, mineType, _Args.Quality, _Args.AbsoluteQuality);
                    }
                }
            }
            else if (_Args.AbsoluteQuality.HasValue || _Args.Quality.HasValue)
            {
                return GetQualityZoomStream(image, mineType, _Args.Quality, _Args.AbsoluteQuality);
            }
            else
            {
                var result = new System.IO.MemoryStream();
                image.Save(result, GetImageFormatByMineType(mineType));
                result.Position = 0;
                return result;
            }
        }
Example #22
0
        private int DataTable2Excel(System.Data.DataTable dt, int totalCount, int currentCount, Dictionary<string, string> dicColumnNameMapping,
            object omissing, Excel.Workbook xlworkbook)
        {
            try
            {
                var tmpDataTable = dt.Copy();

                #region 表头
                if (dicColumnNameMapping != null)
                {
                    ResolveDatatableColumns(tmpDataTable, dicColumnNameMapping);
                }

                //var dr = tmpDataTable.NewRow();
                //for (int i = 0; i < tmpDataTable.Columns.Count; i++)
                //{
                //    dr[i] = tmpDataTable.Columns[i].ColumnName;
                //}
                //tmpDataTable.Rows.InsertAt(dr, 0);
                #endregion

                #region 快速导出数据

                int rowNum = tmpDataTable.Rows.Count;
                int columnNum = tmpDataTable.Columns.Count;
                int rowIndex = 1;
                int columnIndex = 0;

                Excel.Worksheet xlworksheet = (Excel.Worksheet)xlworkbook.Worksheets.Add(omissing, omissing, 1, omissing);
                xlworksheet.Name = tmpDataTable.TableName == null ? xlworksheet.Name : ResolveSheetName(tmpDataTable.TableName);
                int colnum = tmpDataTable.Columns.Count;
                Excel.Range r = xlworksheet.get_Range("A1", NumToExeclRowStr(colnum) + "1");

                object[] objHeader = new object[colnum];

                columnIndex = 0;//表头
                for (int j = 0; j < columnNum; j++)
                {
                    objHeader[columnIndex] = tmpDataTable.Columns[j].ColumnName;
                    columnIndex++;
                }
                r.Value2 = objHeader;

                //将DataTable中的数据导入Excel中
                for (int f = 0; f < rowNum; f++)
                {
                    rowIndex++;
                    columnIndex = 0;
                    for (int j = 0; j < columnNum; j++)
                    {
                        string danyinhao = "";//"'";
                        objHeader[columnIndex] = danyinhao + tmpDataTable.Rows[f][j].ToString();
                        columnIndex++;
                    }
                    r = xlworksheet.get_Range("A" + (f + 2), NumToExeclRowStr(colnum) + (f + 2));
                    r.Value2 = objHeader;
                    currentCount++;
                    AddProcess(currentCount, totalCount);
                }
                //r.EntireColumn.WrapText = true;
                r.EntireColumn.AutoFit();
                #endregion 快速导出数据
            }
            catch (Exception ex)
            {
                AddError(ex.Message);
            }
            return currentCount;
        }