示例#1
0
    public static void Main(String[] args)
    {
        Components.Init();

        Generate gen = new Generate();
        gen.GenerateInterfaceAssembly(args);
    }
 private double[] Exponential(double[] x, double[] y, DirectRegressionMethod method = DirectRegressionMethod.QR)
 {
     double[] y_hat = Generate.Map(y, Math.Log);
     double[] p_hat = Fit.LinearCombination(x, y_hat, method, t => 1.0, t => t);
     return(new[] { Math.Exp(p_hat[0]), p_hat[1] });
 }
示例#3
0
 public V2Strategy(DateTimeOffset?when)
 {
     this.when = when == null ? null : new MockCommit {
         CommitterEx = Generate.Signature(when.Value)
     };
 }
示例#4
0
        public IEnumerable <MethodDeclarationSyntax> Create(IIndexerModel indexer, ClassModel model)
        {
            if (indexer == null)
            {
                throw new ArgumentNullException(nameof(indexer));
            }

            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var paramExpressions = indexer.Parameters.Select(param => AssignmentValueHelper.GetDefaultAssignmentValue(param.TypeInfo, model.SemanticModel, _frameworkSet)).ToArray();

            var method = _frameworkSet.TestFramework.CreateTestMethod(string.Format(CultureInfo.InvariantCulture, "CanGet{0}", model.GetIndexerName(indexer)), false, model.IsStatic)
                         .AddBodyStatements(_frameworkSet.TestFramework.AssertIsInstanceOf(Generate.IndexerAccess(model.TargetInstance, paramExpressions), indexer.TypeInfo.ToTypeSyntax(_frameworkSet.Context)))
                         .AddBodyStatements(_frameworkSet.TestFramework.AssertFail(Strings.PlaceholderAssertionMessage));

            yield return(method);
        }
示例#5
0
        public override IEnumerable <Row> Execute(IEnumerable <Row> rows)
        {
            var counter = 0;

            foreach (var row in rows)
            {
                counter++;
                if (counter == 1)
                {
                    Guard.Against(!row.Contains(CONNECTION_STRING_KEY), "Row must contain connectionstring key.");
                }

                _connectionStringBuilder = new SqlConnectionStringBuilder(row[CONNECTION_STRING_KEY].ToString());
                var sqlConnectionChecker = new SqlConnectionChecker(new[] { _connectionStringBuilder.ConnectionString });

                if (!sqlConnectionChecker.AllGood())
                {
                    continue;
                }

                var results   = new Database();
                var subRows   = new List <Row>();
                var generator = new Generate()
                {
                    ConnectionString = _connectionStringBuilder.ConnectionString
                };

                Debug("Started generating definitions on {0} for {1}", _connectionStringBuilder.DataSource, _connectionStringBuilder.InitialCatalog);

                try {
                    results = generator.Process();
                } catch (Exception e) {
                    Warn("Trouble processing objects from {0}.{1}.\nError Message: {2}.", _connectionStringBuilder.DataSource, _connectionStringBuilder.InitialCatalog, e.Message);
                }

                Debug("Finished generating defs on {0} for {1}", _connectionStringBuilder.DataSource, _connectionStringBuilder.InitialCatalog);

                subRows.AddRange(ToRows(results.Procedures, "StoredProcedures", "Stored Procedure"));
                subRows.AddRange(ToRows(results.Functions, "Functions", "Function"));
                subRows.AddRange(ToRows(results.Tables, "Tables", "Table"));
                subRows.AddRange(ToRows(results.Views, "Views", "View"));
                subRows.AddRange(ToRows(results.Schemas, "Schemas", "Schema"));
                subRows.AddRange(ToRows(results.Synonyms, "Synonyms", "Synonym"));
                subRows.AddRange(ToRows(results.FullText, "FullTextCatalogs", "Full Text Catalog"));

                foreach (var table in results.Tables)
                {
                    subRows.AddRange(ToRows(table.Indexes, "Indexes", "Index", true));
                    subRows.AddRange(ToRows(table.Triggers, "Triggers", "Trigger", true));
                    foreach (var constraint in table.Constraints)
                    {
                        switch (constraint.Type)
                        {
                        case Constraint.ConstraintType.Check:
                            subRows.AddRange(ToRows(Enumerable.Repeat(constraint, 1), "CheckConstraints", "Check Constraint", true, true));
                            break;

                        case Constraint.ConstraintType.Default:
                            subRows.AddRange(ToRows(Enumerable.Repeat(constraint, 1), "DefaultConstraints", "Default Constraint", true, true));
                            break;

                        case Constraint.ConstraintType.ForeignKey:
                            subRows.AddRange(ToRows(Enumerable.Repeat(constraint, 1), "ForeignKeys", "Foreign Key", true, true));
                            break;

                        case Constraint.ConstraintType.PrimaryKey:
                            subRows.AddRange(ToRows(Enumerable.Repeat(constraint, 1), "PrimaryKeys", "Primary Key", true, true));
                            break;

                        case Constraint.ConstraintType.Unique:
                            subRows.AddRange(ToRows(Enumerable.Repeat(constraint, 1), "UniqueConstraints", "Unique Constraint", true, true));
                            break;
                        }
                    }

                    foreach (var index in table.FullTextIndex)
                    {
                        subRows.AddRange(ToRows(Enumerable.Repeat(index, 1), "FullTextIndexes", "Full Text Index", true));
                    }
                }

                Info("Found {0} in {1}.", subRows.Count, _connectionStringBuilder.InitialCatalog);

                foreach (var subRow in subRows)
                {
                    yield return(subRow);
                }
            }
        }
        public void AlgorithmsMatchReferenceArbitraryLarge64_GH286()
        {
            var samples = Generate.RandomComplex(46500, GetUniform(1));

            Verify(samples, 10, FourierOptions.NoScaling, ReferenceDiscreteFourierTransform.Forward, Fourier.Forward);
        }
示例#7
0
        /// <summary>
        /// 编辑用户,账号名称最少5个字|多于30个字
        /// </summary>
        /// <param name="appWin"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool EditUser_UserNameLength(Window appWin, out string msg)
        {
            try
            {
                var startTime = DateTime.Now;

                //账号名称少于1个字符
                TextBox txtUserName = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtUserName"));
                txtUserName.BulkText = Generate.GenerateChineseWords(1);

                //点击确定按钮
                Button btnComfirmEditUser = appWin.Get <Button>(SearchCriteria.ByAutomationId("btnComfirmEditUser"));
                btnComfirmEditUser.Click();

                try
                {
                    //捕捉提醒信息,如果能捕捉到,则测试通过
                    string error_info = appWin.Get <Label>(SearchCriteria.ByText("账号名称最少5个字,最多30个字!")).ToString();
                    //关闭提醒框
                    Button btnTips = appWin.Get <Button>(SearchCriteria.ByAutomationId("2"));
                    btnTips.Click();

                    //账号名称多于30个字符
                    txtUserName.BulkText = Generate.GenerateChineseWords(31);

                    //点击确定按钮
                    btnComfirmEditUser.Click();

                    try
                    {
                        //捕捉提醒信息,如果能捕捉到,则测试通过
                        error_info = appWin.Get <Label>(SearchCriteria.ByText("账号名称最少5个字,最多30个字!")).ToString();
                        //关闭提醒框
                        btnTips = appWin.Get <Button>(SearchCriteria.ByAutomationId("2"));
                        btnTips.Click();

                        //点击取消按钮,关闭编辑窗口
                        Button btnCancleEditUser = appWin.Get <Button>(SearchCriteria.ByAutomationId("btnCancleEditUser"));
                        btnCancleEditUser.Click();

                        msg = "测试【编辑用户,账号名称最少5个字|多于30个字】--通过,用时:" + (DateTime.Now - startTime).TotalSeconds;
                        return(true);
                    }
                    catch
                    {
                        msg = "测试【编辑用户,账号名称最少5个字|多于30个字】--未通过,缺少账号名称长度验证提醒。用时:" + (DateTime.Now - startTime).TotalSeconds;
                        return(false);
                    }
                }
                catch
                {
                    msg = "测试【编辑用户,账号名称最少5个字|多于30个字】--未通过,缺少账号名称长度验证提醒。用时:" + (DateTime.Now - startTime).TotalSeconds;
                    return(false);
                }
            }
            catch (Exception e)
            {
                msg = "测试【编辑用户,账号名称最少5个字|多于30个字】--失败,原因:" + e.ToString();
                return(false);
            }
        }
示例#8
0
        /// <summary>
        /// 新增用户,真实姓名为空|真实姓名多于30个字
        /// </summary>
        /// <param name="appWin"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool AddUser_RealNameLength(Window appWin, out string msg)
        {
            try
            {
                var startTime = DateTime.Now;

                //点击新增按钮
                Button btnAddUser = appWin.Get <Button>(SearchCriteria.ByAutomationId("btnAddUser"));
                btnAddUser.Click();

                //正确账号名称
                TextBox txtUserName = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtUserName"));
                txtUserName.BulkText = Generate.GenerateChineseWords(5);

                //密码不少于8个字符
                TextBox pwdUserPwd = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("pwdUserPwd"));
                pwdUserPwd.Text = "12345678";

                //选择角色
                ComboBox cbRole = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <ComboBox>(SearchCriteria.ByAutomationId("cbRole"));
                cbRole.Select(1);

                //真实姓名为空
                TextBox txtRealName = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtRealName"));
                txtRealName.Text = "";

                //点击确定按钮
                Button btnComfirmAddUser = appWin.Get <Button>(SearchCriteria.ByAutomationId("btnComfirmAddUser"));
                btnComfirmAddUser.Click();

                try
                {
                    //捕捉提醒信息,如果能捕捉到,则测试通过
                    string error_info = appWin.Get <Label>(SearchCriteria.ByText("请输入真实姓名!")).ToString();
                    //关闭提醒框
                    Button btnTips = appWin.Get <Button>(SearchCriteria.ByAutomationId("2"));
                    btnTips.Click();

                    //真实姓名多于30个字符
                    txtRealName.BulkText = Generate.GenerateChineseWords(31);

                    //点击确定按钮
                    btnComfirmAddUser.Click();

                    try
                    {
                        //捕捉提醒信息,如果能捕捉到,则测试通过
                        error_info = appWin.Get <Label>(SearchCriteria.ByText("真实姓名最多30个字!")).ToString();
                        //关闭提醒框
                        btnTips = appWin.Get <Button>(SearchCriteria.ByAutomationId("2"));
                        btnTips.Click();

                        msg = "测试【新增用户,真实姓名为空|真实姓名多于30个字】--通过,用时:" + (DateTime.Now - startTime).TotalSeconds;
                        return(true);
                    }
                    catch
                    {
                        msg = "测试【新增用户,真实姓名为空|真实姓名多于30个字】--未通过,缺少真实姓名长度验证提醒。用时:" + (DateTime.Now - startTime).TotalSeconds;
                        return(false);
                    }
                }
                catch
                {
                    msg = "测试【新增用户,真实姓名为空|真实姓名多于30个字】--未通过,缺少真实姓名空验证提醒。用时:" + (DateTime.Now - startTime).TotalSeconds;
                    return(false);
                }
            }
            catch (Exception e)
            {
                msg = "测试【新增用户,真实姓名为空|真实姓名多于30个字】--失败,原因:" + e.ToString();
                return(false);
            }
        }
