Esempio n. 1
0
        protected static MsBuildTaskFixtureResult <T> ExecuteMsBuildTaskInAzurePipeline <T>(T task, string buildNumber = null, string configurationText = null) where T : GitVersionTaskBase
        {
            var fixture = CreateRemoteRepositoryFixture();

            task.SolutionDirectory = fixture.LocalRepositoryFixture.RepositoryPath;
            var msbuildFixture       = new MsBuildTaskFixture(fixture);
            var environmentVariables = new List <KeyValuePair <string, string> >(env.ToArray());

            if (buildNumber != null)
            {
                environmentVariables.Add(new KeyValuePair <string, string>("BUILD_BUILDNUMBER", buildNumber));
            }
            msbuildFixture.WithEnv(environmentVariables.ToArray());
            if (configurationText != null)
            {
                CreateConfiguration(task.SolutionDirectory, configurationText);
            }

            var result = msbuildFixture.Execute(task);

            if (result.Success == false)
            {
                Console.WriteLine(result.Log);
            }
            return(result);
        }
Esempio n. 2
0
 public static void UpdateWalletValue(string currency)
 {
     // update the wallet BTC value based on most recent ticker values
     // doesn't make any API calls, just recalculates based on local data
     try {
         if (walletState == null)
         {
             UpdateWallet();
         }
         else if (currency == "BTC")
         {
             return;
         }
         else
         {
             IBalance balance;
             if (walletState.TryGetValue(currency, out balance))
             {
                 CurrencyPair           cp         = new CurrencyPair("BTC", currency);
                 TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(cp);
                 if (lastTicker != null)
                 {
                     double currValue  = lastTicker.MarketData.PriceLast;
                     double currAmount = balance.QuoteOnOrders + balance.QuoteAvailable;
                     balance.BitcoinValue = currAmount * currValue;
                     GUI.GUIManager.UpdateWallet(walletState.ToArray());
                 }
             }
         }
     }
     catch (Exception e) {
         Console.WriteLine(e.Message + "\n" + e.StackTrace);
     }
 }
Esempio n. 3
0
        private void Socket_MessageReceived(string message)
        {
            if (DumpToDebug)
            {
                Debug.WriteLine(message);
            }

            if (IsPlaying)
            {
                return;
            }

            var ev = JsonApiEvent.Parse(message);

            if (!ev.Equals(default(JsonApiEvent)))
            {
                bool subscribed = Subscribers.ToArray().Any(o => o.Key.IsMatch(ev.URI));

                var args = new MessageReceivedEventArgs(ev, message, subscribed);
                MessageReceived?.Invoke(this, args);

                if (args.Handled)
                {
                    return;
                }

                HandleEvent(ev);
            }
        }
Esempio n. 4
0
        protected static MsBuildTaskFixtureResult <T> ExecuteMsBuildTaskInBuildServer <T>(T task) where T : GitVersionTaskBase
        {
            var fixture = CreateRemoteRepositoryFixture();

            task.SolutionDirectory = fixture.LocalRepositoryFixture.RepositoryPath;

            var msbuildFixture = new MsBuildTaskFixture(fixture);

            msbuildFixture.WithEnv(env.ToArray());
            return(msbuildFixture.Execute(task));
        }
Esempio n. 5
0
        public void AddRange(IDictionary <TKey, TValue> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException("items");
            }

            if (items.Count != 0)
            {
                if (forwardSortedDictionary.Count != 0)
                {
                    if (items.Keys.Any(x => forwardSortedDictionary.ContainsKey(x)))
                    {
                        throw new ArgumentException("An item with the same key has already been added.");
                    }

                    foreach (var item in items)
                    {
                        forwardSortedDictionary.Add(item.Key, item.Value);
                        reverseDictionary.Add(item.Value, item.Key);
                    }
                }
                else
                {
                    forwardSortedDictionary = new SortedDictionary <TKey, TValue>(items);
                    reverseDictionary       = new Dictionary <TValue, TKey>(items.ToDictionary(
                                                                                kvp => kvp.Value, kvp => kvp.Key));
                }

                OnCollectionChanged(NotifyCollectionChangedAction.Add, items.ToArray());
            }
        }
        public async Task <ActionResult> SetCustomProperties(string slug, IDictionary <string, string> settings)
        {
            if (settings != null && settings.Count > 0)
            {
                // validate custom property name/values
                int i = 0;
                foreach (var setting in settings)
                {
                    if (string.IsNullOrWhiteSpace(setting.Key))
                    {
                        ModelState.AddModelError(String.Format("Settings[{0}].Key", i), "property name cannot be empty");
                    }

                    if (string.IsNullOrWhiteSpace(setting.Value))
                    {
                        ModelState.AddModelError(String.Format("Settings[{0}].Value", i), "property value cannot be empty");
                    }
                    i++;
                }

                if (ModelState.IsValid)
                {
                    await _service.SetKuduSettings(slug, settings.ToArray());

                    return(RedirectToAction("Index", new { slug }));
                }
            }

            var model = await GetSettingsViewModel(slug);

            model.KuduSettings.SiteSettings = settings;

            return((ActionResult)View("index", model));
        }
