public void given_empty_cache_and_valid_commit_function() { var cache = new LockingInMemoryCache(); long? commitStoreVersion = null; long? commitStreamVersion = null; cache.ConcurrentAppend("stream", GetEventBytes(1), (version, storeVersion) => { commitStoreVersion = storeVersion; commitStreamVersion = version; }); Assert.AreEqual(1, commitStoreVersion, "commitStoreVersion"); Assert.AreEqual(1, commitStreamVersion, "commitStreamVersion"); Assert.AreEqual(1, cache.StoreVersion); var expected = new[] { CreateKey(1, 1, "stream"), }; DataAssert.AreEqual(expected, cache.ReadStream("stream",0,100)); DataAssert.AreEqual(expected, cache.ReadAll(0, 100)); }
public static void GenerateCompareOperatorCode() { var s = new StringBuilder(); var types = new[] { "DynamicValue", "bool", "byte", "sbyte", "char", "decimal", "double", "float", "int", "uint", "long", "ulong", "short", "ushort", "string" }; var operators = new[] {"==", "!=", ">", "<", ">=", "<="}; foreach (string @operator in operators) { foreach (string type1 in types) { string typeName = type1; s.AppendLine("public static bool operator " + @operator + "(DynamicValue p1, " + typeName + " p2) {"); if (typeName == "DynamicValue") { s.AppendLine("return (p1.Value " + @operator + " (dynamic)p2.To(p1.Type));"); } else { s.AppendLine("return (p1.Value " + @operator + " (dynamic)DynamicConversion.To(p1.Type, p2));"); } s.AppendLine("}"); s.AppendLine(); } } File.WriteAllText("code.cs", s.ToString()); }
public bool GetRunning() { var json = _wc.DownloadString(URL + "?action=getStatus"); var status = new { running = false }; status = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json, status); return status.running; }
public void TransformToGrayscaleFromArray() { foreach (var data in TestUtils.GetTestImagesData("*.jpg")) { Assert.DoesNotThrow(() => { var transforms = new[] { new TJTransformDescription { Operation = TJTransformOperations.TJXOP_NONE, Options = TJTransformOptions.GRAY, Region = TJRegion.Empty } }; var result = _transformer.Transform(data.Item2, transforms, TJFlags.NONE); Assert.NotNull(result); Assert.NotNull(result.Length == 1); var file = Path.Combine(OutDirectory, "gray_" + Path.GetFileName(data.Item1)); File.WriteAllBytes(file, result[0]); }); } }
public void SortObjectCanBeSortedByMonsterIdAndMark() { var s = new[]{ new SortedBoxObject { Mark = 0, MonsterId = 3 }, new SortedBoxObject { Mark = 0, MonsterId = 2 }, new SortedBoxObject { Mark = 0, MonsterId = 3 }, new SortedBoxObject { Mark = 0, MonsterId = 1 }, new SortedBoxObject { Mark = 1, MonsterId = 3 }, new SortedBoxObject { Mark = 1, MonsterId = 2 }, new SortedBoxObject { Mark = 2, MonsterId = 3 }, new SortedBoxObject { Mark = 1, MonsterId = 1 }, new SortedBoxObject { Mark = 0, MonsterId = 0 } }; var r = s.OrderBy( o=> o ).ToArray(); Assert.AreSame( s[6], r[0] ); Assert.AreSame( s[7], r[1] ); Assert.AreSame( s[5], r[2] ); Assert.AreSame( s[4], r[3] ); Assert.AreSame( s[8], r[4] ); Assert.AreSame( s[3], r[5] ); Assert.AreSame( s[1], r[6] ); Assert.AreSame( s[0], r[7] ); Assert.AreSame( s[2], r[8] ); }
private static bool IsSupported(string fileName) { string extension = Path.GetExtension(fileName).ToLowerInvariant(); string[] allowed = new[] { ".js", ".css", ".html", ".htm", ".less", ".scss", ".coffee", ".iced", ".config", ".cs", "vb" }; return allowed.Contains(extension); }
public static void RenderTexture(TextureInfo textureInfo, float x, float y, float orientation = 0, float offsetX = 0, float offsetY = 0, LabelStyle.HorizontalAlignmentEnum horizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center, LabelStyle.VerticalAlignmentEnum verticalAlignment = LabelStyle.VerticalAlignmentEnum.Center, float opacity = 1f, float scale = 1f) { GL.Enable(All.Texture2D); GL.BindTexture(All.Texture2D, textureInfo.TextureId); GL.PushMatrix(); GL.Translate(x, y, 0f); GL.Rotate(orientation, 0, 0, 1); GL.Scale (scale, scale, 1); x = offsetX + DetermineHorizontalAlignmentCorrection(horizontalAlignment, textureInfo.Width); y = -offsetY + DetermineVerticalAlignmentCorrection(verticalAlignment, textureInfo.Height); var halfWidth = textureInfo.Width / 2; var halfHeight = textureInfo.Height / 2; var vertextArray = new[] { x - halfWidth, y - halfHeight, x + halfWidth, y - halfHeight, x + halfWidth, y + halfHeight, x - halfWidth, y + halfHeight }; RenderTextureWithoutBinding(textureInfo.TextureId, vertextArray, opacity); GL.PopMatrix(); GL.BindTexture(All.Texture2D, 0); GL.Disable(All.Texture2D); }
public void FiltersEventsWithLevelExactValue() { var expected = new[] { new EventExpectation { Level = Level.Error, Logger = "Root.ChildA.LoggerA1", Thread = "Thread-5", Timestamp = 1411231353795L, Message = "#5. Test event F.", Throwable = null, Id = 672 } }; using (var sourceStream = new MemoryStream (sampleBytes)) using (var source = Log4JFile.Create (sourceStream)) using (var subject = new FilterLevel (Level.Error, Level.Error)) { source.Encoding = Encoding.GetEncoding (1251); var actual = source.GetEvents ().Where (subject); Assert.That (actual, Is.EqualTo (expected)); } }
public bool IsSatisifedBy(string path) { var fileExt = Path.GetExtension(path); var extensions = new[] { "PNG", "PCX", "JPG", "JPEG", "GIF", "TIF", "BMP", "TGA", }; if (fileExt != null && fileExt != "") fileExt = fileExt.Substring(1).ToUpper(); return extensions.Any(extension => fileExt != null && fileExt.Equals(extension)); }
private static string GetPrelude(DirectoryInfo dir) { var preludeFile = new[] { dir, dir.Parent }. SelectMany(d => d.GetFiles("prelude.*", SearchOption.TopDirectoryOnly)) .FirstOrDefault(f => f.Exists); return preludeFile == null ? "" : preludeFile.ContentAsUtf8(); }
public void ComplexTest() { var source = @"{{#each nav ~}} <a href=""{{url}}""> {{~#if test}} {{~title}} {{~else~}} Empty {{~/if~}} </a> {{~/each}}"; var template = Handlebars.Compile(source); var data = new { nav = new [] { new { url = "https://google.com", test = true, title = "Google" }, new { url = "https://bing.com", test = false, title = "Bing" } } }; var result = template(data); Assert.AreEqual(@"<a href=""https://google.com"">Google</a><a href=""https://bing.com"">Empty</a>", result); }
public TextureAtlas Parse(string dataFilePath) { if (!File.Exists(dataFilePath)) { throw new FileNotFoundException(nameof(dataFilePath) + $" : {dataFilePath}"); } var xml = XDocument.Load(dataFilePath); var atlasDetails = new { Width = (int)xml.Element("TextureAtlas").Attribute("width"), Height = (int)xml.Element("TextureAtlas").Attribute("height"), TextureRegions = from s in xml.Root.Descendants("sprite") select new { X = (int)s.Attribute("x"), Y = (int)s.Attribute("y"), Width = (int)s.Attribute("w"), Height = (int)s.Attribute("h") } }; var textureAtlas = new TextureAtlas(atlasDetails.Width, atlasDetails.Height); foreach (var region in atlasDetails.TextureRegions) { textureAtlas.Add(new TextureRegion(region.X, region.Y, region.Width, region.Height)); } return textureAtlas; }
public void non_dotnet_files_are_skipped() { var assemblyScanner = new AssemblyScanner(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestDlls")); var results = assemblyScanner .GetScannableAssemblies(); var skippedFiles = results.SkippedFiles; var notProperDotNetDlls = new[] { "libzmq-v120-mt-3_2_3.dll", "Tail.exe", "some_random.dll", "some_random.exe" }; foreach (var notProperDll in notProperDotNetDlls) { var skippedFile = skippedFiles.FirstOrDefault(f => f.FilePath.Contains(notProperDll)); if (skippedFile == null) { throw new AssertionException($"Could not find skipped file matching {notProperDll}"); } Assert.That(skippedFile.SkipReason, Contains.Substring("not a .NET assembly")); } }
protected TribitPyramid TransformImpl(TribitPyramid tribitPyramid) { var indices = tribitPyramid.GetPyramidIndices(); var bitscnt = new[] { 0, 0 }; for (var i = 0; i < indices.Length; ++i) { var triange = tribitPyramid[indices[i]]; var tribitPyramidRule = TribitPyramidRule.GetBy(triange); if (tribitPyramidRule != null) { tribitPyramid[indices[i]] = tribitPyramidRule.To; } else { bitscnt[triange[0]]++; } } if (bitscnt[0] + bitscnt[1] == indices.Length) { if (bitscnt[0] == 0) return new TribitPyramid(1); if (bitscnt[1] == 0) return new TribitPyramid(0); var bits = new byte[tribitPyramid.Count >> 2]; for (var i = 0; i < bits.Length; ++i) { bits[i] = tribitPyramid[indices[i]][0]; } return new TribitPyramid(bits); } return tribitPyramid; }
public void DownloadFile() { var path = packet.args.First().ToString(); if (File.Exists(path)) { var fileName = Path.GetFileName(path); var size = new FileInfo(path).Length; var data = new { fileValid = true, fileName, size }; serializator.Serialize(_client, packet.endpoint, packet.syncKey, data); serializator.PushFile(_client, path); } else { var data = new { fileValid = false }; serializator.Serialize(_client, packet.endpoint, packet.syncKey, data); } }
public async Task CreatePackage_SetContentFilesMetadata() { var result = await Scenario.RestoreAndBuildSinglePackageAsync(); var solutionPath = Assets.GetScenarioSolutionPath(); var projectPath = Path.GetDirectoryName(solutionPath); var nuspecFile = Path.Combine(projectPath, @"Package\obj\Debug\Package.nuspec"); Manifest manifest; using (var stream = File.OpenRead(nuspecFile)) { manifest = Manifest.ReadFrom(stream, false); } var expected = new[] { new ManifestContentFiles { Include=@"any\any\1x1.png", BuildAction="EmbeddedResource", CopyToOutput="false", Flatten="false"}, new ManifestContentFiles { Include=@"any\any\TextFile.txt", BuildAction="None", CopyToOutput="true", Flatten="false"}, new ManifestContentFiles { Include=@"cs\any\Class.cs.pp", CopyToOutput="false", Flatten="false"}, new ManifestContentFiles { Include=@"cs\any\Class1.cs.pp", CopyToOutput="false", Flatten="false"} }; Assert.Equal<ManifestContentFiles>( expected, manifest.Metadata.ContentFiles.OrderBy(x => x.Include), ManifestContentFilesComparer.Instance); }
private static void Main() { using (var csv = new CsvWriter(new StreamWriter("results.csv", false, Encoding.UTF8))) { WriteHeader(csv); var languagesToTest = new[] {Languages.EnglishUK, Languages.GermanGermany}; foreach (var language in languagesToTest) { var results = new AutoCorrectTester(language).Run(); foreach (var result in results) { foreach (var testResult in result.Results) { csv.WriteField(language); csv.WriteField(result.AutoCompleteMethod); csv.WriteField(result.MemorySize); csv.WriteField(testResult.Misspelling); csv.WriteField(testResult.TargetWord); csv.WriteField(testResult.CharactersTyped); csv.WriteField(testResult.TargetWord.Length); csv.WriteField(testResult.TimeTaken.Milliseconds); csv.WriteField(testResult.CharactersTyped != -1 ? (double) testResult.CharactersTyped/testResult.TargetWord.Length : 2d); csv.NextRecord(); } } } } }
public void PackageIsCorrect() { this.SetupTest("ExtractXSLTWorks", isPackTest: true); var files = new[] { "GenerateProject.CSharp.xslt", "GenerateProject.CPlusPlus.MonoDevelop.xslt", "GenerateProject.CPlusPlus.VisualStudio.xslt", "GenerateSolution.xslt", "GenerationFunctions.cs", "SelectSolution.xslt", }; foreach (var file in files) { if (File.Exists(this.GetPath("Build\\" + file))) { File.Delete(this.GetPath("Build\\" + file)); } } this.OtherMode("extract-xslt"); foreach (var file in files) { _assert.True(File.Exists(this.GetPath("Build\\" + file))); } }
public void Should_Generate_HTML_References_with_pre_and_post_text() { // Arrange var compilers = new[] { new JQueryTemplateCompiler(), }; var referencer = new LABjsScriptReference(); var package = new Package(".", compilers, referencer); var references = new[] { new SystemReference(new DirectoryInfo("C:/Root/"), new FileInfo("C:/Root/Scripts/depper1.js"), "depper1.js") { Type = Reference.TypeEnum.App } }; // Act var result = package.GenerateReferences(references, new HelperOptions { GenerateHeaderAndFooter = true }); // Assert result.ShouldBe( @"<script> $LAB .script(""/hotglue.axd/Scripts/depper1.js-app""); </script> "); }
public void Test_Trim() { { const string testCase = "\t\t\t APA \r\n BEPA \r\n "; var ss = testCase.ToSubString (); TestFor.Equality (testCase.TrimStart() , ss.TrimStart ().Value , "TrimStart must work as expected"); TestFor.Equality (testCase.TrimEnd () , ss.TrimEnd ().Value , "TrimEnd must work as expected"); TestFor.Equality (testCase.Trim () , ss.Trim ().Value , "Trim must work as expected"); } { const string testCase = "ABCBA"; var ss = testCase.ToSubString (); var trimChars = new [] {'A', 'B'}; TestFor.Equality (testCase.TrimStart(trimChars) , ss.TrimStart (trimChars).Value, "TrimStart must work as expected"); TestFor.Equality (testCase.TrimEnd (trimChars) , ss.TrimEnd (trimChars).Value , "TrimEnd must work as expected"); TestFor.Equality (testCase.Trim (trimChars) , ss.Trim (trimChars).Value , "Trim must work as expected"); } }
public void FiltersEventsWithMessageContainingString() { var expected = new[] { new EventExpectation { Level = Level.Warn, Logger = "Root.ChildA.LoggerA1", Thread = "Thread-4", Timestamp = 1411231353793L, Message = "#4. Test event E.", Throwable = null, Id = 507 } }; using (var sourceStream = new MemoryStream (sampleBytes)) using (var source = Log4JFile.Create (sourceStream)) using (var subject = new FilterMessage ("nt E")) { source.Encoding = Encoding.GetEncoding (1251); var actual = source.GetEvents ().Where (subject); Assert.That (actual, Is.EqualTo (expected)); } }
public void DnuPublishWebApp_SubdirAsPublicDir_DirPlusFlatList(DnxSdk sdk) { const string projectName = "ProjectForTesting"; FrameworkName[] frameworkCandidates = { FrameworkNameHelper.ParseFrameworkName("dnx451"), FrameworkNameHelper.ParseFrameworkName("dnxcore50") }; var targetFramework = DependencyContext.SelectFrameworkNameForRuntime( frameworkCandidates, sdk.FullName).FullName; var projectJson = new JObject { ["publishExclude"] = "**.useless", ["frameworks"] = new JObject { ["dnx451"] = new JObject { }, ["dnxcore50"] = new JObject { } } }; var hostingJson = new JObject { ["webroot"] = "public" }; var projectStructure = new Dir {
public void LoadsInputFromAGivenFile(FileWrapper wrapper) { string inputPath = null; try { // -- Setup var expected = new[] {"multiply 9", "apply 5"}; inputPath = Path.GetTempFileName(); File.WriteAllLines(inputPath, expected); // -- Arrange // -- Act var actual = wrapper.ReadAllLines(inputPath); // -- Assert Assert.Equal(expected.Length, actual.Length); Assert.Equal(expected[0], actual[0]); Assert.Equal(expected[1], actual[1]); } finally { // -- Teardown if (File.Exists(inputPath)) File.Delete(inputPath); } }
public void TestExportArchive() { using (var cp = GetCP()) { var testPk = "CertificateProviderTests.key.json"; var testCert = "CertificateProviderTests-Certificate.pem"; var testIcaCert = "CertificateProviderTests-ICA-Certificate.pem"; PrivateKey pk; using (var s = new FileStream(testPk, FileMode.Open)) { pk = cp.LoadPrivateKey(s); } Crt cert; using (var s = new FileStream(testCert, FileMode.Open)) { cert = cp.ImportCertificate(EncodingFormat.PEM, s); } Crt icaCert; using (var s = new FileStream(testIcaCert, FileMode.Open)) { icaCert = cp.ImportCertificate(EncodingFormat.PEM, s); } using (var s = new MemoryStream()) { var certs = new[] { cert, icaCert }; cp.ExportArchive(pk, certs, ArchiveFormat.PKCS12, s); } } }
static void Main(string[] args) { const string categoryName = "Likes"; var methods = new[] { "likes.getList", "likes.add", "likes.delete", "likes.isLiked" }; var parser = new VkApiParser(); var generator = new VkApiGenerator(); var source = InitializeSource(categoryName); foreach (string methodName in methods) { System.Console.WriteLine("*** {0} ***", methodName); VkMethodInfo methodInfo; try { methodInfo = parser.Parse(methodName); } catch (WebException ex) { System.Console.WriteLine(ex.Message); continue; } System.Console.WriteLine("DESCRIPTION: {0}", methodInfo.Description); System.Console.WriteLine("RETURN TEXT: {0}", methodInfo.ReturnText); System.Console.WriteLine("RETURN TYPE: {0}", methodInfo.ReturnType); System.Console.WriteLine("PAPAMETERS:"); foreach (var p in methodInfo.Params) { System.Console.WriteLine(" {0} - {1}", p.Name, p.Description); } source.Append(generator.GenerateMethod(methodInfo)) .AppendLine() .AppendLine(); System.Console.WriteLine("\n========================================\n"); //System.Console.ReadLine(); } source.Append("}}"); System.Console.WriteLine("Saving to disk"); string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); path = Path.Combine(path, @"..\VkNet\Categories\"); path = string.Format("{0}\\{1}Category_Generated.cs", path, categoryName); File.WriteAllText(path, source.ToString()); System.Console.WriteLine("done."); }
public bool IsSatisifedBy(string path) { var nonImageDaxFiles = new [] { "WALLDEF", "MON", "ITEM", "MUSIC", "SOUND", "ZOUNDS", "LUCK" }; var fileName = Path.GetFileName(path); if (fileName == null) return false; fileName = fileName.ToUpper(); return !nonImageDaxFiles.Any(prefix => fileName.StartsWith(prefix)) && fileName.ToUpper().EndsWith(".DAX"); }
private static string GetSource(IVsProject project, string source) { var directory = Directory.Exists(source) ? source : Path.GetDirectoryName(source); var candidates = new[]{ Path.Combine(directory, Globals.SettingsFilename) }; return candidates.FirstOrDefault(f => project.HasFile(f)); }
public void FileDropContainerShouldReturnFileNames() { var input = new[] { @"c:\temp\file1.txt", @"c:\temp\file2.txt" }; var expectedResult = new[] { @"file1.txt", @"file2.txt" }; var container = new FileDropContainer(input); container.Files.Should().BeEquivalentTo(expectedResult); }
public void PrepareCMDirectory() { var cmFiles = new[] { "CM.Common.dll", "CM.MSBuild.Tasks.dll", "deployer.exe" }; foreach (var file in cmFiles) File.Copy(file, Path.Combine("CM.NET", file), true); File.Copy(@"..\..\..\CM.Deployer\App.config", @"CM.NET\deployer.exe.config", true); }
public static object QueryResultToJson(QueryResultTable queryResult) { var resultsTable = new { columnNames = queryResult.ColumnNames.Select(name => name.ToString()).ToList(), rows = queryResult.Rows.Select(RowToJson).ToList() }; return resultsTable; }