示例#9
0
 /// <summary>
 /// Create a new dense matrix with values sampled from the provided random distribution.
 /// </summary>
 public static DenseMatrix CreateRandom(int rows, int columns, IContinuousDistribution distribution)
 {
     return(new DenseMatrix(new DenseColumnMajorMatrixStorage <double>(rows, columns, Generate.Random(rows * columns, distribution))));
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ServiceContainer.Resolve <IInitRequestScopeContext>().BeginRequest(actionContext.Request);

            if (!actionContext.HasMarkerAttribute <NonTracingAttribute>())
            {
                var request = actionContext.Request;
                IRequestModel <Header> reqModel = null;
                Header reqHeader = null;

                if (actionContext.ActionArguments.Count > 0)
                {
                    foreach (var dic in actionContext.ActionArguments)
                    {
                        //if (dic.Value is RequestModel)
                        //{
                        //    reqModel = dic.Value as RequestModel;
                        //    break;
                        //}
                        reqModel = dic.Value as IRequestModel <Header>;
                        if (reqModel != null)
                        {
                            break;
                        }
                    }
                }
                if (reqModel == null && actionContext.Request.Content != null && string.Equals(actionContext.Request.Method.Method, "post", StringComparison.CurrentCultureIgnoreCase))
                {
                    try
                    {
                        reqModel = actionContext.Request.Content.ReadAsAsync <RequestModel>().Result;
                    }
                    catch { }
                    if (reqModel != null)
                    {
                        actionContext.ActionArguments.Add(Guid.NewGuid().ToString("N"), reqModel);
                    }
                }

                if (reqModel != null && reqModel.Header != null)
                {
                    reqHeader = reqModel.Header;
                    if (string.IsNullOrWhiteSpace(reqHeader.TraceID))
                    {
                        reqHeader.TraceID = Generate.GenerateId();// Util.GetUniqueCode32();
                    }
                    if (string.IsNullOrWhiteSpace(reqHeader.RpcID))
                    {
                        reqHeader.RpcID = "0";
                    }

                    //HttpContentData.SetTrackID(reqHeader.TraceID);
                    //HttpContentData.SubRpcID = reqHeader.RpcID + ".0";
                    //var header = HttpContentData.CloneRequestHeader(reqModel.Header);
                    //header.RpcID = header.RpcID + ".0";
                }
                else
                {
                    reqHeader = TracingContextData.GetDefaultRequestHeader();
                    //HttpContentData.SetTrackID(reqHeader.TraceID);
                }
                TracingContextData.SetSubRpcID(reqHeader.RpcID + ".0");
                TracingContextData.SetRequestHeader(reqHeader);
                //HttpContentData.RequestHeader = reqHeader;

                //Not To Log
                if (!actionContext.HasMarkerAttribute <NotToLogAttribute>())
                {
                    TraceLogs trace = new TraceLogs();
                    trace.ContextType = ContextType.Server.ToString();
                    trace.StartTime   = DateTime.Now;
                    trace.MachineAddr = Util.TracingContextHelper.GetServerAddress();
                    trace.TraceId     = reqHeader.TraceID;
                    trace.RpcId       = reqHeader.RpcID;
                    trace.Protocol    = string.Format("{0}/{1}", actionContext.Request.RequestUri.Scheme, actionContext.Request.Version);

                    trace.Environment = this.environment ?? EnvironmentConfig.Environment;
                    trace.SystemID    = this.systemID ?? EnvironmentConfig.SystemID;
                    trace.SystemName  = this.systemName ?? EnvironmentConfig.SystemName;

                    //InvokeID
                    trace.InvokeID = request.RequestUri.AbsolutePath;
                    IEnumerable <string> folder;
                    if (actionContext.Request.Headers.TryGetValues(Config.ResponseHeaderFolderKey, out folder))
                    {
                        trace.ServerHost = actionContext.Request.RequestUri.Host + folder.FirstOrDefault();
                    }
                    else
                    {
                        trace.ServerHost = actionContext.Request.RequestUri.Host;
                    }

                    //SearchKey
                    var searchKey = reqModel as ISearchKey;
                    if (searchKey != null)
                    {
                        trace.SearchKey = searchKey.GetSearchKey();
                    }

                    TraceExtensionOnActionExecuting(actionContext, trace);

                    //srs.InvokeID = string.Format("{0}_{1}", actionContext.ControllerContext.ControllerDescriptor.ControllerName.ToLower(), actionContext.ActionDescriptor.ActionName.ToLower());

                    //if (actionContext.ActionArguments != null && actionContext.ActionArguments.Count > 0)
                    //{
                    //    srs.Extension.Add(Config.ParamsKey, actionContext.ActionArguments);
                    //}

                    //ServerRS Log Data TODO

                    Util.TracingContextHelper.SetContextItem(Config.ServerRSKey, trace);
                }
            }

            base.OnActionExecuting(actionContext);
        }
        public void PreReleaseNumberShouldBeScopeToPreReleaseLabelInContinuousDelivery()
        {
            var config = new Config
            {
                VersioningMode = VersioningMode.ContinuousDelivery,
                Branches       = new Dictionary <string, BranchConfig>
                {
                    {
                        "master", new BranchConfig
                        {
                            Tag = "beta"
                        }
                    },
                }
            };

            using var fixture = new EmptyRepositoryFixture();
            fixture.Repository.MakeACommit();

            fixture.Repository.CreateBranch("feature/test");
            Commands.Checkout(fixture.Repository, "feature/test");
            fixture.Repository.MakeATaggedCommit("0.1.0-test.1");
            fixture.Repository.MakeACommit();

            fixture.AssertFullSemver("0.1.0-test.2+2", config);

            Commands.Checkout(fixture.Repository, "master");
            fixture.Repository.Merge((Branch) new GitRepository(fixture.Repository).FindBranch("feature/test"), Generate.SignatureNow());

            fixture.AssertFullSemver("0.1.0-beta.1+2", config);
        }
示例#12
0
 void Start()
 {
     generator = this;
     GenerateMap();
 }