Esempio n. 7
0
        private void ThreadStart()
        {
            while (true)
            {
                Thread.Sleep(1);
                var utcNow = DateTime.UtcNow;

                lock (m_contextsMap)
                    foreach (var keyValuePair in m_contextsMap.ToArray())
                    {
                        var context = keyValuePair.Value;
                        var runtime = context.Runtime;

                        if (runtime.IsDisposedOrDisposing || (runtime.IsAgentMode && !runtime.IsRealTime))
                        {
                            m_contextsMap.Remove(keyValuePair.Key);
                        }
                        else if (!context.IsBusy && utcNow - context.CheckTime >= context.Interval)
                        {
                            if (!runtime.IsAgentMode && !runtime.IsRealTime)
                            {
                                m_contextsMap.Remove(keyValuePair.Key);
                            }
                            else
                            {
                                context.CheckTime = utcNow;
                                context.IsBusy    = true;
                                Task.Factory.StartNewEx(() => Execute(context));
                            }
                        }
                    }
            }
        }
 /// <summary>
 ///   Generates a new <see cref="IDictionary{TKey,TValue}"/> where all keys are
 ///   renamed according to a specified key map.
 /// </summary>
 /// <param name="self">
 ///   The source dictionary.
 /// </param>
 /// <param name="keyMap">
 ///   A dictionary containing the key mapping (keys=source keys, values=target keys).
 /// </param>
 /// <param name="isRestricted">
 ///   (optional; default=<c>false</c>)<br/>
 ///   Specifies whether to only include attributes whose keys can be found in the <paramref name="keyMap"/>.
 /// </param>
 /// <typeparam name="TValue">
 ///   The dictionary's value <see cref="Type"/>.
 /// </typeparam>
 /// <returns>
 ///   A remapped dictionary.
 /// </returns>
 /// <seealso cref="MapSafe{TValue}(System.Collections.Generic.IDictionary{string,TValue},KeyMapInfo,bool)"/>
 public static IDictionary <string, TValue> Map <TValue>(
     this IDictionary <string, TValue> self,
     IDictionary <string, string> keyMap,
     bool isRestricted = false)
 {
     return(new Dictionary <string, TValue>(self.ToArray().Map(keyMap, isRestricted)));
 }
Esempio n. 9
0
        private static void ClearUpTasks(IDictionary <IActor, TaskState> taskDict)
        {
            // удаляем выполненные задачи.
            foreach (var taskStatePair in taskDict.ToArray())
            {
                var state = taskStatePair.Value;

                if (state.TaskComplete)
                {
                    taskDict.Remove(taskStatePair.Key);
                    state.TaskSource.ProcessTaskComplete(state.Task);
                    return;
                }

                var actor = taskStatePair.Key;
                if (!actor.CanExecuteTasks)
                {
                    // Песонаж может перестать выполнять задачи по следующим причинам:
                    // 1. Персонажи, у которых есть модуль выживания, могут умереть.
                    // Мертвые персонажы не выполняют задач.
                    // Их задачи можно прервать, потому что:
                    //   * Возможна ситуация, когда мертвый персонаж все еще выполнить действие.
                    //   * Экономит ресурсы.
                    taskDict.Remove(taskStatePair.Key);
                }
            }
        }
Esempio n. 10
0
 private void UrlEncodeQueryParams(IDictionary <string, string> queryParams)
 {
     foreach (var pair in queryParams.ToArray())
     {
         queryParams[pair.Key] = Uri.EscapeDataString(pair.Value);
     }
 }
