public void Initialize() { if (!SteamManager.initializedMain) { return; } m_GameRichPresenceJoinRequested = Steamworks.Callback <GameRichPresenceJoinRequested_t> .Create(OnGameRichPresenceJoinRequested); m_PersonaStateChange = Steamworks.Callback <PersonaStateChange_t> .Create(OnPersonaStateChange); EFriendFlags friendFlags = EFriendFlags.k_EFriendFlagImmediate; int friendsCount = SteamFriends.GetFriendCount(friendFlags); for (int friendIndex = 0; friendIndex < friendsCount; ++friendIndex) { CSteamID friendSteamId = SteamFriends.GetFriendByIndex(friendIndex, friendFlags); if (!friendSteamId.IsValid()) { continue; } SteamFriend steamFriend = new SteamFriend(friendSteamId); m_Friends.Add(friendSteamId, steamFriend); } }
/// <summary> /// /// </summary> /// <param name="dimensions">Canvas dimentions.</param> /// <param name="items"></param> /// <returns></returns> public DictionaryList <int, long> CalculateRows(FloatPoint dimensions, DICT <long, FloatRect> items) { this.Dimensions = dimensions; int rowIndex = 0; float rowTotalWidth = 0; DictionaryList <int, long> newRow = new DictionaryList <int, long>(); List <long> newRowIndex = new List <long>(); foreach (long l in items.Keys) { if (HasColumnWidth(items[l], rowTotalWidth, dimensions.X)) { newRowIndex.Add(l); rowTotalWidth += items[l].Width; } else { newRow.Add(rowIndex++, new List <long>(newRowIndex.ToArray())); newRowIndex.Clear(); rowTotalWidth = 0; newRowIndex.Add(l); rowTotalWidth += items[l].Width; } } newRow.Add(rowIndex++, new List <long>(newRowIndex.ToArray())); rowsAndColumns = newRow; Rows = GetRowHeights(items).ToArray(); // we could have gotten these? return(newRow); }
/// <summary> /// Adds an entry to this bucket /// </summary> /// <param name="entry">The entry for a transaction</param> public void AddEntry(ITransactionBookEntry entry) { if (!(entry is ISplitTransactionBookEntry)) { _entries.Add(entry.StockId, entry.Copy()); } AdjustAvailableUnits(entry.Copy()); }
void ICommandVisitor.Visit(CommandUpdateResource cmd) { if (Resources.TryGetValue(cmd.Data, out var model)) { model.Update(cmd.Amount); } else { Resources.Add(cmd.Data, new ResourceModel(cmd.Data, cmd.Amount)); EventResourcesChanged?.Invoke(); } }
private MethodInfo MatchGenericMethod(Type type, string memberName, IList <Type> arguments) { var potentialMatches = type.GetMethods(BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy) .Where(m => m.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) .Where(m => m.IsGenericMethod) .Where(m => m.GetParameters().Length == arguments.Count()); foreach (var genericMethodInfo in potentialMatches) { var genericVersion = ResolveGenericMethodParameters(genericMethodInfo); if (genericVersion != null) { return(genericVersion); } } // check to see if the supplied types can be used to resolve the genericParamters MethodInfo ResolveGenericMethodParameters(MethodInfo potentialmatch) { //Match Generic arguments with the method arguments to find possible types //connect a <T> to a arguments (T item) DictionaryList <Type, Type> genericTargetTypes = new DictionaryList <Type, Type>(); var methodParameters = potentialmatch.GetParameters(); for (int i = 0; i < methodParameters.Count(); i++) { if (methodParameters[i].ParameterType.IsGenericParameter) { genericTargetTypes.Add(methodParameters[i].ParameterType, arguments[i]); } if (methodParameters[i].ParameterType.IsGenericType) { genericTargetTypes.Add(methodParameters[i].ParameterType.GenericTypeArguments[0], arguments[i].GenericTypeArguments[0]); } } //todo We need to check the the supplied types implement the generic where constraints var genericParameters = potentialmatch.GetGenericArguments(); // todo we need to look at all posssible types and find their highest common ancestor // currently just assuming the first var typeArguments = genericParameters.Select(g => genericTargetTypes.Get(g).First()); return(potentialmatch.MakeGenericMethod(typeArguments.ToArray())); } return(null); }
private void OnCastCard(ActionCompletedEvent <CastCardCommand> evt) { GameCard card = evt.Action.CastedCard; Spell spell = evt.Action.CastedSpell; int xpos = XPosFromPlayer(card.Owner); int ypos = YPosFromPlayer(card.Owner); GameObject gobj = this.Factory.GameObjectFromModel(card); Factory.TransformCardToSpell(gobj, spell); var spellview = gobj.GetComponent <GuiSpellViewHandler>(); var vec3 = Factory.ConvertPos(new Point(xpos, ypos)); vec3.z += +1.5f - ZPosFromPlayer(card.Owner); var scale = gobj.transform.localScale; scale.x = scale.x * 10; scale.y = scale.y * 10; scale.z = scale.z * 10; gobj.transform.localScale = scale; spellview.FlyToPos = vec3; playersCardStack.Add(card.Owner, spell); //gobj.c }
// INTERNALS private void InternalAddTouch(GameObject i_Source, FP i_Timestamp) { int currentTick = TrueSyncManager.ticksMain; // Build touche cache. tnTouchCache touch = new tnTouchCache(i_Source, i_Timestamp); // Add it to list. List <tnTouchCache> touches; bool alreadyPresent = m_PendingTouches.TryGetValue(currentTick, out touches); if (touches == null) { touches = new List <tnTouchCache>(); } if (!alreadyPresent) { m_PendingTouches.Add(currentTick, touches); } touches.Add(touch); }
private void LoadAssemblies() { String _pluginDirectory = Path.Combine(Application.StartupPath, "Plugins"); DirectoryInfo _directory = new DirectoryInfo(_pluginDirectory); if (!_directory.Exists) { return; } FileInfo[] _files = _directory.GetFiles("*.dll"); foreach (FileInfo file in _files) { Assembly _assembly = Assembly.LoadFrom(file.FullName); Type[] _types = _assembly.GetTypes(); foreach (Type type in _types) { if (!Utils.HasInterface(type, typeof(IEditorPlugin))) { continue; } IEditorPlugin _plugin = Activator.CreateInstance(type) as IEditorPlugin; PluginContainer _pluginref = new PluginContainer(_plugin, _plugin.Id.ToString()); _Plugins.Add(_pluginref); } } }
public DictionaryList<Point, ConsoleEntityView> AllEntities() { var locs = new DictionaryList<Point, ConsoleEntityView>(); Size wbSize = this.model.BurstSize; if (focus == null || focus.Module<VisionModule>().Vision == null) { foreach (KeyValuePair<XmasEntity, ConsoleEntityView> kv in viewlookup) { Point p = ((TilePosition) kv.Value.Position).Point; Point transp = new Point(p.X + wbSize.Width, p.Y + wbSize.Height); locs.Add(transp, kv.Value); } } else { var vision = focus.Module<VisionModule>(); foreach (var kv in vision.Vision.VisibleTiles) { Point p = kv.Key; Point transp = new Point(p.X + wbSize.Width, p.Y + wbSize.Height); foreach (var ent in kv.Value.Entities) { ConsoleEntityView vent; if(viewlookup.TryGetValue(ent,out vent)) locs.Add(transp, vent); } } } return locs; }
public void putInBulletPool(GameObject bullet) { //bulletPoolDic.Add(bullet.name,bullet); bulletPoolDicList.Add(bullet.name, bullet); bullet.transform.parent = bulletPool.transform; bullet.SetActive(false); }
public void TestAdd() { var newList = new DictionaryList<int>(); Assert.AreEqual(0, newList.Count); newList.Add(1); Assert.AreEqual(1, newList.Count); Assert.AreEqual(1, newList[0]); newList.Add(3); Assert.AreEqual(2, newList.Count); Assert.AreEqual(1, newList[0]); Assert.AreEqual(3, newList[1]); newList[null] = 7; Assert.AreEqual(3, newList.Count); Assert.AreEqual(1, newList[0]); Assert.AreEqual(3, newList[1]); Assert.AreEqual(7, newList[2]); Assert.AreEqual(7, newList[null]); newList.Add(1, 9); Assert.AreEqual(4, newList.Count); Assert.AreEqual(1, newList[0]); Assert.AreEqual(9, newList[1]); Assert.AreEqual(3, newList[2]); Assert.AreEqual(7, newList[3]); newList.Add(null, 44); Assert.AreEqual(5, newList.Count); Assert.AreEqual(1, newList[0]); Assert.AreEqual(9, newList[1]); Assert.AreEqual(3, newList[2]); Assert.AreEqual(7, newList[3]); Assert.AreEqual(44, newList[4]); Assert.AreEqual(44, newList[null]); Assert.AreEqual(5, newList.Count); Assert.AreEqual(5, newList.Count); Assert.AreEqual(1, newList[0]); Assert.AreEqual(9, newList[1]); Assert.AreEqual(3, newList[2]); Assert.AreEqual(7, newList[3]); Assert.AreEqual(44, newList[4]); }
public void Add(IObserver observer, bool notify = true) { ObserverSystem.Logger.Debug($"Name={observer.Name} is observing VarName={observer.VarName}"); observers.Add(observer.VarName, observer); if (notify && varRegistry.TryGetVar(observer.VarName, out IObservable obj)) { NotifyObserver(obj); } }
internal ObjectInfo(object receiver, Type type, string modelName) : this() { IsObjectContext = Attribute.GetCustomAttribute(type, typeof(ObjectContextAttribute), false) != null; // 扫描对象的每个属性,根据属性所标注的特性,配置Attribute,Content和Element子项 PropertyInfo[] properties = type.GetProperties(BIND_ATTRIBUTE); foreach (var property in properties) { object[] propertyAttributes = property.GetCustomAttributes(false); if (propertyAttributes.Length == 0) { continue; } var attribute = (from attr in propertyAttributes where attr is SimpleAttributeAttribute select attr).FirstOrDefault(); if (attribute != null) { SimpleAttributeAttribute simpleAttr = attribute as SimpleAttributeAttribute; simpleAttr.SetNameMode(modelName, property); ObjectPropertyInfo attrInfo = new ReflectorObjectPropertyInfo( property, simpleAttr, modelName); fAttributes.Add(attrInfo.QName.LocalName, attrInfo); continue; } attribute = (from attr in propertyAttributes where (attr is TextContentAttribute || attr is ComplexContentAttribute) select attr).FirstOrDefault(); if (attribute != null) { AssertContent(receiver, type, fContent); fContent = new ReflectorObjectPropertyInfo(property, attribute as BaseObjectAttribute, modelName); continue; } attribute = (from attr in propertyAttributes where attr is TagElementAttribute select attr).FirstOrDefault(); if (attribute != null) { TagElementAttribute tagAttr = attribute.Convert <TagElementAttribute>(); tagAttr.SetNameMode(modelName, property); fElements.Add(type, property, tagAttr, modelName); tagAttr.Read(type, property, modelName, propertyAttributes); continue; } fElements.ReadElementAttribute(type, property, modelName, propertyAttributes); } }
/// <summary> /// 添加任务 /// </summary> /// <param name="task"></param> public WorkFlow AddTask(Task task) { if (task.workFlow != null && task.workFlow != this) { Debug.unityLogger.LogError("添加任务错误", "该任务已经在别的工程当中了"); return(this); } task.workFlow = this; taskDict.Add(task.name, task); return(this); }
public static void tokenAdd(string user, string token, DateTime dateExpiry) { if (dicUserToken.ContainsKey(user)) { var ls = dicUserToken[user]; if (ls.IndexOf(token) == -1) { lock (lock_token) { dicUserToken.Add(user, token); } } } else { lock (lock_token) { dicUserToken.Add(user, token); } } }
public List <DatabaseSearchResult> Find(String searchText, String databaseName, Int32 limit, List <string> keywordsToHighligh) { var dbDictionary = DictionaryList.FirstOrDefault(x => x.DatabaseName == databaseName); if (dbDictionary == null) { dbDictionary = new DatabaseDictionary(); dbDictionary.Initialise(databaseName); DictionaryList.Add(dbDictionary); FillDatabase(dbDictionary); } return(dbDictionary.Find(searchText, limit, keywordsToHighligh)); }
/// <summary> /// リソースのロード /// </summary> /// <param name="directryName"></param> /// <param name="PrefabName"></param> /// <returns></returns> public GameObject Load(string directryName, string PrefabName) { var obj = Resources.Load(directryName + PrefabName) as GameObject; if (obj != null) { DictionaryList.Add(PrefabName, obj); } else { DebugLog.log("読み込み失敗 : " + PrefabName); Debug.Log("読み込み失敗 : " + PrefabName); } return(obj); }
void Awake() { if (_mixerControls != null) { for (int i = 0; i < _mixerControls.Length; ++i) { var c = _mixerControls[i]; if (c.mixerGroup != null) { MixerGroupState s = new MixerGroupState(); s.mixerControl = c; _mixerState.Add(c.mixerGroup, s); } } } }
// LOGIC public void RegisterGameObject(GameObject i_Go, int i_Delay = 0) { if (i_Go == null) { return; } int delay = Mathf.Max(0, i_Delay); tnInput[] inputs = new tnInput[delay + 1]; for (int index = 0; index < inputs.Length; ++index) { inputs[index] = new tnInput(); } m_RegisteredGameObjects.Add(i_Go, inputs); }
// INTERNALS private void Internal_CacheTarget(int i_Tick, tnHoleTarget i_Target) { if (i_Target == null) { return; } List <tnHoleTarget> targets; bool alreadyPresent = m_Pending.TryGetValue(i_Tick, out targets); if (targets == null) { targets = new List <tnHoleTarget>(); } if (!alreadyPresent) { m_Pending.Add(i_Tick, targets); } targets.Add(i_Target); }
public PegBuilder(Grammar grammar, bool searchSubclasses) { this.grammar = grammar; foreach (var rule in grammar.Nonterminals) { string name = rule.Name; MethodInfo method = grammar.GetType().GetMethod(name, new Type[0]); if (method != null) { AstAttribute[] asts = grammar.GetType().GetMethod(name, new Type[0]).GetAttributes <AstAttribute>(); foreach (AstAttribute ast in asts) { if (ast != null) { astTypes.Add(name, new TypeRecord(ast.GetExpression(), ast.Type)); Nonterminal nonterminal = grammar.GetNonterminal(method.Name); astAttributes.Add(nonterminal, ast); } } } } HashSet <Type> types = new HashSet <Type>(); WalkTypeForNonTerminals(typeof(T), types, searchSubclasses); foreach (Type type in types) { ConsumeAttribute[] nonterminalAttributes = type.GetAttributes <ConsumeAttribute>(); foreach (var attribute in nonterminalAttributes) { // nonterminalTypes[attribute.Expression] = type; nonterminalNames[type] = attribute.Expression; } } }
// #TODO GetPath will be expensive !!!! public List <CodeSnippet> FindNodes(string find) { DictionaryList <CodeSnippet, string> _items = CodeLib.Instance.CodeSnippets.Where(p => LocalUtils.LastPart(p.GetPath()).ToLower().Contains(find.ToLower())).ToDictionaryList(p => p.Id); _items.RegisterLookup("PATH", p => p.GetPath()); DictionaryList <CodeSnippet, string> _paths = new DictionaryList <CodeSnippet, string>(p => p.GetPath()); foreach (CodeSnippet item in _items) { List <CodeSnippet> _parents = GetParents(item.GetPath()); foreach (CodeSnippet parent in _parents) { if (!_paths.ContainsKey(parent.GetPath()) && (_items.Lookup("PATH", parent.GetPath()).FirstOrDefault() == null)) { _paths.Add(parent); } } } _items.AddRange(_paths); return(_items.ToList()); }
/// <summary> /// Adjusts the amount of available units for every transaction /// </summary> /// <param name="newEntry">New entry</param> private void AdjustAvailableUnits(ITransactionBookEntry newEntry) { var id = newEntry.StockId; if (newEntry is ISellingTransactionBookEntry && newEntry.Shares > GetOrAddOpenPosition(id).Shares) { throw new InvalidOperationException("Cannot sell more units than available."); } _changedEntries.Clear(id); if (newEntry is IBuyingTransactionBookEntry) { UpdateOpenPosition(id); return; } if (newEntry is ISplitTransactionBookEntry split) { var buys = _entries.GetOrAdd(id).Where(e => e is IBuyingTransactionBookEntry).ToList(); buys.ForEach(t => _entries.Delete(id, t)); _entries.Add(id, split.CreatePositionAfterSplit(buys)); UpdateOpenPosition(id); return; } var newUnitsToSell = newEntry.Shares; var deletes = new List <ITransactionBookEntry>(); foreach (var entry in _entries.GetOrAdd(id).OrderBy(e => e.OrderDate)) { if (entry is IBuyingTransactionBookEntry) { var changed = entry.Copy(); //Complete buying transaction filled if (entry.Shares <= newUnitsToSell) { newUnitsToSell -= entry.Shares; if (!(newEntry is IDividendTransactionBookEntry)) { entry.Shares = 0; } } //Partly filled else { changed.Shares = newUnitsToSell; changed.OrderCosts = (entry.OrderCosts / entry.Shares) * newUnitsToSell; if (!(newEntry is IDividendTransactionBookEntry)) { entry.OrderCosts = (entry.OrderCosts / entry.Shares) * (entry.Shares - newUnitsToSell); entry.Shares -= newUnitsToSell; } newUnitsToSell = 0; } _changedEntries.Add(id, changed); if (entry.Shares == 0 && !(newEntry is IDividendTransactionBookEntry)) { deletes.Add(entry); } if (newUnitsToSell == 0) { break; } } } _changedEntries.Add(id, newEntry); _entries.Delete(id, newEntry); if (!(newEntry is IDividendTransactionBookEntry)) { deletes.ForEach(t => _entries.Delete(id, t)); } UpdateOpenPosition(id); }
/// <summary> /// 依赖任务 /// </summary> /// <param name="task"></param> public Task DependsOn(Task task) { taskDict.Add(task.name, task); return(this); }
void BackupProgramHandler_DoWork(object sender, DoWorkEventArgs e) { if (Core.settings.IsBackupPathSet || archive_name_override != null) { if (archive_name_override != null) { output_path = Path.GetDirectoryName(archive_name_override); } else { output_path = Core.settings.backup_path; } IList <GameEntry> games; if (back_these_up != null && back_these_up.Count > 0) { games = back_these_up; } else { if (Games.detected_games_count == 0) { Games.detectGames(); } games = Games.DetectedGames.Items; } if (games.Count > 0) { ProgressHandler.value = 1; ProgressHandler.max = games.Count; TranslatingProgressHandler.setTranslatedMessage("GamesToBeBackedUpCount", games.Count.ToString()); foreach (GameEntry game in games) { if (CancellationPending) { return; } //if(archive_name_override!=null) //all_users_archive = new ArchiveHandler(new FileInfo(archive_name_override),game.id); if (games.Count == 1) { TranslatingProgressHandler.setTranslatedMessage("BackingUpSingleGame", game.Title); } else { TranslatingProgressHandler.setTranslatedMessage("BackingUpMultipleGames", game.Title, ProgressHandler.value.ToString(), games.Count.ToString()); } List <DetectedFile> files; if (only_these_files != null && only_these_files.Count > 0) { files = only_these_files; } else { files = game.Saves.Flatten(); ; } Archive override_archive = null; try { DictionaryList <Archive, DetectedFile> backup_files = new DictionaryList <Archive, DetectedFile>(); foreach (DetectedFile file in files) { ArchiveID archive_id; Archive archive; if (CancellationPending) { return; } archive_id = new ArchiveID(game.id, file); if (archive_name_override != null) { if (override_archive == null) { file.Type = null; } override_archive = new Archive(new FileInfo(archive_name_override), new ArchiveID(game.id, file)); archive = override_archive; } else { if (Archives.Get(archive_id) == null) { Archives.Add(new Archive(output_path, new ArchiveID(game.id, file))); } archive = Archives.Get(archive_id); } backup_files.Add(archive, file); } if (CancellationPending) { return; } foreach (KeyValuePair <Archive, List <DetectedFile> > backup_file in backup_files) { if (override_archive == null) { backup_file.Key.backup(backup_file.Value, false, false); } else { backup_file.Key.backup(backup_file.Value, true, false); } } } catch (Exception ex) { TranslatingMessageHandler.SendException(ex); } finally { ProgressHandler.value++; } } } else { TranslatingMessageHandler.SendError("NothingToBackup"); } } else { TranslatingMessageHandler.SendError("BackupPathNotSet"); } }
public void CanAddNullValueList() { // ReSharper disable RedundantCast var sample = new DictionaryList<string, object> { { "key1", (IList<object>)null } }; Assert.AreEqual(0, sample["key1"].Count); sample.Add("key1", (IList<object>)null); Assert.AreEqual(0, sample["key1"].Count); // ReSharper restore RedundantCast }
public FrontAction(string targetFrontObject) { this.targetFrontObject = targetFrontObject; actionsByTarget.Add(targetFrontObject, this); }
/// <summary> /// 应用属性 /// </summary> /// <param name="prop"></param> public WorkFlow Apply(Property prop) { propertys.Add(prop.name, prop); return(this); }
/// <summary> /// Recursive method to resolve annotations in parameter class and its super classes. /// This mehthod creates field descriptors and other optimized datastructures, which /// is used for marshalling and ummarshalling of runtime objects. /// </summary> /// <param name="thatClass"> /// The parameter class <c>Type</c> to resolve any defined annotations. /// </param> /// <param name="fieldDescriptorClass"> /// Used by recursive call from inside the function. Can be null if being called /// for the first time. /// </param> public void DeriveAndOrganizeFieldsRecursive(Type thatClass) { if (XmlTools.IsAnnotationPresent <SimplInherit>(thatClass)) { TypeInfo classTypeInfo = thatClass.GetTypeInfo(); Type[] superClassGenericArguments = classTypeInfo.BaseType.GenericTypeArguments; ClassDescriptor superClassDescriptor = GetClassDescriptor(classTypeInfo.BaseType); ReferFieldDescriptorsFrom(superClassDescriptor, superClassGenericArguments); } IEnumerable <FieldInfo> fields = thatClass.GetTypeInfo().DeclaredFields; // Iterate through all fields for the type foreach (FieldInfo thatField in fields) { // We don't serialize static values in S.im.pl, continue on to the next field if ((thatField.IsStatic)) { continue; } Int16 fieldType = FieldTypes.UnsetType; if (XmlTools.IsScalar(thatField)) { fieldType = FieldTypes.Scalar; } else if (XmlTools.IsAnnotationPresent <SimplComposite>(thatField)) { fieldType = FieldTypes.CompositeElement; } else if (XmlTools.IsAnnotationPresent <SimplCollection>(thatField)) { fieldType = FieldTypes.CollectionElement; } else if (XmlTools.IsAnnotationPresent <SimplMap>(thatField)) { fieldType = FieldTypes.MapElement; } if (fieldType == FieldTypes.UnsetType) { continue; //not a simpl serialization annotated field } FieldDescriptor fieldDescriptor = NewFieldDescriptor(thatField, fieldType, fieldDescriptorClass); //generics fieldDescriptor.GenericTypeVarsContextCD = this; if (fieldDescriptor.FdType == FieldTypes.Scalar) { Hint xmlHint = fieldDescriptor.XmlHint; switch (xmlHint) { case Hint.XmlAttribute: _attributeFieldDescriptors.Add(fieldDescriptor); break; case Hint.XmlText: case Hint.XmlTextCdata: break; case Hint.XmlLeaf: case Hint.XmlLeafCdata: _elementFieldDescriptors.Add(fieldDescriptor); break; } } else { _elementFieldDescriptors.Add(fieldDescriptor); } if (XmlTools.IsCompositeAsScalarValue(thatField)) { _scalarValueFieldDescriptor = fieldDescriptor; } _fieldDescriptorsByFieldName.Add(thatField.Name, fieldDescriptor); if (fieldDescriptor.IsMarshallOnly) { continue; } String fieldTagName = fieldDescriptor.TagName; if (fieldDescriptor.IsWrapped) { FieldDescriptor wrapper = NewFieldDescriptor(fieldDescriptor, fieldTagName, fieldDescriptorClass); MapTagToFdForTranslateFrom(fieldTagName, wrapper); } else if (!fieldDescriptor.IsPolymorphic) { String tag = fieldDescriptor.IsCollection ? fieldDescriptor.CollectionOrMapTagName : fieldTagName; MapTagToFdForTranslateFrom(tag, fieldDescriptor); var otherTagsAttributes = XmlTools.GetAnnotation <SimplOtherTags>(thatField); String[] otherTags = XmlTools.OtherTags(otherTagsAttributes); if (otherTags != null) { foreach (String otherTag in otherTags) { MapTagToFdForTranslateFrom(otherTag, fieldDescriptor); } } } else { MapTagClassDescriptors(fieldDescriptor); } } }
public void TickServer(float dt, byte[] recvBuffer, ref NetIOMetrics reliableChannelMetrics, ref NetIOMetrics unreliableChannelMetrics) { Perf.Begin("SocketNetDriver.TickServer"); for (;;) { Socket newSocket; try { newSocket = _serverSock[0].Accept(); } catch (SocketException) { break; } if (_tcpConnections.ContainsKey(newSocket.RemoteEndPoint)) { Debug.LogError("Connection attempt from already connected client!"); newSocket.Close(); continue; } var clientSocks = new Socket[2]; clientSocks[0] = newSocket; clientSocks[1] = _serverSock[1]; newSocket.Blocking = false; //newSocket.NoDelay = true; newSocket.SendBufferSize = World.MAX_RELIABLE_MESSAGE_SIZE * 8; newSocket.SendTimeout = 500; var newConn = new SocketNetDriverConnection(this, clientSocks, nextChannelID++); _tcpConnections.Add(newSocket.RemoteEndPoint, newConn); SendTcpControl(newConn); } for (int i = 0; i < _tcpConnections.Values.Count;) { var c = _tcpConnections.Values[i]; bool wasReset = false; bool isDisposed = false; try { wasReset = c.sockets[0].Poll(0, SelectMode.SelectRead); } catch (Exception) { isDisposed = true; } if (isDisposed || (wasReset && (c.sockets[0].Available == 0))) { c.Dispose(); continue; } Recv(c, _serverCallbacks, c.sockets[0], recvBuffer, ref reliableChannelMetrics, false); if (c.isValid && !c.didHandshake) { c.handshakeTime += dt; if (c.handshakeTime > UDP_CONTROL_DISCONNECT_TIMEOUT) { // handshake failed Debug.LogError("Disconnecting " + c.tcpEndpoint.ToString() + ": udp handshake timed out"); c.Dispose(); } } if (c.isValid) { ++i; } } RecvFrom(_serverCallbacks, _serverSock[1], recvBuffer, ref unreliableChannelMetrics); Perf.End(); }
public static void load() { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string path_file = path + file_name + ".mmf"; list = hostFile.read_file_MMF <m_kh_nhom>(path_file).ToList(); string p_index = hostServer.pathRoot + @"db_kh_nhom_index\"; if (!Directory.Exists(p_index)) { Directory.CreateDirectory(p_index); } else { var ds = Directory.GetFiles(p_index, "*.mmf"); for (int k = 0; k < ds.Length; k++) { string arr = hostFile.readFile(ds[k], Encoding.ASCII); string key = arr.Split(';')[0]; long id = key.TryParseToLong(); arr = arr.Substring(key.Length, arr.Length - key.Length); if (!dic_Nhom_Index.ContainsKey(id)) { dic_Nhom_Index.Add(id, arr); } } } string p_item = hostServer.pathRoot + @"db_kh_nhom_item\"; if (!Directory.Exists(p_item)) { Directory.CreateDirectory(p_item); } else { var ds = Directory.GetFiles(p_item, "*.mmf"); for (int k = 0; k < ds.Length; k++) { string arr = hostFile.readFile(ds[k], Encoding.ASCII); string key = arr.Split(';')[0]; List <long> aids = arr.Split(';').Select(x => x.TryParseToLong()).ToList(); if (aids.Count > 0) { aids.RemoveAt(0); if (aids.Count > 0) { long id = key.TryParseToLong(); arr = arr.Substring(key.Length, arr.Length - key.Length); if (!dic_Nhom_Item.ContainsKey(id)) { dic_Nhom_Item.Add(id, aids); } } } } } }
public void AddInstruction(INode target, IFlowInstruction instruction) { _instructions.Add(target, instruction); }
void RecvFrom(INetDriverCallbacks callbacks, Socket socket, byte[] buffer, ref NetIOMetrics metrics) { Perf.Begin("SocketNetDriver.RecvFrom"); while (socket.Available > 0) { int r; try { r = socket.ReceiveFrom(buffer, 0, World.MAX_UNRELIABLE_MESSAGE_SIZE, SocketFlags.None, ref _recvEndPoint); } catch (Exception e) { Debug.LogException(e); SocketNetDriverConnection conn; if (_udpConnections.TryGetValue(_recvEndPoint, out conn)) { callbacks.OnInvalidMessageReceived(conn); } continue; } if (r <= 0) { throw new SocketException((int)SocketError.SocketError); } metrics.bytesRecv += r; ++metrics.numPacketsRecv; SocketNetDriverConnection connection; if (_udpConnections.TryGetValue(_recvEndPoint, out connection)) { if (connection.isValid) { if (r > 3) { // currently NetMsgs are always more than 3 bytes, and this guarantees that we don't // try to process a duplicated control udp control message. callbacks.OnMessageReceived(connection, buffer, r); } } } else { // is this a control code? var id = RecvControl(buffer, r); if (id != -1) { for (int i = 0; i < _tcpConnections.Values.Count; ++i) { var c = _tcpConnections.Values[i]; if (c.channelID == id) { if (_udpConnections.Values.Contains(c)) { Debug.LogWarning("UDP control message received for registered channel."); } else { c.udpEndpoint = new IPEndPoint(((IPEndPoint)_recvEndPoint).Address, ((IPEndPoint)_recvEndPoint).Port); _udpConnections.Add(c.udpEndpoint, c); SendTcpControlAck(c); c.didHandshake = true; callbacks.OnConnect(c); break; } } } } } } Perf.End(); }
private SortedList<int, Notice[]> PrepareSortedQueue() { DictionaryList<int, Notice> dl = new DictionaryList<int, Notice>(); List<NabfAgent> agents; SortedList<int, NabfAgent> topDesires; int lowestDesire; foreach (Notice n in _availableJobs.SelectMany(kvp => kvp.Value)) { lowestDesire = FindTopDesiresForNotice(n, out topDesires, out agents); if (lowestDesire != -1) { n.HighestAverageDesirabilityForNotice = topDesires.Keys.Sum() / topDesires.Keys.Count; dl.Add(n.HighestAverageDesirabilityForNotice, n); n.AddRangeToTopDesireAgents(agents); } } SortedList<int, Notice[]> jobs = new SortedList<int, Notice[]>(new InvertedComparer<int>()); foreach (KeyValuePair<int, Notice[]> kvp in dl) jobs.Add(kvp.Key, kvp.Value); return jobs; }
public void AddFromICollectionCountAndContainsAndThisGetWorkingFine() { var sample = new DictionaryList<string, object> { { "key1", new List<object> { "value1" } }, { "key2", new List<object> { "value2" } }, { "key3", new List<object> { 33 } } }; Assert.AreEqual(3, sample.Count); var value = sample["key1"]; Assert.AreEqual(1, value.Count); Assert.IsInstanceOf<string>(value[0]); Assert.AreEqual("value1", value[0]); value = sample["key2"]; Assert.AreEqual(1, value.Count); Assert.IsInstanceOf<string>(value[0]); Assert.AreEqual("value2", value[0]); value = sample["key3"]; Assert.AreEqual(1, value.Count); Assert.IsInstanceOf<int>(value[0]); Assert.AreEqual(33, value[0]); sample.Add("key1", 44); Assert.AreEqual(3, sample.Count); value = sample["key1"]; Assert.IsInstanceOf<List<object>>(value); Assert.AreEqual(2, value.Count); Assert.IsInstanceOf<string>(value[0]); Assert.AreEqual("value1", value[0]); Assert.IsInstanceOf<int>(value[1]); Assert.AreEqual(44, value[1]); value = sample["key2"]; Assert.AreEqual(1, value.Count); Assert.IsInstanceOf<string>(value[0]); Assert.AreEqual("value2", value[0]); value = sample["key3"]; Assert.AreEqual(1, value.Count); Assert.IsInstanceOf<int>(value[0]); Assert.AreEqual(33, value[0]); sample.Remove("key2"); Assert.AreEqual(2, sample.Count); value = sample["key1"]; Assert.AreEqual(2, value.Count); Assert.IsInstanceOf<string>(value[0]); Assert.AreEqual("value1", value[0]); Assert.IsInstanceOf<int>(value[1]); Assert.AreEqual(44, value[1]); value = sample["key3"]; Assert.AreEqual(1, value.Count); Assert.IsInstanceOf<int>(value[0]); Assert.AreEqual(33, value[0]); Assert.IsFalse(sample.Remove("key2")); sample.Remove("key1"); Assert.AreEqual(1, sample.Count); value = sample["key3"]; Assert.AreEqual(1, value.Count); Assert.IsInstanceOf<int>(value[0]); Assert.AreEqual(33, value[0]); sample.Remove("key3"); Assert.AreEqual(0, sample.Count); }
void BackupProgramHandler_DoWork(object sender, DoWorkEventArgs e) { if (Core.settings.IsBackupPathSet || archive_name_override != null) { if (archive_name_override != null) output_path = Path.GetDirectoryName(archive_name_override); else output_path = Core.settings.backup_path; IList<GameEntry> games; if (back_these_up != null && back_these_up.Count > 0) { games = back_these_up; } else { if (Games.detected_games_count == 0) Games.detectGames(); games = Games.DetectedGames.Items; } if (games.Count > 0) { ProgressHandler.value = 1; ProgressHandler.max = games.Count; TranslatingProgressHandler.setTranslatedMessage("GamesToBeBackedUpCount", games.Count.ToString()); foreach (GameEntry game in games) { if (CancellationPending) return; //if(archive_name_override!=null) //all_users_archive = new ArchiveHandler(new FileInfo(archive_name_override),game.id); if (games.Count == 1) { TranslatingProgressHandler.setTranslatedMessage("BackingUpSingleGame", game.Title); } else { TranslatingProgressHandler.setTranslatedMessage("BackingUpMultipleGames", game.Title, ProgressHandler.value.ToString(), games.Count.ToString()); } List<DetectedFile> files; if (only_these_files != null && only_these_files.Count > 0) { files = only_these_files; } else { files = game.Saves.Flatten(); ; } Archive override_archive = null; try { DictionaryList<Archive, DetectedFile> backup_files = new DictionaryList<Archive, DetectedFile>(); foreach (DetectedFile file in files) { ArchiveID archive_id; Archive archive; if (CancellationPending) return; archive_id = new ArchiveID(game.id, file); if (archive_name_override != null) { if (override_archive == null) file.Type = null; override_archive = new Archive(new FileInfo(archive_name_override), new ArchiveID(game.id, file)); archive = override_archive; } else { if (Archives.Get(archive_id) == null) { Archives.Add(new Archive(output_path, new ArchiveID(game.id, file))); } archive = Archives.Get(archive_id); } backup_files.Add(archive, file); } if (CancellationPending) return; foreach (KeyValuePair<Archive, List<DetectedFile>> backup_file in backup_files) { if (override_archive == null) backup_file.Key.backup(backup_file.Value, false,false); else backup_file.Key.backup(backup_file.Value, true, false); } } catch (Exception ex) { TranslatingMessageHandler.SendException(ex); } finally { ProgressHandler.value++; } } } else { TranslatingMessageHandler.SendError("NothingToBackup"); } } else { TranslatingMessageHandler.SendError("BackupPathNotSet"); } }