示例#13
0
        /*private void ProcesarSybase()
         * {
         *  DBDiff.Schema.Sybase.Model.Database origen;
         *  DBDiff.Schema.Sybase.Model.Database destino;
         *
         *  DBDiff.Schema.Sybase.Generate sql = new DBDiff.Schema.Sybase.Generate();
         *  sql.ConnectioString = txtConnectionOrigen.Text;
         *
         *  AseFilter.OptionFilter.FilterTrigger = false;
         *
         *  origen = sql.Process(AseFilter);
         *
         *  sql.ConnectioString = txtConnectionDestino.Text;
         *  destino = sql.Process(AseFilter);
         *
         *  this.txtScript.SQLType = SQLEnum.SQLTypeEnum.Sybase;
         *  this.txtDiferencias.SQLType = SQLEnum.SQLTypeEnum.Sybase;
         *  //origen = DBDiff.Schema.Sybase.Generate.Compare(origen, destino);
         *
         *  this.txtScript.Text = origen.ToSQL();
         *  //this.txtDiferencias.Text = origen.ToSQLDiff();
         * }*/

        /*private void ProcesarMySQL()
         * {
         *  DBDiff.Schema.MySQL.Model.Database origen;
         *  DBDiff.Schema.MySQL.Model.Database destino;
         *
         *  DBDiff.Schema.MySQL.Generate sql = new DBDiff.Schema.MySQL.Generate();
         *  sql.ConnectioString = mySqlConnectFront1.ConnectionString;
         *  origen = sql.Process(MySQLfilter);
         *
         *  sql.ConnectioString = mySqlConnectFront2.ConnectionString;
         *  destino = sql.Process(MySQLfilter);
         *
         *  //this.txtScript.SQLType = SQLEnum.SQLTypeEnum.MySQL;
         *  //this.txtDiferencias.SQLType = SQLEnum.SQLTypeEnum.MySQL;
         *  origen = DBDiff.Schema.MySQL.Generate.Compare(origen, destino);
         *  this.txtDiferencias.Text = origen.ToSQLDiff();
         * }
         */

        private void ProcesarSQL2005()
        {
            ProgressForm progres       = null;
            string       errorLocation = null;

            try
            {
                Database origen;
                Database destino;

                if ((!String.IsNullOrEmpty(mySqlConnectFront1.DatabaseName) &&
                     (!String.IsNullOrEmpty(mySqlConnectFront2.DatabaseName))))
                {
                    Generate sql1 = new Generate();
                    Generate sql2 = new Generate();

                    sql1.ConnectionString = mySqlConnectFront1.ConnectionString;
                    sql1.Options          = SqlFilter;

                    sql2.ConnectionString = mySqlConnectFront2.ConnectionString;
                    sql2.Options          = SqlFilter;

                    progres = new ProgressForm("Source Database", "Destination Database", sql2, sql1);
                    progres.ShowDialog(this);
                    if (progres.Error != null)
                    {
                        throw new SchemaException(progres.Error.Message, progres.Error);
                    }

                    origen  = progres.Source;
                    destino = progres.Destination;

                    txtDiferencias.ConfigurationManager.Language = "mssql";
                    txtDiferencias.IsReadOnly = false;
                    txtDiferencias.Styles.LineNumber.BackColor = Color.White;
                    txtDiferencias.Styles.LineNumber.IsVisible = false;
                    errorLocation                       = "Generating Synchronized Script";
                    txtDiferencias.Text                 = destino.ToSqlDiff(_selectedSchemas).ToSQL();
                    txtDiferencias.IsReadOnly           = true;
                    schemaTreeView1.DatabaseSource      = destino;
                    schemaTreeView1.DatabaseDestination = origen;
                    schemaTreeView1.OnSelectItem       += new SchemaTreeView.SchemaHandler(schemaTreeView1_OnSelectItem);
                    textBox1.Text                       = origen.ActionMessage.Message;

                    btnCopy.Enabled      = true;
                    btnSaveAs.Enabled    = true;
                    btnUpdateAll.Enabled = true;
                }
                else
                {
                    MessageBox.Show(Owner, "Please select a valid connection string", "ERROR", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                if (errorLocation == null && progres != null)
                {
                    errorLocation = String.Format("{0} (while {1})", progres.ErrorLocation, progres.ErrorMostRecentProgress ?? "initializing");
                }

                throw new SchemaException("Error " + (errorLocation ?? " Comparing Databases"), ex);
            }
        }
示例#14
0
文件: GA.cs 项目: GKBelmonte/Core
        private void Test_PolynomialGA(Func <double, double> func)
        {
            //Settings
            bool adaptive = false;
            int  seed     = 0;

            Utils.SetRandomSeed(seed);
            var rng = new Random(seed);

            PolynomialOrder = 5;
            int populationSize = 100;
            //number of samples to use the in the polynomial approx
            // to test the differnce
            double start = -10, end = 10;
            //Step between the samples
            double step = 0.02;
            //Number of generations to bundle
            int genBundleCount = 10;

            //Stop at Gen
            GenerationStop = 500;

            //Get Data for tests
            double[] xRange, expectedValues;
            GetFofXForRange(func, start, step, end, out xRange, out expectedValues);

            double[][] allPowsOfX = GetPowersOfX(xRange, PolynomialOrder);

            ExpectedValsX  = xRange;
            ExpectedValsY  = expectedValues;
            PowsOfXForAllX = allPowsOfX;

            //Create Delegates
            Evaluate eval = (i) =>
                            ((CartesianIndividual)i).PolynomialEval(allPowsOfX, expectedValues);

            CrossOver crossOver = adaptive
                ? AdaptiveCartesianIndividual.CrossOver
                : (CrossOver)CartesianIndividual.CrossOver;

            Generate generate = adaptive
                ? (Generate)((r) => new AdaptiveCartesianIndividual(PolynomialOrder, 1, r: r, emptySigma: true))
                : (r) => new CartesianIndividual(PolynomialOrder, 1, r);

            // Generate Population
            List <IIndividual> pop;

            pop = Enumerable
                  .Range(0, populationSize)
                  .Select(i => generate(rng))
                  .Cast <IIndividual>()
                  .ToList();

            Ages = new Ages(genBundleCount,
                            eval,
                            crossOver,
                            generate,
                            pop);

            Ages.SetRandomSeed(seed);

            Ages.NicheStrat = new NicheDensityStrategy(
                Ages,
                (l, r) => CartesianIndividual.Distance((CartesianIndividual)l, (CartesianIndividual)r));
        }
示例#15
0
        private void working()
        {
            TextOGlitchForm1.threadLocalization();
            CheckForIllegalCrossThreadCalls = false;
            switch (TextOGlitchForm1.modeTray)
            {
            case 0:
                if (textBox1.Text != "")
                {
                    if (textOutput != textBox1.Text)
                    {
                        textOriginal  = textBox1.Text;
                        textOutput    = Glitch.Text(textOriginal, Convert.ToInt32(numericUpDown1.Value), false);
                        textBox1.Text = textOutput;
                    }
                    else
                    {
                        textOutput    = Glitch.Text(textOriginal, Convert.ToInt32(numericUpDown1.Value), false);
                        textBox1.Text = textOutput;
                    }
                }
                break;

            case 1:
                if (textOutput != textBox1.Text)
                {
                    textOriginal  = textBox1.Text;
                    textOutput    = Glitch.Text(textOriginal, Convert.ToInt32(numericUpDown1.Value), true);
                    textBox1.Text = textOutput;
                }
                else
                {
                    textOutput    = Glitch.Text(textOriginal, Convert.ToInt32(numericUpDown1.Value), true);
                    textBox1.Text = textOutput;
                }
                break;

            case 2:
                if (textBox1.Text != "")
                {
                    if (textOutput != textBox1.Text)
                    {
                        textOriginal  = textBox1.Text;
                        textOutput    = Replace.Text(textOriginal);
                        textBox1.Text = textOutput;
                    }
                    else
                    {
                        textOutput    = Replace.Text(textOriginal);
                        textBox1.Text = textOutput;
                    }
                }
                break;

            case 3:
                if (textBox1.Text != "")
                {
                    textBox1.Text = Reverse.Text(textBox1.Text);
                }
                break;

            case 4:
                if (radioButton1.Checked)
                {
                    textBox1.Text = Generate.TextAndNumbers(Convert.ToInt32(numericUpDown1.Value));
                }
                else if (radioButton2.Checked)
                {
                    textBox1.Text = Generate.OnlyText(Convert.ToInt32(numericUpDown1.Value));
                }
                else if (radioButton3.Checked)
                {
                    textBox1.Text = Generate.OnlyNumbers(Convert.ToInt32(numericUpDown1.Value));
                }
                break;
            }
            try
            {
                EmptyWorkingSet(System.Diagnostics.Process.GetCurrentProcess().Handle);
            }
            catch
            {
            }
        }
示例#16
0
        private double computeAimValue()
        {
            if (Attributes.TotalObjectCount <= 1)
            {
                return(0);
            }

            // Get player's throughput according to combo
            int comboTpCount     = Attributes.ComboThroughputs.Length;
            var comboPercentages = Generate.LinearSpaced(comboTpCount, 1.0 / comboTpCount, 1);

            double scoreComboPercentage = ((double)scoreMaxCombo) / Attributes.MaxCombo;
            double comboTp = LinearSpline.InterpolateSorted(comboPercentages, Attributes.ComboThroughputs)
                             .Interpolate(scoreComboPercentage);

            // Get player's throughput according to miss count
            double missTp = LinearSpline.InterpolateSorted(Attributes.MissCounts, Attributes.MissThroughputs)
                            .Interpolate(effectiveMissCount);

            missTp = Math.Max(missTp, 0);

            // Combine combo based throughput and miss count based throughput
            double tp = PowerMean.Of(comboTp, missTp, 20);

            // Hidden mod
            if (mods.Any(h => h is OsuModHidden))
            {
                double hiddenFactor = Attributes.AimHiddenFactor;

                // the buff starts decreasing at AR9.75 and reaches 0 at AR10.75
                if (Attributes.ApproachRate > 10.75)
                {
                    hiddenFactor = 1;
                }
                else if (Attributes.ApproachRate > 9.75)
                {
                    hiddenFactor = 1 + (1 - Math.Pow(Math.Sin((Attributes.ApproachRate - 9.75) * Math.PI / 2), 2)) * (hiddenFactor - 1);
                }

                tp *= hiddenFactor;
            }

            // Account for cheesing
            double modifiedAcc      = getModifiedAcc();
            double accOnCheeseNotes = 1 - (1 - modifiedAcc) * Math.Sqrt(totalHits / Attributes.CheeseNoteCount);

            // accOnCheeseNotes can be negative. The formula below ensures a positive acc while
            // preserving the value when accOnCheeseNotes is close to 1
            double accOnCheeseNotesPositive = Math.Exp(accOnCheeseNotes - 1);
            double urOnCheeseNotes          = 10 * greatWindow / (Math.Sqrt(2) * SpecialFunctions.ErfInv(accOnCheeseNotesPositive));
            double cheeseLevel  = SpecialFunctions.Logistic(((urOnCheeseNotes * Attributes.AimDifficulty) - 3200) / 2000);
            double cheeseFactor = LinearSpline.InterpolateSorted(Attributes.CheeseLevels, Attributes.CheeseFactors)
                                  .Interpolate(cheeseLevel);

            if (mods.Any(m => m is OsuModTouchDevice))
            {
                tp = Math.Min(tp, 1.47 * Math.Pow(tp, 0.8));
            }

            double aimValue = tpToPP(tp * cheeseFactor);

            // penalize misses
            aimValue *= Math.Pow(0.96, Math.Max(effectiveMissCount - miss_count_leniency, 0));

            // Buff long maps
            aimValue *= 1 + (SpecialFunctions.Logistic((totalHits - 2800) / 500.0) - SpecialFunctions.Logistic(-2800 / 500.0)) * 0.22;

            // Buff very high AR and low AR
            double approachRateFactor = 1.0;

            if (Attributes.ApproachRate > 10)
            {
                approachRateFactor += (0.05 + 0.35 * Math.Pow(Math.Sin(Math.PI * Math.Min(totalHits, 1250) / 2500), 1.7)) *
                                      Math.Pow(Attributes.ApproachRate - 10, 2);
            }
            else if (Attributes.ApproachRate < 8.0)
            {
                approachRateFactor += 0.01 * (8.0 - Attributes.ApproachRate);
            }

            aimValue *= approachRateFactor;

            if (mods.Any(h => h is OsuModFlashlight))
            {
                // Apply object-based bonus for flashlight.
                aimValue *= 1.0 + 0.35 * Math.Min(1.0, totalHits / 200.0) +
                            (totalHits > 200
                                ? 0.3 * Math.Min(1.0, (totalHits - 200) / 300.0) +
                             (totalHits > 500 ? (totalHits - 500) / 2000.0 : 0.0)
                                : 0.0);
            }

            // Scale the aim value down with accuracy
            double accLeniency = greatWindow * Attributes.AimDifficulty / 300;
            double accPenalty  = (0.09 / (accuracy - 1.3) + 0.3) * (accLeniency + 1.5);

            aimValue *= 0.2 + SpecialFunctions.Logistic(-((accPenalty - 0.24953) / 0.18));

            return(aimValue);
        }
示例#17
0
        /// <summary>
        /// 新增用户,密码少于8位|多于30位
        /// </summary>
        /// <param name="appWin"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool AddUser_PwdLength(Window appWin, out string msg)
        {
            try
            {
                var startTime = DateTime.Now;

                //点击新增按钮
                Button btnAddUser = appWin.Get <Button>(SearchCriteria.ByAutomationId("btnAddUser"));
                btnAddUser.Click();

                //账号名称不为空
                TextBox txtUserName = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtUserName"));
                txtUserName.BulkText = Generate.GenerateChineseWords(5);

                //密码少于8位
                TextBox pwdUserPwd = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("pwdUserPwd"));
                pwdUserPwd.Text = "123";

                //点击确定按钮
                Button btnComfirmAddUser = appWin.Get <Button>(SearchCriteria.ByAutomationId("btnComfirmAddUser"));
                btnComfirmAddUser.Click();

                try
                {
                    //捕捉提醒信息,如果能捕捉到,则测试通过
                    string error_info = appWin.Get <Label>(SearchCriteria.ByText("密码最少8位,最多30位!")).ToString();
                    //关闭提醒框
                    Button btnTips = appWin.Get <Button>(SearchCriteria.ByAutomationId("2"));
                    btnTips.Click();

                    //密码多于30位
                    pwdUserPwd.Text = "1233444444444444444444444444444444444444";

                    //点击确定按钮
                    btnComfirmAddUser.Click();

                    try
                    {
                        //捕捉提醒信息,如果能捕捉到,则测试通过
                        error_info = appWin.Get <Label>(SearchCriteria.ByText("密码最少8位,最多30位!")).ToString();
                        //关闭提醒框
                        btnTips = appWin.Get <Button>(SearchCriteria.ByAutomationId("2"));
                        btnTips.Click();

                        msg = "测试【新增用户,密码少于8位|多于30位】--通过,用时:" + (DateTime.Now - startTime).TotalSeconds;
                        return(true);
                    }
                    catch
                    {
                        msg = "测试【新增用户,密码少于8位|多于30位】--未通过,缺少密码长度验证提醒。用时:" + (DateTime.Now - startTime).TotalSeconds;
                        return(false);
                    }
                }
                catch
                {
                    msg = "测试【新增用户,密码少于8位|多于30位】--未通过,缺少密码长度验证提醒。用时:" + (DateTime.Now - startTime).TotalSeconds;
                    return(false);
                }
            }
            catch (Exception e)
            {
                msg = "测试【新增用户,密码少于8位|多于30位】--失败,原因:" + e.ToString();
                return(false);
            }
        }
示例#18
0
        public MM3Model()
        {
            // Server STORAGE 3
            this.SERVER = 10000;
            this.AddName("SERVER", SERVER);
            AnyCommand command1 = new Storage(new ParExpression(this.Command1_Operand1));

            command1.SetId(this.SERVER);
            this.AddVerb(command1);

            // START 1000
            AnyCommand command2 = new Start(new ParExpression(this.Command2_Operand1), null, null, null);

            this.AddVerb(command2);

            // GENERATE (Exponential(1,0,1/2))
            AnyBlock block1 = new Generate(new ParExpression(this.Block1_Operand1), null, null, null, null);

            this.AddVerb(block1);

            // SAVEVALUE GenerateCounter,X$GenerateCounter+1
            this.GENERATECOUNTER = 10001;
            this.AddName("GENERATECOUNTER", GENERATECOUNTER);
            AnyBlock block2 = new Savevalue(new ParExpression(this.Block2_Operand1), new ParExpression(this.Block2_Operand2));

            this.AddVerb(block2);

            // TEST L Q$Tail,20,GoAway		;Jump if in Queue >20
            this.TAIL = 10002;
            this.AddName("TAIL", TAIL);
            this.GOAWAY = 10003;
            this.AddName("GOAWAY", GOAWAY);
            AnyBlock block3 = new Test(new LiteralOperand("L"), new ParExpression(this.Block3_Operand2), new ParExpression(this.Block3_Operand3), new ParExpression(this.Block3_Operand4));

            this.AddVerb(block3);

            // QUEUE Tail
            AnyBlock block4 = new Queue(new ParExpression(this.Block4_Operand1), null);

            this.AddVerb(block4);

            // ENTER Server,1
            AnyBlock block5 = new Enter(new ParExpression(this.Block5_Operand1), new ParExpression(this.Block5_Operand2));

            this.AddVerb(block5);

            // DEPART Tail
            AnyBlock block6 = new Depart(new ParExpression(this.Block6_Operand1), null);

            this.AddVerb(block6);

            // ADVANCE (Exponential(2,0,1/0.2))
            AnyBlock block7 = new Advance(new ParExpression(this.Block7_Operand1), null);

            this.AddVerb(block7);

            // LEAVE Server,1
            AnyBlock block8 = new Leave(new ParExpression(this.Block8_Operand1), new ParExpression(this.Block8_Operand2));

            this.AddVerb(block8);

            // SAVEVALUE RejetionProb,(X$RejectCounter/X$GenerateCounter)
            this.REJETIONPROB = 10004;
            this.AddName("REJETIONPROB", REJETIONPROB);
            this.REJECTCOUNTER = 10005;
            this.AddName("REJECTCOUNTER", REJECTCOUNTER);
            AnyBlock block9 = new Savevalue(new ParExpression(this.Block9_Operand1), new ParExpression(this.Block9_Operand2));

            this.AddVerb(block9);

            // TERMINATE 1
            AnyBlock block10 = new Terminate(new ParExpression(this.Block10_Operand1));

            this.AddVerb(block10);

            // GoAway	SAVEVALUE RejectCounter,X$RejectCounter+1
            this.GOAWAY = 11;
            this.ReplaceNameId("GOAWAY", GOAWAY);
            AnyBlock block11 = new Savevalue(new ParExpression(this.Block11_Operand1), new ParExpression(this.Block11_Operand2));

            this.AddVerb(block11);

            // TERMINATE        ;Delete rejected.
            AnyBlock block12 = new Terminate(null);

            this.AddVerb(block12);
        }
示例#19
0
        /// <summary>
        /// 新增用户成功,同时关闭新增用户窗口
        /// </summary>
        /// <param name="appWin"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool AddUserSucc(Window appWin, out string msg)
        {
            try
            {
                var startTime = DateTime.Now;

                //点击新增按钮
                Button btnAddUser = appWin.Get <Button>(SearchCriteria.ByAutomationId("btnAddUser"));
                btnAddUser.Click();

                //账号名称不为空
                TextBox txtUserName = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtUserName"));
                txtUserName.BulkText = Generate.GenerateChineseWords(5);

                //密码不少于8个字符
                TextBox pwdUserPwd = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("pwdUserPwd"));
                pwdUserPwd.Text = "12345678";

                //正确邮箱地址
                TextBox txtEmail = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtEmail"));
                txtEmail.Text = "*****@*****.**";

                //选择角色
                ComboBox cbRole = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <ComboBox>(SearchCriteria.ByAutomationId("cbRole"));
                cbRole.Select(1);

                //真实姓名不为空
                TextBox txtRealName = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtRealName"));
                txtRealName.BulkText = Generate.GenerateChineseWords(3);

                //身份证不为空
                TextBox txtIDCard = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtIDCard"));
                txtIDCard.Text = "440444199605043242";

                //职务不为空
                TextBox txtDuty = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtDuty"));
                txtDuty.BulkText = Generate.GenerateChineseWords(3);

                //手机不为空
                TextBox txtTel = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <TextBox>(SearchCriteria.ByAutomationId("txtTel"));
                txtTel.Text = "13422222222";

                //选择状态
                ComboBox cbStauts = appWin.MdiChild(SearchCriteria.ByAutomationId("AddOrEditUserView")).Get <ComboBox>(SearchCriteria.ByAutomationId("cbStauts"));
                cbStauts.Select(0);

                //点击确定按钮
                Button btnComfirmAddUser = appWin.Get <Button>(SearchCriteria.ByAutomationId("btnComfirmAddUser"));
                btnComfirmAddUser.Click();

                try
                {
                    //捕捉提醒信息,如果不能捕捉到,则测试不通过
                    string error_info = appWin.Get <Label>(SearchCriteria.ByText("新增成功!")).ToString();
                    //关闭提醒框
                    Button btnTips = appWin.Get <Button>(SearchCriteria.ByAutomationId("2"));
                    btnTips.Click();

                    try
                    {
                        //捕捉新增用户窗口,如果不能捕捉到,则测试通过
                        string add_win = appWin.Get <Label>(SearchCriteria.ByText("新增用户")).ToString();

                        msg = "测试【新增用户成功,同时关闭新增用户窗口】--未通过,未关闭新增用户窗口。用时:" + (DateTime.Now - startTime).TotalSeconds;
                        return(true);
                    }
                    catch
                    {
                        msg = "测试【新增用户成功,同时关闭新增用户窗口】--通过,用时:" + (DateTime.Now - startTime).TotalSeconds;
                        return(true);
                    }
                }
                catch
                {
                    msg = "测试【新增用户成功,同时关闭新增用户窗口】-未通过。用时:" + (DateTime.Now - startTime).TotalSeconds;
                    return(false);
                }
            }
            catch (Exception e)
            {
                msg = "测试【新增用户成功,同时关闭新增用户窗口】--失败,原因:" + e.ToString();
                return(false);
            }
        }
