public static void ShowGroupedResults(TextWriter wr = null) { if (wr == null) { wr = Console.Out; } var r = new Dictionary <int, List <int> >(); var teams = File.ReadLines("teams.csv") .Select(z => z.Split(';')) .ToDictionary(z => int.Parse(z[0]), z => z[1]); var results = File.ReadLines("results.json").Select(JsonConvert.DeserializeObject <TournamentGameResult>).ToList(); foreach (var e in results) { r.SafeGet(e.Task.Participants[0].Id).Add(GetScores(e, "Left")); r.SafeGet(e.Task.Participants[1].Id).Add(GetScores(e, "Right")); } var s = r.Select(x => new { x.Key, Av = x.Value.Average(), Cn = x.Value.Count() }) .OrderByDescending(z => z.Av) .Select((z, i) => string.Format("{0,-3}{1,-40}{2,-5}{3,-3} {4}", i, teams[z.Key], z.Key, z.Cn, z.Av)) .Aggregate((a, b) => a + "\n" + b); wr.WriteLine(s); }
public void Add(string animationKey, AnimationDNABlock animationDnaBlock) { string cacheKey = animationKey.Split('_').FirstOrDefault(); var cache = _cacheLookup.SafeGet(cacheKey); cache[animationKey] = animationDnaBlock; }
public void SafeGet_DictionaryOfQueryable_NotFound_ShouldReturnDefault() { QueryableProperty expected = null; var actual = dictionaryOfQueryable.SafeGet("test"); Assert.Equal(expected, actual); }
public void SafeGet_DictionaryOfStrings_NotFound_ShouldReturnDefault() { string expected = null; var actual = dictionaryOfStrings.SafeGet("test"); Assert.Equal(expected, actual); }
public void SafeGet_From_Dictionary_Test() { var obj = new Dictionary <string, int> { { "a", 1 } }; Assert.Equal(1, obj.SafeGet(x => x["a"])); Assert.Equal(0, obj.SafeGet(x => x["b"])); }
public AnimationDNABlock Get(string animationKey) { AnimationDNABlock returnVal; var cacheKey = animationKey.Split('_').FirstOrDefault(); var cache = _cacheLookup.SafeGet(cacheKey); cache.TryGetValue(animationKey, out returnVal); return(returnVal); }
public FileRenameParameterReplacements(Dictionary <string, string> genParameters) { FileRenameParams = new Dictionary <string, string>() { { "Param_ProjectName", genParameters.SafeGet(GenParams.ProjectName) }, { "Param_SourceName_Kebab", genParameters.SafeGet("wts.sourceName.casing.kebab") }, { "Param_SourceName_Pascal", genParameters.SafeGet("wts.sourceName.casing.pascal") }, { "Param_SourceName_Camel", genParameters.SafeGet("wts.sourceName.casing.camel") }, }; }
public static void GetException(this Dictionary <string, object> dict) { var isError = dict.SafeGet("IsError", false); if (isError) { var rawException = dict.SafeGet("Exception", new Dictionary <string, object>()); var className = rawException.SafeGet("ClassName", string.Empty); var message = rawException.SafeGet("Message", string.Empty); var stackTraceString = rawException.SafeGet("StackTraceString", string.Empty); throw new ServerException(className + ": " + message + "\n\nSTACKTRACE: " + stackTraceString); } }
public Type GetView(Type viewModelType) { var viewTypeInfo = m_htTypes.SafeGet(viewModelType); if (viewTypeInfo == null) { var baseType = viewModelType.GetTypeInfo( ).BaseType; viewTypeInfo = m_htTypes.SafeGet(baseType); return(viewTypeInfo); } else { return(viewTypeInfo); } }
protected void Initialize() { _platform = _replacementsDictionary.SafeGet("$wts.platform$"); _appModel = _replacementsDictionary.SafeGet("$wts.appmodel$"); _language = _replacementsDictionary.SafeGet("$wts.language$"); if (GenContext.CurrentLanguage != _language || GenContext.CurrentPlatform != _platform) { #if DEBUG GenContext.Bootstrap(new LocalTemplatesSource(string.Empty), new VsGenShell(), _platform, _language); #else var mstxFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "InstalledTemplates"); GenContext.Bootstrap(new RemoteTemplatesSource(_platform, _language, mstxFilePath, new DigitalSignatureService()), new VsGenShell(), _platform, _language); #endif } }
public FileRenameParameterReplacements(Dictionary <string, string> genParameters) { FileRenameParams = new Dictionary <string, string>() { { "Param_ProjectName", genParameters.SafeGet(GenParams.ProjectName) }, }; }
private static KeyValuePair <int, int> GetMapCoordinatesForNPC(NPC character) { string locationName = character.currentLocation?.Name ?? character.DefaultMap; // Ginger Island if (character.currentLocation is IslandLocation) { return(new KeyValuePair <int, int>(1104, 658)); } // Scale Town and Forest if (locationName == "Town" || locationName == "Forest") { int xStart = locationName == "Town" ? 595 : 183; int yStart = locationName == "Town" ? 163 : 378; int areaWidth = locationName == "Town" ? 345 : 319; int areaHeight = locationName == "Town" ? 330 : 261; xTile.Map map = character.currentLocation.Map; float xScale = (float)areaWidth / (float)map.DisplayWidth; float yScale = (float)areaHeight / (float)map.DisplayHeight; float scaledX = character.position.X * xScale; float scaledY = character.position.Y * yScale; int xPos = (int)scaledX + xStart; int yPos = (int)scaledY + yStart; return(new KeyValuePair <int, int>(xPos, yPos)); } // Other known locations return(_mapLocations.SafeGet(locationName, new KeyValuePair <int, int>(0, 0))); }
/// <exception cref="System.Xml.XPath.XPathException"></exception> private void ValidateSingleNode(XmlNode baseNode, string containedNodeXPath, Hl7Errors validationResult) { XmlNodeList baseTemplateIds = xPathHelper.GetNodes(baseNode, "cda:templateId/@root", PREFIX, NAMESPACE); for (int j = 0, jlength = baseTemplateIds.Count; j < jlength; j++) { string templateId = baseTemplateIds.Item(j).Value; PackageLocation packageLocation = packagesByOid.SafeGet(templateId); if (packageLocation != null && packageLocation.ContainedTemplateConstraints != null && !packageLocation.ContainedTemplateConstraints .IsEmpty()) { XmlNodeList containedTemplateIds = xPathHelper.GetNodes(baseNode, containedNodeXPath, PREFIX, NAMESPACE); Dictionary <string, Int32?> containedTemplateMap = PopulateContainedTemplateMap(containedTemplateIds); foreach (ContainedTemplate containedTemplate in packageLocation.ContainedTemplateConstraints) { Int32?count = containedTemplateMap.SafeGet(containedTemplate.TemplateOid); if (count == null) { count = 0; } if (!containedTemplate.Cardinality.Contains((int)count)) { //Cast for .NET validationResult.AddHl7Error(new Hl7Error(Hl7ErrorCode.CDA_CARDINALITY_CONSTRAINT, "Expected [" + containedTemplate.RawCardinality + "] instances of template " + containedTemplate.TemplateOid + ", but found " + count, baseNode)); } } } } }
void ParseParagraph(HtmlNode node, Style style) { if (_currentParagraph.Inlines.Count > 0) { ConvertedBlocks.Add(_currentParagraph); } _currentParagraph = new Paragraph(); var className = node.GetClassName(); if (!string.IsNullOrEmpty(className)) { var cssStyle = _cssStyles.SafeGet(className); if (cssStyle != default(Style)) { var newStyle = new Style(style); newStyle.RebaseOn(cssStyle); _currentParagraph.ApplyStyle(newStyle); } } foreach (var child in node.ChildNodes) { _currentParagraph.Inlines.SafeAdd(ParseNode(child, style)); } }
public virtual void TestSafeGetKeyDoesNotExist() { IDictionary <string, string> dictionary = new Dictionary <string, string>(); dictionary.Add("key", "value"); Assert.IsNull(dictionary.SafeGet("some-other-key")); }
public virtual void TestSafeGetKeyExists() { IDictionary <string, string> dictionary = new Dictionary <string, string>(); dictionary.Add("key", "value"); Assert.AreEqual("value", dictionary.SafeGet("key")); }
protected override object DoGetInstance(Type serviceType, string key) { return (m_additionalTypes.SafeGet(serviceType) ?? (key != null ? m_context.Resolve(serviceType, new [] { new NamedParameter("key", key) }) : m_context.SafeResolve(serviceType))); }
public void CanSafeGetValueTypeDictionaryValueWhenTheValueNotExists() { var seq = new Dictionary <int, int>() { { 2, 3 }, { 4, 5 } }; seq.SafeGet(3).Should().Be(0); }
public void CanSafeGetReferenceTypeDictionaryValueWhenTheValueNotExists() { var seq = new Dictionary <string, string>() { { "2", "3" }, { "4", "5" } }; seq.SafeGet("3").Should().Be(null); }
public static string Get(string key) { if (dictionary != null && dictionary.ContainsKey(key)) { return(dictionary[key]); } Initial(); return(dictionary.SafeGet(key)); }
public static RedisConfig Get(int key) { if (dictionary != null && dictionary.ContainsKey(key)) { return(dictionary[key]); } Initial(); return(dictionary.SafeGet(key)); }
public IEntityService <TEntity> GetEntityService <TEntity> () where TEntity : Entity, new() { var factory = m_factories.SafeGet(typeof(TEntity)) as Func <IDataContextProvider, long, IEntityService <TEntity> >; if (factory == null) { throw new InvalidOperationException($"Service is not available for type '{typeof(TEntity).Name}'"); } return(factory(m_provider, m_userId)); }
public string ConvertLaTeXToImages() { string newSelection = LaTeXConst.RE.LaTeXError.Replace(Selection, string.Empty); var filters = Config.Filters; var allTaggedMatches = filters.Select( f => (f.Value, f.Key.Matches(Selection)) ); foreach (var taggedMatches in allTaggedMatches) { var itemsOccurences = new Dictionary <string, int>(); var processedMatches = GenerateImages(taggedMatches.Item1, taggedMatches.Item2); foreach (var processedMatch in processedMatches) { var(success, imgHtmlOrError, fullHtml) = processedMatch; int nb = itemsOccurences.SafeGet(fullHtml, 0) + 1; itemsOccurences[fullHtml] = nb; if (success) { try { newSelection = newSelection.ReplaceNth(fullHtml, imgHtmlOrError, nb); } catch (Exception ex) { success = false; imgHtmlOrError = ex.Message; } } if (success == false) { newSelection = newSelection.ReplaceNth(fullHtml, GenerateErrorHtml(fullHtml, imgHtmlOrError), nb); } } } Html = Html.Replace(Selection, newSelection); Selection = newSelection; return(Html); }
public DelegateTriggerMachine <TTrigger, TEnumComparer> Connect(StateDelegate source, TTrigger trigger, StateDelegate destination) { Add(source); Add(destination); var transitions = connections.SafeGet(source.Method); transitions[trigger] = destination.Method; return(this); }
public void Send <T> (T message) where T : IMessage { Contract.AssertNotNull(() => message, message); Array listeners = null; m_rwlListeners.ReadLocked(() => { System.Collections.IList listenersRaw = m_listenersByMessageType.SafeGet(message.GetType( )); if (listenersRaw != null) { lock ( listenersRaw ) { if (listenersRaw.Count > 0) { listeners = new object [listenersRaw.Count]; listenersRaw.CopyTo(listeners, 0); } } } }); if (listeners != null) { LogMessage(message, listeners); foreach (IListener <T> listener in listeners) { // clousure binding fixup IListener <T> listenerCopy = listener; if (message.IsAsync) { Runner.RunAsync(() => listenerCopy.Receive(message)); } else { Runner.RunWrapped(() => listenerCopy.Receive(message)); } } } else if (typeof(T) != typeof(StatusMessage)) { Logger.Log( StatusMessage.Types.Debug, string.Format("Noone Listening for Message : Type = '{0}', Message = '{1}'.", typeof(T).FullName, message), null, "BandSox.Utility.Messaging.Bus.Send<T>()"); } Fabric?.Send(message); }
public MtkPluginParameters GetParameters(Dictionary <string, object> parameters) { string url = parameters["url"].ToString(); return(new MtkPluginParameters { Url = url, PageType = pageTypeResolver.GetPageType(url), Content = parameters.SafeGet("content", "").ToString() }); }
static TsDateFormats() { IDictionary <StandardDataType, IList <string> > map = new Dictionary <StandardDataType, IList <string> >(); map[StandardDataType.TS_FULLDATETIME] = Arrays.AsList("yyyyMMddHHmmss.SSS0ZZZZZ", "yyyyMMddHHmmss.SSSZZZZZ", "yyyyMMddHHmmssZZZZZ" ); map[StandardDataType.TS_FULLDATEPARTTIME] = Arrays.AsList("yyyyMMddHHmmss.SSS0ZZZZZ", "yyyyMMddHHmmss.SSS0", "yyyyMMddHHmmss.SSSZZZZZ" , "yyyyMMddHHmmss.SSS", "yyyyMMddHHmmssZZZZZ", "yyyyMMddHHmmss", "yyyyMMddHHmmZZZZZ", "yyyyMMddHHmm", "yyyyMMddHHZZZZZ", "yyyyMMddHH", "yyyyMMddZZZZZ", "yyyyMMdd"); // not allowed if non-CeRx // not allowed if non-CeRx // not allowed if non-CeRx // not allowed if non-CeRx // not allowed if non-CeRx map[StandardDataType.TS_FULLDATE] = Arrays.AsList("yyyyMMdd"); // this is an abstract type and these formats are only used after issuing a warning (there should be a specializationType); only defined in MR2009 map[StandardDataType.TS_FULLDATEWITHTIME] = Arrays.AsList("yyyyMMddHHmmss.SSS0ZZZZZ", "yyyyMMddHHmmss.SSSZZZZZ", "yyyyMMddHHmmssZZZZZ" , "yyyyMMdd"); map[StandardDataType.TS_DATE] = Arrays.AsList("yyyyMMdd", "yyyyMM", "yyyy"); map[StandardDataType.TS_DATETIME] = Arrays.AsList("yyyyMMddHHmmss.SSS0ZZZZZ", "yyyyMMddHHmmss.SSS0", "yyyyMMddHHmmss.SSSZZZZZ" , "yyyyMMddHHmmss.SSS", "yyyyMMddHHmmssZZZZZ", "yyyyMMddHHmmss", "yyyyMMddHHmmZZZZZ", "yyyyMMddHHmm", "yyyyMMddHHZZZZZ", "yyyyMMddHH", "yyyyMMddZZZZZ", "yyyyMMdd", "yyyyMMZZZZZ", "yyyyMM", "yyyyZZZZZ", "yyyy"); // not allowed if non-CeRx // not allowed if non-CeRx // not allowed if non-CeRx // not allowed if non-CeRx // not allowed if non-CeRx map[StandardDataType.TS] = map.SafeGet(StandardDataType.TS_DATETIME); formats = Ca.Infoway.Messagebuilder.CollUtils.CreateUnmodifiableDictionary(map); datetimeFormatsRequiringWarning = Arrays.AsList("yyyyMMddHHmmss.SSS0", "yyyyMMddHHmmss.SSS", "yyyyMMddHHmmss", "yyyyMMddHHmm" , "yyyyMMddHH"); IDictionary <string, string> _expandedFormats = new Dictionary <string, string>(); _expandedFormats["yyyyMMddHHmmss.SSSZZZZZ"] = "yyyyMMddHHmmss.SSS0ZZZZZ"; _expandedFormats["yyyyMMddHHmmss.SSS"] = "yyyyMMddHHmmss.SSS0"; expandedFormats = Ca.Infoway.Messagebuilder.CollUtils.CreateUnmodifiableDictionary(_expandedFormats); // some older versions have slightly different rules for allowable time formats IDictionary <StandardDataType, IList <string> > exceptionMapMR2007 = new Dictionary <StandardDataType, IList <string> >(); exceptionMapMR2007[StandardDataType.TS_FULLDATEWITHTIME] = CollUtils.EmptyList <string>(); IDictionary <StandardDataType, IList <string> > exceptionMapCeRx = new Dictionary <StandardDataType, IList <string> >(); exceptionMapCeRx[StandardDataType.TS_FULLDATEWITHTIME] = CollUtils.EmptyList <string>(); exceptionMapCeRx[StandardDataType.TS_FULLDATETIME] = Arrays.AsList("yyyyMMddHHmmss"); exceptionMapCeRx[StandardDataType.TS_DATETIME] = Arrays.AsList("yyyyMMddHHmmss.SSS0", "yyyyMMddHHmmss.SSS", "yyyyMMddHHmmss" , "yyyyMMddHHmm", "yyyyMMddHH", "yyyyMMdd", "yyyyMM", "yyyy"); IDictionary <Hl7BaseVersion, IDictionary <StandardDataType, IList <string> > > versionMap = new Dictionary <Hl7BaseVersion, IDictionary <StandardDataType, IList <string> > >(); versionMap[Hl7BaseVersion.MR2007] = Ca.Infoway.Messagebuilder.CollUtils.CreateUnmodifiableDictionary(exceptionMapMR2007); versionMap[Hl7BaseVersion.CERX] = Ca.Infoway.Messagebuilder.CollUtils.CreateUnmodifiableDictionary(exceptionMapCeRx); versionFormatExceptions = Ca.Infoway.Messagebuilder.CollUtils.CreateUnmodifiableDictionary(versionMap); }
/// <summary> /// Gets the fitting orthographic size in bounds. /// </summary> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="gameObject">The game object.</param> /// <param name="f_forceMax">if set to <c>true</c> [f force maximum].</param> /// <returns></returns> /// <exception cref="System.Exception">GameObject has no Renderers!</exception> public static float GetFittingOrthographicSizeInBounds(float width, float height, GameObject gameObject, bool f_forceMax = false) { if (f_forceMax && ortSizes.ContainsKey(gameObject.name)) { return(ortSizes.SafeGet(gameObject.name)); } var renderers = gameObject.GetComponentsInChildren <Renderer>(); if (renderers.Length == 0) { throw new Exception("GameObject has no Renderers!"); } Bounds targetBounds = GetEncapsulatedBounds(gameObject, renderers); float screenRatio = width / height; float targetRatio = targetBounds.size.x / targetBounds.size.y; // TODO: Why I need this padding? float padding = Mathf.Sqrt(Mathf.Sqrt(2)); float finalOrt = 0; if (screenRatio >= targetRatio) { finalOrt = targetBounds.size.y / 2 * padding; } else { float differenceInSize = targetRatio / screenRatio; finalOrt = targetBounds.size.y / 2 * differenceInSize * padding; } if (finalOrt > ortSizes.SafeGet(gameObject.name)) { ortSizes.AddOrSet(gameObject.name, finalOrt); } return(finalOrt); }
public void SetPlayer(int playerIndex, GameObject player) { GameObject previousPlayer = _players.SafeGet(playerIndex, null); if (previousPlayer != null) { Destroy(previousPlayer); } _players[playerIndex] = player; Player playerComponent = player.GetComponent<Player>(); playerComponent.PlayerIndex = playerIndex; DTGameEngineNotifications.PlayerChanged.Invoke(playerIndex, player); }
private string[] GetTodaysRecipe() { String[] array1 = new string[2]; int recipeNum = (int)(Game1.stats.DaysPlayed % 224 / 7); //var recipes = Game1.content.Load<Dictionary<String, String>>("Data\\TV\\CookingChannel"); String recipeValue = _recipes.SafeGet(recipeNum.ToString()); String[] splitValues = null; String key = null; bool checkCraftingRecipes = true; if (String.IsNullOrEmpty(recipeValue)) { recipeValue = _recipes["1"]; checkCraftingRecipes = false; } splitValues = recipeValue.Split('/'); key = splitValues[0]; ///Game code sets this to splitValues[1] to display the language specific ///recipe name. We are skipping a bunch of their steps to just get the ///english name needed to tell if the player knows the recipe or not array1[0] = key; if (checkCraftingRecipes) { String craftingRecipesValue = CraftingRecipe.cookingRecipes.SafeGet(key); if (!String.IsNullOrEmpty(craftingRecipesValue)) { splitValues = craftingRecipesValue.Split('/'); } } string languageRecipeName = (_helper.Content.CurrentLocaleConstant == LocalizedContentManager.LanguageCode.en) ? key : splitValues[splitValues.Length - 1]; array1[1] = languageRecipeName; //String str = null; //if (!Game1.player.cookingRecipes.ContainsKey(key)) //{ // str = Game1.content.LoadString(@"Strings\StringsFromCSFiles:TV.cs.13153", languageRecipeName); //} //else //{ // str = Game1.content.LoadString(@"Strings\StringsFromCSFiles:TV.cs.13151", languageRecipeName); //} //array1[1] = str; return(array1); }
protected void ResampleGaussian() { while (transform.childCount != 0) { GameObject.DestroyImmediate(transform.GetChild(0).gameObject); } Assert.IsTrue(_dot != null); Dictionary<int, int> distributionMapping = new Dictionary<int, int>(); if (_dot != null) { for (int i = 0; i < _pointsToGenerate; i++) { int val = (int)Mathf.Round(MathUtil.SampleGaussian(_mean, _standardDeviation)); int oldCount = distributionMapping.SafeGet(val, 0); GameObject dotClone = MonoBehaviour.Instantiate(_dot, Vector3.zero, Quaternion.identity) as GameObject; this.SetSelfAsParent(dotClone); dotClone.transform.localPosition = new Vector3(val, oldCount, 0.0f); dotClone.GetComponent<SpriteRenderer>().color = ColorExtensions.RandomPleasingColor(); distributionMapping[val] = oldCount + 1; } } }
private void GenerateProxyMethods(IEnumerable<Type> interfaces, TypeDefinition proxyType) { var methodsExcludingGetters = interfaces .SelectMany(x => x.GetMethods().Except(x.GetProperties().SelectMany(GetPropertyMethods))); foreach (var targetMethod in methodsExcludingGetters) { var baseDef = this.proxyBaseTypeDef; if (BaseTypeHasMatchingPublicMethod(baseDef, targetMethod)) continue; var genArgMapping = new Dictionary<Type, Type>(); if (targetMethod.DeclaringType == null) throw new InvalidOperationException($"{targetMethod} has no declaring type."); if (targetMethod.DeclaringType.IsGenericType) { var declTypeGenArgs = targetMethod.DeclaringType .GetGenericArguments() .Zip(targetMethod.DeclaringType.GetGenericTypeDefinition().GetGenericArguments(), (a, p) => new { a, p }); foreach (var declTypeGenArg in declTypeGenArgs) genArgMapping.Add(declTypeGenArg.p, declTypeGenArg.a); } Func<Type, Type> typeReplacer = t => TypeUtils.ReplaceInGenericArguments(t, x => genArgMapping.SafeGet(x, x)); var parameters = targetMethod.GetParameters(); var paramTypes = parameters.Select(x => x.ParameterType).ToArray(); var method = proxyType.DefineMethod(targetMethod.Name, MethodAttributes.NewSlot | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public, targetMethod.ReturnType, paramTypes); CopyGenericMethodParameters(targetMethod, method, genArgMapping, typeReplacer); AdjustParameterTypes(parameters, typeReplacer, method); var proxyOnGetMethod = baseDef .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .FirstOrDefault(x => x.Name == "OnInvokeMethod"); if (proxyOnGetMethod == null) { var message = $"Unable to generate proxy for {targetMethod.GetFullNameWithSignature()} because {baseDef.FullName}.OnInvokeMethod() is missing."; throw new MissingMethodException(message); } GenerateInvokeMethodIl(method, paramTypes, parameters, proxyOnGetMethod); } }
public void CanSafeGetValueTypeDictionaryValueWhenTheValueNotExists() { var seq = new Dictionary<int, int>() { { 2, 3 }, { 4, 5 } }; seq.SafeGet(3).Should().Be(0); }
public void CanSafeGetReferenceTypeDictionaryValueWhenTheValueNotExists() { var seq = new Dictionary<string, string>() { { "2", "3" }, { "4", "5" } }; seq.SafeGet("3").Should().Be(null); }