C# (CSharp) System.Collections. Dictionary Code Examples

C# (CSharp) System.Collections.Dictionary - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для System.Collections.Dictionary, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Пример #1
0
 public Gateway(string gatewayServer,bool server)
 {
     Console.WriteLine("did " + gatewayServer);
     channels = new Dictionary<string, GatewayMessage>();
     if (server) {
         var jv = new JsDictionary<string, bool>();
         jv["force new connection"] = true;
         GatewaySocket = Global.Require<SocketIOClient>("socket.io-client").AConnect(gatewayServer, jv);
     } else {        
         GatewaySocket = SocketIOClient.Connect(gatewayServer);
     }
     GatewaySocket.On<SocketClientMessageModel>("Client.Message", data => channels[data.Channel](data.User, data.Content));
     GatewaySocket.On<string>("disconnect", data => Console.WriteLine("Disconnected "+ DateTime.Now));
 }
Пример #2
0
 public InputMapper(Dictionary<string, InputContext> contexts, int playerIndex)
 {
     _contexts = contexts;
     _activeContexts = new Stack<InputContext>();
     _callbacks = new List<Action<MappedInput>>();
     _currentFrameMappedInput = new MappedInput(playerIndex);
 }
        /// <summary>
        /// Gets an array of supported method names for Flickr.
        /// </summary>
        /// <remarks>
        /// Note: Not all methods might be supported by the FlickrNet Library.</remarks>
        /// <param name="callback">Callback method to call upon return of the response from Flickr.</param>
        public void ReflectionGetMethodsAsync(Action<FlickrResult<MethodCollection>> callback)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("method", "flickr.reflection.getMethods");

            GetResponseAsync<MethodCollection>(parameters, callback);
        }
 public ModuleControl(Guid moduleID, String fileName)
 {
     Dictionary<string, object> parameters = new Dictionary<string,object>();
     parameters.Add("moduleID", moduleID);
     parameters.Add("fileName", fileName);
     this.DataManager.Load(parameters);
 }
Пример #5
0
        public BaseGame(int id, int roomId, Map map, eRoomType roomType, eGameType gameType, int timeType)
            : base(id, roomType, gameType, timeType)
        {
            m_roomId = roomId;
            m_players = new Dictionary<int, Player>();
            m_turnQueue = new List<TurnedLiving>();
            m_livings = new List<Living>();

            m_random = new Random();

            m_map = map;
            m_actions = new ArrayList();
            PhysicalId = 0;
            BossWarField = "";

            m_tempBox = new List<Box>();
            m_tempPoints = new List<Point>();

            if (roomType == eRoomType.Dungeon)
            {
                Cards = new int[21];
            }
            else
            {
                Cards = new int[8];
            }

            m_gameState = eGameState.Inited;
        }
Пример #6
0
 private static void FillEventArgs(Hashtable mapArgs, Dictionary<string, string> additionalInfo)
 {
     if (additionalInfo == null)
     {
         for (int i = 0; i < 3; i++)
         {
             string str = (i + 1).ToString("d1", CultureInfo.CurrentCulture);
             mapArgs["AdditionalInfo_Name" + str] = "";
             mapArgs["AdditionalInfo_Value" + str] = "";
         }
     }
     else
     {
         string[] array = new string[additionalInfo.Count];
         string[] strArray2 = new string[additionalInfo.Count];
         additionalInfo.Keys.CopyTo(array, 0);
         additionalInfo.Values.CopyTo(strArray2, 0);
         for (int j = 0; j < 3; j++)
         {
             string str2 = (j + 1).ToString("d1", CultureInfo.CurrentCulture);
             if (j < array.Length)
             {
                 mapArgs["AdditionalInfo_Name" + str2] = array[j];
                 mapArgs["AdditionalInfo_Value" + str2] = strArray2[j];
             }
             else
             {
                 mapArgs["AdditionalInfo_Name" + str2] = "";
                 mapArgs["AdditionalInfo_Value" + str2] = "";
             }
         }
     }
 }