示例#20
0
    // Update is called once per frame
    void Update()
    {
        // Get lilypad positions
        GameObject g         = GameObject.Find("ExtraPads");
        Generate   generator = g.GetComponent <Generate> ();

        padLocations = generator.pads;

//		// Get the bluetooth data
//		string strData = bleReceiver.getData ();
//		bleVal = int.Parse(strData);

        // Get the bluetooth data
        bleVal = bleReceiver.getData();

        if (bleVal < THRESHOLD && !isPreviousHigh && !jumpInProgress)
        {
            // Initiate a jump
            jumpInProgress = true;
            jumpNum++;
            isPreviousHigh = true;
            if (jumpNum == 1)
            {
                // Position of the first lilypad
                startPoint = new Vector2(0.64f, 0.1f);
            }
            else
            {
                // Position of a lilypad that is not the first lilypad (first one is
                // hard coded in Unity and is not in the dictionary).
                startPoint = padLocations[jumpNum - 2];
            }
        }
        else if (bleVal > THRESHOLD)
        {
            isPreviousHigh = false;
        }

        // If jump button pressed and we aren't already jumping
//		if (Input.GetKeyUp ("space") && !jumpInProgress) {
//			// Initiate a jump
//			jumpInProgress = true;
//			jumpNum++;
//		}

        if (jumpNum > 4)
        {
            // Give encouragement
            StartCoroutine("displayEncouragement");
            // Restart game
            transform.position = new Vector2(0.45f, 0.1f);
            jumpNum            = 0;
            jumpInProgress     = false;
        }

        if (jumpInProgress)
        {
            Debug.Log(padLocations [jumpNum - 1]);
            transform.position = CalculateCubicBezierPoint(t,
                                                           startPoint, (Vector2)startPoint + new Vector2(1.5f, 2.0f),
                                                           (Vector2)startPoint + new Vector2(3.0f, 2.0f),
                                                           padLocations[jumpNum - 1]);
            // Update time
            t += 0.02f;
            if (Mathf.Abs(1.0f - t) < 0.001f)
            {
                jumpInProgress = false;
                t = 0.0f;
            }
        }

        //Debug.Log ("Battery level is " + BatteryLevelPlugin.GetBatteryLevel());
        //Debug.Log ("Bluetooth Device found named: " + BatteryLevelPlugin.GetBleDeviceName ());
        //UnityToastExample.ScanDevices ();

        // We get the text property of our receiver
//		javaMessage = jc.GetStatic<string> ("text");
//		Debug.Log ("RECEIVED MESSAGE is: " + javaMessage);

        // Get the data from the ble module
        //Debug.Log ("Data value is: " + blerec.getData ());
    }
        public void ProviderMatchesManagedProviderArbitraryLarge64_GH286()
        {
            var samples = Generate.RandomComplex(46500, GetUniform(1));

            Verify(samples, 10, FourierTransformScaling.NoScaling, FourierTransformControl.CreateManaged().Forward, FourierTransformControl.Provider.Forward);
        }
        public override bool ApplyOn(ExecutableComponent oModSub)
        {
            //string outputString = "";
            string[] output1 = new string[count];
            using (var csvFile = new CSVFiler(CsvPath))
            {
                for (int i = 0; i < count; i++)
                {
                    double xi       = this.xi[i];
                    double xn       = this.xn[i];
                    double stepSize = this.stepSize[i];
                    Data   input    = this.input[i];
                    Data   output   = this.output[i];
                    string option   = this.option[i];

                    //Selecting the initial step size as 1/1000th of interval
                    double h1 = (xn - xi) / 1000;
                    bool   zeroSensitivity = false;
                    while (true)
                    {
                        double f1 = EvalModel(oModSub, input, output, xi);
                        double f2 = EvalModel(oModSub, input, output, xi + h1);

                        // If the output appears to be insensitive to the input
                        if ((Math.Abs(f1 - f2)) < 1e-16)
                        {
                            // Duplicate the step
                            h1 *= 2;
                            // If the step is greater than the studied interval,
                            // declare than the output is insensitive
                            if (h1 > (xn - xi))
                            {
                                zeroSensitivity = true;
                                break;
                            }
                        }
                        else
                        {
                            zeroSensitivity = false;
                            break;
                        }
                    }

                    double h2    = h1 / 10;
                    double h     = 0;
                    double termc = 0.01;
                    if (zeroSensitivity == true)
                    {
                        Console.WriteLine("The output has zero sensitivity with respect  to selected input");
                    }
                    else
                    {
                        double x;
                        double f1;
                        double f2;
                        while (true)
                        {
                            x  = xi;
                            f1 = EvalModel(oModSub, input, output, x);
                            x  = xi + 2 * h1;
                            f2 = EvalModel(oModSub, input, output, x);
                            double s1 = (f2 - f1) / (2 * h1);

                            x  = xi;
                            f1 = EvalModel(oModSub, input, output, x);
                            x  = xi + 2 * h2;
                            f2 = EvalModel(oModSub, input, output, x);
                            double s2 = (f2 - f1) / (2 * h2);

                            double diff = (s1 - s2) / s1;

                            // Deciding the step size for partial derivative
                            // If the sensitivites are similar keep the step
                            if (diff <= termc)
                            {
                                break;
                            }

                            // Other wise reduce the step by 10
                            h1  = h2;
                            h2 /= 10;
                        }

                        h = h1;

                        double[] xinp   = Generate.LinearRange(xi, stepSize, xn);
                        int      nSteps = xinp.Length;
                        double[] sens   = new double[nSteps];
                        double[] f0s    = new double[nSteps];



                        xinp[0] = xi;
                        f0s[0]  = EvalModel(oModSub, input, output, xi);

                        csvFile.NewRow();
                        output1[i] = output1[i] + input.Name + " Sen(abs)" + "\r\n";
                        for (int j = 0; j < nSteps; j++)
                        {
                            x  = xinp[j] - h;
                            f1 = EvalModel(oModSub, input, output, x);
                            x  = xinp[j] + h;
                            f2 = EvalModel(oModSub, input, output, x);

                            if (option == "Absolute Sensitivity")
                            {
                                sens[j] = EvalSenAb(f1, f2, h);
                            }
                            else
                            {
                                sens[j]    = EvalSenRel(f1, f2, f0s[j], xinp[j], h);
                                f0s[j + 1] = EvalModel(oModSub, input, output, xinp[j + 1]);
                            }

                            csvFile.AddToRow(xinp[j]);
                            csvFile.AddToRow(sens[j]);
                            csvFile.WriteRow();
                        }
                    }
                }
            }
            //outputString = output1[0];
            //output_struct = new Treatment_InOut(outputString);
            return(true);
        }
 /// <summary>
 /// Create a new diagonal matrix with diagonal values sampled from the provided random distribution.
 /// </summary>
 public static DiagonalMatrix CreateRandom(int rows, int columns, IContinuousDistribution distribution)
 {
     return(new DiagonalMatrix(new DiagonalMatrixStorage <float>(rows, columns, Generate.RandomSingle(Math.Min(rows, columns), distribution))));
 }
