private void ImportOneUnit(MCS.Library.SOA.DataObjects.Security.SCObjectSet objectSet, Operations.IFacade exec, ImportContextWrapper wrapper, SchemaObjectBase parent, int totalSteps, AdminUnit unit) { int currentStep = 0; var scopes = (from m in objectSet.Membership where m.ContainerID == unit.ID && m.MemberSchemaType == AUCommon.SchemaAUAdminScope && m.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal join o in objectSet.Objects on m.ID equals o.ID where o.SchemaType == AUCommon.SchemaAUAdminScope && o.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal select (AUAdminScope)o).ToArray(); var roles = (from m in objectSet.Membership where m.ContainerID == unit.ID && m.MemberSchemaType == AUCommon.SchemaAdminUnitRole && m.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal join o in objectSet.Objects on m.ID equals o.ID where o.SchemaType == AUCommon.SchemaAdminUnitRole && o.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal select (AURole)o).ToArray(); try { currentStep++; wrapper.SetStatusAndLog(currentStep, totalSteps, "正在导入管理单元" + unit.GetQualifiedName()); exec.AddAdminUnitWithMembers(unit, (AdminUnit)parent, roles, scopes); ImportRoleMembers(objectSet, exec, wrapper, totalSteps, unit, currentStep, roles); ImportConditions(objectSet, exec, wrapper, totalSteps, unit, currentStep, scopes); if (this.ImportSubUnits) { wrapper.IncreaseLevel(); var subs = (from r in objectSet.Relations where r.ParentID == unit.ID && r.ChildSchemaType == AUCommon.SchemaAdminUnit && r.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal join o in objectSet.Objects on r.ID equals o.ID where o.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal && o.SchemaType == AUCommon.SchemaAdminUnit select (AdminUnit)o).ToArray(); int count = subs.Length; foreach (AdminUnit s in subs) { ImportOneUnit(objectSet, exec, wrapper, unit, count, s); } wrapper.DecreaseLevel(); } } catch (Exception ex) { wrapper.IncreaseError(); wrapper.SetStatusAndLog(currentStep, totalSteps, string.Format("导入单元 {0} 失败,原因是:{1}", unit.GetQualifiedName(), ex.ToString())); } }
public static CalculationHandler GetOperation(Operations op) { switch (op) { case Operations.Addition: return (x, y) => x + y + ""; case Operations.Division: return (x, y) => { if (y.Equals(0)) return " Cannot divide by zero"; return x/y + ""; }; case Operations.Multiplication: return (x, y) => x*y + ""; case Operations.Substraction: return (x, y) => x - y + ""; case Operations.Sqrt: return (x, y) => Math.Sqrt(x) + ""; case Operations.Mod: return (x, y) => x%y + ""; case Operations.Reciprocal: return (x, y) => { if (x.Equals(0)) return " Cannot divide by zero"; return 1/x + ""; }; } return null; }
public ValueAssignEx(Position position, Operations operation, VariableUse/*!*/ lvalue, Expression/*!*/ rvalue) : base(position) { this.lvalue = lvalue; this.rvalue = rvalue; this.operation = operation; }
public static void ComparePerformance(float value, Operations funcion) { var result = value; Stopwatch stopwatch = new Stopwatch(); for (var j = 0; j < TestsCount; j++) { var testNumber = value; stopwatch.Start(); for (var i = 0; i < RepeatFunctionsCount; i++) { switch (funcion) { case Operations.Add: testNumber += anotherValue; break; case Operations.Division: testNumber %= anotherValue; break; case Operations.Substraction: testNumber -= anotherValue; break; case Operations.Multiply: testNumber *= anotherValue; break; case Operations.Increment: testNumber++; break; } } stopwatch.Stop(); } Console.WriteLine(value.GetType().ToString() + " time in milliseconds: " + stopwatch.Elapsed.Milliseconds / TestsCount); }
public ValueAssignEx(Text.Span span, Operations operation, VariableUse/*!*/ lvalue, Expression/*!*/ rvalue) : base(span) { this.lvalue = lvalue; this.rvalue = rvalue; this.operation = operation; }
public CalculatorViewModel() { _calculator = new CalculatorSimple(); _operation = Operations.None; AddCommand = new ActionCommand(Add); SubtractCommand = new ActionCommand(Subtract); MultiplyCommand = new ActionCommand(Multiply); DivideCommand = new ActionCommand(Divide); EquateCommand = new ActionCommand(Equate); ZeroCommand = new ActionCommand(() => InputSymbol('0')); OneCommand = new ActionCommand(() => InputSymbol('1')); TwoCommand = new ActionCommand(() => InputSymbol('2')); ThreeCommand = new ActionCommand(() => InputSymbol('3')); FourCommand = new ActionCommand(() => InputSymbol('4')); FiveCommand = new ActionCommand(() => InputSymbol('5')); SixCommand = new ActionCommand(() => InputSymbol('6')); SevenCommand = new ActionCommand(() => InputSymbol('7')); EightCommand = new ActionCommand(() => InputSymbol('8')); NineCommand = new ActionCommand(() => InputSymbol('9')); MarkCommand = new ActionCommand(() => InputSymbol(',')); RemoveLastDigitCommand = new ActionCommand(RemoveLastDigit); ClearCommand = new ActionCommand(Clear); PlusMinusCommand = new ActionCommand(ChangeSign); }
internal static void TestOperation(double number, Operations operation) { storeResults.Clear(); for (int i = 0; i < OperationRepeatCount; i++) { watchTime.Reset(); watchTime.Start(); for (int j = 0; j < LoopsCount; j++) { switch (operation) { case Operations.Sqrt: result = Math.Sqrt(number); break; case Operations.Log: result = Math.Log(number); break; case Operations.Sin: result = Math.Sin(number); break; default: throw new InvalidOperationException("You have entered an invalid operation"); } } watchTime.Stop(); storeResults.Add(watchTime.Elapsed.Milliseconds); } double averageResult = storeResults.Average(); Console.WriteLine("Math {0} with double finished in {1} miliseconds", operation, averageResult); }
public UnaryEx(Text.Span span, Operations operation, Expression/*!*/ expr) : base(span) { Debug.Assert(expr != null); this.operation = operation; this.expr = expr; }
public UnaryEx(Position position, Operations operation, Expression/*!*/ expr) : base(position) { Debug.Assert(expr != null); this.operation = operation; this.expr = expr; }
private void btnCalculate_Click(object sender, RoutedEventArgs e) { Operations o = new Operations(); if (optAdd.IsChecked == true) { double addResult = add(Convert.ToDouble(txtFirstNumber.Text), Convert.ToDouble(txtSecondNumber.Text)); txtResult.Text = "" + addResult; } else if (optSub.IsChecked == true) { double subResult = sub(Convert.ToDouble(txtFirstNumber.Text), Convert.ToDouble(txtSecondNumber.Text)); txtResult.Text = "" + subResult; } else if (optMult.IsChecked == true) { double multResult = mult(Convert.ToDouble(txtFirstNumber.Text), Convert.ToDouble(txtSecondNumber.Text)); txtResult.Text = "" + multResult; } else if (optDiv.IsChecked == true) { double divResult = sub(Convert.ToDouble(txtFirstNumber.Text), Convert.ToDouble(txtSecondNumber.Text)); txtResult.Text = "" + divResult; } }
public BinaryEx(Position position, Operations operation, Expression/*!*/ leftExpr, Expression/*!*/ rightExpr) : base(position) { Debug.Assert(leftExpr != null && rightExpr != null); this.operation = operation; this.leftExpr = leftExpr; this.rightExpr = rightExpr; }
public void Operation(Operations operation) { Random rand = new Random(84329); Vector4 v1 = new Vector4(Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble())); Vector4 v2 = new Vector4(Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble())); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) ExecuteTest(operation, 1000000, v1, v2); }
public bool OperationValidity(Operations operation) { switch(operation) { case Operations.EditClient: return CanEditClient(); } return false; }
public static void Run(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); ProgramOptions options = new ProgramOptions(); string settingPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Oxel.Settings.xml"); VoxelizationInput input = VoxelizationInput.Load(settingPath); if (input == null) input = new VoxelizationInput(); if (args.Contains("-c")) { // Make sure user can see console output AttachConsole(PARENT_PROCESS_ID); input.Clone(options); if (!CommandLineParser.Parse<ProgramOptions>(args, ref options)) return; options.Clone(input); } else { CommandLineParser.Parse<VoxelizationInput>(args, ref input); } if (options.UseCommandLine) { Logger.IsCommandLine = true; Operations operations = new Operations(); operations.Initialize(input); operations.Open(options.InputMesh, input.WindingOrder); WaitHandle waitHandle = operations.GenerateOccluder((VoxelizationProgress vp) => { string coverage = String.Format("Volume Coverage : {0,5:0.##}%", (100 * vp.VolumeCoverage)) + " " + String.Format("Silhouette Coverage : {0,5:0.##}%", (100 * vp.SilhouetteCoverage)); if (!String.IsNullOrEmpty(vp.Status)) Console.WriteLine(vp.Status + "\r\n"); Console.WriteLine(coverage); }, new Action(() => { })); waitHandle.WaitOne(); operations.Save(options.OutputMesh); } else { using (MainWindow window = new MainWindow(input)) { window.ShowDialog(); } } }
public DeleteController(Operations.Delete delete) { if (delete == null) { throw new ArgumentNullException(nameof(delete)); } Delete = delete; }
public void ExecuteTest(Operations operation, int innerIterations, Vector3 v1, Vector3 v2) { Vector3 res; switch (operation) { case Operations.Add_Operator: for (int i = 0; i < innerIterations; i++) { res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; } break; case Operations.Add_Function: for (int i = 0; i < innerIterations; i++) { Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); } break; case Operations.Sub_Operator: for (int i = 0; i < innerIterations; i++) { res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; } break; case Operations.Sub_Function: for (int i = 0; i < innerIterations; i++) { Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); } break; case Operations.Mul_Operator: for (int i = 0; i < innerIterations; i++) { res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; } break; case Operations.Mul_Function: for (int i = 0; i < innerIterations; i++) { Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); } break; case Operations.Dot: for (int i = 0; i < innerIterations; i++) { Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); } break; case Operations.SquareRoot: for (int i = 0; i < innerIterations; i++) { Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); } break; case Operations.Length_Squared: for (int i = 0; i < innerIterations; i++) { v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); } break; case Operations.Normalize: for (int i = 0; i < innerIterations; i++) { Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); } break; case Operations.Distance_Squared: for (int i = 0; i < innerIterations; i++) { Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); } break; case Operations.Cross: for (int i = 0; i < innerIterations; i++) { Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); } break; } }
public bool OperationValidity(Operations operation) { switch(operation) { case Operations.GenerateChallan: return CanGenerateChallan(); case Operations.ViewChallan: return CanViewChallan(); } return false; }
public IOperation<Frame> GetFrameOperation() { var ops = new Operations<Frame>(); foreach (var frameOperation in _frameOperations) { ops.Register(frameOperation); } return ops; }
public IOperation<Portrait> GetPortraitOperation() { var ops = new Operations<Portrait>(); foreach (var portraitOperation in _portraitOperations) { ops.Register(portraitOperation); } return ops; }
/// <summary> /// Parses a given expression into a graph. /// </summary> /// <returns>The built graph.</returns> /// <param name="expression">The expression to create the graph from.</param> /// <param name="initGraph">The graph to append too. Used for recursion.</param> public Graph ParseExpression(string expression, Graph initGraph = null) { var lang = new Language (); var ops = new Operations (); expression = expression.Trim (); var opStack = new Stack<Word>(); foreach (char letter in expression) { //find the language mapping var inLanguage = lang .DefaultIfEmpty(null) .FirstOrDefault (w => w.Letter == letter); //find the operation mapping var inOps = ops .DefaultIfEmpty(null) .FirstOrDefault(w => w.Letter == letter); //not in the language or operators if(inLanguage == null && inOps == null){ throw new InvalidLanguageException("Invalid input: " + letter); } //it is valid language input, so add it to the list. if(inLanguage != null){ opStack.Push(inLanguage); continue; } else{ //not a letter, so must be an operation //verify that it has the correct arg count for that type of operation. if (opStack.Count != inOps.MinArgCount && initGraph == null) { throw new InvalidLanguageException ( string.Format( "Unbalanced arguement count for operation (expected {0}, but got {1}.", inOps.MinArgCount, opStack.Count )); } //operation, so stop, and process graph initGraph = ProcessOperation(initGraph, inOps, opStack); } } //expression was given with no operation, so error out. if (opStack.Count > 0) { throw new InvalidLanguageException ("No operation was specified in the given expression."); } //once done with graph, renumber the states. initGraph.RenumberStates (); //return the completed graph. return initGraph; }
private void ChangeValue(dynamic calculator, Operations operation) { dynamic addvalue = null; if (CurrentVal.Text != "Write your Value:") { if (state.CalcEnum == CalcEnum.IntCalc) { addvalue = new Real<int>(int.Parse(CurrentVal.Text)); } if (state.CalcEnum == CalcEnum.FloatCalc) { addvalue = new Real<double>(double.Parse(CurrentVal.Text)); } if (state.CalcEnum == CalcEnum.ComCalc) { addvalue = new Complecs(CurrentVal.Text); } switch (operation) { case Operations.Add: calculator.Add(addvalue); break; case Operations.Remove: calculator.Remove(addvalue); break; case Operations.Divide: calculator.Divide(addvalue); break; case Operations.Multiply: calculator.Multiply(addvalue); break; case Operations.Clear: calculator.Clear(addvalue); break; case Operations.Sqrt: try { calculator.Sqrt(addvalue); } catch (Exception) { MessageBox.Show("Eror: Divide at 0"); } break; case Operations.Modul: calculator.Modul(addvalue); break; } } else { MessageBox.Show("Write Value!!!!"); } }
public void Run() { var operations = new Operations(); bool exit = false; while(!exit) { Console.Clear(); CWMenu(); exit = Select(operations); Console.ReadKey(); } }
static void Main(string[] args) { #if DEBUG var operations = new Operations(new FileInfo(Path.Combine(Directory.GetCurrentDirectory(),@"debug.yaml"))); #else if (args.Length == 0) return; Operations operations = new Operations(new FileInfo(args[0])); #endif var oroom = new OperatingRoom(operations); oroom.DoOperations(); System.Console.ReadKey(); }
public ARPPacket(int HardwareType, int ProtocolType, Operations Operation, MemBlock SenderHWAddress, MemBlock SenderProtoAddress, MemBlock TargetHWAddress, MemBlock TargetProtoAddress) { byte[] header = new byte[8]; NumberSerializer.WriteUShort((ushort) HardwareType, header, 0); NumberSerializer.WriteUShort((ushort) ProtocolType, header, 2); header[4] = (byte) SenderHWAddress.Length; header[5] = (byte) SenderProtoAddress.Length; NumberSerializer.WriteUShort((ushort) Operation, header, 6); _icpacket = new CopyList(MemBlock.Reference(header), SenderHWAddress, SenderProtoAddress, TargetHWAddress, TargetProtoAddress); }
public void Action_With_14_Args_InvokeWithNoRetry() { // arrange Operations operations = new Operations(0); var action = operations.GetAction<int,int,int,int,int,int,int,int,int,int,int,int,int,int>(); // act action.InvokeWithRetry(RetryPolicies.NoRetry(),0,0,0,0,0,0,0,0,0,0,0,0,0,0); // assert Assert.Equal(0, operations.ThrowCount); Assert.Equal(1, operations.ExecuteCount); }
public bool Select(Operations operations) { string userEnter = Console.ReadLine(); switch (userEnter) { case INSERT: operations.Insert(); Console.WriteLine("Press any key to continue..."); return false; case SHOWALL: operations.Show(); Console.WriteLine("Press any key to continue..."); return false; case FINDBYNAME: operations.FindByName(); Console.WriteLine("Press any key to continue..."); return false; case FINDBYID: operations.FindById(); Console.WriteLine("Press any key to continue..."); return false; case UPDATE: operations.Update(); Console.WriteLine("Press any key to continue..."); return false; case DELETE: operations.Delete(); Console.WriteLine("Press any key to continue..."); return false; case TXT: operations.SaveTxt(); Console.WriteLine("Press any key to continue..."); return false; case EXIT: Console.WriteLine("Press any key to exit..."); return true; default: Console.WriteLine("Invalid operation..."); return false; } }
private void ImportConditions(MCS.Library.SOA.DataObjects.Security.SCObjectSet objectSet, Operations.IFacade exec, ImportContextWrapper wrapper, int totalSteps, AdminUnit unit, int currentStep, AUAdminScope[] scopes) { if (this.IncludeScopeConditions) { wrapper.SetStatusAndLog(currentStep, totalSteps, "正在导入管理单元管理范围条件" + unit.GetQualifiedName()); foreach (AUAdminScope sc in scopes) { var conditions = (from c in objectSet.Conditions where c.OwnerID == sc.ID select c); foreach (var c in conditions) { DBTimePointActionContext.Current.DoActions(() => exec.UpdateScopeCondition(sc, c)); } } } }
public ListColumn(string columnName, Operations operations) { Guid columnId; if (TryParseGuid(columnName, out columnId)) { this.ColumnId = columnId; } else { this.ColumnName = columnName; } this.Operations = operations; }
public void Action_With_No_Args_InvokeWithNoRetry() { // arrange Operations operations = new Operations(0); var policy = Policy.NoRetry(); var action = operations.GetAction(); // act action.InvokeWithRetry(policy.RetryPolicy); // assert Assert.Equal(0, policy.ShouldRetryCallCount); Assert.Equal(0, operations.ThrowCount); Assert.Equal(1, operations.ExecuteCount); }
public void Func_With_1_Args_InvokeWithNoRetry() { // arrange Operations operations = new Operations(0); var policy = Policy.NoRetry(); var func = operations.GetFunc<int, int>(); // act func.InvokeWithRetry(policy.RetryPolicy, 0); // assert Assert.Equal(0, policy.ShouldRetryCallCount); Assert.Equal(0, operations.ThrowCount); Assert.Equal(1, operations.ExecuteCount); }
/// <inheritdoc/> public override ArmOperation <AvailabilitySet> StartCreateOrUpdate(string name, AvailabilitySetData resourceDetails, CancellationToken cancellationToken = default) { return(new PhArmOperation <AvailabilitySet, Azure.ResourceManager.Compute.Models.AvailabilitySet>( Operations.CreateOrUpdate(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken), a => new AvailabilitySet(Parent, new AvailabilitySetData(a)))); }
protected void populateBody(Dictionary <StatType, float> stats, bool skipUnitValues = true, Ability[] abils = null) { string text = ""; int[] valueText = new int[2]; string valueLines = ""; foreach (StatType t in stats.Keys) { string line = ""; switch (t) { case StatType.health: valueText[1] = (int)stats[t]; break; case StatType.attack: valueText[0] = (int)stats[t]; break; case StatType.range: line = "+{0} Range"; break; case StatType.moveSpeed: line = "+{0} Move Speed"; break; case StatType.resourceMax: line = "+{0} Max Resources"; break; case StatType.resourceIncome: line = "+{0}<sprite index= 1> Resource Income"; break; case StatType.armor: line = "Armor {0}"; break; case StatType.piercing: line = "Piercing"; break; case StatType.regen: line = "Regen {0}"; break; case StatType.agile: line = "Agile"; break; case StatType.overwhelm: line = "Overwhelm {0}"; break; case StatType.charge: line = "Charge"; break; case StatType.bypass: line = "Bypass"; break; case StatType.frontline: line = "Frontline"; break; case StatType.ghost: line = "Ghost"; break; case StatType.slow: line = "Slow {0}"; break; case StatType.bloodlust: line = "Bloodlust"; break; //case StatType.collateral://benched // line = "Collateral {0}"; // break; case StatType.cleave: //benched line = "Cleave {0}"; break; case StatType.cardDraw: line = "+{0} Card Draw"; break; case StatType.addOn: line = "Add-On"; break; case StatType.resourceSpend: line = "+{0}<sprite index= 0> Power Limit"; break; default: line = ""; break; } if (line != "") { if (t == StatType.range || t == StatType.moveSpeed) { valueLines += string.Format(line + "\n", stats[t]); } else { text += string.Format(line + "\n", stats[t]); } } } if (!skipUnitValues) { if (valueText[0] != 0 || valueText[1] != 0) { string atkcolor = ColorUtility.ToHtmlStringRGB(GameColors.attack); string defcolor = ColorUtility.ToHtmlStringRGB(GameColors.defense); string valueLine = "+<color=#" + atkcolor + ">" + valueText[0] + "</color>/<color=#" + defcolor + ">" + valueText[1] + "</color>\n"; valueLines = valueLine + valueLines; } text = valueLines + text; } if (abils != null) { foreach (Ability ab in abils) { string desc = ab.toDesc(); desc = Operations.Capatialize(desc); text += ab.GetComponent <Ordnance>().resourceCost + ": " + desc + "\n"; } } cardBody.text = text; }
public void Enqueue(IImageOperation operation) => Operations.Enqueue(operation);
public static Dictionary <string, object> Receive(StreamWrapper stream, CancellationToken cancellationToken, Action <ConcurrentDictionary <string, int> > onProgressAction = null, Action <string, Exception> onErrorAction = null, Action <int> onTotalChildrenCountKnown = null) { var account = stream.GetAccount().Result; stream.BranchName = string.IsNullOrEmpty(stream.BranchName) ? "main" : stream.BranchName; var client = new Client(account); Commit commit = null; if (stream.Type == StreamWrapperType.Stream || stream.Type == StreamWrapperType.Branch) { List <Branch> branches; try { branches = client.StreamGetBranches(cancellationToken, stream.StreamId).Result; } catch (Exception ex) { Utils.HandleApiExeption(ex); return(null); } var branch = branches.FirstOrDefault(b => b.name == stream.BranchName); if (branch == null) { throw new SpeckleException("No branch found with name " + stream.BranchName); } if (!branch.commits.items.Any()) { throw new SpeckleException("No commits found."); } commit = branch.commits.items[0]; } else if (stream.Type == StreamWrapperType.Commit) { try { commit = client.CommitGet(cancellationToken, stream.StreamId, stream.CommitId).Result; } catch (Exception ex) { Utils.HandleApiExeption(ex); return(null); } } else if (stream.Type == StreamWrapperType.Object) { commit = new Commit() { referencedObject = stream.ObjectId, id = Guid.NewGuid().ToString() }; } if (commit == null) { throw new SpeckleException("Could not get commit."); } if (cancellationToken.IsCancellationRequested) { return(null); } var transport = new ServerTransport(account, stream.StreamId); var @base = Operations.Receive( commit.referencedObject, cancellationToken, remoteTransport: transport, onProgressAction: onProgressAction, onErrorAction: onErrorAction, onTotalChildrenCountKnown: onTotalChildrenCountKnown ).Result; if (cancellationToken.IsCancellationRequested) { return(null); } var converter = new BatchConverter(); var data = converter.ConvertRecursivelyToNative(@base); return(new Dictionary <string, object> { { "data", data }, { "commit", commit } }); }
public void InsertTest() { Operations operations = new Operations(); operations.Insert(); }
// Refreshes Cart Table private void ButtonRefreshCart_OnClick(object sender, RoutedEventArgs e) { Operations.LoadCart(); this.CartDisplay.ItemsSource = Operations.CartData; }
public Task <bool> IsUserAuthorizedAsync(UsageType usageType, IEntity entity) { return(IsUserAuthorizedAsync(Operations.GetOperationForUsageType(usageType), entity)); }
public override bool Calibrate() { if (NumImages == 0) { //throw new ArgumentException("numImages=0 in Calibrate()"); return(false); } try { CalibrationDataLeft = new CalibrationData(); CalibrationDataRight = new CalibrationData(); Matrix <double> targets = new Matrix <double>(NumImages, 3); Matrix <double> designMatrixLeft = new Matrix <double>(NumImages, 6); Matrix <double> designMatrixRight = new Matrix <double>(NumImages, 6); var rowLeft = new double[6]; var rowRight = new double[6]; int k = 0; foreach (CalibrationTarget ct in CalibrationTargets) { for (int j = 0; j < ct.NumImages; j++) { targets[k, 0] = ct.targetCoordinates.X; targets[k, 1] = ct.targetCoordinates.Y; double xLeft = ct.pupilCentersLeft[j].X; double yLeft = ct.pupilCentersLeft[j].Y; rowLeft[0] = 1; rowLeft[1] = xLeft; rowLeft[2] = yLeft; rowLeft[3] = xLeft * yLeft; rowLeft[4] = xLeft * xLeft; rowLeft[5] = yLeft * yLeft; for (int r = 0; r < 6; r++) { designMatrixLeft[k, r] = rowLeft[r]; } if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { double xRight = ct.pupilCentersRight[j].X; double yRight = ct.pupilCentersRight[j].Y; rowRight[0] = 1; rowRight[1] = xRight; rowRight[2] = yRight; rowRight[3] = xRight * yRight; rowRight[4] = xRight * xRight; rowRight[5] = yRight * yRight; for (int r = 0; r < 6; r++) { designMatrixRight[k, r] = rowRight[r]; } } k++; } } CalibrationDataLeft.CoeffsX = new Matrix <double>(6, 1); CalibrationDataLeft.CoeffsY = new Matrix <double>(6, 1); CalibrationDataLeft.CoeffsX = Operations.SolveLeastSquares(designMatrixLeft, targets.GetCol(0)); CalibrationDataLeft.CoeffsY = Operations.SolveLeastSquares(designMatrixLeft, targets.GetCol(1)); if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { CalibrationDataRight.CoeffsX = new Matrix <double>(6, 1); CalibrationDataRight.CoeffsY = new Matrix <double>(6, 1); CalibrationDataRight.CoeffsX = Operations.SolveLeastSquares(designMatrixRight, targets.GetCol(0)); CalibrationDataRight.CoeffsY = Operations.SolveLeastSquares(designMatrixRight, targets.GetCol(1)); } double sum_precision = 0; // For each image we calculate the estimated gaze coordinates foreach (CalibrationTarget ct in CalibrationTargets) { // We might be recalibrating so clear estGazeCoords first ct.estimatedGazeCoordinatesLeft.Clear(); ct.estimatedGazeCoordinatesRight.Clear(); for (int j = 0; j < ct.NumImages; j++) { PupilCenterLeft = ct.pupilCentersLeft[j]; ct.estimatedGazeCoordinatesLeft.Add(GetGazeCoordinates(EyeEnum.Left)); if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { PupilCenterRight = ct.pupilCentersRight[j]; ct.estimatedGazeCoordinatesRight.Add(GetGazeCoordinates(EyeEnum.Right)); } } ct.CalculateAverageCoords(); ct.averageErrorLeft = Operations.Distance(ct.meanGazeCoordinatesLeft, ct.targetCoordinates); //double precision = Operations.StandardDeviation(ct.estimatedGazeCoordinatesLeft); sum_precision += ct.stdDeviationGazeCoordinatesLeft; if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { ct.averageErrorRight = Operations.Distance(ct.meanGazeCoordinatesRight, ct.targetCoordinates); } } Console.WriteLine("**************************Precision:" + sum_precision / 9); //calibrated = true; CalibrationDataLeft.Calibrated = true; CalculateAverageErrorLeft(); CalculateDegreesLeft(); System.Diagnostics.Debug.WriteLine(" " + DegreesLeft + " " + CalculateDegreesLeft()); if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { CalibrationDataRight.Calibrated = true; CalculateAverageErrorRight(); CalculateDegreesRight(); } } catch (Exception ex) { //IsCalibrated = false; System.Diagnostics.Debug.WriteLine(ex + " " + DegreesLeft + " " + DegreesRight); return(true); // what to do here } IsCalibrated = true; return(IsCalibrated); //OnCalibrationComplete(EventArgs.Empty); // Raise event }
public void SetTextIntoSearchBox(string textToBeSearch) { Operations.SetTextIntoTextBox(page.SearchTextBox, textToBeSearch); }
public void ClickSearchButton() { Operations.ClickElement(page.SearchButton); }
public bool IsSearchGridVisible() { return(Operations.IsElementVisible(page.SearchResultGrid)); }
public Sensor Greedy4(Sensor ni, Packet packet) { List <CoordinationEntry> coordinationEntries = new List <CoordinationEntry>(); Point endPoint = (packet.Destination != null) ? packet.Destination.CenterLocation : packet.DestinationPoint; Sensor sj = null; double sum = 0; switch (packet.PacketType) { case PacketType.ObtainSinkPosition: { foreach (Sensor nj in ni.NeighborsTable) { if (nj.ResidualEnergyPercentage > 0) { if (nj.IsHightierNode) { double aggregatedValue = 1; sum += aggregatedValue; coordinationEntries.Add(new CoordinationEntry() { Priority = aggregatedValue, Sensor = nj }); // candidaite //return nj; } else { double Norangle = Operations.AngleDotProdection(ni.CenterLocation, nj.CenterLocation, endPoint); double dj = Operations.DistanceBetweenTwoPoints(nj.CenterLocation, endPoint); if (Norangle < 0.5) { double aggregatedValue = dj; sum += aggregatedValue; coordinationEntries.Add(new CoordinationEntry() { Priority = aggregatedValue, Sensor = nj }); // candidaite } else if (Norangle == 0 || Double.IsNaN(Norangle)) { double aggregatedValue = 1; sum += aggregatedValue; coordinationEntries.Add(new CoordinationEntry() { Priority = aggregatedValue, Sensor = nj }); // candidaite } } } } } break; case PacketType.ReportSinkPosition: { foreach (Sensor nj in ni.NeighborsTable) { if (nj.ResidualEnergyPercentage > 0) { if (nj.IsHightierNode) { return(nj); } else { double Norangle = Operations.AngleDotProdection(ni.CenterLocation, nj.CenterLocation, endPoint); double dj = Operations.DistanceBetweenTwoPoints(nj.CenterLocation, endPoint); if (Norangle == 0 || Double.IsNaN(Norangle)) { double aggregatedValue = 1; sum += aggregatedValue; coordinationEntries.Add(new CoordinationEntry() { Priority = aggregatedValue, Sensor = nj }); // candidaite } else if (Norangle < 0.5) { double aggregatedValue = dj; sum += aggregatedValue; coordinationEntries.Add(new CoordinationEntry() { Priority = aggregatedValue, Sensor = nj }); // candidaite } } } } } break; default: { // defaul greedy: foreach (Sensor nj in ni.NeighborsTable) { if (nj.ResidualEnergyPercentage > 0) { double Norangle = Operations.AngleDotProdection(ni.CenterLocation, nj.CenterLocation, endPoint); double dj = Operations.DistanceBetweenTwoPoints(nj.CenterLocation, endPoint); if (Norangle == 0 || Double.IsNaN(Norangle)) { double aggregatedValue = 1; sum += aggregatedValue; coordinationEntries.Add(new CoordinationEntry() { Priority = aggregatedValue, Sensor = nj }); // candidaite } else if (Norangle < 0.5) { double aggregatedValue = dj; sum += aggregatedValue; coordinationEntries.Add(new CoordinationEntry() { Priority = aggregatedValue, Sensor = nj }); // candidaite } } } } break; } // coordination"..... here sj = counter.CoordinateGetMin1(coordinationEntries, packet, sum); return(sj); }
// Unary negation: negates the given value. // Example: 42 becomes -42 when negated. public static T Negate <T>(T value) { return(Operations <T> .Negate(value)); }
public void Divide(decimal number1, decimal number2) => Console.WriteLine($"={Operations.Divide(number1, number2)}");
public override bool Calibrate() { if (numOutliersRemovedLeft == 0 && numOutliersRemovedRight == 0) { RemoveOutliers(); // Only works sometimes, tried fixing it.. } if (NumImages == 0) { //throw new ArgumentException("numImages=0 in Calibrate()"); IsCalibrated = false; return(false); } #region Initialize variabels CalibrationDataLeft = new CalibrationData(); CalibrationDataRight = new CalibrationData(); Matrix <double> targets = new Matrix <double>(NumImages, 3); Matrix <double> designMatrixLeft = new Matrix <double>(NumImages, 6); Matrix <double> designMatrixRight = new Matrix <double>(NumImages, 6); double[] rowLeft = new double[6]; double[] rowRight = new double[6]; int k = 0; #endregion #region Build matrices foreach (CalibrationTarget ct in CalibrationTargets) { for (int j = 0; j < ct.NumImages; j++) { #region Left if (ct.pupilCentersLeft.Count - 1 >= j && ct.glintsLeft.Count - 1 >= j) { GTPoint pupilCenterLeft = ct.pupilCentersLeft.ElementAt(j); GlintConfiguration glintsLeft = ct.glintsLeft.ElementAt(j); if (pupilCenterLeft != null && glintsLeft != null && glintsLeft.Count > 0) { targets[k, 0] = ct.targetCoordinates.X; targets[k, 1] = ct.targetCoordinates.Y; double xLeft = pupilCenterLeft.X - glintsLeft.AverageCenter.X; double yLeft = pupilCenterLeft.Y - glintsLeft.AverageCenter.Y; rowLeft[0] = 1; rowLeft[1] = xLeft; rowLeft[2] = yLeft; rowLeft[3] = xLeft * yLeft; rowLeft[4] = xLeft * xLeft; rowLeft[5] = yLeft * yLeft; for (int r = 0; r < 6; r++) { designMatrixLeft[k, r] = rowLeft[r]; } } } #endregion #region Right if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { if (ct.pupilCentersRight.Count - 1 > j && ct.glintsRight.Count - 1 > j) { GTPoint pupilCenterRight = ct.pupilCentersRight.ElementAt(j); GlintConfiguration glintsRight = ct.glintsRight.ElementAt(j); if (pupilCenterRight != null && glintsRight != null && glintsRight.Count > 0) { double xRight = pupilCenterRight.X - glintsRight.AverageCenter.X; double yRight = pupilCenterRight.Y - glintsRight.AverageCenter.Y; rowRight[0] = 1; rowRight[1] = xRight; rowRight[2] = yRight; rowRight[3] = xRight * yRight; rowRight[4] = xRight * xRight; rowRight[5] = yRight * yRight; for (int r = 0; r < 6; r++) { designMatrixRight[k, r] = rowRight[r]; } } } } #endregion k++; } } #endregion #region SolveLeastSquares CalibrationDataLeft.CoeffsX = new Matrix <double>(6, 1); CalibrationDataLeft.CoeffsY = new Matrix <double>(6, 1); CalibrationDataLeft.CoeffsX = Operations.SolveLeastSquares(designMatrixLeft, targets.GetCol(0)); CalibrationDataLeft.CoeffsY = Operations.SolveLeastSquares(designMatrixLeft, targets.GetCol(1)); if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { CalibrationDataRight.CoeffsX = new Matrix <double>(6, 1); CalibrationDataRight.CoeffsY = new Matrix <double>(6, 1); CalibrationDataRight.CoeffsX = Operations.SolveLeastSquares(designMatrixRight, targets.GetCol(0)); CalibrationDataRight.CoeffsY = Operations.SolveLeastSquares(designMatrixRight, targets.GetCol(1)); } #endregion #region Calculated est. gaze coordinates (per image) // For each image we calculate the estimated gaze coordinates foreach (CalibrationTarget ct in CalibrationTargets) { // We might be recalibrating so clear estGazeCoords first ct.estimatedGazeCoordinatesLeft.Clear(); ct.estimatedGazeCoordinatesRight.Clear(); for (int j = 0; j < ct.NumImages; j++) { #region Left if (ct.pupilCentersLeft.Count - 1 >= j && ct.glintsLeft.Count - 1 >= j) { var pupilCenterLeft = new GTPoint(0, 0); var glintConfigLeft = new GlintConfiguration(new Blobs()); if (ct.pupilCentersLeft.ElementAt(j) != null) { pupilCenterLeft = ct.pupilCentersLeft[j]; } if (ct.glintsLeft.ElementAt(j) != null) { glintConfigLeft = ct.glintsLeft[j]; } if (pupilCenterLeft.Y != 0) { ct.estimatedGazeCoordinatesLeft.Add(GetGazeCoordinates(EyeEnum.Left, pupilCenterLeft, glintConfigLeft)); } } #endregion #region Right if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { if (ct.pupilCentersRight.Count - 1 > j && ct.glintsRight.Count - 1 > j) { var pupilCenterRight = new GTPoint(0, 0); var glintConfigRight = new GlintConfiguration(new Blobs()); if (ct.pupilCentersRight.ElementAt(j) != null) { pupilCenterRight = ct.pupilCentersRight[j]; } if (ct.glintsRight.ElementAt(j) != null) { glintConfigRight = ct.glintsRight[j]; } if (pupilCenterRight.Y != 0) { ct.estimatedGazeCoordinatesRight.Add(GetGazeCoordinates(EyeEnum.Right, pupilCenterRight, glintConfigRight)); } } } #endregion } ct.CalculateAverageCoords(); ct.averageErrorLeft = Operations.Distance(ct.meanGazeCoordinatesLeft, ct.targetCoordinates); if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { ct.averageErrorRight = Operations.Distance(ct.meanGazeCoordinatesRight, ct.targetCoordinates); } } CalibrationDataLeft.Calibrated = true; CalculateAverageErrorLeft(); CalculateDegreesLeft(); if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { CalibrationDataRight.Calibrated = true; CalculateAverageErrorRight(); CalculateDegreesRight(); } #endregion IsCalibrated = true; return(IsCalibrated); }
private void addOperation(string line, int opIndex, int lineNumber) { const string sectionName = "operations"; if (!Regex.IsMatch(line, $@"^{registerNamePattern}\s+{registerNamePattern}\s+\d+\s+{registerNamePattern}\s+{registerNamePattern}\s+{registerNamePattern}$", RegexOptions.IgnoreCase)) { throw new ParsingError(sectionName, line, lineNumber, 0, "Incorrect Format"); } var splitLine = Regex.Replace(line, @"\s+", "\t").Split('\t'); string codeFileForOp; if (!operationToCodeMap.TryGetValue(splitLine[1], out codeFileForOp)) { throw new ParsingError(sectionName, line, lineNumber, line.IndexOf(splitLine[1], StringComparison.Ordinal), "Unable to find the VHDL code for the provided operation."); } int bits; if (!int.TryParse(splitLine[2], out bits) || bits < 1) { var lineIndex = line.Skip(splitLine[0].Length).TakeWhile(char.IsWhiteSpace).Count(); throw new ParsingError(sectionName, line, lineNumber, lineIndex, "The number of bits is less then one."); } RegisterBase left; if (!Registers.TryGetValue(splitLine[3], out left)) { throw new ParsingError(sectionName, line, lineNumber, line.IndexOf(splitLine[3], StringComparison.Ordinal), "Unable to find the left input register."); } RegisterBase right; if (!Registers.TryGetValue(splitLine[4], out right)) { throw new ParsingError(sectionName, line, lineNumber, line.IndexOf(splitLine[4], StringComparison.Ordinal), "Unable to find the right input register."); } RegisterBase output; if (!Registers.TryGetValue(splitLine[5], out output) || output is InputRegister) { throw new ParsingError(sectionName, line, lineNumber, line.IndexOf(splitLine[5], StringComparison.Ordinal), "Unable to find the output register."); } var outputWithParent = (RegisterWithParentBase)output; if (outputWithParent.Parent != null) { throw new ParsingError(sectionName, line, lineNumber, line.IndexOf(splitLine[5], StringComparison.Ordinal), "The output register is already linked to another operation."); } var operation = outputWithParent.Parent = new Operation { Id = $"op{opIndex:000}", Name = splitLine[0], Op = splitLine[1].ToUpper(), Bits = bits, Left = left, Right = right, Output = outputWithParent, VhdlCodeFile = codeFileForOp }; Operations.Add(operation.Name, operation); }
private async Task TryCommitToFileAsync(ITxStoreOperation operation) { try { if (operation is null || operation.IsEmpty) { return; } // Make sure that only one call can continue. lock (OperationsLock) { var isRunning = Operations.Any(); Operations.Add(operation); if (isRunning) { return; } } // Wait until the operation list calms down. IEnumerable <ITxStoreOperation> operationsToExecute; while (true) { var count = Operations.Count; await Task.Delay(100).ConfigureAwait(false); lock (OperationsLock) { if (count == Operations.Count) { // Merge operations. operationsToExecute = OperationMerger.Merge(Operations).ToList(); Operations.Clear(); break; } } } using (await TransactionsFileAsyncLock.LockAsync().ConfigureAwait(false)) { foreach (ITxStoreOperation op in operationsToExecute) { if (op is Append appendOperation) { var toAppends = appendOperation.Transactions; try { await TransactionsFileManager.AppendAllLinesAsync(toAppends.ToBlockchainOrderedLines()).ConfigureAwait(false); } catch { await SerializeAllTransactionsNoLockAsync().ConfigureAwait(false); } } else if (op is Remove removeOperation) { var toRemoves = removeOperation.Transactions; string[] allLines = await TransactionsFileManager.ReadAllLinesAsync().ConfigureAwait(false); var toSerialize = new List <string>(); foreach (var line in allLines) { var startsWith = false; foreach (var toRemoveString in toRemoves.Select(x => x.ToString())) { startsWith = startsWith || line.StartsWith(toRemoveString, StringComparison.Ordinal); } if (!startsWith) { toSerialize.Add(line); } } try { await TransactionsFileManager.WriteAllLinesAsync(toSerialize).ConfigureAwait(false); } catch { await SerializeAllTransactionsNoLockAsync().ConfigureAwait(false); } } else if (op is Update updateOperation) { var toUpdates = updateOperation.Transactions; string[] allLines = await TransactionsFileManager.ReadAllLinesAsync().ConfigureAwait(false); IEnumerable <SmartTransaction> allTransactions = allLines.Select(x => SmartTransaction.FromLine(x, Network)); var toSerialize = new List <SmartTransaction>(); foreach (SmartTransaction tx in allTransactions) { var txsToUpdateWith = toUpdates.Where(x => x == tx); foreach (var txToUpdateWith in txsToUpdateWith) { tx.TryUpdate(txToUpdateWith); } toSerialize.Add(tx); } try { await TransactionsFileManager.WriteAllLinesAsync(toSerialize.ToBlockchainOrderedLines()).ConfigureAwait(false); } catch { await SerializeAllTransactionsNoLockAsync().ConfigureAwait(false); } } else { throw new NotSupportedException(); } } } } catch (Exception ex) { Logger.LogError(ex); } }
static void Main(string[] args) { var options = new Options(); if (!CommandLineParser.Default.ParseArguments(args, options)) { Environment.Exit(1); } var manager = new ResxDocumentManager(options); var printer = new ResxDataPrinter(options.FullData); if (options.MissingKeys) { var docs = manager.RequireTwoFiles(); var keys = Helpers.MissingKeys(docs.Item1, docs.Item2); var data = keys.Select(k => docs.Item1.Data.First(d => d.Name == k)); Console.Out.Write(string.Join(Environment.NewLine, data.Select(printer.SingleDataString))); } if (options.PresentKeys) { var docs = manager.RequireTwoFiles(); var keys = Helpers.PresentKeys(docs.Item1, docs.Item2); var leftData = keys.Select(k => docs.Item1.Data.First(d => d.Name == k)); var rightData = keys.Select(k => docs.Item2.Data.First(d => d.Name == k)); Console.Out.Write(string.Join(Environment.NewLine, leftData.Zip(rightData, printer.DoubleDataString))); } if (options.DifferentValues) { var docs = manager.RequireTwoFiles(); var keys = Helpers.DifferentValues(docs.Item1, docs.Item2); var leftData = keys.Select(k => docs.Item1.Data.First(d => d.Name == k)); var rightData = keys.Select(k => docs.Item2.Data.First(d => d.Name == k)); Console.Out.Write(string.Join(Environment.NewLine, leftData.Zip(rightData, printer.DoubleDataString))); } if (options.IdenticalValues) { var docs = manager.RequireTwoFiles(); var keys = Helpers.IdenticalValues(docs.Item1, docs.Item2); var data = keys.Select(k => docs.Item1.Data.First(d => d.Name == k)); Console.Out.Write(string.Join(Environment.NewLine, data.Select(printer.SingleDataString))); } if (options.MismatchedMetadata) { var docs = manager.RequireTwoFiles(); var keys = Helpers.MismatchedMetadata(docs.Item1, docs.Item2); var leftData = keys.Select(k => docs.Item1.Data.First(d => d.Name == k)); var rightData = keys.Select(k => docs.Item2.Data.First(d => d.Name == k)); Console.Out.Write(string.Join(Environment.NewLine, leftData.Zip(rightData, printer.DoubleDataString))); } if (options.DuplicateKeys) { var doc = manager.RequireOneFile(); var keys = Helpers.DuplicateKeys(doc); var data = keys.Select(k => doc.Data.First(d => d.Name == k)); Console.Out.Write(string.Join(Environment.NewLine, data.Select(printer.SingleDataString))); } if (options.MissingSpacePreserve) { var doc = manager.RequireOneFile(); var keys = Helpers.MissingSpacePreserve(doc); var data = keys.Select(k => doc.Data.First(d => d.Name == k)); Console.Out.Write(string.Join(Environment.NewLine, data.Select(printer.SingleDataString))); } // Operations if (options.CopyMissingKeys) { var docs = manager.RequireTwoFiles(); var keys = Helpers.MissingKeys(docs.Item1, docs.Item2); Operations.CopyKeys(keys, docs.Item1, docs.Item2); manager.MarkForSaving(docs.Item2); } if (options.CopyDifferentValues) { var docs = manager.RequireTwoFiles(); var keys = Helpers.DifferentValues(docs.Item1, docs.Item2); Operations.CopyValues(keys, docs.Item1, docs.Item2); manager.MarkForSaving(docs.Item2); } if (options.Alphabetise) { var docs = manager.RequireFiles(); docs.ToList().ForEach(Operations.Alphabetise); manager.MarkForSaving(docs); } if (options.AddMissingSpacePreserve) { var docs = manager.RequireFiles(); docs.ToList().ForEach(Operations.AddMissingSpacePreserve); manager.MarkForSaving(docs); } manager.SaveMarkedDocuments(); }
/// <summary> /// preAgent send an obtian packet to ask for the new agent of the sink. /// </summary> /// <param name="preAgent"></param> /// <param name="SinksIDsRequiredRecovery"></param> public RecoveryMessage(Sensor preAgent, Packet packet) { // preAgent: if it has no record, then we obtian the sink position first. // if the preAgent did not sent an obtian message to the hightier node if (preAgent.RecoveryRow == null) { // obtian the recovery. obtian the sink location. Console.WriteLine("RecoveryMessage. >>>>Trying to recover the packet. Source ID=" + packet.Source.ID + " PID=" + packet.PID + " Path " + packet.Path); new ObtainSinkFreshPositionMessage(preAgent, packet.SinkIDsNeedsRecovery); } else { // it has record. no need to resend an obtian: but you should wait. if (!preAgent.RecoveryRow.IsExpired) { // not expired List <Sensor> NewAents = new List <Sensor>(); // new agent for the recovery. foreach (SinksAgentsRow newAgentRow in preAgent.RecoveryRow.RecoveryAgentList) { if (newAgentRow.AgentNode.ID != preAgent.ID) { bool isFound = Operations.FindInAlistbool(newAgentRow.AgentNode, NewAents); if (!isFound) { packet.Destination = newAgentRow.AgentNode.CenterLocation; NewAents.Add(newAgentRow.AgentNode); } } } // if we found the new agent. if (NewAents.Count > 0) { Console.WriteLine("RecoveryMessage. Source ID=" + packet.Source.ID + " PID=" + packet.PID + " Path " + packet.Path); packet.SinksAgentsList = preAgent.RecoveryRow.RecoveryAgentList; new DataPacketMessages(preAgent, packet); } else { if (preAgent.RecoveryRow.ObtainPacketsRetry >= 3) { // in case no new agent is found. Console.WriteLine("RecoveryMessage. No agent is found during the recovery.Source ID = " + packet.Source.ID + " PID = " + packet.PID + " Path " + packet.Path); NetworkOverheadCounter counter = new NetworkOverheadCounter(); counter.DropPacket(packet, preAgent, PacketDropedReasons.RecoveryNoNewAgentFound); } else { Console.WriteLine("RecoveryMessage. Recovery period is expired. Old Agent is sending new obtain packet!" + " Path " + packet.Path); new ObtainSinkFreshPositionMessage(preAgent, packet.SinkIDsNeedsRecovery); // obtain } } } else { // resent the obtian packet. 2 times. if (preAgent.RecoveryRow.ObtainPacketsRetry <= 3) { Console.WriteLine("RecoveryMessage. Recovery period is expired. Old Agent is sending new obtain packet!" + " Path " + packet.Path); new ObtainSinkFreshPositionMessage(preAgent, packet.SinkIDsNeedsRecovery); // obtain } else { Console.WriteLine("RecoveryMessage. Recovery period is expired. we tryied to re-sent the obtian packet for three times and faild. The packet will be droped." + " Path " + packet.Path); // drop the packet: NetworkOverheadCounter counter = new NetworkOverheadCounter(); counter.DropPacket(packet, preAgent, PacketDropedReasons.RecoveryPeriodExpired); preAgent.RecoveryRow = null; } } } }
/// <summary> /// Initializes a new instance of the <see cref="MixedRational" /> struct. /// </summary> /// <param name="value">The value.</param> public MixedRational(double value) : this(0, (int)(value / Operations.GCD(value, 1d)), 1) { }
// Reloads data when tab is switched private async void Tab_ChangeFocus(object sender, RoutedEventArgs e) { await Task.Run(() => Operations.LoadProductData()); }
private void RemoveOutliers() { GTPoint meanLeft = new GTPoint(); GTPoint stddevLeft = new GTPoint(); GTPoint meanRight = new GTPoint(); GTPoint stddevRight = new GTPoint(); numOutliersRemovedLeft = 0; numOutliersRemovedRight = 0; foreach (CalibrationTarget ct in CalibrationTargets) { #region Calculate mean and std // Left if (ct.DifferenceVectorLeft != null) { meanLeft = Operations.Mean(ct.DifferenceVectorLeft); stddevLeft = Operations.StandardDeviation(ct.DifferenceVectorLeft); //double averageErrorMM = ConvertPixToMm(stddevLeft); //double precision = (180 / Math.PI) * Math.Atan(averageErrorMM / (2 * GTSettings.Current.Calibration.DistanceFromScreen)); //Console.Write(precision); } // Right if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { if (ct.DifferenceVectorRight != null) { meanRight = Operations.Mean(ct.DifferenceVectorRight); stddevRight = Operations.StandardDeviation(ct.DifferenceVectorRight); } } #endregion try { for (int i = 0; i < ct.NumImages - 1; i++) { // remove left if (ct.DifferenceVectorLeft != null && i <= ct.DifferenceVectorLeft.Length) { if (Math.Abs(ct.DifferenceVectorLeft[i].X - meanLeft.X) > stddevLeft.X || Math.Abs(ct.DifferenceVectorLeft[i].Y - meanLeft.Y) > stddevLeft.Y) { if (ct.pupilCentersLeft.Count <= i) { ct.pupilCentersLeft.RemoveAt(i - numOutliersRemovedLeft); } if (ct.glintsLeft.Count <= i) { ct.glintsLeft.RemoveAt(i - numOutliersRemovedLeft); } numOutliersRemovedLeft++; } } // remove right (if binocular) if (GTSettings.Current.Processing.TrackingMode == TrackingModeEnum.Binocular) { if (ct.DifferenceVectorRight != null && i <= ct.DifferenceVectorRight.Length) { if (Math.Abs(ct.DifferenceVectorRight[i].X - meanRight.X) > stddevRight.X || Math.Abs(ct.DifferenceVectorRight[i].Y - meanRight.Y) > stddevRight.Y) { if (ct.pupilCentersRight.Count <= i) { ct.pupilCentersRight.RemoveAt(i - numOutliersRemovedRight); } if (ct.glintsRight.Count <= i) { ct.glintsRight.RemoveAt(i - numOutliersRemovedRight); } numOutliersRemovedRight++; } } } //Console.WriteLine("{0} outliers removed out of a total of {1}, Old std: {2}, {3}, New std: {4}, {5}", // numOutliersRemovedLeft, ct.NumImages, stddevLeft.X, stddevLeft.Y, Operations.StandardDeviation(ct.DifferenceVectorLeft).X, // Operations.StandardDeviation(ct.DifferenceVectorLeft).Y); } } catch (Exception ex) { Console.Out.WriteLine("Calibration.cs, error while removing outlier eye. Message: " + ex.Message); } } }
public void Test_Is_Empty() { List <int> emptyList = new List <int>(); Assert.AreEqual(0, Operations.Max(emptyList)); }
public static void OperationTest(Operations operation, DataType dataType) { dynamic result = 0; switch (dataType) { case DataType.Int: result = Integer; break; case DataType.Long: result = LongInteger; break; case DataType.Float: result = FloatNumber; break; case DataType.Double: result = DoubleNumber; break; case DataType.Decimal: result = DecimalNumber; break; } Stopwatch.Start(); ///using "Integer" const because "result" is casted to the specific type ///so c# explicitly casts the "Integer" const to whatever data type "result" is for (int i = 0; i < OpertaionsCount; i++) { switch (operation) { case Operations.Add: result += Integer; break; case Operations.Subtract: result -= Integer; break; case Operations.Multiply: result *= Integer; break; case Operations.Divide: result /= Integer; break; case Operations.Increment: result++; break; default: throw new InvalidOperationException(); } } var elapsedType = Stopwatch.Elapsed; Console.WriteLine("Used type: {0}\nElapsed Time for {1} operations: {2}\n", (Enum)dataType, OpertaionsCount, elapsedType); }
public MeasureToMeasure(string name, Hierarchy HostHier, Member Measure1, Member Measure2, Operations op) : base(name, HostHier) { if (HostHier.UniqueName != "[Measures]") { throw new Exception("Cannot create on non-measures hierarchy"); } _operation = op; //DataMember measure1=this.Hierarchy.AddDataMember(Measure1); //DataMember measure2=this.Hierarchy.AddDataMember(Measure2); _mdxParameters.Add(Measure1, false); if (Measure1.UniqueName != Measure2.UniqueName) { _mdxParameters.Add(Measure2, false); //add if not equal } Initialize(name, true); }
public IfOperator( Operations repository) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); }
/// <inheritdoc/> public async override Task <ArmOperation <AvailabilitySet> > StartCreateOrUpdateAsync(string name, AvailabilitySetData resourceDetails, CancellationToken cancellationToken = default) { return(new PhArmOperation <AvailabilitySet, Azure.ResourceManager.Compute.Models.AvailabilitySet>( await Operations.CreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken).ConfigureAwait(false), a => new AvailabilitySet(Parent, new AvailabilitySetData(a)))); }
/// <summary> /// Get grouped OrderStatus /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1StatusGrouped_Click(object sender, EventArgs e) { var ops = new Operations(); MessageBox.Show(ops.GroupedStatus()); }
public static bool Decode(out object result, Type type, BinaryReader reader, Operations encryptOperations, bool reverseByteOrder = false) { result = null; if (type == typeof(Int32) || type == typeof(Int16)) { var bitcounter = 0; var data = 0; do { var encryptedByte = encryptOperations.Decrypt(reader.ReadByte()); data |= (encryptedByte & 0x7F) << bitcounter; if ((sbyte)encryptedByte >= 0) { result = (dynamic)data; return(true); } bitcounter += 7; } while (reader.BaseStream.Position < reader.BaseStream.Length); } else if (type == typeof(Byte)) { result = (dynamic)encryptOperations.Decrypt(reader.ReadByte()); return(true); } else if (type == typeof(Single)) { byte[] buffer = new byte[4]; for (int i = 0; i < buffer.Length; i++) { buffer[i] = encryptOperations.Decrypt(reader.ReadByte()); } result = BitConverter.ToSingle(reverseByteOrder ? buffer : buffer.Reverse().ToArray(), 0); return(true); } else if (type == typeof(Vector3)) { object x = null; object y = null; object z = null; bool success = Decode(out x, typeof(Single), reader, encryptOperations, reverseByteOrder) && Decode(out y, typeof(Single), reader, encryptOperations, reverseByteOrder) && Decode(out z, typeof(Single), reader, encryptOperations, reverseByteOrder); result = new Vector3((float)x, (float)y, (float)z); return(success); } else if (type == typeof(Vector2)) { object x = null; object y = null; bool success = Decode(out x, typeof(Single), reader, encryptOperations, reverseByteOrder) && Decode(out y, typeof(Single), reader, encryptOperations, reverseByteOrder); result = (dynamic) new Vector2((float)x, (float)y); return(success); } return(false); }
/// <summary> /// Calculation and sending results to string /// </summary> /// <param name="numberA">#1 number</param> /// <param name="numberB">#2 number</param> /// <param name="operation">Type of operation</param> /// <param name="repeats">Number of repetitions</param> /// <returns></returns> public List <String> CalucaltionsAndReturningThemAsString(float numberA, float numberB, Operations operation, int repeats) { List <String> listResult = new List <String>(); { listResult.Add("========================================"); listResult.Add($"A = {numberA}, B = {numberB}, Działanie = {EnumUtils.StringValueOf(operation)}, Liczba działań = {repeats}\n"); } for (int i = 0; i < repeats; i++) { // Switch loop with type of operations as argument used switch (operation) { case Operations.Addition: listResult.Add($"[{numberA}] + [{numberB}] = [{numberA + numberB}]\n"); numberB = numberA + numberB; break; case Operations.Subtraction: listResult.Add($"[{numberA}] - [{numberB}] = [{numberA - numberB}]\n"); numberB = numberA - numberB; break; case Operations.Multiplication: listResult.Add($"[{numberA}] * [{numberB}] = [{numberA * numberB}]\n"); numberB = numberA * numberB; break; case Operations.Division: listResult.Add( (String.Format("{0:0.##}", numberA) + " / " + (String.Format("{0:0.##}", numberB)) + " = " + (String.Format("{0:0.##}", numberA / numberB)) + "\n")); numberB = numberA / numberB; break; case Operations.exponentiation: listResult.Add($"[{numberA}] ^ [{numberB}] = [{Math.Pow(System.Convert.ToDouble(numberA), Convert.ToDouble(numberB))}]\n"); numberB = Convert.ToSingle(Math.Pow(System.Convert.ToDouble(numberA), Convert.ToDouble(numberB))); break; case Operations.modulo: listResult.Add($"[{numberA}] % [{numberB}] = [{numberA % numberB}]\n"); numberB = numberA % numberB; break; } } return(listResult); }