public Network(NetworkBuilder builder, StateOptimizer optimizer, IEnumerable<RuleBinding> rules, Dictionary<int, RuleBinding> stateRules, Dictionary<int, RuleBinding> contextRules) { Contract.Requires<ArgumentNullException>(builder != null, "builder"); Contract.Requires<ArgumentNullException>(optimizer != null, "optimizer"); Contract.Requires<ArgumentNullException>(rules != null, "rules"); _builder = builder; _rules = new List<RuleBinding>(rules); //Dictionary<int, string> stateRules = new Dictionary<int, string>(); //foreach (var rule in _rules) //{ // stateRules[rule.StartState.Id] = rule.Name; // stateRules[rule.EndState.Id] = rule.Name; //} HashSet<State> states = new HashSet<State>(ObjectReferenceEqualityComparer<State>.Default); HashSet<Transition> transitions = new HashSet<Transition>(ObjectReferenceEqualityComparer<Transition>.Default); foreach (var rule in _rules) { ExtractStatesAndTransitions(optimizer, rule, rule.StartState, states, transitions, stateRules, contextRules); //ExtractStatesAndTransitions(rule.Name, rule.EndState, states, transitions, stateRules, contextRules); } _states = states.ToDictionary(i => i.Id); _transitions = new List<Transition>(transitions); _stateRules = stateRules; _contextRules = contextRules; _optimizer = optimizer; }
/// <summary> /// Returns the possible ways that a query term can unify with a program term /// </summary> public static IBindings Unify(this ILiteral query, ILiteral program, IBindings bindings = null) { var simpleUnifier = new SimpleUnifier(); var freeVariables = new HashSet<ILiteral>(); // Run the unifier var queryFreeVars = simpleUnifier.QueryUnifier.Compile(query, bindings); if (queryFreeVars == null) return null; simpleUnifier.PrepareToRunProgram(); var programFreeVars = simpleUnifier.ProgramUnifier.Compile(program, bindings); if (programFreeVars == null) return null; freeVariables.UnionWith(queryFreeVars); // Retrieve the unified value for the program var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query); // If the result was valid, return as the one value from this function if (result != null) { var variableBindings = freeVariables.ToDictionary(variable => variable, variable => simpleUnifier.UnifiedValue(variable)); return new BasicBinding(result, variableBindings); } else { return null; } }
/// <summary> /// Erstellt eine neue Option, die einen der angegebenen Werte aus validValues annehmen kann, mit dem angegebenen Namen in dem /// angegebenen Abschnitt der angegebenen Einstellungsdatei. /// [base=section, name, defaultValue, configFile] /// </summary> public DistinctOption(string section, string name, string defaultValue, IEnumerable<string> validValues, ConfigFile configFile) : base(section, name, defaultValue, configFile) { ValidValues = new HashSet<string> (validValues); ValidValues.Add (defaultValue); DisplayValidValues = new Dictionary<string,string> (ValidValues.ToDictionary (x=>x,x=>x)); }
public Solution10(string[] lines) { grid = lines.Select(line => line.Select(x => x == '#').ToArray()).ToArray(); height = grid.Length; width = grid[0].Length; slopes = GetSlopes(width, height).ToHashSet(); asteroids = GetAsteroids().ToHashSet(); var visiblePerAsteroid = asteroids.ToDictionary(x => x, x => GetVisibleAsteroids(x, asteroids, slopes, width, height)); best = visiblePerAsteroid.MaxBy(x => x.Value.Count); }
public override String GetVideoUrl(VideoInfo video) { string bestVideoQualityUrl = string.Empty; if (video.PlaybackOptions == null) { if (string.IsNullOrWhiteSpace(video.VideoUrl)) { throw new OnlineVideosException("Video nicht verfügbar!"); } var json = GetWebData <JObject>(video.VideoUrl, headers: headers); var playbackOptions = new HashSet <KeyValuePair <string, string> >(KeyValuePairComparer.KeyOrdinalIgnoreCase); foreach (var formitaet in json["priorityList"].SelectMany(l => l["formitaeten"])) { if (formitaet["facets"].Any(f => f.ToString() == "restriction_useragent")) { continue; } var type = formitaet.Value <string>("type"); foreach (var vid in formitaet["qualities"]) { var quality = vid.Value <string>("quality"); if (quality == "auto") { continue; } var url = vid["audio"]["tracks"].First.Value <string>("uri"); if (url.EndsWith(".m3u8") || url.EndsWith(".webm")) { continue; } if (url.Contains("master.m3u8")) { var m3u8Data = GetWebData(url); var m3u8PlaybackOptions = HlsPlaylistParser.GetPlaybackOptions(m3u8Data, video.VideoUrl); playbackOptions.UnionWith(m3u8PlaybackOptions); bestVideoQualityUrl = m3u8PlaybackOptions.FirstOrDefault().Value; //Default, if m3u8 playlist cannot be collected, e.g. geoblocking } else { playbackOptions.Add(new KeyValuePair <string, string>(string.Format("{0}-{1}", quality, type), url)); } } } video.PlaybackOptions = playbackOptions.ToDictionary(e => e.Key, e => e.Value); } return(!string.IsNullOrWhiteSpace(bestVideoQualityUrl) ? bestVideoQualityUrl : video.PlaybackOptions.LastOrDefault().Value); }
public static Dictionary <K, R> OuterJoinDictionarySS <K, V1, V2, R>(this IDictionary <K, V1> dic1, IDictionary <K, V2> dic2, Func <K, V1?, V2?, R> mixer) where V1 : struct where V2 : struct { HashSet <K> set = new HashSet <K>(); set.UnionWith(dic1.Keys); set.UnionWith(dic2.Keys); return(set.ToDictionary(k => k, k => mixer(k, dic1.TryGetS(k), dic2.TryGetS(k)))); }
public TfBased( ITimeProvider timeProvider, EventByTypeIndexEventReader reader, TFPos fromTfPosition, IPublisher publisher, ClaimsPrincipal readAs) : base(reader, readAs) { _timeProvider = timeProvider; _eventTypes = reader._eventTypes; _streamToEventType = _eventTypes.ToDictionary(v => "$et-" + v, v => v); _publisher = publisher; _fromTfPosition = fromTfPosition; }
private ReadOnlyDictionary <char, int> CreateCounts() { var counts = ValidNucleotides.ToDictionary(n => n, _ => 0); foreach (var n in _dna) { counts[n]++; } return(new ReadOnlyDictionary <char, int>(counts)); }
private void Initialize() { _fileInfo = new HashSet<PathInfo>( Directory.EnumerateFiles(_basePathConverted, "*", SearchOption.AllDirectories) .Select(fileName => PathInfo.GetSubPath(_basePath, fileName))); _fileInfoCache = _fileInfo.ToDictionary(i => GetRootPath(i), i => FileInfo.Create(GetRootPath(i))); _directoryInfo = new HashSet<PathInfo>( Directory.EnumerateDirectories(_basePathConverted, "*", SearchOption.AllDirectories) .Select(fileName => PathInfo.GetSubPath(_basePath, fileName))); }
public static IDictionary <char, int> Count(string sequence) { var nucleotideCount = NucleotideSymbols.ToDictionary(c => c, c => 0); foreach (char nucleotide in sequence) { CheckNucleotideIsValid(nucleotide); nucleotideCount[nucleotide]++; } return(nucleotideCount); }
public static IDictionary <string, T> Flatten <T>(this IDictionary <string, IDictionary <string, T> > source, string[] tierOrder) where T : class { if (source == null) { return(new Dictionary <string, T>()); } var allKeys = new HashSet <string>(source.Keys.SelectMany(s => source[s].Select(v => v.Key))); return(allKeys.ToDictionary(k => k, k => source.Search(k, tierOrder))); }
public DfaBuilder(Nfa nfa) { _stateCounter = 0; _nfa = nfa; _states = nfa.GetStates(); _alphabet = GetAlphabet(_states); _epsilonClosures = _states .ToDictionary(state => state, state => GetEpsilonClosure(state)); _visited = new HashSet <DfaState>(); _queue = new Queue <DfaState>(); }
private void OnDeserialized(StreamingContext context) { if (Rooms != null) { mRoomsByName = Rooms.ToDictionary(room => room.Name, room => room); foreach (Room room in Rooms) { room.UpdateNeighbors(this); } } }
private void Initialize() { _fileInfo = new HashSet <PathInfo>( Directory.EnumerateFiles(_basePathConverted, "*", SearchOption.AllDirectories) .Select(fileName => PathInfo.GetSubPath(_basePath, fileName))); _fileInfoCache = _fileInfo.ToDictionary(i => GetRootPath(i), i => FileInfo.Create(GetRootPath(i))); _directoryInfo = new HashSet <PathInfo>( Directory.EnumerateDirectories(_basePathConverted, "*", SearchOption.AllDirectories) .Select(fileName => PathInfo.GetSubPath(_basePath, fileName))); }
protected override object Evaluate(CommonRequest request) { using (var ctx = new XiangXiEntities()) { UserInformation user = Sessions["UserInformation"] as UserInformation; string name = user.UILoginName; string pwd = user.UICode; var rows = ctx.V_Table_Comments.ToList(); var tables = new HashSet <string>(rows.Select(p => p.table_name)); return(tables.ToDictionary(p => p, p => rows.Where(r => r.table_name == p).ToList())); } }
/// <summary> /// Initializes a new instance of the <see cref="RepositoryAssemblyResolver"/> class. /// </summary> /// <param name="assemblies">The assemblies to look for.</param> /// <param name="packageSource">The package sources to search.</param> /// <param name="fileSystem">The file system to output any packages.config files.</param> /// <param name="console">The console to output to.</param> public RepositoryAssemblyResolver(List <string> assemblies, IQueryable <IPackage> packageSource, IFileSystem fileSystem, IConsole console) { _packageSource = packageSource; _fileSystem = fileSystem; _console = console; foreach (var assembly in assemblies.Where(assembly => !_assemblies.Add(assembly))) { console.WriteWarning("Same assembly resolution will be used for both assembly references to {0}", assembly); } _resolvedAssemblies = _assemblies.ToDictionary(a => a, _ => new List <IPackage>()); }
private HashSet <int> GetBestAlternatives( Relation relation, List <char> suitableSetsMarkers) { // Будуємо множину Sn int[][] characteristicSet = new int[relation.Dimension][]; Dictionary <int, int> verticesRelationsCounter = new Dictionary <int, int>(); for (int i = 0; i < relation.Dimension; i++) { characteristicSet[i] = new int[relation.Dimension]; verticesRelationsCounter[i] = 0; for (int j = 0; j < relation.Dimension; j++) { if (suitableSetsMarkers.Contains(relation.Characteristic[i][j])) { characteristicSet[i][j] = 1; verticesRelationsCounter[i]++; } } } Relation helperSetRelation = new Relation(characteristicSet); // Відбираємо максимальні за включенням множини Sn int maxForBetter = verticesRelationsCounter.Values.Max(); HashSet <int> bestAlternatives = verticesRelationsCounter.Where(elem => elem.Value == maxForBetter) .Select(elem => elem.Key) .ToHashSet(); Dictionary <int, HashSet <int> > bestAlternativesLowerSections = bestAlternatives.ToDictionary(elem => elem, elem => helperSetRelation.GetLowerSection(elem)); HashSet <int> vertexLowerSection; // Перевіряємо, що інші рядки не включають найкращі як власні підмножини for (int vertex = 0; vertex < helperSetRelation.Dimension; vertex++) { vertexLowerSection = helperSetRelation.GetLowerSection(vertex); foreach (var alternative in bestAlternativesLowerSections) { if (vertexLowerSection.Except(alternative.Value).Count() > 0) { bestAlternatives.Remove(alternative.Key); } } } return(bestAlternatives); }
private void Update(string[] domains, HashSet <IpType> targetTypes) { HashSet <IpType> types = new HashSet <IpType>(GetSupportIpTypes()); types.IntersectWith(targetTypes); var tasks = types.ToDictionary(t => t, t => t == IpType.A ? PublicIPGetter.GetIpv4() : PublicIPGetter.GetIpv6()); Task.WaitAll(tasks.Values.ToArray()); var ips = tasks.ToDictionary(p => p.Key, p => p.Value.Result); foreach (var i in domains) { var oldRecords = GetRecords(i);//获取域名的所有记录 if (oldRecords == null) { Log.Print($"跳过设置域名 { i }"); continue; } ClearCName(ref oldRecords);//清理必然重复的CNAME记录。 foreach (var j in ips) { string type = j.Key.ToString(); //获取当前类型的所有记录。 List <Record> typedRecords = new List <Record>(); for (int k = oldRecords.Count - 1; k >= 0; --k) { if (oldRecords[k].Type == type) { typedRecords.Add(oldRecords[k]); oldRecords.RemoveAt(k); } } //根据已有记录数量决定操作。 if (typedRecords.Count == 1) { UpdateRecord(typedRecords[0], j.Value); } else { if (typedRecords.Count > 1) { DeleteRecords(typedRecords[0].DomainName, typedRecords[0].RR, type); } AddRecord(j.Key, i, j.Value); } } } }
public ActionResult<GenericResponse<IDictionary<string, Bot>>> BotGet(string botNames) { if (string.IsNullOrEmpty(botNames)) { ASF.ArchiLogger.LogNullError(nameof(botNames)); return BadRequest(new GenericResponse<IDictionary<string, Bot>>(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames)))); } HashSet<Bot> bots = Bot.GetBots(botNames); if (bots == null) { return BadRequest(new GenericResponse<IDictionary<string, Bot>>(false, string.Format(Strings.ErrorIsInvalid, nameof(bots)))); } return Ok(new GenericResponse<IDictionary<string, Bot>>(bots.ToDictionary(bot => bot.BotName, bot => bot))); }
// TODO: // Find all fields to replace in the document and populate dictionary with oldText as the Keys and newText as the Values public static void ParseDocument(AutoFillDocument.Form1 form, Word._Document oDoc) { // get a set of fields to replace in the document HashSet <String> words = GetTextFields(oDoc.Content.Text, '{', '}'); // use ToDictionary(), not ToDictionary<String, String>() to overload 2 lambda functions. // create dictionary from hashset where the keys are the hashset's elements. // use dictionary in String.Replace. textTransformMap = words.ToDictionary(Key => Key, Value => ""); // Populate the table with oldText fields and newText textbox inputs AddNewTextInput(form); }
public RemotePathProvider(HashSet <string> remotePaths) { if (remotePaths == null) { throw new ArgumentNullException(nameof(remotePaths)); } if (!remotePaths.Any()) { throw new ArgumentException(); } RemotePaths = new ConcurrentDictionary <string, double>(remotePaths.ToDictionary(item => item, item => 0.0)); }
void WriteMefCacheControl(ComposableCatalog catalog, ITimeTracker timer) { var mefAssemblyNames = new HashSet <string> (); var mefAssemblyInfos = new List <MefControlCacheAssemblyInfo> (); foreach (var assembly in MefAssemblies) { mefAssemblyNames.Add(assembly.GetName().ToString()); mefAssemblyInfos.Add(new MefControlCacheAssemblyInfo { Location = assembly.Location, ModuleVersionId = assembly.ManifestModule.ModuleVersionId, }); } var additionalInputAssemblies = new List <MefControlCacheAssemblyInfo> (); var loadedMap = loadedAssemblies.ToDictionary(x => x.FullName, x => x); foreach (var asm in catalog.GetInputAssemblies()) { var assemblyName = asm.ToString(); if (mefAssemblyNames.Contains(assemblyName)) { continue; } if (!loadedMap.TryGetValue(assemblyName, out var assembly)) { throw new InvalidRuntimeCompositionException(assemblyName); } additionalInputAssemblies.Add(new MefControlCacheAssemblyInfo { Location = assembly.Location, ModuleVersionId = assembly.ManifestModule.ModuleVersionId, }); } // Create cache control data. var controlCache = new MefControlCache { MefAssemblyInfos = mefAssemblyInfos, AdditionalInputAssemblyInfos = additionalInputAssemblies, }; var serializer = new JsonSerializer(); using (var fs = File.Open(MefCacheControlFile, FileMode.Create)) using (var sw = new StreamWriter(fs)) { serializer.Serialize(sw, controlCache); } timer.Trace("Composition control file written"); }
public static void CombineMisMatchedCsvFiles(string[] filePaths, string destinationFile, char splitter = ',', bool Union = true) { HashSet <string> combinedheaders = new HashSet <string>(); int i; // aggregate headers for (i = 0; i < filePaths.Length; i++) { string file = filePaths[i]; //if (Union) combinedheaders.UnionWith(File.ReadLines(file).First().Split(splitter)); //else //combinedheaders.Intersect(File.ReadLines(file).First().Split(splitter)); } if (combinedheaders.Contains("")) { combinedheaders.Remove(""); } var hdict = combinedheaders.ToDictionary(y => y, y => new List <object>()); string[] combinedHeadersArray = combinedheaders.ToArray(); for (i = 0; i < filePaths.Length; i++) { var fileheaders = File.ReadLines(filePaths[i]).First().Split(splitter).Where(x => x != "").ToArray(); var notfiledheaders = combinedheaders.Except(fileheaders); var fi = new FileInfo(filePaths[i]); if (fi.Length == 0) { throw new Exception($"File {fi.Name} is empty"); } File.ReadLines(filePaths[i]).Skip(1).Select(line => line.Split(splitter)).ForEach(spline => { for (int j = 0; j < fileheaders.Length; j++) { hdict[fileheaders[j]].Add(spline[j]); } foreach (string header in notfiledheaders) { hdict[header].Add(null); } }); } System.Data.DataTable dt = hdict.ToDataTable(); dt.SaveToCSV(destinationFile); }
protected static SavedGameDto ConvertFromXml(SavedGameXML game) { if (game == null) { return(null); } if (!(game.CellTypes?.Count >= 3)) { throw new ArgumentOutOfRangeException(nameof(game) + "." + nameof(game.CellTypes), "Не может быть меньше трёх"); } HashSet <CellTypeDto> types = game.CellTypes .Select(xml => CellTypeDto.Create(xml.Id, xml.Value)) .ToHashSet(); var tps = types.ToDictionary(tp => tp.Id); HashSet <CellDto> cells = null; if (game.Cells != null) { cells = new HashSet <CellDto>(); foreach (CellXML cell in game.Cells) { if (types.FirstOrDefault(dto => dto.Id == cell.TypeId) == null) { throw new ArgumentException("Такого типа нет в списке", "cell.id"); } cells.Add(new CellDto(cell.Id, cell.Row, cell.Column, tps[cell.TypeId])); } } if (!(game.Users?.Count > 0)) { throw new ArgumentOutOfRangeException(nameof(game) + "." + nameof(game.Users), "Не может быть меньше одного"); } HashSet <UserDto> users = game.Users .Select(xml => new UserDto(xml.Id, xml.Name, xml.ImageIndex, xml.Turn, xml.Id == game.CurrentUser.UserId, tps[xml.TypeId])) .ToHashSet(); return(new SavedGameDto ( users, cells, types, game.Game.Rows, game.Game.Columns, game.Game.LengthToWin )); }
public static void InitUserPermission(HttpContext ctx, Account user) { //if (ctx.Session[Global.GlobalConsts.IdToRoleContextKey] != null || // ctx.Session[Global.GlobalConsts.RoleToIdContextKey] != null || // ctx.Session[Global.GlobalConsts.IdToPermissionContextKey] != null || // ctx.Session[Global.GlobalConsts.PermissionToIdContextKey] != null || // ctx.Session[Global.GlobalConsts.RoleIdToMappedContextKey] != null) return; var permissions = new HashSet <AccountPemission>(); foreach (var role in user.Roles.Select(c => c.Role)) { foreach (var applicationPemission in role.Permissions) { permissions.Add(applicationPemission); } } var idToRole = user.Roles.ToDictionary(p => p.RoleId.ToString(), p => p.Role.Name); var roleToId = user.Roles.ToDictionary(p => p.Role.Name, p => p.Role.Id.ToString()); var roleToMapping = user.Roles.ToDictionary(p => p.RoleId.ToString(), p => p.Role.MappedToId ?? string.Empty); var idToPermission = permissions.ToDictionary(p => p.PermissionId.ToString(), p => p.Name); var permissionToId = permissions.ToDictionary(p => p.Name.ToString(), p => p.PermissionId); var permissionTypeToName = permissions.ToDictionary(p => p.Type, p => p.Name); ctx.Session[Global.GlobalConsts.IdToRoleContextKey] = idToRole; ctx.Session[Global.GlobalConsts.RoleToIdContextKey] = roleToId; ctx.Session[Global.GlobalConsts.IdToPermissionContextKey] = idToPermission; ctx.Session[Global.GlobalConsts.PermissionToIdContextKey] = permissionToId; ctx.Session[Global.GlobalConsts.PermissionTypeToNameContextKey] = permissionTypeToName; ctx.Session[Global.GlobalConsts.RoleIdToMappedContextKey] = roleToMapping; }
public Client(string host, int port, int locklease = 10, string username = "", string password = "", string caCert = "", string clientCert = "", string clientKey = "", bool publicRootCa = false) { _client = new dotnet_etcd.EtcdClient(host, port, username, password, caCert, clientCert, clientKey, publicRootCa); _locklease = locklease; //获取集群中全部客户端制作客户端列表 foreach (var item in _client.MemberList(new Etcdserverpb.MemberListRequest()).Members) { if (item.ClientURLs.Count > 0) { string[] baseurl = item.ClientURLs[0].Substring(item.ClientURLs[0].LastIndexOf("/") + 1).Split(':'); string clienthost = baseurl[0] == "0.0.0.0" ? host : baseurl[0]; int clientport = int.Parse(baseurl[1]); _clients.Add(new dotnet_etcd.EtcdClient(clienthost, clientport, username, password, caCert, clientCert, clientKey, publicRootCa)); } } //后台自延期部分 System.Threading.Tasks.Task.Run(() => { while (!IsDisposing) { //获取客户端全部node Dictionary <Google.Protobuf.ByteString, Google.Protobuf.ByteString> lockers = null; lock (_lockerList) { lockers = _lockerList .ToDictionary(c => Google.Protobuf.ByteString.CopyFromUtf8(c.Name) , c => Google.Protobuf.ByteString.CopyFromUtf8(c.Id.ToString())); } //生成lease Etcdserverpb.LeaseGrantRequest request = new Etcdserverpb.LeaseGrantRequest(); request.TTL = _locklease; var lease = _client.LeaseGrant(request); //更新全部node foreach (var item in lockers) { _client.Put(new Etcdserverpb.PutRequest() { Key = item.Key, Value = item.Value, Lease = lease.ID }); } //休眠 TTL/2 时间,防止执行过程导致的node丢失 System.Threading.Thread.Sleep(_locklease * 500); } }); }
/// <summary> /// Build a dictionary of mixins /// </summary> /// <param name="finalMixins">a list of mixins</param> /// <returns>a dictionary of all the necessary mixins</returns> private Dictionary <string, ModuleMixin> BuildMixinDictionary(IEnumerable <ModuleMixin> finalMixins) { var allMixins = new HashSet <ModuleMixin>(); foreach (var mixin in finalMixins) { if (allMixins.All(x => x.MixinName != mixin.MixinName)) { allMixins.Add(mixin); } } return(allMixins.ToDictionary(x => x.MixinName, x => x)); }
public static void Visit(ArmadaSymbolTable symbols, MethodInfo methodInfo, IPCNodeVisitor visitor) { var states = new List <PCNode>(); var steps = new List <StepDescriptor>(); var loopHeads = new HashSet <ArmadaPC>(); var branches = new List <bool>(); var rootNode = methodInfo.method.Body == null?GeneratePCStructureForMethodWithNoBody(symbols, methodInfo, loopHeads) : GeneratePCStructureForMethodWithBody(methodInfo, loopHeads); var visitedLoops = loopHeads.ToDictionary(h => h, h => - 1); rootNode.Visit(visitor, methodInfo.method.Name, states, steps, visitedLoops, branches); }
private Dictionary <string, List <string> > ArrangeTime(List <Line> personelList) { Dictionary <string, List <string> > dateDict = Set.ToDictionary(x => x, x => new List <string>()); Dictionary <string, int> setDict = Set.ToDictionary(x => x, x => 0); while (personelList.Count > 0) { var mostUrgentline = personelList.Aggregate((x, y) => x.ApplicableSet.Count < y.ApplicableSet.Count ? x : y); personelList.Remove(mostUrgentline); var bestDates = setDict.OrderBy(x => x.Value).Select(x => x.Key); foreach (string bestDate in bestDates) { if (mostUrgentline.ApplicableSet.Contains(bestDate)) { setDict[bestDate]++; dateDict[bestDate].Add(mostUrgentline.Id); break; } } } return(dateDict); }
public static ReadOnlyDictionary <String, String> AssertParse(this String input, String pattern, RegexOptions options) { var names = new HashSet <String>(); var m_meta = Regex.Match(pattern, @"\(\?\<(?<name>.*?)\>"); for (; m_meta.Success; m_meta = m_meta.NextMatch()) { var name = m_meta.Result("${name}"); names.Add(name); } var m = input.AssertMatch(pattern, options); return(names.ToDictionary(name => name, name => m.Result("${" + name + "}")).ToReadOnly()); }
public void Visit(OrNode node) { var set = new HashSet <KeyValuePair <string, Type> >(); foreach (var inner in node.Inner) { inner.Accept(this); foreach (var field in Fields) { set.Add(field); } } Fields = set.ToDictionary(f => f.Key, f => f.Value); }
public void Initialize() { var blocks = transformer.RootScope.GetBasicBlocks().Cast <BasicBlock <IRInstrList> >().ToList(); liveness = LivenessAnalysis.ComputeLiveness(blocks); var stackVars = new HashSet <IRVariable>(); foreach (var blockLiveness in liveness) { foreach (var instr in blockLiveness.Key.Content) { if (instr.OpCode != IROpCode.__LEA) { continue; } var variable = (IRVariable)instr.Operand2; if (variable.VariableType != IRVariableType.Argument) { stackVars.Add(variable); } } stackVars.UnionWith(blockLiveness.Value.OutLive); } // [BP - 2] = last argument // [BP - 1] = return address // [BP ] = old BP // [BP + 1] = first local var offset = 1; globalVars = stackVars.ToDictionary(var => var, var => new StackSlot(offset++, var)); baseOffset = offset; LocalSize = baseOffset - 1; offset = -2; var parameters = transformer.Context.GetParameters(); for (var i = parameters.Length - 1; i >= 0; i--) { var paramVar = parameters[i]; globalVars[paramVar] = new StackSlot(offset--, paramVar); } allocation = globalVars.ToDictionary(pair => pair.Key, pair => (object)pair.Value); }
public IndexBased(HashSet <string> eventTypes, EventByTypeIndexEventReader reader, IPrincipal readAs) : base(reader, readAs) { _streamToEventType = eventTypes.ToDictionary(v => "$et-" + v, v => v); _eofs = _streamToEventType.Keys.ToDictionary(v => v, v => false); // whatever the first event returned is (even if we start from the same position as the last processed event // let subscription handle this _publisher = _reader._publisher; _pendingRequests = new Dictionary <string, Guid>(); _pendingRequests.Add("$et", Guid.Empty); foreach (var stream in _streamToEventType.Keys) { _pendingRequests.Add(stream, Guid.Empty); } }
public TrashedRegisterFinder( Program program, ProgramDataFlow flow, IEnumerable <SsaTransform> sccGroup, DecompilerEventListener listener) { this.arch = program.Architecture; this.segmentMap = program.SegmentMap; this.flow = flow; this.sccGroup = sccGroup.ToHashSet(); this.callGraph = program.CallGraph; this.listener = listener; this.cmp = new ExpressionValueComparer(); this.worklist = new WorkStack <Block>(); this.ssas = sccGroup.ToDictionary(s => s.SsaState.Procedure, s => s.SsaState); }
private Dictionary<KspPartObject, List<KspPartLinkProperty>> FindPartDependencies (KspCraftObject craft, RegexFilter filter) { ui.DisplayUserMessage ($"Entering craft '{craft.Name}'..."); var partLookup = new PartLookup (craft); var dependencies = partLookup.LookupParts (filter).ToList (); var dependentParts = new HashSet<KspPartObject> (); Parallel.ForEach (dependencies, dependency => { foreach (var part in partLookup.LookupSoftDependencies (dependency)) { lock (dependentParts) { dependentParts.Add (part); } } }); ui.DisplayUserMessage ($"Found {dependentParts.Count} dependent parts"); return dependentParts.ToDictionary (part => part, part => FindPartLinks (part, dependencies)); }
public static SqlPreCommand SynchronizeSchemasScript(Replacements replacements) { HashSet<SchemaName> model = Schema.Current.GetDatabaseTables().Select(a => a.Name.Schema).ToHashSet(); HashSet<SchemaName> database = new HashSet<SchemaName>(); foreach (var db in model.Select(a => a.Database).Distinct()) { using (Administrator.OverrideDatabaseInViews(db)) { database.AddRange( from s in Database.View<SysSchemas>() select new SchemaName(db, s.name)); } } return Synchronizer.SynchronizeScript( model.ToDictionary(a => a), database.ToDictionary(a => a), (_, newSN) => SqlBuilder.CreateSchema(newSN), null, null, Spacing.Simple); }
internal static Dictionary<string, DocumentedNamespaceTree> Build(IEnumerable<DocumentedNamespace> @namespaces) { var result = new HashSet<DocumentedNamespaceTree>(); foreach (var ns in namespaces) { result.Add(new DocumentedNamespaceTree(ns)); } foreach (var tree in result) { var parts = tree.Namespace.Identity.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); var prefix = string.Join(".", parts.Take(parts.Length - 1)); foreach (var other in result) { if (other.Namespace.Identity == prefix) { other.AddChild(tree); } } } return result.ToDictionary(x => x.Namespace.Identity, x => x, StringComparer.Ordinal); }
public Dictionary<Webpage, HashSet<string>> GetSecondary(HashSet<Webpage> webpages) { if (!webpages.Any()) return new Dictionary<Webpage, HashSet<string>>(); Tag tagAlias = null; TagInfo tagInfo = null; string typeName = webpages.First().DocumentType; Dictionary<int, IEnumerable<string>> tagInfoDictionary = _session.QueryOver<Webpage>() .Where(webpage => webpage.DocumentType == typeName) .JoinAlias(webpage => webpage.Tags, () => tagAlias) .SelectList(builder => builder.Select(webpage => webpage.Id).WithAlias(() => tagInfo.WebpageId) .Select(() => tagAlias.Name).WithAlias(() => tagInfo.TagName)) .TransformUsing(Transformers.AliasToBean<TagInfo>()).List<TagInfo>() .GroupBy(info => info.WebpageId) .ToDictionary(infos => infos.Key, infos => infos.Select(x => x.TagName)); return webpages.ToDictionary(webpage => webpage, webpage => GetSecondaryTerms(webpage, tagInfoDictionary.ContainsKey(webpage.Id) ? tagInfoDictionary[webpage.Id] : Enumerable.Empty<string>()).ToHashSet()); }
public static SqlPreCommand SynchronizeSchemasScript(Replacements replacements) { HashSet<SchemaName> model = Schema.Current.GetDatabaseTables().Select(a => a.Name.Schema).Where(a => !SqlBuilder.SystemSchemas.Contains(a.Name)).ToHashSet(); HashSet<SchemaName> database = new HashSet<SchemaName>(); foreach (var db in Schema.Current.DatabaseNames()) { using (Administrator.OverrideDatabaseInSysViews(db)) { var schemaNames = Database.View<SysSchemas>().Select(s => s.name).ToList().Except(SqlBuilder.SystemSchemas); database.AddRange(schemaNames.Select(sn => new SchemaName(db, sn))); } } using (replacements.WithReplacedDatabaseName()) return Synchronizer.SynchronizeScriptReplacing(replacements, "Schemas", model.ToDictionary(a => a.ToString()), database.ToDictionary(a => a.ToString()), (_, newSN) => SqlBuilder.CreateSchema(newSN), (_, oldSN) => DropSchema(oldSN) ? SqlBuilder.DropSchema(oldSN) : null, (_, newSN, oldSN) => newSN.Equals(oldSN) ? null : SqlPreCommand.Combine(Spacing.Simple, SqlBuilder.DropSchema(oldSN), SqlBuilder.CreateSchema(newSN)), Spacing.Double); }
/// <summary> /// eliminate redundant rows in sparse matrix structure, based on extreme points selection. /// </summary> /// <param name="rowsIntheSameGroup"></param> /// <returns></returns> public static HashSet<Row> EliminateRedundantRowsSubExtreme(HashSet<Row> rowsIntheSameGroup) { if(rowsIntheSameGroup.Count<=1) { return rowsIntheSameGroup; } var clonedRows = Row.CloneSetRows(rowsIntheSameGroup); var i = 0; var rows1 = clonedRows.ToDictionary(item => (i++), item => item); var j = 0; var row2 = rowsIntheSameGroup.ToDictionary(item => (j++), item => item); var resultingRows = new HashSet<int>(); var workingstack = new Stack<Dictionary<int, Row>>(); workingstack.Push(rows1); //rows with same extreme col value. The reductions is done based on the rest columns. while (workingstack.Count != 0) { var rows = workingstack.Pop(); if (rows.Count > 1) { var colMaxValue = new Dictionary<int, double>(); var colMaxRow = new Dictionary<int, Dictionary<int, Row>>(); var colIndexHashSet = new HashSet<int>(); bool flag2 = true; foreach (KeyValuePair<int, Row> keyValuePair in rows) { if (flag2) { foreach (int i1 in keyValuePair.Value.col) { if (colIndexHashSet.Contains(i1)) { flag2 = false; } } } colIndexHashSet.UnionWith(keyValuePair.Value.col); } if (flag2) { resultingRows.UnionWith(rows.Keys); continue; } var rowsIndex = new List<int>(rows.Keys); foreach (int colIndex in colIndexHashSet) { var flag = false; for(int i2=rowsIndex.Count-1;i2>=0;i2--) //rows { var currentRowIndex = rowsIndex[i2]; var currentRow1 = rows[currentRowIndex]; if(currentRow1.col.Contains(colIndex)) { var valIndex = currentRow1.col.BinarySearch(colIndex); var colValue = currentRow1.val[valIndex]; if (colValue < 0) { if (colMaxValue.ContainsKey(colIndex)) { if (colMaxValue[colIndex] > colValue) { colMaxValue[colIndex] = colValue; colMaxRow[colIndex] = new Dictionary<int, Row> { { currentRowIndex, currentRow1 } }; //can also be equal } else if (Math.Abs(colMaxValue[colIndex] - colValue) < EPSILON) { colMaxRow[colIndex].Add(currentRowIndex, currentRow1); } } else { colMaxValue[colIndex] = colValue; colMaxRow[colIndex] = new Dictionary<int, Row> { { currentRowIndex, currentRow1 } }; } flag = true; }else { currentRow1.col.RemoveAt(valIndex); //if positive, like, 1, remove. currentRow1.val.RemoveAt(valIndex); } } } //remove the rows that already added to colMaxRow[colIndex] if (flag) { //if (colMaxRow.ContainsKey(colIndex)) // { foreach (int key in colMaxRow[colIndex].Keys) { rows.Remove(key); rowsIndex.Remove(key); } // } } // var rowsIndex = new List<int>(colMaxRow.Keys); foreach (KeyValuePair<int, Dictionary<int, Row>> keyValuePair in colMaxRow) { Dictionary<int, Row> rowsDictionary = keyValuePair.Value; //List<int> rowsIndex2 = new List<int>(keyValuePair.Value.Keys.Count); //List<int> rowsIndex3 = new List<int>(keyValuePair.Value.Keys.Count); //foreach (KeyValuePair<int, Row> intRowPair in keyValuePair.Value) //{ // if (intRowPair.Value.col.Count == 1) // { // rowsIndex2.Add(intRowPair.Key); // } //} //////if there is only one element in a row, and rows with the same values then, remove //////List<int> rowsIndex=new List<int>(keyValuePair.Value.Keys); //for (int inneri = rowsIndex2.Count - 1; inneri >= 1; inneri--) //{ // var inneriIndex = rowsIndex2[inneri]; // var row = rowsDictionary[inneriIndex]; // for (int innerj = inneri - 1; innerj >= 0; innerj--) // { // var innerjIndex = rowsIndex2[innerj]; // var rowj = rowsDictionary[innerjIndex]; // //if all equal.then, this is a identical /redundant row, remove // if (row.col[0]==rowj.col[0]&&Math.Abs(row.val[0] - rowj.val[0]) < EPSILON) // { // rowsDictionary.Remove(inneriIndex); // break; // } // } //} //rowsIndex = new List<int>(keyValuePair.Value.Keys); //// remove similar rows //for (int inneri = rowsDictionary.Count - 1; inneri >= 1; inneri--) //{ // var inneriIndex = rowsIndex[inneri]; // var row = rowsDictionary[inneriIndex]; // if(row.col.Count>2) // { // continue; // } // //if (row.col[0] == i) // //{ // for (int innerj = inneri - 1; innerj >= 0; innerj--) // { // var innerjIndex = rowsIndex[innerj]; // var rowj = rowsDictionary[innerjIndex]; // if (row.col.Count != rowj.col.Count) // { // continue; // } // bool flag = true; // for (int k = 0; k < row.col.Count; k++) // { // if (row.col[k] == rowj.col[k]) // //GL:TODO:can improve, try int compare // { // if (Math.Abs(row.val[k] - rowj.val[k]) > EPSILON) // { // flag = false; // break; // } // } // else // { // flag = false; // break; // } // } // //if all equal.then, this is a identical /redundant row, remove // if (flag) // { // rowsDictionary.Remove(inneriIndex); // break; // } // } // //find sub extreme points and remove rest //} //recursive if number of rows larger than 1 if (rowsDictionary.Count > 1) { var nonZeroElementDictionary = new Dictionary<int, Row>(); foreach (KeyValuePair<int, Row> rowPair in rowsDictionary) { var index=rowPair.Value.col.BinarySearch(keyValuePair.Key); rowPair.Value.col.RemoveAt(index); rowPair.Value.val.RemoveAt(index); if (rowPair.Value.col.Count > 0) { nonZeroElementDictionary.Add(rowPair.Key, rowPair.Value); } else { resultingRows.Add(rowPair.Key); break; //only one-elements rows, keep one to delete same rows } } if(nonZeroElementDictionary.Count>0) { workingstack.Push(nonZeroElementDictionary); } } else { Debug.Assert(rowsDictionary.Keys.Count > 0, "true1"); resultingRows.UnionWith(rowsDictionary.Keys); } } } else { Debug.Assert(rows.Keys.Count > 0, "true2"); resultingRows.UnionWith(rows.Keys); } } var returnRows = new HashSet<Row>(); foreach (int k in resultingRows) { returnRows.Add(row2[k]); } Debug.Assert(resultingRows.Count>0,"true"); return returnRows; }
public static SparseMatrixMDP GaussianJordenElimination(SparseMatrixMDP smatrixMdp, bool first) { var r = smatrixMdp.Ngroup; // Debug.WriteLine(smatrixMdp); //reduce if(first) { foreach (var group in smatrixMdp.Groups) { group.RowsInSameGroup = LinearEquationsSolver.EliminateRedundantRowsSubExtreme(group.RowsInSameGroup); } } // Debug.WriteLine(smatrixMdp); var groups = smatrixMdp.Groups; for (int i = 0; i < r; i++) //operating on each group, i can take as pivot position { var currentGroup = groups[i]; //rows in ith group should normalized according to the element in its pivot position (ith group, ith column) //Debug.Assert(groups != null, "groups != null"); // var initialZeroRows = new HashSet<Row>(); foreach (Row currentRow1 in currentGroup.RowsInSameGroup) { // Debug.Assert(currentRow1.col[0] == i, "zero value"); if (currentRow1.col[0] == i) //TODO:I think this info is redundant { double currentFirstValue = currentRow1.val[0]; if (Math.Abs(currentFirstValue - 1) > EPSILON) { for (int k = 1; k < currentRow1.val.Count; k++) { currentRow1.val[k] = currentRow1.val[k]/currentFirstValue; } } currentRow1.col.RemoveAt(0); currentRow1.val.RemoveAt(0); currentRow1.diag = 1; } //else // { // initialZeroRows.Add(currentRow1); // } } currentGroup.RowsInSameGroup = LinearEquationsSolver.EliminateRedundantRowsSubExtreme(currentGroup.RowsInSameGroup); //using current row to deduct every rows in other group if corresponding element (column i in dense matrix) is not zero //follow upper triangular form. for (int j = 0; j < r; j++) //scan all groups { if (j == i) { continue; } //update rows in group j var pivotGroup = groups[j]; var removeCollection = new HashSet<Row>(); var addCollection = new HashSet<Row>(); foreach (Row pivotRow in pivotGroup.RowsInSameGroup) { if (pivotRow.col[0] == i) //index of col for column value in dense matrix equal to pivot element. if value is zero, it will not be found { double t = -pivotRow.val[0]; pivotRow.col.RemoveAt(0); pivotRow.val.RemoveAt(0); if(currentGroup.RowsInSameGroup.Count>1) { foreach (Row currentRow in currentGroup.RowsInSameGroup) { // bool flag; if (!CheckDictionarySubset(pivotRow.SelectionMemoryInGroups, currentRow.SelectionMemoryInGroups,pivotRow.WorkingGroup,currentRow.WorkingGroup)) { continue; } var r3 = new Row { diag = pivotRow.diag, diagCol = pivotRow.diagCol, Index = pivotRow.Index, }; //add elements in colValuePair // var hashset1 = new HashSet<int>(currentRow.col); //hashset1.UnionWith(pivotRow.col); var colValuePair = new SortedDictionary<int, double>(); for (int inneri = 0; inneri < currentRow.col.Count; inneri++) { //if (Math.Abs(currentRow.val[inneri]) > EPSILON) //{ colValuePair[currentRow.col[inneri]] = currentRow.val[inneri] * t; // } if(currentRow.col[inneri]==r3.diagCol) { r3.diag = r3.diag + currentRow.val[inneri] * t; } } //add workingRow to r3 //var hashset2 = new HashSet<int>(); for (int inneri = 0; inneri < pivotRow.col.Count; inneri++) { if (colValuePair.ContainsKey(pivotRow.col[inneri])) { double m = colValuePair[pivotRow.col[inneri]] + pivotRow.val[inneri]; if (Math.Abs(m) > EPSILON) { colValuePair[pivotRow.col[inneri]] = m; } }else { colValuePair[pivotRow.col[inneri]] = pivotRow.val[inneri]; } } r3.col = new List<int>(colValuePair.Keys); r3.val = new List<double>(colValuePair.Values); r3.SelectionMemoryInGroups = new Dictionary<int, int>(pivotRow.SelectionMemoryInGroups); r3.WorkingGroup=new BitArray(pivotRow.WorkingGroup); foreach (KeyValuePair<int, int> d in currentRow.SelectionMemoryInGroups) { r3.SelectionMemoryInGroups[d.Key] = d.Value; r3.WorkingGroup.Set(d.Key,true); } addCollection.Add(r3); if (pivotRow.SelectionMemoryInGroups.ContainsKey(currentGroup.Index)) { break; } } }else { foreach (Row currentRow in currentGroup.RowsInSameGroup) { var r3 = new Row { diag = pivotRow.diag, diagCol = pivotRow.diagCol, Index = pivotRow.Index, }; //add elements in colValuePair var hashset1 = new HashSet<int>(currentRow.col); hashset1.UnionWith(new HashSet<int>(pivotRow.col)); var colValuePair = new SortedDictionary<int, double>(hashset1.ToDictionary(item => item, item => 0.0)); for (int inneri = 0; inneri < currentRow.col.Count; inneri++) { //if (Math.Abs(currentRow.val[inneri]) > EPSILON) //{ colValuePair[currentRow.col[inneri]] = currentRow.val[inneri] * t; // } if (currentRow.col[inneri] == r3.diagCol) { r3.diag = r3.diag + currentRow.val[inneri] * t; } } for (int inneri = 0; inneri < pivotRow.col.Count; inneri++) { double m = colValuePair[pivotRow.col[inneri]] + pivotRow.val[inneri]; if (Math.Abs(m) > EPSILON) { colValuePair[pivotRow.col[inneri]] = m; } } r3.col = new List<int>(colValuePair.Keys); r3.val = new List<double>(colValuePair.Values); r3.SelectionMemoryInGroups = new Dictionary<int, int>(pivotRow.SelectionMemoryInGroups); r3.WorkingGroup = new BitArray(pivotRow.WorkingGroup); foreach (KeyValuePair<int, int> d in currentRow.SelectionMemoryInGroups) { r3.SelectionMemoryInGroups[d.Key] = d.Value; r3.WorkingGroup.Set(d.Key, true); } addCollection.Add(r3); } } removeCollection.Add(pivotRow); } } //update rows in current group foreach (Row row in removeCollection) { pivotGroup.RowsInSameGroup.Remove(row); } //clear redundant rows in addCollection //pivotGroup.RowsInSameGroup.UnionWith(EliminateRedundantRows(addCollection)); //var reducedRows = EliminateRedundantRowsSubExtreme(addCollection); pivotGroup.RowsInSameGroup.UnionWith(addCollection); if (pivotGroup.RowsInSameGroup.Count > smatrixMdp.Ncols) //r is not correct bound. { //if (pivotGroup.Index > currentGroup.Index) //{ // pivotGroup.RowsInSameGroup = //EliminateRedundantRowsSubExtremeWithNormalization(pivotGroup.RowsInSameGroup); //}else //{ // pivotGroup.RowsInSameGroup = //EliminateRedundantRowsSubExtreme(pivotGroup.RowsInSameGroup); //} pivotGroup.RowsInSameGroup = pivotGroup.Index > currentGroup.Index ? EliminateRedundantRowsSubExtremeWithNormalization(pivotGroup.RowsInSameGroup) : EliminateRedundantRowsSubExtreme(pivotGroup.RowsInSameGroup); } } //Debug.WriteLine(smatrixMdp); } foreach (var group in smatrixMdp.Groups) { group.RowsInSameGroup = LinearEquationsSolver.EliminateRedundantRowsSubExtreme(group.RowsInSameGroup); } return smatrixMdp; }
public static SparseMatrixMDP GaussianJordenElimination(SparseMatrixMDP smatrixMdp) { var r = smatrixMdp.Ngroup; var groups = smatrixMdp.Groups; for (int i = 0; i < r; i++) //operating on each group, i can take as pivot position { var currentGroup = groups[i]; //rows in ith group should normalized according to the element in its pivot position (ith group, ith column) Debug.Assert(groups != null, "groups != null"); foreach (Row currentRow1 in currentGroup.RowsInSameGroup) { if (currentRow1.col[0] == i) //TODO:I think this info is redundant { if (Math.Abs(currentRow1.val[0] - 1) > EPSILON) { for (int k = 1; k < currentRow1.val.Count; k++) { currentRow1.val[k] = currentRow1.val[k]/currentRow1.val[0]; } } currentRow1.col.RemoveAt(0); currentRow1.val.RemoveAt(0); } } //currentRow1.colIndexCurrentRow = currentRow1.col.BinarySearch(i); //using current row to deduct every rows in other group if corresponding element (column i in dense matrix) is not zero //follow upper triangular form. for (int j = 0; j < r; j++) //scan all groups { if (j == i) { continue; } //update rows in group j var pivotGroup = groups[j]; var removeCollection = new HashSet<Row>(); var addCollection = new HashSet<Row>(); foreach (Row pivotRow in pivotGroup.RowsInSameGroup) { if (pivotRow.col[0] == i) //index of col for column value in dense matrix equal to pivot element. if value is zero, it will not be found { double t = -pivotRow.val[0]; //var hashset1 = new HashSet<int>(pivotRow.col); //hashset1.UnionWith(new HashSet<int>(currentRow.col)); pivotRow.col.RemoveAt(0); pivotRow.val.RemoveAt(0); foreach (Row currentRow in currentGroup.RowsInSameGroup) { // bool flag; if (!CheckDictionarySubset(pivotRow.SelectionMemoryInGroups, currentRow.SelectionMemoryInGroups)) { continue; } var r3 = new Row { diag = pivotRow.diag, diagCol = pivotRow.diagCol, // val = new List<double>(hashset1.Count), // col = hashset1.ToList(), Index = pivotRow.Index, }; //add elements in colValuePair var hashset1 = new HashSet<int>(currentRow.col); hashset1.UnionWith(new HashSet<int>(pivotRow.col)); var colValuePair = new Dictionary<int, double>(hashset1.ToDictionary(item => item, item => 0.0)); for (int inneri = 0; inneri < currentRow.col.Count; inneri++) { if (Math.Abs(currentRow.val[inneri]) > EPSILON) { colValuePair[currentRow.col[inneri]] += currentRow.val[inneri]*t; } } //add workingRow to r3 //var hashset2 = new HashSet<int>(); for (int inneri = 0; inneri < pivotRow.col.Count; inneri++) { double m = colValuePair[pivotRow.col[inneri]] + pivotRow.val[inneri]; if (Math.Abs(m) > EPSILON) { colValuePair[pivotRow.col[inneri]] = m; } } r3.col = new List<int>(colValuePair.Keys); r3.val = new List<double>(colValuePair.Values); // r3.SelectionMemoryInGroups = new Dictionary<Group, Row>(pivotRow.SelectionMemoryInGroups); // r3.SelectionMemoryInGroups[currentGroup] = currentRow; r3.SelectionMemoryInGroups = new Dictionary<int,int>(pivotRow.SelectionMemoryInGroups); r3.SelectionMemoryInGroups[currentGroup.Index] = currentRow.Index; //update diag elements in that row. After row adding, the pivot element/diag info is redundant. // r3.diag = r3.col.Contains(r3.diagCol) ? colValuePair[r3.diagCol] : 0; //pivotGroup.RowsInSameGroup.Add(r3); addCollection.Add(r3); if(pivotRow.SelectionMemoryInGroups.ContainsKey(currentGroup.Index)) { break; } //If pivotRow contains currentGroup index, and currentRow can work with pivotRow, //that means the rest of rows in the group are not that useful. } removeCollection.Add(pivotRow); } } //update rows in current group foreach (Row row in removeCollection) { pivotGroup.RowsInSameGroup.Remove(row); } foreach (Row row in addCollection) { pivotGroup.RowsInSameGroup.Add(row); } } Debug.WriteLine(smatrixMdp); } return smatrixMdp; }
/// <summary> /// Build a dictionary of mixins /// </summary> /// <param name="finalMixins">a list of mixins</param> /// <returns>a dictionary of all the necessary mixins</returns> private Dictionary<string, ModuleMixin> BuildMixinDictionary(IEnumerable<ModuleMixin> finalMixins) { var allMixins = new HashSet<ModuleMixin>(); foreach (var mixin in finalMixins) { if (allMixins.All(x => x.MixinName != mixin.MixinName)) allMixins.Add(mixin); } return allMixins.ToDictionary(x => x.MixinName, x => x); }
public static String Replace(this String input, String pattern, Func<ReadOnlyDictionary<String, String>, String> replacer, RegexOptions options) { if (input == null) return null; var names = new HashSet<String>(); var m_meta = Regex.Match(pattern, @"\(\?\<(?<name>.*?)\>"); for (; m_meta.Success; m_meta = m_meta.NextMatch()) { var name = m_meta.Result("${name}"); names.Add(name); } return Regex.Replace(input, pattern, m => replacer(names.ToDictionary(name => name, name => m.Result("${" + name + "}")).ToReadOnly()), options); }
public static ReadOnlyCollection<ReadOnlyDictionary<String, String>> ParseMulti(this String input, String pattern, RegexOptions options) { if (input == null) return null; var names = new HashSet<String>(); var m_meta = Regex.Match(pattern, @"\(\?\<(?<name>.*?)\>"); for (; m_meta.Success; m_meta = m_meta.NextMatch()) { var name = m_meta.Result("${name}"); names.Add(name); } var ms = input.MatchMulti(pattern, options); if (ms == null) return null; return ms.Select(m => { if (!m.Success) return null; return names.ToDictionary(name => name, name => m.Result("${" + name + "}")).ToReadOnly(); }).Where(m => m != null).ToReadOnly(); }
public Dictionary<Webpage, HashSet<string>> GetPrimary(HashSet<Webpage> webpages) { return webpages.ToDictionary(webpage => webpage, webpage => GetPrimaryTerms(webpage).ToHashSet()); }
public List<Account> GetUserList(string searchString) { Require.NotEmpty(searchString, nameof(searchString)); var allProjectMemberships = _projectMembershipRepostiory.GetAllProjectMemberships().ToList(); var allUsers = new HashSet<Account>(_userRepository.GetAllAccounts()); var allUsersToSearchByRole = new HashSet<Account>( allProjectMemberships.Select(membership => allUsers.Single(account => account.UserId == membership.DeveloperId))); var userRolesDictionary = allUsersToSearchByRole.ToDictionary(user => user, user => allProjectMemberships.Where(membership => membership.DeveloperId == user.UserId) .Select(that => that.Role)); return userRolesDictionary.Where( pair => pair.Value.Any(role => Extensions.Contains(role, searchString))) .Select(pair => pair.Key) .Union( allUsers.Where( account => Extensions.Contains($"{account.Firstname} {account.Lastname}", searchString))).ToList(); }
private HashSet<State> GetLiveStates(HashSet<State> states) { var dictionary = states.ToDictionary(s => s, s => new HashSet<State>()); foreach (State s in states) { foreach (Transition t in s.Transitions) { // TODO: Java code does not check for null states. if (t.To == null) { continue; } dictionary[t.To].Add(s); } } var comparer = new StateEqualityComparer(); var live = new HashSet<State>(this.GetAcceptStates(), comparer); var worklist = new LinkedList<State>(live); while (worklist.Count > 0) { State s = worklist.RemoveAndReturnFirst(); foreach (State p in dictionary[s]) { if (!live.Contains(p)) { live.Add(p); worklist.AddLast(p); } } } return live; }
public Dictionary<Layout, HashSet<string>> GetSecondary(HashSet<Layout> layouts) { return layouts.ToDictionary(layout => layout, layout => GetSecondary(layout).ToHashSet()); }
public Dictionary<MediaCategory, HashSet<string>> GetSecondary(HashSet<MediaCategory> mediaCategories) { return mediaCategories.ToDictionary(category => category, category => GetSecondary(category).ToHashSet()); }
public Dictionary<User, HashSet<string>> GetSecondary(HashSet<User> users) { return users.ToDictionary(user => user, user => GetSecondary(user).ToHashSet()); }
public void Spawn() { PreventTurrets(); TakeOutTurrets(); var units = new HashSet<Unit> { Unit.CLAW, Unit.ARCHER, Unit.HACKER, Unit.REPAIRER, Unit.TERMINATOR, Unit.TURRET }; var ourUnitCounts = units.ToDictionary(u => u, u => 0); var theirUnitCounts = units.ToDictionary(u => u, u => 0); droids.Where(d => units.Contains((Unit)d.Variant)).ForEach(d => { if (d.Owner == Bb.id) ourUnitCounts[(Unit)d.Variant]++; else theirUnitCounts[(Unit)d.Variant]++; }); var theirTotal = theirUnitCounts.Sum(kvp => kvp.Value); var isSpawningTurretsSoon = Bb.TheirSpawning.ToPoints().Any(p => (Unit)Bb.TileLookup[p].VariantToAssemble == Unit.TURRET && Bb.TileLookup[p].TurnsUntilAssembled < 10); float targetClawRatio = theirTotal == 0 ? 1.0f : 0.0f; float targetHackerRatio = theirUnitCounts[Unit.HACKER] + theirUnitCounts[Unit.CLAW]; float targetArcherRatio = theirUnitCounts[Unit.ARCHER] + theirUnitCounts[Unit.TURRET] + (isSpawningTurretsSoon ? 5 : 0); float targetTerminatorRatio = theirUnitCounts[Unit.ARCHER] + theirUnitCounts[Unit.TERMINATOR] + theirUnitCounts[Unit.CLAW] + theirUnitCounts[Unit.REPAIRER]; float targetRepairerRatio = theirUnitCounts[Unit.ARCHER] / 4 + theirUnitCounts[Unit.CLAW] / 4 + ourUnitCounts[Unit.TERMINATOR]; var total = targetClawRatio + targetHackerRatio + targetArcherRatio + targetTerminatorRatio + targetRepairerRatio; targetHackerRatio /= total; targetArcherRatio /= total; targetTerminatorRatio /= total; targetRepairerRatio /= total; float unitCount = Bb.OurUnits.Count() - Bb.OurHangars.Count() - Bb.OurTurrets.Count() - Bb.OurWalls.Count() + .0001f; int clawCount = Bb.OurClaws.Count(); int archerCount = Bb.OurArchers.Count(); int hackerCount = Bb.OurHackers.Count(); int terminatorCount = Bb.OurTerminators.Count(); int repairerCount = Bb.OurRepairers.Count(); if (CanAfford(Unit.CLAW) && clawCount / unitCount < targetClawRatio) { SpawnUnit(Unit.CLAW); Bb.ReadBoard(); } if (CanAfford(Unit.TERMINATOR) && terminatorCount / unitCount < targetTerminatorRatio) { SpawnUnit(Unit.TERMINATOR); Bb.ReadBoard(); } if (CanAfford(Unit.HACKER) && hackerCount / unitCount < targetHackerRatio) { SpawnUnit(Unit.HACKER); Bb.ReadBoard(); } if (CanAfford(Unit.ARCHER) && archerCount / unitCount < targetArcherRatio) { SpawnUnit(Unit.ARCHER); Bb.ReadBoard(); } if (CanAfford(Unit.REPAIRER) && repairerCount / unitCount < targetRepairerRatio) { SpawnUnit(Unit.REPAIRER); Bb.ReadBoard(); } }
// constructors private SubqueryRemover(IEnumerable<SelectExpression> selectsToRemove) { _selectsToRemove = new HashSet<SelectExpression>(selectsToRemove); _map = _selectsToRemove.ToDictionary(d => d.Alias, d => d.Columns.ToDictionary(d2 => d2.Name, d2 => d2.Expression)); }
private static List<Reference> ResolveReferences(Queue<AtomModel> sortedReferences, HashSet<AtomModel> projectedAtoms) { // Pick the first ref to be the atomModel var primaryRef = new SimpleReference(sortedReferences.Dequeue()); var references = new List<Reference> { primaryRef }; var referenceMap = new Dictionary<string, Reference> { { primaryRef.Name, primaryRef } }; var atomDependencyMap = projectedAtoms.ToDictionary(atom => atom.Name, atom => atom.GetDependencies()); foreach (var atomRelation in sortedReferences) { var posibleReferences = atomDependencyMap[atomRelation.Name]; if (!posibleReferences.Any()) { var r = new SimpleReference(atomRelation); references.Add(r); referenceMap.Add(r.Name, r); } else { var referenceName = posibleReferences.First(referenceMap.ContainsKey); var reference = referenceMap[referenceName]; var resolvedDependencies = posibleReferences.Where(referenceMap.ContainsKey) .Select(p => referenceMap[p]); var r = new ResolvedReference(atomRelation, resolvedDependencies); references.Add(r); referenceMap.Add(r.Name, r); } } return references; }
/// <summary> /// Moves items from the Stash to the Backpack /// </summary> /// <param name="itemIds">list of items to withdraw</param> /// <param name="maxAmount">amount to withdraw up to (including counts already in backpack)</param> /// <returns></returns> public static async Task<bool> Execute(IEnumerable<int> itemIds, int maxAmount) { Logger.Log("TakeItemsFromStash Started!"); if (!ZetaDia.IsInGame || !ZetaDia.IsInTown) return true; if (Town.Locations.Stash.Distance(ZetaDia.Me.Position) > 3f) { await MoveToAndInteract.Execute(Town.Locations.Stash, Town.ActorIds.Stash, 8f); } var stash = Town.Actors.Stash; if (stash == null) { Logger.Log("Unable to find Stash"); return false; } if (!UIElements.StashWindow.IsVisible && Town.Locations.Stash.Distance(ZetaDia.Me.Position) <= 10f) { Logger.Log("Stash window not open, interacting"); stash.Interact(); } var itemIdsHashSet = new HashSet<int>(itemIds); var amountWithdrawn = itemIdsHashSet.ToDictionary(k => k, v => (long)0); var overageTaken = itemIdsHashSet.ToDictionary(k => k, v => false); var lastStackTaken = itemIdsHashSet.ToDictionary(k => k, v => default(ACDItem)); foreach (var item in ZetaDia.Me.Inventory.Backpack.Where(i => i.ACDGuid != 0 && i.IsValid && itemIdsHashSet.Contains(i.ActorSNO)).ToList()) { amountWithdrawn[item.ActorSNO] += item.ItemStackQuantity; lastStackTaken[item.ActorSNO] = item; } foreach (var item in ZetaDia.Me.Inventory.StashItems.Where(i => i.ACDGuid != 0 && i.IsValid && itemIdsHashSet.Contains(i.ActorSNO)).ToList()) { try { if (!item.IsValid || item.IsDisposed) continue; var stackSize = item.ItemStackQuantity; var numTakenAlready = amountWithdrawn[item.ActorSNO]; // We have enough of this material already var alreadyTakenEnough = numTakenAlready >= maxAmount; if (alreadyTakenEnough) continue; // We have enough of everything already. if (amountWithdrawn.All(i => i.Value >= maxAmount)) break; // Only take up to the required amount. var willBeOverMax = numTakenAlready + stackSize > maxAmount; if (!willBeOverMax || !overageTaken[item.ActorSNO]) { var lastItem = lastStackTaken[item.ActorSNO]; var amountRequiredToMax = maxAmount - numTakenAlready; if (willBeOverMax && lastItem != null && lastItem.IsValid && !lastItem.IsDisposed && stackSize > amountRequiredToMax) { // Tried InventoryManager.SplitStack but it didnt work, reverting to moving onto existing stacks. var amountToSplit = stackSize - lastItem.ItemStackQuantity; Logger.Log("Merging Stash Stack {0} onto Backpack Stack. StackSize={1} WithdrawnAlready={2}", item.Name, amountToSplit, numTakenAlready); ZetaDia.Me.Inventory.MoveItem(item.DynamicId, ZetaDia.Me.CommonData.DynamicId, InventorySlot.BackpackItems, lastItem.InventoryColumn, lastItem.InventoryRow); amountWithdrawn[item.ActorSNO] += amountToSplit; overageTaken[item.ActorSNO] = true; } else { Logger.Log("Removing {0} ({3}) from stash. StackSize={1} WithdrawnAlready={2}", item.Name, stackSize, numTakenAlready, item.ActorSNO); if (item.IsValid && !item.IsDisposed) { ZetaDia.Me.Inventory.QuickWithdraw(item); amountWithdrawn[item.ActorSNO] += stackSize; lastStackTaken[item.ActorSNO] = item; } } await Coroutine.Sleep(25); await Coroutine.Yield(); } } catch (Exception ex) { Logger.LogError(ex.ToString()); } } await Coroutine.Sleep(1000); Logger.Log("TakeItemsFromStash Finished!"); return true; }
public IEnumerable<ReduceTypePerKey> GetReduceTypesPerKeys(string indexName, int limitOfItemsToReduceInSingleStep) { var allKeysToReduce = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); foreach (var reduction in storage.ScheduleReductions["ByViewLevelReduceKeyAndBucket"].SkipTo(new RavenJObject { {"view", indexName}, {"level", 0} }).TakeWhile(x => string.Equals(indexName, x.Value<string>("view"), StringComparison.InvariantCultureIgnoreCase) && x.Value<int>("level") == 0)) { allKeysToReduce.Add(reduction.Value<string>("reduceKey")); } var reduceTypesPerKeys = allKeysToReduce.ToDictionary(x => x, x => ReduceType.SingleStep); foreach (var reduceKey in allKeysToReduce) { var count = GetNumberOfMappedItemsPerReduceKey(indexName, reduceKey); if (count >= limitOfItemsToReduceInSingleStep) { reduceTypesPerKeys[reduceKey] = ReduceType.MultiStep; } } return reduceTypesPerKeys.Select(x => new ReduceTypePerKey(x.Key, x.Value)); }
private IEnumerable<string> GetNamePointPath(string from, string to, IEnumerable<PointGroup> roads) { var routes = new List<PointGroup>(); var cities = new HashSet<string>(); foreach (var road in roads) { cities.Add(road.Point1); cities.Add(road.Point2); routes.Add(new PointGroup { Point1 = road.Point1, Point2 = road.Point2, Lenght = road.Lenght }); routes.Add(new PointGroup { Point1 = road.Point2, Point2 = road.Point1, Lenght = road.Lenght }); } var shortestPaths = cities.ToDictionary(city => city, city => new Tuple<double, List<PointGroup>>(int.MaxValue, new List<PointGroup>())); shortestPaths[from] = new Tuple<double, List<PointGroup>>(0, new List<PointGroup>()); bool finish = false; var processed = new List<string>(); while (processed.Count != cities.Count) { var shortestCities = (from s in shortestPaths orderby s.Value.Item1 select s.Key).ToList(); string currentCity = null; foreach (string city in shortestCities) { if (!processed.Contains(city)) { if (shortestPaths[city].Item1 == int.MaxValue) { finish = true; } currentCity = city; break; } } if (finish) { break; } var citiesToGo = routes.Where(route => route.Point1 == currentCity); foreach (PointGroup cityToGo in citiesToGo) { if (shortestPaths[cityToGo.Point2].Item1 > cityToGo.Lenght + shortestPaths[cityToGo.Point1].Item1) { List<PointGroup> sss = shortestPaths[cityToGo.Point1].Item2.ToList(); sss.Add(cityToGo); var cost = cityToGo.Lenght + shortestPaths[cityToGo.Point1].Item1; shortestPaths[cityToGo.Point2] = new Tuple<double, List<PointGroup>>(cost, sss); } } processed.Add(currentCity); } try { try { if (shortestPaths[to].Item1 == int.MaxValue) { return new List<string>(); } } catch { Debug.Log(to); throw; } } catch (Exception e) { Debug.Log(to); throw e; } var shortPath = shortestPaths[to].Item2.Select(t => t.Point1).ToList(); shortPath.Add(to); return shortPath; }