示例#24
0
        private void SimpanTSB_Click(object sender, EventArgs e)
        {
            //simpan header
            gin      k   = new gin();
            Generate gen = new Generate();

            txtGRNNO.Text = gen.genMIN();
            k.GINNO       = txtGRNNO.Text;
            k.DATE        = dateCreated.Value;
            DataRow selectedDIV = ((DataRowView)cbDIV.SelectedItem).Row;

            k.GDIV              = selectedDIV["DIVID"].ToString();
            k.APPROVE           = 0;
            k.APPROVEBY         = "";
            k.CLOSE             = 0;
            k.CUSTVENDCODE      = txtCustomerID.Text;
            k.DOCREGNO          = "";
            k.OFFICER           = GlobalVariables.GUserID;
            k.DELIVERYTO        = txtRefer.Text; // untuk refer to
            k.REMARKS           = txtRemarks.Text;
            k.STOREID           = cbStore.Text;
            k.TYPE              = cbJENIS.Text;
            k.DELIVERYTOADDRESS = txtAddress.Text;
            k.DELIVERYTONAME    = txtCustomerDesc.Text;
            //k.OFFICER = GlobalVariables.GUserID;
            //k.CLOSE = 0;
            //  k.STYLEID="";
            if ((txtGRNNO.Text == "") || (txtCustomerID.Text == ""))
            {
                MessageBox.Show("Isian Belum lengkap untuk PONO");
            }
            else if (new ginCRUD().insertData(k))
            {
                gindetail d = new gindetail();
                dtGrid.EndEdit();
                for (int i = 0; i < dtGrid.Rows.Count - 1; i++)
                {
                    //d.PONO = txtJONO.Text;
                    d.GINNO       = txtGRNNO.Text;
                    d.ID          = Convert.ToInt32(dtGrid.Rows[i].Cells["hID"].Value); //Convert.ToInt32(dtGrid.Rows[i].Cells["hCostingID"].Value);
                    d.GRNNO       = Convert.ToString(dtGrid.Rows[i].Cells["hGRNNO"].Value);
                    d.ITEMSID     = dtGrid.Rows[i].Cells["hItemsID"].Value == null ? null : dtGrid.Rows[i].Cells["hItemsID"].Value.ToString();
                    d.DESCRIPTION = dtGrid.Rows[i].Cells["hDescription"].Value == null ? null : dtGrid.Rows[i].Cells["hDescription"].Value.ToString().ToString();
                    d.QUANTITY    = Convert.ToDecimal(dtGrid.Rows[i].Cells["hQuantity"].Value);
                    d.UOM         = dtGrid.Rows[i].Cells["hUOM"].Value == null ? null : dtGrid.Rows[i].Cells["hUOM"].Value.ToString();
                    d.COLORID     = dtGrid.Rows[i].Cells["hColorID"].Value == null ? null : dtGrid.Rows[i].Cells["hColorID"].Value.ToString();
                    d.GRADE       = dtGrid.Rows[i].Cells["hGrade"].Value == null ? null : dtGrid.Rows[i].Cells["hGrade"].Value.ToString();
                    d.JENIS       = cbJENIS.Text;
                    d.PONO        = Convert.ToString(dtGrid.Rows[i].Cells["hPONO"].Value);
                    d.SIZEID      = Convert.ToString(dtGrid.Rows[i].Cells["hSizeID"].Value);
                    d.STYLEID     = dtGrid.Rows[i].Cells["hStyleID"].Value == null ? null : dtGrid.Rows[i].Cells["hStyleID"].Value.ToString();
                    d.STYLEIDTO   = dtGrid.Rows[i].Cells["hStyleID"].Value == null ? null : dtGrid.Rows[i].Cells["hStyleID"].Value.ToString();
                    if (dtGrid.Rows[i].HeaderCell.Value.ToString() == "#")
                    {
                        if (new gindetailCRUD().insertData(d))
                        {
                            dtGrid.Rows[i].HeaderCell.Value = "V";
                        }
                        else
                        {
                        }
                    }
                }

                MessageBox.Show("Data berhasil di tambahkan");
                SimpanTSB.Enabled = false;
                UbahTSB.Enabled   = true;
                dtGrid.Enabled    = true;
                // Binding();
            }
            else
            {
                MessageBox.Show("Data gagal ditambahkan");
            }
        }
