protected override void DisposeOverride() { DiagnosticsWriter.WriteInformation("Disconnecting from device"); var resources = mResources?.ToArray() ?? new HardwareResource[0]; if (resources.Length > 0) { DiagnosticsWriter.WriteWarning("The is being disconnected from but there are still {0} associated resource(s) allocated. The resources will be disposed to avoid memory leaks", resources.Length); foreach (var resource in resources) { resource?.Dispose(); } } mResources?.Clear(); mResources = null; System.Diagnostics.Debug.Assert(!mDevice.Disposed); mDevice?.Dispose(); mFactory?.Dispose(); mDevice = null; mFactory = null; DiagnosticsWriter.WriteInformation("Disconnection completed."); }
public ScriptProjectGenerator(string[] _files, HashSet<string> assemblyReferences, ScriptSequence _sequence) { isCSharp = _sequence.Language.GetType().Name.Contains("CSharp"); sequence = _sequence; files.AddRange(_files); references.AddRange(assemblyReferences.ToArray()); }
QueryTableDialog(IEnumerable<string> tables) { this.tables = new HashSet<string>(tables); InitializeComponent(); tablesList.AddSuggestions(tables.ToArray()); tablesList.IsDropDownOpen = true; }
private void InitAssemblyCache() { if (this.assemblies != null) return; // Retrieve a list of all loaded, non-disposed Assemblies Assembly[] loadedAssemblies = DualityApp.PluginLoader.LoadedAssemblies .Where(a => !DualityApp.PluginManager.DisposedPlugins.Contains(a)) .ToArray(); // Aggregate selectable assemblies based on Duality core Assemblies and their dependencies HashSet<Assembly> selectableAssemblies = new HashSet<Assembly>(); foreach (Assembly coreAssembly in DualityApp.GetDualityAssemblies()) { selectableAssemblies.Add(coreAssembly); AssemblyName[] referencedAssemblies = coreAssembly.GetReferencedAssemblies(); foreach (AssemblyName reference in referencedAssemblies) { string shortName = reference.GetShortAssemblyName(); Assembly dependency = loadedAssemblies.FirstOrDefault(a => a.GetShortAssemblyName() == shortName); if (dependency != null) selectableAssemblies.Add(dependency); } } this.assemblies = selectableAssemblies.ToArray(); this.namespaces = this.assemblies .SelectMany(a => { try { return a.GetExportedTypes(); } catch (Exception) { return new Type[0]; } }) .Select(t => t.Namespace) .Distinct() .Where(n => !string.IsNullOrEmpty(n)) .ToArray(); }
/// <summary> /// iterates fields of Hash types and their associated values. /// </summary> /// <remarks> /// Time complexity: O(1) for every call. O(N) for a complete iteration, including enough command calls for the cursor to return back to 0. /// N is the number of elements inside the collection. /// </remarks> /// <typepar am name="T">Type of the returned value</typeparam> /// <param name="hashKey">Key of the hash</param> /// <param name="pattern">GLOB search pattern</param> /// <param name="pageSize">Number of elements to retrieve from the redis server in the cursor</param> /// <param name="commandFlags">Command execution flags</param> /// <returns></returns> public TResult HashScan <TResult>(string hashKey, string pattern, CommandFlags commandFlags = CommandFlags.None) where TResult : IDictionary { var value = Excute((db) => { var values = new HashSet <HashEntry>(); int nextCursor = 0; do { var redisResult = db.HashScan(hashKey, pattern, 1000, 0, nextCursor, commandFlags); if (redisResult.Count() == 0) { break; } var innerResult = redisResult.ToArray(); nextCursor += redisResult.Count(); values.UnionWith(innerResult); } while (nextCursor != 0); return(values?.ToArray()); }); return(ToGenericValue <TResult>(value)); }
/// <summary> /// Returns the CSS classes (if any) associated with the theme(s) of the content, as decided by its categories /// </summary> /// <param name="content"></param> /// <returns>CSS classes associated with the content's theme(s), or an empty string array if no theme is applicable</returns> /// <remarks>Content's categorization may map to more than one theme. This method assumes there are website categories called "Meet", "Track", and "Plan"</remarks> public static string[] GetThemeCssClassNames(this ICategorizable content) { if (content.Category == null) { return new string[0]; } var cssClasses = new HashSet<string>(); // Although with some overhead, a HashSet allows us to ensure we never add a CSS class more than once foreach (var categoryName in content.Category.Select(category => content.Category.GetCategoryName(category).ToLower())) { switch (categoryName) { case "meet": cssClasses.Add("theme1"); break; case "track": cssClasses.Add("theme2"); break; case "plan": cssClasses.Add("theme3"); break; } } return cssClasses.ToArray(); }
public void run(int seconds) { var tsks = new HashSet<Task>(); durationSeconds = seconds; var metrics = Metric.Context("shared"); foreach (var t in tasks) { t.Duration = durationSeconds; if (sharedMetrics > 0) { t.metrics = metrics; } else { t.metrics = Metric.Context(t.ToString()); } var task = new Task(() => t.Call(),TaskCreationOptions.LongRunning); task.Start(); tsks.Add(task); } try { Task.WaitAll(tsks.ToArray()); } catch (Exception) { } Console.WriteLine("TASKS COMPLETE "); }
public override void Run(List<Point> points, List<Line> lines, List<Polygon> polygons, ref List<Point> outPoints, ref List<Line> outLines, ref List<Polygon> outPolygons) { HashSet<PointComparer> hashP = new HashSet<PointComparer>(); for (int i = 0; i < points.Count; ++i) hashP.Add(new PointComparer(points[i])); PointComparer[] res = hashP.ToArray(); points.Clear(); for (int i = 0; i < res.Length; ++i) points.Add(res[i].p); List<bool> visited = new List<bool>(); for (int i = 0; i < points.Count; ++i) visited.Add(false); for (int i = 0; i < points.Count; ++i) { for (int j = 0; j < points.Count; ++j) if (!visited[j]) for (int k = 0; k < points.Count; ++k) if (!visited[k]) for (int l = 0; l < points.Count; ++l) if (!visited[l] && (valid(i, j, k, l))) { Enums.PointInPolygon state = HelperMethods.PointInTriangle(points[i], points[j], points[k], points[l]); if (state == Enums.PointInPolygon.Inside || state == Enums.PointInPolygon.OnEdge) visited[i] = true; } } outPoints = new List<Point>(); for (int i = 0; i < points.Count; ++i) if (!visited[i]) outPoints.Add(points[i]); return; }
static void Main() { //var numberOfShirtsK = int.Parse(Console.ReadLine()); var numberOfShirtsK = 3; usedShirt = new int[numberOfShirtsK]; //var skirts = Console.ReadLine(); var skirtsL = "baca"; var numberOfSkirtsL = skirtsL.Length; usedSkirt = new int[numberOfSkirtsL]; //var numberOfGirls = int.Parse(Console.ReadLine()); var numberOfGirls = 2; HashSet<string> possibleCombos = new HashSet<string>(); for (int i = 0; i < numberOfShirtsK; i++) { for (int j = 0; j < numberOfSkirtsL; j++) { possibleCombos.Add(i.ToString() + j.ToString()); } } GenerateCombinations(0, 0, numberOfGirls, possibleCombos.ToArray(), new string[numberOfGirls]); }
static string[] ExtractParameters(string script) { var ps = ParameterExtractor.Matches(script); if (ps.Count == 0) return null; var ret = new HashSet<string>(); for (var i = 0; i < ps.Count; i++) { var c = ps[i]; var ix = c.Index - 1; if (ix >= 0) { var prevChar = script[ix]; // don't consider this a parameter if it's in the middle of word (ie. if it's preceeded by a letter) if (char.IsLetterOrDigit(prevChar) || prevChar == '_') continue; // this is an escape, ignore it if (prevChar == '@') continue; } var n = c.Groups["paramName"].Value; if (!ret.Contains(n)) ret.Add(n); } return ret.ToArray(); }
public IBrush MakeBrush(Player player, CommandReader cmd) { if (player == null) throw new ArgumentNullException("player"); if (cmd == null) throw new ArgumentNullException("cmd"); // read the block filter list HashSet<Block> blocks = new HashSet<Block>(); while (cmd.HasNext) { Block block; if (!cmd.NextBlock(player, false, out block)) { return null; } if (!blocks.Add(block)) { // just a warning -- don't abort player.Message("{0}: {1} was specified twice!", Name, block); } } // create a brush if (blocks.Count > 0) { return new PasteBrush(blocks.ToArray(), Not); } else if (Not) { player.Message("PasteNot brush requires at least 1 block."); return null; } else { return new PasteBrush(); } }
private static BuildingInfo[] GetUniquePillars() { var pillarsTemp = new HashSet<BuildingInfo>(); foreach (var buildingInfo in Util.GetAllPrefabs().SelectMany(prefab => prefab.GetPillars())) { pillarsTemp.Add(buildingInfo); } for (uint i = 0; i < PrefabCollection<BuildingInfo>.LoadedCount(); i++) { var prefab = PrefabCollection<BuildingInfo>.GetLoaded(i); if (prefab == null || prefab.m_buildingAI.GetType() != typeof(BuildingAI)) { continue; } var asset = PackageManager.FindAssetByName(prefab.name); var crpPath = asset?.package?.packagePath; var directoryName = Path.GetDirectoryName(crpPath); if (directoryName == null) { continue; } var pillarConfigPath = Path.Combine(directoryName, "Pillar.xml"); if (!File.Exists(pillarConfigPath)) { continue; } pillarsTemp.Add(prefab); } return pillarsTemp.ToArray(); }
public static int[] many(int x) { ICollection<int> set = new HashSet<int>(); while (set.Count < x) set.Add(RANDOM.Next(1, 50)); return set.ToArray(); }
static void drawCodeGenerators(CodeGeneratorConfig codeGeneratorConfig, Type[] codeGenerators) { EditorGUILayout.Space(); EditorGUILayout.LabelField("Code Generators", EditorStyles.boldLabel); var enabledCodeGenerators = new HashSet<string>(codeGeneratorConfig.enabledCodeGenerators); var availableGeneratorNames = new HashSet<string>(); foreach (var codeGenerator in codeGenerators) { availableGeneratorNames.Add(codeGenerator.Name); var isEnabled = enabledCodeGenerators.Contains(codeGenerator.Name); isEnabled = EditorGUILayout.Toggle(codeGenerator.Name, isEnabled); if (isEnabled) { enabledCodeGenerators.Add(codeGenerator.Name); } else { enabledCodeGenerators.Remove(codeGenerator.Name); } } foreach (var generatorName in codeGeneratorConfig.enabledCodeGenerators.ToArray()) { if (!availableGeneratorNames.Contains(generatorName)) { enabledCodeGenerators.Remove(generatorName); } } var sortedCodeGenerators = enabledCodeGenerators.ToArray(); Array.Sort(sortedCodeGenerators); codeGeneratorConfig.enabledCodeGenerators = sortedCodeGenerators; }
string[] GetEnabledSceneNames() { var scenes = (sceneNameAttribute.enableOnly ? EditorBuildSettings.scenes.Where(scene => scene.enabled) : EditorBuildSettings.scenes).ToList(); var sceneNames = new HashSet<string>(); scenes.ForEach(scene => sceneNames.Add(scene.path.Substring(scene.path.LastIndexOf("/") + 1).Replace(".unity", string.Empty))); return sceneNames.ToArray(); }
private static IEnumerable<Assembly> GetNancyReferencingAssemblies() { #if DNX var libraryManager = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.LibraryManager; var results = new HashSet<Assembly> { typeof (INancyEngine).Assembly }; var referencingLibraries = libraryManager.GetReferencingLibraries(NancyAssemblyName.Name); foreach (var assemblyName in referencingLibraries.SelectMany(referencingLibrary => referencingLibrary.Assemblies)) { try { results.Add(Assembly.Load(assemblyName)); } catch { } } return results.ToArray(); #else return AppDomain.CurrentDomain.GetAssemblies().Where(IsNancyReferencing); #endif }
public void Install(RunningDeployment deployment) { var transformDefinitions = GetTransformDefinitions(deployment.Variables.Get(SpecialVariables.Package.AdditionalXmlConfigurationTransforms)); var sourceExtensions = new HashSet<string>( transformDefinitions .Where(transform => transform.Advanced) .Select(transform => "*" + Path.GetExtension(transform.SourcePattern)) .Distinct() ); if (deployment.Variables.GetFlag(SpecialVariables.Package.AutomaticallyRunConfigurationTransformationFiles)) { sourceExtensions.Add("*.config"); transformDefinitions.Add(new XmlConfigTransformDefinition("Release")); var environment = deployment.Variables.Get(SpecialVariables.Environment.Name); if (!string.IsNullOrWhiteSpace(environment)) { transformDefinitions.Add(new XmlConfigTransformDefinition(environment)); } } var transformsRun = new HashSet<string>(); foreach (var configFile in fileSystem.EnumerateFilesRecursively(deployment.CurrentDirectory, sourceExtensions.ToArray())) { ApplyTransformations(configFile, transformDefinitions, transformsRun); } deployment.Variables.SetStrings(SpecialVariables.AppliedXmlConfigTransforms, transformsRun, "|"); }
public override void IndexDocuments( AbstractViewGenerator viewGenerator, IEnumerable<dynamic> documents, WorkContext context, IStorageActionsAccessor actions, DateTime minimumTimestamp) { actions.Indexing.SetCurrentIndexStatsTo(name); var count = 0; Func<object, object> documentIdFetcher = null; var reduceKeys = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); var documentsWrapped = documents.Select(doc => { var documentId = doc.__document_id; foreach (var reduceKey in actions.MappedResults.DeleteMappedResultsForDocumentId((string)documentId, name)) { reduceKeys.Add(reduceKey); } return doc; }); foreach (var doc in RobustEnumeration(documentsWrapped, viewGenerator.MapDefinition, actions, context)) { count++; documentIdFetcher = CreateDocumentIdFetcherIfNeeded(documentIdFetcher, doc); var docIdValue = documentIdFetcher(doc); if (docIdValue == null) throw new InvalidOperationException("Could not find document id for this document"); var reduceValue = viewGenerator.GroupByExtraction(doc); if (reduceValue == null) { logIndexing.DebugFormat("Field {0} is used as the reduce key and cannot be null, skipping document {1}", viewGenerator.GroupByExtraction, docIdValue); continue; } var reduceKey = ReduceKeyToString(reduceValue); var docId = docIdValue.ToString(); reduceKeys.Add(reduceKey); var data = GetMapedData(doc); logIndexing.DebugFormat("Mapped result for '{0}': '{1}'", name, data); var hash = ComputeHash(name, reduceKey); actions.MappedResults.PutMappedResult(name, docId, reduceKey, data, hash); actions.Indexing.IncrementSuccessIndexing(); } actions.Tasks.AddTask(new ReduceTask { Index = name, ReduceKeys = reduceKeys.ToArray() }, minimumTimestamp); logIndexing.DebugFormat("Mapped {0} documents for {1}", count, name); }
public void Run() { //if (!File.Exists("WordLookup.txt")) // Contains about 150,000 words // new WebClient().DownloadFile( // "http://www.albahari.com/ispell/allwords.txt", "WordLookup.txt"); var wordLookup = new HashSet<string>( File.ReadAllLines("WordLookup.txt"), StringComparer.InvariantCultureIgnoreCase); // Random is not thread-safe,所以無法簡單的使用AsParallel, // 解決方法,使用locks 的方式包住random.Next // 參考網址:http://csharpindepth.com/Articles/Chapter12/Random.aspx var random = new Random(); string[] wordList = wordLookup.ToArray(); // Fortunately, the new ThreadLocal<T> class in .NET 4 makes it very easy to write providers which need to have a single instance per thread // 使用ThreadLocal,建立分開的Random object 給每一個Thread //new Random(參數), 是為了確保如果兩個Random objects 被建立在很短的時間,會回傳不同的亂數序列 var allocationRandom = new ThreadLocal<Random>(() => new Random(Guid.NewGuid().GetHashCode())); // 隨機取100W的值塞給wordsToTest string[] wordsToTest = Enumerable.Range(0, 1000000) .AsParallel() .Select(i => wordList[allocationRandom.Value.Next(0, wordList.Length)]) .ToArray(); var startTime = DateTime.Now.Ticks; var endTime = DateTime.Now.Ticks; Console.WriteLine("Time : " + (endTime - startTime).ToString()); }
/// <summary> /// Creates a new object code file object. /// </summary> /// <param name="StartAddress">The load address of the object file.</param> /// <param name="Filename">The name of the object file.</param> /// <param name="Architecture">The targeted architecture of the object file.</param> /// <param name="Sections">The sections of the object file.</param> /// <param name="SymbolTable">The symbol table of the object file.</param> /// <param name="Code">The source code of the object file.</param> public ObjectCodeFile(long StartAddress, String Filename, String Architecture, Section[] Sections, SymbolTable SymbolTable, CodeUnit[] Code) { this.loadAddress = StartAddress; this.Filepath = Filename; this.Architecture = Architecture; this.Sections = Sections; this.SymbolTable = SymbolTable; this.Code = Code; this.RequestedLoadAddress = StartAddress; // Sum loaded sections' sizes if (this.Sections != null) this.Size = this.Sections.Sum( sec => sec.Flags.HasFlag(SectionFlags.Load) ? (long)sec.Size : 0); // Get unique source file paths var tmpFiles = new HashSet<string>(); foreach (CodeUnit unit in this.Code) { tmpFiles.Add(unit.SourceFilepath.Trim()); } this.SourceFiles = tmpFiles.ToArray(); }
static PrefabAssembler[] GetSelectedAssemblers () { HashSet<PrefabAssembler> assemblers = new HashSet<PrefabAssembler>(); foreach(var go in Selection.gameObjects) { if(EditorUtility.IsPersistent(go)) { continue; } // Seek assemblers in children foreach(var a in go.GetComponentsInChildren<PrefabAssembler>()) { assemblers.Add(a); } // Seek assemblers in parents Transform t = go.transform.parent; while(t) { var a = t.GetComponent<PrefabAssembler>(); if(a) { assemblers.Add(a); } t = t.parent; } } return assemblers.ToArray(); }
public static void Run() { using (FastScanner fs = new FastScanner(new BufferedStream(Console.OpenStandardInput()))) using (StreamWriter writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()))) { int n = fs.NextInt(); HashSet<int> set = new HashSet<int>(); for (int i = 0; i < n; i++) { int x = fs.NextInt(); set.Add(x); } if (set.Count < 3) { writer.WriteLine("YES"); } else if (set.Count > 3) { writer.WriteLine("NO"); } else { int[] a = set.ToArray(); Array.Sort(a); writer.WriteLine(a[1] - a[0] == a[2] - a[1] ? "YES" : "NO"); } } }
static void OnSavedScene () { var behaviours = GameObject.FindObjectsOfType(typeof(MonoBehaviour)); var assemblers = new HashSet<PrefabAssembler>(); foreach(MonoBehaviour b in behaviours) { if(b.GetType().GetCustomAttributes(typeof(AssembleOnSave), true).Length == 0) { continue; } Transform target = b.transform; while(target) { var a = target.GetComponent<PrefabAssembler>(); if(a) { assemblers.Add(a); } target = target.parent; } } if(assemblers.Count != 0) { PrefabAssembler.IsSaving = true; PrefabAssemblerUtility.Assemble(assemblers.ToArray()); PrefabAssembler.IsSaving = false; } }
public string GetSpecialAas() { Dictionary<char, int> count1 = new Dictionary<char, int>(); Dictionary<char, int> count2 = new Dictionary<char, int>(); foreach (string s in specificity){ char c1 = s[0]; char c2 = s[1]; if (!count1.ContainsKey(c1)){ count1.Add(c1, 0); } if (!count2.ContainsKey(c2)){ count2.Add(c2, 0); } count1[c1]++; count2[c2]++; } HashSet<char> result = new HashSet<char>(); foreach (char c in count1.Keys){ if (count1[c] >= 17){ result.Add(c); } } foreach (char c in count2.Keys){ if (count2[c] >= 17){ result.Add(c); } } return new string(result.ToArray()); }
/// <summary> /// Starts the clustering. /// </summary> /// <param name="elements"></param> /// <param name="fusion"></param> /// <param name="metric"></param> /// <returns></returns> protected internal Cluster[] Cluster(List<Element> elements, Fusion fusion, IDistanceMetric metric) { HashSet<Cluster> clusters = new HashSet<Cluster>(); ClusterPairs pairs = new ClusterPairs(); // 1. Initialize each element as a cluster foreach (Element el in elements) { Cluster cl = new Cluster(fusion); cl.AddElement(el); clusters.Add(cl); } // 2. a) Calculate the distances of all clusters to all other clusters foreach (Cluster cl1 in clusters) { foreach (Cluster cl2 in clusters) { if (cl1 == cl2) continue; ClusterPair pair = new ClusterPair(cl1, cl2, cl1.CalculateDistance(cl2)); pairs.AddPair(pair); } } // 2. b) Initialize the pair with the lowest distance to each other. ClusterPair lowestDistancePair = pairs.LowestDistancePair; // 3. Merge clusters to new clusters and recalculate distances in a loop until there are only countCluster clusters while (!isFinished(clusters, lowestDistancePair)) { // a) Merge: Create a new cluster and add the elements of the two old clusters lowestDistancePair = pairs.LowestDistancePair; Cluster newCluster = new Cluster(fusion); newCluster.AddElements(lowestDistancePair.Cluster1.GetElements()); newCluster.AddElements(lowestDistancePair.Cluster2.GetElements()); // b)Remove the two old clusters from clusters clusters.Remove(lowestDistancePair.Cluster1); clusters.Remove(lowestDistancePair.Cluster2); // c) Remove the two old clusters from pairs pairs.RemovePairsByOldClusters(lowestDistancePair.Cluster1, lowestDistancePair.Cluster2); // d) Calculate the distance of the new cluster to all other clusters and save each as pair foreach (Cluster cluster in clusters) { ClusterPair pair = new ClusterPair(cluster, newCluster, cluster.CalculateDistance(newCluster)); pairs.AddPair(pair); } // e) Add the new cluster to clusters clusters.Add(newCluster); } return clusters.ToArray<Cluster>(); }
private UnitTestInfo[] GetTests(string path, string[] hintPaths) { var codeGenDllPath = Assembly.GetExecutingAssembly().Location; var codegenDir = Path.GetDirectoryName(codeGenDllPath); AppDomain loaderDomain = AppDomain.CreateDomain(path, AppDomain.CurrentDomain.Evidence, new AppDomainSetup() { ApplicationBase = codegenDir }); var loader = (TestAssemblyLoader)loaderDomain.CreateInstanceFromAndUnwrap(codeGenDllPath, typeof(TestAssemblyLoader).FullName); loader.InitializeLifetimeService(); HashSet<string> hints = new HashSet<string>(hintPaths) { Path.GetDirectoryName(path) }; loader.Load(path, hints.ToArray()); UnitTestInfo[] tests = loader.GetTests<XUnitTestDiscoverer>(); //if no xunit tests were discovered and the assembly is an exe treat as a standalone exe test if ((tests == null || tests.Length == 0) && Path.GetExtension(path).ToLowerInvariant() == ".exe") { tests = loader.GetTests<StandAloneTestDiscoverer>(); } AppDomain.Unload(loaderDomain); if (tests.Length > 0) { CodeGenOutput.Info($"{path}: {tests.Length} tests discovered"); } return tests; }
public static uint[] GetInstructionOffsets(MethodDef method, IList<MethodSourceStatement> list) { if (method == null) return null; var body = method.Body; if (body == null) return null; var foundInstrs = new HashSet<uint>(); // The instructions' offset field is assumed to be valid var instrs = body.Instructions.Select(a => a.Offset).ToArray(); foreach (var binSpan in list.Select(a => a.Statement.BinSpan)) { int index = Array.BinarySearch(instrs, binSpan.Start); if (index < 0) continue; for (int i = index; i < instrs.Length; i++) { uint instrOffset = instrs[i]; if (instrOffset >= binSpan.End) break; foundInstrs.Add(instrOffset); } } return foundInstrs.ToArray(); }
public void fun1() { Dictionary<int, char> dt1 = new Dictionary<int, char>(); dt1.Add(9, 'a'); dt1.Add(5, 'a'); dt1.Add(4, 'a'); foreach (KeyValuePair<int, char> kvp in dt1) { //Console.WriteLine("key ={0} value = {1}", kvp.Key, kvp.Value); } int[] arr = { 3, 1, 8 }; HashSet<int> hs = new HashSet<int>(arr); hs.Add(3); hs.Add(9); hs.Add(5); hs.Add(1); //hs.Add(1); //hs.Add(3); //hs.ExceptWith(arr); int[] arr1 = hs.ToArray(); // hs.IntersectWith(arr); hs.UnionWith(arr); //Console.WriteLine(hs.Max()); // Console.WriteLine(hs.Average()); foreach (int kvp in hs) { Console.WriteLine(kvp); } }
public static string[] Build(string solutionFile) { Console.Error.Write("// Building '{0}'... ", Path.GetFileName(solutionFile)); var pc = new ProjectCollection(); var parms = new BuildParameters(pc); var globalProperties = new Dictionary<string, string>(); var request = new BuildRequestData(solutionFile, globalProperties, null, new string[] { "Build" }, null); parms.Loggers = new[] { new ConsoleLogger(LoggerVerbosity.Quiet) }; var result = BuildManager.DefaultBuildManager.Build(parms, request); var resultFiles = new HashSet<string>(); Console.Error.WriteLine("done."); foreach (var kvp in result.ResultsByTarget) { var targetResult = kvp.Value; if (targetResult.Exception != null) Console.Error.WriteLine("// Compilation failed for target '{0}':\r\n{1}", kvp.Key, targetResult.Exception.Message); else { foreach (var filename in targetResult.Items) resultFiles.Add(filename.ItemSpec); } } return resultFiles.ToArray(); }
private void DistributeComunicatToAll(Comunicat item) { var connectedUsers = listaPolaczec.Keys; String[] oldBlackList = item.NotToUser; // dodajemu użytkowników do czarnej listy HashSet<string> newBlackList = new HashSet<string>(item.NotToUser); foreach(var user in listaPolaczec.Keys) { if(!newBlackList.Contains(user)) { newBlackList.Add(user); } } item.NotToUser = newBlackList.ToArray<String>(); // wysyłamy wiadomości do urzytkowników foreach(var user in listaPolaczec) { if(!oldBlackList.Contains(user.Key) && user.Key != UNKNOWN_USER) { foreach(var modul in user.Value) { modul.addComunicatToSend(item); } } } }
public Response.IResponse Execute( CommandArgs args ) { var pa = args.As<parentsArgs>(); if( string.IsNullOrWhiteSpace( pa.target ) ) return new Response.ErrorResponse( "target not specified" ); // get volume for our target var vol = _volumeManager.GetByHash( pa.target ); // try to get directory for our target var cwd = ( vol != null ? vol.GetDirectoryByHash( pa.target ) : null ); // if we still haven't got volume service, then something is wrong if( cwd == null || cwd.IsReadable.IsFalse() ) return new Response.ErrorResponse( "target dir not found or access denied" ); HashSet<Model.DirectoryModel> tree = new HashSet<Model.DirectoryModel>(); tree.Add( cwd ); var rootDir = vol.GetRootDirectory(); // now get parent untill we reach root while( cwd != null && cwd.Hash != rootDir.Hash ) { if( cwd.ParentHash == null ) break; var parentDir = vol.GetDirectoryByHash( cwd.ParentHash ); if( parentDir == null ) return new Response.ErrorResponse( "error getting parent dir: not found or access denied" ); tree.Add( parentDir ); var subDirs = vol.GetSubdirectoriesFlat( parentDir, 0 ); foreach( var sd in subDirs ) tree.Add( sd ); cwd = parentDir; } return new Response.TreeResponse( tree.ToArray() ); }
// get set of object name for subgoals public string[] GetSubgoalObjectNames(int index) { HashSet <string> objectNames = new HashSet <string>(); var names = GetSubgoalNames(index); if (names != null) { foreach (var subgoal in names) { foreach (var on in subgoalPool[subgoal]) { objectNames.Add(on); } } } return(objectNames?.ToArray()); }
public AllowedChildTagDescriptor Build() { var validationDiagnostics = Validate(); var diagnostics = new HashSet <RazorDiagnostic>(validationDiagnostics); if (_diagnostics != null) { diagnostics.UnionWith(_diagnostics); } var displayName = DisplayName ?? Name; var descriptor = new DefaultAllowedChildTagDescriptor( Name, displayName, diagnostics?.ToArray() ?? Array.Empty <RazorDiagnostic>()); return(descriptor); }
/// <exception cref="InvalidOperationException"> /// If the type of the `submetric` parameter is currently not supported. /// </exception> public LabeledMetricType( bool disabled, string category, Lifetime lifetime, string name, string[] sendInPings, T submetric, HashSet <string> labels = null ) { this.disabled = disabled; this.sendInPings = sendInPings; this.submetric = submetric; Func <string, string, string[], int, int, bool, string[], int, UInt64> metricTypeInstantiator; switch (submetric) { case BooleanMetricType _: metricTypeInstantiator = LibGleanFFI.glean_new_labeled_boolean_metric; break; case CounterMetricType _: metricTypeInstantiator = LibGleanFFI.glean_new_labeled_counter_metric; break; case StringMetricType _: metricTypeInstantiator = LibGleanFFI.glean_new_labeled_string_metric; break; default: throw new InvalidOperationException("Can not create a labeled version of this metric type"); } handle = metricTypeInstantiator( category, name, sendInPings, sendInPings.Length, (int)lifetime, disabled, labels?.ToArray(), (labels != null) ? labels.Count : 0); }
public RequiredAttributeDescriptor Build() { var validationDiagnostics = Validate(); var diagnostics = new HashSet <RazorDiagnostic>(validationDiagnostics); if (_diagnostics != null) { diagnostics.UnionWith(_diagnostics); } var displayName = NameComparisonMode == RequiredAttributeDescriptor.NameComparisonMode.PrefixMatch ? string.Concat(Name, "...") : Name; var rule = new DefaultRequiredAttributeDescriptor( Name, NameComparisonMode, Value, ValueComparisonMode, displayName, diagnostics?.ToArray() ?? Array.Empty <RazorDiagnostic>()); return(rule); }
public RequiredAttributeDescriptor Build() { var validationDiagnostics = Validate(); var diagnostics = new HashSet <RazorDiagnostic>(validationDiagnostics); if (_diagnostics != null) { diagnostics.UnionWith(_diagnostics); } var displayName = GetDisplayName(); var rule = new DefaultRequiredAttributeDescriptor( Name, NameComparisonMode, Value, ValueComparisonMode, displayName, diagnostics?.ToArray() ?? Array.Empty <RazorDiagnostic>(), new Dictionary <string, string>(Metadata)); return(rule); }
public IItemData[] ExtractItems(Guid rootId, string rootParentItemPath, Guid[] itemIds, IEnumerableFieldFilter fieldFilter) { lock (SyncLock) { var timer = new Stopwatch(); timer.Start(); var intersectedIgnoredFields = new HashSet <Guid>(); intersectedIgnoredFields.UnionWith(fieldFilter.Excludes); if (itemIds.Length == 0) { return(null); } using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["master"].ConnectionString)) { sqlConnection.Open(); using (var sqlCommand = ConstructSqlBatch(rootId, itemIds, intersectedIgnoredFields?.ToArray())) { sqlCommand.Connection = sqlConnection; using (var reader = sqlCommand.ExecuteReader()) { if (!Ingest(reader, rootParentItemPath)) { // TODO: Log error } } } } timer.Stop(); return(_itemsById.Values.ToArray() as IItemData[]); } }
public override void IndexDocuments( AbstractViewGenerator viewGenerator, IEnumerable <dynamic> documents, WorkContext context, IStorageActionsAccessor actions) { actions.Indexing.SetCurrentIndexStatsTo(name); try { var count = 0; Func <object, object> documentIdFetcher = null; var reduceKeys = new HashSet <string>(); var documentsWrapped = documents.Select(doc => { var documentId = doc.__document_id; foreach (var reduceKey in actions.MappedResults.DeleteMappedResultsForDocumentId((string)documentId, name)) { reduceKeys.Add(reduceKey); } return(doc); }); foreach (var doc in RobustEnumeration(documentsWrapped, viewGenerator.MapDefinition, actions, context)) { count++; documentIdFetcher = CreateDocumentIdFetcherIfNeeded(documentIdFetcher, doc); var docIdValue = documentIdFetcher(doc); if (docIdValue == null) { throw new InvalidOperationException("Could not find document id for this document"); } var reduceValue = viewGenerator.GroupByExtraction(doc); if (reduceValue == null) { log.DebugFormat("Field {0} is used as the reduce key and cannot be null, skipping document {1}", viewGenerator.GroupByExtraction, docIdValue); continue; } var reduceKey = ReduceKeyToString(reduceValue); var docId = docIdValue.ToString(); reduceKeys.Add(reduceKey); var data = GetMapedData(doc); log.DebugFormat("Mapped result for '{0}': '{1}'", name, data); var hash = ComputeHash(name, reduceKey); actions.MappedResults.PutMappedResult(name, docId, reduceKey, data, hash); actions.Indexing.IncrementSuccessIndexing(); } actions.Tasks.AddTask(new ReduceTask { Index = name, ReduceKeys = reduceKeys.ToArray() }); log.DebugFormat("Mapped {0} documents for {1}", count, name); } finally { actions.Indexing.FlushIndexStats(); } }
private NPath[] SetupIL2CPPConversion(NPath[] linkerOutputFiles, NPath il2cppdata_destinationdir) { var il2cpp = new DotNetAssembly( string.IsNullOrEmpty(CustomIL2CPPLocation) ? $"{EditorApplication.applicationContentsPath}/il2cpp/build/deploy/net471/il2cpp.exe" : $"{CustomIL2CPPLocation}/build/deploy/net471/il2cpp.exe", Framework.Framework471); var netCoreRunRuntime = DotNetRuntime.FindFor(il2cpp); //NetCoreRunRuntime.FromSteve; var il2cppProgram = new DotNetRunnableProgram(il2cpp, netCoreRunRuntime); var extraTypes = new HashSet <string>(); foreach (var extraType in PlayerBuildInterface.ExtraTypesProvider?.Invoke() ?? Array.Empty <string>()) { extraTypes.Add(extraType); } NPath extraTypesFile = Configuration.RootArtifactsPath.Combine("extra-types.txt").MakeAbsolute().WriteAllLines(extraTypes.ToArray()); NPath il2cppOutputDir = Configuration.RootArtifactsPath.Combine("il2cpp"); Backend.Current.AddAction("IL2CPP", Array.Empty <NPath>(), linkerOutputFiles .Concat(il2cpp.Path.Parent.Files()).Concat(netCoreRunRuntime.Inputs) .Concat(new[] { extraTypesFile }) .ToArray(), il2cppProgram.InvocationString, new[] { "--convert-to-cpp", "--emit-null-checks", "--enable-array-bounds-check", "--dotnetprofile=\"unityaot\"", "--libil2cpp-static", $"--extra-types-file={extraTypesFile.InQuotes()}", "--profiler-report", $"--generatedcppdir={il2cppOutputDir.InQuotes(SlashMode.Native)}", $"--directory={linkerOutputFiles.First().Parent.InQuotes(SlashMode.Native)}", }, targetDirectories: new[] { il2cppOutputDir }, allowUnwrittenOutputFiles: true); var il2cppOutputFiles = GuessTargetDirectoryContentsFor(il2cppOutputDir, "dummy.cpp"); var dataDir = il2cppOutputDir.Combine("Data"); foreach (var il2cppdatafile in dataDir.FilesIfExists(recurse: true)) { CopyTool.Instance().Setup(il2cppdata_destinationdir.Combine(il2cppdatafile.RelativeTo(dataDir)), il2cppdatafile); } return(il2cppOutputFiles); }
static void OnCompilationFinished(string assemblyPath, CompilerMessage[] messages) { // Do nothing if there were compile errors on the target if (CompilerMessagesContainError(messages)) { Debug.Log("Weaver: stop because compile errors on target"); return; } // Should not run on the editor only assemblies if (assemblyPath.Contains("-Editor") || assemblyPath.Contains(".Editor")) { return; } // don't weave mirror files string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath); if (assemblyName == MirrorRuntimeAssemblyName || assemblyName == MirrorWeaverAssemblyName) { return; } // find Mirror.dll string mirrorRuntimeDll = FindMirrorRuntime(); if (string.IsNullOrEmpty(mirrorRuntimeDll)) { Debug.LogError("Failed to find Mirror runtime assembly"); return; } if (!File.Exists(mirrorRuntimeDll)) { // this is normal, it happens with any assembly that is built before mirror // such as unity packages or your own assemblies // those don't need to be weaved // if any assembly depends on mirror, then it will be built after return; } // find UnityEngine.CoreModule.dll string unityEngineCoreModuleDLL = UnityEditorInternal.InternalEditorUtility.GetEngineCoreModuleAssemblyPath(); if (string.IsNullOrEmpty(unityEngineCoreModuleDLL)) { Debug.LogError("Failed to find UnityEngine assembly"); return; } // build directory list for later asm/symbol resolving using CompilationPipeline refs HashSet <string> dependencyPaths = new HashSet <string>(); dependencyPaths.Add(Path.GetDirectoryName(assemblyPath)); foreach (UnityAssembly unityAsm in CompilationPipeline.GetAssemblies()) { if (unityAsm.outputPath != assemblyPath) { continue; } foreach (string unityAsmRef in unityAsm.compiledAssemblyReferences) { dependencyPaths.Add(Path.GetDirectoryName(unityAsmRef)); } } // passing null in the outputDirectory param will do an in-place update of the assembly if (Program.Process(unityEngineCoreModuleDLL, mirrorRuntimeDll, null, new[] { assemblyPath }, dependencyPaths.ToArray(), HandleWarning, HandleError)) { // NOTE: WeaveFailed is critical for unit tests but isn't used elsewhere WeaveFailed = false; //Debug.Log("Weaving succeeded for: " + assemblyPath); } else { WeaveFailed = true; if (UnityLogEnabled) { Debug.LogError("Weaving failed for: " + assemblyPath); } } }
/// <summary> /// Gets the marketing lists. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="conditionOperator">Condition operator.</param> /// <param name="values">The values of the property.</param> /// <returns>The marketing lists.</returns> protected IEnumerable <list> GetMarketingLists(string propertyName, ConditionOperator conditionOperator, params object[] values) { var propertyConditionExpression = new ConditionExpression(); propertyConditionExpression.AttributeName = propertyName; propertyConditionExpression.Operator = conditionOperator; propertyConditionExpression.Values = values; var memberTypeConditionExpression = new ConditionExpression(); memberTypeConditionExpression.AttributeName = "membertype"; memberTypeConditionExpression.Operator = ConditionOperator.Equal; memberTypeConditionExpression.Values = new object[] { 2 }; var stateCodeConditionExpression = new ConditionExpression(); stateCodeConditionExpression.AttributeName = "statecode"; stateCodeConditionExpression.Operator = ConditionOperator.Equal; stateCodeConditionExpression.Values = new object[] { "Active" }; var filterExpression = new FilterExpression(); filterExpression.Conditions = new ConditionExpression[] { propertyConditionExpression, memberTypeConditionExpression, stateCodeConditionExpression }; filterExpression.FilterOperator = LogicalOperator.And; var pagingInfo = new PagingInfo { PageNumber = 1, Count = Configuration.Settings.FetchThrottlingPageSize }; var queryExpression = new QueryExpression(); queryExpression.PageInfo = pagingInfo; queryExpression.ColumnSet = new ColumnSet { Attributes = this.Attributes }; queryExpression.Criteria = filterExpression; queryExpression.EntityName = EntityName.list.ToString(); var returnValue = new HashSet <list>(new ListEqualityComparer()); try { while (true) { var entities = this.CrmService.RetrieveMultiple(queryExpression); if (entities == null) { break; } foreach (var list in entities.BusinessEntities.Cast <list>()) { returnValue.Add(list); } if (!entities.MoreRecords) { break; } pagingInfo.PageNumber++; pagingInfo.PagingCookie = entities.PagingCookie; } } catch (Exception e) { ConditionalLog.Error("Couldn't get the marketing list(s) from CRM.", e, this); } return(returnValue.ToArray()); }
public override void IndexDocuments( AbstractViewGenerator viewGenerator, IEnumerable <dynamic> documents, WorkContext context, IStorageActionsAccessor actions, DateTime minimumTimestamp) { actions.Indexing.SetCurrentIndexStatsTo(name); var count = 0; Func <object, object> documentIdFetcher = null; // we mark the reduce keys to delete when we delete the mapped results, then we remove // any reduce key that is actually being used to generate new mapped results // this way, only reduces that removed data will force us to use the tasks approach var reduceKeysToDelete = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase); var documentsWrapped = documents.Select(doc => { var documentId = doc.__document_id; foreach (var reduceKey in actions.MappedResults.DeleteMappedResultsForDocumentId((string)documentId, name)) { reduceKeysToDelete.Add(reduceKey); } return(doc); }); foreach (var doc in RobustEnumerationIndex(documentsWrapped, viewGenerator.MapDefinition, actions, context)) { count++; documentIdFetcher = CreateDocumentIdFetcherIfNeeded(documentIdFetcher, doc); var docIdValue = documentIdFetcher(doc); if (docIdValue == null) { throw new InvalidOperationException("Could not find document id for this document"); } var reduceValue = viewGenerator.GroupByExtraction(doc); if (reduceValue == null) { logIndexing.DebugFormat("Field {0} is used as the reduce key and cannot be null, skipping document {1}", viewGenerator.GroupByExtraction, docIdValue); continue; } var reduceKey = ReduceKeyToString(reduceValue); var docId = docIdValue.ToString(); reduceKeysToDelete.Remove((string)reduceKey); var data = GetMapedData(doc); logIndexing.DebugFormat("Mapped result for '{0}': '{1}'", name, data); var hash = ComputeHash(name, reduceKey); actions.MappedResults.PutMappedResult(name, docId, reduceKey, data, hash); actions.Indexing.IncrementSuccessIndexing(); } if (reduceKeysToDelete.Count > 0) { actions.Tasks.AddTask(new ReduceTask { Index = name, ReduceKeys = reduceKeysToDelete.ToArray() }, minimumTimestamp); } logIndexing.DebugFormat("Mapped {0} documents for {1}", count, name); }
public static MagicOnionServiceDefinition BuildServerServiceDefinition(IEnumerable <Type> targetTypes, MagicOnionOptions option) { option.RegisterOptionToServiceLocator(); var builder = ServerServiceDefinition.CreateBuilder(); var handlers = new HashSet <MethodHandler>(); var streamingHubHandlers = new List <StreamingHubHandler>(); var types = targetTypes .Where(x => typeof(IServiceMarker).IsAssignableFrom(x)) .Where(x => !x.GetTypeInfo().IsAbstract) .Where(x => x.GetCustomAttribute <IgnoreAttribute>(false) == null) .Concat(SupplyEmbeddedServices(option)) .ToArray(); option.MagicOnionLogger.BeginBuildServiceDefinition(); var sw = Stopwatch.StartNew(); try { Parallel.ForEach(types, /* new ParallelOptions { MaxDegreeOfParallelism = 1 }, */ classType => { var className = classType.Name; if (!classType.GetConstructors().Any(x => x.GetParameters().Length == 0)) { // supports paramaterless constructor after v2.1(DI support). // throw new InvalidOperationException(string.Format("Type needs parameterless constructor, class:{0}", classType.FullName)); } var isStreamingHub = typeof(IStreamingHubMarker).IsAssignableFrom(classType); HashSet <StreamingHubHandler> tempStreamingHubHandlers = null; if (isStreamingHub) { tempStreamingHubHandlers = new HashSet <StreamingHubHandler>(); } var inheritInterface = classType.GetInterfaces() .First(x => x.IsGenericType && x.GetGenericTypeDefinition() == (isStreamingHub ? typeof(IStreamingHub <,>) : typeof(IService <>))) .GenericTypeArguments[0]; var interfaceMap = classType.GetInterfaceMap(inheritInterface); for (int i = 0; i < interfaceMap.TargetMethods.Length; ++i) { var methodInfo = interfaceMap.TargetMethods[i]; var methodName = interfaceMap.InterfaceMethods[i].Name; if (methodInfo.IsSpecialName && (methodInfo.Name.StartsWith("set_") || methodInfo.Name.StartsWith("get_"))) { continue; } if (methodInfo.GetCustomAttribute <IgnoreAttribute>(false) != null) { continue; // ignore } // ignore default methods if (methodName == "Equals" || methodName == "GetHashCode" || methodName == "GetType" || methodName == "ToString" || methodName == "WithOptions" || methodName == "WithHeaders" || methodName == "WithDeadline" || methodName == "WithCancellationToken" || methodName == "WithHost" ) { continue; } // register for StreamingHub if (isStreamingHub && methodName != "Connect") { var streamingHandler = new StreamingHubHandler(option, classType, methodInfo); if (!tempStreamingHubHandlers.Add(streamingHandler)) { throw new InvalidOperationException($"Method does not allow overload, {className}.{methodName}"); } continue; } else { // create handler var handler = new MethodHandler(option, classType, methodInfo, methodName); lock (builder) { if (!handlers.Add(handler)) { throw new InvalidOperationException($"Method does not allow overload, {className}.{methodName}"); } handler.RegisterHandler(builder); } } } if (isStreamingHub) { var connectHandler = new MethodHandler(option, classType, classType.GetMethod("Connect"), "Connect"); lock (builder) { if (!handlers.Add(connectHandler)) { throw new InvalidOperationException($"Method does not allow overload, {className}.Connect"); } connectHandler.RegisterHandler(builder); } lock (streamingHubHandlers) { streamingHubHandlers.AddRange(tempStreamingHubHandlers); StreamingHubHandlerRepository.RegisterHandler(connectHandler, tempStreamingHubHandlers.ToArray()); IGroupRepositoryFactory factory; var attr = classType.GetCustomAttribute <GroupConfigurationAttribute>(true); if (attr != null) { factory = attr.Create(); } else { factory = option.DefaultGroupRepositoryFactory; } StreamingHubHandlerRepository.AddGroupRepository(connectHandler, factory.CreateRepository(option.ServiceLocator)); } } }); } catch (AggregateException agex) { ExceptionDispatchInfo.Capture(agex.InnerExceptions[0]).Throw(); } var result = new MagicOnionServiceDefinition(builder.Build(), handlers.ToArray(), streamingHubHandlers.ToArray()); sw.Stop(); option.MagicOnionLogger.EndBuildServiceDefinition(sw.Elapsed.TotalMilliseconds); return(result); }
public static string Stringified<T>(this HashSet<T> self, string delimiter = null) { return self.ToArray().Stringified(delimiter); }
protected override async Task <IEnumerable <RuleDescriptor> > LoadDescriptorsAsync() { var language = _services.WorkContext.WorkingLanguage; var oneStarStr = T("Search.Facet.1StarAndMore").Value; var xStarsStr = T("Search.Facet.XStarsAndMore").Value; var stores = _services.StoreContext.GetAllStores() .Select(x => new RuleValueSelectListOption { Value = x.Id.ToString(), Text = x.Name }) .ToArray(); var visibilities = await((ProductVisibility[])Enum.GetValues(typeof(ProductVisibility))) .SelectAsync(async x => new RuleValueSelectListOption { Value = ((int)x).ToString(), Text = await _localizationService.GetLocalizedEnumAsync(x) }) .ToArrayAsync(); var productTypes = await((ProductType[])Enum.GetValues(typeof(ProductType))) .SelectAsync(async x => new RuleValueSelectListOption { Value = ((int)x).ToString(), Text = await _localizationService.GetLocalizedEnumAsync(x) }) .ToArrayAsync(); var ratings = FacetUtility.GetRatings() .Reverse() .Skip(1) .Select(x => new RuleValueSelectListOption { Value = ((double)x.Value).ToString(CultureInfo.InvariantCulture), Text = (double)x.Value == 1 ? oneStarStr : xStarsStr.FormatInvariant(x.Value) }) .ToArray(); var categoryTree = _catalogSettings.ShowProductsFromSubcategories ? await _categoryService.GetCategoryTreeAsync(includeHidden : true) : null; #region Special filters CatalogSearchQuery categoryFilter(SearchFilterContext ctx, int[] x) { if (x?.Any() ?? false) { var ids = new HashSet <int>(x); if (_catalogSettings.ShowProductsFromSubcategories) { foreach (var id in x) { var node = categoryTree.SelectNodeById(id); if (node != null) { ids.AddRange(node.Flatten(false).Select(y => y.Id)); } } } return(ctx.Query.WithCategoryIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? (bool?)null : false, ids.ToArray())); } return(ctx.Query); }; CatalogSearchQuery stockQuantityFilter(SearchFilterContext ctx, int x) { if (ctx.Expression.Operator == RuleOperator.IsEqualTo || ctx.Expression.Operator == RuleOperator.IsNotEqualTo) { return(ctx.Query.WithStockQuantity(x, x, ctx.Expression.Operator == RuleOperator.IsEqualTo, ctx.Expression.Operator == RuleOperator.IsEqualTo)); } else if (ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo || ctx.Expression.Operator == RuleOperator.GreaterThan) { return(ctx.Query.WithStockQuantity(x, null, ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo, null)); } else if (ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo || ctx.Expression.Operator == RuleOperator.LessThan) { return(ctx.Query.WithStockQuantity(null, x, null, ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo)); } return(ctx.Query); }; CatalogSearchQuery priceFilter(SearchFilterContext ctx, decimal x) { if (ctx.Expression.Operator == RuleOperator.IsEqualTo || ctx.Expression.Operator == RuleOperator.IsNotEqualTo) { return(ctx.Query.PriceBetween(x, x, ctx.Expression.Operator == RuleOperator.IsEqualTo, ctx.Expression.Operator == RuleOperator.IsEqualTo)); } else if (ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo || ctx.Expression.Operator == RuleOperator.GreaterThan) { return(ctx.Query.PriceBetween(x, null, ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo, null)); } else if (ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo || ctx.Expression.Operator == RuleOperator.LessThan) { return(ctx.Query.PriceBetween(null, x, null, ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo)); } return(ctx.Query); }; CatalogSearchQuery createdFilter(SearchFilterContext ctx, DateTime x) { if (ctx.Expression.Operator == RuleOperator.IsEqualTo || ctx.Expression.Operator == RuleOperator.IsNotEqualTo) { return(ctx.Query.CreatedBetween(x, x, ctx.Expression.Operator == RuleOperator.IsEqualTo, ctx.Expression.Operator == RuleOperator.IsEqualTo)); } else if (ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo || ctx.Expression.Operator == RuleOperator.GreaterThan) { return(ctx.Query.CreatedBetween(x, null, ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo, null)); } else if (ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo || ctx.Expression.Operator == RuleOperator.LessThan) { return(ctx.Query.CreatedBetween(null, x, null, ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo)); } return(ctx.Query); }; #endregion var descriptors = new List <SearchFilterDescriptor> { new SearchFilterDescriptor <int>((ctx, x) => ctx.Query.HasStoreId(x)) { Name = "Store", DisplayName = T("Admin.Rules.FilterDescriptor.Store"), RuleType = RuleType.Int, SelectList = new LocalRuleValueSelectList(stores), Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.AllowedCustomerRoles(x)) { Name = "CustomerRole", DisplayName = T("Admin.Rules.FilterDescriptor.IsInCustomerRole"), RuleType = RuleType.IntArray, SelectList = new RemoteRuleValueSelectList("CustomerRole") { Multiple = true }, Operators = new RuleOperator[] { RuleOperator.In } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.PublishedOnly(x)) { Name = "Published", DisplayName = T("Admin.Catalog.Products.Fields.Published"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.AvailableOnly(x)) { Name = "AvailableByStock", DisplayName = T("Products.Availability.InStock"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.AvailableByDate(x)) { Name = "AvailableByDate", DisplayName = T("Admin.Rules.FilterDescriptor.AvailableByDate"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <int>((ctx, x) => ctx.Query.WithVisibility((ProductVisibility)x)) { Name = "Visibility", DisplayName = T("Admin.Catalog.Products.Fields.Visibility"), RuleType = RuleType.Int, SelectList = new LocalRuleValueSelectList(visibilities), Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithProductIds(x)) { Name = "Product", DisplayName = T("Common.Entity.Product"), RuleType = RuleType.IntArray, SelectList = new RemoteRuleValueSelectList("Product") { Multiple = true }, Operators = new RuleOperator[] { RuleOperator.In } }, new SearchFilterDescriptor <int>((ctx, x) => ctx.Query.IsProductType((ProductType)x)) { Name = "ProductType", DisplayName = T("Admin.Catalog.Products.Fields.ProductType"), RuleType = RuleType.Int, SelectList = new LocalRuleValueSelectList(productTypes), Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <int[]>(categoryFilter) { Name = "Category", DisplayName = T("Common.Entity.Category"), RuleType = RuleType.IntArray, SelectList = new RemoteRuleValueSelectList("Category") { Multiple = true }, Operators = new RuleOperator[] { RuleOperator.In } }, new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithManufacturerIds(null, x)) { Name = "Manufacturer", DisplayName = T("Common.Entity.Manufacturer"), RuleType = RuleType.IntArray, SelectList = new RemoteRuleValueSelectList("Manufacturer") { Multiple = true }, Operators = new RuleOperator[] { RuleOperator.In } }, // Same logic as the filter above product list. new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.HasAnyCategory(!x)) { Name = "WithoutCategory", DisplayName = T("Admin.Catalog.Products.List.SearchWithoutCategories"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.HasAnyManufacturer(!x)) { Name = "WithoutManufacturer", DisplayName = T("Admin.Catalog.Products.List.SearchWithoutManufacturers"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithProductTagIds(x)) { Name = "ProductTag", DisplayName = T("Admin.Catalog.Products.Fields.ProductTags"), RuleType = RuleType.IntArray, SelectList = new RemoteRuleValueSelectList("ProductTag") { Multiple = true }, Operators = new RuleOperator[] { RuleOperator.In } }, new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithDeliveryTimeIds(x)) { Name = "DeliveryTime", DisplayName = T("Admin.Catalog.Products.Fields.DeliveryTime"), RuleType = RuleType.IntArray, Operators = new RuleOperator[] { RuleOperator.In }, SelectList = new RemoteRuleValueSelectList("DeliveryTime") { Multiple = true } }, new SearchFilterDescriptor <int>(stockQuantityFilter) { Name = "StockQuantity", DisplayName = T("Admin.Catalog.Products.Fields.StockQuantity"), RuleType = RuleType.Int }, new SearchFilterDescriptor <decimal>(priceFilter) { Name = "Price", DisplayName = T("Admin.Catalog.Products.Fields.Price"), RuleType = RuleType.Money }, new SearchFilterDescriptor <DateTime>(createdFilter) { Name = "CreatedOn", DisplayName = T("Common.CreatedOn"), RuleType = RuleType.DateTime }, new SearchFilterDescriptor <double>((ctx, x) => ctx.Query.WithRating(x, null)) { Name = "Rating", DisplayName = T("Admin.Catalog.ProductReviews.Fields.Rating"), RuleType = RuleType.Float, Operators = new RuleOperator[] { RuleOperator.GreaterThanOrEqualTo }, SelectList = new LocalRuleValueSelectList(ratings) }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.HomePageProductsOnly(x)) { Name = "HomepageProduct", DisplayName = T("Admin.Catalog.Products.Fields.ShowOnHomePage"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.DownloadOnly(x)) { Name = "Download", DisplayName = T("Admin.Catalog.Products.Fields.IsDownload"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.RecurringOnly(x)) { Name = "Recurring", DisplayName = T("Admin.Catalog.Products.Fields.IsRecurring"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.ShipEnabledOnly(x)) { Name = "ShipEnabled", DisplayName = T("Admin.Catalog.Products.Fields.IsShipEnabled"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.FreeShippingOnly(x)) { Name = "FreeShipping", DisplayName = T("Admin.Catalog.Products.Fields.IsFreeShipping"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.TaxExemptOnly(x)) { Name = "TaxExempt", DisplayName = T("Admin.Catalog.Products.Fields.IsTaxExempt"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.EsdOnly(x)) { Name = "Esd", DisplayName = T("Admin.Catalog.Products.Fields.IsEsd"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } }, new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.HasDiscount(x)) { Name = "Discount", DisplayName = T("Admin.Catalog.Products.Fields.HasDiscountsApplied"), RuleType = RuleType.Boolean, Operators = new RuleOperator[] { RuleOperator.IsEqualTo } } }; if (_services.ApplicationContext.ModuleCatalog.GetModuleByName("SmartStore.MegaSearchPlus") != null) { ISearchFilter[] filters(string fieldName, int parentId, int[] valueIds) { return(valueIds.Select(id => SearchFilter.ByField(fieldName, id).ExactMatch().NotAnalyzed().HasParent(parentId)).ToArray()); } // Sort by display order! var pageIndex = -1; var variantsQuery = _services.DbContext.ProductAttributes .AsNoTracking() .Where(x => x.AllowFiltering) .OrderBy(x => x.DisplayOrder); while (true) { var variants = await variantsQuery.ToPagedList(++pageIndex, 1000).LoadAsync(); foreach (var variant in variants) { var descriptor = new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithFilter(SearchFilter.Combined(filters("variantvalueid", variant.Id, x)))) { Name = $"Variant{variant.Id}", DisplayName = variant.GetLocalized(x => x.Name, language, true, false), GroupKey = "Admin.Catalog.Attributes.ProductAttributes", RuleType = RuleType.IntArray, SelectList = new RemoteRuleValueSelectList("VariantValue") { Multiple = true }, Operators = new RuleOperator[] { RuleOperator.In } }; descriptor.Metadata["ParentId"] = variant.Id; descriptors.Add(descriptor); } if (!variants.HasNextPage) { break; } } pageIndex = -1; var attributesQuery = _services.DbContext.SpecificationAttributes .AsNoTracking() .Where(x => x.AllowFiltering) .OrderBy(x => x.DisplayOrder); while (true) { var attributes = await attributesQuery.ToPagedList(++pageIndex, 1000).LoadAsync(); foreach (var attribute in attributes) { var descriptor = new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithFilter(SearchFilter.Combined(filters("attrvalueid", attribute.Id, x)))) { Name = $"Attribute{attribute.Id}", DisplayName = attribute.GetLocalized(x => x.Name, language, true, false), GroupKey = "Admin.Catalog.Attributes.SpecificationAttributes", RuleType = RuleType.IntArray, SelectList = new RemoteRuleValueSelectList("AttributeOption") { Multiple = true }, Operators = new RuleOperator[] { RuleOperator.In } }; descriptor.Metadata["ParentId"] = attribute.Id; descriptors.Add(descriptor); } if (!attributes.HasNextPage) { break; } } } descriptors .Where(x => x.RuleType == RuleType.Money) .Each(x => x.Metadata["postfix"] = _services.StoreContext.CurrentStore.PrimaryStoreCurrency.CurrencyCode); return(descriptors.Cast <RuleDescriptor>()); }
//--- Methods --- // Note (arnec): this call is not threadsafe, since QueryTermParser keeps state in the instance, which is why // it is not used by itself but embedded in SearchQueryParser public IEnumerable <QueryTerm> GetQueryTerms(string rawQuery, bool abortOnLuceneConstruct) { _abortOnLuceneConstruct = abortOnLuceneConstruct; _inQuote = _escaping = false; _escapedTerm.Length = 0; _normalizedTerm.Length = 0; _leadingOperator = char.MinValue; _terms.Clear(); for (var i = 0; i < rawQuery.Length; i++) { var c = rawQuery[i]; if (_escaping) { _escaping = false; } else { switch (c) { // quote case '"': if (!_inQuote) { if (IsTermStart) { // start of quoted term _inQuote = true; continue; } // quote in middle of unquoted term, throw throw new FormatException(string.Format("Quote in middle of unquoted term: {0}", _escapedTerm)); } if (i < rawQuery.Length - 1) { i++; var c2 = rawQuery[i]; if (!char.IsWhiteSpace(c2)) { if (_abortOnLuceneConstruct) { // might be legal in lucene, i.e. term followed by range, boost, etc. return(null); } // badly ended quoted term throw new FormatException(string.Format("Unescaped quote in middle of quoted term: \"{0}", _escapedTerm)); } } if (!BuildTerm()) { return(null); } continue; // possible inclusion or exclusion operator case '+': case '-': if (_inQuote) { EscapeCharacter(); break; } if (_leadingOperator == char.MinValue && IsTermStart && !HasFieldPrefix) { // capture operator _leadingOperator = c; continue; } EscapeCharacter(); break; // special characters case '!': case '(': case ')': case '{': case '}': case '[': case ']': case '^': case '~': if (!_inQuote && abortOnLuceneConstruct) { return(null); } EscapeCharacter(); break; // wild cards case '*': case '?': if (_inQuote) { EscapeCharacter(); } break; // possible field separator case ':': if (_inQuote) { EscapeCharacter(); } else if (HasFieldPrefix) { EscapeCharacter(); } else if (IsTermStart) { if (abortOnLuceneConstruct) { return(null); } EscapeCharacter(); } else { _escapedField = _escapedTerm.ToString(); _normalizedField = _normalizedTerm.ToString(); if (_knownFields.Contains(_escapedField) || _escapedField.Contains("#")) { _escapedTerm.Length = 0; _normalizedTerm.Length = 0; continue; } _escapedField = _normalizedField = null; EscapeCharacter(); } break; // possible escaped sequence case '\\': _escapedTerm.Append('\\'); _escaping = true; continue; // everything else default: if (!_inQuote && char.IsWhiteSpace(c)) { if (!BuildTerm()) { return(null); } continue; } if (_inQuote && char.IsWhiteSpace(c)) { EscapeCharacter(); } break; } } _escapedTerm.Append(c); _normalizedTerm.Append(c); } if (_inQuote) { throw new FormatException(string.Format("Unclosed quote on quoted term term: \"{0}", _escapedTerm)); } return(!BuildTerm() ? null : _terms.ToArray()); }
public string[] GetTagsList() { return(_tags?.ToArray()); }
internal CompiledIndexField[] GetReduceFieldsNames() { if (_groupByFields != null) { return(_groupByFields); } var ast = Key.FunctionDeclaration; var body = ast.ChildNodes.ToList(); if (body.Count != 2) { throw new InvalidOperationException($"Was requested to get reduce fields from a scripted function in an unexpected format, expected a single return statement got {body.Count}."); } var parameters = ast.Params; if (parameters.Count != 1) { throw new InvalidOperationException($"Was requested to get reduce fields from a scripted function in an unexpected format, expected a single argument but got {parameters.Count}."); } if (parameters[0] is Identifier == false) { throw new InvalidOperationException($"Was requested to get reduce fields from a scripted function in an unexpected format, expected a single argument of type 'Identifier' but got {parameters[0].GetType().Name}."); } var actualBody = body[1]; switch (actualBody) { case StaticMemberExpression sme: if (sme.Property is Identifier id) { _groupByFields = new[] { CreateField(id.Name, GetPropertyPath(sme).ToArray()) }; _singleField = true; return(_groupByFields); } throw new InvalidOperationException($"Was requested to get reduce fields from a scripted function in an unexpected format, expected a single return object expression statement got a statement of type {actualBody.GetType().Name}."); case ObjectExpression oe: var cur = new HashSet <CompiledIndexField>(); foreach (var prop in oe.Properties) { if (prop is Property property) { string[] path = null; if (property.Value is MemberExpression me) { path = GetPropertyPath(me).ToArray(); } var propertyName = property.GetKey(Engine); cur.Add(CreateField(propertyName.AsString(), path)); } } _groupByFields = cur.ToArray(); return(_groupByFields); default: throw new InvalidOperationException($"Unknown body type: {actualBody.GetType().Name}"); } CompiledIndexField CreateField(string propertyName, string[] path) { if (path == null || path.Length <= 1) { return(new SimpleField(propertyName)); } return(new JsNestedField(propertyName, path[0], path.Skip(1).ToArray())); } IEnumerable <string> GetPropertyPath(MemberExpression e) { if (e.Object is MemberExpression inner) { foreach (var path in GetPropertyPath(inner)) { yield return(path); } } if (e.Property is Identifier identifier) { yield return(identifier.Name); } } }
/// <summary> /// Raytrace the specified x0, y0, x1 and y1. /// </summary> /// <returns>The raytrace.</returns> /// <param name="x0">X0.</param> /// <remarks>From http://playtechs.blogspot.ca/2007/03/raytracing-on-grid.html</remarks> public static IEnumerable <GridPoint> raytrace(double x0, double y0, double x1, double y1) { double dx = Math.Abs(x1 - x0); double dy = Math.Abs(y1 - y0); int x = (int)(Math.Floor(x0)); int y = (int)(Math.Floor(y0)); int n = 1; int x_inc, y_inc; double error; HashSet <GridPoint> hs = new HashSet <GridPoint>(); if (dx == 0) { x_inc = 0; error = double.PositiveInfinity; } else if (x1 > x0) { x_inc = 1; n += (int)(Math.Floor(x1)) - x; error = (Math.Floor(x0) + 1 - x0) * dy; } else { x_inc = -1; n += x - (int)(Math.Floor(x1)); error = (x0 - Math.Floor(x0)) * dy; } if (dy == 0) { y_inc = 0; error -= double.PositiveInfinity; } else if (y1 > y0) { y_inc = 1; n += (int)(Math.Floor(y1)) - y; error -= (Math.Floor(y0) + 1 - y0) * dx; } else { y_inc = -1; n += y - (int)(Math.Floor(y1)); error -= (y0 - Math.Floor(y0)) * dx; } for (; n > 0; --n) { hs.Add(new Game.GridPoint(x, y)); if (error > 0) { y += y_inc; error -= dx; } else { x += x_inc; error += dy; } } return(hs.ToArray()); }
// the actual download method // async Task<string> DownloadNextPageAsync(string url) { ... } // the actual process methods // void ProcessResults(string data) { ... } // download and process all pages async Task DownloadAndProcessAllAsync( string startUrl, int maxDownloads, int maxProcesses) { // max parallel downloads SemaphoreSlim downloadSemaphore = new SemaphoreSlim(maxDownloads); // max parallel processing tasks SemaphoreSlim processSemaphore = new SemaphoreSlim(maxProcesses); var tasks = new HashSet <Task>(); var complete = false; var protect = new Object(); // protect tasks var page = 0; // do the page Func <string, Task> doPageAsync = async(url) => { bool downloadSemaphoreAcquired = true; try { // download the page var data = await DownloadNextPageAsync( url).ConfigureAwait(false); if (String.IsNullOrEmpty(data)) { Volatile.Write(ref complete, true); } else { // enable the next download to happen downloadSemaphore.Release(); downloadSemaphoreAcquired = false; // process this download await processSemaphore.WaitAsync(); try { await Task.Run(() => ProcessResults(data)); } finally { processSemaphore.Release(); } } } catch (Exception) { Volatile.Write(ref complete, true); throw; } finally { if (downloadSemaphoreAcquired) { downloadSemaphore.Release(); } } }; // do the page and save the task Func <string, Task> queuePageAsync = async(url) => { var task = doPageAsync(url); lock (protect) tasks.Add(task); await task; lock (protect) tasks.Remove(task); }; while (!Volatile.Read(ref complete)) { page++; // acquire download semaphore synchrnously await downloadSemaphore.WaitAsync(); // do the page var task = queuePageAsync(startUrl + "?page=" + page); } // await completion of the pending tasks Task[] pendingTasks; lock (protect) pendingTasks = tasks.ToArray(); await Task.WhenAll(pendingTasks); }
public override Parser Create() => new TokenParser(ValidType, Factory, ValidValues?.ToArray());
public static void CheckModsVisibility() { HashSet <string> compilerOpLines = new HashSet <string>(); System.Xml.Linq.XDocument linkxml = new System.Xml.Linq.XDocument(); var flags = new HashSet <string>(ResManager.PreRuntimeDFlags); var mods = GetAllModsOrPackages(); for (int i = 0; i < mods.Length; ++i) { var mod = mods[i]; if (!IsModOptional(mod) || flags.Contains(mod)) { // enable string defpath; bool defPathExists = false; var pdir = GetModRootInPackage(mod); if (!string.IsNullOrEmpty(pdir)) { defpath = pdir + "/mcs.rsp"; if (defPathExists = System.IO.File.Exists(defpath)) { var pname = GetPackageName(mod); compilerOpLines.Add("-define:MOD_" + pname.ToUpper().Replace(".", "_")); } else { defpath = "Assets/Mods/" + mod + "/Link/mcs.rsp"; } } else { defpath = "Assets/Mods/" + mod + "/Link/mcs.rsp"; } if (defPathExists || System.IO.File.Exists(defpath)) { compilerOpLines.Add("-define:MOD_" + mod.ToUpper().Replace(".", "_")); try { compilerOpLines.UnionWith(System.IO.File.ReadAllLines(defpath)); } catch (Exception e) { Debug.LogException(e); } } string linkxmlpath; bool linkxmlPathExists = false; if (!string.IsNullOrEmpty(pdir)) { linkxmlpath = pdir + "/link.xml"; if (linkxmlPathExists = System.IO.File.Exists(linkxmlpath)) { } else { linkxmlpath = "Assets/Mods/" + mod + "/Link/link.xml"; } } else { linkxmlpath = "Assets/Mods/" + mod + "/Link/link.xml"; } if (linkxmlPathExists || System.IO.File.Exists(linkxmlpath)) { CapsEditorUtils.MergeXml(linkxml, linkxmlpath); } CapsEditorUtils.UnhideFile("Assets/Mods/" + mod); if (System.IO.File.Exists("Assets/Mods/" + mod + ".meta")) { CapsEditorUtils.UnhideFile("Assets/Mods/" + mod + ".meta"); } foreach (var sdir in UniqueSpecialFolders) { var moddir = "Assets/" + sdir + "/Mods/" + mod; if (System.IO.Directory.Exists(moddir)) { CapsEditorUtils.UnhideFile(moddir); if (System.IO.File.Exists(moddir + ".meta")) { CapsEditorUtils.UnhideFile(moddir + ".meta"); } } } } else { // disable CapsEditorUtils.HideFile("Assets/Mods/" + mod); if (System.IO.File.Exists("Assets/Mods/" + mod + ".meta")) { System.IO.File.Delete("Assets/Mods/" + mod + ".meta"); } foreach (var sdir in UniqueSpecialFolders) { var moddir = "Assets/" + sdir + "/Mods/" + mod; if (System.IO.Directory.Exists(moddir)) { CapsEditorUtils.HideFile(moddir); if (System.IO.File.Exists(moddir + ".meta")) { System.IO.File.Delete(moddir + ".meta"); } } } } } if (linkxml.Root != null) { linkxml.Save("Assets/link.xml"); } else { System.IO.File.Delete("Assets/link.xml"); } compilerOpLines.Remove(""); HashSet <string> existCompilerOpLines = new HashSet <string>(); if (System.IO.File.Exists("Assets/mcs.rsp")) { try { existCompilerOpLines.UnionWith(System.IO.File.ReadAllLines("Assets/mcs.rsp")); existCompilerOpLines.Remove(""); } catch (Exception e) { Debug.LogException(e); } } bool hasdiff = true; if (existCompilerOpLines.Count == compilerOpLines.Count) { var diff = new HashSet <string>(compilerOpLines); diff.ExceptWith(existCompilerOpLines); hasdiff = diff.Count > 0; } if (hasdiff) { if (System.IO.File.Exists("Assets/mcs.rsp")) { System.IO.File.Delete("Assets/mcs.rsp"); } if (System.IO.File.Exists("Assets/csc.rsp")) { System.IO.File.Delete("Assets/csc.rsp"); } var lines = compilerOpLines.ToArray(); Array.Sort(lines); System.IO.File.WriteAllLines("Assets/mcs.rsp", lines); System.IO.File.WriteAllLines("Assets/csc.rsp", lines); AssetDatabase.ImportAsset("Assets/mcs.rsp"); AssetDatabase.ImportAsset("Assets/csc.rsp"); EditorApplication.LockReloadAssemblies(); try { AssetDatabase.ImportAsset(CapsEditorUtils.__ASSET__, ImportAssetOptions.ForceUpdate); } catch { } AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(ScriptableObject.CreateInstance <CapsModDesc>())), ImportAssetOptions.ForceUpdate); // Update all package... //foreach (var kvp in _PackageName2ModName) //{ // var pname = kvp.Key; // AssetDatabase.ImportAsset("Packages/" + pname, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ImportRecursive); //} ReimportAllAssemblyDefinitions(); EditorApplication.UnlockReloadAssemblies(); } AssetDatabase.Refresh(); }
public void DownloadTrainsProblemsTest() { HashSet <UInt64> arguments = new HashSet <UInt64>(); arguments.Add(UInt64.MaxValue); arguments.Add(UInt64.MinValue); for (long i = -1; i <= 100; ++i) { arguments.Add((ulong)i); } Random rnd = new Random(Environment.TickCount); while (arguments.Count < 255) { arguments.Add((((ulong)rnd.Next()) << 32) + ((ulong)rnd.Next())); } ProblemsReader source = new ProblemsReader() { ProblemsFilename = @"..\..\..\..\problems.txt", ProblemsResultsPath = @"..\..\..\..\problems-results\", TrainProblemsPath = @"..\..\..\..\problems-samples\", TrainProblemsResultsPath = @"..\..\..\..\problems-samples\" }; ProblemsMiner miner = new ProblemsMiner(source); //miner.DownloadTrainProblemsResults(true, arguments.ToArray()); miner.DownloadTrainProblemsResults(source.ReadProblems().Where(p => p.Size > 12).ToArray(), true, arguments.ToArray()); }
/// <summary> /// Gets the type tags. /// </summary> /// <returns>The type tags.</returns> public string[] GetTypeTags() { return(typeTags.ToArray()); }
private static ServicePlan Compile(Dictionary <MethodInfo, MethodCallExpression> expressions, object serviceObject) { // step: collect all types, methods, variables referenced in this expression var workerQueue = new Queue <KeyValuePair <MethodInfo, MethodCallExpression> >(); foreach (var exp in expressions) { workerQueue.Enqueue(new KeyValuePair <MethodInfo, MethodCallExpression>(exp.Key, exp.Value)); } var contexts = new Dictionary <MethodInfo, QueryContext>(); while (workerQueue.Count > 0) { var exp = workerQueue.Dequeue(); var context = new QueryContext(serviceObject, exp.Value, exp.Key.Name); context.Collect(); contexts.Add(exp.Key, context); foreach (var s in context.ExternalComposedSerivce.Where(s => !contexts.ContainsKey(s.Key))) { workerQueue.Enqueue(new KeyValuePair <MethodInfo, MethodCallExpression>(s.Key, s.Value)); } } // step: prepare service plan var codeGenerator = new CodeGenerator(); var name = serviceObject.GetType().Name + "." + codeGenerator.AppId; var plan = new ServicePlan { DependentServices = contexts .SelectMany(c => c.Value.Services.Select(r => r.Value)) .DistinctBy(s => s.URL) .ToArray(), Package = new ServicePackage() }; SystemHelper.CreateOrCleanDirectory(name); // step: generate composed service code var sources = new HashSet <string>(); var libs = new HashSet <string>(); var dir = name + ".Source"; SystemHelper.CreateOrCleanDirectory(dir); libs.Add(Path.Combine(Environment.GetEnvironmentVariable("DSN_ROOT"), "lib", "dsn.dev.csharp.dll")); libs.Add(Path.Combine(Environment.GetEnvironmentVariable("DSN_ROOT"), "lib", "Thrift.dll")); var code = codeGenerator.BuildRdsn(serviceObject.GetType(), contexts.Select(c => c.Value).ToArray()); SystemHelper.StringToFile(code, Path.Combine(dir, name + ".cs")); sources.Add(Path.Combine(dir, name + ".cs")); libs.UnionWith(QueryContext.KnownLibs); // step: generate client code for all dependent services foreach (var s in contexts .SelectMany(c => c.Value.Services.Select(r => r.Value)) .DistinctBy(s => s.PackageName) .Select(s => s.ExtractSpec())) { var provider = SpecProviderManager.Instance().GetProvider(s.SType); Trace.Assert(null != provider, "Language provider missing for type " + s.SType); LinkageInfo linkInfo; var err = provider.GenerateServiceClient(s, dir, ClientLanguage.Client_CSharp, ClientPlatform.Windows, out linkInfo); Trace.Assert(FlowErrorCode.Success == err); sources.UnionWith(linkInfo.Sources); libs.UnionWith(linkInfo.DynamicLibraries); } // step: fill service plan plan.Package.Spec = new ServiceSpec { SType = ServiceSpecType.thrift, MainSpecFile = serviceObject.GetType().Name + ".thrift", ReferencedSpecFiles = plan.DependentServices .DistinctBy(s => s.PackageName) .Where(s => s.Spec.SType == ServiceSpecType.thrift) .SelectMany(s => { var spec = s.ExtractSpec(); var specFiles = new List <string> { spec.MainSpecFile }; SystemHelper.SafeCopy(Path.Combine(spec.Directory, spec.MainSpecFile), Path.Combine(name, spec.MainSpecFile), false); foreach (var ds in spec.ReferencedSpecFiles) { specFiles.Add(ds); SystemHelper.SafeCopy(Path.Combine(spec.Directory, ds), Path.Combine(name, ds), false); } return(specFiles); } ) .Distinct() .ToList(), Directory = name }; plan.Package.MainSpec = ServiceContract.GenerateStandAloneThriftSpec(serviceObject.GetType(), plan.Package.Spec.ReferencedSpecFiles); SystemHelper.StringToFile(plan.Package.MainSpec, Path.Combine(name, plan.Package.Spec.MainSpecFile)); if (SystemHelper.RunProcess("php.exe", Path.Combine(Environment.GetEnvironmentVariable("DSN_ROOT"), "bin", "dsn.generate_code.php") + " " + Path.Combine(name, plan.Package.Spec.MainSpecFile) + " csharp " + dir + " binary layer3") == 0) { sources.Add(Path.Combine(dir, serviceObject.GetType().Name + ".client.cs")); sources.Add(Path.Combine(dir, serviceObject.GetType().Name + ".server.cs")); sources.Add(Path.Combine(dir, "ThriftJsonHelper.cs")); sources.Add(Path.Combine(dir, serviceObject.GetType().Name + ".main.composed.cs")); sources.Add(Path.Combine(dir, serviceObject.GetType().Name + ".code.definition.cs")); } else { Console.Write("php codegen failed"); } //grab thrift-generated files sources.UnionWith(Directory.GetFiles(Path.Combine(dir, "thrift"), "*.cs", SearchOption.AllDirectories)); // step: generate composed service package CSharpCompiler.ToDiskAssembly(sources.ToArray(), libs.ToArray(), new string[] { }, Path.Combine(name, name + ".exe"), true, true ); libs.Add(Path.Combine(Environment.GetEnvironmentVariable("DSN_ROOT"), "lib", "dsn.core.dll")); libs.Add(Path.Combine(Environment.GetEnvironmentVariable("DSN_ROOT"), "lib", "zookeeper_mt.dll")); foreach (var lib in libs.Where(lib => !lib.StartsWith("System."))) { SystemHelper.SafeCopy(lib, Path.Combine(name, Path.GetFileName(lib)), false); } //Console.ReadKey(); return(plan); }
protected override byte[] CaptureDMD() { // Initialize a new writeable bitmap to receive DMD pixels. var frame = new byte[DMDWidth * DMDHeight]; // Init DMD hack for Stern tables. InitSternDMD(_hProcess, false); // Check if a table is loaded.. var tableLoaded = new byte[1]; ReadProcessMemory(_hProcess, _gameStateAddr, tableLoaded, 1, IntPtr.Zero); // ..if not, return an empty frame (blank DMD). if (tableLoaded[0] == 0) { sternInit = false; // Reset Stern DMD hack state. return(frame); } // Table is loaded, reset Stern DMD hack. InitSternDMD(_hProcess, true); // Retrieve the DMD entrypoint from EAX registry (returned by our codecave). var eax = new byte[4]; ReadProcessMemory(_hProcess, _codeCave, eax, 4, IntPtr.Zero); // Now we have our DMD location in memory + little hack to re-align the DMD block. var dmdOffset = B4ToPointer(eax) - 0x1F406; // Grab the whole raw DMD block from game's memory. ReadProcessMemory(_hProcess, dmdOffset, RawDMD, MemBlockSize + 2, IntPtr.Zero); // Check the DMD CRC flag, skip the frame if the value is incorrect. if (RawDMD[0] != 0x02) { return(null); } // Used to parse pixel bytes of the DMD memory block, starting at 2 to skip the flag bytes. var rawPixelIndex = 2; var identical = true; // For each pixel on Y axis. for (var dmdY = 0; dmdY < DMDHeight; dmdY++) { // For each pixel on X axis. for (var dmdX = 0; dmdX < DMDWidth; dmdX++) { // RGB to BGR double hue, sat, lum; ColorUtil.RgbToHsl(RawDMD[rawPixelIndex], RawDMD[rawPixelIndex + 1], RawDMD[rawPixelIndex + 2], out hue, out sat, out lum); var pos = dmdY * DMDWidth + dmdX; byte pixel; // NoEx: how to check if it's stern? if (hasSpecialDMD(_hProcess)) { // from STERN, we get: [ 0, 0.0666666666666667, 0.135294117647059, 0.203921568627451, 0.272549019607843, 0.341176470588235, 0.409803921568627, 0.47843137254902 ] pixel = (byte)(lum * 15 * 2); } else { // from others, we get: [ 0, 0.366666666666667, 0.509803921568627, 0.605882352941176 ] pixel = (byte)(lum * 15 * 1.6); } if (pixel > 0 && pixel < 15) { pixel++; } if (!lums.Contains(lum)) { lums.Add(lum); Logger.Trace(String.Join(" ", lums.ToArray().OrderBy(l => l))); } // drop garbage frames if (pixel > 15) { return(null); } if (identical && (_lastFrame == null || _lastFrame[pos] == pixel)) { identical = false; } frame[pos] = pixel; // Each pixel takes 4 bytes of data in memory, advance 2 pixels. rawPixelIndex += 8; } // Jump to the next DMD line. rawPixelIndex += LineJump * 2 + DMDWidth * 8; } _lastFrame = frame; // Return the DMD bitmap we've created or null if frame was identical to previous. return(identical ? null : frame); }
private DotNetInterface ParseInterface(NetworkInterface n) { HashSet <UdpIPv4Address> hashSet = new HashSet <UdpIPv4Address>(UdpIPv4Address.Comparer.Instance); HashSet <UdpIPv4Address> hashSet2 = new HashSet <UdpIPv4Address>(UdpIPv4Address.Comparer.Instance); HashSet <UdpIPv4Address> hashSet3 = new HashSet <UdpIPv4Address>(UdpIPv4Address.Comparer.Instance); IPInterfaceProperties ipinterfaceProperties = null; try { ipinterfaceProperties = n.GetIPProperties(); } catch { return(null); } if (ipinterfaceProperties != null) { try { foreach (GatewayIPAddressInformation gatewayIPAddressInformation in ipinterfaceProperties.GatewayAddresses) { try { if (gatewayIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork) { hashSet.Add(DotNetPlatform.ConvertAddress(gatewayIPAddressInformation.Address)); } } catch { } } } catch { } try { foreach (IPAddress ipaddress in ipinterfaceProperties.DnsAddresses) { try { if (ipaddress.AddressFamily == AddressFamily.InterNetwork) { hashSet.Add(DotNetPlatform.ConvertAddress(ipaddress)); } } catch { } } } catch { } try { foreach (UnicastIPAddressInformation unicastIPAddressInformation in ipinterfaceProperties.UnicastAddresses) { try { if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork) { UdpIPv4Address item = DotNetPlatform.ConvertAddress(unicastIPAddressInformation.Address); hashSet2.Add(item); hashSet.Add(new UdpIPv4Address(item.Byte3, item.Byte2, item.Byte1, 1)); } } catch { } } } catch { } try { foreach (MulticastIPAddressInformation multicastIPAddressInformation in ipinterfaceProperties.MulticastAddresses) { try { if (multicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork) { hashSet3.Add(DotNetPlatform.ConvertAddress(multicastIPAddressInformation.Address)); } } catch { } } } catch { } if (hashSet2.Count == 0 || hashSet.Count == 0) { return(null); } } return(new DotNetInterface(n, hashSet.ToArray <UdpIPv4Address>(), hashSet2.ToArray <UdpIPv4Address>(), hashSet3.ToArray <UdpIPv4Address>())); }
/// <summary> /// Verify/Normalize the test source files. /// </summary> /// <param name="sources"> Paths to source file to look for tests in. </param> /// <returns> The list of verified sources. </returns> internal static IEnumerable <string> GetValidSources(IEnumerable <string> sources, IMessageLogger logger) { Debug.Assert(sources != null, "sources"); var verifiedSources = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (string source in sources) { if (!File.Exists(source)) { var errorMessage = string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.FileNotFound, source); logger.SendMessage(TestMessageLevel.Warning, errorMessage); continue; } if (!verifiedSources.Add(source)) { var errorMessage = string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.DuplicateSource, source); logger.SendMessage(TestMessageLevel.Warning, errorMessage); continue; } } // No valid source is found => we cannot discover. if (!verifiedSources.Any()) { var sourcesString = string.Join(",", sources.ToArray()); var errorMessage = string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.NoValidSourceFoundForDiscovery, sourcesString); logger.SendMessage(TestMessageLevel.Warning, errorMessage); EqtTrace.Warning("TestDiscoveryManager: None of the source {0} is valid. ", sourcesString); return(verifiedSources); } // Log the sources from where tests are being discovered if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("TestDiscoveryManager: Discovering tests from sources {0}", string.Join(",", verifiedSources.ToArray())); } return(verifiedSources); }
public override string[] GetUsersInRole(string roleName) { Assert.ArgumentNotNull(roleName, "roleName"); const string GetUsersInRoleKey = "getUsersInRole"; ConditionalLog.Info(String.Format("GetUsersInRole({0}). Started.", roleName), this, TimerAction.Start, GetUsersInRoleKey); var users = this.CacheService.MembersCache.Get(roleName); if (users != null) { ConditionalLog.Info(String.Format("GetUsersInRole({0}). Finished (users have been retrieved from cache).", roleName), this, TimerAction.Stop, GetUsersInRoleKey); return(users.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)); } var contactStateCodeConditionExpression = new ConditionExpression(); contactStateCodeConditionExpression.AttributeName = "statecode"; contactStateCodeConditionExpression.Operator = ConditionOperator.Equal; contactStateCodeConditionExpression.Values = new object[] { "Active" }; var contactUniquePropertyNotNullConditionExpression = new ConditionExpression(); contactUniquePropertyNotNullConditionExpression.AttributeName = Configuration.Settings.UniqueKeyProperty; contactUniquePropertyNotNullConditionExpression.Operator = ConditionOperator.NotNull; var contactUniquePropertyNotEmptyConditionExpression = new ConditionExpression(); contactUniquePropertyNotEmptyConditionExpression.AttributeName = Configuration.Settings.UniqueKeyProperty; contactUniquePropertyNotEmptyConditionExpression.Operator = ConditionOperator.NotEqual; contactUniquePropertyNotEmptyConditionExpression.Values = new object[] { String.Empty }; var contactFilterExpression = new FilterExpression(); contactFilterExpression.Conditions = new[] { contactStateCodeConditionExpression, contactUniquePropertyNotNullConditionExpression, contactUniquePropertyNotEmptyConditionExpression }; contactFilterExpression.FilterOperator = LogicalOperator.And; var listNameConditionExpression = new ConditionExpression(); listNameConditionExpression.AttributeName = "listname"; listNameConditionExpression.Operator = ConditionOperator.Equal; listNameConditionExpression.Values = new object[] { roleName }; var listFilterExpression = new FilterExpression(); listFilterExpression.Conditions = new[] { listNameConditionExpression }; listFilterExpression.FilterOperator = LogicalOperator.And; var listMemberListLinkEntity = new LinkEntity(); listMemberListLinkEntity.JoinOperator = JoinOperator.Inner; listMemberListLinkEntity.LinkCriteria = listFilterExpression; listMemberListLinkEntity.LinkFromAttributeName = "listid"; listMemberListLinkEntity.LinkFromEntityName = EntityName.listmember.ToString(); listMemberListLinkEntity.LinkToAttributeName = "listid"; listMemberListLinkEntity.LinkToEntityName = EntityName.list.ToString(); var contactListMemberLinkEntity = new LinkEntity(); contactListMemberLinkEntity.JoinOperator = JoinOperator.Inner; contactListMemberLinkEntity.LinkEntities = new[] { listMemberListLinkEntity }; contactListMemberLinkEntity.LinkFromAttributeName = "contactid"; contactListMemberLinkEntity.LinkFromEntityName = EntityName.contact.ToString(); contactListMemberLinkEntity.LinkToAttributeName = "entityid"; contactListMemberLinkEntity.LinkToEntityName = EntityName.listmember.ToString(); var pagingInfo = new PagingInfo(); pagingInfo.Count = Configuration.Settings.FetchThrottlingPageSize; pagingInfo.PageNumber = 1; var queryExpression = new QueryExpression(); queryExpression.ColumnSet = new ColumnSet { Attributes = new[] { Configuration.Settings.UniqueKeyProperty } }; queryExpression.Criteria = contactFilterExpression; queryExpression.EntityName = EntityName.contact.ToString(); queryExpression.LinkEntities = new[] { contactListMemberLinkEntity }; queryExpression.PageInfo = pagingInfo; var request = new RetrieveMultipleRequest(); request.Query = queryExpression; request.ReturnDynamicEntities = true; var result = new HashSet <string>(); try { while (true) { var response = (RetrieveMultipleResponse)this.CrmService.Execute(request); if ((response != null) && (response.BusinessEntityCollection != null)) { ConditionalLog.Info(String.Format("GetUsersInRole({0}). Retrieved {1} users from CRM.", roleName, response.BusinessEntityCollection.BusinessEntities.Length), this, TimerAction.Tick, GetUsersInRoleKey); foreach (var entity in response.BusinessEntityCollection.BusinessEntities) { var item = (DynamicEntity)entity; var uniqueKeyProperty = (StringProperty)item.Properties.ByName(Configuration.Settings.UniqueKeyProperty); result.Add(uniqueKeyProperty.Value); } if (response.BusinessEntityCollection.MoreRecords) { pagingInfo.PageNumber++; pagingInfo.PagingCookie = response.BusinessEntityCollection.PagingCookie; } else { break; } } } this.CacheService.MembersCache.Add(roleName, String.Join("|", result.ToArray())); } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't get contacts of {0} marketing list from CRM.", roleName), e, this); } ConditionalLog.Info(String.Format("GetUsersInRole({0}). Finished.", roleName), this, TimerAction.Stop, GetUsersInRoleKey); return(result.ToArray()); }
public void Run() { var wordLookupFile = Path.Combine(Path.GetTempPath(), "WordLookup.txt"); if (!File.Exists(wordLookupFile)) { new WebClient().DownloadFile("http://www.albahari.com/ispell/allwords.txt", wordLookupFile); } var wordLookup = new HashSet<string>(File.ReadAllLines(wordLookupFile), StringComparer.InvariantCultureIgnoreCase); var wordList = wordLookup.ToArray(); // Here, we're using ThreadLocal to generate a thread-safe random number generator, // so we can parallelize the building of the wordsToTest array. var localRandom = new ThreadLocal<Random>(() => new Random(Guid.NewGuid().GetHashCode())); var wordsToTest = Enumerable.Range(0, 1000000) .AsParallel() .Select(i => wordList[localRandom.Value.Next(0, wordList.Length)]) .ToArray(); wordsToTest[12345] = "woozsh"; // Introduce a couple wordsToTest[23456] = "wubsie"; // of spelling mistakes. var query = wordsToTest .AsParallel() //.Select((word, index) => new IndexedWord { Word = word, Index = index }) .Select((word, index) => new { Word = word, Index = index }) .Where(iword => !wordLookup.Contains(iword.Word)) .OrderBy(iword => iword.Index); var result = query.ToList(); }