public void Manage_Newlines() { var dict = new StringDictionary { { "temp", "temporary" } }; var replacer = new Replacer(dict); Assert.That(replacer.Replace("$temp$\r\nword"), Is.EqualTo("temporary\r\nword")); }
static void Main(string[] args) { if (args.Length < 1) { help(); return; } if (args[0] == "--patch") { patch_file(args); return; } String path = args[0]; String mode = args.Length > 1 ? args[1] : null; Match m; String file_content; parse_version_file_content(path, out file_content, out m); //set mode to DEFAULT MODE if mode is not specified as command line param if (mode == null) { if (m.Groups.Count >= 3) { mode = m.Groups[3].Captures[0].ToString(); } } //replace version according mode Regex r_replace = new Regex("\\d+\\.\\d+\\.\\d+\\.\\d+"); Replacer replacer = new Replacer(mode); System.Diagnostics.Debug.Assert(m != null); file_content = r_replace.Replace(file_content, new MatchEvaluator(replacer.Replace)); //save results SaveStringToFile(file_content, path, "utf-8"); }
public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); if (Core.EJ) { Replacer.Replace(this, new Grapeshot()); } }
public void TestExplicitExpression() { Expression<Func<IQueryable<int>, IQueryable<int>>> ex = ints => ints.OrderBy(i => i).Where(i => i > 10).Select(i => i); var e2 = new Replacer().Convert(ex); var func = e2.Compile(); var x = func.Invoke(new[] { 1, 5, 10, 15, 25, 20 }); Assert.That(x, Is.EqualTo(new[] { 15, 20, 25 })); }
public override int runCommand(XdmNode node) { Replacer rp = new Replacer(match, replace, source, target, ignorecase); if (rp.isValid) { EventContext.instance.replacers.Add(rp); } return(0); }
public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); if (Core.EJ) { Replacer.Replace(this, new FrostCannonball()); } }
public void TransformStrings() { Replacer replacer = new Replacer(); replacer.Add("<br/>", "\n"); replacer.Add("z", "."); Assert.That(replacer.TransformForward("zz<br/>zz"), Is.EqualTo("..\n..")); Assert.That(replacer.TransformBackward("..\n.."), Is.EqualTo("zz<br/>zz")); }
public void TransformChars() { Replacer replacer = new Replacer(); replacer.Add("a", "z"); replacer.Add("b", "y"); Assert.That(replacer.TransformForward("ababtr"), Is.EqualTo("zyzytr")); Assert.That(replacer.TransformBackward("zyzytr"), Is.EqualTo("ababtr")); }
public static void Shuffle() { for (int i = 0; i < 8; i++) { if (i != 4 && i == 0) { List <string> npccoords = new List <string>(ExportList(0)); List <string> npccoordlines = new List <string>(ExportList(0)); npccoords.Shuffle(); foreach (GODFile file in Files.onfoot) { Replacer.ReplaceRCF("onfoot.rcf", file.start, Replacer.ReplaceInstances(file, npccoords, npccoordlines), file.length); } } else if (i != 4) { List <string> npccoords = new List <string>(ExportList(i)); List <string> npccoordlines = new List <string>(ExportList(i)); npccoords.Shuffle(); List <GODFile> temp = new List <GODFile>(); switch (i) { case (1): temp = Files.onfoot1; break; case (2): temp = Files.onfoot2; break; case (3): temp = Files.onfoot3; break; case (5): temp = Files.onfoot5; break; case (6): temp = Files.onfoot6; break; } foreach (GODFile file in temp) { Replacer.ReplaceRCF("onfoot" + i + ".rcf", file.start, Replacer.ReplaceInstances(file, npccoords, npccoordlines), file.length); } } } }
public void CheckForWord_PhraseContainsWord_True() { // Arrange string phrase = "Hello world", word = "world", replacement = "Haru"; Replacer newReplacer = new Replacer(phrase, word, replacement); // Act bool wordExists = newReplacer.CheckForWord(); // Assert Assert.AreEqual(true, wordExists); }
public void TestImplicitExpression() { var q = new[] { 1, 2, 3 }.AsQueryable(); var ex = q.OrderBy(i => i).Where(i => i > 2).Select(i => i).Expression; var newParam = Expression.Constant(new[] { 6, 4, 5, }); var newBody = new Replacer().Convert(q.Expression, newParam, ex); var result = Expression.Lambda(newBody).Compile().DynamicInvoke(); Assert.That(result, Is.EqualTo(new[] { 4, 5, 6 })); }
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (pguidCmdGroup == ReplaceCommandSet && nCmdID == ReplaceCommandId) { //this.textView.TextBuffer.Insert(0, "// Invoked from legacy command filter\r\n"); Replacer.ReplaceSelectedLines(this.textView, contextProvider.EditorOperations.GetEditorOperations(this.textView)); return(VSConstants.S_OK); } return(NextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut)); }
public void IsReplaceable_OnNonReplaceableString_ShouldReturnTrue() { // Arrange var replacer = new Replacer(); // Act var res = replacer.IsReplaceable("pale", "bae"); // Assert Assert.IsFalse(res); }
public static Expression?Replace(LambdaExpression?expression, ParameterExpression parameter) { if (expression == null) { return(null); } var visitor = new Replacer(expression.Parameters[0], parameter); return(visitor.Visit(expression.Body)); }
public void ReplaceWord_ReplacementWordReplacesWordInPhrase_String() { // Arrange string phrase = "Hello world", word = "world", replacement = "Haru"; Replacer newReplacer = new Replacer(phrase, word, replacement); // Act string updatedPhrase = newReplacer.ReplaceWord(); // Assert Assert.AreEqual(true, updatedPhrase); }
public void Replacer_WithNoSpace_ShouldReturnSameString() { // Arrange var replacer = new Replacer(); // Act var res = replacer.ReplaceSpace("testnospace"); // Assert Assert.AreEqual("testnospace", res); }
public void ParseFile_WhenCalled_ReturnsNumberOfEntries(string path, string find, string replace, int expected) { // Arrange Replacer replacer = new Replacer(path, find, replace); // Act int actual = replacer.ParseFile(); // Assert Assert.AreEqual(expected, actual); }
public void Test_Two_Words() { var dict = new StringDictionary { { "greeting", "Watch out!" }, { "name", "John Doe" } }; var replacer = new Replacer(dict); Assert.That(replacer.Replace("$greeting$ here comes $name$"), Is.EqualTo("Watch out! here comes John Doe")); }
public void SetReplacesExistingEntry() { Replacer map = new Replacer(); map.Add("a", "b"); map.Add("a", "c"); Assert.That(map.Map.Count, Is.EqualTo(1)); Assert.That(map.Map[0].Original, Is.EqualTo("a")); Assert.That(map.Map[0].Modified, Is.EqualTo("c")); }
public void SetAddsCharToMap() { Replacer map = new Replacer(); Assert.That(map.Map.Count, Is.EqualTo(0)); map.Add("a", "b"); Assert.That(map.Map.Count, Is.EqualTo(1)); Assert.That(map.Map[0].Original, Is.EqualTo("a")); Assert.That(map.Map[0].Modified, Is.EqualTo("b")); }
public void Replacer_WithSpace_ShouldReturnUpdatedString() { // Arrange var replacer = new Replacer(); // Act var res = replacer.ReplaceSpace("test with space"); // Assert Assert.AreEqual("test%20with%20space", res); }
public Converters(string fn, string nname, Types t, double s, string f, string[] q, Replacer r) { fieldnames = fn; newname = nname; converttype = t; scale = s; format = f; formatsplit = f.Split(';'); eventqual = q == null ? null : new HashSet <string>(q); replacer = r; }
public static QilNode GetCurrentPosition(QilFactory f, QilTuple context) { Debug.Assert(context != null); if (context.Where.Type != QilNodeType.True) { Debug.Assert(context.For.Type == QilNodeType.For); // convert context (1) --> (2) QilIterator for2 = f.For(context.For.Binding); QilNode cnd2 = new Replacer(f).Replace(/*inExpr:*/context.Where, /*from:*/context.For, /*to:*/for2); context.For.Binding = f.OldTuple(for2, cnd2, for2); context.Where = f.True(); } return f.Convert(f.PositionOf((QilIterator)XPathContext.GetCurrentNode(context)), f.TypeFactory.Double()); }
public TransliterateStage(Config config, History history, List <string> patterns, List <string> substitutionSources, string separatorSubstitutionSource) : base(config, history) { var fromBuilder = new List <char?>(); var toBuilder = new List <char?>(); int otherIndexInFrom = -1; bool otherReversedInFrom = false; string remainder = ParseCharacterSet(fromBuilder, patterns[0], out otherIndexInFrom, out otherReversedInFrom); int otherIndexInTo = -1; bool otherReversedInTo = false; remainder = ParseCharacterSet(toBuilder, remainder, out otherIndexInTo, out otherReversedInTo); if (otherIndexInFrom > -1 && otherIndexInTo > -1) { fromBuilder.Insert(otherIndexInFrom, 'o'); toBuilder.Insert(otherIndexInTo, 'o'); } else if (otherIndexInFrom > -1) { var otherSet = toBuilder.ToList(); if (otherReversedInFrom) { otherSet.Reverse(); } fromBuilder.InsertRange(otherIndexInFrom, otherSet); } else if (otherIndexInTo > -1) { var otherSet = fromBuilder.ToList(); if (otherReversedInTo) { otherSet.Reverse(); } toBuilder.InsertRange(otherIndexInTo, otherSet); } From = fromBuilder; To = toBuilder; if (To.Count == 0) { To = new List <char?>(); To.Add(null); } patterns[0] = remainder.Length == 0 ? @"\A(?s:.*)\z" : remainder; RegexSources = patterns; Replacers = substitutionSources.Select(s => new Replacer(s, History, Config.CyclicMatches)).ToList(); SeparatorReplacer = new Replacer(separatorSubstitutionSource, History); }
public void Test_Replace_FileInDeepSubDirectory() { Console.WriteLine(""); Console.WriteLine("Preparing test"); Console.WriteLine(""); var directoryName = "hello1/hello2"; var directoryPath = Path.GetFullPath(directoryName); var fileName = "hello.txt"; var oldValue = "hello"; var newValue = "hi"; var filePath = Path.GetFullPath(directoryName + "/" + fileName); Directory.CreateDirectory(Path.GetFullPath(directoryName)); File.WriteAllText(filePath, "hello world"); var replacer = new Replacer(Environment.CurrentDirectory); replacer.IsVerbose = true; replacer.CommitChanges = true; replacer.IncludeSubDirectories = true; Console.WriteLine(""); Console.WriteLine("Executing test"); Console.WriteLine(""); replacer.Replace("*", oldValue, newValue); replacer.IsVerbose = true; Console.WriteLine(""); Console.WriteLine("Analysing test"); Console.WriteLine(""); var newDirectoryPath = directoryPath.Replace(oldValue, newValue); var newFilePath = filePath.Replace(oldValue, newValue); Assert.IsTrue(Directory.Exists(newDirectoryPath)); Assert.IsFalse(Directory.Exists(directoryPath)); Assert.IsTrue(File.Exists(newFilePath)); var newContent = File.ReadAllText(newFilePath); var expectedContent = "hi world"; Assert.AreEqual(expectedContent, newContent); }
/// <summary> /// Post-processes the rendered message. /// </summary> /// <param name="text">The text to be post-processed.</param> /// <returns>Post-processed text.</returns> protected override string Transform(string text) { if (string.IsNullOrEmpty(ReplaceGroupName)) { return(_regex.Replace(text, ReplaceWith)); } else { var replacer = new Replacer(text, ReplaceGroupName, ReplaceWith); return(_regex.Replace(text, replacer.EvaluateMatch)); } }
public PlayingRotateService(DiscordSocketClient client, IBotConfigProvider bcp, MusicService music, DbService db) { _client = client; _bcp = bcp; _music = music; _db = db; _log = LogManager.GetCurrentClassLogger(); _rep = new ReplacementBuilder() .WithClient(client) .WithStats(client) .WithMusic(music) .Build(); _t = new Timer(async(objState) => { try { bcp.Reload(); var state = (TimerState)objState; if (!BotConfig.RotatingStatuses) { return; } if (state.Index >= BotConfig.RotatingStatusMessages.Count) { state.Index = 0; } if (!BotConfig.RotatingStatusMessages.Any()) { return; } var status = BotConfig.RotatingStatusMessages[state.Index++].Status; if (string.IsNullOrWhiteSpace(status)) { return; } status = _rep.Replace(status); try { await client.SetGameAsync(status).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } catch (Exception ex) { _log.Warn("Rotating playing status errored.\n" + ex); } }, new TimerState(), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); }
public void RemoveEmptyMapEntry() { Replacer replacer = new Replacer(); replacer.Add("a", "b"); Assert.That( () => replacer.Remove(string.Empty), Throws.ArgumentNullException); Assert.That( () => replacer.Remove(null), Throws.ArgumentNullException); }
public DataRow[] ParseQuery(string txt) { if (Environment.PrintData == null) { throw new Exception("DocTypeParser: " + Environment.StringResources.GetString("Select_SelectTypeDialog_SelectType_Load_Error1") + " data."); } if (dsPrintForms == null || dsPrintForms.Tables.Count < 1) { throw new Exception("DocTypeParser: " + Environment.StringResources.GetString("Select_SelectTypeDialog_SelectType_Load_Error1") + " table."); } txt = Regex.Replace( Replacer.ReplaceRusLat(txt), "[" + Regex.Escape(@"]\*+?|{[()^$.#%'") + "]{1,}", "", RegexOptions.IgnoreCase); txt = txt.Replace("-", " "); txt = txt.Replace(" ", " "); if (txt.Length == 0) { return(null); } string[] w = Regex.Split(txt, @"\s"); if (w.Length > 0) { string field = Environment.PrintData.NameField; List <DataRow> rows = dsPrintForms.Tables[0].Rows.Cast <DataRow>().Where <DataRow>( x => Replacer.ReplaceRusLat(x[field].ToString()).StartsWith(w[0], true, CultureInfo. InvariantCulture)).ToList(); for (int i = 1; i < w.Length; i++) { rows = rows.Where(x => Replacer.ReplaceRusLat(x[field].ToString()).ToLower().Contains(w[i].ToLower())).ToList(); } try { return(rows.ToArray()); } catch { } } return(null); }
public void RemoveFakeMapEntry() { Replacer replacer = new Replacer(); replacer.Add("a", "b"); Assert.That( () => replacer.Remove("c"), Throws.InstanceOf <KeyNotFoundException>()); Assert.That( () => replacer.Remove("b"), Throws.InstanceOf <KeyNotFoundException>()); }
public HomeModule() { Get["/"] = _ => View["index.cshtml"]; Post["/replace"] = _ => { string inputString = Request.Form["newString"]; string stringToReplace = Request.Form["newToReplace"]; string replacementString = Request.Form["newReplacer"]; Replacer newReplacer = new Replacer(inputString, stringToReplace, replacementString); string finalResult = newReplacer.FindReplace(); return(View["index.cshtml", finalResult]); }; }
public void Replace_WhenFileMaskIsTxt1Only_NoRepacesText() { Replacer replacer = new Replacer(); replacer.Dir = _tempDir; replacer.FileMask = "*.txt1"; replacer.FindText = "a"; replacer.ReplaceText = "b"; var resultItems = replacer.Replace().ResultItems; Assert.AreEqual(0, resultItems.Count); }
public void Replace_WhenSearchTextIsNewYork_NoReplacesText() { Replacer replacer = new Replacer(); replacer.Dir = _tempDir; replacer.FileMask = "*.*"; replacer.FindText = "New York"; replacer.ReplaceText = "Moscow"; var resultItems = replacer.Replace().ResultItems; Assert.AreEqual(0, resultItems.Count); }
public static void Shuffle() { List <string> minigames = new List <string>(ExportList()); minigames.Shuffle(); List <string> minigamelines = new List <string>(ExportList()); foreach (GODFile file in Files.objectives) { Replacer.ReplaceRCF("common.rcf", file.start, Replacer.ReplaceInstances(file, minigames, minigamelines), file.length); } }
protected string GetSQLCondition(string field, bool rl) { string val = Options.PrepareTextParameter(rl ? Replacer.ReplaceRusLat(Value) : Value).Trim(); switch (Mode) { case Modes.Contains: return(field + " LIKE '%" + Regex.Replace(val, "[ ]{1,}", "%") + "%'"); default: return("' '+" + field + " LIKE '" + Regex.Replace(" " + val, "[ ]{1,}", "% ") + "%'"); } }
public static Type GetReferenceType(this TypeSourceAttribute attribute, Replacer replacer) { var typeName = replacer.Replace(attribute.TypeName); if (string.IsNullOrEmpty(attribute.AssemblyPath)) { return(Type.GetType(typeName)); } var assemblySource = replacer.Replace(attribute.AssemblyPath); var assembly = Assembly.LoadFrom(assemblySource); return(assembly.GetType(typeName)); }
public void Manage_Dollars_In_Replaced_Word() { var dict = new StringDictionary { { "tem$p", "temporary" } }; var replacer = new Replacer(dict); Assert.That(replacer.Replace("$tem$p$"), Is.EqualTo("temporary")); }
/// <summary> /// Post-processes the rendered message. /// </summary> /// <param name="text">The text to be post-processed.</param> /// <returns>Post-processed text.</returns> protected override string Transform(string text) { var replacer = new Replacer(text, this.ReplaceGroupName, this.ReplaceWith); return string.IsNullOrEmpty(this.ReplaceGroupName) ? this.regex.Replace(text, this.ReplaceWith) : this.regex.Replace(text, replacer.EvaluateMatch); }
public void Test_Empty() { var dict = new StringDictionary(); var replacer = new Replacer(dict); Assert.That(replacer.Replace(""), Is.EqualTo("")); }
public void Test_One_Word() { var dict = new StringDictionary { { "temp", "temporary" } }; var replacer = new Replacer(dict); Assert.That(replacer.Replace("$temp$"), Is.EqualTo("temporary")); }
// TODO: First search the moveNextBody to see if there are any contracts at all. /// <summary> /// /// </summary> /// <param name="host"></param> /// <param name="extractor"></param> /// <param name="iteratorMethodBody"></param> /// <param name="moveNextBody"></param> /// <param name="pdbReader"></param> /// <returns></returns> public static MethodContract GetMethodContractFromMoveNext( IContractAwareHost host, ContractExtractor extractor, ISourceMethodBody iteratorMethodBody, ISourceMethodBody moveNextBody, PdbReader pdbReader ) { // Walk the iterator method and collect all of the state that is assigned to fields in the iterator class // That state needs to replace any occurrences of the fields in the contracts (if they exist...) var iteratorStmts = new List<IStatement>(iteratorMethodBody.Block.Statements); Dictionary<uint, IExpression> capturedThings = new Dictionary<uint, IExpression>(); // Find all of the state captured for the IEnumerable // REVIEW: Is this state ever used in the contracts? Since they're all sitting in the MoveNext // method, maybe they always use the IEnumerator state? if (1 < iteratorStmts.Count) { // First statement should be the creation of the iterator class int j = 1; while (j < iteratorStmts.Count) { var es = iteratorStmts[j++] as IExpressionStatement; if (es == null) break; var assign = es.Expression as IAssignment; if (assign == null) break; var field = assign.Target.Definition as IFieldReference; var capturedThing = assign.Source; var k = field.InternedKey; var spec = field as ISpecializedFieldReference; if (spec != null) k = spec.UnspecializedVersion.InternedKey; capturedThings.Add(k, capturedThing); } } else { var ret = iteratorStmts[0] as IReturnStatement; if (ret != null) { var be = ret.Expression as IBlockExpression; if (be != null) { var beStmts = new List<IStatement>(be.BlockStatement.Statements); var j = 1; while (j < beStmts.Count) { var es = beStmts[j++] as IExpressionStatement; if (es == null) break; var assign = es.Expression as IAssignment; if (assign == null) break; var field = assign.Target.Definition as IFieldReference; var capturedThing = assign.Source; var k = field.InternedKey; var spec = field as ISpecializedFieldReference; if (spec != null) k = spec.UnspecializedVersion.InternedKey; capturedThings.Add(k, capturedThing); } } } } // Find all of the state captured for the IEnumerator // That state is captured at the beginning of the IEnumerable<T>.GetEnumerator method IMethodDefinition getEnumerator = null; var t = moveNextBody.MethodDefinition.ContainingTypeDefinition; foreach (IMethodImplementation methodImplementation in t.ExplicitImplementationOverrides) { if (methodImplementation.ImplementedMethod.Name == host.NameTable.GetNameFor("GetEnumerator")) { var gtir = methodImplementation.ImplementedMethod.ContainingType as IGenericTypeInstanceReference; if (gtir != null && TypeHelper.TypesAreEquivalent(gtir.GenericType, host.PlatformType.SystemCollectionsGenericIEnumerable)) { getEnumerator = methodImplementation.ImplementingMethod.ResolvedMethod as IMethodDefinition; break; } } } if (getEnumerator != null) { IMethodBody geBody = getEnumerator.Body; var sourceGeBody = geBody as ISourceMethodBody; if (sourceGeBody == null) sourceGeBody = Decompiler.GetCodeModelFromMetadataModel(host, geBody, pdbReader, DecompilerOptions.AnonymousDelegates); foreach (var stmt in sourceGeBody.Block.Statements) { var es = stmt as IExpressionStatement; if (es == null) continue; var assign = es.Expression as IAssignment; if (assign == null) continue; var field2 = assign.Target.Definition as IFieldReference; if (field2 == null) continue; var k = field2.InternedKey; var spec = field2 as ISpecializedFieldReference; if (spec != null) k = spec.UnspecializedVersion.InternedKey; var sourceBe = assign.Source as IBoundExpression; if (sourceBe == null) continue; var field3 = sourceBe.Definition as IFieldReference; if (field3 == null) continue; var k3 = field3.InternedKey; var spec3 = field3 as ISpecializedFieldReference; if (spec3 != null) k3 = spec3.UnspecializedVersion.InternedKey; IExpression capturedThing = null; if (!capturedThings.TryGetValue(k3, out capturedThing)) continue; capturedThings[k] = capturedThing; } } var mc = HermansAlwaysRight.ExtractContracts(host, pdbReader, extractor, moveNextBody); if (mc == null) return mc; // substitute all field references in contract with the captured state var replacer = new Replacer(host, capturedThings, iteratorMethodBody.MethodDefinition, moveNextBody.MethodDefinition); replacer.RewriteChildren(mc); if (moveNextBody.MethodDefinition.ContainingTypeDefinition.IsGeneric) { var genericParameterMapper = new GenericMethodParameterMapper(host, iteratorMethodBody.MethodDefinition, moveNextBody.MethodDefinition.ContainingType as INestedTypeReference); mc = genericParameterMapper.Rewrite(mc) as MethodContract; } return mc; }