private void LoadUI(Code.Playlist.Playlist playlist) { this.StackMedia.Children.Clear(); if (playlist != null) { this.UITitle.Text = playlist.Name; List<MediaEvent> Medias = playlist.LoadMediaEvent(); if (Medias != null) { foreach (MediaEvent e in Medias) { UIMediaEvent UIE = new UIMediaEvent(); UIE.Height = 50; UIE.Width = 395; UIE.Event = e; UIE.DeleteEvent += UIE_DeleteEvent; UIE.ViewMediaEvent += UIE_ViewMediaEvent; this.StackMedia.Children.Add(UIE); } } } else { this.UITitle.Text = string.Empty; } }
public static string GetLanguageCodeAsString(Code languageCode) { switch (languageCode) { case Code.EN: return "EN"; case Code.FR: return "FR"; case Code.IT: return "IT"; case Code.DE: return "DE"; case Code.ES: return "ES"; case Code.AR: return "AR"; case Code.ZHCN: return "ZH-CN"; case Code.JA: return "JA"; case Code.KO: return "KO"; case Code.VI: return "VI"; case Code.RU: return "RU"; case Code.NL: return "NL"; case Code.PT: return "PT"; } return "Invalid Language"; }
public Instruction(int offset, Code opcode, object operand, object operand2) { this.offset = offset; this.opcode = opcode; Operand = operand; this.operand2 = operand2; }
public void power_search_doctor_pageloaddata() { Code cd = new Code(); DataSet ds = cd.power_search_doctor_pageloaddata(); if (ds != null && ds.Tables[0].Rows.Count > 0) { // Health center Names DropDownList1.DataTextField = ds.Tables[0].Columns["Name"].ToString(); DropDownList1.DataValueField = ds.Tables[0].Columns["ID"].ToString(); DropDownList1.DataSource = ds.Tables[0]; DropDownList1.DataBind(); DropDownList1.Items.Insert(0, "Any"); // Studied at - Country table DropDownList7.DataTextField = ds.Tables[1].Columns["Name"].ToString(); DropDownList7.DataValueField = ds.Tables[1].Columns["ID"].ToString(); DropDownList7.DataSource = ds.Tables[1]; DropDownList7.DataBind(); DropDownList7.Items.Insert(0, "Any"); // Worked at - Country table DropDownList2.DataTextField = ds.Tables[1].Columns["Name"].ToString(); DropDownList2.DataValueField = ds.Tables[1].Columns["ID"].ToString(); DropDownList2.DataSource = ds.Tables[1]; DropDownList2.DataBind(); DropDownList2.Items.Insert(0, "Any"); // Specialist - Specifications table DropDownList4.DataTextField = ds.Tables[2].Columns["Name"].ToString(); DropDownList4.DataValueField = ds.Tables[2].Columns["ID"].ToString(); DropDownList4.DataSource = ds.Tables[2]; DropDownList4.DataBind(); DropDownList4.Items.Insert(0, "Any"); } }
public void CanBeEqual() { var code1 = new Code("code"); var code2 = new Code("code"); Assert.AreEqual(code1,code2); }
public void TestCanAddAFunctionStrCode() { const string name = "faddsc"; var func = new Code("function(x, y){return x + y;}"); _javascript.Add(name, func); Assert.IsNotNull(_javascript[name]); }
public CodeViewModel(Code codeModel) { var View = new CodeView(); View.DataContext = this; foreach (var backProp in codeModel.BackingProperties) { FullCode += backProp; } FullCode += "/r"; foreach (var backDel in codeModel.BackingDelegates) { FullCode += backDel; } FullCode += "/r/r"; foreach (var con in codeModel.Constructors) { FullCode += con; } FullCode += "/r/r #region DelegateMethods/r"; foreach (var delMethod in codeModel.DelegateMethods) { FullCode += delMethod; } FullCode += "#endregion/r/r#region Properties/r"; foreach (var foreProp in codeModel.ForegroundProperties) { FullCode += foreProp; } FullCode += "#endregion"; FullCode = FullCode.Replace("/r", Environment.NewLine); View.Show(); }
private static Boolean Is_Ldarg_C(VirtualOpCode ins, Code code) { // Ldarg_C delegates will reference the arguments field in their Ldfld, which sets them apart from // other very similar delegates return ins.Matches(ins.ModifyPattern(Pattern_Ldarg_C, Code.Ldc_I4, code)) && ((FieldDef)ins.DelegateMethod.Body.Instructions[2].Operand).MDToken == ins.VType.ArgumentsField.MDToken; }
static FieldDefinition GetSingleField(PropertyDefinition property, Code code, MethodDefinition methodDefinition) { if (methodDefinition?.Body == null) { return null; } FieldReference fieldReference = null; foreach (var instruction in methodDefinition.Body.Instructions) { if (instruction.OpCode.Code == code) { //if fieldReference is not null then we are at the second one if (fieldReference != null) { return null; } var field = instruction.Operand as FieldReference; if (field != null) { if (field.DeclaringType != property.DeclaringType) { continue; } if (field.FieldType != property.PropertyType) { continue; } fieldReference = field; } } } return fieldReference?.Resolve(); }
async void feedControl_FeedbackReceived(Code.FeedbackObject feedbackObj) { ShowProgressBar(true); // send the feedback to the server from here var feedbackResult = await MyILPClient.RegisterFacultyFeedback(currentSelectedSchedule, feedbackObj); string title = "Information"; string content = ""; switch (feedbackResult.FeedStatus) { case FeedbackResult.FeedbackStatusType.NEW: content = "Thank you giving your valuable feedback!"; break; case FeedbackResult.FeedbackStatusType.OLD: content = "Feedback has already been given for the selected slot"; break; case FeedbackResult.FeedbackStatusType.ERROR: title = "Error"; content = "Some error has occured while trying to send feedback. Please try again later."; break; } MessageDialog md = new MessageDialog(content, title); await md.ShowAsync(); #if DEBUG System.Diagnostics.Debug.WriteLine("Feedback result: " + feedbackResult.FeedStatus); #endif ShowProgressBar(false); }
public static Value[] getInitializedArray(int arraySize, MethodDefinition method, ref int newarrIndex, Code stelemOpCode) { var resultValueArray = new Value[arraySize]; var emulator = new InstructionEmulator(method.HasThis, false, method.Parameters, method.Body.Variables); var theArray = new UnknownValue(); emulator.push(theArray); var instructions = method.Body.Instructions; int i; for (i = newarrIndex + 1; i < instructions.Count; i++) { var instr = instructions[i]; if (instr.OpCode.FlowControl != FlowControl.Next) break; if (instr.OpCode.Code == Code.Newarr) break; if (instr.OpCode.Code == stelemOpCode) { var value = emulator.pop(); var index = emulator.pop() as Int32Value; var array = emulator.pop(); if (ReferenceEquals(array, theArray) && index != null && index.allBitsValid()) { if (0 <= index.value && index.value < resultValueArray.Length) resultValueArray[index.value] = value; } } else emulator.emulate(instr); } if (i != newarrIndex + 1) i--; newarrIndex = i; return resultValueArray; }
public void Convert(string inputFileName, string outputFileName) { VersionableBase.DefaultAgencyId = "example.org"; if (string.IsNullOrWhiteSpace(inputFileName)) { throw new ArgumentNullException("inputFileName"); } if (string.IsNullOrWhiteSpace(outputFileName)) { throw new ArgumentNullException("outputFileName"); } InitializeDdiElements(); // Go through each row of the spreadsheet. DataTable iscoTable = GetSpreadsheetContents(inputFileName); foreach (DataRow row in iscoTable.Rows) { // Create a category and map information from each column. Category category = new Category(); category.Label["en"] = row["description EN"].ToString(); category.Label["fr"] = row["description FR"].ToString(); category.Label["de"] = row["description DE"].ToString(); category.Description["en"] = row["texte auto EN"].ToString(); category.Description["fr"] = row["texte auto FR"].ToString(); category.Description["de"] = row["texte auto DE"].ToString(); categoryScheme.Categories.Add(category); // Create a code. Code code = new Code(); code.Category = category; code.Value = row["code"].ToString(); // First level codes are added directly the CodeScheme. int level = code.Value.Length; if (level == 1) { codeScheme.Codes.Add(code); } else { // For child codes, look up the parent code. // The parent's value will be the same as this new code's value, // minus the last character. var flatCodes = codeScheme.GetFlattenedCodes(); Code parent = flatCodes.SingleOrDefault(c => c.Value == code.Value.Substring(0, code.Value.Length - 1)); parent.ChildCodes.Add(code); } Console.WriteLine(string.Format("{0} {1}", code.Value, category.Label["en"])); } // Save the DDI XML. DDIWorkflowSerializer serializer = new DDIWorkflowSerializer(); serializer.UseConciseBoundedDescription = false; XmlDocument doc = serializer.Serialize(this.instance); DDIWorkflowSerializer.SaveXml(outputFileName, doc); }
public void TestCanAddFunctionByAssignment() { const string name = "fassignadd"; var func = new Code("function(x,y){return x + y;}"); var doc = new Document().Add("_id", name).Add("value", func); _javascript[name] = doc; Assert.IsNotNull(_javascript[name]); }
public ScanData(int count, int retCode, int d9, int d324) { this.count = count; this.retCode = retCode; this.priority = (Code)retCode; this.patternD9 = d9; this.patternD3D2D4 = d324; }
public CodeRunner(IDebugger debugger, string source) { _debugger = debugger; _source = source; Context = new Context(new Scope()); CodeGenerator = new Code(); }
public Code Field(Code baseExpr, String name) { Type scope = (baseExpr == null) ? cls : ((Node)baseExpr).Type; FieldInfo f = QueryImpl.lookupField(scope, name); if (f == null) { throw new CodeGeneratorException("No such field " + name + " in class " + scope); } return new LoadNode((Node)baseExpr, f); }
private static InstructionKindEnum GetInstructionKind(Code value) { var xName = value.ToString(); if (xName.EndsWith("_S")) { xName = xName.Substring(0, xName.Length - 2); } return (InstructionKindEnum)Enum.Parse(typeof(InstructionKindEnum), xName); }
public void TestSerializeDocWithCode() { var c = new Code("function add(x, y){\n" + " return x + y;\n" + "}\n"); var doc = new Document(){{"c", c}}; Assert.AreEqual(@"{ ""c"": { $code : ""function add(x, y){\n return x + y;\n}\n"" } }", JsonUtils.Serialize(doc)); }
public SnapWindow(Code.Interface.ISnapWindow Window, string HeaderText) { InitializeComponent(); Pinned = false; HeaderVisible = true; this.WindowContent = Window; this.Header.Text = HeaderText; }
public static int FindCallMethod(IList<Instr> instrs, int index, Code callCode, string methodFullName) { for (int i = index; i < instrs.Count; i++) { if (!IsCallMethod(instrs[i].Instruction, callCode, methodFullName)) continue; return i; } return -1; }
public static void BranchShort(this List<object> codeList, Code op, int label) { Debug.Assert((codeList.Count() - label) < SByte.MaxValue); // +2, op code + address code, as backward jump start from first byte of the end of branch command with address var address = (byte) -(codeList.Count() - label + 2); codeList.Add(op); codeList.Add(address); }
void feedControl_FeedbackCancelled(Code.FeedbackObject feedbackObj) { string fdString = string.Format("Cancelled feedback for {0}\nCourse: {1}\n", feedbackObj.FacultyName, feedbackObj.CourseName); #if DEBUG System.Diagnostics.Debug.WriteLine(fdString); #endif }
void feedControl_FeedbackReceived(Code.FeedbackObject feedbackObj) { string fdString = string.Format("Received feedback for {0}\nCourse: {1}\nRating: {2}\nComments: {3}\n", feedbackObj.FacultyName, feedbackObj.CourseName, feedbackObj.Rating, feedbackObj.Comments); #if DEBUG System.Diagnostics.Debug.WriteLine(fdString); #endif }
public BFunction(IEnvironment environment, Code code, ReadOnlyList<string> formalParameters) : base(environment) { _code = code; _formalParameters = formalParameters; Class = "Function"; Extensible = true; Prototype = Environment.FunctionPrototype; DefineOwnProperty("length", Environment.CreateDataDescriptor(Environment.CreateNumber(_formalParameters.Count), false, false, false), false); }
static void Main(string[] args) { Code code = new Code(); // Dry run. Console.WriteLine(code.encode("Dry run.")); // Suspend the console. Console.ReadKey(); }
public static int FindOpCodeIndex(MethodDef method, int index, Code code) { for (; index < method.Body.Instructions.Count; index++) { var instr = method.Body.Instructions[index]; if (instr.OpCode.Code != code) continue; return index; } return -1; }
public override void VisitCode(Code code) { _builder.AppendLine(); _builder.AppendLine(); // Indent code with 4 spaces according to Markdown syntax. foreach (var line in code.Content.Split(new[] { Environment.NewLine }, StringSplitOptions.None)) { _builder.Append(" "); _builder.AppendLine(line); } base.VisitCode(code); }
public void CanBeXmlSerializedWithNullValue() { var source = new Code(null); var serializer = new XmlSerializer(typeof(Code)); var writer = new StringWriter(); serializer.Serialize(writer, source); var dest = (Code)serializer.Deserialize(new StringReader(writer.ToString())); Assert.AreEqual(source, dest); }
public static Page Fetch(Service service) { if (!Platform.HasInternetConnection()) { return new ContentPage { Content = new Label { Text = Localize.GetString("TelegramPleaseConnectToInternet"), VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand, XAlign = TextAlignment.Center, Font = Font.SystemFontOfSize(18), }, Title = Localize.GetString("TelegramSetupWizardTitle"), Padding = 30, }; } LoadSettingsIfNeeded(); if (_cachedPage != null) { return _cachedPage; } var tabs = new TabbedPage(); var code = new Code(service, tabs); var verify = new Verify(service, tabs, code); var info = new Info(service, tabs, verify); tabs.Children.Add(info); tabs.PropertyChanged += (sender, e) => { if (e.PropertyName == "CurrentPage") { var selected = tabs.CurrentPage; if (selected is Info) { tabs.Children.Remove(verify); tabs.Children.Remove(code); } if (selected is Verify) { tabs.Children.Remove(code); } } }; tabs.Title = Localize.GetString("TelegramSetupWizardTitle"); _cachedPage = tabs; return tabs; }
protected void TestInstructionInfo(int bitness, string hexBytes, Code code, DecoderOptions options, int lineNo, InstructionInfoTestCase testCase) { var codeBytes = HexUtils.ToByteArray(hexBytes); Instruction instr; if (testCase.IsSpecial) { if (bitness == 16 && code == Code.Popw_CS && hexBytes == "0F") { instr = default; instr.Code = Code.Popw_CS; instr.Op0Kind = OpKind.Register; instr.Op0Register = Register.CS; instr.CodeSize = CodeSize.Code16; instr.ByteLength = 1; } else if (code >= Code.DeclareByte) { instr = default; instr.Code = code; instr.DeclareDataCount = 1; Assert.Equal(64, bitness); instr.CodeSize = CodeSize.Code64; switch (code) { case Code.DeclareByte: Assert.Equal("66", hexBytes); instr.SetDeclareByteValue(0, 0x66); break; case Code.DeclareWord: Assert.Equal("6644", hexBytes); instr.SetDeclareWordValue(0, 0x4466); break; case Code.DeclareDword: Assert.Equal("664422EE", hexBytes); instr.SetDeclareDwordValue(0, 0xEE224466); break; case Code.DeclareQword: Assert.Equal("664422EE12345678", hexBytes); instr.SetDeclareQwordValue(0, 0x78563412EE224466); break; default: throw new InvalidOperationException(); } } else { var decoder = CreateDecoder(bitness, codeBytes, options); instr = decoder.Decode(); if (codeBytes.Length > 1 && codeBytes[0] == 0x9B && instr.ByteLength == 1) { instr = decoder.Decode(); switch (instr.Code) { case Code.Fnstenv_m14byte: instr.Code = Code.Fstenv_m14byte; break; case Code.Fnstenv_m28byte: instr.Code = Code.Fstenv_m28byte; break; case Code.Fnstcw_m16: instr.Code = Code.Fstcw_m16; break; case Code.Fneni: instr.Code = Code.Feni; break; case Code.Fndisi: instr.Code = Code.Fdisi; break; case Code.Fnclex: instr.Code = Code.Fclex; break; case Code.Fninit: instr.Code = Code.Finit; break; case Code.Fnsetpm: instr.Code = Code.Fsetpm; break; case Code.Fnsave_m94byte: instr.Code = Code.Fsave_m94byte; break; case Code.Fnsave_m108byte: instr.Code = Code.Fsave_m108byte; break; case Code.Fnstsw_m16: instr.Code = Code.Fstsw_m16; break; case Code.Fnstsw_AX: instr.Code = Code.Fstsw_AX; break; default: throw new InvalidOperationException(); } } else { throw new InvalidOperationException(); } } } else { var decoder = CreateDecoder(bitness, codeBytes, options); instr = decoder.Decode(); } Assert.Equal(code, instr.Code); Assert.Equal(testCase.StackPointerIncrement, instr.StackPointerIncrement); var info = instr.GetInfo(); Assert.Equal(testCase.Encoding, info.Encoding); Assert.Equal(testCase.CpuidFeatures, info.CpuidFeatures); Assert.Equal(testCase.RflagsRead, info.RflagsRead); Assert.Equal(testCase.RflagsUndefined, info.RflagsUndefined); Assert.Equal(testCase.RflagsWritten, info.RflagsWritten); Assert.Equal(testCase.RflagsCleared, info.RflagsCleared); Assert.Equal(testCase.RflagsSet, info.RflagsSet); Assert.Equal(testCase.IsPrivileged, info.IsPrivileged); Assert.Equal(testCase.IsProtectedMode, info.IsProtectedMode); Assert.Equal(testCase.IsStackInstruction, info.IsStackInstruction); Assert.Equal(testCase.IsSaveRestoreInstruction, info.IsSaveRestoreInstruction); Assert.Equal(testCase.FlowControl, info.FlowControl); Assert.Equal(testCase.Op0Access, info.Op0Access); Assert.Equal(testCase.Op1Access, info.Op1Access); Assert.Equal(testCase.Op2Access, info.Op2Access); Assert.Equal(testCase.Op3Access, info.Op3Access); Assert.Equal(testCase.Op4Access, info.Op4Access); Assert.Equal( new HashSet <UsedMemory>(testCase.UsedMemory, UsedMemoryEqualityComparer.Instance), new HashSet <UsedMemory>(info.GetUsedMemory(), UsedMemoryEqualityComparer.Instance)); Assert.Equal( new HashSet <UsedRegister>(GetUsedRegisters(testCase.UsedRegisters), UsedRegisterEqualityComparer.Instance), new HashSet <UsedRegister>(GetUsedRegisters(info.GetUsedRegisters()), UsedRegisterEqualityComparer.Instance)); Assert.Equal(info.GetUsedMemory(), instr.GetUsedMemory(), UsedMemoryEqualityComparer.Instance); Assert.Equal(info.GetUsedRegisters(), instr.GetUsedRegisters(), UsedRegisterEqualityComparer.Instance); Debug.Assert(Iced.Intel.DecoderConstants.MaxOpCount == 5); Debug.Assert(instr.OpCount <= Iced.Intel.DecoderConstants.MaxOpCount); for (int i = 0; i < instr.OpCount; i++) { switch (i) { case 0: Assert.Equal(testCase.Op0Access, info.GetOpAccess(i)); break; case 1: Assert.Equal(testCase.Op1Access, info.GetOpAccess(i)); break; case 2: Assert.Equal(testCase.Op2Access, info.GetOpAccess(i)); break; case 3: Assert.Equal(testCase.Op3Access, info.GetOpAccess(i)); break; case 4: Assert.Equal(testCase.Op4Access, info.GetOpAccess(i)); break; default: throw new InvalidOperationException(); } } for (int i = instr.OpCount; i < Iced.Intel.DecoderConstants.MaxOpCount; i++) { Assert.Equal(OpAccess.None, info.GetOpAccess(i)); } Assert.Equal(RflagsBits.None, info.RflagsWritten & (info.RflagsCleared | info.RflagsSet | info.RflagsUndefined)); Assert.Equal(RflagsBits.None, info.RflagsCleared & (info.RflagsWritten | info.RflagsSet | info.RflagsUndefined)); Assert.Equal(RflagsBits.None, info.RflagsSet & (info.RflagsWritten | info.RflagsCleared | info.RflagsUndefined)); Assert.Equal(RflagsBits.None, info.RflagsUndefined & (info.RflagsWritten | info.RflagsCleared | info.RflagsSet)); Assert.Equal(info.RflagsWritten | info.RflagsCleared | info.RflagsSet | info.RflagsUndefined, info.RflagsModified); var info2 = new InstructionInfoFactory().GetInfo(instr); CheckEqual(ref info, ref info2, hasRegs2: true, hasMem2: true); info2 = new InstructionInfoFactory().GetInfo(instr, InstructionInfoOptions.None); CheckEqual(ref info, ref info2, hasRegs2: true, hasMem2: true); info2 = new InstructionInfoFactory().GetInfo(instr, InstructionInfoOptions.NoMemoryUsage); CheckEqual(ref info, ref info2, hasRegs2: true, hasMem2: false); info2 = new InstructionInfoFactory().GetInfo(instr, InstructionInfoOptions.NoRegisterUsage); CheckEqual(ref info, ref info2, hasRegs2: false, hasMem2: true); info2 = new InstructionInfoFactory().GetInfo(instr, InstructionInfoOptions.NoRegisterUsage | InstructionInfoOptions.NoMemoryUsage); CheckEqual(ref info, ref info2, hasRegs2: false, hasMem2: false); info2 = instr.GetInfo(InstructionInfoOptions.None); CheckEqual(ref info, ref info2, hasRegs2: true, hasMem2: true); info2 = instr.GetInfo(InstructionInfoOptions.NoMemoryUsage); CheckEqual(ref info, ref info2, hasRegs2: true, hasMem2: false); info2 = instr.GetInfo(InstructionInfoOptions.NoRegisterUsage); CheckEqual(ref info, ref info2, hasRegs2: false, hasMem2: true); info2 = instr.GetInfo(InstructionInfoOptions.NoRegisterUsage | InstructionInfoOptions.NoMemoryUsage); CheckEqual(ref info, ref info2, hasRegs2: false, hasMem2: false); Assert.Equal(info.Encoding, instr.Code.Encoding()); #if !NO_ENCODER Assert.Equal(code.ToOpCode().Encoding, instr.Code.Encoding()); #endif var cf = instr.Code.CpuidFeatures(); if (cf.Length == 1 && cf[0] == CpuidFeature.AVX && instr.Op1Kind == OpKind.Register && (code == Code.VEX_Vbroadcastss_xmm_xmmm32 || code == Code.VEX_Vbroadcastss_ymm_xmmm32 || code == Code.VEX_Vbroadcastsd_ymm_xmmm64)) { cf = new[] { CpuidFeature.AVX2 } } ; Assert.Equal(info.CpuidFeatures, cf); Assert.Equal(info.FlowControl, instr.Code.FlowControl()); Assert.Equal(info.IsProtectedMode, instr.Code.IsProtectedMode()); Assert.Equal(info.IsPrivileged, instr.Code.IsPrivileged()); Assert.Equal(info.IsStackInstruction, instr.Code.IsStackInstruction()); Assert.Equal(info.IsSaveRestoreInstruction, instr.Code.IsSaveRestoreInstruction()); Assert.Equal(info.Encoding, instr.Encoding); Assert.Equal(info.CpuidFeatures, instr.CpuidFeatures); Assert.Equal(info.FlowControl, instr.FlowControl); Assert.Equal(info.IsProtectedMode, instr.IsProtectedMode); Assert.Equal(info.IsPrivileged, instr.IsPrivileged); Assert.Equal(info.IsStackInstruction, instr.IsStackInstruction); Assert.Equal(info.IsSaveRestoreInstruction, instr.IsSaveRestoreInstruction); Assert.Equal(info.RflagsRead, instr.RflagsRead); Assert.Equal(info.RflagsWritten, instr.RflagsWritten); Assert.Equal(info.RflagsCleared, instr.RflagsCleared); Assert.Equal(info.RflagsSet, instr.RflagsSet); Assert.Equal(info.RflagsUndefined, instr.RflagsUndefined); Assert.Equal(info.RflagsModified, instr.RflagsModified); } void CheckEqual(ref InstructionInfo info1, ref InstructionInfo info2, bool hasRegs2, bool hasMem2) { if (hasRegs2) { Assert.Equal(info1.GetUsedRegisters(), info2.GetUsedRegisters(), UsedRegisterEqualityComparer.Instance); } else { Assert.Empty(info2.GetUsedRegisters()); } if (hasMem2) { Assert.Equal(info1.GetUsedMemory(), info2.GetUsedMemory(), UsedMemoryEqualityComparer.Instance); } else { Assert.Empty(info2.GetUsedMemory()); } Assert.Equal(info1.IsProtectedMode, info2.IsProtectedMode); Assert.Equal(info1.IsPrivileged, info2.IsPrivileged); Assert.Equal(info1.IsStackInstruction, info2.IsStackInstruction); Assert.Equal(info1.IsSaveRestoreInstruction, info2.IsSaveRestoreInstruction); Assert.Equal(info1.Encoding, info2.Encoding); Assert.Equal(info1.CpuidFeatures, info2.CpuidFeatures); Assert.Equal(info1.FlowControl, info2.FlowControl); Assert.Equal(info1.Op0Access, info2.Op0Access); Assert.Equal(info1.Op1Access, info2.Op1Access); Assert.Equal(info1.Op2Access, info2.Op2Access); Assert.Equal(info1.Op3Access, info2.Op3Access); Assert.Equal(info1.Op4Access, info2.Op4Access); Assert.Equal(info1.RflagsRead, info2.RflagsRead); Assert.Equal(info1.RflagsWritten, info2.RflagsWritten); Assert.Equal(info1.RflagsCleared, info2.RflagsCleared); Assert.Equal(info1.RflagsSet, info2.RflagsSet); Assert.Equal(info1.RflagsUndefined, info2.RflagsUndefined); Assert.Equal(info1.RflagsModified, info2.RflagsModified); } IEnumerable <UsedRegister> GetUsedRegisters(IEnumerable <UsedRegister> usedRegisterIterator) { var read = new List <Register>(); var write = new List <Register>(); var condRead = new List <Register>(); var condWrite = new List <Register>(); foreach (var info in usedRegisterIterator) { switch (info.Access) { case OpAccess.Read: read.Add(info.Register); break; case OpAccess.CondRead: condRead.Add(info.Register); break; case OpAccess.Write: write.Add(info.Register); break; case OpAccess.CondWrite: condWrite.Add(info.Register); break; case OpAccess.ReadWrite: read.Add(info.Register); write.Add(info.Register); break; case OpAccess.ReadCondWrite: read.Add(info.Register); condWrite.Add(info.Register); break; case OpAccess.None: case OpAccess.NoMemAccess: default: throw new InvalidOperationException(); } } foreach (var reg in GetRegisters(read)) { yield return(new UsedRegister(reg, OpAccess.Read)); } foreach (var reg in GetRegisters(write)) { yield return(new UsedRegister(reg, OpAccess.Write)); } foreach (var reg in GetRegisters(condRead)) { yield return(new UsedRegister(reg, OpAccess.CondRead)); } foreach (var reg in GetRegisters(condWrite)) { yield return(new UsedRegister(reg, OpAccess.CondWrite)); } } IEnumerable <Register> GetRegisters(List <Register> regs) { if (regs.Count <= 1) { return(regs); } regs.Sort(RegisterSorter); var hash = new HashSet <Register>(); int index; foreach (var reg in regs) { if (Register.EAX <= reg && reg <= Register.R15D) { index = reg - Register.EAX; if (hash.Contains(Register.RAX + index)) { continue; } } else if (Register.AX <= reg && reg <= Register.R15W) { index = reg - Register.AX; if (hash.Contains(Register.RAX + index)) { continue; } if (hash.Contains(Register.EAX + index)) { continue; } } else if (Register.AL <= reg && reg <= Register.R15L) { index = reg - Register.AL; if (Register.AH <= reg && reg <= Register.BH) { index -= 4; } if (hash.Contains(Register.RAX + index)) { continue; } if (hash.Contains(Register.EAX + index)) { continue; } if (hash.Contains(Register.AX + index)) { continue; } } else if (Register.YMM0 <= reg && reg <= Register.YMM0 + InstructionInfoConstants.VMM_count - 1) { index = reg - Register.YMM0; if (hash.Contains(Register.ZMM0 + index)) { continue; } } else if (Register.XMM0 <= reg && reg <= Register.XMM0 + InstructionInfoConstants.VMM_count - 1) { index = reg - Register.XMM0; if (hash.Contains(Register.ZMM0 + index)) { continue; } if (hash.Contains(Register.YMM0 + index)) { continue; } } hash.Add(reg); } foreach (var info in lowRegs) { if (hash.Contains(info.rl) && hash.Contains(info.rh)) { hash.Remove(info.rl); hash.Remove(info.rh); hash.Add(info.rx); } } return(hash); }
public StreamCipherException(Code ErrorCode) : base() { this.ErrorCode = ErrorCode; }
/// <summary>Returns the hash code for this instance.</summary> /// <returns>A 32-bit signed integer hash code.</returns> public override int GetHashCode() { return(Code.GetHashCode()); }
void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { using (DataReader dataReader = args.GetDataReader()) { dataReader.ByteOrder = ByteOrder.LittleEndian; while (dataReader.UnconsumedBufferLength != 0) { Code code = (Code)dataReader.ReadInt32(); Packet p; switch (code) { case Code.Connected: { Connected = true; p = null; break; } case Code.Ping: { p = Ping.ConstructPacket(dataReader); break; } case Code.Pong: { p = Pong.ConstructPacket(dataReader); break; } case Code.LevelGenerationData: { p = LevelGenData.ConstructPacket(dataReader); send_buffer.Add(new Acknowledge(p.Code)); break; } case Code.Acknowledge: { p = Acknowledge.ConstructPacket(dataReader); break; } case Code.OtherPlayerCreationData: { p = AddOtherPlayer.ConstructPacket(dataReader); break; } case Code.OtherPlayerID: { p = OtherPlayerID.ConstructPacket(dataReader); break; } case Code.Input: { p = Input.ConstructPacket(dataReader); break; } case Code.EntityXYCorrection: { p = EntityCorrection.ConstructPacket(dataReader); break; } default: p = null; break; } if (p != null) { receive_buffer.Add(p); } else { Debug.WriteLine("Unrecognized packet " + code); break; } } } }
/// <summary> /// Write human readable output. /// </summary> public override void WriteTo(ITextOutput output) { if (Operand is AstVariable && ((AstVariable)Operand).IsGenerated) { if (Code == AstCode.Stloc && InferredType == null) { output.Write(((AstVariable)Operand).Name); output.Write(" = "); Arguments.First().WriteTo(output); return; } if (Code == AstCode.Ldloc) { output.Write(((AstVariable)Operand).Name); if (InferredType != null) { output.Write(':'); InferredType.WriteTo(output, AstNameSyntax.ShortTypeName); if ((ExpectedType != null) && (ExpectedType.FullName != this.InferredType.FullName)) { output.Write("[exp:"); ExpectedType.WriteTo(output, AstNameSyntax.ShortTypeName); output.Write(']'); } } return; } } if (Prefixes != null) { foreach (var prefix in Prefixes) { output.Write(prefix.Code.GetName()); output.Write(". "); } } output.Write(Code.GetName()); if (InferredType != null) { output.Write(':'); InferredType.WriteTo(output, AstNameSyntax.ShortTypeName); if ((ExpectedType != null) && (ExpectedType.FullName != InferredType.FullName)) { output.Write("[exp:"); ExpectedType.WriteTo(output, AstNameSyntax.ShortTypeName); output.Write(']'); } } else if (ExpectedType != null) { output.Write("[exp:"); ExpectedType.WriteTo(output, AstNameSyntax.ShortTypeName); output.Write(']'); } output.Write('('); var first = true; if (Operand != null) { if (Operand is AstLabel) { output.WriteReference(((AstLabel)Operand).Name, Operand); } else if (Operand is AstLabel[]) { var labels = (AstLabel[])Operand; for (var i = 0; i < labels.Length; i++) { if (i > 0) { output.Write(", "); } output.WriteReference(labels[i].Name, labels[i]); } } else if (Operand is AstLabelKeyPair[]) { var pairs = (AstLabelKeyPair[])Operand; for (var i = 0; i < pairs.Length; i++) { if (i > 0) { output.Write(", "); } output.Write("{0} -> ", pairs[i].Key); output.WriteReference(pairs[i].Label.Name, pairs[i].Label); } } else if (Operand is XMethodReference) { var method = (XMethodReference)Operand; if (method.DeclaringType != null) { method.DeclaringType.WriteTo(output, AstNameSyntax.ShortTypeName); output.Write("::"); } output.WriteReference(method.Name, method); } else if (Operand is XFieldReference) { var field = (XFieldReference)Operand; field.DeclaringType.WriteTo(output, AstNameSyntax.ShortTypeName); output.Write("::"); output.WriteReference(field.Name, field); } else { DisassemblerHelpers.WriteOperand(output, Operand); } first = false; } foreach (var arg in Arguments) { if (!first) { output.Write(", "); } arg.WriteTo(output); first = false; } output.Write(')'); }
/// <summary>Initializes a new instance of the <see cref="CompetitionFeaturesAttribute"/> class.</summary> /// <param name="features">The features.</param> protected CompetitionFeaturesAttribute([NotNull] CompetitionFeatures features) { Code.NotNull(features, nameof(features)); _features = new CompetitionFeatures(features); }
/// <summary> /// Initializes a new instance of the <see cref="HResult"/> struct. /// </summary> /// <param name="value">The value of the HRESULT.</param> public HResult(Code value) { this.Value = value; }
public async Task<RegisterClientCommandVm> Handle(RegisterClientCommand request, CancellationToken cancellationToken) { User user = await _context.User .SingleOrDefaultAsync(x => x.PhoneNumber.Equals(request.PhoneNumber) && !x.IsDelete, cancellationToken); if (user == null) { Code gender = await _context.Code .SingleOrDefaultAsync(x => x.CodeGuid == request.GenderGuid, cancellationToken); if (gender == null) { return new RegisterClientCommandVm() { Message = "جنسیت نامعتبر است", State = (int)RegisterContractorState.GenderNotFound }; } City city = await _context.City .SingleOrDefaultAsync(x => x.CityGuid == request.CityGuid, cancellationToken); if (city == null) { return new RegisterClientCommandVm() { Message = "اطلاعات مکانی نامعتبر است", State = (int)RegisterContractorState.CityNotFound }; } //int t = new Random().Next(100000, 999999); const int t = 111111; User newUser = new User { RoleId = (int)Domain.Enums.Role.Client, GenderCodeId = gender.CodeId, FirstName = request.FirstName, LastName = request.LastName, Email = request.Email, PhoneNumber = request.PhoneNumber }; Client client = new Client() { User = newUser, CityId = city.CityId }; Token userToken = new Token { User = newUser, RoleCodeId = 14, Value = t, ExpireDate = DateTime.Now.AddMinutes(2) }; _context.User.Add(newUser); _context.Client.Add(client); _context.Token.Add(userToken); await _context.SaveChangesAsync(cancellationToken); //object smsResult = await _sms.SendServiceable(Domain.Enums.SmsTemplate.VerifyAccount, request.PhoneNumber, t.ToString()); //if (smsResult.GetType().Name != "SendResult") //{ // // sent result //} //else //{ // // sms error //} return new RegisterClientCommandVm() { Message = "عملیات موفق آمیز", State = (int)RegisterClientState.Success }; } else { if (user.IsRegister) { return new RegisterClientCommandVm() { Message = "کاربر مورد نظر در سامانه ثبت شده است", State = (int)RegisterClientState.UserExists }; } Code gender = await _context.Code .SingleOrDefaultAsync(x => x.CodeGuid == request.GenderGuid, cancellationToken); if (gender == null) { return new RegisterClientCommandVm() { Message = "جنسیت نامعتبر است", State = (int)RegisterContractorState.GenderNotFound }; } City city = await _context.City .SingleOrDefaultAsync(x => x.CityGuid == request.CityGuid, cancellationToken); if (city == null) { return new RegisterClientCommandVm() { Message = "اطلاعات مکانی نامعتبر است", State = (int)RegisterClientState.CityNotFound }; } DateTime now = DateTime.Now; user.FirstName = request.FirstName; user.LastName = request.LastName; user.GenderCodeId = gender.CodeId; user.Email = request.Email; user.ModifiedDate = now; Client client = await _context.Client .Where(x => x.UserId == user.UserId && !x.IsDelete) .SingleOrDefaultAsync(cancellationToken); if (client == null) { return new RegisterClientCommandVm() { Message = "کاربر مورد نظر یافت نشد", State = (int)RegisterClientState.ClientNotFound }; } client.CityId = city.CityId; client.ModifiedDate = now; //int t = new Random().Next(100000, 999999); const int t = 111111; Token userToken = new Token { UserId = user.UserId, RoleCodeId = 14, Value = t, ExpireDate = now.AddMinutes(2) }; _context.Token.Add(userToken); await _context.SaveChangesAsync(cancellationToken); //object smsResult = await _sms.SendServiceable(Domain.Enums.SmsTemplate.VerifyAccount, request.PhoneNumber, t.ToString()); //if (smsResult.GetType().Name != "SendResult") //{ // // sent result //} //else //{ // // sms error //} return new RegisterClientCommandVm() { Message = "عملیات موفق آمیز", State = (int)RegisterClientState.Success }; } }
public OpSwitch(Code aOpCode, int aPos, int aNextPos, int[] aBranchLocations, _ExceptionRegionInfo aCurrentExceptionRegion) : base(aOpCode, aPos, aNextPos, aCurrentExceptionRegion) { BranchLocations = aBranchLocations; }
void Test32_DecodeMemOps(string hexBytes, Code code, Register register, Register prefixSeg, Register segReg, Register baseReg, Register indexReg, int scale, uint displ, int displSize, ConstantOffsets constantOffsets, string encodedHexBytes, DecoderOptions options) => DecodeMemOpsBase(32, hexBytes, code, register, prefixSeg, segReg, baseReg, indexReg, scale, displ, displSize, constantOffsets, encodedHexBytes, options);
#pragma warning disable xUnit1026 // Theory methods should use all of their parameters void Test_all_OpCodeInfos(int lineNo, Code code, string opCodeString, string instructionString, OpCodeInfoTestCase tc) { #pragma warning restore xUnit1026 // Theory methods should use all of their parameters var info = tc.Code.ToOpCode(); Assert.Equal(tc.Code, info.Code); #pragma warning disable xUnit2006 // Do not use invalid string equality check // Show the full string without ellipses by using Equal<string>() instead of Equal() Assert.Equal <string>(tc.OpCodeString, info.ToOpCodeString()); Assert.Equal <string>(tc.InstructionString, info.ToInstructionString()); #pragma warning restore xUnit2006 // Do not use invalid string equality check Assert.True((object)info.ToInstructionString() == info.ToString()); Assert.Equal(tc.Encoding, info.Encoding); Assert.Equal(tc.IsInstruction, info.IsInstruction); Assert.Equal(tc.Mode16, info.Mode16); Assert.Equal(tc.Mode32, info.Mode32); Assert.Equal(tc.Mode64, info.Mode64); Assert.Equal(tc.Fwait, info.Fwait); Assert.Equal(tc.OperandSize, info.OperandSize); Assert.Equal(tc.AddressSize, info.AddressSize); Assert.Equal(tc.L, info.L); Assert.Equal(tc.W, info.W); Assert.Equal(tc.IsLIG, info.IsLIG); Assert.Equal(tc.IsWIG, info.IsWIG); Assert.Equal(tc.IsWIG32, info.IsWIG32); Assert.Equal(tc.TupleType, info.TupleType); Assert.Equal(tc.CanBroadcast, info.CanBroadcast); Assert.Equal(tc.CanUseRoundingControl, info.CanUseRoundingControl); Assert.Equal(tc.CanSuppressAllExceptions, info.CanSuppressAllExceptions); Assert.Equal(tc.CanUseOpMaskRegister, info.CanUseOpMaskRegister); Assert.Equal(tc.RequireNonZeroOpMaskRegister, info.RequireNonZeroOpMaskRegister); if (tc.RequireNonZeroOpMaskRegister) { Assert.True(info.CanUseOpMaskRegister); Assert.False(info.CanUseZeroingMasking); } Assert.Equal(tc.CanUseZeroingMasking, info.CanUseZeroingMasking); Assert.Equal(tc.CanUseLockPrefix, info.CanUseLockPrefix); Assert.Equal(tc.CanUseXacquirePrefix, info.CanUseXacquirePrefix); Assert.Equal(tc.CanUseXreleasePrefix, info.CanUseXreleasePrefix); Assert.Equal(tc.CanUseRepPrefix, info.CanUseRepPrefix); Assert.Equal(tc.CanUseRepnePrefix, info.CanUseRepnePrefix); Assert.Equal(tc.CanUseBndPrefix, info.CanUseBndPrefix); Assert.Equal(tc.CanUseHintTakenPrefix, info.CanUseHintTakenPrefix); Assert.Equal(tc.CanUseNotrackPrefix, info.CanUseNotrackPrefix); Assert.Equal(tc.Table, info.Table); Assert.Equal(tc.MandatoryPrefix, info.MandatoryPrefix); Assert.Equal(tc.OpCode, info.OpCode); Assert.Equal(tc.IsGroup, info.IsGroup); Assert.Equal(tc.GroupIndex, info.GroupIndex); Assert.Equal(tc.OpCount, info.OpCount); Assert.Equal(tc.Op0Kind, info.Op0Kind); Assert.Equal(tc.Op1Kind, info.Op1Kind); Assert.Equal(tc.Op2Kind, info.Op2Kind); Assert.Equal(tc.Op3Kind, info.Op3Kind); Assert.Equal(tc.Op4Kind, info.Op4Kind); Assert.Equal(tc.Op0Kind, info.GetOpKind(0)); Assert.Equal(tc.Op1Kind, info.GetOpKind(1)); Assert.Equal(tc.Op2Kind, info.GetOpKind(2)); Assert.Equal(tc.Op3Kind, info.GetOpKind(3)); Assert.Equal(tc.Op4Kind, info.GetOpKind(4)); Assert.Equal(5, Iced.Intel.DecoderConstants.MaxOpCount); for (int i = tc.OpCount; i < Iced.Intel.DecoderConstants.MaxOpCount; i++) { Assert.Equal(OpCodeOperandKind.None, info.GetOpKind(i)); } }
/// <summary> /// Waits for commands to be received and enqueues them in a concurrent queue so that a <see cref="Code"/> /// can decide when to cancel/resume/resolve the execution. /// </summary> /// <returns>Task that represents the lifecycle of the connection</returns> public override async Task Process() { using (await _connections[_mode].LockAsync()) { _connections[_mode].Items.Add(this); } Connection.Logger.Debug("Interception processor registered"); try { do { // Read another code from the interceptor if (await _codeQueue.OutputAvailableAsync(Program.CancelSource.Token)) { Code code = await _codeQueue.TakeAsync(Program.CancelSource.Token); await Connection.Send(code); } else { break; } // Keep processing commands until an action for the code has been received BaseCommand command; do { // Read another command from the IPC connection command = await Connection.ReceiveCommand(); if (Command.SupportedCommands.Contains(command.GetType())) { // Interpret regular Command codes here object result = await command.Invoke(); await Connection.SendResponse(result); } else if (SupportedCommands.Contains(command.GetType())) { // Send other commands to the task intercepting the code await _commandQueue.AddAsync(command); break; } else { // Take care of unsupported commands throw new ArgumentException($"Invalid command {command.Command} (wrong mode?)"); } }while (!Program.CancelSource.IsCancellationRequested); // Stop if the connection has been terminated if (command == null) { break; } }while (!Program.CancelSource.IsCancellationRequested); } catch (SocketException) { // IPC client has closed the connection } finally { _commandQueue.CompleteAdding(); using (await _connections[_mode].LockAsync()) { _connections[_mode].Items.Remove(this); } Connection.Logger.Debug("Interception processor unregistered"); } }
internal void Autoload() { if (Code == null) { return; } Interface.loadMods.SubProgressText = Language.GetTextValue("tModLoader.MSFinishingResourceLoading"); while (AsyncLoadQueue.Count > 0) { AsyncLoadQueue.Dequeue().Wait(); } AutoloadLocalization(); ModSourceBestiaryInfoElement = new GameContent.Bestiary.ModSourceBestiaryInfoElement(this, DisplayName, Assets); IList <Type> modSounds = new List <Type>(); Type modType = GetType(); foreach (Type type in Code.GetTypes().OrderBy(type => type.FullName, StringComparer.InvariantCulture)) { if (type == modType) { continue; } if (type.IsAbstract) { continue; } if (type.ContainsGenericParameters) { continue; } if (type.GetConstructor(new Type[0]) == null) { continue; //don't autoload things with no default constructor } if (type.IsSubclassOf(typeof(ModSound))) { modSounds.Add(type); } else if (typeof(ILoadable).IsAssignableFrom(type)) { var autoload = AutoloadAttribute.GetValue(type); if (autoload.NeedsAutoloading) { AddContent((ILoadable)Activator.CreateInstance(type)); } } } if (Properties.AutoloadGores) { GoreLoader.AutoloadGores(this); } if (Properties.AutoloadSounds) { AutoloadSounds(modSounds); } if (Properties.AutoloadBackgrounds) { AutoloadBackgrounds(); } }
public RuleResult CheckMethod(MethodDefinition method) { if (!method.HasBody) { return(RuleResult.DoesNotApply); } //is there any potential IDisposable-getting opcode in the method? if (!callsAndNewobjBitmask.Intersect(OpCodeEngine.GetBitmask(method))) { return(RuleResult.DoesNotApply); } // we will not report IDiposable locals that are returned from a method bool return_idisposable = DoesReturnDisposable(method); locals.ClearAll(); foreach (Instruction ins in method.Body.Instructions) { Code code = ins.OpCode.Code; switch (code) { case Code.Ret: if (return_idisposable) { CheckForReturn(method, ins.Previous); } continue; case Code.Stind_Ref: CheckForOutParameters(method, ins); continue; default: if (!callsAndNewobjBitmask.Get(code)) { continue; } break; } MethodReference call = (MethodReference)ins.Operand; if (IsDispose(call)) { CheckDisposeCalls(method, ins); continue; } if (call.HasThis && (code != Code.Newobj)) { if (!CheckCallsToOtherInstances(method, ins, call)) { continue; } } if (!DoesReturnDisposable(call)) { continue; } Instruction nextInstruction = ins.Next; if (nextInstruction == null) { continue; } Code nextCode = nextInstruction.OpCode.Code; if (nextCode == Code.Pop || OpCodeBitmask.Calls.Get(nextCode)) { // We ignore setter because it is an obvious share of the IDisposable if (!IsSetter(nextInstruction.Operand as MethodReference)) { ReportCall(method, ins, call); } } else if (nextInstruction.IsStoreLocal()) { // make sure we're not re-assigning over a non-disposed IDisposable CheckReassignment(method, nextInstruction); } } ReportNonDisposedLocals(method); return(Runner.CurrentRuleResult); }
public NewprocessesViewModel() { back = new Command(() => { Ico.getValue <ContentApp>().back(); }); save = new Command(async() => { erour = new List <string>(); if (Name.ToString().Length == 0) { erour.Add("الرجاء كتابة إسم العملية "); } if (Code.ToString().Length != 15) { erour.Add(" كود العملية يجب أن يحتوي على 15 حرف"); } if (Num.ToString().Length == 0) { erour.Add("الرجاء كتابة رقم الثابت للعملية "); } else { string pattern = "[1-9]+/[1-9]+"; Regex rgx = new Regex(pattern); if (!rgx.IsMatch(Num.ToString())) { erour.Add("الرجاء كتابة رقم الثابت بشكل الصحيح ##/## "); } } if (erour.Count == 0) { AcceptSample4Dialog(); await Task.Run(() => { double totalCoast = 0; var p = new process() { Name = Name, date = date, Code = Code, num = Num, NewCost = totalCoast, location = Ico.getValue <IO>().CREATE_F_PRO(Code), edit = true }; Ico.getValue <db>().GetUnivdb().processes.Add(p); Ico.getValue <db>().GetUnivdb().SaveChanges(); CancelSample4Dialog(); }); Ico.getValue <ContentApp>().back(); Ico.getValue <ContentApp>().clear(); } else { OpenSample4Dialog(); Sample4Content = new Messagebox(erour, () => { CancelSample4Dialog(); }); } }); }
/// <summary>获取完整源代码</summary> /// <returns></returns> public String GetFullCode() { if (String.IsNullOrEmpty(Code)) { throw new ArgumentNullException("Code"); } // 预处理代码 var code = Code.Trim(); // 把命名空间提取出来 code = ParseNameSpace(code); // 表达式需要构造一个语句 if (IsExpression) { // 如果代码不含有reutrn关键字,则在最前面加上,因为可能是简单表达式 if (!code.Contains("return ")) { code = "return " + code; } if (!code.EndsWith(";")) { code += ";"; } var sb = new StringBuilder(64 + code.Length); sb.Append("\t\tpublic static Object Eval("); // 参数 var isfirst = false; foreach (var item in Parameters) { if (isfirst) { sb.Append(", "); } else { isfirst = true; } sb.AppendFormat("{0} {1}", item.Value.FullName, item.Key); } sb.AppendLine(")"); sb.AppendLine("\t\t{"); sb.Append("\t\t\t"); sb.AppendLine(code); sb.AppendLine("\t\t}"); code = sb.ToString(); } //else if (!code.Contains("static void Main(")) // 这里也许用正则判断会更好一些 else if (!code.Contains(" Main(") && !code.Contains(" class ")) { // 单行才考虑加分号,多行可能有 #line 指令开头 if (!code.Contains(Environment.NewLine)) { // 如果不是;和}结尾,则增加分号 var last = code[code.Length - 1]; if (last != ';' && last != '}') { code += ";"; } } code = String.Format("\t\tstatic void Main()\r\n\t\t{{\r\n\t\t\t{0}\r\n\t\t}}", code); } // 没有命名空间,包含一个 if (!code.Contains("namespace ")) { // 没有类名,包含一个 if (!code.Contains("class ")) { code = String.Format("\tpublic class {0}\r\n\t{{\r\n{1}\r\n\t}}", GetType().Name, code); } code = String.Format("namespace {0}\r\n{{\r\n{1}\r\n}}", GetType().Namespace, code); } // 命名空间 if (NameSpaces.Count > 0) { var sb = new StringBuilder(code.Length + NameSpaces.Count * 20); foreach (var item in NameSpaces) { sb.AppendFormat("using {0};\r\n", item); } sb.AppendLine(); sb.Append(code); code = sb.ToString(); } return(code); }
public ValidationOutcome(Code code, object value) { this.code = code; this.value = value; }
/// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } if (!string.IsNullOrEmpty(ResourceType)) { writer.WriteString("resourceType", (string)ResourceType !); } ((Fhir.R4.Models.DomainResource) this).SerializeJson(writer, options, false); if ((Category != null) && (Category.Count != 0)) { writer.WritePropertyName("category"); writer.WriteStartArray(); foreach (CodeableConcept valCategory in Category) { valCategory.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (Code != null) { writer.WritePropertyName("code"); Code.SerializeJson(writer, options); } if ((Identifier != null) && (Identifier.Count != 0)) { writer.WritePropertyName("identifier"); writer.WriteStartArray(); foreach (Identifier valIdentifier in Identifier) { valIdentifier.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((PermittedDataType != null) && (PermittedDataType.Count != 0)) { writer.WritePropertyName("permittedDataType"); writer.WriteStartArray(); foreach (string valPermittedDataType in PermittedDataType) { writer.WriteStringValue(valPermittedDataType); } writer.WriteEndArray(); } if ((_PermittedDataType != null) && (_PermittedDataType.Count != 0)) { writer.WritePropertyName("_permittedDataType"); writer.WriteStartArray(); foreach (Element val_PermittedDataType in _PermittedDataType) { val_PermittedDataType.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (MultipleResultsAllowed != null) { writer.WriteBoolean("multipleResultsAllowed", (bool)MultipleResultsAllowed !); } if (Method != null) { writer.WritePropertyName("method"); Method.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(PreferredReportName)) { writer.WriteString("preferredReportName", (string)PreferredReportName !); } if (_PreferredReportName != null) { writer.WritePropertyName("_preferredReportName"); _PreferredReportName.SerializeJson(writer, options); } if (QuantitativeDetails != null) { writer.WritePropertyName("quantitativeDetails"); QuantitativeDetails.SerializeJson(writer, options); } if ((QualifiedInterval != null) && (QualifiedInterval.Count != 0)) { writer.WritePropertyName("qualifiedInterval"); writer.WriteStartArray(); foreach (ObservationDefinitionQualifiedInterval valQualifiedInterval in QualifiedInterval) { valQualifiedInterval.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (ValidCodedValueSet != null) { writer.WritePropertyName("validCodedValueSet"); ValidCodedValueSet.SerializeJson(writer, options); } if (NormalCodedValueSet != null) { writer.WritePropertyName("normalCodedValueSet"); NormalCodedValueSet.SerializeJson(writer, options); } if (AbnormalCodedValueSet != null) { writer.WritePropertyName("abnormalCodedValueSet"); AbnormalCodedValueSet.SerializeJson(writer, options); } if (CriticalCodedValueSet != null) { writer.WritePropertyName("criticalCodedValueSet"); CriticalCodedValueSet.SerializeJson(writer, options); } if (includeStartObject) { writer.WriteEndObject(); } }
protected override ClassTemplate WriteClass(IModelConfiguration configuration, ModelTransferObject model, string nameSpace, List <FileTemplate> files) { ClassTemplate classTemplate = base.WriteClass(configuration, model, nameSpace, files); if (!model.IsAbstract && !model.IsInterface && configuration.Language.IsTypeScript()) { ConstructorTemplate constructor = classTemplate.AddConstructor(); constructor.WithParameter(Code.Generic("Partial", classTemplate.ToType()), "init", Code.Null()) .WithCode(Code.Static(Code.Type("Object")).Method("assign", Code.This(), Code.Local("init")).Close()); if (classTemplate.BasedOn.Any(x => !x.ToType().IsInterface)) { // TODO: Add super parameters constructor.WithSuper(); } } return(classTemplate); }
public static IEqualityComparer <T> GetEqualityComparer([NotNull] params Expression <Func <T, object> >[] membersToCompare) { Code.NotNull(membersToCompare, nameof(membersToCompare)); return(new Comparer(CreateEqualsFunc(membersToCompare), CreateGetHashCodeFunc(membersToCompare))); }
public override int GetHashCode() { return(Code != null ? Code.GetHashCode() : 0); }
protected override void Arrange() { base.Arrange(); base.Act(); Code.Stub(x => x.value).Return("(00)370456789123456789"); }
/// <summary> /// Process a T-code that should be interpreted by the control server /// </summary> /// <param name="code">Code to process</param> /// <returns>Result of the code if the code completed, else null</returns> public static Task <CodeResult> Process(Code code) => Task.FromResult <CodeResult>(null);
private static string Format(Code code) { return(CodeNames.GetName(code).PadRight(15)); }
public Lexer(string compiledCode) { Func currentFunc = null; Block currentBlock = null; int blockNumber = 0; Stack <Block> blockstack = new Stack <Block>(); foreach (string line in compiledCode.Replace(((char)13).ToString(), "").Split('\n')) { if (line.StartsWith(":")) { string op = line.Substring(1); if (currentFunc == null) { currentFunc = new Func(op, Code.buffer.Count); } else { Code.Write(Opcodes.ret); Funcs.Add(currentFunc); currentFunc = new Func(op, Code.buffer.Count); } } else if (line.StartsWith("e:")) { string op = line.Substring(2); if (currentFunc == null) { currentFunc = new Func(op, Code.buffer.Count); } else { Code.Write(Opcodes.ret); Funcs.Add(currentFunc); currentFunc = new Func(op, Code.buffer.Count); } Events.Add(currentFunc); } else if (line.StartsWith(".")) { string name = line.Substring(1); Label l = new Label(name, Code.buffer.Count()); currentFunc.labels.Add(l); } else if (line.StartsWith($"{nameof(Opcodes.pushInt)} ")) { int value = Convert.ToInt32(line.Substring(8)); Code.Write(Opcodes.pushInt); Code.Write(value); _pushVarValue = value.ToString(); } else if (line.StartsWith($"{nameof(Opcodes.pushString)} ")) { string temp = line.Substring(11); string value = temp.Substring(temp.IndexOf("\"") + 1, temp.LastIndexOf("\"") - 1); Code.Write(Opcodes.pushString); Code.Write(value); _pushVarValue = value; } else if (line.StartsWith($"{nameof(Opcodes.pushVar)} ")) { string name = line.Substring(8); Code.Write(Opcodes.pushVar); Code.Write(name); } else if (line.Equals(nameof(Opcodes.pop))) { Code.Write(Opcodes.pop); } else if (line.Equals(nameof(Opcodes.popa))) { Code.Write(Opcodes.popa); } else if (line.StartsWith($"{nameof(Opcodes.decVar)} ")) { string name = line.Substring(7); Code.Write(Opcodes.decVar); Code.Write(name); } else if (line.StartsWith($"{nameof(Opcodes.setGlobalVar)} ")) { string name = line.Substring(13); Code.Write(Opcodes.setGlobalVar); Code.Write(name); if (_pushVarValue != null) { GlobalVars.Add(new Var(name, _pushVarValue)); } } else if (line.StartsWith($"{nameof(Opcodes.setVar)} ")) { string name = line.Substring(7); Code.Write(Opcodes.setVar); Code.Write(name); } else if (line.Equals(nameof(Opcodes.add))) { Code.Write(Opcodes.add); } else if (line.Equals(nameof(Opcodes.sub))) { Code.Write(Opcodes.sub); } else if (line.Equals(nameof(Opcodes.mul))) { Code.Write(Opcodes.mul); } else if (line.Equals(nameof(Opcodes.div))) { Code.Write(Opcodes.div); } else if (line.Equals(nameof(Opcodes.clear))) { Code.Write(Opcodes.clear); } else if (line.StartsWith("if")) { string op = line.Substring(2); if (currentBlock != null) { blockstack.Push(currentBlock); } currentBlock = new IfBlock(blockNumber); if (op.Equals("e")) { Code.Write(Opcodes.ife); } else if (op.Equals("n")) { Code.Write(Opcodes.ifn); } else if (op.Equals("gt")) { Code.Write(Opcodes.ifgt); } else if (op.Equals("gte")) { Code.Write(Opcodes.ifgte); } else if (op.Equals("lt")) { Code.Write(Opcodes.iflt); } else if (op.Equals("lte")) { Code.Write(Opcodes.iflte); } Code.Write(blockNumber); blockNumber++; } else if (line.StartsWith("elseif")) { string op = line.Substring(6); if (currentBlock != null) { blockstack.Push(currentBlock); } currentBlock = new ElseIfBlock(blockNumber); if (op.Equals("e")) { Code.Write(Opcodes.elseife); } else if (op.Equals("n")) { Code.Write(Opcodes.elseifn); } else if (op.Equals("gt")) { Code.Write(Opcodes.elseifgt); } else if (op.Equals("gte")) { Code.Write(Opcodes.elseifgte); } else if (op.Equals("lt")) { Code.Write(Opcodes.elseiflt); } else if (op.Equals("lte")) { Code.Write(Opcodes.elseiflte); } Code.Write(blockNumber); blockNumber++; } else if (line.Equals("else")) { if (currentBlock != null) { blockstack.Push(currentBlock); } currentBlock = new ElseBlock(blockNumber); Code.Write(Opcodes.els); Code.Write(blockNumber); blockNumber++; } else if (line.Equals(nameof(Opcodes.endif))) { Code.Write(Opcodes.endif); currentBlock.endBlock = Code.buffer.Count(); Blocks.Add(currentBlock); if (blockstack.Count > 0) { currentBlock = blockstack.Pop(); } else { currentBlock = null; } } else if (line.StartsWith($"{nameof(Opcodes.call)} ")) { string name = line.Substring(5); Code.Write(Opcodes.call); Code.Write(name); } else if (line.StartsWith("goto ")) { string name = line.Substring(6); Code.Write(Opcodes.got); Code.Write(name); } else if (line.Equals(nameof(Opcodes.print))) { Code.Write(Opcodes.print); } else if (line.Equals(nameof(Opcodes.printLine))) { Code.Write(Opcodes.printLine); } else if (line.Equals(nameof(Opcodes.read))) { Code.Write(Opcodes.read); } else if (line.Equals(nameof(Opcodes.readLine))) { Code.Write(Opcodes.readLine); } else if (line.Equals(nameof(Opcodes.delay))) { Code.Write(Opcodes.delay); } else if (line.Equals(nameof(Opcodes.captureScreen))) { Code.Write(Opcodes.captureScreen); } else if (line.Equals(nameof(Opcodes.getClipboard))) { Code.Write(Opcodes.getClipboard); } else if (line.Equals(nameof(Opcodes.setClipboard))) { Code.Write(Opcodes.setClipboard); } else if (line.Equals(nameof(Opcodes.write))) { Code.Write(Opcodes.write); } else if (line.Equals(nameof(Opcodes.exit))) { Code.Write(Opcodes.exit); } else if (line.StartsWith(nameof(Opcodes.msg))) { Code.Write(Opcodes.msg); } else if (line.Equals(nameof(Opcodes.inputInt32))) { Code.Write(Opcodes.inputInt32); } else if (line.Equals(nameof(Opcodes.inputString))) { Code.Write(Opcodes.inputString); } else if (line.Equals(nameof(Opcodes.ret))) { Code.Write(Opcodes.ret); } } Code.Write(Opcodes.ret); Funcs.Add(currentFunc); }
public CancelConfirmResetView() { InitializeComponent(); Loaded += (sender, args) => Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.3), () => Code.Focus()); }
public bool Equals(Code other) { return(_guid == other?._guid); }
internal void Write_In_Configuration_XML_File(StreamWriter Writer, string Default_BrowseBy) { switch (Browse_Type) { case Item_Aggregation_Child_Visibility_Enum.Metadata_Browse_By: Writer.WriteLine(String.Compare(Default_BrowseBy ?? String.Empty, Code, StringComparison.OrdinalIgnoreCase) == 0 ? " <hi:browse visibility=\"BROWSEBY\" default=\"DEFAULT\">" : " <hi:browse visibility=\"BROWSEBY\">"); break; case Item_Aggregation_Child_Visibility_Enum.None: Writer.WriteLine(" <hi:browse visibility=\"NONE\">"); break; case Item_Aggregation_Child_Visibility_Enum.Main_Menu: Writer.WriteLine(String.IsNullOrEmpty(Parent_Code) ? " <hi:browse visibility=\"MAIN_MENU\">" : " <hi:browse visibility=\"MAIN_MENU\" parent=\"" + Parent_Code + "\">"); break; } // Is this a database option, (usually browse by)? if (Source_Data_Type == Item_Aggregation_Child_Source_Data_Enum.Database_Table) { Writer.WriteLine(" <hi:metadata>" + Code.ToUpper() + "</hi:metadata>"); } else { // Write the code for this static html sourced browse/info Writer.WriteLine(" <hi:code>" + Code.ToLower() + "</hi:code>"); // Include the titles, or just use the code as the title if no titles given Writer.WriteLine(" <hi:titles>"); if ((Label_Dictionary != null) && (Label_Dictionary.Count > 0)) { foreach (KeyValuePair <Web_Language_Enum, string> thisLabel in Label_Dictionary) { if (thisLabel.Key == Web_Language_Enum.DEFAULT) { Writer.WriteLine(" <hi:title>" + thisLabel.Value.Replace("&", "&").Replace("\"", """) + "</hi:title>"); } else { Writer.WriteLine(" <hi:title lang=\"" + Web_Language_Enum_Converter.Enum_To_Code(thisLabel.Key) + "\">" + thisLabel.Value.Replace("&", "&").Replace("\"", """) + "</hi:title>"); } } } else { Writer.WriteLine(" <hi:title>" + Code + "</hi:title>"); } Writer.WriteLine(" </hi:titles>"); // Include the sources as well if ((Source_Dictionary != null) && (Source_Dictionary.Count > 0)) { Writer.WriteLine(" <hi:content>"); foreach (KeyValuePair <Web_Language_Enum, string> thisSource in Source_Dictionary) { if (thisSource.Key == Web_Language_Enum.DEFAULT) { Writer.WriteLine(" <hi:body>" + thisSource.Value.Replace("&", "&").Replace("\"", """) + "</hi:body>"); } else { Writer.WriteLine(" <hi:body lang=\"" + Web_Language_Enum_Converter.Enum_To_Code(thisSource.Key) + "\">" + thisSource.Value.Replace("&", "&").Replace("\"", """) + "</hi:body>"); } } Writer.WriteLine(" </hi:content>"); } } Writer.WriteLine(" </hi:browse>"); }
/// <summary>生成验证码图片 /// </summary> /// <returns></returns> private Bitmap tempImage() { //创建验证码图片对象 Bitmap image = new Bitmap(ImageWidth, ImageHeight); //创建绘布对象 Graphics g = Graphics.FromImage(image); try { Font[] fonts = { new Font(new FontFamily("Impact"), RandomHelper.GetRndNext(FontSize - 2, FontSize), FontStyle.Bold), new Font(new FontFamily("Kokila"), RandomHelper.GetRndNext(FontSize - 3, FontSize), FontStyle.Bold), //new Font(new FontFamily("Bell MT"), RandomHelp.GetRndNext(FontSize - 3, FontSize), FontStyle.Bold), new Font(new FontFamily("MV Boli"), RandomHelper.GetRndNext(FontSize - 3, FontSize), FontStyle.Bold) }; Color[] bgColors = { Color.Snow, Color.White, Color.Linen, Color.FromArgb(242, 251, 246), Color.FromArgb(233, 240, 245), Color.FromArgb(244, 244, 244), Color.FromArgb(255, 228, 188) }; Color[] colors = { Color.FromArgb(24, 1, 58), Color.Red, Color.DarkRed, Color.Black, Color.RoyalBlue, Color.FromArgb(57, 77, 14), Color.FromArgb(85, 72, 64) }; Color bgcolor = bgColors[RandomHelper.GetRndNext(0, bgColors.Length)];//背景色 //生成随机生成器 Random random = new Random(); //清空图片背景色,画上背景干扰线 g.Clear(bgcolor); for (int i = 0; i < NoiseLine; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.FromArgb(random.Next())), x1, y1, x2, y2); } LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), colors[RandomHelper.GetRndNext(0, colors.Length)], colors[RandomHelper.GetRndNext(0, colors.Length)], 1.2f, true); int count = Code.Length; for (int i = 0; i < count; i++) { int x = i * image.Width / count - i * RandomHelper.GetRndNext(2, 4); g.DrawString(Code.Substring(i, 1), fonts[RandomHelper.GetRndNext(0, fonts.Length)], brush, RandomHelper.GetRndNext(-2, 1) + x, RandomHelper.GetRndNext(-3, -1)); } //int count = Code.Length; //for (int i = 0; i < count; i++) //{ // //字体设定 // Font font = new Font("Arial", RandomHelp.GetRndNext(FontSize - 5, FontSize), // (FontStyle.Bold | FontStyle.Italic)); // //创建画笔 // LinearGradientBrush brush = // new LinearGradientBrush( // new Rectangle( 1 + i * 10, 0, image.Width, // image.Height), // Color.Blue, Color.DarkRed, 2.8f, true); // g.DrawString(Code.Substring(i, 1), font, brush, 5, 2); //} //画图片的前景干扰点 for (int i = 0; i < NoisePoint; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //定义干扰线中间点位置 int midX = RandomHelper.GetRndNext(0, image.Width / 2); int midX2 = RandomHelper.GetRndNext(midX, image.Width); //定义画笔 Pen pen = new Pen(colors[RandomHelper.GetRndNext(0, colors.Length)], 2); //画干扰线 g.DrawLine(pen, 0, random.Next(image.Height), midX, random.Next(image.Height)); g.DrawLine(pen, midX, random.Next(image.Height), midX2, random.Next(image.Height)); g.DrawLine(pen, midX2, random.Next(image.Height), image.Width, random.Next(image.Height)); //画多一条干扰线 midX = RandomHelper.GetRndNext(0, image.Width / 2); midX2 = RandomHelper.GetRndNext(midX, image.Width); //定义画笔 pen = new Pen(colors[RandomHelper.GetRndNext(0, colors.Length)], 2); //画干扰线 g.DrawLine(pen, 0, random.Next(image.Height), midX, random.Next(image.Height)); g.DrawLine(pen, midX, random.Next(image.Height), midX2, random.Next(image.Height)); g.DrawLine(pen, midX2, random.Next(image.Height), image.Width, random.Next(image.Height)); //画图片的边框线 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); } catch (Exception) { return(image); } return(image); }
public bool Equals(HttpStatus other) { return(Code.Equals(other.Code)); }