public static int GetNearestLevel(IDictionary<int, Resolution> resolutions, double resolution) { if (resolutions.Count == 0) { throw new ArgumentException("No tile resolutions"); } //smaller than smallest if (resolutions.Last().Value.UnitsPerPixel > resolution) return resolutions.Last().Key; //bigger than biggest if (resolutions.First().Value.UnitsPerPixel < resolution) return resolutions.First().Key; int result = 0; double resultDistance = double.MaxValue; foreach (var key in resolutions.Keys) { double distance = Math.Abs(resolutions[key].UnitsPerPixel - resolution); if (distance < resultDistance) { result = key; resultDistance = distance; } } return result; }
public async Task <decimal> GetConversion(string fromCode, string toCode) { var url = $"convert?q={fromCode}_{toCode}&compact=y"; IDictionary <string, JToken> response = await GetAsync(url); var val = response?.First().Value.First().First().Value <float>(); //{"EUR_USD":{"val":1.19403}} return(response?.First().Value.First().First().Value <decimal>() ?? 0); }
private void SetToDataGridViewResult(IDictionary<bool[], bool[]> results) { InitializeDataGridViewResult(results.First().Key.Length, results.First().Value.Length); dataGridViewResult.Rows.Clear(); List<int[]> result = new List<int[]>(); foreach (KeyValuePair<bool[], bool[]> item in results) { int[] currentRes = new int[item.Key.Length + item.Value.Length]; for (int i = 0; i < item.Key.Length; i++) { if (item.Key[i]) { currentRes[i] = 1; } else { currentRes[i] = 0; } } for (int i = 0; i < item.Value.Length; i++) { if (item.Value[i]) { currentRes[item.Key.Length + i] = 1; } else { currentRes[item.Key.Length + i] = 0; } } result.Add(currentRes); } for (int i = 0; i < result.Count; i++) { dataGridViewResult.Rows.Add(); for (int j = 0; j < result[i].Length; j++) { dataGridViewResult.Rows[i].Cells[j].Value = result[i][j]; } } }
public PullAPIResponse PullRequest(IDictionary<string, object> prms) { string response = null; PullAPIResponse result = new PullAPIResponse() { PullDetails = new PullInfo() }; var id = (string)prms.First(p => p.Key == "id").Value; switch (id) { case "08b923395b6ce8bfa4d96f57jsonmeta": response = MockAPIResponses.Default.PullJsonMetaFormat; result.PullDetails.Format = "json_meta"; break; case "08b923395b6ce8bfa4d96f5jsonarray": response = MockAPIResponses.Default.PullJsonArrayFormat; result.PullDetails.Format = "json_array"; break; case "08b923395b6ce8bfa4d96jsonnewline": response = MockAPIResponses.Default.PullJsonNewLineFormat; result.PullDetails.Format = "json_new_line"; break; } result.StatusCode = HttpStatusCode.OK; if (response != null) { result.Data = APIHelpers.DeserializeResponse(response, result.PullDetails.Format); } return result; }
/// <summary>Resolve untyped parameters used for the code or expression.</summary> /// <param name="scope">The expression scope for the code or expression to compile.</param> /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param> /// <returns>A ParameterExpression list used in code or expression to compile.</returns> private static List<ParameterExpression> ResolveParameterUntyped(ExpressionScope scope, IDictionary<string, Type> parameterTypes, bool forceFirstParameterProperty = false) { var parameters = new List<ParameterExpression>(); foreach (var parameter in parameterTypes) { var parameterExpression = scope.CreateParameter(typeof (object)); parameters.Add(parameterExpression); scope.CreateLazyVariable(parameter.Key, new Lazy<Expression>(() => { var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key); var innerExpression = parameterExpression.Type != parameter.Value ? Expression.Assign(innerParameter, Expression.Convert(parameterExpression, parameter.Value)) : Expression.Assign(innerParameter, parameterExpression); scope.Expressions.Insert(0, innerExpression); return innerParameter; })); } if (parameterTypes.Count == 1 || (parameterTypes.Count > 0 && forceFirstParameterProperty)) { var keyValue = parameterTypes.First(); if (Type.GetTypeCode(keyValue.Value) == TypeCode.Object) { ResolzeLazyMember(scope, parameterTypes, keyValue.Key, keyValue.Value); } } return parameters; }
/// <summary> /// Update any existing rows for the given values, and remove them from the values collection. /// </summary> /// <param name="configName"></param> /// <param name="values"></param> /// <param name="conn"></param> /// <param name="transaction"></param> /// <returns></returns> public bool UpdateExisting(string configName, IDictionary<long, MonitorRecord<double>> values, IDbConnection conn, IDbTransaction transaction = null) { var result = false; if (values.Count == 0) return true; MonitorInfo monitorInfo; if (_cache.MonitorInfo.TryGetValue(configName, out monitorInfo)) { var reduceLevel = monitorInfo.FirstReduceLevel; var reduceMethod = reduceLevel.AggregationClass; var startTime = values.First().Value.TimeStamp; var tableName = Support.MakeReducedName(configName, reduceLevel.Resolution); var updateList = new List<MonitorRecord<double>>(); var combineList = new List<MonitorRecord<double>>(); //Based on the timestamp we have we pull out from the database all recrods that have a date //grater than the timestamp we have. For each value we find loop through and find the value //that is the next greatest time past our current value from the database var existingList = _storageCommands.SelectListForUpdateExisting(tableName, startTime, conn, transaction); foreach (var existingValue in existingList) { var hasNext = false; var matchingValue = _cache.Empty; var valuesEnumerator = values.GetEnumerator(); while ((hasNext = valuesEnumerator.MoveNext()) && ((matchingValue = valuesEnumerator.Current.Value).TimeStamp < existingValue.TimeStamp)) ; combineList.Clear(); if (hasNext && !_cache.Empty.Equals(matchingValue)) { combineList.Add(existingValue); combineList.Add(matchingValue); values.Remove(matchingValue.TimeStamp.Ticks); } else continue; //Reduce the value we have from the database with the value we have here (thats what is in the combined list) var update = reduceMethod.Reduce(existingValue.TimeStamp, combineList); updateList.Add(update); } //Update everything in the database _storageCommands.Update(tableName, updateList, conn, transaction); result = true; } else throw new DataException("No monitor config found for " + configName); return result; }
public ResultCachesViewsPanel (IDictionary<ContextBase, ResultCache> target, SourceView master) { Target = target; Master = master; var selector = true.CreateLineupView (Target.Keys.Select(i => i.CreateLink(this)).ToArray()); Client = false.CreateLineupView(selector, Target.First().CreateView(Master)); }
private static string SubstituteRouteParameters(string endpointUri, IDictionary<string, string> parameters) { var regex = new Regex("{(.*?)}"); var result = regex.Matches(endpointUri); foreach (var match in result) { var key = match.ToString().Remove(match.ToString().Length - 1).Remove(0, 1); var entry = parameters.First(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); parameters.Remove(entry.Key); endpointUri = endpointUri.Replace(match.ToString(), entry.Value); } return endpointUri.ToLower(); }
public ShardStrategy(IDictionary<string, IAsyncFilesCommands> shards) { if (shards == null) throw new ArgumentNullException("shards"); if (shards.Count == 0) throw new ArgumentException("Shards collection must have at least one item", "shards"); this.shards = new Dictionary<string, IAsyncFilesCommands>(shards, StringComparer.OrdinalIgnoreCase); Conventions = shards.First().Value.Conventions.Clone(); ShardAccessStrategy = new SequentialShardAccessStrategy(); ShardResolutionStrategy = new DefaultShardResolutionStrategy(shards.Keys, this); ModifyFileName = (convention, shardId, documentId) => convention.IdentityPartsSeparator + shardId + convention.IdentityPartsSeparator + documentId; }
private static void AssertResponseHeadersAreExpected(IEnumerable<KeyValuePair<string, string>> expectedResponseHeaders, IDictionary<string, string> actualResponseHeaders) { foreach (var expectedHeader in expectedResponseHeaders) { if (!actualResponseHeaders.ContainsKey(expectedHeader.Key)) { throw new UnexpectedResponseHeaderException(expectedHeader.Key, expectedHeader.Value); } var actualValue = actualResponseHeaders.First(h => h.Key == expectedHeader.Key).Value; if (actualValue != expectedHeader.Value) { throw new UnexpectedResponseHeaderException(expectedHeader.Key, expectedHeader.Value, actualValue); } } }
/// <summary> /// Replaces tokens in the template text with the values from the supplied dictionary /// </summary> /// <param name="templateText">The template text</param> /// <param name="tokenValues">Dictionary mapping token names to values</param> /// <returns>Text with tokens replaced with their corresponding values from the dictionary</returns> public string ReplaceTokens(string templateText, IDictionary<string, string> tokenValues) { var output = RegExToken.Replace(templateText, (match) => { var tokenName = match.Groups["TokenName"].Value.ToLower(); try { KeyValuePair<string, string> property = tokenValues.First(x => x.Key.ToLower() == tokenName); return property.Value; } catch (Exception) { throw new ArgumentException("No value supplied for token: " + tokenName); } }); return output; }
/// <summary>Resolve typed parameters used for the code or expression.</summary> /// <param name="scope">The expression scope for the code or expression to compile.</param> /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param> /// <returns>A ParameterExpression list used in code or expression to compile.</returns> private static List<ParameterExpression> ResolveParameterTyped(ExpressionScope scope, IDictionary<string, Type> parameterTypes) { var parameters = new List<ParameterExpression>(); foreach (var parameter in parameterTypes) { parameters.Add(scope.CreateParameter(parameter.Value, parameter.Key)); } if (parameterTypes.Count == 1) { var keyValue = parameterTypes.First(); if (Type.GetTypeCode(keyValue.Value) == TypeCode.Object) { ResolzeLazyMember(scope, parameterTypes, keyValue.Key, keyValue.Value); } } return parameters; }
/// <summary> /// Generates a server pfx file used by the command server with the specified password within the arguments. /// </summary> /// <param name="arguments"> /// <para>The arguments for this command</para> /// <para>Expecting "password", but it is optional. If no password is supplied a random password will be generated</para> /// </param> public static ServiceMessage CommandServerGenerateCertificate(IDictionary<String, String> arguments) { var model = new CertificateModel(); if (arguments != null && arguments.Count > 0) { model.Password = arguments.First().Value; } else { model.RandomizePassword(); } model.Generate(); return new ServiceMessage() { Name = "result", Arguments = new Dictionary<String, String>() { { "Command", "CommandServerCreateCertificate" }, { "Success", model.Exists.ToString() }, { "Message", String.Format("Created certificate with password: {0}", model.Password) }, { "Password", model.Password } } }; }
/// <summary> /// Registers the the specified container. /// </summary> /// <param name="container">The container.</param> /// <param name="assembly">The assembly.</param> /// <param name="typesToIgnore">The types you want this method to ignore (class and/or interface).</param> /// <exception cref="System.ArgumentNullException">assembly</exception> /// <exception cref="DependencyConfigurationException"></exception> /// <exception cref="ArgumentNullException">assembly</exception> public static void Register(Container container, Assembly assembly, params Type[] typesToIgnore) { if (container == null) { throw new ArgumentNullException("container"); } if (assembly == null) { throw new ArgumentNullException("assembly"); } RegisteredInterfacesWithTypes = new Dictionary<Type, Type>(); var registrations = GetTypes(container, assembly, typesToIgnore); IList<string> validationErrors = new List<string>(); foreach (Type type in registrations) { Type[] interfaces = type.GetInterfaces(); Type interfaceToUse = null; if (interfaces.Length > 1) { interfaceToUse = InterfaceToUse(interfaces, type, validationErrors); if (interfaceToUse != null) { Register(container, interfaceToUse, type); } } else { interfaceToUse = interfaces.First(); if (RegisteredInterfacesWithTypes.ContainsKey(interfaceToUse)) { // Does this match the naming convention? if (interfaceToUse.Name.Substring(1).Equals(type.Name)) { bool currentOverrideOption = container.Options.AllowOverridingRegistrations; container.Options.AllowOverridingRegistrations = true; Register(container, interfaceToUse, type); container.Options.AllowOverridingRegistrations = currentOverrideOption; } else { KeyValuePair<Type, Type> registeredInterface = RegisteredInterfacesWithTypes.First(x => x.Key == interfaceToUse); if (!registeredInterface.Key.Name.Substring(1).Equals(registeredInterface.Value.Name)) { // Neither of the interfaces matches naming convention. validationErrors.Add(string.Format(CultureInfo.InvariantCulture, "Multiple Implementations found for [{0}]", interfaceToUse)); } } } else { Register(container, interfaceToUse, type); } } } if (validationErrors.Any()) { throw new DependencyConfigurationException(string.Join(Environment.NewLine, validationErrors), validationErrors); } }
public IDictionary <string, TreeSearchResult> Search(string query) { IDictionary <string, TreeSearchResult> result = GetTreeSearchResultStructure(); if (string.IsNullOrEmpty(query)) { return(result); } IAzureSearchClient client = AzureSearchContext.Instance.GetSearchClient(); // if the search term contains a space this will be transformed to %20 and no search results returned // so lets decode the query term to turn it back into a proper space // will this mess up any other Url encoded terms? or fix them too? query = HttpUtility.UrlDecode(query); ISearchResult searchResults = client.Term(query + "*").Results(); if (result.Keys.Any(x => x.Equals(Constants.Applications.Content, StringComparison.CurrentCultureIgnoreCase))) { List <SearchResultItem> entities = new List <SearchResultItem>(); foreach (ISearchContent searchResult in searchResults.Content.Where(c => c.IsContent).Take(NumberOfItemsPerSection)) { var entity = SearchContentToEntityBasicMapper.Map(searchResult); entities.Add(entity); } result.First(x => x.Key.Equals(Constants.Applications.Content, StringComparison.CurrentCultureIgnoreCase)) .Value.Results = entities; } if (result.Keys.Any(x => x.Equals(Constants.Applications.Media, StringComparison.CurrentCultureIgnoreCase))) { List <SearchResultItem> entities = new List <SearchResultItem>(); foreach (ISearchContent searchResult in searchResults.Content.Where(c => c.IsMedia).Take(NumberOfItemsPerSection)) { var entity = SearchContentToEntityBasicMapper.Map(searchResult); entities.Add(entity); } result.First(x => x.Key.Equals(Constants.Applications.Media, StringComparison.CurrentCultureIgnoreCase)) .Value.Results = entities; } if (result.Keys.Any(x => x.Equals(Constants.Applications.Members, StringComparison.CurrentCultureIgnoreCase))) { List <SearchResultItem> entities = new List <SearchResultItem>(); ApplicationTree tree = Services.ApplicationTreeService.GetByAlias(Constants.Applications.Members); foreach (ISearchContent searchResult in searchResults.Content.Where(c => c.IsMember).Take(NumberOfItemsPerSection)) { var entity = SearchContentToEntityBasicMapper.Map(searchResult); entities.Add(entity); } result.First(x => x.Key.Equals(Constants.Applications.Members, StringComparison.CurrentCultureIgnoreCase)) .Value.Results = entities; } return(result); }
public IEndpointState DetermineState(IDictionary<int, bool> currentState) { return currentState.First().Value ? HandledStates.First(s => s.Name == "In") : HandledStates.First(s => s.Name == "Out"); }
public override ISentence CreateSentence(string subject, IDictionary<string, string[]> facts) { var separator = facts.Count > 1 || (facts.Count == 1 && facts.First().Value.Length > 1) ? Environment.NewLine + Indent : " "; var factsText = string.Join(";" + Environment.NewLine + Indent, facts.Select(this.GetFact)); var text = string.Format("{0}{1}{2}.", subject, separator, factsText); var file = this.CreateNTriplesFile(text, true); var sentence = file.SentencesEnumerable.First(); return sentence; }
private byte GetByte(char c, IDictionary<byte, string> charLookup) { return charLookup.First(kv => kv.Value[0] == c).Key; // lazy }
public static CaveLayoutStatus CheckIfValid(IDictionary <int, Room> Cave, int NumMinConnections = -1, int NumMaxConnections = -1) { // Make sure that all connections lead to valid rooms, // and that all connections are bi-directional bool AllConnectionsValid = Cave.Values.All( e => e.AdjacentRooms.All( r => r == -1 || (Cave.ContainsKey(r) && Cave[r].AdjacentRooms.Contains(e.RoomID)) )); Dictionary <int, int> ValidatedRooms = Cave.ToDictionary(pair => pair.Key, pair => 0); List <int> UnmarkedRooms = ValidatedRooms.Keys.ToList(); Action <Room> MarkConnectedRooms = null; MarkConnectedRooms = (Room Room) => { if (!UnmarkedRooms.Contains(Room.RoomID)) { return; } UnmarkedRooms.Remove(Room.RoomID); foreach (int ID in (from TmpID in Room.AdjacentRooms where TmpID >= 0 select TmpID)) { ValidatedRooms[ID]++; MarkConnectedRooms(Cave[ID]); } }; MarkConnectedRooms(Cave.First().Value); int[] UnreachableRooms = UnmarkedRooms.ToArray(); int[] TooFewConnections = ValidatedRooms .Where(Pair => NumMinConnections != -1 && Pair.Value < NumMinConnections) .Select(Pair => Pair.Key) .ToArray(); int[] TooManyConnections = ValidatedRooms .Where(Pair => NumMaxConnections != -1 && Pair.Value > NumMaxConnections) .Select(Pair => Pair.Key) .ToArray(); CaveLayoutStatus Result = CaveLayoutStatus.None; if (UnreachableRooms.Length > 0) { Result |= CaveLayoutStatus.UnreachableRooms; } if (TooFewConnections.Length > 0) { Result |= CaveLayoutStatus.TooFewConnections; } if (TooManyConnections.Length > 0) { Result |= CaveLayoutStatus.TooManyConnections; } if (!AllConnectionsValid) { Result |= CaveLayoutStatus.MismatchedConnections; } return(Result); }
private static void OnConsoleVariableChanged(IntPtr consoleVariableArg) { var foundValue = s_variablesDelegates.First(item => ICVar.GetIntPtr(item.Value.m_icVar) == consoleVariableArg); foundValue.Value.m_managedConsoleVariableDelegate?.Invoke(foundValue.Value.m_icVar); }
public int GetId(string value) { return(values.First(x => x.Value.Equals(value)).Key); }
public static int Convert(string value) { return(mapping.First(m => m.Value == value).Key); }
public void Evaluate(object model, RenderingContext context, IDictionary <string, string> parameters) { string value; value = parameters.TryGetValue("name", out value) ? value.Trim('"', '\'') : parameters.First().Key.Trim('"', '\''); var template = value; _handler.RenderPartial(template, model, context); }
private Mock <T> TheRegisteredMockForThisType <T>(Type type) where T : class { return((Mock <T>)_registeredMocks.First(x => x.Key == type).Value); }
public Level GetFirstLevelInPack() { return(levels.First().Value); }
public static string GetNetType(Shape shape, IDictionary <string, ApiObject> existingObjects = null, IDictionary <string, ApiObject> newObjects = null, IDictionary <string, ApiEnum> existingEnums = null, IDictionary <string, ApiEnum> newEnums = null) { if (!string.IsNullOrWhiteSpace(shape.LinkTargetName)) { return(NetNamingMapper.GetObjectName(GetTypeFromLinkOrId(shape.LinkTargetName))); } string id = shape.Id; if (shape is ScalarShape scalar) { if (shape.Values != null && shape.Values.Any()) { var key = GetTypeFromLinkOrId(id); if (existingEnums != null && existingEnums.ContainsKey(key)) { return(existingEnums[key].Name); } if (newEnums != null && newEnums.ContainsKey(key)) { return(newEnums[key].Name); } } return(GetNetType(scalar.DataType.Substring(scalar.DataType.LastIndexOf('#') + 1), scalar.Format)); } string type = null; if (shape is ArrayShape arr && !(arr.Items is ScalarShape) && !string.IsNullOrWhiteSpace(arr.Items.Id)) { type = FindTypeById(arr.Items.Id, existingObjects, newObjects, existingEnums, newEnums); } if (type != null) { return(CollectionTypeHelper.GetCollectionType(type)); } if (!(shape is ArrayShape) && !string.IsNullOrWhiteSpace(id)) { type = FindTypeById(id, existingObjects, newObjects, existingEnums, newEnums); } if (type != null) { return(type); } if (id != null && id.Contains("#/declarations")) { var key = GetTypeFromLinkOrId(id); if (existingObjects != null && (existingObjects.ContainsKey(key) || existingObjects.Keys.Any(k => k.ToLowerInvariant() == key.ToLowerInvariant()))) { if (existingObjects.ContainsKey(key)) { return(existingObjects[key].Type); } return(existingObjects.First(kv => kv.Key.ToLowerInvariant() == key.ToLowerInvariant()).Value.Type); } if (newObjects != null && newObjects.ContainsKey(key)) { return(newObjects[key].Type); } } if (shape is ArrayShape array) { return(CollectionTypeHelper.GetCollectionType(GetNetType(array.Items, existingObjects, newObjects, existingEnums, newEnums))); } if (shape is FileShape file) { return(TypeStringConversion["file"]); } if (shape.Inherits.Count() == 1) { if (shape is NodeShape nodeShape) { if (nodeShape.Properties.Count() == 0) { return(GetNetType(nodeShape.Inherits.First(), existingObjects, newObjects, existingEnums, newEnums)); } } if (shape.Inherits.First() is ArrayShape arrayShape) { return(CollectionTypeHelper.GetCollectionType(GetNetType(arrayShape.Items, existingObjects, newObjects, existingEnums, newEnums))); } if (shape is AnyShape any) { var key = NetNamingMapper.GetObjectName(any.Inherits.First().Name); if (existingObjects != null && existingObjects.ContainsKey(key)) { return(key); } if (newObjects != null && newObjects.ContainsKey(key)) { return(key); } } } if (shape.Inherits.Count() > 0) { //TODO: check } if (shape.GetType() == typeof(AnyShape)) { return(GetNetType("any", null)); } if (shape is UnionShape) { return("object"); } return(NetNamingMapper.GetObjectName(shape.Name)); }
public HttpWebResponse PostUserForm(string relativeUrl, IDictionary <string, object> formFields, List <string> excludedInputPrefixes, bool checkUserLoggedIn = true, bool followRedirect = false) { if (checkUserLoggedIn) { this.EnsureLoggedIn(); } var clientHandler = new HttpClientHandler { CookieContainer = this._sessionCookiesContainer, }; var postParameters = new Dictionary <string, object>(); string[] inputFields; using (var client = new HttpClient(clientHandler) { BaseAddress = this.Domain, Timeout = this.Timeout, }) { inputFields = this.GetPageInputFields(client, relativeUrl); } var firstField = formFields.First().Key; if (!inputFields.Any(f => f.Contains(firstField))) { // the form doesn't have the proper input fields Console.WriteLine( @"Either User '{0}' has no rights to post to this page {1} or " + @"this page does not contain correct form ", this.UserName, relativeUrl); // return null; } foreach (var field in inputFields) { XElement xe = null; try { // fixes the error in HTML file input fields; e.g.: // <input type="file" name="postfile" multiple /> // but should work with XHTML file input fields; e.g.: // <input type="file" name="postfile" multiple="multiple" /> var text = field.Contains(" multiple") && !field.Contains(" multiple=") ? field.Replace(" multiple", string.Empty) : field; xe = XElement.Parse(text); } catch (XmlException ex) { Console.WriteLine(@"XmlException: cannot parse input fields: {0}. Ex: {1}", field, ex.Message); } var attrs = xe == null ? new XAttribute[0] : xe.Attributes().ToArray(); var inputType = attrs.FirstOrDefault(a => a.Name == "type"); var inputName = attrs.FirstOrDefault(a => a.Name == "name"); var inputValue = attrs.FirstOrDefault(a => a.Name == "value"); if (inputType != null && inputName != null) { switch (inputType.Value) { case "hidden": { if (!postParameters.ContainsKey(inputName.Value)) { var value = inputValue == null ? string.Empty : inputValue.Value; if (formFields.ContainsKey(inputName.Value)) { value = formFields[inputName.Value].ToString(); } postParameters.Add(inputName.Value, value); } } break; case "text": case "checkbox": case "radio": if (formFields.ContainsKey(inputName.Value) && !postParameters.ContainsKey(inputName.Value)) { postParameters.Add(inputName.Value, formFields[inputName.Value]); } break; // other types as "submit", etc. are ignored/discarded } } } foreach (var field in formFields) { if (!postParameters.ContainsKey(field.Key)) { postParameters.Add(field.Key, field.Value); } } if (excludedInputPrefixes != null) { var keys = postParameters.Keys.ToArray(); var filteredKeys = from prefix in excludedInputPrefixes from key in keys where key.StartsWith(prefix) select key; foreach (var key in filteredKeys) { postParameters.Remove(key); } } if (postParameters.Count > 0) { var url = CombineUrlPath(this.Domain, relativeUrl); return(this.MultipartFormDataPost(url, this.UserAgentValue, postParameters, null, followRedirect)); } return(null); }
public static string GetDefaultFormat() { return(SUPPORTED_FORMATS.First().Key); }
public static T DictFirstValue <T>(IDictionary <int, T> dict) => dict.First().Value;
private IDictionary <string, string> CalcularRiesgoHoja(List <HojasDeRuta> hojas, bool EsContratista, List <dynamic> itemsSubContratistas) { Dictionary <string, string> riesgoGrado = new Dictionary <string, string>(); /// 1. Si ningun item tiene docementacion recepcionada el riesgo es ALTO grado 5 directamente if (!hojas.Any(w => w.HojaFechaControlado != null || w.DocFechaEntrega.HasValue)) { riesgoGrado.Add("ALTO", "5"); //estadoRuta.Riesgo = "ALTO"; //estadoRuta.Grado = "5"; } /// 2. Controlo si hay almenos un item con documentacion recepcionada else if (hojas.Any(w => w.HojaFechaControlado != null || w.DocFechaEntrega.HasValue)) { /// 2.1 Si todos lo items estan aprobados indica que el riesgo es NULO if (hojas.Where(w => w.HojaFechaAprobacion.HasValue).Count() == hojas.Count) { /// SI TIENE SUCONTRATISTAS TENGO QUE VERIFICAR EL ESTADO DE LA MISMA, SI NO ESTA APROBADA ENTONCES DEBO PONER /// EL ESTADO A LA CONTRATISTA DE LA SUBCONTRATISTA. SINO EL RIESGO ES NULO YA QUE TIENE TODOS LOS ITEMS APROBADOS. if (EsContratista && itemsSubContratistas.Count > 0) { Dictionary <string, string> riesgoGradoSub = new Dictionary <string, string>(); foreach (var item in itemsSubContratistas) { List <HojasDeRuta> hojasSub = new List <HojasDeRuta>(); hojasSub.AddRange(item.Hojas); IDictionary <string, string> result = CalcularRiesgoHoja(hojasSub, false, null); if (!riesgoGradoSub.ContainsKey(result.First().Key)) { riesgoGradoSub.Add(result.First().Key, result.First().Value); } } if (riesgoGradoSub.ContainsKey("ALTO")) { riesgoGrado.Add(riesgoGradoSub.Where(w => w.Key == "ALTO").First().Key, riesgoGradoSub.Where(w => w.Key == "ALTO").First().Value); } else if (riesgoGradoSub.ContainsKey("MEDIO")) { riesgoGrado.Add(riesgoGradoSub.Where(w => w.Key == "MEDIO").First().Key, riesgoGradoSub.Where(w => w.Key == "MEDIO").First().Value); } else if (riesgoGradoSub.ContainsKey("BAJO")) { riesgoGrado.Add(riesgoGradoSub.Where(w => w.Key == "BAJO").First().Key, riesgoGradoSub.Where(w => w.Key == "BAJO").First().Value); } else if (riesgoGradoSub.ContainsKey("NULO")) { riesgoGrado.Add(riesgoGradoSub.Where(w => w.Key == "NULO").First().Key, riesgoGradoSub.Where(w => w.Key == "NULO").First().Value); } } else { riesgoGrado.Add("NULO", "0"); } } /// 2.2 Si todos lo item tiene documentacion recepcionada y hay algunos aprobados y otros no /// significa que el riesgo es BAJO else if (hojas.Where(w => w.DocFechaEntrega.HasValue || w.HojaFechaControlado.HasValue).Count() == hojas.Count) { riesgoGrado.Add("BAJO", "1"); } /// 2.3 Si existen algunos items con documentacion recepcionada y otros no, tengo que hacer la evaluación /// según los items sin documentacion. else if (hojas.Where(w => w.DocFechaEntrega.HasValue || w.HojaFechaControlado.HasValue).Count() < hojas.Count) { if (hojas.Any(w => (w.HojaFechaControlado == null && !w.DocFechaEntrega.HasValue) && w.Plantilla.Riesgo == "ALTO")) { riesgoGrado.Add("ALTO", hojas.Where(w => w.HojaFechaControlado == null && !w.DocFechaEntrega.HasValue && w.Plantilla.Riesgo == "ALTO").Max(w => w.Plantilla.Grado).Value.ToString()); } else if (hojas.Any(w => (w.HojaFechaControlado == null && !w.DocFechaEntrega.HasValue) && w.Plantilla.Riesgo == "MEDIO")) { riesgoGrado.Add("MEDIO", hojas.Where(w => w.HojaFechaControlado == null && !w.DocFechaEntrega.HasValue && w.Plantilla.Riesgo == "MEDIO").Max(w => w.Plantilla.Grado).Value.ToString()); } else if (hojas.Any(w => (w.HojaFechaControlado == null && !w.DocFechaEntrega.HasValue) && w.Plantilla.Riesgo == "BAJO")) { riesgoGrado.Add("BAJO", hojas.Where(w => w.HojaFechaControlado == null && !w.DocFechaEntrega.HasValue && w.Plantilla.Riesgo == "BAJO").Max(w => w.Plantilla.Grado).Value.ToString()); } } } return(riesgoGrado); }
/// <summary> /// Restore the secret given the threshhold number, and that number of shares. /// </summary> /// <param name='shares'> /// The shares being used to reconstruct the secret. /// </param> /// <returns> /// The reconstructed secret. /// </returns> public byte[] Restore(IDictionary<int, byte[]> shares) { var length = shares.First().Value.Length; var result = new byte[length]; for(var cur = 0; cur < length; cur++) { result[cur] = ResolveByte(shares.ToDictionary(x => x.Key, x => x.Value[cur])); } return result; }
public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return(Icons.First(f => Equals(f.Value, value)).Key); }
public TermExpression(IDictionary<TermExpression, TermExpression> terms) { if (terms == null || terms.Count == 0) throw new CqlLinqException("Empty dictionaries are not allowed"); var firstElement = terms.First(); _type = typeof(IDictionary<,>).MakeGenericType(firstElement.Key.Type, firstElement.Value.Type); _dictionaryTerms = terms.AsReadOnly(); _termType = CqlExpressionType.Map; }
/// <summary> /// 统计该位置彩票出现的频率 /// </summary> /// <returns></returns> public IDictionary <int, NumberRateDataInfo> StatisticsNumberRate() { var numberRateDic = new SortedDictionary <int, NumberRateDataInfo>(); foreach (var dataItem in _numberHistoryDatas) { if (numberRateDic.ContainsKey(dataItem.Value.LotteryNum)) { numberRateDic[dataItem.Value.LotteryNum].PutHistoryItemData(new KeyValuePair <int, PeriodNumberInfo>(dataItem.Key, NumberHistoryDatas.First(p => p.Key == dataItem.Key).Value)); } else { numberRateDic.Add(dataItem.Value.LotteryNum, new NumberRateDataInfo(new KeyValuePair <int, PeriodNumberInfo>(dataItem.Key, NumberHistoryDatas.First(p => p.Key == dataItem.Key).Value), _lotteryDataPackage.Count)); } } for (int i = _numberInfo.MinValue; i <= _numberInfo.MaxValue; i++) { if (!numberRateDic.ContainsKey(i)) { numberRateDic.Add(i, new NumberRateDataInfo(_lotteryDataPackage.Count)); } } return(numberRateDic.OrderByDescending(p => p.Value.RepeatNum).ThenByDescending(p => p.Key).ToDictionary(p => p.Key, p => p.Value)); }
public static XDocument OrderBy([NotNull] this XDocument document, [NotNull] IDictionary <XName, SortOrderType> sortOrder) { if (document is null) { throw new ArgumentNullException(nameof(document)); } if (sortOrder is null) { throw new ArgumentNullException(nameof(sortOrder)); } if (!sortOrder.Any()) { return(document); } IOrderedEnumerable <XElement> orderedDocument; switch (sortOrder.First().Value) { case SortOrderType.Ascending: orderedDocument = document.Root? .Elements() .OrderBy(x => x.Element(sortOrder.First().Key)?.Value); break; case SortOrderType.Descending: orderedDocument = document.Root? .Elements() .OrderByDescending(x => x.Element(sortOrder.First().Key)?.Value); break; default: throw new NotSupportedException(); } foreach (KeyValuePair <XName, SortOrderType> kvp in sortOrder.Skip(1)) { switch (kvp.Value) { case SortOrderType.Ascending: orderedDocument = orderedDocument?.ThenBy(x => x.Element(kvp.Key)?.Value); continue; case SortOrderType.Descending: orderedDocument = orderedDocument?.ThenByDescending(x => x.Element(kvp.Key)?.Value); continue; default: throw new NotSupportedException(); } } if (orderedDocument == null) { throw new ArgumentException(); } return(orderedDocument.ToXDocument()); }
private void SetFeatureData(SqlCommand cmd, string featureName, string state, IDictionary<string, string> options) { cmd.CommandText = string.Format("UPDATE {0} SET State = @State, PropertyName = @PropertyName, PropertyValues = @PropertyValues WHERE Name = @Name", tableName); var propertyName = options == null ? "" : options.First().Key; var propertyValues = options == null ? "" : options.First().Value; cmd.Parameters.Add(new SqlParameter("@State", state)); cmd.Parameters.Add(new SqlParameter("@PropertyName", propertyName)); cmd.Parameters.Add(new SqlParameter("@PropertyValues", propertyValues)); cmd.Parameters.Add(new SqlParameter("@Name", featureName)); var rows = cmd.ExecuteNonQuery(); if (rows > 0) { return; } cmd.CommandText = string.Format("INSERT INTO {0} (Name, State, PropertyName, PropertyValues) VALUES (@Name, @State, @PropertyName, @PropertyValues)", tableName); cmd.ExecuteNonQuery(); }
/// <summary> /// Apply levels /// </summary> /// <param name="talentsUsed">Selected talents</param> /// <param name="talentLevelDictionary">Talents levels</param> private void ApplyCastleContext(IEnumerable<Talent> talentsUsed, IDictionary<Guid, byte> talentLevelDictionary) { if (talentsUsed == null) throw new ArgumentNullException("talentsUsed"); if (talentLevelDictionary == null) throw new ArgumentNullException("talentLevelDictionary"); var level = new TalentLevelChanger(); var levels = talentLevelDictionary.Values.Distinct(); var allSameLevel = levels.Count() < 2; if (allSameLevel) { level.Change(talentsUsed, levels.First()); return; } talentsUsed .ToList() .ForEach(x => level.Change(x, talentLevelDictionary.First(y => y.Key == x.Id).Value)); }
private Size ComputeMinSize(IDictionary<string, Bitmap> container) { int minWidth = container.First().Value.Width; int minHeight = container.First().Value.Height; ForeachInput(container, (i, k) => { minWidth = i.Width < minWidth ? i.Width : minWidth; minHeight = i.Height < minHeight ? i.Height : minHeight; }); return new Size(minWidth, minHeight); }
private bool ShouldDeleteSequence(MethodBody method, IDictionary<int, OpCode> opCodes) { if (opCodes.Values.All(o => o == OpCodes.Nop)) return false; if (opCodes.Values.All(o => o == OpCodes.Pop)) return false; if (opCodes.Values.All(o => o == OpCodes.Leave)) return false; if (opCodes.Values.Any(o => o == OpCodes.Ret)) return false; // If just setting compiler-generated return variable in Debug mode, don't delete. if (opCodes.Values.Last().Code == Code.Br) { if (((Instruction)method.Instructions[opCodes.Keys.Last()].Operand).Offset == method.Instructions[opCodes.Keys.Last() + 1].Offset) { if (method.Instructions[opCodes.Keys.Last() + 2].OpCode == OpCodes.Ret) { return false; } } } // If calling base constructor, don't delete. if (opCodes.Any(kv => kv.Value == OpCodes.Call)) { if (((MethodReference)method.Instructions[opCodes.First(kv => kv.Value == OpCodes.Call).Key].Operand).Name == Methods.CONSTRUCTOR) { return false; } } // If compiler-generated dispose, don't delete. if (method.Instructions[opCodes.Keys.First()].IsPartOfCompilerGeneratedDispose()) { return false; } // If setting default value to a field, don't delete. if (method.Instructions[opCodes.Keys.First()] .FollowsSequence(OpCodes.Ldarg, OpCodes.Ldc_I4, OpCodes.Stfld) && (int)method.Instructions[opCodes.Keys.First() + 1].Operand == 0) { return false; } return true; }
public IEndpointState DetermineState(IDictionary<int, bool> currentState) { return currentState.First ().Value ? HandledStates.First (s => s is On) : HandledStates.First (s => s is Off); }
public PlayerModel Get(Guid id) { // todo: add exception handling return(_list.First(e => e.Key == id).Value); }
public void SimulateNetwork() { // define test hyperparams const int testNodesCount = 100; const int chordPort = 9876; const int testTimeoutSecs = 5 * 60; _logger.WriteLine($"Simulating a chord network with { testNodesCount } nodes, timeout={ testTimeoutSecs }s"); // define a lookup cache for the nodes to be simulated IDictionary <long, ChordNode> simulatedNodes = null; // define the message transmission function (just pass the message // directly to the target node's ProcessRequest() function) MessageCallback sendMessageFunc = (IChordRequestMessage request, IChordEndpoint receiver) => { return(simulatedNodes[receiver.NodeId].ProcessRequest(request)); }; // create yet unconnected chord nodes simulatedNodes = Enumerable.Range(1, testNodesCount) .Select(x => new ChordNode(sendMessageFunc, $"10.0.0.{ x }", chordPort.ToString())) .ToDictionary(x => x.NodeId); _logger.WriteLine("Successfully created nodes. Starting node join procedures."); // connect the chord nodes to a self-organized cluster by simulating // something like e.g. a Kubernetes rollout of several chord instances var bootstrap = simulatedNodes.First().Value.Local; Func <Task <IChordEndpoint> > bootstrapFunc = () => { return(Task.Run(() => bootstrap)); }; var joinTasks = simulatedNodes.Values.AsParallel() .Select(x => x.JoinNetwork(bootstrapFunc)).ToArray(); // log the system state on a regular schedule until all join tasks completed // abort after several minutes if the tasks did not finish until then -> unit test failed var cancelCallback = new CancellationTokenSource(); var timeoutTask = Task.Delay(testTimeoutSecs * 1000); var monitorTask = Task.Run(() => { int i = 0; while (joinTasks.Any(x => x.Status == TaskStatus.Running)) { // report the states on a 5 second schedule Task.Delay(5000).Wait(); // log the episode's system status _logger.WriteLine("=================================="); _logger.WriteLine($"System state after { ++i } seconds:"); _logger.WriteLine(string.Join("\n", joinTasks.Select(task => $"task { task.Id }: { task.Status }"))); } Task.WaitAll(joinTasks); }, cancelCallback.Token); // abort the simulation on timeout if needed -> unit test failed bool allTasksComplete = Task.WhenAny(timeoutTask, monitorTask) != timeoutTask; Assert.True(allTasksComplete); _logger.WriteLine("Successfully joined all nodes to the chord network."); // TODO: evaluate the network structure by some graph analysis // TODO: test sending some key lookups and health checks // TODO: test the node leave prodecure (in particular the case for the last leaving node) }
public string GetKeyByName(string name) { return(_items.First(kv => kv.Value.Name.Equals(name)).Key); }
private string ReverseInput(string name) { return(inputMap.First(i => i.Value == name).Key); }
private string GetJsonSchemaOrDefault(IDictionary<string, MimeType> body) { if (body.Any(b => b.Key.ToLowerInvariant().Contains("json") && !string.IsNullOrWhiteSpace(b.Value.Schema))) return body.First(b => b.Key.ToLowerInvariant().Contains("json") && !string.IsNullOrWhiteSpace(b.Value.Schema)).Value.Schema; var isDefaultMediaTypeDefined = !string.IsNullOrWhiteSpace(raml.MediaType); var hasSchemaWithDefaultMediaType = raml.MediaType != null && body.Any(b => b.Key.ToLowerInvariant() == raml.MediaType.ToLowerInvariant() && !string.IsNullOrWhiteSpace(b.Value.Schema)); if (isDefaultMediaTypeDefined && hasSchemaWithDefaultMediaType) return body.First(b => b.Key.ToLowerInvariant() == raml.MediaType.ToLowerInvariant() && !string.IsNullOrWhiteSpace(b.Value.Schema)).Value.Schema; if (body.Any(b => !string.IsNullOrWhiteSpace(b.Value.Schema))) return body.First(b => !string.IsNullOrWhiteSpace(b.Value.Schema)).Value.Schema; return null; }
public void CreateScene() { var canvas = Canvas.GetElementById( "game-window" ); var engine = new Engine( canvas, true ); var scene = new Scene( engine ); var light0 = new PointLight( "Omni", new Vector3( 0, 100, 8 ), scene ); var light1 = new HemisphericLight( "HemisphericLight", new Vector3( 0, 100, 8 ), scene ); var advancedTexture = AdvancedDynamicTexture.CreateFullscreenUI("UI"); var UiPanel = new StackPanel("name") { width = "220px", fontSize = "14px", horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_RIGHT, verticalAlignment = Control.VERTICAL_ALIGNMENT_CENTER }; advancedTexture.addControl(UiPanel); var house = SceneLoader.ImportMesh( null, "assets/", "Player.glb", scene, new Interop.Callbacks.ActionCallback <AbstractMesh[], IParticleSystem[], Skeleton[], AnimationGroup[]>((arg1, arg2, arg3, arg4) => { foreach (var animation in arg4) { animation.stop(); _animationMap.Add(animation.name, animation); AddRunAnimationButton( UiPanel, animation.name ); } if (_animationMap.Count > 0) { _runningAnimation = _animationMap.First().Value; _runningAnimation.start(true); } return(Task.CompletedTask); }) ); var camera = new ArcRotateCamera( "ArcRotateCamera", (decimal)(System.Math.PI / 2), (decimal)(System.Math.PI / 4), 3, new Vector3(0, 1, 0), scene ) { lowerRadiusLimit = 2, upperRadiusLimit = 10, wheelDeltaPercentage = 0.01m }; scene.activeCamera = camera; camera.attachControl( canvas, false ); engine.runRenderLoop(() => Task.Run(() => scene.render(true, false))); _engine = engine; }
public static T DictFirstKey <T>(IDictionary <T, int> dict) => dict.First().Key;
public virtual object Create(IDictionary<PropertySpec, object> args) { if (MappedTypeInstance.IsAnonymous()) { var ctor = mappedTypeInstance.GetConstructors().Single(); var ctorArgs = ctor.GetParameters().Select(x => args.First(y => y.Key.Name == x.Name).Value).ToArray(); return ctor.Invoke(ctorArgs); } throw new NotImplementedException(); }
/// <summary> /// Send message of one broker. /// </summary> /// <param name="brokerId"></param> /// <param name="messagesPerTopic"></param> /// <returns></returns> private ProducerSendResult <IEnumerable <Tuple <TopicAndPartition, ProducerResponseStatus> > > Send(int brokerId, IDictionary <TopicAndPartition, BufferedMessageSet> messagesPerTopic) { try { if (brokerId < 0) { throw new NoLeaderForPartitionException( string.Format("No leader for some partition(s). And it try write to on invalid broker {0}. The assigned TopicAndPartition for the data is :{1} ", brokerId, messagesPerTopic.Any() ? messagesPerTopic.First().Key.ToString() : "(null)")); } if (messagesPerTopic.Any()) { var producerRequest = new ProducerRequest(NextCorrelationId, this.producerConfig.ClientId, this.producerConfig.RequiredAcks, this.producerConfig.AckTimeout, messagesPerTopic); ISyncProducer syncProducer = null; try { syncProducer = this.syncProducerPool.GetProducer(brokerId); } catch (UnavailableProducerException e) { Logger.Error(e.Message); // When initializing producer pool, some broker might be unavailable, and now it is healthy and is leader for some partitions. // A new producer should be added to the pool, creating a TCP connection to the broker. var broker = this.brokerPartitionInfo.GetBrokerPartitionLeaders(messagesPerTopic.Keys.First().Topic) .Values.FirstOrDefault(b => b.Id == brokerId); if (broker != null) { this.syncProducerPool.AddProducer(broker); syncProducer = this.syncProducerPool.GetProducer(brokerId); } } if (producerConfig.Verbose) { Logger.DebugFormat("Kafka producer before sent messages for topics {0} to broker {1}", messagesPerTopic, brokerId); } ProducerResponse response = syncProducer.Send(producerRequest); if (this.producerConfig.Verbose) { string msg = string.Format("Kafka producer sent messages for topics {0} to broker {1} on {2}:{3}", messagesPerTopic, brokerId, syncProducer.Config.Host, syncProducer.Config.Port); Logger.Debug(msg); } if (response != null) { int statusCount = response.Statuses.Count; //In java version //https://git-wip-us.apache.org/repos/asf?p=kafka.git;a=blob;f=core/src/main/scala/kafka/producer/async/DefaultEventHandler.scala;h=821901e4f434dfd9eec6eceabfc2e1e65507a57c;hb=HEAD#l260 //The producerRequest.data just the messagesPerTopic. So there compare the statusCount with producerRequest.data.size //But in this C# version, the producerRequest.Data already grouped by topic. So here need compare with messagesPerTopic.Count() int requestCount = messagesPerTopic.Count; if (statusCount != requestCount) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Incomplete response count {0} for producer request count {1}. ", statusCount, requestCount); sb.AppendFormat(" Broker {0} on {1}:{2}", brokerId, syncProducer.Config.Host, syncProducer.Config.Port); sb.Append(" Message detail:"); sb.Append(string.Join(",", messagesPerTopic.Select(r => string.Format("{0},{1}", r.Key.Topic, r.Key.PartitionId)))); sb.Append(" Response status detail which has error:"); sb.Append(string.Join(",", response.Statuses.Where(r => r.Value.Error != (short)ErrorMapping.NoError).Select(r => r.ToString()))); throw new FailedToSendMessageException <TK>(sb.ToString()); } return(new ProducerSendResult <IEnumerable <Tuple <TopicAndPartition, ProducerResponseStatus> > >(response.Statuses.Where(s => s.Value.Error != (short)ErrorMapping.NoError) .Select(s => new Tuple <TopicAndPartition, ProducerResponseStatus>(s.Key, s.Value)))); } } } catch (NoLeaderForPartitionException e) { Logger.Error(ExceptionUtil.GetExceptionDetailInfo(e)); return(new ProducerSendResult <IEnumerable <Tuple <TopicAndPartition, ProducerResponseStatus> > >(messagesPerTopic.Keys.Select( s => new Tuple <TopicAndPartition, ProducerResponseStatus>(s, new ProducerResponseStatus { Error = ErrorMapping.NotLeaderForPartitionCode })), e)); } catch (Exception e) { Logger.Error(ExceptionUtil.GetExceptionDetailInfo(e)); return(new ProducerSendResult <IEnumerable <Tuple <TopicAndPartition, ProducerResponseStatus> > >(messagesPerTopic.Keys.Select( s => new Tuple <TopicAndPartition, ProducerResponseStatus>(s, new ProducerResponseStatus { Error = ErrorMapping.UnknownCode })), e)); } return(new ProducerSendResult <IEnumerable <Tuple <TopicAndPartition, ProducerResponseStatus> > >(Enumerable.Empty <Tuple <TopicAndPartition, ProducerResponseStatus> >())); }
protected override void OnWebSocketEvent(WebSocketStreamEventArgs args, IEnumerable <Action <UserDataEventArgs> > callbacks) { var user = _listenKeys.First(_ => _.Value == args.StreamName).Key; Logger?.LogDebug($"{nameof(UserDataWebSocketClient)}: \"{args.Json}\""); try { var jObject = JObject.Parse(args.Json); var eventType = jObject["e"].Value <string>(); var eventTime = jObject["E"].Value <long>().ToDateTime(); // ReSharper disable once ConvertIfStatementToSwitchStatement if (eventType == "outboundAccountInfo") { var commissions = new AccountCommissions( jObject["m"].Value <int>(), // maker jObject["t"].Value <int>(), // taker jObject["b"].Value <int>(), // buyer jObject["s"].Value <int>()); // seller var status = new AccountStatus( jObject["T"].Value <bool>(), // can trade jObject["W"].Value <bool>(), // can withdraw jObject["D"].Value <bool>()); // can deposit var balances = jObject["B"] .Select(entry => new AccountBalance( entry["a"].Value <string>(), // asset entry["f"].Value <decimal>(), // free amount entry["l"].Value <decimal>())) // locked amount .ToList(); var eventArgs = new AccountUpdateEventArgs(eventTime, args.Token, new AccountInfo(user, commissions, status, jObject["u"].Value <long>().ToDateTime(), balances)); try { if (callbacks != null) { foreach (var callback in callbacks) { callback(eventArgs); } } AccountUpdate?.Invoke(this, eventArgs); } catch (OperationCanceledException) { } catch (Exception e) { if (!args.Token.IsCancellationRequested) { Logger?.LogError(e, $"{nameof(UserDataWebSocketClient)}: Unhandled account update event handler exception."); } } } else if (eventType == "executionReport") { var order = new Order(user); FillOrder(order, jObject); var executionType = ConvertOrderExecutionType(jObject["x"].Value <string>()); var rejectedReason = ConvertOrderRejectedReason(jObject["r"].Value <string>()); var newClientOrderId = jObject["c"].Value <string>(); if (executionType == OrderExecutionType.Trade) // trade update event. { var trade = new AccountTrade( jObject["s"].Value <string>(), // symbol jObject["t"].Value <long>(), // ID jObject["i"].Value <long>(), // order ID jObject["L"].Value <decimal>(), // price (price of last filled trade) jObject["z"].Value <decimal>(), // quantity (accumulated quantity of filled trades) jObject["n"].Value <decimal>(), // commission jObject["N"].Value <string>(), // commission asset jObject["T"].Value <long>() .ToDateTime(), // time order.Side == OrderSide.Buy, // is buyer jObject["m"].Value <bool>(), // is buyer maker jObject["M"].Value <bool>()); // is best price var quantityOfLastFilledTrade = jObject["l"].Value <decimal>(); var eventArgs = new AccountTradeUpdateEventArgs(eventTime, args.Token, order, rejectedReason, newClientOrderId, trade, quantityOfLastFilledTrade); try { if (callbacks != null) { foreach (var callback in callbacks) { callback(eventArgs); } } TradeUpdate?.Invoke(this, eventArgs); } catch (OperationCanceledException) { } catch (Exception e) { if (!args.Token.IsCancellationRequested) { Logger?.LogError(e, $"{nameof(UserDataWebSocketClient)}: Unhandled trade update event handler exception."); } } } else // order update event. { var eventArgs = new OrderUpdateEventArgs(eventTime, args.Token, order, executionType, rejectedReason, newClientOrderId); try { if (callbacks != null) { foreach (var callback in callbacks) { callback(eventArgs); } } OrderUpdate?.Invoke(this, eventArgs); } catch (OperationCanceledException) { } catch (Exception e) { if (!args.Token.IsCancellationRequested) { Logger?.LogError(e, $"{nameof(UserDataWebSocketClient)}: Unhandled order update event handler exception."); } } } } else { Logger?.LogWarning($"{nameof(UserDataWebSocketClient)}.{nameof(OnWebSocketEvent)}: Unexpected event type ({eventType}) - \"{args.Json}\""); } } catch (OperationCanceledException) { } catch (Exception e) { if (!args.Token.IsCancellationRequested) { Logger?.LogError(e, $"{nameof(UserDataWebSocketClient)}.{nameof(OnWebSocketEvent)}"); } } }
// If there are more examples, take the first one // To the future consider creating request for each example static string GetExampleFromExamplesDict(IDictionary <string, OpenApiExample> examples) { return(examples.Count > 0 ? GetSingleExample(examples.First().Value.Value) : null); }
private static IEnumerable<RouteDescription> GetRouteDescriptions(IRequest request, IDictionary<string, IEnumerable<ModuleMeta>> modules) { return modules.First().Value.SelectMany(s => s.RouteDescriptions); }
public global::Opcodes this[uint opcode] => opcodes.First(x => x.Value == opcode).Key;
/// <summary> /// </summary> /// <param name="methodSymbol"> /// </param> /// <param name="map"> /// </param> /// <param name="resolvedTypes"> /// </param> private static void SelectGenericsFromArgumentsForOneLevel(MethodSymbol methodSymbol, IDictionary<IType, IType> map, List<TypeSymbol> resolvedTypes) { ////if (namedTypeSymbol.IsNestedType()) ////{ //// SelectGenericsFromArgumentsForOneLevel(namedTypeSymbol.ContainingType, map, resolvedTypes); ////} foreach (var typeSymbol in methodSymbol.TypeArguments) { if (typeSymbol.Kind == SymbolKind.TypeParameter) { var foundType = map.First(pair => pair.Key.Name == typeSymbol.Name); resolvedTypes.Add((foundType.Value as MetadataTypeAdapter).TypeDef); continue; } var subTypeNamedTypeSymbol = typeSymbol as NamedTypeSymbol; if (subTypeNamedTypeSymbol != null && subTypeNamedTypeSymbol.Arity > 0) { resolvedTypes.Add(ConstructGenericTypeSymbol(subTypeNamedTypeSymbol, map)); continue; } resolvedTypes.Add(subTypeNamedTypeSymbol); } }
private string GetResourceType(IDictionary <string, IDictionary <string, string> > type) { return(type != null && type.Any() ? type.First().Key : string.Empty); }
private void translations_SelectedIndexChanged(object sender, EventArgs e) { AskForSave(); _changesMade = false; _translation = Translator.GetTranslation(translations.Text); LoadTranslation(); UpdateCategoriesList(); FillTranslateGrid(translateCategories.SelectedItem as TranslationCategory); if (_translation == null) { _NO_TRANSLATE_languageCode.Text = ""; return; } try { var culture = new CultureInfo(_translation.First().Value.LanguageCode); _NO_TRANSLATE_languageCode.Text = string.Concat(culture.TwoLetterISOLanguageName, " (", culture.DisplayName, ")"); } catch { _NO_TRANSLATE_languageCode.Text = _translation.First().Value.LanguageCode; } }
protected void cboPeriodos_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e) { /// Busca: las hojas de ruta donde el /// periodo coincida con el periodod de consulta List <EstadosRutaTemp> DetallesEstadosTemp = new List <EstadosRutaTemp>(); int mes = int.Parse(cboPeriodos.SelectedItem.Value.Split('/')[0]); int año = int.Parse(cboPeriodos.SelectedItem.Value.Split('/')[1]); var a = (from C in Contexto.CabeceraHojasDeRuta where (C.Periodo.Month == mes && C.Periodo.Year == año) //&& C.ContratoEmpresas.Contrato.Codigo == "4600002679" orderby C.ContratoEmpresas.EsContratista.Value descending select new { CodigoContrato = C.ContratoEmpresas.Contrato.Codigo, Estado = C.Estado.Descripcion, FechaFin = C.ContratoEmpresas.Contrato.FechaVencimiento, FechaInicio = C.ContratoEmpresas.Contrato.FechaInicio, FechaProrroga = C.ContratoEmpresas.Contrato.Prorroga, NombreEmpresa = C.ContratoEmpresas.Empresa.RazonSocial.Trim(), EsContratista = C.ContratoEmpresas.EsContratista.Value, Contratadopor = C.ContratoEmpresas.Contrato.objContratadopor.Descripcion, Servicio = C.ContratoEmpresas.Contrato.Servicio, Categoria = C.ContratoEmpresas.Contrato.objCategoria, Gestor = C.ContratoEmpresas.Contrato.GestorNombre, GestorEmail = C.ContratoEmpresas.Contrato.GestorEmail, Fiscal = C.ContratoEmpresas.Contrato.FiscalNombre, FiscalEmail = C.ContratoEmpresas.Contrato.FiscalEmail, Area = C.ContratoEmpresas.Contrato.objArea.Descripcion, Hojas = C.HojasDeRuta, C.AprobacionEpecial }).ToList().Distinct(); foreach (var item in a) { EstadosRutaTemp estadoRuta = new EstadosRutaTemp(); estadoRuta.CodigoContrato = item.CodigoContrato; estadoRuta.Estado = item.Estado; estadoRuta.FechaFin = GetFormatoFecha(item.FechaFin); estadoRuta.FechaInicio = GetFormatoFecha(item.FechaInicio); estadoRuta.FechaProrroga = GetFormatoFecha(item.FechaProrroga); estadoRuta.NombreEmpresaContratista = GetNombreContratista(item.EsContratista, item.CodigoContrato, item.NombreEmpresa); estadoRuta.NombreEmpresaSubContratista = GetNombreSubContratista(item.EsContratista, item.CodigoContrato, item.NombreEmpresa); estadoRuta.Contratadopor = item.Contratadopor; estadoRuta.Servicio = item.Servicio; estadoRuta.Periodo = string.Format("{0:00}/{1:0000}", mes, año); estadoRuta.Gestor = item.Gestor; estadoRuta.GestorEmail = item.GestorEmail; estadoRuta.Fiscal = item.Fiscal; estadoRuta.FiscalEmail = item.FiscalEmail; estadoRuta.Area = item.Area; estadoRuta.AprobacionEspecial = item.AprobacionEpecial.HasValue ? item.AprobacionEpecial.Value : false; if (item.Estado != "Aprobada") { ///// 1. Si no tiene item con documentacion recepcionada ///// 2. Si no tiene ningun item aprobado ///// 3. Si no tiene ningun item con auditoria terminada ///// ENTONCES se asume que no posee documentacion presentada. //if (!item.Hojas.Any(w => w.DocFechaEntrega.HasValue) // && // !item.Hojas.Any(w => w.HojaAprobado.HasValue && !w.HojaAprobado.HasValue) // && // !item.Hojas.Any(w => w.AuditoriaTerminada.HasValue && w.AuditoriaTerminada.HasValue) // ) //{ // estadoRuta.PresentoDocumentacion = "NO"; //} //else //{ // estadoRuta.PresentoDocumentacion = "SI"; //} int SinDoc = (from H in item.Hojas where H.DocComentario != null && H.DocComentario.Trim() != "" select H).Count(); if (SinDoc == 0) { /// Si no tiene comentarios de pendientes y no tiene todos los items aprobados, /// entonces no se ha aprobado porque alguna de las sub contratistas /// no esta aprobada y por lo tanto no puede aprobarce esta hoja. int ItemsAprobados = item.Hojas.Where(w => w.HojaFechaAprobacion.HasValue).Count(); if (ItemsAprobados == 0) { estadoRuta.PresentoDocumentacion = "No Presentó Documentación"; } else { estadoRuta.PresentoDocumentacion = "Por pendientes de Subcontratista"; } } int CantComentarios = (from H in item.Hojas where H.HojaComentario != null && H.HojaComentario.Trim() != "" select H).Count(); if (CantComentarios > 0) { estadoRuta.PresentoDocumentacion = "Con Pendientes"; } List <HojasDeRuta> hojas = item.Hojas.ToList(); List <dynamic> itemsSubContratista = (from i in a where i.CodigoContrato == item.CodigoContrato && i.EsContratista == false select i).ToList <dynamic>(); ///// Calculo del riesgo que poses la hoja de ruta IDictionary <string, string> RiesgoGrado = CalcularRiesgoHoja(hojas, item.EsContratista, itemsSubContratista); estadoRuta.Riesgo = RiesgoGrado.First().Key; estadoRuta.Grado = RiesgoGrado.First().Value; } else { if (!estadoRuta.AprobacionEspecial) { estadoRuta.PresentoDocumentacion = "Con Documentación"; estadoRuta.Riesgo = "NULO"; estadoRuta.Grado = "0"; } else { estadoRuta.PresentoDocumentacion = "Sin Documentación"; estadoRuta.Riesgo = "NULO"; estadoRuta.Grado = "0"; estadoRuta.Estado = "Aprobada (Sin Actividad)"; } } if (item.Categoria != null) { estadoRuta.Categoria = item.Categoria.Descripcion; } DetallesEstadosTemp.Add(estadoRuta); } DetallesEstados = DetallesEstadosTemp; gvEstadoContratos.Rebind(); }
public void ApplyReductionToCurrentSimplex(IDictionary<int, double> measures, Func<IVertex, double> getObjectiveFunction) { var minVal = measures.Min(f => f.Value); var bestValueAsKey = measures.First(e => e.Value == minVal).Key; foreach (var vertex in CurrentSimplex.Vertices.Where(e => e.Key != bestValueAsKey)) { for (int i = 0; i < CurrentSimplex.Vertices.Count - 1; i++) { var bestValParam = CurrentSimplex.Vertices[bestValueAsKey].Parameters[i]; vertex.Value.Parameters[i] = bestValParam + SigmaReduction * (vertex.Value.Parameters[i] - bestValParam); } measures[vertex.Key] = getObjectiveFunction(vertex.Value); } }
protected virtual void ApplyDiscountToOrderLines(PromotionResult promotionResult, OrderLine orderLine, CustomerOrder customerOrder) { CustomerOrderPromotion appliedPromotion = customerOrder.CustomerOrderPromotions.FirstOrDefault <CustomerOrderPromotion>((Func <CustomerOrderPromotion, bool>)(p => p.PromotionId == promotionResult.PromotionId)); List <OrderLine> list = new List <OrderLine>(); list.Add(orderLine); if (SiteContext.Current != null && SiteContext.Current.ShipTo != null) { if (string.IsNullOrEmpty(orderLine.CostCode)) { //orderLine.PromotionResult = promotionResult; ProductPromotionHelper_Brasseler helper = new ProductPromotionHelper_Brasseler(this.pricingPipeline, this.promotionAmountProvider); IDictionary <Guid, ProductPriceDto> pricingServiceResult = helper.GetPricingServiceResult((IEnumerable <OrderLine>)list); ProductPriceDto productPriceDto = pricingServiceResult.First(o => o.Key == orderLine.Id).Value; Decimal UnitNetPrice = orderLine.UnitNetPrice; // Check current flow of Customer. HelperUtility helperUtility = new HelperUtility(); var currentCustomer = helperUtility.GetCurrentCustomerFlow(customerOrder); if (currentCustomer.CustomProperties.Where(x => x.Name.EqualsIgnoreCase("SubscriptionDiscount")).Count() > 0) { var amount = currentCustomer.CustomProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase("SubscriptionDiscount")).Value; if (string.IsNullOrEmpty(amount)) { return; } Decimal?subscriptionDiscount = Decimal.Parse(amount, CultureInfo.InvariantCulture); //return if subscription discount is zero if (subscriptionDiscount < 1) { return; } Decimal percent = subscriptionDiscount.Value / new Decimal(100); //BUSA-463 Subscription: Hold previous ActualPrice to calculate discount for this promotion orderLine.CostCode = orderLine.UnitNetPrice.ToString(CultureInfo.InvariantCulture); var num1 = NumberHelper.ApplyDiscount(UnitNetPrice, percent); //if (orderLine.PromotionResult != null) //{ // if (!(orderLine.UnitNetPrice < num1)) // { // CustomerOrderPromotion deleted = customerOrder.CustomerOrderPromotions.FirstOrDefault<CustomerOrderPromotion>((Func<CustomerOrderPromotion, bool>)(p => // { // Guid? orderLineId = p.OrderLineId; // Guid id = orderLine.Id; // if (!orderLineId.HasValue) // return false; // if (!orderLineId.HasValue) // return true; // return orderLineId.GetValueOrDefault() == id; // })); // if (deleted != null) // { // customerOrder.CustomerOrderPromotions.Remove(deleted); // this.UnitOfWork.GetRepository<CustomerOrderPromotion>().Delete(deleted); // } // } // else // return; //} //orderLine.PromotionResult = promotionResult; orderLine.UnitListPrice = productPriceDto.UnitListPrice; orderLine.UnitRegularPrice = productPriceDto.UnitRegularPrice; orderLine.UnitNetPrice = num1; orderLine.UnitNetPrice = orderLine.UnitNetPrice < Decimal.Zero ? Decimal.Zero : orderLine.UnitNetPrice; orderLine.TotalRegularPrice = NumberHelper.RoundCurrency(orderLine.UnitListPrice * orderLine.QtyOrdered); orderLine.TotalNetPrice = NumberHelper.RoundCurrency(orderLine.UnitNetPrice * orderLine.QtyOrdered); this.AddOrUpdateCustomerOrderPromotion(customerOrder, appliedPromotion, orderLine, promotionResult); } } } }