public static void GrownTree() { Pre sol = new Pre(); HappyLittleTrees happy = new HappyLittleTrees(); happy.NewBranch(); happy.GrowTrunk(); happy.GrowBranches(); happy.GrowTrunk(); happy.NewBranch(); happy.NewBranch(); happy.NewBranch(); happy.NewBranch(); happy.GrowBranches(); happy.Ouch(3); happy.GrowTrunk(); happy.GrowTrunk(); happy.NewBranch(); happy.GrowBranches(); Console.WriteLine(happy.Description()); Assert.AreEqual(sol.sol3, happy.Description()); }
public override int Read(byte[] buffer, int offset, int count) { for (int i = 0; i < count; i++) { // Check if we need to download a fragment if (this.currentBufferOffset >= this.currentBuffer.Length) { if (this.isFinalBuffer) { return(i); } HttpResponseMessage response = this.client.DownloadFileFragment( this.itemId, this.currentFragmentOffset, fragmentLength).Result; this.currentBuffer = response.Content.ReadAsByteArrayAsync().Result; this.currentFragmentOffset++; this.currentBufferOffset = 0; var rangeHeader = response.Content.Headers.ContentRange; Pre.Assert(rangeHeader.To != null, "rangeHeader.To != null"); Pre.Assert(rangeHeader.Length != null, "rangeHeader.Length != null"); if (rangeHeader.To.Value == rangeHeader.Length - 1) { this.isFinalBuffer = true; } } buffer[i + offset] = this.currentBuffer[this.currentBufferOffset]; this.currentBufferOffset++; } return(count); }
public static void ApplyChromelessWindowStyle(Window window) { // Attach the window drag handler Grid headerGrid = window.Template.FindName("PART_HeaderGrid", window) as Grid; if (headerGrid != null) { headerGrid.MouseLeftButtonDown += HeaderGridMouseLeftButtonDown; } // Attach the window minimize button handler Button minimizeButton = window.Template.FindName("PART_MinimizeWindowButton", window) as Button; if (minimizeButton != null) { minimizeButton.Click += MinimizeButtonOnClick; } IResizableWindow resizableWindow = window as IResizableWindow; if (resizableWindow != null) { // Attach the window resize event handlers // TODO: Should we look at ResizeMode to determine whether or not to hide these? string[] resizeAreaNames = { "TopLeft", "Top", "TopRight", "Left", "Right", "BottomLeft", "Bottom", "BottomRight" }; foreach (string areaName in resizeAreaNames) { Rectangle resizeRectangle = window.Template.FindName("PART_Resize" + areaName, window) as Rectangle; Pre.Assert(resizeRectangle != null, "resizeRectangle != null"); resizeRectangle.MouseEnter += resizableWindow.DisplayResizeCursor; resizeRectangle.MouseLeave += resizableWindow.ResetCursor; resizeRectangle.PreviewMouseDown += resizableWindow.Resize; } } }
public void FixCasing(List <string> namesEtc, bool changeNameCases, bool makeUppercaseAfterBreak, bool checkLastLine, string lastLine) { var replaceIds = new List <string>(); var replaceNames = new List <string>(); var originalNames = new List <string>(); ReplaceNames1Remove(namesEtc, replaceIds, replaceNames, originalNames); if (checkLastLine) { string s = HtmlUtil.RemoveHtmlTags(lastLine).TrimEnd().TrimEnd('\"').TrimEnd(); bool startWithUppercase = string.IsNullOrEmpty(s) || s.EndsWith('.') || s.EndsWith('!') || s.EndsWith('?') || s.EndsWith(". ♪", StringComparison.Ordinal) || s.EndsWith("! ♪", StringComparison.Ordinal) || s.EndsWith("? ♪", StringComparison.Ordinal) || s.EndsWith(']') || s.EndsWith(')') || s.EndsWith(':'); // start with uppercase after music symbol - but only if next line does not start with music symbol if (!startWithUppercase && (s.EndsWith('♪') || s.EndsWith('♫'))) { if (!Pre.Contains(new[] { '♪', '♫' })) { startWithUppercase = true; } } if (startWithUppercase && StrippedText.Length > 0 && !Pre.Contains("...")) { StrippedText = char.ToUpper(StrippedText[0]) + StrippedText.Substring(1); } } if (makeUppercaseAfterBreak && StrippedText.Contains(ExpectedCharsArray)) { const string breakAfterChars = @".!?:;)]}([{"; const string ExpectedChars = "\"`´'()<>!?.- \r\n"; var sb = new StringBuilder(); bool lastWasBreak = false; for (int i = 0; i < StrippedText.Length; i++) { var s = StrippedText[i]; if (lastWasBreak) { if (ExpectedChars.Contains(s)) { sb.Append(s); } else if ((sb.EndsWith('<') || sb.ToString().EndsWith("</", StringComparison.Ordinal)) && i + 1 < StrippedText.Length && StrippedText[i + 1] == '>') { // tags sb.Append(s); } else if (sb.EndsWith('<') && s == '/' && i + 2 < StrippedText.Length && StrippedText[i + 2] == '>') { // tags sb.Append(s); } else if (sb.ToString().EndsWith("... ", StringComparison.Ordinal)) { sb.Append(s); lastWasBreak = false; } else { if (breakAfterChars.Contains(s)) { sb.Append(s); } else { lastWasBreak = false; sb.Append(char.ToUpper(s)); } } } else { sb.Append(s); if (breakAfterChars.Contains(s)) { var idx = sb.ToString().IndexOf('['); if (s == ']' && idx > 1) { // I [Motor roaring] love you! string temp = sb.ToString(0, idx - 1).Trim(); if (temp.Length > 0 && !Utilities.LowercaseLetters.Contains(temp[temp.Length - 1])) { lastWasBreak = true; } } else { lastWasBreak = true; } } } } StrippedText = sb.ToString(); } if (changeNameCases) { ReplaceNames2Fix(replaceIds, replaceNames); } else { ReplaceNames2Fix(replaceIds, originalNames); } }
// Test pre-conditions and raise an error if incorrect. protected void Preconditions(Pre flags) { // The object must never be closed. if(isClosed) { Raise(VsaError.EngineClosed); } if(flags == Pre.EngineNotClosed) { return; } // Test the various conditions. if((flags & Pre.SupportForDebug) != Pre.None) { if(!isDebugInfoSupported) { Raise(VsaError.DebugInfoNotSupported); } } if((flags & Pre.EngineCompiled) != Pre.None) { if(!haveCompiledState) { Raise(VsaError.EngineNotCompiled); } } if((flags & Pre.EngineRunning) != Pre.None) { if(!isEngineRunning) { Raise(VsaError.EngineNotRunning); } } if((flags & Pre.EngineNotRunning) != Pre.None) { if(isEngineRunning) { Raise(VsaError.EngineRunning); } } if((flags & Pre.RootMonikerSet) != Pre.None) { if(engineMoniker == String.Empty) { Raise(VsaError.RootMonikerNotSet); } } if((flags & Pre.RootMonikerNotSet) != Pre.None) { if(engineMoniker != String.Empty) { Raise(VsaError.RootMonikerAlreadySet); } } if((flags & Pre.RootNamespaceSet) != Pre.None) { if(rootNamespace == String.Empty) { Raise(VsaError.RootNamespaceNotSet); } } if((flags & Pre.SiteSet) != Pre.None) { if(engineSite == null) { Raise(VsaError.SiteNotSet); } } if((flags & Pre.SiteNotSet) != Pre.None) { if(engineSite != null) { Raise(VsaError.SiteAlreadySet); } } if((flags & Pre.EngineInitialized) != Pre.None) { if(!isEngineInitialized) { Raise(VsaError.EngineNotInitialized); } } if((flags & Pre.EngineNotInitialized) != Pre.None) { if(isEngineInitialized) { Raise(VsaError.EngineInitialized); } } }
private static void Menus() { Br = MainMenu.AddMenu("Brand", "Brand"); // Pre = Br.AddSubMenu("Prediction"); Pre.AddLabel("Predictions"); Pre.Add("Qp", new Slider("Prediction [Q]", 75, 1)); Pre.Add("Wp", new Slider("Prediction [W]", 50, 1)); // Comb = Br.AddSubMenu("Combo"); Comb.Add("Qc", new CheckBox("Use [Q]")); Comb.Add("Wc", new CheckBox("Use [W]")); Comb.Add("Ec", new CheckBox("Use [E]")); Comb.AddSeparator(); Comb.AddLabel("Settings [R] Combo"); Comb.Add("Rc", new CheckBox("Use [R]")); Comb.Add("En", new Slider("Max Range Radiun Enemys > %", 2, 1, 5)); Comb.Add("stack", new CheckBox("Use Stack Passive", false)); // Hara = Br.AddSubMenu("AutoHarass"); Hara.Add("AutoW", new CheckBox("Use Auto[W]")); Hara.AddSeparator(); Hara.AddLabel("Mana Percent"); Hara.Add("Mana", new Slider("Mana Percent Auto [W] > %", 50, 1)); // FullCombo = Br.AddSubMenu("FullCombo"); FullCombo.Add("Eb", new CheckBox("Use FullCombo")); // Lane = Br.AddSubMenu("LaneClear"); Lane.Add("Ql", new CheckBox("Use [Q] Lane", false)); Lane.Add("Wl", new CheckBox("Use [W] Lane")); Lane.Add("El", new CheckBox("Use [E] Lane")); Lane.AddSeparator(); Lane.AddLabel("Mana Percent"); Lane.Add("manal", new Slider("Mana Percent > %", 50, 1)); Lane.AddSeparator(); Lane.AddLabel("Minion Percent"); Lane.Add("Wmin", new Slider("Minion Percent > %", 3, 1, 6)); // Jungle = Br.AddSubMenu("JungleClear"); Jungle.Add("Qj", new CheckBox("Use [Q]")); Jungle.Add("Wj", new CheckBox("Use [W]")); Jungle.Add("Ej", new CheckBox("Use [E]")); Jungle.AddSeparator(); Jungle.AddLabel("Mana Percent"); Jungle.Add("manaj", new Slider("Mana Percent > %", 50, 1)); // Misc = Br.AddSubMenu("Misc"); Misc.Add("In", new CheckBox("Use Interrupt")); Misc.Add("Gap", new CheckBox("Use GapClose")); // KillSteal = Br.AddSubMenu("KillSteal"); KillSteal.Add("KsQ", new CheckBox("Use [Q] KS")); KillSteal.Add("KsW", new CheckBox("Use [W] KS")); KillSteal.Add("KsE", new CheckBox("Use [E] KS")); KillSteal.Add("KsR", new CheckBox("Use [R] KS")); // Draws = Br.AddSubMenu("Draws"); Draws.Add("DQ", new CheckBox("Use Draw [Q]")); Draws.Add("DW", new CheckBox("Use Draw [W]")); Draws.Add("DE", new CheckBox("Use Draw [E]")); Draws.Add("DR", new CheckBox("Use Draw [R]")); }
private bool IsCondition(Pre flag, Pre test){ return ((flag & test) != Pre.None); }
/// <summary> /// Called from <c>CodeLock.UnlockWithCode(BaseEntity.RPCMessage)</c> /// </summary> public static void On_DoorCodeEntered(CodeLock codeLock, BaseEntity.RPCMessage rpc) { if (!codeLock.IsLocked()) return; string code = rpc.read.String(); Pre<DoorCodeEvent> preDoorCodeEvent = new Pre<DoorCodeEvent>(codeLock, rpc.player, code); OnNext("Pre_DoorCodeEntered", preDoorCodeEvent); if (preDoorCodeEvent.IsCanceled || (!preDoorCodeEvent.Event.IsCorrect() && !preDoorCodeEvent.Event.ForceAllow)) { Effect.server.Run(codeLock.effectDenied.resourcePath, codeLock, 0u, Vector3.zero, Vector3.forward); rpc.player.Hurt(1f, global::Rust.DamageType.ElectricShock, codeLock, true); return; } Effect.server.Run(codeLock.effectUnlocked.resourcePath, codeLock, 0u, Vector3.zero, Vector3.forward); codeLock.SetFlag(BaseEntity.Flags.Locked, false); codeLock.SendNetworkUpdate(BasePlayer.NetworkQueue.Update); List<ulong> whitelist = new List<ulong>(); whitelist = (List<ulong>) codeLock.GetFieldValue("whitelistPlayers"); if (!whitelist.Contains(rpc.player.userID)) { whitelist.Add(rpc.player.userID); codeLock.SetFieldValue("whitelistPlayers", whitelist); } OnNext("On_DoorCodeEntered", preDoorCodeEvent.Event); }
/// <summary> /// Called from <c>BuildingBlock.DoUpgradeToGrade(BaseEntity.RPCMessage)</c> . /// </summary> public static void On_BuildingUpgrade(BuildingBlock block, BaseEntity.RPCMessage msg) { BasePlayer messagePlayer = msg.player; BuildingGrade.Enum buildingGrade = (BuildingGrade.Enum) msg.read.Int32(); ConstructionGrade constructionGrade = (ConstructionGrade) block.CallMethod("GetGrade", buildingGrade); Pre<BuildingUpgradeEvent> preBuildingUpgradeEvent = new Pre<BuildingUpgradeEvent>(block, buildingGrade, messagePlayer); OnNext("Pre_BuildingUpgrade", preBuildingUpgradeEvent); if (preBuildingUpgradeEvent.IsCanceled) return; if (constructionGrade == null) return; if ((bool) block.CallMethod("CanChangeToGrade", buildingGrade, messagePlayer) == false) return; if ((bool)block.CallMethod("CanAffordUpgrade", buildingGrade, messagePlayer) == false) return; block.CallMethod("PayForUpgrade", constructionGrade, messagePlayer); block.SetGrade(buildingGrade); block.SetHealthToMax(); block.CallMethod("StartBeingRotatable"); block.SendNetworkUpdate(BasePlayer.NetworkQueue.Update); block.UpdateSkin(false); Effect.server.Run("assets/bundled/prefabs/fx/build/promote_" + buildingGrade.ToString().ToLower() + ".prefab", block, 0u, Vector3.zero, Vector3.zero); OnNext("On_BuildingUpgrade", preBuildingUpgradeEvent.Event); }
/// <summary> /// Called from <c>BaseMelee.CLProject(BaseEntity.RPCMessage)</c> . /// </summary> public static void On_PlayerThrowWeapon(BaseMelee baseMelee, BaseEntity.RPCMessage msg) { BasePlayer messagePlayer = msg.player; if ((bool) baseMelee.CallMethod("VerifyClientAttack", messagePlayer) == false) { baseMelee.SendNetworkUpdate(BasePlayer.NetworkQueue.Update); return; } if (!baseMelee.canThrowAsProjectile){ Debug.LogWarning(messagePlayer + " fired invalid projectile: Not throwable"); return; } Item item = baseMelee.GetItem(); if (item == null) { Debug.LogWarning(messagePlayer + " fired invalid projectile: Item not found"); return; } ItemModProjectile component = item.info.GetComponent<ItemModProjectile>(); if (component == null) { Debug.LogWarning(messagePlayer + " fired invalid projectile: Item mod not found"); return; } ProjectileShoot projectileShoot = ProjectileShoot.Deserialize(msg.read); if (projectileShoot.projectiles.Count != 1){ Debug.LogWarning(messagePlayer + " fired invalid projectile: Projectile count mismatch"); return; } messagePlayer.CleanupExpiredProjectiles(); foreach (ProjectileShoot.Projectile current in projectileShoot.projectiles) { if (messagePlayer.HasFiredProjectile(current.projectileID)) { Debug.LogWarning(messagePlayer + " fired invalid projectile: Duplicate ID ->" + current.projectileID); } else { Pre<WeaponThrowEvent> preWeaponThrowEvent = new Pre<WeaponThrowEvent>(baseMelee, messagePlayer, projectileShoot, current); OnNext("Pre_PlayerThrowWeapon", preWeaponThrowEvent); if (preWeaponThrowEvent.IsCanceled == false) { messagePlayer.NoteFiredProjectile(current.projectileID, current.startPos, current.startVel, baseMelee, item.info, item); Effect effect = new Effect(); effect.Init(Effect.Type.Projectile, current.startPos, current.startVel.normalized, msg.connection); effect.scale = preWeaponThrowEvent.Event.Magnitude; effect.pooledString = component.projectileObject.resourcePath; effect.number = current.seed; EffectNetwork.Send(effect); OnNext("On_PlayerThrowWeapon", preWeaponThrowEvent.Event); } } } item.SetParent(null); }
private void InitializeWindowSource(object sender, EventArgs e) { this.hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource; Pre.Assert(this.hwndSource != null, "this.hwndSource != null"); }
public void BasicSyncLocalToOneDrive() { if (!GlobalTestSettings.RunNetworkTests) { Assert.Inconclusive(GlobalTestSettings.NetworkTestsDisabledMessage); } string testRootPath = Path.Combine(this.TestContext.TestLogsDir, this.TestContext.TestName); Directory.CreateDirectory(testRootPath); string syncSourcePath = Path.Combine(testRootPath, "Source"); Directory.CreateDirectory(syncSourcePath); // Create temp files/folders List <string> syncFileList = new List <string> { TestHelper.CreateDirectory(syncSourcePath, "dir1"), TestHelper.CreateFile(syncSourcePath, "dir1\\file1.txt"), TestHelper.CreateFile(syncSourcePath, "dir1\\file2.txt"), TestHelper.CreateFile(syncSourcePath, "dir1\\file3.txt"), TestHelper.CreateDirectory(syncSourcePath, "dir2"), TestHelper.CreateFile(syncSourcePath, "dir2\\file1.txt"), TestHelper.CreateFile(syncSourcePath, "dir2\\file2.txt"), TestHelper.CreateFile(syncSourcePath, "dir2\\file3.txt") }; TokenResponse currentToken = GetCurrentToken(); Guid remoteTestFolderName = Guid.NewGuid(); Item remoteTestFolder = CreateOneDriveTestDirectory(currentToken, remoteTestFolderName.ToString("D")).Result; SyncRelationship newRelationship = SetupRelationship(testRootPath, syncSourcePath, remoteTestFolder); AnalyzeJob analyzeJob = new AnalyzeJob(newRelationship); analyzeJob.ContinuationJob = new SyncJob(newRelationship, analyzeJob.AnalyzeResult) { TriggerType = SyncTriggerType.Manual }; analyzeJob.Start(); SyncJob syncJob = (SyncJob)analyzeJob.WaitForCompletion(); Assert.IsTrue(syncJob.HasFinished); Assert.AreEqual(syncFileList.Count, syncJob.AnalyzeResult.AdapterResults.SelectMany(r => r.Value.EntryResults).Count()); OneDriveAdapter oneDriveAdapter = newRelationship.Adapters.First(a => !a.Configuration.IsOriginator) as OneDriveAdapter; OneDriveClient client = new OneDriveClient(GetCurrentToken()); foreach (string syncFile in syncFileList.Where(f => f.EndsWith(".txt"))) { string localPath = Path.Combine(syncSourcePath, syncFile); using (var sha1 = new SHA1Managed()) { byte[] content = File.ReadAllBytes(localPath); byte[] localFileHash = sha1.ComputeHash(content); EntryUpdateInfo entryResult; using (var db = newRelationship.GetDatabase()) { entryResult = syncJob.AnalyzeResult.AdapterResults.SelectMany(r => r.Value.EntryResults).FirstOrDefault( r => r.Entry.GetRelativePath(db, "\\") == syncFile); } Assert.IsNotNull(entryResult); byte[] databaseHash = entryResult.Entry.OriginalSha1Hash; Assert.AreEqual( TestHelper.HashToHex(localFileHash), TestHelper.HashToHex(databaseHash), "Local file hash does not match database hash."); Pre.Assert(oneDriveAdapter != null, "oneDriveAdapter != null"); var adapterEntry = entryResult.Entry.AdapterEntries.First(e => e.AdapterId == oneDriveAdapter.Configuration.Id); string itemId = adapterEntry.AdapterEntryId; var item = client.GetItemByItemIdAsync(itemId); var oneDriveHash = "0x" + item.Result.File.Hashes.Sha1Hash; Assert.AreEqual( TestHelper.HashToHex(localFileHash), oneDriveHash, "Local file hash does not match OneDrive hash."); } } }
internal static string UniqueIdToItemId(byte[] uniqueId) { Pre.ThrowIfArgumentNull(uniqueId, nameof(uniqueId)); return(Encoding.ASCII.GetString(uniqueId)); }
public static Pre <THelper> SetScrollable <THelper>(this Pre <THelper> pre, bool scrollable = true) where THelper : BootstrapHelper <THelper> { return(pre.ToggleCss(Css.PreScrollable, scrollable)); }
internal static byte[] ItemIdToUniqueId(string itemId) { Pre.ThrowIfStringNullOrWhiteSpace(itemId, nameof(itemId)); return(Encoding.ASCII.GetBytes(itemId)); }
// Test pre-conditions and raise an error if incorrect. protected void Preconditions(Pre flags) { // The object must never be closed. if (isClosed) { Raise(VsaError.EngineClosed); } if (flags == Pre.EngineNotClosed) { return; } // Test the various conditions. if ((flags & Pre.SupportForDebug) != Pre.None) { if (!isDebugInfoSupported) { Raise(VsaError.DebugInfoNotSupported); } } if ((flags & Pre.EngineCompiled) != Pre.None) { if (!haveCompiledState) { Raise(VsaError.EngineNotCompiled); } } if ((flags & Pre.EngineRunning) != Pre.None) { if (!isEngineRunning) { Raise(VsaError.EngineNotRunning); } } if ((flags & Pre.EngineNotRunning) != Pre.None) { if (isEngineRunning) { Raise(VsaError.EngineRunning); } } if ((flags & Pre.RootMonikerSet) != Pre.None) { if (engineMoniker == String.Empty) { Raise(VsaError.RootMonikerNotSet); } } if ((flags & Pre.RootMonikerNotSet) != Pre.None) { if (engineMoniker != String.Empty) { Raise(VsaError.RootMonikerAlreadySet); } } if ((flags & Pre.RootNamespaceSet) != Pre.None) { if (rootNamespace == String.Empty) { Raise(VsaError.RootNamespaceNotSet); } } if ((flags & Pre.SiteSet) != Pre.None) { if (engineSite == null) { Raise(VsaError.SiteNotSet); } } if ((flags & Pre.SiteNotSet) != Pre.None) { if (engineSite != null) { Raise(VsaError.SiteAlreadySet); } } if ((flags & Pre.EngineInitialized) != Pre.None) { if (!isEngineInitialized) { Raise(VsaError.EngineNotInitialized); } } if ((flags & Pre.EngineNotInitialized) != Pre.None) { if (isEngineInitialized) { Raise(VsaError.EngineInitialized); } } }
public override void UpdateItem(EntryUpdateInfo updateInfo, SyncEntryChangedFlags changeFlags) { string fullPath, newFullPath = null; using (var database = this.Relationship.GetDatabase()) { fullPath = Path.Combine(this.Config.RootDirectory, updateInfo.Entry.GetRelativePath(database, this.PathSeparator)); if (!string.IsNullOrWhiteSpace(updateInfo.PathNew)) { newFullPath = Path.Combine(this.Config.RootDirectory, updateInfo.PathNew); } } FileSystemInfo fileSystemInfo = GetFileSystemInfo(fullPath, updateInfo.Entry.Type); if ((changeFlags & SyncEntryChangedFlags.CreatedTimestamp) != 0) { Pre.Assert(updateInfo.CreationDateTimeUtcNew != null, "updateInfo.CreationDateTimeUtcNew != null"); // Write the new created timestamp to the file/folder fileSystemInfo.CreationTimeUtc = updateInfo.CreationDateTimeUtcNew.Value; // Update the SyncEntry to record that this is now the "current" value of CreationDateTimeUtcNew updateInfo.Entry.CreationDateTimeUtc = updateInfo.CreationDateTimeUtcNew.Value; } if ((changeFlags & SyncEntryChangedFlags.ModifiedTimestamp) != 0) { Pre.Assert(updateInfo.ModifiedDateTimeUtcNew != null, "updateInfo.ModifiedDateTimeUtcNew != null"); // Write the new modified timestamp to the file/folder fileSystemInfo.LastWriteTimeUtc = updateInfo.ModifiedDateTimeUtcNew.Value; // Update the SyncEntry to record that this is now the "current" value of ModifiedDateTimeUtcNew updateInfo.Entry.ModifiedDateTimeUtc = updateInfo.ModifiedDateTimeUtcNew.Value; } if ((changeFlags & SyncEntryChangedFlags.Renamed) != 0 || (changeFlags & SyncEntryChangedFlags.Moved) != 0) { if (updateInfo.Entry.Type == SyncEntryType.File) { Pre.Assert(!string.IsNullOrEmpty(newFullPath), "newFullPath != null"); File.Move(fullPath, newFullPath); } else if (updateInfo.Entry.Type == SyncEntryType.Directory) { Pre.Assert(!string.IsNullOrEmpty(newFullPath), "newFullPath != null"); Directory.Move(fullPath, newFullPath); } else { throw new NotImplementedException(); } if ((changeFlags & SyncEntryChangedFlags.Renamed) != 0) { updateInfo.Entry.Name = PathUtility.GetSegment(updateInfo.PathNew, -1); } if ((changeFlags & SyncEntryChangedFlags.Moved) != 0) { updateInfo.Entry.ParentId = updateInfo.ParentIdNew; } } }
public void Set(int x, int y, float value) { Pre.Assert(x >= 0 && x < _shapeX, x, _shapeX); Pre.Assert(y >= 0 && y < _shapeY, y, _shapeY); _buffer[x + y * _shapeX] = value; }
public void SyncException() { var testWrapper = TestWrapperFactory .CreateLocalToLocal(this.TestContext) .SaveRelationship() .CreateBasicSourceStructure(); // First sync job testWrapper .CreateSyncJob() .RunToCompletion() .VerifySyncSuccess() .VerifyResultContainsAllFiles() .VerifyDatabaseHashes(); Logger.Info("Logging database before delete:"); using (var db = testWrapper.Relationship.GetDatabase()) { TestHelper.LogConfiguration(testWrapper.Relationship.Configuration); TestHelper.LogDatabase(db); } // Create a new file string relativePath = TestHelper.CreateFile( testWrapper.SourceAdapter.Config.RootDirectory, "dir1\\file4.txt"); string filePath = Path.Combine( testWrapper.SourceAdapter.Config.RootDirectory, relativePath); // Run an analyze path to detect the file var analyzeResult = testWrapper .CreateAnalyzeJob() .RunToCompletion() .GetAnalyzeResult(); // Change the permissions of the file FileSecurity fileSecurity = File.GetAccessControl(filePath); if (fileSecurity == null) { throw new Exception("Failed to create file security"); } SecurityIdentifier currentUser = WindowsIdentity.GetCurrent().User; Pre.Assert(currentUser != null, "currentUser != null"); // Create a new rule denying ready access to the current user FileSystemAccessRule newRule = new FileSystemAccessRule( currentUser, FileSystemRights.Read, AccessControlType.Deny); fileSecurity.AddAccessRule(newRule); File.SetAccessControl(filePath, fileSecurity); // Second sync job var syncRun = testWrapper .CreateSyncJob(analyzeResult) .RunToCompletion() .VerifySyncFailed(); var syncAnalyzeResult = syncRun.GetAnalyzeResult(); var entryResult = syncAnalyzeResult.AdapterResults.First().Value.EntryResults[0]; Assert.AreEqual("file4.txt", entryResult.Entry.Name); Assert.IsTrue(!string.IsNullOrWhiteSpace(entryResult.ErrorMessage)); }
/// <summary> /// Called from <c>MedicalTool.UseOther(BaseEntity.RPCMessage)</c> . /// </summary> public static void On_PlayerSyringeOther(MedicalTool medicalTool, BaseEntity.RPCMessage msg) { BasePlayer messagePlayer = msg.player; if (messagePlayer.CanInteract() == false) return; if ((bool)medicalTool.CallMethod("HasItemAmount") == false || medicalTool.canUseOnOther == false) return; BasePlayer owner = medicalTool.GetOwnerPlayer(); if (owner == null) return; BasePlayer target = BaseNetworkable.serverEntities.Find(msg.read.UInt32()) as BasePlayer; if (target != null && Vector3.Distance(target.transform.position, owner.transform.position) < 4f) { var preSyringeUseEvent = new Pre<SyringeUseEvent>(medicalTool, owner, target); OnNext("Pre_PlayerSyringeOther", preSyringeUseEvent); if (preSyringeUseEvent.IsCanceled == false) { medicalTool.ClientRPCPlayer(null, messagePlayer, "Reset"); medicalTool.CallMethod("GiveEffectsTo", target); medicalTool.CallMethod("UseItemAmount", 1); OnNext("On_PlayerSyringeOther", preSyringeUseEvent.Event); } } }
private void Form1_Load(object sender, EventArgs e) { // ایجاد یک شی از کلاس دیتا بیس کانتکست DatabaseContext oDatabaseContext = null; //try //{ //نیو کردن دیتا بیس کانتکست oDatabaseContext = new DatabaseContext(); //ایجاد یک شی از کلاس کانتری Course oCourse = null; oCourse = new Course() { CourseID = 1100, CourseName = "ادبیات", Unit = 2, TypeID = 1 }; //oCourse.CourseID = 1100; //oCourse.CourseName = "ادبیات"; //oCourse.Unit = 2; //oCourse.TypeID = 1; oDatabaseContext.Course.Add(oCourse); oCourse = new Course() { CourseID = 1105, CourseName = "تربیت بدنی", Unit = 1, TypeID = 2 }; oDatabaseContext.Course.Add(oCourse); oCourse = new Course() { CourseID = 1400, CourseName = "برنامه سازی ۱", Unit = 3, TypeID = 1 }; oDatabaseContext.Course.Add(oCourse); oCourse = new Course() { CourseID = 1401, CourseName = "ساختمان داده ها", Unit = 3, TypeID = 1 }; oDatabaseContext.Course.Add(oCourse); oCourse = new Course() { CourseID = 1402, CourseName = "برنامه سازی ۲", Unit = 3, TypeID = 1 }; oDatabaseContext.Course.Add(oCourse); oCourse = new Course() { CourseID = 1403, CourseName = "بازیابی و ذخیره", Unit = 3, TypeID = 1 }; oDatabaseContext.Course.Add(oCourse); oCourse = new Course() { CourseID = 1407, CourseName = "پایگاه داده ها", Unit = 3, TypeID = 1 }; oDatabaseContext.Course.Add(oCourse); oCourse = new Course() { CourseID = 1500, CourseName = "ریاضی 1", Unit = 3, TypeID = 1 }; oDatabaseContext.Course.Add(oCourse); oCourse = new Course() { CourseID = 1600, CourseName = "زبان پیش نیاز", Unit = 2, TypeID = 1 }; oDatabaseContext.Course.Add(oCourse); // ------------------------ CF oCf = null; oCf = new CF { CourseID = 1100, FieldID = 1, Kind = (int)KindType.O }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1100, FieldID = 2, Kind = (int)KindType.O }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1100, FieldID = 3, Kind = (int)KindType.O }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1105, FieldID = 1, Kind = (int)KindType.O }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1105, FieldID = 2, Kind = (int)KindType.O }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1105, FieldID = 3, Kind = (int)KindType.O }; oDatabaseContext.CF.Add(oCf); //oCf = new CF //{ // CourseID = 1100, // FieldID = 1, // Kind = (int)KindType.O //}; //oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1400, FieldID = 1, Kind = (int)KindType.T }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1400, FieldID = 2, Kind = (int)KindType.E }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1400, FieldID = 3, Kind = (int)KindType.E }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1402, FieldID = 1, Kind = (int)KindType.T }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1403, FieldID = 1, Kind = (int)KindType.T }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1407, FieldID = 1, Kind = (int)KindType.T }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1500, FieldID = 1, Kind = (int)KindType.p }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1500, FieldID = 2, Kind = (int)KindType.p }; oDatabaseContext.CF.Add(oCf); oCf = new CF { CourseID = 1500, FieldID = 3, Kind = (int)KindType.p }; oDatabaseContext.CF.Add(oCf); // ----------------------------------- Field oField = null; oField = new Field() { FieldID = 1, FieldName = "مهندسی کامپیوتر" }; oDatabaseContext.Field.Add(oField); oField = new Field() { FieldID = 2, FieldName = "مهندسی الکترونیک" }; oDatabaseContext.Field.Add(oField); oField = new Field() { FieldID = 3, FieldName = "ریاضی محض" }; oDatabaseContext.Field.Add(oField); // --------------------------------------- TypeU oType = null; oType = new TypeU() { TypeID = 1, TypeName = "نطری", Fee = 5000 }; oDatabaseContext.TypeU.Add(oType); oType = new TypeU() { TypeID = 2, TypeName = "عملی", Fee = 20000 }; oDatabaseContext.TypeU.Add(oType); oType = new TypeU() { TypeID = 3, TypeName = "آزمایشگاه", Fee = 30000 }; oDatabaseContext.TypeU.Add(oType); // -------------------------------------------------- Tution oTution = null; oTution = new Tution() { FieldID = 1, StartYear = 80, ConstTtion = 75000 }; oDatabaseContext.Tution.Add(oTution); oTution = new Tution() { FieldID = 1, StartYear = 81, ConstTtion = 80000 }; oDatabaseContext.Tution.Add(oTution); oTution = new Tution() { FieldID = 1, StartYear = 82, ConstTtion = 90000 }; oDatabaseContext.Tution.Add(oTution); oTution = new Tution() { FieldID = 2, StartYear = 81, ConstTtion = 80000 }; oDatabaseContext.Tution.Add(oTution); oTution = new Tution() { FieldID = 2, StartYear = 82, ConstTtion = 90000 }; oDatabaseContext.Tution.Add(oTution); oTution = new Tution() { FieldID = 3, StartYear = 82, ConstTtion = 75000 }; oDatabaseContext.Tution.Add(oTution); //------------------------------- Student oStudent = null; oStudent = new Student() { StudentID = 8001, StudentName = "آرش راد", StartYear = 80, FieldID = 1 }; oDatabaseContext.Student.Add(oStudent); oStudent = new Student() { StudentID = 8002, StudentName = "عسل شاملو", StartYear = 80, FieldID = 3 }; oDatabaseContext.Student.Add(oStudent); oStudent = new Student() { StudentID = 8003, StudentName = "سیاوش آزاد", StartYear = 80, FieldID = 1 }; oDatabaseContext.Student.Add(oStudent); oStudent = new Student() { StudentID = 8101, StudentName = "ساغر راد", StartYear = 81, FieldID = 1 }; oDatabaseContext.Student.Add(oStudent); oStudent = new Student() { StudentID = 8102, StudentName = "علی نیکی", StartYear = 81, FieldID = 1 }; oDatabaseContext.Student.Add(oStudent); oStudent = new Student() { StudentID = 8111, StudentName = "فرامرز نیکی", StartYear = 81, FieldID = 1 }; oDatabaseContext.Student.Add(oStudent); oStudent = new Student() { StudentID = 8112, StudentName = "علی رضایی", StartYear = 81, FieldID = 2 }; oDatabaseContext.Student.Add(oStudent); // ----------------------- Pre oPre = null; oPre = new Pre() { CourseID = 1400, PreID = 1500 }; oDatabaseContext.Pre.Add(oPre); oPre = new Pre() { CourseID = 1402, PreID = 1400 }; oDatabaseContext.Pre.Add(oPre); oPre = new Pre() { CourseID = 1407, PreID = 1402 }; oDatabaseContext.Pre.Add(oPre); oPre = new Pre() { CourseID = 1407, PreID = 1403 }; oDatabaseContext.Pre.Add(oPre); // ------------------------------------------ G oG = null; oG = new G() { StudentID = 8001, CourseID = 1400, Term = 811, Grade = 9 }; oDatabaseContext.G.Add(oG); oG = new G() { StudentID = 8001, CourseID = 1400, Term = 812, Grade = 13 }; oDatabaseContext.G.Add(oG); oG = new G() { StudentID = 8001, CourseID = 1401, Term = 811, Grade = 13 }; oDatabaseContext.G.Add(oG); oG = new G() { StudentID = 8101, CourseID = 1400, Term = 821, Grade = 19 }; oDatabaseContext.G.Add(oG); oG = new G() { StudentID = 8101, CourseID = 1500, Term = 821, Grade = 14 }; oDatabaseContext.G.Add(oG); oG = new G() { StudentID = 8111, CourseID = 1400, Term = 811, Grade = 12 }; oDatabaseContext.G.Add(oG); oG = new G() { StudentID = 8111, CourseID = 1401, Term = 811, Grade = 20 }; oDatabaseContext.G.Add(oG); //----------------------------------------------- Prof oProf = null; oProf = new Prof() { ProfID = 101, ProfName = "فرانک شایسته", Degree = (int)MyDegree.l }; oDatabaseContext.Prof.Add(oProf); oProf = new Prof() { ProfID = 102, ProfName = "علی پیامی", Degree = (int)MyDegree.f }; oDatabaseContext.Prof.Add(oProf); oProf = new Prof() { ProfID = 106, ProfName = "آزاده نیکوکار", Degree = (int)MyDegree.f }; oDatabaseContext.Prof.Add(oProf); oProf = new Prof() { ProfID = 107, ProfName = "سیامک فرزانه", Degree = (int)MyDegree.d }; oDatabaseContext.Prof.Add(oProf); oProf = new Prof() { ProfID = 108, ProfName = "علی نادر نژاد", Degree = (int)MyDegree.f }; oDatabaseContext.Prof.Add(oProf); //---------------------------------------------- PC oPc = null; oPc = new PC() { ProfID = 101, CourseID = 1400, Term = 801 }; oDatabaseContext.PC.Add(oPc); oPc = new PC() { ProfID = 101, CourseID = 1400, Term = 802 }; oDatabaseContext.PC.Add(oPc); oPc = new PC() { ProfID = 101, CourseID = 1402, Term = 801 }; oDatabaseContext.PC.Add(oPc); oPc = new PC() { ProfID = 102, CourseID = 1400, Term = 801 }; oDatabaseContext.PC.Add(oPc); oPc = new PC() { ProfID = 108, CourseID = 1500, Term = 811 }; oDatabaseContext.PC.Add(oPc); oPc = new PC() { ProfID = 101, CourseID = 1400, Term = 811 }; oDatabaseContext.PC.Add(oPc); // --------------------------------------------- //ایجاد بانک اطلاعاتی در دیتا بیس oDatabaseContext.SaveChanges(); //} //catch (System.Exception ex) //{ // System.Windows.Forms.MessageBox.Show(ex.Message); //} //finally //{ //اگر دیتابیس کانتکست نال نبود آنرا نال میکنیم if (oDatabaseContext != null) { oDatabaseContext.Dispose(); oDatabaseContext = null; } //} }
/// <summary> /// Called from <c>ConnectionAuth.Approve(Connection)</c> . /// </summary> public static void On_ClientAuth(ConnectionAuth ca, Connection connection) { var ae = new Pre<AuthEvent>(connection); OnNext("Pre_ClientAuth", ae); if (!ae.IsCanceled) OnNext("On_ClientAuth", ae.Event); ConnectionAuth.m_AuthConnection.Remove(connection); if (!ae.Event.Approved) { ConnectionAuth.Reject(connection, ae.Event.Reason); return; } SingletonComponent<ServerMgr>.Instance.ConnectionApproved(connection); }
public override IEnumerable <IAdapterItem> GetAdapterItems(IAdapterItem folder) { // When querying items in the root of the container, folder will have a name of '{containerName}', and when // querying items in a folder other than the root, folder will have a have a name of // '{containerName}/{folder}'. We will need to reformat this in order to property query storage. string prefix = null; // Start by triming off the container name from the front of the folder name string relName = folder.FullName.Substring(this.TypedConfiguration.ContainerName.Length); // If the folder name is empty, then we are querying the container, so leave the prefix empty. if (!string.IsNullOrWhiteSpace(relName)) { prefix = relName; // Add a '/' character to the end of the folder name if needed if (!prefix.EndsWith(this.PathSeparator)) { prefix += this.PathSeparator; } // Ensure that the folder name does NOT start with a '/'. prefix = prefix.TrimStart('/'); } ConfiguredTaskAwaitable <IList <ContainerItem> > listBlobsTask = this.storageClient.ListBlobsAsync( this.TypedConfiguration.ContainerName, this.PathSeparator, prefix) .ConfigureAwait(false); IList <ContainerItem> result = listBlobsTask.GetAwaiter().GetResult(); foreach (ContainerItem item in result) { // The item name returned by storage has the prefix at the beginning of the name, which // we will need to trim off string itemName = prefix != null?item.Name.Substring(prefix.Length) : item.Name; string fullPath = string.Format("{0}/{1}", folder.FullName, itemName); string computedId = GetUniqueIdForFile(fullPath); BlobPrefix blobPrefix = item as BlobPrefix; if (blobPrefix != null) { // Azure returns the blob prefix with a '/' character on the end. We need to trim this off // prior to returning it to the caller. yield return(new AzureStorageAdapterItem( itemName.TrimEnd('/'), folder, this, SyncAdapterItemType.Directory, computedId, 0, DateTime.Now, DateTime.Now)); continue; } Blob blob = item as Blob; Pre.Assert(blob != null, "blob != null"); yield return(new AzureStorageAdapterItem( itemName, folder, this, SyncAdapterItemType.File, computedId, blob.Length, blob.Created, blob.LastModified)); } }
/// <summary> /// Called from <c>Landmine.Trigger(BasePlayer)</c> /// </summary> public static void On_LandmineTriggered(Landmine landmine, BasePlayer basePlayer) { Pre<LandmineTriggerEvent> preLandmineTriggerEvent = new Pre<LandmineTriggerEvent>(landmine, basePlayer); OnNext("Pre_LandmineTriggered", preLandmineTriggerEvent); if (preLandmineTriggerEvent.IsCanceled == false) { if (basePlayer != null) { landmine.SetFieldValue("triggerPlayerID", basePlayer.userID); } landmine.SetFlag(BaseEntity.Flags.Open, true); landmine.SendNetworkUpdate(BasePlayer.NetworkQueue.Update); OnNext("On_LandmineTriggered", preLandmineTriggerEvent.Event); } }
public override string ToString() { return(Pre.ToString() + ".pop"); }
/// <summary> /// Called from <c>Door.RPC_OpenDoor(BaseEntity.RPCMessage)</c> and <c>Door.RPC_CloseDoor(BaseEntity.RPCMessage)</c> . /// </summary> public static void On_DoorUse(Door door, BaseEntity.RPCMessage msg, bool open) { if ((open && door.IsOpen()) || (!open && !door.IsOpen())) return; var preDoorUseEvent = new Pre<DoorUseEvent>(door, msg, open); OnNext("Pre_DoorUse", preDoorUseEvent); if (preDoorUseEvent.IsCanceled) { if (preDoorUseEvent.Event.DenyReason != "") msg.player.SendConsoleCommand("chat.add", 0, String.Format("{0}: {1}", Server.server_message_name.ColorText("fa5"), preDoorUseEvent.Event.DenyReason)); return; } bool doAction = true; BaseLock baseLock = door.GetSlot(BaseEntity.Slot.Lock) as BaseLock; if (baseLock != null && preDoorUseEvent.Event.IgnoreLock == false) { doAction = open ? baseLock.OnTryToOpen(msg.player) : baseLock.OnTryToClose(msg.player); if (doAction && open && (baseLock.IsLocked() && Time.realtimeSinceStartup - (float)door.GetFieldValue("decayResetTimeLast") > 60)) { Decay.RadialDecayTouch(door.transform.position, 40, 270532608); door.SetFieldValue("decayResetTimeLast", Time.realtimeSinceStartup); } } if (doAction) { door.SetFlag(BaseEntity.Flags.Open, open); door.SendNetworkUpdateImmediate(false); door.CallMethod("UpdateDoorAnimationParameters", false); OnNext("On_DoorUse", preDoorUseEvent.Event); } }
public override string ToString() { return(Pre.ToString() + ".{loc" + _localIndex + "}"); }
// The Preconditions method tests a set of preconditions and throws the // appropriate VsaException if any of them do not hold. // Pre.EngineNotClosed is always tested, regardless of whether or not it // appears in the flags bitfield (including when only Pre.None is indicated). protected void Preconditions(Pre flags){ // Every operation on this object requires that the engine not be closed if (this.isClosed) throw Error(VsaError.EngineClosed); if (flags == (Pre.EngineNotClosed | Pre.None)) return; if (IsCondition(flags, Pre.SupportForDebug) && !this.isDebugInfoSupported) throw Error(VsaError.DebugInfoNotSupported); if (IsCondition(flags, Pre.EngineCompiled) && !this.haveCompiledState) throw Error(VsaError.EngineNotCompiled); if (IsCondition(flags, Pre.EngineRunning) && !this.isEngineRunning) throw Error(VsaError.EngineNotRunning); if (IsCondition(flags, Pre.EngineNotRunning) && this.isEngineRunning) throw Error(VsaError.EngineRunning); if (IsCondition(flags, Pre.RootMonikerSet) && (this.engineMoniker == "")) throw Error(VsaError.RootMonikerNotSet); if (IsCondition(flags, Pre.RootMonikerNotSet) && (this.engineMoniker != "")) throw Error(VsaError.RootMonikerAlreadySet); if (IsCondition(flags, Pre.RootNamespaceSet) && (this.rootNamespace == "")) throw Error(VsaError.RootNamespaceNotSet); if (IsCondition(flags, Pre.SiteSet) && (this.engineSite == null)) throw Error(VsaError.SiteNotSet); if (IsCondition(flags, Pre.SiteNotSet) && (this.engineSite != null)) throw Error(VsaError.SiteAlreadySet); if (IsCondition(flags, Pre.EngineInitialised) && !this.isEngineInitialized) throw Error(VsaError.EngineNotInitialized); if (IsCondition(flags, Pre.EngineNotInitialised) && this.isEngineInitialized) throw Error(VsaError.EngineInitialized); }
public override string ToString() { return(Pre.ToString() + ".{arg" + _argIndex + "}"); }
public void FixCasing(List <string> namesEtc, bool changeNameCases, bool makeUppercaseAfterBreak, bool checkLastLine, string lastLine) { var replaceIds = new List <string>(); var replaceNames = new List <string>(); var originalNames = new List <string>(); ReplaceNames1Remove(namesEtc, replaceIds, replaceNames, originalNames); if (checkLastLine) { string s = Utilities.RemoveHtmlTags(lastLine).TrimEnd().TrimEnd('\"').TrimEnd(); bool startWithUppercase = string.IsNullOrEmpty(s) || s.EndsWith('.') || s.EndsWith('!') || s.EndsWith('?') || s.EndsWith(". ♪", StringComparison.Ordinal) || s.EndsWith("! ♪", StringComparison.Ordinal) || s.EndsWith("? ♪", StringComparison.Ordinal) || s.EndsWith(']') || s.EndsWith(')') || s.EndsWith(':'); // start with uppercase after music symbol - but only if next line does not start with music symbol if (!startWithUppercase && (s.EndsWith('♪') || s.EndsWith('♫'))) { if (!Pre.Contains("♪") && !Pre.Contains("♫")) { startWithUppercase = true; } } if (startWithUppercase && StrippedText.Length > 0 && !Pre.Contains("...")) { StrippedText = StrippedText.Remove(0, 1).Insert(0, StrippedText[0].ToString().ToUpper()); } } if (makeUppercaseAfterBreak && (StrippedText.Contains(".") || StrippedText.Contains("!") || StrippedText.Contains("?") || StrippedText.Contains(":") || StrippedText.Contains(";") || StrippedText.Contains(")") || StrippedText.Contains("]") || StrippedText.Contains("}") || StrippedText.Contains("(") || StrippedText.Contains("[") || StrippedText.Contains("{"))) { var sb = new StringBuilder(); bool lastWasBreak = false; for (int i = 0; i < StrippedText.Length; i++) { string s = StrippedText[i].ToString(); if (lastWasBreak) { if (("\"`´'()<>!?.- " + Environment.NewLine).Contains(s)) { sb.Append(s); } else if ((sb.ToString().EndsWith('<') || sb.ToString().EndsWith("</", StringComparison.Ordinal)) && i + 1 < StrippedText.Length && StrippedText[i + 1] == '>') { // tags sb.Append(s); } else if (sb.ToString().EndsWith('<') && s == "/" && i + 2 < StrippedText.Length && StrippedText[i + 2] == '>') { // tags sb.Append(s); } else if (sb.ToString().EndsWith("... ", StringComparison.Ordinal)) { sb.Append(s); lastWasBreak = false; } else { if (".!?:;)]}([{".Contains(s)) { sb.Append(s); } else { lastWasBreak = false; sb.Append(s.ToUpper()); } } } else { sb.Append(s); if (".!?:;)]}([{".Contains(s)) { if (s == "]" && sb.ToString().IndexOf('[') > 1) { // I [Motor roaring] love you! string temp = sb.ToString().Substring(0, sb.ToString().IndexOf('[') - 1).Trim(); if (temp.Length > 0 && !Utilities.LowercaseLetters.Contains(temp[temp.Length - 1].ToString())) { lastWasBreak = true; } } else { lastWasBreak = true; } } } } StrippedText = sb.ToString(); } if (changeNameCases) { ReplaceNames2Fix(replaceIds, replaceNames); } else { ReplaceNames2Fix(replaceIds, originalNames); } }
protected void Preconditions(Pre flags) { if (this.isClosed) { throw this.Error(JSVsaError.EngineClosed); } if (flags != Pre.EngineNotClosed) { if (this.IsCondition(flags, Pre.SupportForDebug) && !this.isDebugInfoSupported) { throw this.Error(JSVsaError.DebugInfoNotSupported); } if (this.IsCondition(flags, Pre.EngineCompiled) && !this.haveCompiledState) { throw this.Error(JSVsaError.EngineNotCompiled); } if (this.IsCondition(flags, Pre.EngineRunning) && !this.isEngineRunning) { throw this.Error(JSVsaError.EngineNotRunning); } if (this.IsCondition(flags, Pre.EngineNotRunning) && this.isEngineRunning) { throw this.Error(JSVsaError.EngineRunning); } if (this.IsCondition(flags, Pre.RootMonikerSet) && (this.engineMoniker == "")) { throw this.Error(JSVsaError.RootMonikerNotSet); } if (this.IsCondition(flags, Pre.RootMonikerNotSet) && (this.engineMoniker != "")) { throw this.Error(JSVsaError.RootMonikerAlreadySet); } if (this.IsCondition(flags, Pre.RootNamespaceSet) && (this.rootNamespace == "")) { throw this.Error(JSVsaError.RootNamespaceNotSet); } if (this.IsCondition(flags, Pre.SiteSet) && (this.engineSite == null)) { throw this.Error(JSVsaError.SiteNotSet); } if (this.IsCondition(flags, Pre.SiteNotSet) && (this.engineSite != null)) { throw this.Error(JSVsaError.SiteAlreadySet); } if (this.IsCondition(flags, Pre.EngineInitialised) && !this.isEngineInitialized) { throw this.Error(JSVsaError.EngineNotInitialized); } if (this.IsCondition(flags, Pre.EngineNotInitialised) && this.isEngineInitialized) { throw this.Error(JSVsaError.EngineInitialized); } } }
public void FixCasing(List <string> nameList, bool changeNameCases, bool makeUppercaseAfterBreak, bool checkLastLine, string lastLine, double millisecondsFromLast = 0) { var replaceIds = new List <string>(); var replaceNames = new List <string>(); var originalNames = new List <string>(); ReplaceNames1Remove(nameList, replaceIds, replaceNames, originalNames); if (checkLastLine && ShouldStartWithUpperCase(lastLine, millisecondsFromLast)) { if (StrippedText.StartsWith("_@", StringComparison.Ordinal)) { for (int i = 0; i < replaceIds.Count; i++) { string id = $"_@{i}_"; if (StrippedText.StartsWith(id, StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(originalNames[i])) { originalNames[i] = originalNames[i].CapitalizeFirstLetter(); } break; } } } else { StrippedText = StrippedText.CapitalizeFirstLetter(); } } if (makeUppercaseAfterBreak && StrippedText.Contains(ExpectedCharsArray)) { const string breakAfterChars = @".!?:;)]}([{"; const string expectedChars = "\"“`´'()<>!?.- \r\n"; var sb = new StringBuilder(StrippedText.Length); bool lastWasBreak = false; for (int i = 0; i < StrippedText.Length; i++) { var s = StrippedText[i]; if (lastWasBreak) { if (expectedChars.Contains(s)) { sb.Append(s); } else if ((sb.EndsWith('<') || sb.ToString().EndsWith("</", StringComparison.Ordinal)) && i + 1 < StrippedText.Length && StrippedText[i + 1] == '>') { // tags sb.Append(s); } else if (sb.EndsWith('<') && s == '/' && i + 2 < StrippedText.Length && StrippedText[i + 2] == '>') { // tags sb.Append(s); } else if (sb.ToString().EndsWith("... ", StringComparison.Ordinal)) { sb.Append(s); lastWasBreak = false; } else { if (breakAfterChars.Contains(s)) { sb.Append(s); } else { lastWasBreak = false; sb.Append(char.ToUpper(s)); if (StrippedText.Substring(i).StartsWith("_@", StringComparison.Ordinal)) { var ks = StrippedText.Substring(i); for (int k = 0; k < replaceIds.Count; k++) { string id = $"_@{k}_"; if (ks.StartsWith(id, StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(originalNames[k])) { originalNames[k] = char.ToUpper(originalNames[k][0]) + originalNames[k].Remove(0, 1); } break; } } } } } } else { sb.Append(s); if (breakAfterChars.Contains(s)) { var idx = sb.ToString().IndexOf('['); if (s == ']' && idx > 1) { // I [Motor roaring] love you! string temp = sb.ToString(0, idx - 1).Trim(); if (temp.Length > 0 && !char.IsLetterOrDigit(temp[temp.Length - 1])) { lastWasBreak = true; } } else if (s == ']' && idx == -1 && Pre.Contains('[')) { // [ Motor roaring ] Hallo! lastWasBreak = true; } else if (s == ':') // seems to be the rule (in subtitles) to nearly always capitalize first letter efter semicolon { lastWasBreak = true; } else { idx = sb.ToString().LastIndexOf(' '); if (idx >= 0 && idx < sb.Length - 2 && !IsInMiddleOfUrl(i - idx, StrippedText.Substring(idx + 1))) { lastWasBreak = true; } else if (StrippedText.Length > i + 1 && " \r\n".Contains(StrippedText[i + 1])) { lastWasBreak = true; } } } else if (s == '-' && Pre.Contains('-')) { if (sb.ToString().EndsWith(Environment.NewLine + "-")) { var prevLine = HtmlUtil.RemoveHtmlTags(sb.ToString().Substring(0, sb.Length - 2).TrimEnd()); if (prevLine.EndsWith('.') || prevLine.EndsWith('!') || prevLine.EndsWith('?') || prevLine.EndsWith(". ♪", StringComparison.Ordinal) || prevLine.EndsWith("! ♪", StringComparison.Ordinal) || prevLine.EndsWith("? ♪", StringComparison.Ordinal) || prevLine.EndsWith(']') || prevLine.EndsWith(')') || prevLine.EndsWith(':')) { lastWasBreak = true; } } } } } StrippedText = sb.ToString(); } ReplaceNames2Fix(replaceIds, changeNameCases ? replaceNames : originalNames); }
private bool IsCondition(Pre flag, Pre test) { return((flag & test) != Pre.None); }
protected override void ProcessRecord() { var control = new Text { Value = Value, Color = Color, BgColor = BgColor, Border = Border, BorderWidth = BorderWidth, BorderColor = BorderColor, BorderRadius = BorderRadius, BorderLeft = BorderLeft, BorderRight = BorderRight, BorderTop = BorderTop, BorderBottom = BorderBottom, }; SetControlProps(control); if (Markdown.IsPresent) { control.Markdown = Markdown.ToBool(); } if (Bold.IsPresent) { control.Bold = Bold.ToBool(); } if (Italic.IsPresent) { control.Italic = Italic.ToBool(); } if (Pre.IsPresent) { control.Pre = Pre.ToBool(); } if (Nowrap.IsPresent) { control.Nowrap = Nowrap.ToBool(); } if (Block.IsPresent) { control.Block = Block.ToBool(); } if (Align.HasValue) { control.Align = Align.Value; } if (VerticalAlign.HasValue) { control.VerticalAlign = VerticalAlign.Value; } if (Size.HasValue) { control.Size = Size.Value; } if (BorderStyle.HasValue) { control.BorderStyle = BorderStyle.Value; } WriteObject(control); }
public override ConsoleControl FindControlByAddress(string address) { if (Fader.Address == address) { return(Fader); } else if (Mute.Address == address) { return(Mute); } else if (Link.Address == address) { return(Link); } else if (Pan.Address == address) { return(Pan); } else if (MonoSend.Address == address) { return(MonoSend); } else if (MonoFader.Address == address) { return(MonoFader); } else if (Eq.Address == address) { return(Eq); } else { ConsoleControl c; c = Comp.FindControlByAddress(address); if (c == null) { c = Insert.FindControlByAddress(address); if (c == null) { c = Gate.FindControlByAddress(address); if (c == null) { c = Pre.FindControlByAddress(address); if (c == null) { c = null; // Delay.FindControlByAddress(address); if (c == null) { c = Config.FindControlByAddress(address); if (c == null) { c = Dca.FindControlByAddress(address); if (c == null) { } else { return(c); } } else { return(Config.FindControlByAddress(address)); } } else { return(c); } } else { return(c); } } else { return(c); } } else { return(c); } } else { return(c); } } foreach (var Buss in MixBuss) { if (Buss.Address == address) { return(Buss); } } return(null); }
private static void Prefix(ref GameTime gameTime) { Pre?.Invoke(); }
/// <summary> /// Called from <c>MedicalTool.UseSelf(BaseEntity.RPCMessage)</c> . /// </summary> public static void On_PlayerSyringeSelf(MedicalTool medicalTool, BaseEntity.RPCMessage msg) { BasePlayer messagePlayer = msg.player; if (messagePlayer.CanInteract() == false) return; if ((bool)medicalTool.CallMethod("HasItemAmount") == false) return; BasePlayer owner = medicalTool.GetOwnerPlayer(); var preSyringeUseEvent = new Pre<SyringeUseEvent>(medicalTool, owner, owner); OnNext("Pre_PlayerSyringeSelf", preSyringeUseEvent); if (preSyringeUseEvent.IsCanceled == false) { medicalTool.ClientRPCPlayer(null, messagePlayer, "Reset"); medicalTool.CallMethod("GiveEffectsTo", owner); medicalTool.CallMethod("UseItemAmount", 1); OnNext("On_PlayerSyringeSelf", preSyringeUseEvent.Event); } }
public float Get(int x, int y) { Pre.Assert(x >= 0 && x < _shapeX, x, _shapeX); Pre.Assert(y >= 0 && y < _shapeY, y, _shapeY); return(_buffer[x + y * _shapeX]); }
protected JobBase(SyncRelationship relationship) { Pre.ThrowIfArgumentNull(relationship, "relationship"); this.Relationship = relationship; }