Пример #7
0
		public GoogleSkuInfo( Dictionary<string,object> dict )
		{
			if( dict.ContainsKey( "title" ) )
				title = dict["title"] as string;
	
			if( dict.ContainsKey( "price" ) )
				price = dict["price"] as string;
	
			if( dict.ContainsKey( "type" ) )
				type = dict["type"] as string;
	
			if( dict.ContainsKey( "description" ) )
				description = dict["description"] as string;
	
			if( dict.ContainsKey( "productId" ) )
				productId = dict["productId"] as string;
	
			if( dict.ContainsKey( "price_currency_code" ) )
				priceCurrencyCode = dict["price_currency_code"] as string;
	
			if( dict.ContainsKey( "price_amount_micros" ) )
			{
				var temp = dict["price_amount_micros"] as long?;
				if( temp != null )
					priceAmountMicros = temp.Value;
			}
		}
Пример #8
0
        /// <summary>
        /// Null test.
        /// </summary>
        /// <param name="callback">Callback method to call upon return of the response from Flickr.</param>
        public void TestNullAsync(Action<FlickrResult<NoResponse>> callback)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("method", "flickr.test.null");

            GetResponseAsync<NoResponse>(parameters, callback);
        }
Пример #9
0
        public void CreateOnEmptyDictionaryReturnsEmptyMap()
        {
            Dictionary<int, string> d = new Dictionary<int, string>();
            IPersistentMap m = PersistentHashMap.create(d);

            Expect(m.count(), EqualTo(0));
        }
Пример #10
0
 private SqlFormatter(QueryLanguage language, bool forDebug)
 {
     this.language = language;
     this.sb = new StringBuilder();
     this.aliases = new Dictionary<TableAlias, string>();
     this.forDebug = forDebug;
 }
Пример #11
0
        public override System.Collections.Generic.Dictionary<System.DateTime, double>[] Calculate(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.DateTime, double>> values)
        {
            int basePeriod = base.Period;
            Dictionary<System.DateTime, double> macdValues = new Dictionary<System.DateTime, double>();
            //Dim signalLineValues As New Dictionary(Of Date, Double)

            base.Period = this.PeriodFast;
            Dictionary<DateTime, double> ema12values = base.Calculate(values)[0];

            base.Period = this.PeriodSlow;
            Dictionary<DateTime, double> ema26values = base.Calculate(values)[0];

            List<KeyValuePair<System.DateTime, double>> closeValues = new List<KeyValuePair<System.DateTime, double>>(values);

            System.DateTime d = default(System.DateTime);
            for (int i = 0; i <= closeValues.Count - 1; i++) {
                d = closeValues[i].Key;
                macdValues.Add(d, ema12values[d] - ema26values[d]);
            }

            base.Period = basePeriod;
            Dictionary<DateTime, double> ema9values = base.Calculate(macdValues)[0];

            return new Dictionary<System.DateTime, double>[] {
                macdValues,
                ema9values
            };
        }