示例#25
0
        public static UIElement[] GenerateGearCirclesGeometry(Point Center,
                                                              double DedendumDiameter, double BaseDiameter, double ReferencePitchDiameter,
                                                              double WorkingPitchDiameter, double AddendumDiameter)
        {
            List <UIElement> Elements = new();

            EllipseGeometry DedendumGeometry = new()
            {
                Center  = Center,
                RadiusX = DedendumDiameter / 2,
                RadiusY = DedendumDiameter / 2
            };

            EllipseGeometry BaseGeometry = new()
            {
                Center  = Center,
                RadiusX = BaseDiameter / 2,
                RadiusY = BaseDiameter / 2
            };

            EllipseGeometry RefPitchGeometry = new()
            {
                Center  = Center,
                RadiusX = ReferencePitchDiameter / 2,
                RadiusY = ReferencePitchDiameter / 2
            };

            EllipseGeometry WorkPitchGeometry = new()
            {
                Center  = Center,
                RadiusX = WorkingPitchDiameter / 2,
                RadiusY = WorkingPitchDiameter / 2
            };

            EllipseGeometry AddendumGeometry = new()
            {
                Center  = Center,
                RadiusX = AddendumDiameter / 2,
                RadiusY = AddendumDiameter / 2
            };

            Path DedendumPath = new()
            {
                Stroke          = Brushes.Black,
                StrokeThickness = 0.5,
                Data            = DedendumGeometry
            };

            Elements.Add(DedendumPath);

            Path BasePath = new()
            {
                Stroke          = Brushes.Black,
                StrokeThickness = 0.5,
                StrokeDashArray = DoubleCollection.Parse("1,1"),
                Data            = BaseGeometry
            };

            Elements.Add(BasePath);

            Path RefPitchPath = new()
            {
                Stroke          = Brushes.Black,
                StrokeThickness = 0.5,
                StrokeDashArray = DoubleCollection.Parse("3,1"),
                Data            = RefPitchGeometry
            };

            Elements.Add(RefPitchPath);

            Path WorkPitchPath = new()
            {
                Stroke          = Brushes.Black,
                StrokeThickness = 1,
                Data            = WorkPitchGeometry
            };

            Elements.Add(WorkPitchPath);

            Path AddendumPath = new()
            {
                Stroke          = Brushes.Black,
                StrokeThickness = 0.5,
                Data            = AddendumGeometry
            };

            Elements.Add(AddendumPath);

            return(Elements.ToArray());
        }

        public static SortedDictionary <double, CurveType> GenerateAngleData(
            double dTheta, double Teeth, double InvoluteAngle,
            double ToothSpacingAngle, double TipAngle, double StartAngleOffset)
        {
            SortedDictionary <double, CurveType> GearAngleData = new();
            const double InvoluteOffset = 0.0001;

            for (int j = 0; j < Teeth; j++)
            {
                GearAngleData.Add(StartAngleOffset + (j * ToothSpacingAngle) + InvoluteOffset, CurveType.RisingInvolute);
                GearAngleData.Add(InvoluteAngle + StartAngleOffset + (j * ToothSpacingAngle) - InvoluteOffset, CurveType.RisingInvolute);
            }

            double[] Tip = Generate.LinearSpaced(5, StartAngleOffset + InvoluteAngle, StartAngleOffset + InvoluteAngle + TipAngle);
            for (int j = 0; j < Teeth; j++)
            {
                foreach (double Item in Tip.Select(n => n + (j * ToothSpacingAngle)))
                {
                    GearAngleData.Add(Item, CurveType.Addendum);
                }
            }

            for (int j = 0; j < Teeth; j++)
            {
                GearAngleData.Add(StartAngleOffset + InvoluteAngle + TipAngle + (j * ToothSpacingAngle) + InvoluteOffset, CurveType.ReturningInvolute);
                GearAngleData.Add(StartAngleOffset + (2 * InvoluteAngle) + TipAngle + (j * ToothSpacingAngle) - InvoluteOffset, CurveType.ReturningInvolute);
            }

            double[] Dwell = Generate.LinearSpaced(5, StartAngleOffset + (2 * InvoluteAngle) + TipAngle, StartAngleOffset + ToothSpacingAngle);
            for (int j = 0; j < Teeth; j++)
            {
                foreach (double Item in Dwell.Select(n => n + (j * ToothSpacingAngle)))
                {
                    GearAngleData.Add(Item, CurveType.Dedendum);
                }
            }


            return(GearAngleData);
        }

        public static Point[] GenerateInvoluteProfile(double dTheta, double BaseRadius, double AddendumRadius,
                                                      double InvoluteAngle, bool IsDirectionInverted)
        {
            double Alpha           = InverseInvolute(InvoluteAngle);
            int    NegateDirection = IsDirectionInverted ? -1 : 1;

            List <Point> List = new();

            for (double i = 0; i < Alpha * 1.5; i += dTheta / 2)
            {
                Point InvolutePoint = new()
                {
                    X = BaseRadius * (Math.Cos(i) + (i * Math.Sin(i))),
                    Y = NegateDirection * BaseRadius * (Math.Sin(i) - (i * Math.Cos(i)))
                };

                if (Polar(InvolutePoint).Rho <= AddendumRadius)
                {
                    List.Add(InvolutePoint);
                }
            }
            return(List.ToArray());
        }

        public static PointCollection GenerateGearProfile(double dTheta,
                                                          double BaseRadius, double DedendumRadius, double AddendumRadius,
                                                          SortedDictionary <double, CurveType> AngleCollection, Point Center)
        {
            PointCollection Result = new();

            double?InvoluteMaxAngle = null;

            for (int i = 1; i < AngleCollection.Count; i++)
            {
                KeyValuePair <double, CurveType> Data = AngleCollection.ElementAt(i);
                double Theta = Data.Key;
                switch (Data.Value)
                {
                case CurveType.Dedendum:
                    Result.Add(TranslatePoint(new Point
                    {
                        X = DedendumRadius * Math.Cos(Theta),
                        Y = DedendumRadius * Math.Sin(Theta),
                    }, Center.X, Center.Y));
                    break;

                case CurveType.RisingInvolute:
                    if (AngleCollection.ElementAt(i - 1).Value != CurveType.RisingInvolute)
                    {
                        continue;
                    }

                    double  RisingInvAlpha = AngleCollection.ElementAt(i).Key - AngleCollection.ElementAt(i - 1).Key;
                    Point[] RisingInvolute = GenerateInvoluteProfile(dTheta, BaseRadius, AddendumRadius, RisingInvAlpha, false);

                    foreach (Point Item in RisingInvolute)
                    {
                        Point RaisingClampedPoint = Item;

                        if (DedendumRadius > BaseRadius)
                        {
                            PolarPoint RaisingPolarPoint = Polar(Item);
                            if (RaisingPolarPoint.Rho < DedendumRadius)
                            {
                                RaisingClampedPoint = Cartesian(DedendumRadius, RaisingPolarPoint.Theta);
                            }
                        }

                        Point RisingTranslatedPoint = TranslatePoint(RaisingClampedPoint, Center.X, Center.Y);
                        Point RisingRotatedPoint    = RotatePointAAroundB(RisingTranslatedPoint, Center,
                                                                          AngleCollection.ElementAt(i - 1).Key);

                        Result.Add(RisingRotatedPoint);
                    }
                    break;

                case CurveType.ReturningInvolute:
                    if (AngleCollection.ElementAt(i - 1).Value != CurveType.ReturningInvolute)
                    {
                        continue;
                    }

                    double  ReturningInvAlpha = AngleCollection.ElementAt(i).Key - AngleCollection.ElementAt(i - 1).Key;
                    Point[] ReturningInvolute = GenerateInvoluteProfile(dTheta, BaseRadius, AddendumRadius, ReturningInvAlpha, true);

                    foreach (Point Item in ReturningInvolute.Reverse())
                    {
                        Point ReturningClampedPoint = Item;

                        if (DedendumRadius > BaseRadius)
                        {
                            PolarPoint ReturningPolarPoint = Polar(Item);
                            if (ReturningPolarPoint.Rho < DedendumRadius)
                            {
                                ReturningClampedPoint = Cartesian(DedendumRadius, ReturningPolarPoint.Theta);
                            }
                        }

                        Point ReturningTranslatedPoint = TranslatePoint(ReturningClampedPoint, Center.X, Center.Y);
                        Point ReturningRotatedPoint    = RotatePointAAroundB(ReturningTranslatedPoint, Center,
                                                                             AngleCollection.ElementAt(i).Key);

                        Result.Add(ReturningRotatedPoint);
                    }
                    break;

                case CurveType.Addendum:
                    InvoluteMaxAngle ??= Theta - AngleCollection.ElementAt(i - 1).Key;

                    Result.Add(TranslatePoint(new Point
                    {
                        X = AddendumRadius * Math.Cos(Theta),
                        Y = AddendumRadius * Math.Sin(Theta),
                    }, Center.X, Center.Y));
                    break;
                }
            }
            return(Result);
        }

        public static CalculationsResultsData Calculate(double m, int z1, int z2, double x1, double x2)
        {
            double dTheta = 0.1;
            double alpha  = Radians(20);

            double i = (double)z2 / z1;

            double inv_alpha_prime = (2 * Math.Tan(alpha) * (x1 + x2) / (z1 + z2)) + Involute(alpha);
            double alpha_prime     = InverseInvolute(inv_alpha_prime);

            double y = (double)(z1 + z2) / 2 * ((Math.Cos(alpha) / Math.Cos(alpha_prime)) - 1);
            double a = (((double)(z1 + z2) / 2) + y) * m;

            // Pitch circle
            double d1 = z1 * m;
            double d2 = z2 * m;

            // Base circle
            double d_b1 = d1 * Math.Cos(alpha);
            double d_b2 = d2 * Math.Cos(alpha);

            // Working pitch diameter
            double d_prime1 = d_b1 / Math.Cos(alpha_prime);
            double d_prime2 = d_b2 / Math.Cos(alpha_prime);

            // Addendum
            double h_a1 = (1 + y - x1) * m;
            double h_a2 = (1 + y - x2) * m;
            //double h_a1 = (1 + x1) * m;
            //double h_a2 = (1 + x2) * m;

            // Addendum circle
            double d_a1 = d1 + (2 * h_a1);
            double d_a2 = d2 + (2 * h_a2);

            // Dedendum circle
            double h = (2.25 + y - (x1 + x2)) * m;
            //double h = 2.25 * m;
            double d_f1 = d_a1 - (2 * h);
            double d_f2 = d_a2 - (2 * h);

            // Overlap coefficient
            double epsilon = (Math.Sqrt(Math.Pow(d_a1 / 2, 2) - Math.Pow(d_b1 / 2, 2))
                              + Math.Sqrt(Math.Pow(d_a2 / 2, 2) - Math.Pow(d_b2 / 2, 2))
                              - (a * Math.Sin(alpha_prime))) / (Math.PI * m * Math.Cos(alpha));

            //Pitch
            double p1 = Math.PI * d1 / z1;
            double p2 = Math.PI * d2 / z2;
            double p  = Math.PI * m;
            //double spacing_1 = p / (d1 / 2);

            // Arc length of tooth at the reference pitch circle
            double s_1 = m * ((Math.PI / 2) + (2 * x1 * Math.Tan(alpha)));
            double s_2 = m * ((Math.PI / 2) + (2 * x2 * Math.Tan(alpha)));

            // Arc length of tooth at the working pitch circle
            double sw_1 = d_prime1 * ((s_1 / d1) - Involute(alpha_prime) + Involute(alpha));
            double sw_2 = d_prime2 * ((s_2 / d2) - Involute(alpha_prime) + Involute(alpha));

            // Arc length of tooth at the base pitch circle
            double sb_1 = d_b1 * ((sw_1 / d_prime1) + Involute(alpha_prime));
            double sb_2 = d_b2 * ((sw_2 / d_prime2) + Involute(alpha_prime));

            // InverseInvolute angle of whole involute curve
            double alpha_a1 = Math.Acos(d1 / d_a1 * Math.Cos(alpha));
            double alpha_a2 = Math.Acos(d2 / d_a2 * Math.Cos(alpha));

            // Arc length of tooth at the base pitch circle
            double sa_1 = d_a1 * ((sb_1 / d_b1) - Involute(alpha_a1));
            double sa_2 = d_a2 * ((sb_2 / d_b2) - Involute(alpha_a2));

            double tip_angle1 = 2 * sa_1 / d_a1;
            double tip_angle2 = 2 * sa_2 / d_a2;

            double ang  = 2 * s_1 / d1;
            double angw = 2 * sw_1 / d_prime1;
            double angb = 2 * sb_1 / d_b1;
            double anga = 2 * sa_1 / d_a1;

            double test  = Math.Acos(d1 / d1 * Math.Cos(alpha));
            double testw = Math.Acos(d1 / d_prime1 * Math.Cos(alpha));
            double testb = Math.Acos(d1 / d_b1 * Math.Cos(alpha));
            double testa = Math.Acos(d1 / d_a1 * Math.Cos(alpha));

            double rho = 0.38 * m;

            List <UIElement> GearElements = new();

            GearElements.AddRange(GenerateGearCirclesGeometry(new Point(0, 0), d_f1, d_b1, d1, d_prime1, d_a1));
            GearElements.AddRange(GenerateGearCirclesGeometry(new Point(a, 0), d_f2, d_b2, d2, d_prime2, d_a2));

            SortedDictionary <double, CurveType> Data1 = GenerateAngleData(dTheta, z1, Involute(alpha_a1), 2 * Math.PI / z1, tip_angle1, Involute(alpha_prime));
            PointCollection Points1       = GenerateGearProfile(dTheta, d_b1 / 2, d_f1 / 2, d_a1 / 2, Data1, new Point(0, 0));
            Polygon         InvoluteLine1 = new()
            {
                Stroke          = Brushes.DarkOrange,
                StrokeThickness = 0.75,
                Points          = Points1
            };

            GearElements.Add(InvoluteLine1);

            double Offset = ((double)1 / 2 * Math.PI) - (2 * sb_2 / d_b2) + Involute(alpha_prime);
            SortedDictionary <double, CurveType> Data2 = GenerateAngleData(dTheta, z2, Involute(alpha_a2), 2 * Math.PI / z2, tip_angle2, Offset);
            PointCollection Points2       = GenerateGearProfile(dTheta, d_b2 / 2, d_f2 / 2, d_a2 / 2, Data2, new Point(a, 0));
            Polygon         InvoluteLine2 = new()
            {
                Stroke          = Brushes.Red,
                StrokeThickness = 0.75,
                Points          = Points2
            };

            GearElements.Add(InvoluteLine2);

            GearCharacteristicsData Pinion = new()
            {
                NumberOfTeeth          = z1,
                ShiftCoefficient       = x1,
                ReferencePitchDiameter = d1,
                OperatingPitchDiameter = d_prime1,
                DedendumDiameter       = d_f1,
                AddendumDiameter       = d_a1,
                BaseCircleDiameter     = d_b1,
                ThicknessReference     = s_1,
                ThicknessOperating     = sw_1,
                ThicknessBase          = sb_1,
                ThicknessTip           = sa_1,
                AngleTip = alpha_a1
            };

            GearCharacteristicsData Gear = new()
            {
                NumberOfTeeth          = z2,
                ShiftCoefficient       = x2,
                ReferencePitchDiameter = d2,
                OperatingPitchDiameter = d_prime2,
                DedendumDiameter       = d_f2,
                AddendumDiameter       = d_a2,
                BaseCircleDiameter     = d_b2,
                ThicknessReference     = s_2,
                ThicknessOperating     = sw_2,
                ThicknessBase          = sb_2,
                ThicknessTip           = sa_2,
                AngleTip = alpha_a2
            };

            GearMechanismData MechanismData = new()
            {
                Module                    = m,
                PressureAngle             = 20,
                OperatingPressureAngle    = Degrees(alpha_prime),
                CenterDistance            = a,
                CenterDistanceCoefficient = y,
                TransmissionRatio         = i,
                ContactRatio              = epsilon,
                Pitch        = p,
                FilletRadius = rho
            };

            CalculationsResultsData Result = new()
            {
                GearData          = Gear,
                PinionData        = Pinion,
                MechanismData     = MechanismData,
                MechanismGeometry = GearElements,
                PinionPoints      = Points1,
                GearPoints        = Points2,
                ActionPosition    = new Point(Pinion.OperatingPitchDiameter / 2, 0),
                GearPosition      = new Point((Pinion.OperatingPitchDiameter / 2) + (Gear.OperatingPitchDiameter / 2), 0),
                PinionPosition    = new Point(0, 0)
            };

            return(Result);
        }
    }
}
示例#26
0
        private void DeleteChildren(TableSchema parentTable, CodeStatementCollection codeStatements)
        {
            //				// Delete each of the child Department records in a cascade.
            //				ServerDataModel.DepartmentRow[] departmentRows = objectRow.GetDepartmentRows();
            //				for (int departmentIndex = 0; departmentIndex < departmentRows.Length; departmentIndex = (departmentIndex + 1))
            //				{
            //					// Get the next department in the list.
            //					ServerDataModel.DepartmentRow departmentRow = departmentRows[departmentIndex];
            //					// Lock the ADO record.
            //					departmentRow.ReaderWriterLock.AcquireWriterLock(System.Threading.Timeout.Infinite);
            //					adoResourceManager.Add(departmentRow.ReaderWriterLock);
            //					// Optimistic Concurrency Check.
            //					if ((departmentRow.RowVersion != rowVersion))
            //					{
            //						throw new System.Exception("This record is busy.  Please try again later.");
            //					}
            //					// Delete the SQL record as part of a transaction.
            //					SqlCommand departmentCommand = new SqlCommand(@"delete ""Department"" where ""DepartmentId""=@departmentId", sqlResourceManager.SqlConnection);
            //					departmentCommand.Parameters.Add(new SqlParameter("@departmentId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, departmentRow[ServerDataModel.Department.DepartmentIdColumn]));
            //					sqlCommands.Add(departmentCommand);
            //					// Delete the ADO record as part of a transaction.
            //					adoResourceManager.Add(departmentRow);
            //					departmentRow[ServerDataModel.Department.RowVersionColumn] = ServerDataModel.IncrementRowVersion();
            //					departmentRow.Delete();
            //				}
            foreach (KeyrefSchema childKeyref in parentTable.ChildKeyrefs)
            {
                TableSchema childTable = childKeyref.Selector;
                if (childTable.RootTable == parentTable && childTable != this.tableSchema)
                {
                    continue;
                }

                string parentRowVariable = string.Format("{0}Row", Generate.CamelCase(parentTable.Name));
                string rowArrayType      = string.Format("{0}.{1}Row[]", tableSchema.DataModelSchema.Name, childTable.Name);
                string rowArrayVariable  = string.Format("{0}{1}Rows", Generate.CamelCase(parentTable.Name), childTable.Name);
                string rowType           = string.Format("{0}.{1}Row", tableSchema.DataModelSchema.Name, childTable.Name);
                string rowVariable       = string.Format("{0}Row", Generate.CamelCase(childTable.Name));
                string methodName        = string.Format("Get{0}Rows", childTable.Name);
                string iteratorVariable  = string.Format("{0}Index", Generate.CamelCase(childTable.Name));
                codeStatements.Add(new CodeCommentStatement(string.Format("Delete each of the child {0} records in a cascade.", childTable.Name)));
                codeStatements.Add(new CodeVariableDeclarationStatement(rowArrayType, rowArrayVariable, new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(parentRowVariable), methodName)));

                CodeStatementCollection iteratorStatements = new CodeStatementCollection();
                iteratorStatements.Add(new CodeCommentStatement(string.Format("Get the next {0} row in the list of children and lock it for the duration of the transaction.", childTable.Name)));
                iteratorStatements.Add(new CodeVariableDeclarationStatement(rowType, rowVariable, new CodeIndexerExpression(new CodeVariableReferenceExpression(rowArrayVariable), new CodeVariableReferenceExpression(iteratorVariable))));
                iteratorStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "ReaderWriterLock"), "AcquireWriterLock", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Threading.Timeout)), "Infinite"))));
                iteratorStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("adoResourceManager"), "Add", new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "ReaderWriterLock"))));

                //				// The Optimistic Concurrency check allows only one client to update a record at a time.
                //				if ((departmentRow.RowVersion != rowVersion))
                //				{
                //					throw new System.Exception("This record is busy.  Please try again later.");
                //				}
                if (childTable == this.tableSchema)
                {
                    iteratorStatements.Add(new CodeCommentStatement("The Optimistic Concurrency check allows only one client to update a record at a time."));
                    iteratorStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "RowVersion"), CodeBinaryOperatorType.IdentityInequality, new CodeArgumentReferenceExpression("rowVersion")),
                                                                      new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(System.Exception), new CodePrimitiveExpression("This record is busy.  Please try again later.")))));
                }

                DeleteChildren(childTable, iteratorStatements);

                //					// Delete the Department record from the SQL data model.
                //					sqlCommand = new SqlCommand("delete \"Department\" where \"DepartmentId\"=@departmentId", sqlResourceManager.SqlConnection);
                //					sqlCommand.Parameters.Add(new SqlParameter("@departmentId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, departmentRow[ServerDataModel.Department.DepartmentIdColumn]));
                //					sqlCommands.Add(sqlCommand);
                if (childTable.IsPersistent)
                {
                    iteratorStatements.Add(new CodeCommentStatement(string.Format("Delete the {0} record from the SQL data model.", childTable.Name)));
                    string whereClause = string.Empty;
                    if (childTable.PrimaryKey != null)
                    {
                        foreach (ColumnSchema columnSchema in childTable.PrimaryKey.Fields)
                        {
                            whereClause += string.Format("\"{0}\"=@{1}", columnSchema.Name, Generate.CamelCase(columnSchema.Name));
                        }
                    }
                    string deleteCommandText = string.Format("delete \"{0}\" where {1}", childTable.Name, whereClause);
                    iteratorStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("sqlCommand"), new CodeObjectCreateExpression("SqlCommand", new CodePrimitiveExpression(deleteCommandText), new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("sqlResourceManager"), "SqlConnection"))));
                    if (childTable.PrimaryKey != null)
                    {
                        foreach (ColumnSchema columnSchema in childTable.PrimaryKey.Fields)
                        {
                            string         variableName   = Generate.CamelCase(columnSchema.Name);
                            CodeExpression codeExpression = new CodeIndexerExpression(new CodeVariableReferenceExpression(string.Format("{0}Row", Generate.CamelCase(childTable.Name))), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}.{1}", tableSchema.DataModelSchema.Name, childTable.Name)), string.Format("{0}Column", columnSchema.Name)));
                            iteratorStatements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("sqlCommand"), "Parameters"), "Add", new CodeExpression[] { new CodeObjectCreateExpression("SqlParameter", new CodeExpression[] { new CodePrimitiveExpression(string.Format("@{0}", variableName)), TypeConverter.Convert(columnSchema.DataType), new CodePrimitiveExpression(0), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ParameterDirection"), "Input"), new CodePrimitiveExpression(false), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(null), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DataRowVersion"), "Current"), codeExpression }) }));
                        }
                    }
                    iteratorStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("sqlCommand"), "ExecuteNonQuery"));
                }

                //					// Delete the Department record from the ADO data model.
                //					adoResourceManager.Add(departmentRow);
                //					departmentRow[ServerDataModel.Department.RowVersionColumn] = ServerDataModel.IncrementRowVersion();
                //					departmentRow.Delete();
                iteratorStatements.Add(new CodeCommentStatement(string.Format("Delete the {0} record from the ADO data model.", childTable.Name)));
                iteratorStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("adoResourceManager"), "Add", new CodeVariableReferenceExpression(rowVariable)));

                CodeTryCatchFinallyStatement tryFinallyStatement = new CodeTryCatchFinallyStatement();
                tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "BeginEdit"));
                tryFinallyStatement.TryStatements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeVariableReferenceExpression(rowVariable), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}.{1}", tableSchema.DataModelSchema.Name, childTable.Name)), "RowVersionColumn")), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(tableSchema.DataModelSchema.Name), "IncrementRowVersion")));
                tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "Delete"));
                tryFinallyStatement.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "EndEdit"));
                iteratorStatements.Add(tryFinallyStatement);

                CodeStatement[] iteratorArray = new CodeStatement[iteratorStatements.Count];
                iteratorStatements.CopyTo(iteratorArray, 0);
                codeStatements.Add(new CodeIterationStatement(new CodeVariableDeclarationStatement(typeof(System.Int32), iteratorVariable, new CodePrimitiveExpression(0)),
                                                              new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(iteratorVariable), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowArrayVariable), "Length")),
                                                              new CodeAssignStatement(new CodeVariableReferenceExpression(iteratorVariable), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(iteratorVariable), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))), iteratorArray));
            }
        }
