private IEnumerable <KeyValuePair <ILocation, Action <ITweet> > > GetMatchedLocations(IEnumerable <ICoordinates> coordinates) { if (_locations.IsEmpty() || coordinates.IsNullOrEmpty()) { return(new List <KeyValuePair <ILocation, Action <ITweet> > >()); } return(_locations.Where(x => coordinates.Any(c => Location.CoordinatesLocatedIn(c, x.Key))).ToList()); }
public void IsEmpty_Dictionary_test() { var dictionary = new Dictionary <string, int>(); dictionary.IsEmpty().Should().BeTrue(); dictionary.Add("123", 123); dictionary.IsEmpty().Should().BeFalse(); dictionary.Clear(); dictionary.IsEmpty().Should().BeTrue(); }
public void IsEmpty_IReadOnlyDictionary_test() { IReadOnlyDictionary <string, int> dictionary = new Dictionary <string, int>(); dictionary.IsEmpty().Should().BeTrue(); ((Dictionary <string, int>)dictionary).Add("123", 123); dictionary.IsEmpty().Should().BeFalse(); ((Dictionary <string, int>)dictionary).Clear(); dictionary.IsEmpty().Should().BeTrue(); }
public virtual void UpdateSpecialScriptLayoutResultsTextRendererWithNoSpecialScripts() { IDictionary <int, LayoutResult> specialScriptLayoutResults = new Dictionary <int, LayoutResult>(); LayoutResult res = new LayoutResult(LayoutResult.NOTHING, new LayoutArea(0, new Rectangle(0, 0, 10, 10)), null, null); specialScriptLayoutResults.Put(-1, res); NUnit.Framework.Assert.IsFalse(specialScriptLayoutResults.IsEmpty()); TextRenderer textRenderer = new TextRenderer(new iText.Layout.Element.Text("whatever")); LineRenderer.UpdateSpecialScriptLayoutResults(specialScriptLayoutResults, textRenderer, 1, res); NUnit.Framework.Assert.IsTrue(specialScriptLayoutResults.IsEmpty()); }
public virtual void UpdateSpecialScriptLayoutResultsNonTextRenderer() { IDictionary <int, LayoutResult> specialScriptLayoutResults = new Dictionary <int, LayoutResult>(); LayoutResult res = new LayoutResult(LayoutResult.NOTHING, new LayoutArea(0, new Rectangle(0, 0, 10, 10)), null, null); specialScriptLayoutResults.Put(-1, res); NUnit.Framework.Assert.IsFalse(specialScriptLayoutResults.IsEmpty()); TabRenderer tabRenderer = new TabRenderer(new Tab()); LineRenderer.UpdateSpecialScriptLayoutResults(specialScriptLayoutResults, tabRenderer, 0, res); NUnit.Framework.Assert.IsTrue(specialScriptLayoutResults.IsEmpty()); }
private static Dictionary <string, DiffIndex> ApplyIndexAutoReplacements(DiffTable diff, ITable tab, Dictionary <string, Index> dictionary) { List <string> oldOnly = diff.Indices.Keys.Where(n => !dictionary.ContainsKey(n)).ToList(); List <string> newOnly = dictionary.Keys.Where(n => !diff.Indices.ContainsKey(n)).ToList(); if (oldOnly.Count == 0 || newOnly.Count == 0) { return(diff.Indices); } Dictionary <string, string> replacements = new Dictionary <string, string>(); foreach (var o in oldOnly) { var oldIx = diff.Indices[o]; var nIx = newOnly.FirstOrDefault(n => { var newIx = dictionary[n]; if (oldIx.IsUnique != (newIx is UniqueIndex)) { return(false); } if (oldIx.ViewName != null || (newIx is UniqueIndex) && ((UniqueIndex)newIx).ViewName != null) { return(false); } var news = newIx.Columns.Select(c => diff.Columns.TryGetC(c.Name)?.Name).NotNull().ToHashSet(); if (!news.SetEquals(oldIx.Columns)) { return(false); } var uix = newIx as UniqueIndex; if (uix != null && uix.Where != null && !oldIx.IndexName.EndsWith(StringHashEncoder.Codify(uix.Where))) { return(false); } return(true); }); if (nIx != null) { replacements.Add(o, nIx); newOnly.Remove(nIx); } } if (replacements.IsEmpty()) { return(diff.Indices); } return(diff.Indices.SelectDictionary(on => replacements.TryGetC(on) ?? on, dif => dif)); }
private void DropItems() { if (_loot.IsEmpty()) { return; } var availableNeighbouringNodes = ServiceLocator <IPathFinder> .Instance.GetAvailableNeighouringNodes(_cachedTransform.position); if (availableNeighbouringNodes.Count < _loot.Count) { throw new ArgumentException("Not enough available nodes to drop items on"); } for (var i = 0; i < _loot.Count; i++) { var loot = _loot.ElementAt(i); for (int j = 0; j < loot.Value; j++) { var item = ServiceLocator <IItemHandler> .Instance.CreateItem(loot.Key); var randomNeighbour = availableNeighbouringNodes.GetRandomElement(); ServiceLocator <IItemHandler> .Instance.CreatePhysicalItem(randomNeighbour.WorldCoordinates, item); availableNeighbouringNodes.Remove(randomNeighbour); Debug.Log("Dropped: " + item); } } _loot.Clear(); }
private bool exist_companion_not_in_party(out TextObject text) { HeroesNotInParty = new Dictionary <string, Hero>(); IEnumerable <Hero> members = Hero.MainHero.Clan.Heroes.Concat(Hero.MainHero.Clan.Companions); foreach (Hero hero in members) { if (!MobileParty.MainParty.MemberRoster.Contains(hero.CharacterObject)) { if (!messengerMap.Values.Select((Messenger x) => { return(x.target); }).Concat(messengerMap.Values.Select((Messenger x) => { return(x.messenger); })).Contains(hero)) { if (!hero.IsChild && !hero.IsPrisoner && !hero.IsHeroOccupied(Hero.EventRestrictionFlags.Default) && !hero.IsPartyLeader && hero.GovernorOf == null && hero.IsAlive) { if (!HeroesNotInParty.ContainsKey(hero.Name.ToString())) { HeroesNotInParty.Add(hero.Name.ToString(), hero); } } } } } if (HeroesNotInParty.IsEmpty()) { text = new TextObject("No lost companions"); return(false); } else { text = new TextObject(""); return(true); } }
} // getConverters() // @Override public DataSet intercept(DataSet dataSet) { Dictionary<Column, TypeConverter<object, object>> converters = getConverters(dataSet); if (converters.IsEmpty()) { return dataSet; } bool hasConverter = false; List<SelectItem> selectItems = NArrays.AsList<SelectItem>(dataSet.getSelectItems()); TypeConverter<object, object>[] converterArray = new TypeConverter<object, object>[selectItems.Count]; for (int i = 0; i < selectItems.Count; i++) { SelectItem selectItem = selectItems[i]; Column column = selectItem.getColumn(); if (column != null && selectItem.getAggregateFunction() == null) { TypeConverter<object, object> converter = converters[column]; if (converter != null) { hasConverter = true; converterArray[i] = converter; } } } if (! hasConverter) { return dataSet; } return new ConvertedDataSet(dataSet, converterArray); } // intercept()
public void LateDispose() { if (_settings.RequireStrictUnsubscribe) { if (!_subscriptionMap.IsEmpty()) { throw Assert.CreateException( "Found subscriptions for signals '{0}' in SignalBus.LateDispose! Either add the explicit Unsubscribe or set SignalSettings.AutoUnsubscribeInDispose to true", _subscriptionMap.Values.Select(x => x.SignalId.ToString()).Join(", ")); } } else { foreach (var subscription in _subscriptionMap.Values) { subscription.Dispose(); } } foreach (var declaration in _localDeclarationMap.Values) { declaration.Dispose(); } #if UNITY_EDITOR StaticSignalBusRegistry.Remove(this); #endif }
public void IsEmpty_Returns_True_When_Dictionary_Is_Not_Null_But_Emtpy() { Dictionary <string, string> testValue = new Dictionary <string, string>(); bool result = testValue.IsEmpty(); Assert.True(result); }
private void StopProjections() { _stopping = true; _ioDispatcher.BackwardReader.CancelAll(); _ioDispatcher.ForwardReader.CancelAll(); _ioDispatcher.Writer.CancelAll(); var allProjections = _projections.Values.ToArray(); foreach (var projection in allProjections) { var requiresStopping = projection.Suspend(); if (requiresStopping) { _suspendingProjections.Add(projection._projectionCorrelationId, projection); } } if (_suspendingProjections.IsEmpty()) { FinishStopping(); } else { _publisher.Publish(TimerMessage.Schedule.Create( TimeSpan.FromMilliseconds(_projectionStopTimeoutMs), new PublishEnvelope(_publisher), new ProjectionCoreServiceMessage.StopCoreTimeout(_stopQueueId))); } }
public void TestIsEmpty2() { var dict = new Dictionary("en-fr"); dict.AddTranslation("against", "contre"); Assert.False(dict.IsEmpty()); }
public IDictionary<EventTypeIdPair, IDictionary<int, IList<FilterItem[]>>> GetTraverseStatement( ICollection<int> statementIds) { var evaluatorStack = new ArrayDeque<FilterItem>(); var filters = new Dictionary<int, IList<FilterItem[]>>(); var filtersPerType = new Dictionary<EventTypeIdPair, IDictionary<int, IList<FilterItem[]>>>(); EventTypeIndexTraverse traverse = ( stack, filterHandle) => { var filterArray = stack.ToArray(); var existing = filters.Get(filterHandle.StatementId); if (existing == null) { existing = new List<FilterItem[]>(); filters.Put(filterHandle.StatementId, existing); } existing.Add(filterArray); }; foreach (var entry in eventTypes) { entry.Value.GetTraverseStatement(traverse, statementIds, evaluatorStack); if (!filters.IsEmpty()) { filtersPerType.Put(entry.Key.Metadata.EventTypeIdPair, new Dictionary<int, IList<FilterItem[]>>(filters)); filters.Clear(); } } return filtersPerType; }
private void StopProjections() { _stopping = true; _ioDispatcher.StartDraining( () => _publisher.Publish(new ProjectionSubsystemMessage.IODispatcherDrained(SubComponentName))); var allProjections = _projections.Values.ToArray(); foreach (var projection in allProjections) { var requiresStopping = projection.Suspend(); if (requiresStopping) { _suspendingProjections.Add(projection._projectionCorrelationId, projection); } } if (_suspendingProjections.IsEmpty()) { FinishStopping(); } else { _publisher.Publish(TimerMessage.Schedule.Create( TimeSpan.FromMilliseconds(_projectionStopTimeoutMs), new PublishEnvelope(_publisher), new ProjectionCoreServiceMessage.StopCoreTimeout(_stopQueueId))); } }
//----- property ----- //----- method ----- /// <summary> /// アセットバンドルのバージョンが最新か確認. /// (同梱された別アセットが更新された場合でもtrueを返す) /// </summary> private bool CheckAssetBundleVersion(AssetInfo assetInfo) { var filePath = assetBundleManager.GetFilePath(assetInfo); // ※ シュミレート時はpackageファイルをダウンロードしていないので常にファイルが存在しない. if (!simulateMode) { // ファイルがない. if (!File.Exists(filePath)) { return(false); } } // バージョン情報が存在しない. if (versions.IsEmpty()) { return(false); } var infos = assetInfosByAssetBundleName.FirstOrDefault(x => x.Key == assetInfo.AssetBundle.AssetBundleName); if (infos == null) { return(false); } foreach (var info in infos) { var hash = versions.GetValueOrDefault(info.FileName); // ローカルにバージョンが存在しない. if (string.IsNullOrEmpty(hash)) { return(false); } // アセットバンドル内のアセットが更新されている. if (hash != info.Hash) { return(false); } } return(true); }
/// <summary> /// アセットバンドルのバージョンが最新か確認. /// (同梱された別アセットが更新された場合でもtrueを返す) /// </summary> private bool CheckAssetBundleVersion(string assetBundleName) { var filePath = assetBundleManager.BuildFilePath(assetBundleName); // ※ シュミレート時はpackageファイルをダウンロードしていないので常にファイルが存在しない. if (!isSimulate) { // ファイルがない. if (!File.Exists(filePath)) { return(false); } } // バージョン情報が存在しない. if (versions.IsEmpty()) { return(false); } var assetInfos = assetInfosByAssetBundleName.FirstOrDefault(x => x.Key == assetBundleName); if (assetInfos == null) { return(false); } foreach (var assetInfo in assetInfos) { var info = versions.GetValueOrDefault(assetInfo.ResourcesPath); // ローカルにバージョンが存在しない. if (info == null) { return(false); } // アセットバンドル内のアセットが更新されている. if (info.hash != assetInfo.FileHash) { return(false); } } return(true); }
public void NonEmptyDictionary() { var value = new Dictionary <int, int> { { 1, 2 } }; Assert.False(value.IsEmpty()); }
/// <summary> /// 填充表单信息 /// </summary> /// <param name="stream"></param> /// <param name="formData">表单信息字典</param> public static Stream FillFormDataStream(this Stream stream, Dictionary <string, string> formData) { var formDataBytes = formData.IsEmpty() ? new byte[0] : Encoding.UTF8.GetBytes(formData.ToQueryString()); stream.Write(formDataBytes, 0, formDataBytes.Length); stream.Seek(0, SeekOrigin.Begin); return(stream); }
public void IsEmpty_Returns_False_When_Dictionary_Is_Not_Null_And_Not_Empty() { Dictionary <string, string> testValue = new Dictionary <string, string>(); testValue.Add("test1", "test1"); bool result = testValue.IsEmpty(); Assert.False(result); }
public bool GroupUsesPermissions(Guid groupId) { if (_groupsUsePermissions.IsEmpty()) { _groupsUsePermissions = this._dataSource.Query <Group>().ToDictionary(k => k.Id, v => v.UsePermissions); } return(_groupsUsePermissions[groupId]); }
public bool IsValid(object obj) { Validate(obj); if (errorMessages.IsEmpty()) { return(true); } return(false); }
public static Dictionary <string, object> Group(Dictionary <string, object> input) { Ensure.NotNull(input, "input"); if (input.IsEmpty()) { return(input); } var groupContainer = NewDictionary(); var hasSubGroups = false; foreach (var entry in input) { var groups = entry.Key.Split(SplitSeparator, StringSplitOptions.RemoveEmptyEntries); if (groups.Length < 2) { groupContainer.Add(entry.Key, entry.Value); continue; } hasSubGroups = true; string prefix = groups[0]; string remaining = string.Join(Separator, groups.Skip(1).ToArray()); if (!groupContainer.ContainsKey(prefix)) { groupContainer.Add(prefix, NewDictionary()); } ((Dictionary <string, object>)groupContainer[prefix]).Add(remaining, entry.Value); } if (!hasSubGroups) { return(groupContainer); } // we must first iterate through all dictionary and then aggregate it again var result = NewDictionary(); foreach (var entry in groupContainer) { var subgroup = entry.Value as Dictionary <string, object>; if (subgroup != null) { result[entry.Key] = Group(subgroup); } else { result[entry.Key] = entry.Value; } } return(result); }
public void EvaluateTrue(MatchedEventMap matchEvent, EvalStateNode fromNode, bool isQuitted) { int index; var hasIndex = Nodes.TryGetValue(fromNode, out index); bool[] isFollowedByQuitted = { false }; using (Instrument.With( i => i.QPatternFollowedByEvaluateTrue(EvalFollowedByNode, matchEvent, index), i => i.APatternFollowedByEvaluateTrue(isFollowedByQuitted[0]))) { if (isQuitted) { Nodes.Remove(fromNode); } // the node may already have quit as a result of an outer state quitting this state, // however the callback may still be received; It is fine to ignore this callback. if (!hasIndex) { return; } // If the match came from the very last filter, need to escalate int numChildNodes = EvalFollowedByNode.ChildNodes.Length; if (index == (numChildNodes - 1)) { if (Nodes.IsEmpty()) { isFollowedByQuitted[0] = true; } ParentEvaluator.EvaluateTrue(matchEvent, this, isFollowedByQuitted[0]); } // Else start a new sub-expression for the next-in-line filter else { EvalNode child = EvalFollowedByNode.ChildNodes[index + 1]; EvalStateNode childState = child.NewState(this, null, 0L); Nodes.Put(childState, index + 1); childState.Start(matchEvent); } } }
public static void SetupKingdomParties(MBReadOnlyList <MobileParty> mobileParties) { if (mobileParties == null) { return; } Dictionary <string, MobileParty> existingParties = new Dictionary <string, MobileParty>(); List <MobileParty> tempList = mobileParties.ToList(); tempList.ForEach(p => { // Campaign.Current.MobileParties can have some invalid entries, make sure only valid MobileParties get added for processing if (p.Leader?.Name != null && !existingParties.ContainsKey(p.Leader.Name.ToString())) { existingParties.Add(p.Leader.Name.ToString(), p); } }); if (existingParties.Count > 0 && KingdomConfigs.Any()) { KingdomConfigs.ForEach(kC => { Dictionary <string, KingdomLocation> lordLocations = LoadLocationsForKingdomConfiguration(kC); if (!lordLocations.IsEmpty() && lordLocations.Count > 0) { string[] names = new string[lordLocations.Count]; lordLocations.Keys.CopyTo(names, 0); List <string> lordsToAdd = names.ToList(); lordsToAdd.ForEach(lord => { if (existingParties.ContainsKey(lord)) { MobileParty p = existingParties[lord]; if (p?.Leader?.Name != null) { KingdomLocation location = lordLocations[lord]; Settlement targetSettlement = Settlement.Find(location.SettlementName); // Here we assign ownership of the targetSettlement to the KingdomLeaderId defined in config.xml if (p.Leader.StringId.Equals(kC.kingdomLeaderId)) { TaleWorlds.CampaignSystem.Actions.ChangeOwnerOfSettlementAction.ApplyByDefault(p.LeaderHero, targetSettlement); } // Move the party's position, use the XOffset and YOffset from the relevant locations.xml p.Position2D = new Vec2(targetSettlement.Position2D.X + location.XOffset, targetSettlement.Position2D.Y + location.YOffset); // Make them patrol around their location p.SetMovePatrolAroundSettlement(targetSettlement); } } }); } }); } }
public static string UrlCombineQuery(this string baseUrl, Dictionary <string, string> query, bool encode = false) { if (query.IsEmpty <KeyValuePair <string, string> >()) { return(baseUrl); } string str = query.MakeString <KeyValuePair <string, string> >((Func <KeyValuePair <string, string>, string>)(pair => pair.Key + "=" + (encode ? WebUtility.UrlEncode(pair.Value) : pair.Value)), "&"); return(baseUrl + "?" + str); }
/// <exception cref="System.IO.IOException"/> public virtual void TestSetupDistributedCacheEmpty() { Configuration conf = new Configuration(); IDictionary <string, LocalResource> localResources = new Dictionary <string, LocalResource >(); MRApps.SetupDistributedCache(conf, localResources); NUnit.Framework.Assert.IsTrue("Empty Config did not produce an empty list of resources" , localResources.IsEmpty()); }
// Returns a symbol table for all items. Used to resolve references and provide completion public ISymbolTable GetSymbolTable() { if (myDeclaredElements.IsEmpty()) { return(EmptySymbolTable.INSTANCE); } var psiServices = mySolution.GetComponent <IPsiServices>(); return(new DeclaredElementsSymbolTable <IDeclaredElement>(psiServices, myDeclaredElements.Values)); }
private void CanvasChangedHanler(object sender, SizeChangedEventArgs e) { if (_results.IsEmpty()) { return; } ClearCanvas(); FindMaxPointInResult(); FindMinPointInResult(); _results.ForEach(x => DrawResult(x.Key)); }
private static void Assert(string context) { if (_mapDic.IsEmpty()) { throw new InvalidOperationException(" map list is empty"); } if (!_mapDic.ContainsKey(context)) { throw new KeyNotFoundException(string.Format("{0}:key not find ", context)); } }
public StringMapper(Dictionary<String, String> input) { //copy the dictionary so it can't be modified. Only a shallow copy but Strings are immutable anyway this.data = new Dictionary<String, String>(input); //Desired result is something like "(?<=\\s|^)((Kappa)|(FailFish))(?=\\s|$)" StringBuilder regexBuilder = new StringBuilder(); //In order to ensure to not match Kappa to Kappa! or KappaRoss we need to ensure that before and after the match //is either a whitespace (\s) or a start (^) / end ($) of line. //However we do not want to capture the whitespaces since it would complicate our dictionary lookups: //http://stackoverflow.com/questions/3926451/how-to-match-but-not-capture-part-of-a-regex regexBuilder.Append(@"(?<=\s|^)("); foreach (var entry in input.Keys) { regexBuilder.Append("("); regexBuilder.Append(entry); regexBuilder.Append(")|"); } if(!input.IsEmpty()) regexBuilder.Remove(regexBuilder.Length - 1, 1); regexBuilder.Append(@")(?=\s|$)"); regex = new Regex(regexBuilder.ToString(), RegexOptions.Compiled); }
private ReadOnlyCollection<Node> FixupEvaluationOrder(ReadOnlyCollection<Node> seq) { var q_evalOrders = new Dictionary<Node, ReadOnlyCollection<IILOp>>(); seq.ForEach(q => q_evalOrders[q] = q.CSharpEvaluationOrder().Where(n => n != null) .Select(n => _map.GetOrDefault(n)).Where(op => op != null).ToReadOnly()); var evalOrder = q_evalOrders.SelectMany(kvp => kvp.Value).ToReadOnly(); var violatedDeps = new Dictionary<IILOp, ReadOnlyCollection<IILOp>>(); evalOrder.ForEach((op, i_op) => violatedDeps.Add(op, evalOrder.Where( (oop, i_oop) => i_op > i_oop && op.Offset < oop.Offset).ToReadOnly())); violatedDeps.RemoveElements(kvp => kvp.Value.IsEmpty()); if (violatedDeps.IsEmpty()) { return seq; } else { var fixt = seq.ToList(); foreach (var op in violatedDeps.Keys) { if (op is Call) { var call = op.AssertCast<Call>(); if (call.Method.IsGetter()) /* implemented */ {} else if (call.Method.IsSetter()) throw AssertionHelper.Fail(); else throw AssertionHelper.Fail(); } else if (op is New) /* presume that ctors are stateless */ {} else if (op is Ldloc) /* implemented */ {} else if (op is Ldarg) /* implemented */ {} else if (op is Ldelem) throw AssertionHelper.Fail(); else if (op is Ldfld) /* implemented */ {} else if (op is Ldloca) /* implemented */ {} else if (op is Ldarga) /* implemented */ {} else if (op is Ldelema) throw AssertionHelper.Fail(); else if (op is Ldflda) /* implemented */ {} else if (op is Ldind) throw AssertionHelper.Fail(); else if (op is Ldftn) throw AssertionHelper.Fail(); else if (op is Stloc) throw AssertionHelper.Fail(); else if (op is Starg) throw AssertionHelper.Fail(); else if (op is Stelem) throw AssertionHelper.Fail(); else if (op is Stfld) throw AssertionHelper.Fail(); else if (op is Stind) throw AssertionHelper.Fail(); // ops that neither read nor write from anywhere except stack // can be freely skipped so we have to consider only a dozen of ops else continue; if (op is Ldloc || op is Ldloca) { var ldloc = op as Ldloc; var ldloca = op as Ldloca; var loc_il = ldloc != null ? ldloc.Loc : ldloca != null ? ldloca.Loc : ((Func<ILocalVar>)(() => { throw AssertionHelper.Fail(); }))(); var violations = violatedDeps[op]; if (violations.OfType<Stloc>().Any(stloc => stloc.Index == loc_il.Index)) { var loc_sym = _symbols.ResolveLocal(loc_il.Index); var expr_ldloc = _mapOp(op).AssertCast<Ref>(); (expr_ldloc.Sym == loc_sym).AssertTrue(); var locName = loc_il.Source.DebugInfo == null ? ("loc" + loc_il.Index) : !loc_il.Source.DebugInfo.LocalNames.ContainsKey(loc_il.Index) ? ("loc" + loc_il.Index) : loc_il.Source.DebugInfo.LocalNames[loc_il.Index]; var bufLocName = Seq.Nats.Select(i => locName + "__CF$" + i.ToString("0000")).First(name1 => _symbols.Locals.None(loc1 => loc1.Name == name1)); var bufLoc = _symbols.IntroduceLocal(bufLocName, loc_il.Type); var startOfViolations = q_evalOrders.Keys.First(q => Set.Intersect(q_evalOrders[q], violations).IsNotEmpty()); q_evalOrders[startOfViolations].Except(violations).AssertEmpty(); var insertionPoint = fixt.IndexOf(startOfViolations); fixt.Insert(insertionPoint, new Assign(new Ref(bufLoc), new Ref(loc_sym))); expr_ldloc.Parent.Children.ReplaceElements(expr_ldloc, new Ref(bufLoc)); } } if (op is Ldarg || op is Ldarga) { var ldarg = op as Ldarg; var ldarga = op as Ldarga; var arg_il = ldarg != null ? ldarg.Arg : ldarga != null ? ldarga.Arg : ((Func<ParameterInfo>)(() => { throw AssertionHelper.Fail(); }))(); var arg_index = ldarg != null ? ldarg.Index : ldarga != null ? ldarga.Index : ((Func<int>)(() => { throw AssertionHelper.Fail(); }))(); var violations = violatedDeps[op]; if (violations.OfType<Starg>().Any(starg => starg.Index == arg_index)) { var arg_sym = _symbols.ResolveParam(arg_index); var expr_ldarg = _mapOp(op).AssertCast<Ref>(); (expr_ldarg.Sym == arg_sym).AssertTrue(); var argName = arg_sym.Name; var bufLocName = Seq.Nats.Select(i => argName + "__CF$" + i.ToString("0000")).First(name1 => _symbols.Locals.None(loc => loc.Name == name1)); var bufLoc = _symbols.IntroduceLocal(bufLocName, null); var startOfViolations = q_evalOrders.Keys.First(q => Set.Intersect(q_evalOrders[q], violations).IsNotEmpty()); q_evalOrders[startOfViolations].Except(violations).AssertEmpty(); var insertionPoint = fixt.IndexOf(startOfViolations); fixt.Insert(insertionPoint, new Assign(new Ref(bufLoc), new Ref(arg_sym))); expr_ldarg.Children.ReplaceElements(expr_ldarg, new Ref(bufLoc)); } } if (op is Ldfld || op is Ldflda) { var ldfld = op as Ldfld; var ldflda = op as Ldflda; var fld = ldfld != null ? ldfld.Field : ldflda != null ? ldflda.Field : ((Func<FieldInfo>)(() => { throw AssertionHelper.Fail(); }))(); var violations = violatedDeps[op]; if (violations.OfType<Stfld>().Any(stfld => stfld.Field == fld && ((Func<bool>)(() => { var stfld_fld = _mapOp(stfld).AssertCast<Assign>().Lhs.AssertCast<Fld>(); var ldfld_fld = _mapOp(op).AssertCast<Fld>(); return stfld_fld.This.Equiv(ldfld_fld.This); }))())) { var expr_ldfld = _mapOp(op).AssertCast<Fld>(); (expr_ldfld.Field == fld).AssertTrue(); var fldName = fld.Name; var bufLocName = Seq.Nats.Select(i => fldName + "__CF$" + i.ToString("0000")).First(name1 => _symbols.Locals.None(loc => loc.Name == name1)); var bufLoc = _symbols.IntroduceLocal(bufLocName, null); var startOfViolations = q_evalOrders.Keys.First(q => Set.Intersect(q_evalOrders[q], violations).IsNotEmpty()); q_evalOrders[startOfViolations].Except(violations).AssertEmpty(); var insertionPoint = fixt.IndexOf(startOfViolations); fixt.Insert(insertionPoint, new Assign(new Ref(bufLoc), new Fld(fld, expr_ldfld.This))); expr_ldfld.Children.ReplaceElements(expr_ldfld, new Ref(bufLoc)); } } if (op is Call) { var callGet = op.AssertCast<Call>(); callGet.Method.IsGetter().AssertTrue(); var violations = violatedDeps[callGet]; if (violations.OfType<Call>().Any(callSet => { if (!callSet.Method.IsSetter()) return false; if (!(callSet.Method.EnclosingProperty() == callGet.Method.EnclosingProperty())) return false; // todo. verify that both calls reference the same property // and have the same This (use Dump comparison and add a todo) throw new NotImplementedException(); })) { var prop = callGet.Method.EnclosingProperty().AssertNotNull(); var expr_callGet = _mapOp(callGet); // todo. verify that it references the "prop" property var rawName = callGet.Method.Name; var bufLocName = Seq.Nats.Select(i => rawName + "__CF$" + i.ToString("0000")).First(name1 => _symbols.Locals.None(loc => loc.Name == name1)); var bufLoc = _symbols.IntroduceLocal(bufLocName, null); var startOfViolations = q_evalOrders.Keys.First(q => Set.Intersect(q_evalOrders[q], violations).IsNotEmpty()); q_evalOrders[startOfViolations].Except(violations).AssertEmpty(); var insertionPoint = fixt.IndexOf(startOfViolations); fixt.Insert(insertionPoint, ((Func<Expression>)(() => { throw new NotImplementedException(); }))()); expr_callGet.Children.ReplaceElements(expr_callGet, new Ref(bufLoc)); } } } return fixt.ToReadOnly(); } }
private static Dictionary<string, DiffIndex> ApplyIndexAutoReplacements(DiffTable diff, ITable tab, Dictionary<string, Index> dictionary) { List<string> oldOnly = diff.Indices.Keys.Where(n => !dictionary.ContainsKey(n)).ToList(); List<string> newOnly = dictionary.Keys.Where(n => !diff.Indices.ContainsKey(n)).ToList(); if (oldOnly.Count == 0 || newOnly.Count == 0) return diff.Indices; Dictionary<string, string> replacements = new Dictionary<string, string>(); foreach (var o in oldOnly) { var oldIx = diff.Indices[o]; var nIx = newOnly.FirstOrDefault(n => { var newIx = dictionary[n]; if (oldIx.IsPrimary && newIx is PrimaryClusteredIndex) return true; if (oldIx.IsPrimary || newIx is PrimaryClusteredIndex) return false; if (oldIx.IsUnique != (newIx is UniqueIndex)) return false; if (oldIx.ViewName != null || (newIx is UniqueIndex) && ((UniqueIndex)newIx).ViewName != null) return false; var news = newIx.Columns.Select(c => diff.Columns.TryGetC(c.Name)?.Name).NotNull().ToHashSet(); if (!news.SetEquals(oldIx.Columns)) return false; var uix = newIx as UniqueIndex; if (uix != null && uix.Where != null && !oldIx.IndexName.EndsWith(StringHashEncoder.Codify(uix.Where))) return false; return true; }); if (nIx != null) { replacements.Add(o, nIx); newOnly.Remove(nIx); } } if (replacements.IsEmpty()) return diff.Indices; return diff.Indices.SelectDictionary(on => replacements.TryGetC(on) ?? on, dif => dif); }
private string chooseEncounterName() { string encounterName = null; Dictionary<string, int> damageCountMap = new Dictionary<string, int>(); string targetId; foreach (RiftAction riftAction in this.inProgressEncounterActions) { bool includeAction = RiftActionFilterFactory.getDamageTypes().Contains(riftAction.ActionType); if (includeAction) { targetId = riftAction.TargetId; RiftEntity target = getEntity(targetId); if ((target != null) && (target.OwnerId == null) && (!target.Relationship.IsPartyMember)) { int newValue = riftAction.SpellValue; String targetName = target.Name; int sumValue = damageCountMap.ContainsKey(targetName) ? damageCountMap[targetName] : 0; if (sumValue != 0) { newValue += sumValue; } if(damageCountMap.ContainsKey(targetName)) damageCountMap[targetName] = newValue; else damageCountMap.Add(targetName, newValue);} } } if (!damageCountMap.IsEmpty()) { String maxDamageName = null; int maxDamage = 0; foreach (var entry in damageCountMap) { int entryDamage = entry.Value; if (maxDamage < entryDamage) { maxDamage = entryDamage; maxDamageName = entry.Key; } } if (!string.IsNullOrEmpty(maxDamageName)) { encounterName = maxDamageName; } } if (encounterName == null) { encounterName = "Encounter"; } return encounterName; }
/// <exception cref="NGit.Errors.TransportException"></exception> private void VerifyPrerequisites() { if (prereqs.IsEmpty()) { return; } RevWalk rw = new RevWalk(transport.local); try { RevFlag PREREQ = rw.NewFlag("PREREQ"); RevFlag SEEN = rw.NewFlag("SEEN"); IDictionary<ObjectId, string> missing = new Dictionary<ObjectId, string>(); IList<RevObject> commits = new AList<RevObject>(); foreach (KeyValuePair<ObjectId, string> e in prereqs.EntrySet()) { ObjectId p = e.Key; try { RevCommit c = rw.ParseCommit(p); if (!c.Has(PREREQ)) { c.Add(PREREQ); commits.AddItem(c); } } catch (MissingObjectException) { missing.Put(p, e.Value); } catch (IOException err) { throw new TransportException(transport.uri, MessageFormat.Format(JGitText.Get().cannotReadCommit , p.Name), err); } } if (!missing.IsEmpty()) { throw new MissingBundlePrerequisiteException(transport.uri, missing); } foreach (Ref r in transport.local.GetAllRefs().Values) { try { rw.MarkStart(rw.ParseCommit(r.GetObjectId())); } catch (IOException) { } } // If we cannot read the value of the ref skip it. int remaining = commits.Count; try { RevCommit c; while ((c = rw.Next()) != null) { if (c.Has(PREREQ)) { c.Add(SEEN); if (--remaining == 0) { break; } } } } catch (IOException err) { throw new TransportException(transport.uri, JGitText.Get().cannotReadObject, err); } if (remaining > 0) { foreach (RevObject o in commits) { if (!o.Has(SEEN)) { missing.Put(o, prereqs.Get(o)); } } throw new MissingBundlePrerequisiteException(transport.uri, missing); } } finally { rw.Release(); } }