Пример #12
0
        public void RestoreListViewSelected()
        {
            try
            {
                if (listBox != null && oldItem != null && oldItems != null)
                {
                    if (this.allSelected == true)
                    {
                        listBox.SelectAll();
                        return;
                    }

                    //このUnselectAll()は無いと正しく復元出来ない状況があり得る
                    listBox.UnselectAll();

                    //上限越えの場合は、選択を解除して終了。
                    if (oldItems.Count >= this.MaxRestoreNum) return;

                    //選択数が少ないときは逆に遅くなる気もするが、Dictionaryにしておく
                    var listKeys = new Dictionary<ulong, object>();

                    if (getKey == null)
                    {
                        getKey = CtrlCmdDefEx.GetKeyFunc(oldItem.GetType());
                    }

                    foreach (object listItem1 in listBox.Items)
                    {
                        //重複するキーは基本的に無いという前提
                        try
                        {
                            listKeys.Add(getKey(listItem1), listItem1);
                        }
                        catch { }
                    }

                    object setItem;
                    if (listKeys.TryGetValue(getKey(oldItem), out setItem))
                    {
                        listBox.SelectedItem = setItem;
                    }

                    foreach (object oldItem1 in oldItems)
                    {
                        if (listKeys.TryGetValue(getKey(oldItem1), out setItem))
                        {
                            //数が多いとき、このAddが致命的に遅い
                            listBox.SelectedItems.Add(setItem);
                        }
                    }

                    //画面更新が入るので最後に実行する。SelectedItem==nullのときScrollIntoViewは何もしない。
                    listBox.ScrollIntoView(listBox.SelectedItem);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
Пример #13
0
 public MockTable(TableName name)
 {
     this.name = name;
     columns = new ColumnCollection(this);
     rows = new Dictionary<RowId, TableRow>();
     rowIndex = new List<RowId>();
 }
        public static Dictionary<string, IEnumerable> SampleTestData(int maxRows,
                                                                     int minValue=1,
                                                                     int maxValue=100,
                                                                     int denominator=100,
                                                                     string dataSetName = "Data")
        {
            List<ExcelTestData> values = new List<ExcelTestData>();
            Dictionary<string, IEnumerable> results = new Dictionary<string, IEnumerable>();

            Random random = new Random();
            RandomDateTime randomdt = new RandomDateTime(1990, 1, 1);

            for (int i = 0; i < maxRows; i++)
            {
                int r = random.Next(minValue, maxValue);
                decimal result =Convert.ToDecimal( (double)r / denominator);
                values.Add(new ExcelTestData() {
                    decimalvalue = result,
                    datetimevalue = randomdt.Next()
                });
            }

            results.Add(dataSetName, values);
            return results;
        }
Пример #15
0
        public override void Execute()
        {
            AmazonEC2Client client = new AmazonEC2Client(AWSAuthConnection.OUR_ACCESS_KEY_ID, AWSAuthConnection.OUR_SECRET_ACCESS_KEY);
            DescribeSnapshotsRequest request = new DescribeSnapshotsRequest();
            DescribeSnapshotsResponse response = client.DescribeSnapshots(request);

            Dictionary<string, List<Amazon.EC2.Model.Snapshot>> snapshots = new Dictionary<string, List<Amazon.EC2.Model.Snapshot>>();
            foreach (Amazon.EC2.Model.Snapshot r in response.DescribeSnapshotsResult.Snapshot)
            {
                if (!snapshots.ContainsKey(r.VolumeId))
                    snapshots[r.VolumeId] = new List<Amazon.EC2.Model.Snapshot>();

                snapshots[r.VolumeId].Add(r);
            }

            foreach (string volumeId in snapshots.Keys)
            {
                Console.WriteLine("--- Volume: {0}", volumeId);
                snapshots[volumeId].Sort(delegate(Amazon.EC2.Model.Snapshot x,Amazon.EC2.Model.Snapshot y)
                    { return DateTime.Parse(x.StartTime).CompareTo(DateTime.Parse(y.StartTime)); });

                foreach (Amazon.EC2.Model.Snapshot s in snapshots[volumeId])
                {
                    DateTime startTime = DateTime.Parse(s.StartTime);
                    Console.Write("{0}\t{1}\t{2}\t{3}", s.SnapshotId, startTime, s.Progress, s.Status);
                    Console.WriteLine();
                }

                Console.WriteLine();
            }
        }
Пример #16
0
        /// <summary>
        /// Can be used to call unsupported methods in the Flickr API.
        /// </summary>
        /// <remarks>
        /// Use of this method is not supported. 
        /// The way the FlickrNet API Library works may mean that some methods do not return an expected result 
        /// when using this method.
        /// </remarks>
        /// <param name="method">The method name, e.g. "flickr.test.null".</param>
        /// <param name="parameters">A list of parameters. Note, api_key is added by default and is not included. Can be null.</param>
        /// <param name="callback">Callback method to call upon return of the response from Flickr.</param>
        public void TestGenericAsync(string method, Dictionary<string, string> parameters, Action<FlickrResult<UnknownResponse>> callback)
        {
            if (parameters == null) parameters = new Dictionary<string, string>();

            parameters.Add("method", method);
            GetResponseAsync<UnknownResponse>(parameters, callback);
        }
Пример #17
0
        /// <summary>
        /// Test the logged in state of the current Filckr object.
        /// </summary>
        /// <param name="callback">Callback method to call upon return of the response from Flickr.</param>
        public void TestLoginAsync(Action<FlickrResult<FoundUser>> callback)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("method", "flickr.test.login");

            GetResponseAsync<FoundUser>(parameters, callback);
        }
Пример #18
0
    public static void HeavyChurn(Simulator sim, int time)
    {
      sim.Complete();
      Dictionary<Node, Node> volatile_nodes = new Dictionary<Node, Node>();
      int fifteen_mins = (int) ((new TimeSpan(0, 15, 0)).Ticks / TimeSpan.TicksPerMillisecond);

      int max = sim.StartingNetworkSize * 2;
      Random rand = new Random();
      DateTime end = DateTime.UtcNow.AddSeconds(time);
      while(end > DateTime.UtcNow) {
        SimpleTimer.RunSteps(fifteen_mins);
        List<Node> to_remove = new List<Node>();
        foreach(Node node in volatile_nodes.Keys) {
          double prob = rand.NextDouble();
          if(prob <= .7) {
            continue;
          }

// This is due to some bug that I can no longer remember
//          sim.RemoveNode(node, prob > .9);
          sim.RemoveNode(node, true);
          to_remove.Add(node);
        }

        foreach(Node node in to_remove) {
          volatile_nodes.Remove(node);
        }

        Console.WriteLine("Removed: {0} Nodes" , to_remove.Count);
        while(volatile_nodes.Count < max) {
          Node node = sim.AddNode();
          volatile_nodes.Add(node, node);
        }
      }
    }
Пример #19
0
        public static void initElements()
        {
            masterElement = new Dictionary<string, Element>();

            masterElement.Add(
                "fire", new Element( "Fire", 0, "Burny!" )
            );
            masterElement.Add(
                "ice", new Element( "Ice", 0, "Freezy!" )
            );
            masterElement.Add(
                "electric", new Element( "Electric", 0, "Zappy!" )
            );
            masterElement.Add(
                "holy", new Element( "Holy", 0, "Blessy!" )
            );
            masterElement.Add(
                "dark", new Element( "Dark", 0, "Damney!" )
            );
            masterElement.Add(
                "drain", new Element( "Drain", 0, "Draino!" )
            );
            masterElement.Add(
                "reduction", new Element( "Reduction", 0, "Halvey!" )
            );
            masterElement.Add(
                "antimech", new Element( "AntiMech", 0, "Roboty!" )
            );
        }
Пример #20
0
 public Proxy(DokanOptions options, DokanOperations operations)
 {
     operations_ = operations;
     options_ = options;
     array_ = new ArrayList();
     infoTable_ = new Dictionary<ulong, DokanFileInfo>();
 }
Пример #21
0
        public ActionResult Assign(string loginId)
        {
            User user = _memberShipFactory.CreateUserDao().GetByLoginId(loginId);
            if (user == null)
            {
                throw new HttpException(404, "Cant' find the user with loginid is " + loginId);
            }
            var userGroupRoleMap = new Dictionary<string, List<string>>();
            var rolePermissionsMap = new Dictionary<string, List<string>>();
            foreach (UserGroup ug in _memberShipFactory.CreateUserGroupDao().GetAll())
            {
                userGroupRoleMap.Add(ug.Id, new List<string>());
                foreach (Role role in ug.GetAllRoles())
                {
                    userGroupRoleMap[ug.Id].Add(role.Id);
                }
            }
            foreach (Role role in _memberShipFactory.CreateRoleDao().GetAll())
            {
                rolePermissionsMap.Add(role.Id, new List<string>());
                foreach (Permission permission in role.Permissions)
                {
                    rolePermissionsMap[role.Id].Add(permission.Id);
                }
            }
            ViewData["userGroupRoleMap"] = userGroupRoleMap;
            ViewData["rolePermissionMap"] = rolePermissionsMap;

            return View(user);
        }
Пример #22
0
 public World()
 {
     HhldscompositePool = new List<SimulationObject>();
     HhldsPool = new List<SimulationObject>();
     PersonPool = new List<SimulationObject>();
     ZonalCollection = new Dictionary<string, SpatialZone>();
 }
Пример #23
0
		public static ICache BuildCacheStatic(string regionName, IDictionary<string,string> properties)
		{
			if (regionName != null && caches[regionName] != null)
			{
				return caches[regionName] as ICache;
			}

			if (regionName == null)
			{
				regionName = "";
			}
			if (properties == null)
			{
				properties = new Dictionary<string,string>();
			}
			if (log.IsDebugEnabled)
			{
				StringBuilder sb = new StringBuilder();
				foreach (KeyValuePair<string, string> de in properties)
				{
					sb.Append("name=");
					sb.Append(de.Key);
					sb.Append("&value=");
					sb.Append(de.Value);
					sb.Append(";");
				}
				log.Debug("building cache with region: " + regionName + ", properties: " + sb.ToString());
			}
			FooCache cache = new FooCache(regionName, properties);
			caches.Add(regionName, cache);
			return cache;
		}
Пример #24
0
        static CodeDomProvider GetCodeProviderInstance(Type type, string compilerVersion)
        {
            CodeDomProvider provider;
            lock (providersLock)
            {
                if (providers == null)
                {
                    providers = new Dictionary<Type, Dictionary<string, CodeDomProvider>>();
                }

                Dictionary<string, CodeDomProvider> typedProviders;
                if (!providers.TryGetValue(type, out typedProviders))
                {
                    typedProviders = new Dictionary<string, CodeDomProvider>();
                    providers.Add(type, typedProviders);
                }

                if (!typedProviders.TryGetValue(compilerVersion, out provider))
                {
                    provider = CreateCodeProviderInstance(type, compilerVersion);
                    typedProviders.Add(compilerVersion, provider);
                }
            }

            return provider;
        }
Пример #25
0
 private void PrintDictionary(Dictionary<string, string> dic)
 {
     foreach (var pair in dic)
     {
         Output.WriteLine("{0}-{1}", pair.Key, pair.Value);
     }
 }
Пример #26
0
    /// <summary>Returns at most the 4 closest addresses in order.</summary>
    protected List<Connection> GetClosest(List<Connection> cons)
    {
      List<Connection> closest = new List<Connection>(cons);

      // Since MeasuredLatency could change the duration of our sorting we make
      // a copy as necessary
      Dictionary<Connection, double> latencies = new Dictionary<Connection, double>();

      Comparison<Connection> comparer = delegate(Connection x, Connection y) {
        double lat_x, lat_y;
        if(!latencies.TryGetValue(x, out lat_x)) {
          lat_x = _ncservice.GetMeasuredLatency(x.Address);
          latencies[x] = lat_x;
        }
        if(!latencies.TryGetValue(y, out lat_y)) {
          lat_y = _ncservice.GetMeasuredLatency(y.Address);
          latencies[y] = lat_y;
        }

        // Remember that smaller is better but -1 is bad...
        // If either is smaller than 0 invert the comparison..
        if(lat_x < 0 || lat_y < 0) {
          return lat_y.CompareTo(lat_x);
        } else {
          return lat_x.CompareTo(lat_y);
        }
      };

      closest.Sort(comparer);
      if(closest.Count > 4) {
        closest.RemoveRange(4, closest.Count - 4);
      }
      return closest;
    }
        public void Add()
        {
            IDictionary<string, string> dict = new Dictionary<string, string>();
            dict = dict.ToReadOnlyDictionary();

            Assert.Throws<NotSupportedException>(() => dict.Add("", ""));
        }
Пример #28
0
    static Dictionary<string, int> LoadNameIndex(BitAccess bits) {
      Dictionary<string, int> result = new Dictionary<string, int>();
      int ver;
      int sig;
      int age;
      Guid guid;
      bits.ReadInt32(out ver);    //  0..3  Version
      bits.ReadInt32(out sig);    //  4..7  Signature
      bits.ReadInt32(out age);    //  8..11 Age
      bits.ReadGuid(out guid);       // 12..27 GUID

      //if (ver != 20000404) {
      //  throw new PdbDebugException("Unsupported PDB Stream version {0}", ver);
      //}

      // Read string buffer.
      int buf;
      bits.ReadInt32(out buf);    // 28..31 Bytes of Strings

      int beg = bits.Position;
      int nxt = bits.Position + buf;

      bits.Position = nxt;

      // Read map index.
      int cnt;        // n+0..3 hash size.
      int max;        // n+4..7 maximum ni.

      bits.ReadInt32(out cnt);
      bits.ReadInt32(out max);

      BitSet present = new BitSet(bits);
      BitSet deleted = new BitSet(bits);
      if (!deleted.IsEmpty) {
        throw new PdbDebugException("Unsupported PDB deleted bitset is not empty.");
      }

      int j = 0;
      for (int i = 0; i < max; i++) {
        if (present.IsSet(i)) {
          int ns;
          int ni;
          bits.ReadInt32(out ns);
          bits.ReadInt32(out ni);

          string name;
          int saved = bits.Position;
          bits.Position = beg + ns;
          bits.ReadCString(out name);
          bits.Position = saved;

          result.Add(name.ToUpperInvariant(), ni);
          j++;
        }
      }
      if (j != cnt) {
        throw new PdbDebugException("Count mismatch. ({0} != {1})", j, cnt);
      }
      return result;
    }
Пример #29
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="entity">an actual entity object, not a proxy!</param>
		/// <param name="entityMode"></param>
		/// <returns></returns>
		public string ToString(object entity, EntityMode entityMode)
		{
			IClassMetadata cm = _factory.GetClassMetadata(entity.GetType());
			if (cm == null)
			{
				return entity.GetType().FullName;
			}

			IDictionary<string, string> result = new Dictionary<string, string>();

			if (cm.HasIdentifierProperty)
			{
				result[cm.IdentifierPropertyName] =
					cm.IdentifierType.ToLoggableString(cm.GetIdentifier(entity, entityMode), _factory);
			}

			IType[] types = cm.PropertyTypes;
			string[] names = cm.PropertyNames;
			object[] values = cm.GetPropertyValues(entity, entityMode);

			for (int i = 0; i < types.Length; i++)
			{
				result[names[i]] = types[i].ToLoggableString(values[i], _factory);
			}

			return cm.EntityName + CollectionPrinter.ToString(result);
		}
Пример #30
0
        private int _updateInterval = 60 * (1000*60); // ms

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Create an OrbitGetter object with its update interval set to <i>updateIntervalMinutes</i>
        /// </summary>
        /// <param name="updateIntervalMinutes">the frequency, in minutes, to update TLE files.</param>
        public OrbitGetter(int updateIntervalMinutes)
        {
            this._updateInterval = updateIntervalMinutes * 60 * 1000; // ms
            this._constellations = new Dictionary<string, Constellation2>();
            this._tleThread = new Thread(new ThreadStart(this.UpdateConstellations));
            this._tleThread.Start();
        }