示例#27
0
        /// <summary>
        /// Create a new dense vector with values sampled from the provided random distribution.
        /// </summary>
        public static DenseVector CreateRandom(int length, IContinuousDistribution distribution)
        {
            var samples = Generate.RandomSingle(length, distribution);

            return(new DenseVector(new DenseVectorStorage <float>(length, samples)));
        }
示例#28
0
        /// <summary>
        /// Creates the CodeDOM for a method to delete a record from a table using transacted logic.
        /// </summary>
        /// <param name="tableSchema">A description of the table.</param>
        public Delete(TableSchema tableSchema)
        {
            // Initialize the object.
            this.tableSchema = tableSchema;

            // To reduce the frequency of deadlocking, the tables are always locked in alphabetical order.  This section collects
            // all the table locks that are used for this operation and organizes them in a list that is used to generate the
            // locking and releasing statements below.
            List <LockRequest> tableLockList = new List <LockRequest>();

            foreach (TableSchema familyTable in tableSchema.TableHierarchy)
            {
                tableLockList.Add(new WriteRequest(familyTable));
            }
            foreach (TableSchema childTable in tableSchema.Descendants)
            {
                tableLockList.Add(new WriteRequest(childTable));
            }
            tableLockList.Sort();

            // Shorthand notations for the elements used to construct the interface to this table:
            string tableTypeName        = string.Format("{0}.{1}DataTable", tableSchema.DataModelSchema.Name, tableSchema.Name);
            string tableVariableName    = string.Format("{0}Table", tableSchema.Name[0].ToString().ToLower() + tableSchema.Name.Remove(0, 1));
            string rowTypeName          = string.Format("{0}.{1}Row", tableSchema.DataModelSchema.Name, tableSchema.Name);
            string rowVariableName      = string.Format("{0}Row", tableSchema.Name[0].ToString().ToLower() + tableSchema.Name.Remove(0, 1));
            string identityColumnName   = tableSchema.PrimaryKey == null ? string.Empty : tableSchema.PrimaryKey.Fields[0].Name;
            string identityVariableName = tableSchema.PrimaryKey == null ? string.Empty : identityColumnName[0].ToString().ToLower() + identityColumnName.Remove(0, 1);

            //		/// <summary>Deletes a Employee record.</summary>
            //		/// <param name="employeeId">The value for the EmployeeId column.</param>
            //		/// <param name="rowVersion">Used for Optimistic Concurrency Checking.</param>
            //		public static void Delete(int employeeId, ref long rowVersion)
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Deletes a {0} record.", tableSchema.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            foreach (ColumnSchema columnSchema in tableSchema.Columns)
            {
                if (tableSchema.IsPrimaryKeyColumn(columnSchema) && columnSchema.DeclaringType == tableSchema.TypeSchema)
                {
                    this.Comments.Add(new CodeCommentStatement(string.Format(@"<param name=""{0}"">The value for the {1} column.</param>", Generate.CamelCase(columnSchema.Name), columnSchema.Name), true));
                }
            }
            this.Comments.Add(new CodeCommentStatement(@"<param name=""rowVersion"">Used for Optimistic Concurrency Checking.</param>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
            this.Name       = "Delete";
            foreach (ColumnSchema columnSchema in tableSchema.Columns)
            {
                if (tableSchema.IsPrimaryKeyColumn(columnSchema) && columnSchema.DeclaringType == tableSchema.TypeSchema)
                {
                    Type typeColumn    = columnSchema.DataType;
                    Type parameterType = tableSchema.IsPrimaryKeyColumn(columnSchema) ? typeColumn : typeof(object);
                    CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(parameterType, Generate.CamelCase(columnSchema.Name));
                    this.Parameters.Add(parameter);
                }
            }
            CodeParameterDeclarationExpression rowVersionParameter = new CodeParameterDeclarationExpression(typeof(long), "rowVersion");

            this.Parameters.Add(rowVersionParameter);

            //			// This method is part of a larger transaction.  Instead of passing the transaction and the resource managers down
            //			// through several layers of methods, they are acccessed as ambient properties of the Transaction class.
            //			Transaction transaction = Transaction.Current;
            //			AdoResourceManager adoResourceManager = ((AdoResourceManager)(transaction["ADO Data Model"]));
            //			SqlResourceManager sqlResourceManager = ((SqlResourceManager)(transaction["SQL Data Model"]));
            this.Statements.Add(new CodeCommentStatement("This method is part of a larger transaction.  Instead of passing the transaction and the resource managers down"));
            this.Statements.Add(new CodeCommentStatement("through several layers of methods, they are acccessed as ambient properties of the Transaction class."));
            this.Statements.Add(new CodeVariableDeclarationStatement("Transaction", "transaction", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("Transaction"), "Current")));
            this.Statements.Add(new CodeVariableDeclarationStatement("AdoResourceManager", "adoResourceManager", new CodeCastExpression("AdoResourceManager", new CodeIndexerExpression(new CodeVariableReferenceExpression("transaction"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}DataTable", tableSchema.Name)), "VolatileResource")))));
            this.Statements.Add(new CodeVariableDeclarationStatement("SqlResourceManager", "sqlResourceManager", new CodeCastExpression("SqlResourceManager", new CodeIndexerExpression(new CodeVariableReferenceExpression("transaction"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}DataTable", tableSchema.Name)), "DurableResource")))));

            //				// This is used below to assemble the SQL commands.
            //				SqlCommand sqlCommand = null;
            this.Statements.Add(new CodeCommentStatement("This is used below to assemble the SQL commands."));
            this.Statements.Add(new CodeVariableDeclarationStatement("SqlCommand", "sqlCommand", new CodePrimitiveExpression(null)));

            //				// The Department record is locked for the duration of the transaction.
            //				ServerDataModel.DepartmentRow departmentRow = ((ServerDataModel.DepartmentRow)(ServerDataModel.Department.FindByDepartmentId(departmentId)));
            //				if ((departmentRow == null))
            //				{
            //					throw new System.Exception(string.Format("Attempt to update a Department record ({0}) that doesn\'t exist", departmentId));
            //				}
            //				departmentRow.ReaderWriterLock.AcquireWriterLock(System.Threading.Timeout.Infinite);
            TableSchema rootTable = tableSchema.RootTable;

            this.Statements.Add(new CodeCommentStatement(string.Format("The {0} record is deleted from the most distant descendant back up to the root object in order to preserved", rootTable.Name)));
            this.Statements.Add(new CodeCommentStatement("the integrity of the cascading relations."));
            string rowVariable      = string.Format("{0}Row", Generate.CamelCase(rootTable.Name));
            string rowType          = string.Format("{0}.{1}Row", tableSchema.DataModelSchema.Name, rootTable.Name);
            string findMethodName   = string.Format("FindBy");
            string exceptionFormat  = string.Empty;
            int    parameterCounter = 0;
            List <CodeExpression> methodParameters    = new List <CodeExpression>();
            List <CodeExpression> exceptionParameters = new List <CodeExpression>();

            if (tableSchema.PrimaryKey != null)
            {
                foreach (ColumnSchema columnSchema in tableSchema.PrimaryKey.Fields)
                {
                    methodParameters.Add(new CodeArgumentReferenceExpression(Generate.CamelCase(columnSchema.Name)));
                    exceptionParameters.Add(new CodeArgumentReferenceExpression(Generate.CamelCase(columnSchema.Name)));
                    exceptionFormat += string.Format("{{0}}", parameterCounter++);
                }
                foreach (ColumnSchema columnSchema in rootTable.PrimaryKey.Fields)
                {
                    findMethodName += columnSchema.Name;
                }
            }
            exceptionParameters.Insert(0, new CodePrimitiveExpression(string.Format("Attempt to delete a {0} record ({1}) that doesn't exist", rootTable.Name, exceptionFormat)));
            this.Statements.Add(new CodeVariableDeclarationStatement(string.Format("{0}.{1}Row", tableSchema.DataModelSchema.Name, rootTable.Name), rowVariable, new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModelSchema.Name), rootTable.Name), findMethodName, methodParameters.ToArray())));
            this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(rowVariable), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)),
                                                           new CodeThrowExceptionStatement(new CodeObjectCreateExpression("MarkThree.RecordNotFoundException", exceptionParameters.ToArray()))));
            this.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "ReaderWriterLock"), "AcquireWriterLock", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Threading.Timeout)), "Infinite")));
            this.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("adoResourceManager"), "Add", new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "ReaderWriterLock"))));

            DeleteChildren(rootTable, this.Statements);

            //					// Delete the Department record from the SQL data model.
            //					sqlCommand = new SqlCommand("delete \"Department\" where \"DepartmentId\"=@departmentId", sqlResourceManager.SqlConnection);
            //					sqlCommand.Parameters.Add(new SqlParameter("@departmentId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, departmentRow[ServerDataModel.Department.DepartmentIdColumn]));
            //					sqlCommands.Add(sqlCommand);
            if (tableSchema.IsPersistent)
            {
                this.Statements.Add(new CodeCommentStatement(string.Format("Delete the {0} record from the SQL data model.", rootTable.Name)));
                string whereClause = string.Empty;
                if (rootTable.PrimaryKey != null)
                {
                    foreach (ColumnSchema columnSchema in rootTable.PrimaryKey.Fields)
                    {
                        whereClause += string.Format("\"{0}\"=@{1}", columnSchema.Name, Generate.CamelCase(columnSchema.Name));
                    }
                }
                string deleteCommandText = string.Format("delete \"{0}\" where {1}", rootTable.Name, whereClause);
                this.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("sqlCommand"), new CodeObjectCreateExpression("SqlCommand", new CodePrimitiveExpression(deleteCommandText), new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("sqlResourceManager"), "SqlConnection"))));
                if (rootTable.PrimaryKey != null)
                {
                    foreach (ColumnSchema columnSchema in rootTable.PrimaryKey.Fields)
                    {
                        string         variableName   = Generate.CamelCase(columnSchema.Name);
                        CodeExpression codeExpression = new CodeIndexerExpression(new CodeVariableReferenceExpression(string.Format("{0}Row", Generate.CamelCase(rootTable.Name))), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}.{1}", tableSchema.DataModelSchema.Name, rootTable.Name)), string.Format("{0}Column", columnSchema.Name)));
                        this.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("sqlCommand"), "Parameters"), "Add", new CodeExpression[] { new CodeObjectCreateExpression("SqlParameter", new CodeExpression[] { new CodePrimitiveExpression(string.Format("@{0}", variableName)), TypeConverter.Convert(columnSchema.DataType), new CodePrimitiveExpression(0), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ParameterDirection"), "Input"), new CodePrimitiveExpression(false), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(null), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DataRowVersion"), "Current"), codeExpression }) }));
                    }
                }
                this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("sqlCommand"), "ExecuteNonQuery"));
            }

            //					// Delete the Department record from the ADO data model.
            //					adoResourceManager.Add(departmentRow);
            //					departmentRow[ServerDataModel.Department.RowVersionColumn] = ServerDataModel.IncrementRowVersion();
            //					departmentRow.Delete();
            this.Statements.Add(new CodeCommentStatement(string.Format("Delete the {0} record from the ADO data model.", rootTable.Name)));
            this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("adoResourceManager"), "Add", new CodeVariableReferenceExpression(rowVariable)));
            CodeTryCatchFinallyStatement tryFinallyStatement = new CodeTryCatchFinallyStatement();

            tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "BeginEdit"));
            tryFinallyStatement.TryStatements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeVariableReferenceExpression(rowVariable), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}.{1}", tableSchema.DataModelSchema.Name, rootTable.Name)), "RowVersionColumn")), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(tableSchema.DataModelSchema.Name), "IncrementRowVersion")));
            tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "Delete"));
            tryFinallyStatement.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "EndEdit"));
            this.Statements.Add(tryFinallyStatement);
        }
 public GenerateCommand(Generate opts)
 {
     this._options = opts;
 }