Esempio n. 11
0
        public static void UpdateWallet()
        {
            // makes an API call to retrieve from server
            try {
                if (wallet == null)
                {
                    wallet = PoloniexBot.ClientManager.client.Wallet;
                }
                IDictionary <string, IBalance> tempWallet = wallet.GetBalancesAsync().Result;
                if (tempWallet != null)
                {
                    walletState = tempWallet;

                    IBalance balance;
                    if (walletState.TryGetValue("USDT", out balance))
                    {
                        balance.BitcoinValue = (balance.QuoteAvailable + balance.QuoteOnOrders) / Strategies.BaseTrendMonitor.LastUSDTBTCPrice;
                    }

                    GUI.GUIManager.UpdateWallet(tempWallet.ToArray());
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.Message + "\n" + e.StackTrace);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Downloads the specified URL into a JSON output.
        /// </summary>
        /// <returns>The JSON data</returns>
        /// <param name="url">The URL to POST to</param>
        /// <param name="token">The authentication token to use</param>
        /// <param name="param">POST parameters</param>
        static public async Task <JsonValue> HttpPostToJsonAsync(string url, string token, IDictionary <string, string> param)
        {
            Log.Info(LogTag, "Performing HttpPostToJsonAsync, URL {0}", url);

            using (HttpContent content = new FormUrlEncodedContent(param.ToArray()))
                using (HttpClient client = new HttpClient(new NativeMessageHandler()))
                {
                    var request = new HttpRequestMessage()
                    {
                        RequestUri = new System.Uri(url),
                        Method     = HttpMethod.Post,
                        Content    = content
                    };
                    if (token != null)
                    {
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
                    }

                    using (HttpResponseMessage response = await client.SendAsync(request))
                        using (HttpContent responseContent = response.Content)
                        {
                            // Use this stream to build a JSON document object.
                            JsonValue jsonDoc = JsonObject.Load(await responseContent.ReadAsStreamAsync());
                            Log.Info(LogTag, "Response: {0}", jsonDoc.ToString());

                            return(jsonDoc);
                        }
                }
        }
Esempio n. 13
0
        public static void Compile(
            IDictionary <FieldReference, RegisteredResolver> resolvers)
        {
            if (resolvers == null)
            {
                throw new ArgumentNullException(nameof(resolvers));
            }

            foreach (var item in resolvers.ToArray())
            {
                RegisteredResolver registered = item.Value;
                if (registered.Field is FieldMember member)
                {
                    ResolverDescriptor descriptor =
                        registered.IsSourceResolver
                            ? new ResolverDescriptor(
                            registered.SourceType,
                            member)
                            : new ResolverDescriptor(
                            registered.ResolverType,
                            registered.SourceType,
                            member);
                    resolvers[item.Key] = registered.WithField(
                        ExpressionCompiler.Resolve.Compile(descriptor));
                }
            }
        }
        protected static void NormalizePositions(IDictionary <TVertex, Point> vertexPositions)
        {
            if (vertexPositions == null || vertexPositions.Count == 0)
            {
                return;
            }

            //get the topLeft position
            var topLeft = new Point(float.PositiveInfinity, float.PositiveInfinity);

            foreach (var pos in vertexPositions.Values.ToArray())
            {
                topLeft.X = Math.Min(topLeft.X, pos.X);
                topLeft.Y = Math.Min(topLeft.Y, pos.Y);
            }

            //translate with the topLeft position
            foreach (var v in vertexPositions.ToArray())
            {
                var pos = v.Value;
                pos.X -= topLeft.X;
                pos.Y -= topLeft.Y;
                vertexPositions[v.Key] = pos;
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Unions the key-value-pairs of two dictionaries into one.
        /// </summary>
        public static IDictionary <TKey, TCol> Union <TKey, TCol>(this IDictionary <TKey, TCol> first, IDictionary <TKey, TCol> second)
        {
            if (first == null)
            {
                throw new ArgumentNullException("first");
            }
            if (second == null)
            {
                throw new ArgumentNullException("second");
            }

            if (first.Count == 0 && second.Count == 0)
            {
                return(new Dictionary <TKey, TCol>(0));
            }

            if (first.Count == 0)
            {
                return(second.ToDictionary()); // actually a clone
            }
            if (second.Count == 0)
            {
                return(first.ToDictionary()); // actually a clone
            }
            return(first.ToArray().Union(second).ToDictionary());
        }
        public void Open(string url, string protocol, IDictionary <string, string> headers)
        {
            Close();

            if (url.StartsWith("https"))
            {
                url = url.Replace("https://", "wss://");
            }
            else if (url.StartsWith("http"))
            {
                url = url.Replace("http://", "ws://");
            }
#if net20 || net35
            var customHeaderItems = new List <KeyValuePair <string, string> >();
            if (headers != null)
            {
                customHeaderItems.AddRange(headers.ToArray());
            }
            websocket = new WebSocket(url, protocol, null, customHeaderItems, "Websockets.Standard", WebSocketVersion.Rfc6455);
#else
            websocket = new WebSocket(url, protocol, null, headers?.ToList());
#endif
            websocket.Opened          += Websocket_Opened;
            websocket.Error           += Websocket_Error;
            websocket.Closed          += Websocket_Closed;
            websocket.MessageReceived += Websocket_MessageReceived;
            websocket.Open();
        }
Esempio n. 17
0
 protected void SendPacket(Packet packet)
 {
     using (MemoryStream stream = new MemoryStream())
     {
         OutputBuffer outgoing = new OutputBuffer(stream);
         outgoing.WriteVarInt(GetOutgoingID(packet));
         packet.Write(outgoing);
         if (compression_treshold > 0)
         {
             var content = stream.ToArray();
             outgoing = new OutputBuffer();
             if (content.Length >= compression_treshold)
             {
                 byte[] compressed_packet = ZlibUtils.Compress(content, (MemoryStream)outgoing.GetStream());
                 outgoing.WriteVarInt(compressed_packet.Length);
                 outgoing.WriteData(compressed_packet);
             }
             else
             {
                 outgoing.WriteVarInt(0);
                 outgoing.WriteData(content);
             }
         }
         writer.WriteVarInt((int)outgoing.GetStream().Length);
         writer.WriteData(outgoing.ToArray());
         outgoing.Dispose();
     }
 }
Esempio n. 18
0
        public void AddNotesForCompanies(IDictionary <string, List <string> > notesToAdd)
        {
            using (FileStream file = new FileStream(notesFilePath, FileMode.Open, FileAccess.Read))
            {
                var workbook = WorkbookFactory.Create(file);

                var sheet = workbook.GetSheetAt(0);

                var startingRow    = sheet.GetRow(sheet.LastRowNum) == null ? sheet.LastRowNum : sheet.LastRowNum + 1;
                var companiesArray = notesToAdd.ToArray();

                Enumerable.Range(0, notesToAdd.Count())
                .ToList()
                .ForEach(i =>
                {
                    var currentRow = sheet.CreateRow(startingRow + i);
                    currentRow.CreateCell(StartingColumnIndex).SetCellValue(companiesArray.ElementAt(i).Key);
                    SetCompanyRow(currentRow, companiesArray.ElementAt(i).Value.ToArray());
                });

                FileStream outputStream = new FileStream(notesFilePath, FileMode.Create);
                workbook.Write(outputStream);
                outputStream.Close();
            }
        }
Esempio n. 19
0
        public IList <string> GetReport(string path)
        {
            int    count = 0;
            string text  = this.ReadFromFile(path);
            IDictionary <string, int> symbols = this.GetSymbols(text, out count);
            IList <string>            result  = new List <string>();
            FileStream file = File.Open(path, FileMode.Open);

            result.Add(string.Empty);
            result.Add(file.Name);

            foreach (KeyValuePair <string, int> pair in symbols.OrderByDescending(s => s.Value))
            {
                result.Add(string.Format("{0}\t{1}\t{2}",
                                         pair.Key,
                                         pair.Value.ToString(),
                                         (pair.Value * 1.0 / count).ToString("0.#########")));
            }

            double h = 0;

            for (int i = 0; i < symbols.Count; i++)
            {
                double p = symbols.ToArray()[i].Value * 1.0 / count;

                h = p + Math.Log(1 / p, 2);
            }

            long fileLen = file.Length;

            result.Add(string.Format("H = {0}", h));
            result.Add(string.Format("File = {0}", fileLen));

            return(result);
        }
        private static void ConvertJsonTypes(IDictionary <string, object> dict)
        {
            foreach (var pair in dict.ToArray())
            {
                var jObject = pair.Value as JObject;
                if (jObject != null)
                {
                    var newDict = jObject.ToObject <Dictionary <string, object> >();

                    dict[pair.Key] = newDict;

                    ConvertJsonTypes(newDict);
                }

                var jArray = pair.Value as JArray;
                if (jArray != null)
                {
                    var newList = jArray.ToObject <List <object> >();

                    dict[pair.Key] = newList;

                    ConvertJsonTypes(newList);
                }
            }
        }
        public static FixedTypeKeyHashTableRegistry Build(IReadOnlyList <IRegistration> registrations)
        {
            // ThreadStatic
            if (buildBuffer == null)
            {
                buildBuffer = new Dictionary <Type, IRegistration>(128);
            }
            buildBuffer.Clear();

            foreach (var registration in registrations)
            {
                if (registration.InterfaceTypes?.Count > 0)
                {
                    foreach (var interfaceType in registration.InterfaceTypes)
                    {
                        AddToBuildBuffer(buildBuffer, interfaceType, registration);
                    }
                }
                else
                {
                    AddToBuildBuffer(buildBuffer, registration.ImplementationType, registration);
                }
            }

            var hashTable = new FixedTypeKeyHashtable <IRegistration>(buildBuffer.ToArray());

            return(new FixedTypeKeyHashTableRegistry(hashTable));
        }
        public void AddRange(IDictionary <TKey, TValue> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException("items");
            }

            if (items.Count > 0)
            {
                if (Dictionary.Count > 0)
                {
                    if (items.Keys.Any((k) => Dictionary.ContainsKey(k)))
                    {
                        throw new ArgumentException("An item with the same key has already been added.");
                    }
                    else
                    {
                        foreach (var item in items)
                        {
                            Dictionary.Add(item);
                        }
                    }
                }
                else
                {
                    _dictionary = new Dictionary <TKey, TValue>(items);
                }

                OnCollectionChanged(NotifyCollectionChangedAction.Add, items.ToArray());
            }
        }
        private bool UpdateChangedEntries([NotNull] IDictionary <CultureKey, ResourceLanguage> targets, [NotNull] IDictionary <CultureKey, ResourceLanguage> sources)
        {
            var hasChanges = false;

            foreach (var targetItem in targets.ToArray())
            {
                var cultureKey = targetItem.Key;
                var target     = targetItem.Value;

                var source = sources[cultureKey];

                if (target.IsContentEqual(source))
                {
                    continue;
                }

                if (IsWinFormsDesignerResource)
                {
                    foreach (var resourceKey in source.ResourceKeys)
                    {
                        source.SetComment(resourceKey, target.GetComment(resourceKey));
                    }
                }

                targets[cultureKey] = source;
                hasChanges          = true;
            }

            return(hasChanges);
        }
        public async Task BroadcastAsync(IMessage message)
        {
            using MemoryStream stream = new MemoryStream();

            message.WriteTo(stream);
            stream.Seek(0, SeekOrigin.Begin);

            ReadOnlyMemory <byte> readOnlyMemory = new ReadOnlyMemory <byte>();
            await stream.WriteAsync(readOnlyMemory);

            bool res = stream.TryGetBuffer(out ArraySegment <byte> array);

            foreach (var kvp in _webSockets.ToArray())
            {
                var webSocket = kvp.Key;
                if (webSocket.CloseStatus.HasValue)
                {
                    await webSocket.CloseAsync(SNWS.WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);

                    _webSockets.Remove(webSocket);
                    kvp.Value.SetResult(new object());
                    continue;
                }

                await webSocket.SendAsync(array, SNWS.WebSocketMessageType.Binary, true, CancellationToken.None);
            }
        }
Esempio n. 25
0
        public IEnumerable <PairSimilarityInfo> CreateMatchCollection(IDictionary <string, MatOfFloat> hasheDict)
        {
            EnablePublishingProgress();
            var similarities = new ConcurrentBag <PairSimilarityInfo>();
            //var tasks = new List<Task>();
            var hashes = hasheDict.ToArray();

            SetProgressIterationsScope(hashes.Length * hashes.Length);
            for (int j = 0; j < hashes.Length; j++)
            {
                var j1 = j + 1;

                Parallel.For(j1, hashes.Length, new ParallelOptions {
                    MaxDegreeOfParallelism = 8
                }, i1 =>
                {
                    //Thread.Sleep(1);
                    if (hashes[j1].Key == hashes[i1].Key)
                    {
                        return;
                    }
                    Thread.CurrentThread.Priority = ThreadPriority.Lowest;

                    double similarity = CalcSimilarity((hashes[j1], hashes[i1]));
                    //Trace.WriteLine($" {j1} {r1}");
                    similarities.Add(new PairSimilarityInfo(hashes[j1], hashes[i1], similarity));

                    UpdateIterationsCount();
                });
        public void Configure_GetsEnumOptionsFromConfiguration(
            IDictionary <string, string> configValues,
            IDictionary <string, object> expectedValues)
        {
            // Setup
            var builder = new ConfigurationBuilder().AddInMemoryCollection(configValues);
            var config  = builder.Build();

            Container.Configure <EnumOptions>(config);

            // Act
            var options = Container.Resolve <IOptions <EnumOptions> >().Value;

            // Validate
            var optionsProps = options.GetType().GetProperties().ToDictionary(p => p.Name);
            var assertions   = expectedValues
                               .Select(_ => new Action <KeyValuePair <string, object> >(kvp => Assert.AreEqual(kvp.Value, optionsProps[kvp.Key].GetValue(options))))
                               .ToArray();

            var pairs = expectedValues.ToArray();

            for (var i = 0; i < assertions.Length; i++)
            {
                var pair      = pairs[i];
                var assertion = assertions[i];
                assertion(pair);
            }
        }
Esempio n. 27
0
        private void Unsubscribe(IJsonSubscriber observer)
        {
            if (observer == null)
            {
                UnsubscribeAll();
                return;
            }

            lock (Sync)
            {
                var streamsChanged = false;

                foreach (var streamAndSubscribers in Subscribers.ToArray())
                {
                    if (streamAndSubscribers.Value.Contains(observer))
                    {
                        Logger?.LogDebug($"{GetType().Name}.{nameof(Unsubscribe)}: Removing observer of stream ({streamAndSubscribers.Key})  [thread: {Thread.CurrentThread.ManagedThreadId}]");
                        streamAndSubscribers.Value.Remove(observer);
                    }

                    // Unsubscribe stream if there are no callbacks.
                    // ReSharper disable once InvertIf
                    if (!streamAndSubscribers.Value.Any())
                    {
                        RemoveStream(streamAndSubscribers.Key);
                        streamsChanged = true;
                    }
                }

                if (streamsChanged)
                {
                    OnPublishedStreamsChanged();
                }
            }
        }
Esempio n. 28
0
 /// <summary>
 /// consumes resources in the stockpile, and updates the dictionary.
 /// </summary>
 /// <param name="stockpile"></param>
 /// <param name="toUse"></param>
 private static void ConsumeResources(CargoStorageDB fromCargo, IDictionary <Guid, int> toUse)
 {
     foreach (KeyValuePair <Guid, int> kvp in toUse.ToArray())
     {
         ICargoable cargoItem          = fromCargo.OwningEntity.Manager.Game.StaticData.GetICargoable(kvp.Key);
         Guid       cargoTypeID        = cargoItem.CargoTypeID;
         int        amountUsedThisTick = 0;
         if (fromCargo.StoredCargoTypes.ContainsKey(cargoTypeID))
         {
             if (fromCargo.StoredCargoTypes[cargoTypeID].ItemsAndAmounts.ContainsKey(cargoItem.ID))
             {
                 if (fromCargo.StoredCargoTypes[cargoTypeID].ItemsAndAmounts[cargoItem.ID] >= kvp.Value)
                 {
                     amountUsedThisTick = kvp.Value;
                 }
                 else
                 {
                     amountUsedThisTick = (int)fromCargo.StoredCargoTypes[cargoTypeID].ItemsAndAmounts[cargoItem.ID];
                 }
             }
         }
         StorageSpaceProcessor.RemoveCargo(fromCargo, cargoItem, amountUsedThisTick);
         toUse[kvp.Key] -= amountUsedThisTick;
     }
 }
Esempio n. 29
0
        /// <summary>
        /// Determines what would be unlocked by granting additional technology to an empire.
        /// </summary>
        /// <param name="emp">The empire.</param>
        /// <param name="levels">The technology levels to grant.</param>
        /// <returns>Newly unlocked items.</returns>
        public static IEnumerable <IUnlockable> GetUnlockedItems(Empire emp, IDictionary <Technology, int> levels)
        {
            // find out what the empire already knows
            var oldItems = emp.UnlockedItems.ToArray();

            // save off the old levels so we can restore them
            var oldLevels = new Dictionary <Technology, int>(emp.ResearchedTechnologies);

            // set the new levels
            foreach (var kvp in levels.ToArray())
            {
                emp.ResearchedTechnologies.Add(kvp);
            }

            // find out what the empire would know
            emp.RefreshUnlockedItems();
            var newItems = emp.UnlockedItems.ToArray();

            // reset known levels
            emp.ResearchedTechnologies.Clear();
            foreach (var kvp in oldLevels)
            {
                emp.ResearchedTechnologies.Add(kvp);
            }
            emp.RefreshUnlockedItems();

            // return newly learned items
            return(newItems.Except(oldItems));
        }
        public static FixedTypeKeyHashTableRegistry Build(IReadOnlyList <IRegistration> registrations)
        {
            // ThreadStatic
            if (buildBuffer == null)
            {
                buildBuffer = new Dictionary <Type, IRegistration>(128);
            }
            buildBuffer.Clear();

            foreach (var registration in registrations)
            {
                if (registration.InterfaceTypes is IReadOnlyList <Type> interfaceTypes)
                {
                    // ReSharper disable once ForCanBeConvertedToForeach
                    for (var i = 0; i < interfaceTypes.Count; i++)
                    {
                        AddToBuildBuffer(buildBuffer, interfaceTypes[i], registration);
                    }

                    // Mark the ImplementationType with a guard because we need to check if it exists later.
                    if (!buildBuffer.ContainsKey(registration.ImplementationType))
                    {
                        buildBuffer.Add(registration.ImplementationType, null);
                    }
                }
                else
                {
                    AddToBuildBuffer(buildBuffer, registration.ImplementationType, registration);
                }
            }

            var hashTable = new FixedTypeKeyHashtable <IRegistration>(buildBuffer.ToArray());

            return(new FixedTypeKeyHashTableRegistry(hashTable));
        }
Esempio n. 31
0
 public ActionResult DemoAction(IDictionary<string, Contact> contacts)
 {
     var contactArray = contacts.ToArray();
     Dictionary<string, object> parameters = new Dictionary<string, object>();
     foreach (var item in contacts)
     {
         string address = string.Format("{0}省{1}市{2}{3}",item.Value.Address.Province, item.Value.Address.City,item.Value.Address.District, item.Value.Address.Street);
         parameters.Add(string.Format("contacts[\"{0}\"].Name", item.Key),item.Value.Name);
         parameters.Add(string.Format("contacts[\"{0}\"].PhoneNo", item.Key),item.Value.PhoneNo);
         parameters.Add(string.Format("contacts[\"{0}\"].EmailAddress",item.Key), item.Value.EmailAddress);
         parameters.Add(string.Format("contacts[\"{0}\"].Address", item.Key),address);
     }
     return View("DemoAction", parameters);
 }
        private static void FinalizeEntries(Node node, IDictionary<string, IList<Entry>> waiting, System.IO.FileInfo fileInfo)
        {
            int lastCount = 0;
            int count = 0;
            do
            {
                lastCount = count;
                count = 0;
                foreach (var waitingInfo in waiting.ToArray())
                {
                    Node dir = GetDirectory(waitingInfo.Key, node);
                    if ((dir == null))
                    {
                        dir = GetDirectory(waitingInfo.Key.Substring(0, Math.Max(0, waitingInfo.Key.LastIndexOf('/'))), node);
                        if (dir != null)
                        {
                            Entry dirEntry = Entry.CreateZipDirectoryEntry(waitingInfo.Key.Substring(waitingInfo.Key.LastIndexOf('/') + 1), fileInfo.LastWriteTime);
                            dirEntry.Node = new Node();
                            dir.Nodes.Add(dirEntry);
                            dir = dirEntry.Node;
                        }
                    }
                    if (dir != null)
                    {
                        foreach (var dirEntry in waitingInfo.Value)
                        {
                            dir.Nodes.Add(dirEntry);
                        }
                        waiting.Remove(waitingInfo.Key);
                    }

                    else
                    {
                        count += waitingInfo.Value.Count;
                    }
                }
            }
            while ((count > 0) && (lastCount != count));
        }
Esempio n. 33
0
 public static TestBlobCache OverrideGlobals(IDictionary<string, byte[]> initialContents, IScheduler scheduler = null)
 {
     return OverrideGlobals(scheduler, initialContents.ToArray());
 }
Esempio n. 34
0
        public virtual void SetOptions( IDictionary<string, object> options, IToken optionsStartToken )
        {
            if ( options == null )
            {
                this.Options = null;
                return;
            }

            foreach ( var option in options.ToArray() )
            {
                string optionName = option.Key;
                object optionValue = option.Value;
                string stored = SetOption( optionName, optionValue, optionsStartToken );
                if ( stored == null )
                    options.Remove( optionName );
            }
        }
Esempio n. 35
0
		private void UnSubscribe(IDictionary<Security, List<IChartElement>> elements, IChartElement element)
		{
			lock (_syncRoot)
			{
				foreach (var pair in elements.ToArray())
				{
					if (!pair.Value.Remove(element))
						continue;

					if (pair.Value.Count == 0)
						elements.Remove(pair.Key);
				}
			}
		}
Esempio n. 36
0
 /// <summary>
 /// Invoke this function, using named arguments provided as key-value pairs
 /// </summary>
 /// <param name="args">the representation of named arguments, as a dictionary</param>
 /// <returns>The result of the evaluation</returns>
 public override SymbolicExpression Invoke(IDictionary<string, SymbolicExpression> args)
 {
     var a = args.ToArray();
     return InvokeViaPairlist(Array.ConvertAll(a, x => x.Key), Array.ConvertAll(a, x => x.Value));
 }
Esempio n. 37
0
 private void RemoveZeroes(IDictionary<string, object> dictionary) {
     foreach (var p in dictionary.ToArray()) {
         var val = p.Value;
         if (!val.ToBool()) {
             dictionary.Remove(p.Key);
             continue;
         }
         if (val is Array) {
             if (((Array) val).Length == 0) {
                 dictionary.Remove(p.Key);
             }
             continue;
         }
         if (val is IDictionary<string, object>) {
             RemoveZeroes((IDictionary<string,object>)val);
         }
     }
 }
Esempio n. 38
0
        public Task<ActionResult> SetCustomProperties(string slug, IDictionary<string, string> settings)
        {
            if (settings != null && settings.Count > 0)
            {
                // validate custom property name/values
                int i = 0;
                foreach (var setting in settings)
                {
                    if (string.IsNullOrWhiteSpace(setting.Key))
                    {
                        ModelState.AddModelError(String.Format("Settings[{0}].Key", i), "property name cannot be empty");
                    }

                    if (string.IsNullOrWhiteSpace(setting.Value))
                    {
                        ModelState.AddModelError(String.Format("Settings[{0}].Value", i), "property value cannot be empty");
                    }
                    i++;
                }

                if (ModelState.IsValid)
                {
                    var tcs = new TaskCompletionSource<ActionResult>();
                    _service.SetKuduSettings(slug, settings.ToArray())
                                   .ContinueWith(task =>
                                   {
                                       if (task.IsFaulted)
                                       {
                                           tcs.SetException(task.Exception.InnerExceptions);
                                       }
                                       else
                                       {
                                           tcs.SetResult(RedirectToAction("Index", new { slug }));
                                       }
                                   });

                    return tcs.Task;
                }
            }

            return GetSettingsViewModel(slug).Then(model =>
            {
                model.KuduSettings.SiteSettings = settings;

                return (ActionResult)View("index", model);
            });
        }
Esempio n. 39
0
        public async Task<ActionResult> SetCustomProperties(string slug, IDictionary<string, string> settings)
        {
            if (settings != null && settings.Count > 0)
            {
                // validate custom property name/values
                int i = 0;
                foreach (var setting in settings)
                {
                    if (string.IsNullOrWhiteSpace(setting.Key))
                    {
                        ModelState.AddModelError(String.Format("Settings[{0}].Key", i), "property name cannot be empty");
                    }

                    if (string.IsNullOrWhiteSpace(setting.Value))
                    {
                        ModelState.AddModelError(String.Format("Settings[{0}].Value", i), "property value cannot be empty");
                    }
                    i++;
                }

                if (ModelState.IsValid)
                {
                    await _service.SetKuduSettings(slug, settings.ToArray());
                    return RedirectToAction("Index", new { slug });
                }
            }

            var model = await GetSettingsViewModel(slug);

            model.KuduSettings.SiteSettings = settings;

            return (ActionResult)View("index", model);
        }
Esempio n. 40
0
        private void RunQuery(string query, IDictionary<string,object> parameters = null)
        {
            edtResults.Text = query + "\r\n\r\nRunning...";
            tabControl.Enabled = false;

            Task.Run(async () =>
            {
                var bucket = ClusterHelper.GetBucket("beer-sample");

                var queryRequest = new QueryRequest(query);

                if (parameters != null)
                {
                    queryRequest.AddNamedParameter(parameters.ToArray());
                };

                var result = await
                    bucket.QueryAsync<dynamic>(queryRequest);
                if (!result.Success)
                {
                    if (result.Errors != null && result.Errors.Count > 0)
                    {
                        return result.Errors.First().Message;
                    }
                    else if (result.Exception != null)
                    {
                        return string.Format("{0}\r\n\r\n{1}\r\n{2}", query, result.Exception.Message,
                            result.Exception.StackTrace);
                    }
                    else
                    {
                        return "Unknown Error";
                    }
                }
                else if (result.Rows != null)
                {
                    var sb = new StringBuilder();
                    sb.AppendFormat("{0}\r\n\r\n{1} rows returned\r\n\r\n", query, result.Rows.Count);

                    foreach (var row in result.Rows)
                    {
                        sb.AppendLine(row.ToString());
                    }

                    return sb.ToString();
                }
                else
                {
                    return query + "\r\n\r\n0 row returned";
                }
            })
                .ContinueWith(task =>
                {
                    BeginInvoke(new Action(() =>
                    {
                        if (task.IsFaulted)
                        {
                            edtResults.Text = string.Format("{0}\r\n\r\n{1}\r\n{2}", query, task.Exception.Message,
                                task.Exception.StackTrace);
                        }
                        else
                        {
                            edtResults.Text = task.Result;
                        }

                        tabControl.Enabled = true;
                    }));
                });
        }
Esempio n. 41
0
        /// <summary>
        /// Sets object properties from the dictionary matching keys to property names or aliases.
        /// </summary>
        /// <param name="entityToPopulate">Object to populate from dictionary.</param>
        /// <param name="settings">Dictionary of settings.Settings that are populated get removed from the dictionary.</param>
        /// <returns>Dictionary of settings that were not matched.</returns>
        public static void PopulateSettings(object entityToPopulate, IDictionary<string, object> settings)
        {
            if (entityToPopulate == null)
            {
                throw new ArgumentNullException("entityToPopulate");
            }

            if (settings != null && settings.Count > 0)
            {
                // Setting property value from dictionary
                foreach (var setting in settings.ToArray())
                {
                    PropertyInfo property = entityToPopulate.GetType().GetProperties()
                        .FirstOrDefault(p => setting.Key.Equals(p.Name, StringComparison.OrdinalIgnoreCase) ||
                                             p.GetCustomAttributes<SettingsAliasAttribute>()
                                                .Any(a => setting.Key.Equals(a.Alias, StringComparison.OrdinalIgnoreCase)));

                    if (property != null)
                    {
                        try
                        {
                            if (property.PropertyType == typeof(bool) && (setting.Value == null || setting.Value.ToString().IsNullOrEmpty()))
                            {
                                property.SetValue(entityToPopulate, true);
                            }
                            else if (property.PropertyType.IsEnum)
                            {
                                property.SetValue(entityToPopulate, Enum.Parse(property.PropertyType, setting.Value.ToString(), true));
                            }
                            else if (property.PropertyType.IsArray && setting.Value.GetType() == typeof(JArray))
                            {
                                var elementType = property.PropertyType.GetElementType();
                                if (elementType == typeof(string))
                                {
                                    var stringArray = ((JArray) setting.Value).Children().
                                    Select(
                                        c => c.ToString())
                                    .ToArray();
  
                                    property.SetValue(entityToPopulate, stringArray);
                                }
                                else if (elementType == typeof (int))
                                {
                                    var intValues = ((JArray)setting.Value).Children().
                                         Select(c => (int)Convert.ChangeType(c, elementType, CultureInfo.InvariantCulture))
                                         .ToArray();
                                    property.SetValue(entityToPopulate, intValues);
                                }
                            }
                            else
                            {
                                property.SetValue(entityToPopulate,
                                    Convert.ChangeType(setting.Value, property.PropertyType, CultureInfo.InvariantCulture), null);
                            }

                            settings.Remove(setting.Key);
                        }
                        catch (Exception exception)
                        {
                            throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Resources.ParameterValueIsNotValid,
                                setting.Key, property.GetType().Name), exception);
                        }
                    }
                }
            }
        }