示例#30
0
 /// <typeparam name="T">MUST BE AN ENUM. FOR NORMAL VALUES, USE Any.OtherThan()</typeparam>
 /// <param name="excludedValues"></param>
 /// <returns></returns>
 public static T Besides <[MustBeAnEnum] T>([MustBeAnEnum] params T[] excludedValues) where T : struct, IConvertible
 {
     return(Generate.Besides(excludedValues));
 }
示例#31
0
 public static T Of <T>() where T : struct, IConvertible
 {
     return(Generate.Of <T>());
 }
示例#32
0
    private static void DoGenerateFromXML(ObjectModel objects, XmlNode framework)
    {
        string name = framework.Attributes["name"].Value;
        Blacklist[] blacklist = DoGetBlacklist(framework);
        Threading[] threading = DoGetThreading(framework);

        string outPath = ms_outDir;
        outPath = Path.Combine(outPath, name);
        outPath = Path.Combine(outPath, "generated");

        string[] files;
        if (Directory.Exists(outPath))
        {
            files = Directory.GetFiles(outPath, "*.cs", SearchOption.AllDirectories);
            foreach (string file in files)
                File.SetAttributes(file, FileAttributes.Normal);	// need to unlock generated .cs files so we can delete the directory
            Directory.Delete(outPath, true);
        }
        Directory.CreateDirectory(outPath);

        string dir;
        var analyze = new AnalyzeHeader(objects);
        foreach (XmlNode child in framework.ChildNodes)
        {
            if (child.Name == "Include")
            {
                dir = child.Attributes["path"].Value;
                DoParseHeaders(analyze, dir, false);
            }
        }

        objects.Reset();			// need to clear out any files from previous frameworks
        dir = framework.Attributes["path"].Value;
        DoParseHeaders(analyze, dir, true);

        analyze.PostParse();
        Generate generate = new Generate(objects);
        generate.Code(outPath, blacklist, threading);
    }