コード例 #1
0
        /// <summary>
        /// Note: you can call this more than once, in order to change the search language id
        /// </summary>
        public virtual void LoadIndex(string searchLanguageId)
        {
            if (_imageIndexReader == null)
            {
                LoadLanguageChoices();
            }

            _indexOfWordsToRelativePath           = new Dictionary <string, List <string> >();
            _indexOfRelativeFilePathToKeywordsCsv = new Dictionary <string, string>();

            using (var f = File.OpenText(FindIndexFileInFolder(FolderPath)))
            {
                //skip header line, which was already read to make the index layout above
                f.ReadLine();
                while (!f.EndOfStream)
                {
                    var line          = f.ReadLine();
                    var fields        = line.Split(new char[] { '\t' });
                    var relativePath  = _imageIndexReader.GetImageRelativePath(fields);
                    var csvOfKeywords = _imageIndexReader.GetCSVOfKeywordsOrEmpty(searchLanguageId, fields);
                    if (String.IsNullOrWhiteSpace(csvOfKeywords))
                    {
                        continue;
                    }
                    lock (_padlock)
                        _indexOfRelativeFilePathToKeywordsCsv.Add(relativePath, csvOfKeywords.Replace(",", ", "));
                    var keys = csvOfKeywords.SplitTrimmed(',');
                    foreach (var key in keys)
                    {
                        lock (_padlock)
                            _indexOfWordsToRelativePath.GetOrCreate(key.ToLowerInvariant()).Add(relativePath);
                    }
                }
            }
        }
コード例 #2
0
ファイル: HttpUtils.cs プロジェクト: nicetester/ZKWeb-1
        /// <summary>
        /// Parse query string<br/>
        /// 解析查询字符串<br/>
        /// </summary>
        /// <param name="queryString">Query string</param>
        /// <returns></returns>
        /// <example>
        /// <code language="cs">
        /// var result = HttpUtils.ParseQueryString("a=1&amp;b=2&amp;key=%27%26%5E%25%3Dabc");
        /// result.Count == 3
        /// result["a"].Count == 1
        /// result["a"][0] == "1"
        /// result["b"].Count == 1
        /// result["b"][0] == "2"
        /// result["key"].Count == 1
        /// result["key"][0] == "'&amp;^%=abc"
        /// </code>
        /// </example>
        public static IDictionary <string, IList <string> > ParseQueryString(string queryString)
        {
            var result = new Dictionary <string, IList <string> >();

            if (string.IsNullOrEmpty(queryString))
            {
                return(result);
            }
            // Trim beginning `?`
            var startIndex = (queryString[0] == '?') ? 1 : 0;

            // Find all keys and values
            while (startIndex < queryString.Length)
            {
                var equalIndex = queryString.IndexOf('=', startIndex);
                if (equalIndex < 0)
                {
                    return(result);
                }
                var andIndex = queryString.IndexOf('&', equalIndex);
                if (andIndex < 0)
                {
                    andIndex = queryString.Length;
                }
                var key   = UrlDecode(queryString.Substring(startIndex, equalIndex - startIndex));
                var value = UrlDecode(queryString.Substring(equalIndex + 1, andIndex - equalIndex - 1));
                startIndex = andIndex + 1;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    result.GetOrCreate(key, () => new List <string>()).Add(value);
                }
            }
            return(result);
        }
コード例 #3
0
 public string CreatePurgeSql <TReadModel>()
     where TReadModel : IReadModel
 {
     return(_purgeSqls.GetOrCreate(
                typeof(TReadModel),
                t => $"DELETE FROM {GetTableName(t)}"));
 }
コード例 #4
0
        private static AutomationPattern GetAutomationPatternKey(Type patternType)
        {
            AutomationPattern key = patterns.GetOrCreate(patternType, () =>
                                                         (AutomationPattern)patternType.GetField("Pattern", BindingFlags.Static | BindingFlags.Public).GetValue(null));

            return(key);
        }
コード例 #5
0
ファイル: Symbol.cs プロジェクト: jeason0813/framework-2
        /// <summary>
        /// Similar methods of inheritors will be automatically called by Signum.MSBuildTask using AutoInitiAttribute
        /// </summary>
        public Symbol(Type declaringType, string fieldName)
        {
            this.fieldInfo = declaringType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

            if (this.fieldInfo == null)
            {
                throw new InvalidOperationException(string.Format("No field with name {0} found in {1}", fieldName, declaringType.Name));
            }

            this.Key = declaringType.Name + "." + fieldName;

            try
            {
                Symbols.GetOrCreate(this.GetType()).Add(this.Key, this);
            }
            catch (Exception e) when(StartParameters.IgnoredCodeErrors != null)
            {
                //Could happend if Dynamic code has a duplicated name
                this.fieldInfo = null;
                this.Key       = null;
                StartParameters.IgnoredCodeErrors.Add(e);
                return;
            }

            var dic = Ids.TryGetC(this.GetType());

            if (dic != null)
            {
                PrimaryKey?id = dic.TryGetS(this.Key);
                if (id != null)
                {
                    this.SetId(id.Value);
                }
            }
        }
コード例 #6
0
    public static ObservableCollection <Node <T> > ToTreeC <T>(IEnumerable <T> collection, Func <T, T?> getParent)
        where T : class
    {
        Node <T> top = new Node <T>();

        Dictionary <T, Node <T> > dic = new Dictionary <T, Node <T> >();

        Func <T, Node <T> > createNode = null !;

        createNode = item => dic.GetOrCreate(item, () =>
        {
            Node <T> itemNode   = new Node <T>(item);
            T?parent            = getParent(item);
            Node <T> parentNode = parent != null ? createNode(parent) : top;
            parentNode.Children.Add(itemNode);
            return(itemNode);
        });

        foreach (var item in collection)
        {
            createNode(item);
        }

        return(top.Children);
    }
コード例 #7
0
        public IUserAssetEntity GetEntity(Guid guid)
        {
            return(entities.GetOrCreate(guid, () =>
            {
                var element = elements.GetOrThrow(guid);

                Type type = UserAssetNames.GetOrThrow(element.Name.ToString());

                var entity = giRetrieveOrCreate.GetInvoker(type)(guid);

                entity.FromXml(element, this);

                previews.Add(guid, new UserAssetPreviewLineEmbedded
                {
                    Text = entity.ToString() !,
                    Type = entity.GetType().ToTypeEntity(),
                    Guid = guid,
                    Action = entity.IsNew ? EntityAction.New :
                             customResolutionModel.ContainsKey(entity.Guid) ? EntityAction.Different :
                             GraphExplorer.FromRootVirtual((Entity)entity).Any(a => a.Modified != ModifiedState.Clean) ? EntityAction.Different :
                             EntityAction.Identical,
                    CustomResolution = customResolutionModel.TryGetCN(entity.Guid),
                });

                return entity;
            }));
コード例 #8
0
        /// <summary>
        /// Constructs a new material.
        /// </summary>
        /// <param name="name">The name of the material. Must not be null or whitespace.</param>
        /// <param name="shader">The fragment shader used to draw objects rendered with this material.</param>
        public Material(string name, FragmentShader shader)
        {
            Assure.False(name.IsNullOrEmpty(), "Invalid material name.");
            Assure.NotNull(shader);
            Assure.False(shader.IsDisposed, "Shader must not be disposed.");
            Name   = name;
            Shader = shader;
            lock (staticMutationLock) {
                for (uint i = 0; i < activeMaterials.Length; ++i)
                {
                    if (activeMaterials[i] == null)
                    {
                        Index = i;
                        goto slotFound;
                    }
                }
                Material[] newMatArray = new Material[activeMaterials.Length * 2];
                Array.Copy(activeMaterials, newMatArray, activeMaterials.Length);
                Index           = (uint)activeMaterials.Length;
                activeMaterials = newMatArray;
                slotFound : activeMaterials[Index] = this;

                shaderMaterialMap.GetOrCreate(shader, _ => new List <Material>()).Add(this);
            }
        }
コード例 #9
0
        public static void AddRange <K, V, T>(this IDictionary <K, V> dictionary, IEnumerable <T> collection, Func <T, K> keySelector, Func <T, V> valueSelector, string errorContext)
        {
            Dictionary <K, List <V> > repetitions = new Dictionary <K, List <V> >();

            foreach (var item in collection)
            {
                var key = keySelector(item);
                if (dictionary.ContainsKey(key))
                {
                    repetitions.GetOrCreate(key, () => new List <V> {
                        dictionary[key]
                    }).Add(valueSelector(item));
                }
                else
                {
                    dictionary.Add(key, valueSelector(item));
                }
            }

            if (repetitions.Count > 0)
            {
                throw new ArgumentException("There are some repeated {0}: {1}".FormatWith(errorContext, repetitions
                                                                                          .ToString(kvp => "{0} ({1})".FormatWith(kvp.Key, kvp.Value.ToString(", ")), "\r\n")));
            }
        }
コード例 #10
0
        public static void AddRange <K, V, T>(this IDictionary <K, V> dictionary, IEnumerable <T> collection, Func <T, K> keySelector, Func <T, V> valueSelector, string errorContext)
            where K : notnull
        {
            Dictionary <K, List <V> > repetitions = new Dictionary <K, List <V> >();

            foreach (var item in collection)
            {
                var key = keySelector(item);
                if (dictionary.ContainsKey(key))
                {
                    repetitions.GetOrCreate(key, () => new List <V> {
                        dictionary[key]
                    }).Add(valueSelector(item));
                }
                else
                {
                    dictionary.Add(key, valueSelector(item));
                }
            }

            if (repetitions.Count > 0)
            {
                throw new RepeatedElementsException($@"There are some repeated {errorContext}...
{repetitions.ToString(kvp => $@"Key ""{kvp.Key}"" has {kvp.Value.Count} repetitions:
{kvp.Value.Take(ErrorExampleLimit).ToString("\r\n").Indent(4)}", "\r\n")}");
            }
        }
コード例 #11
0
        static string GetToken(LambdaExpression expr)
        {
            var tuple = Tuple.Create(expr.Parameters.Single().Type, expr.Body.Type);

            return(Tokens.GetOrCreate(tuple, () =>
                                      "Entity." + Reflector.GetMemberListBase(expr.Body).ToString(a => a.Name, ".")));
        }
コード例 #12
0
        public void Custom(string t, string msg)
        {
            var date = DateTime.UtcNow.ToLongTimeString();
            var log  = "C" + date + ": " + msg;

            _customSubj.GetOrCreate(t).OnNext(log);
        }
コード例 #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="frame">Inheritors should use new StackFrame(1, false) and add [MethodImpl(MethodImplOptions.NoInlining)]</param>
        /// <param name="fieldName">Inheritors should use [CallerMemberName]</param>
        protected void MakeSymbol(StackFrame frame, string fieldName)
        {
            var mi = frame.GetMethod();

            if (mi != mi.DeclaringType.TypeInitializer)
            {
                throw new InvalidOperationException(string.Format("{0} {1} can only be created in static field initializers", GetType().Name, fieldName));
            }

            if (!IsStaticClass(mi.DeclaringType))
            {
                throw new InvalidOperationException(string.Format("{0} {1} is declared in {2}, but {2} is not static", GetType().Name, fieldName, mi.DeclaringType.Name));
            }

            this.fieldInfo = mi.DeclaringType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

            if (this.fieldInfo == null)
            {
                throw new InvalidOperationException(string.Format("No field with name {0} found in {1}", fieldName, mi.DeclaringType.Name));
            }

            this.Key = mi.DeclaringType.Name + "." + fieldName;

            var dic = Ids.TryGetC(this.GetType());

            if (dic != null)
            {
                var tup = dic.TryGetC(this.Key);
                if (tup != null)
                {
                    this.SetIdAndName(tup);
                }
            }
            Symbols.GetOrCreate(this.GetType()).Add(this.Key, this);
        }
コード例 #14
0
        public async Task <Dictionary <string, int> > BuildOffsetCoordinatorMapAsync(CancellationToken token, params string[] consumerGroups)
        {
            if (connections.Count == 0)
            {
                await RefreshAsync(token).ConfigureAwait(false);
            }

            foreach (var consumerGroup in consumerGroups)
            {
                var currentCoordinator = offsetCoordinatorMap.GetOrCreate(consumerGroup, () => - 1);
                if (currentCoordinator == -1)
                {
                    var request = new ConsumerMetadataRequest {
                        ConsumerGroup = consumerGroup
                    };
                    var response = await connections.Values.First().SendRequestAsync(request, token).ConfigureAwait(false);

                    if (response.Error != ErrorResponseCode.NoError)
                    {
                        throw new InvalidOperationException("Failed to retrieve consumer offsets " + response.Error);
                    }
                    offsetCoordinatorMap[consumerGroup] = response.CoordinatorId;
                }
            }
            return(offsetCoordinatorMap);
        }
コード例 #15
0
        public MList <S> LookupRequest <K, S>(LookupToken token, K key, MList <S> field)
            where K : notnull
        {
            Dictionary <K, MList <S> > dictionary = (Dictionary <K, MList <S> >)lookups.GetOrCreate(token, () => (IEnumerable) new Dictionary <K, MList <S> >());

            return(dictionary.GetOrCreate(key, () => field != null && field.Count == 0 ? field : new MList <S>()));
        }
コード例 #16
0
        public VarietyPairSurrogate(VarietyPair vp)
        {
            Variety1 = vp.Variety1.Name;
            Variety2 = vp.Variety2.Name;
            var wordPairSurrogates = new Dictionary <WordPair, WordPairSurrogate>();

            _wordPairs = vp.WordPairs.Select(wp => wordPairSurrogates.GetOrCreate(wp, () => new WordPairSurrogate(wp))).ToList();
            PhoneticSimilarityScore = vp.PhoneticSimilarityScore;
            LexicalSimilarityScore  = vp.LexicalSimilarityScore;
            DefaultSoundCorrespondenceProbability            = vp.DefaultSoundCorrespondenceProbability;
            _cognateSoundCorrespondenceFrequencyDistribution = new Dictionary <SoundContextSurrogate, Tuple <string[], int>[]>();
            foreach (SoundContext lhs in vp.CognateSoundCorrespondenceFrequencyDistribution.Conditions)
            {
                FrequencyDistribution <Ngram <Segment> > freqDist = vp.CognateSoundCorrespondenceFrequencyDistribution[lhs];
                _cognateSoundCorrespondenceFrequencyDistribution[new SoundContextSurrogate(lhs)] = freqDist.ObservedSamples.Select(ngram => Tuple.Create(ngram.Select(seg => seg.StrRep).ToArray(), freqDist[ngram])).ToArray();
            }
            _cognateSoundCorrespondenceByPosition = new Dictionary <string, List <SoundCorrespondenceSurrogate> >();
            foreach (KeyValuePair <FeatureSymbol, SoundCorrespondenceCollection> kvp in vp.CognateSoundCorrespondencesByPosition)
            {
                string pos;
                if (kvp.Key == CogFeatureSystem.Onset)
                {
                    pos = "onset";
                }
                else if (kvp.Key == CogFeatureSystem.Nucleus)
                {
                    pos = "nucleus";
                }
                else
                {
                    pos = "coda";
                }
                _cognateSoundCorrespondenceByPosition[pos] = kvp.Value.Select(corr => new SoundCorrespondenceSurrogate(wordPairSurrogates, corr)).ToList();
            }
        }
コード例 #17
0
 public void AccumulateCollectionElement <T>(string key, T collectionValue)
 {
     m_values
     .GetOrCreate(key, () => new List <T>().CastTo <object>())
     .CastTo <List <T> >()
     .Add(collectionValue);
 }
コード例 #18
0
        /// <summary>
        ///     Adds an order for the given contract and market side with the given properties
        /// </summary>
        /// <returns>The added order</returns>
        public IOrder AddOrder(long orderID,
                               Contract contract,
                               OrderType orderType,
                               MarketSide marketSide,
                               decimal price,
                               decimal quantity,
                               string clOrdID,
                               TradingAccount account)
        {
            var order = new Order(orderID,
                                  orderType,
                                  contract,
                                  marketSide,
                                  price,
                                  quantity,
                                  clOrdID,
                                  account);

            var stack = _market.GetOrCreate(
                contract,
                () =>
            {
                var os            = OrderStackFactory.CreateStandardSortedStack(_orderMatcher);
                os.OrdersMatched += OnOrdersMatched;
                return(os);
            });

            stack.AddOrder(order);
            return(order);
        }
コード例 #19
0
    private void UpdateSurfacesCache(GameObject prefab, List <DrawSurfaceTask> tasks, Dictionary <VtsMesh, List <Part> > partsCache)
    {
        // organize tasks by meshes
        Dictionary <VtsMesh, List <DrawSurfaceTask> > tasksByMesh = new Dictionary <VtsMesh, List <DrawSurfaceTask> >();

        foreach (var t in tasks)
        {
            List <DrawSurfaceTask> ts = tasksByMesh.GetOrCreate(t.mesh as VtsMesh);
            ts.Add(t);
        }

        // remove obsolete cache entries
        {
            tmpKeys.UnionWith(partsCache.Keys);
            tmpKeys.ExceptWith(tasksByMesh.Keys);
            foreach (var k in tmpKeys)
            {
                foreach (var j in partsCache[k])
                {
                    Destroy(j.go);
                }
                partsCache.Remove(k);
            }
            tmpKeys.Clear();
        }

        // update remaining cache entries
        foreach (var k in tasksByMesh)
        {
            List <DrawSurfaceTask> ts = k.Value;
            List <Part>            ps = partsCache.GetOrCreate(k.Key);

            // update current objects
            int updatable = ts.Count < ps.Count ? ts.Count : ps.Count;
            for (int i = 0; i < updatable; i++)
            {
                UpdatePart(ps[i], ts[i]);
            }

            // update the rest of the cache
            int changeCount = ts.Count - ps.Count;
            while (changeCount > 0)
            {
                // inflate
                ps.Add(InitPart(prefab, ts[updatable++]));
                changeCount--;
            }
            if (changeCount < 0)
            {
                // deflate
                foreach (var p in ps.GetRange(updatable, -changeCount))
                {
                    Destroy(p.go);
                }
                ps.RemoveRange(updatable, -changeCount);
            }
            Debug.Assert(ts.Count == ps.Count);
        }
    }
コード例 #20
0
 public static T[] GetEmpty <T>()
 {
     lock (_cachedEmptyArrays)
     {
         var array = _cachedEmptyArrays.GetOrCreate(typeof(T), _ => new T[0]);
         return((T[])array);
     }
 }
コード例 #21
0
 public static NationalCustomizationDatabase GetDatabase(IRepository repository, string nationKey)
 {
     return(s_databases.GetOrCreate(repository,
                                    () => new Dictionary <string, NationalCustomizationDatabase>())
            .GetOrCreate(nationKey,
                         () => new NationalCustomizationDatabase(
                             repository.CustomizationDatabase.Query("customization[@nation='{0}']", nationKey))));
 }
コード例 #22
0
        public void GetOrCreate_NoItemExists_ItIsCreated()
        {
            var dict     = new Dictionary <int, MySampleValue>();
            var theValue = dict.GetOrCreate(100);

            dict.Should().HaveCount(1);
            dict.Should().Contain(100, theValue);
        }
コード例 #23
0
 /// <summary>
 /// Registers the specified wrapper.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="wrapper">The wrapper.</param>
 internal static void Register <T>(SandboxWrapper <T> wrapper)
 {
     if (wrapper != null)
     {
         var container = wrappers.GetOrCreate(typeof(T), new Dictionary <Guid, SandboxWrapper>());
         container.Merge(wrapper.Key, wrapper);
     }
 }
コード例 #24
0
        public void SetValue(string domain, string key, double value)
        {
            var domainStorage = _storage.GetOrCreate(domain, () => new Dictionary <string, double>());

            domainStorage[key] = value;

            this.RaiseDomainChanged(domain);
        }
コード例 #25
0
    public void Create_item_if_none_exists()
    {
        var dict     = new Dictionary <int, MySampleValue>();
        var theValue = dict.GetOrCreate(100);

        dict.Should().HaveCount(1);
        dict.Should().Contain(100, theValue);
    }
コード例 #26
0
        private void Train(WordPartOfSpeech item)
        {
            WordStatistics.GetOrCreate(item.Word).GetOrCreate(item.PartOfSpeech);
            WordStatistics[item.Word][item.PartOfSpeech]++;

            PartOfSpeechStatistics.GetOrCreate(item.PartOfSpeech);
            PartOfSpeechStatistics[item.PartOfSpeech]++;
        }
コード例 #27
0
ファイル: LightDBMgr.cs プロジェクト: NecroSharper/WCell
        static void AddMapping(LightDBDefinitionSet defs, TableDefinition[] defaultTables, SimpleFlatFieldDefinition fieldDef,
                               Dictionary <string, List <SimpleDataColumn> > mappedFields, IFlatDataFieldAccessor accessor, MemberInfo member)
        {
            var column = fieldDef.Column;

            var    tables = defs.EnsureTables(fieldDef.Table, defaultTables);
            object defaultValue;

            if (!String.IsNullOrEmpty(fieldDef.DefaultStringValue))
            {
                defaultValue = StringParser.Parse(fieldDef.DefaultStringValue, member.GetVariableType());
            }
            else
            {
                if (String.IsNullOrEmpty(column))
                {
                    return;
                }
                defaultValue = null;
            }

            foreach (var table in tables)
            {
                var dataHolders = defs.m_tableDataHolderMap.GetOrCreate(table);
                if (!dataHolders.Contains(accessor.DataHolderDefinition))
                {
                    dataHolders.Add(accessor.DataHolderDefinition);
                }

                var mappedFieldMap = mappedFields.GetOrCreate(table.Name);

                SimpleDataColumn dataColumn;
                var dbAttrs = member.GetCustomAttributes <DBAttribute>();
                var attr    = dbAttrs.Where(attribute => attribute is PersistentAttribute).FirstOrDefault() as PersistentAttribute;

                if (String.IsNullOrEmpty(column))
                {
                    // use default value
                    mappedFieldMap.Add(dataColumn = new SimpleDataColumn(fieldDef.Name, defaultValue));
                }
                else
                {
                    dataColumn = mappedFieldMap.Find((cmpField) => cmpField.ColumnName == column);
                    if (dataColumn == null)
                    {
                        var type = member.GetActualType();
                        if (attr != null)
                        {
                            type = attr.ReadType ?? type;
                        }
                        var reader = Converters.GetReader(type);
                        mappedFieldMap.Add(dataColumn = new SimpleDataColumn(column, reader));
                    }
                }

                dataColumn.FieldList.Add(accessor);
            }
        }
コード例 #28
0
 static Func <object, object?>[] ModifiableFieldGetters(Type type)
 {
     lock (getterCache)
         return(getterCache.GetOrCreate(type, () =>
         {
             FieldInfo[] aux = Reflector.InstanceFieldsInOrder(type);
             return aux.Where(fi => Reflector.IsModifiableIdentifiableOrLite(fi.FieldType) && !IsIgnored(fi))
             .Select(fi => ReflectionTools.CreateGetterUntyped(type, fi) !).ToArray();
         }));
コード例 #29
0
        public static bool IsCompatibleWith(Attribute a, AttributeTargets targets)
        {
            using (HeavyProfiler.LogNoStackTrace("IsCompatibleWith"))
            {
                var au = AttributeUssageCache.GetOrCreate(a.GetType(), t => t.GetCustomAttribute <AttributeUsageAttribute>());

                return(au != null && (au.ValidOn & targets) != 0);
            }
        }
コード例 #30
0
 public ImageSource GetSkillIcon(string icon)
 {
     if (icon == null)
     {
         return(null);
     }
     return(_skillIcons.GetOrCreate(icon,
                                    () => PackageImage.Load(_paths.GuiPackageFile, "gui/maps/icons/tankmen/skills/big/" + icon)));
 }
コード例 #31
0
        public static DataHolderTableMapping[] CreateDataHolderTableMappings(
            Dictionary<TableDefinition, List<DataHolderDefinition>> tableDataHolderMap,
            DataHolderDefinition[] dataHolderDefinitions
            )
        {
            // find exact mappings and split them up into as small parts as possible
            // this way we will only read the data from tables that is actually
            // mapped to DataHolders and we will read every cell only once

            var tablesByHolder = new Dictionary<DataHolderDefinition, List<TableDefinition>>();
            foreach (var pair in tableDataHolderMap)
            {
                if (pair.Value == null)
                {
                    log.Warn("Table-definition \"{0}\" has no used columns (and can possibly be removed from the config).");
                }
                else
                {
                    pair.Key.DataHolderDefinitions = pair.Value.ToArray();
                    foreach (var dataHolder in pair.Key.DataHolderDefinitions)
                    {
                        tablesByHolder.GetOrCreate(dataHolder).Add(pair.Key);
                    }
                }
            }

            var mappings = new List<DataHolderTableMapping>();
            var allDefs = new HashSet<DataHolderDefinition>(tablesByHolder.Keys.ToArray());

            var dataHolders = new HashSet<DataHolderDefinition>();
            var tables = new HashSet<TableDefinition>();
            foreach (var holder in tablesByHolder.Keys)
            {
                if (AddTables(allDefs, holder, tablesByHolder, dataHolders, tables))
                {
                    var mapping = new DataHolderTableMapping(dataHolders.ToArray(), tables.ToArray());
                    mappings.Add(mapping);
                    dataHolders.Clear();
                    tables.Clear();
                }
            }

            foreach (var table in tableDataHolderMap.Keys)
            {
                foreach (var field in table.ColumnDefinitions)
                {
                    if (field is IDataFieldBase)
                    {
                        var holderDef = ((IDataFieldBase)field).DataHolderDefinition;
                        if (!dataHolders.Contains(holderDef))
                        {
                            var mapping = mappings.Find(map => map.TableDefinitions.Contains(table));
                            var tableHolders = mapping.DataHolderDefinitions;
                            mapping.DataHolderDefinitions = new DataHolderDefinition[tableHolders.Length + 1];
                            Array.Copy(tableHolders, mapping.TableDefinitions, tableHolders.Length);
                            mapping.DataHolderDefinitions[tableHolders.Length] = holderDef;
                        }
                    }
                }
            }

            return mappings.ToArray();
        }
コード例 #32
0
ファイル: LightDBMgr.cs プロジェクト: remixod/netServer
		static void AddMapping(LightDBDefinitionSet defs, TableDefinition[] defaultTables, SimpleFlatFieldDefinition fieldDef,
			Dictionary<string, List<SimpleDataColumn>> mappedFields, IFlatDataFieldAccessor accessor, MemberInfo member)
		{
			var column = fieldDef.Column;

			var tables = defs.EnsureTables(fieldDef.Table, defaultTables);
			object defaultValue;
			if (!String.IsNullOrEmpty(fieldDef.DefaultStringValue))
			{
				defaultValue = StringParser.Parse(fieldDef.DefaultStringValue, member.GetVariableType());
			}
			else
			{
				if (String.IsNullOrEmpty(column))
				{
					return;
				}
				defaultValue = null;
			}

			foreach (var table in tables)
			{
				var dataHolders = defs.m_tableDataHolderMap.GetOrCreate(table);
				if (!dataHolders.Contains(accessor.DataHolderDefinition))
				{
					dataHolders.Add(accessor.DataHolderDefinition);
				}

				var mappedFieldMap = mappedFields.GetOrCreate(table.Name);

				SimpleDataColumn dataColumn;
                var dbAttrs = member.GetCustomAttributes<DBAttribute>();
                var attr = dbAttrs.Where(attribute => attribute is PersistentAttribute).FirstOrDefault() as PersistentAttribute;

				if (String.IsNullOrEmpty(column))
				{
					// use default value
					mappedFieldMap.Add(dataColumn = new SimpleDataColumn(fieldDef.Name, defaultValue));
				}
				else
				{
					dataColumn = mappedFieldMap.Find((cmpField) => cmpField.ColumnName == column);
					if (dataColumn == null)
					{
                        var type = member.GetActualType();
                        if (attr != null)
                            type = attr.ReadType ?? type;
                        var reader = Converters.GetReader(type);
                        mappedFieldMap.Add(dataColumn = new SimpleDataColumn(column, reader));
					}
				}

				dataColumn.FieldList.Add(accessor);
			}
		}
コード例 #33
0
ファイル: QuestMgr.cs プロジェクト: MeaNone/WCell
		/// <summary>
		/// Creates the graph of all quests and their relations
		/// </summary>
		private static void CreateQuestRelationGraph()
		{
			var groups = new Dictionary<int, List<uint>>();
			foreach (var quest in Templates)
			{
				if (quest != null)
				{
					if (quest.Id == 10068)
					{
						quest.ToString();
					}
					if (quest.ExclusiveGroup != 0)
					{
						groups.GetOrCreate(quest.ExclusiveGroup).AddUnique(quest.Id);
					}
					else if (quest.NextQuestId != 0)
					{
						var nextQuest = GetTemplate((uint)Math.Abs(quest.NextQuestId));
						if (nextQuest == null)
						{
							ContentMgr.OnInvalidDBData("NextQuestId {0} is invalid in: {1}", quest.NextQuestId, quest);
						}
						else
						{
							if (quest.NextQuestId > 0)
							{
								nextQuest.ReqAllFinishedQuests.AddUnique(quest.Id);
							}
							else
							{
								nextQuest.ReqAllActiveQuests.AddUnique(quest.Id);
							}
						}
					}
					if (quest.PreviousQuestId != 0)
					{
						//var prevQuest = GetTemplate((uint)Math.Abs(quest.PreviousQuestId));
						//if (prevQuest == null)
						//{
						//    ContentHandler.OnInvalidDBData("PreviousQuestId {0} is invalid in: {1}", quest.PreviousQuestId, quest);
						//}
						//else
						if (quest.PreviousQuestId > 0)
						{
							quest.ReqAllFinishedQuests.AddUnique((uint)quest.PreviousQuestId);
						}
						else
						{
							quest.ReqAllActiveQuests.AddUnique((uint)-quest.PreviousQuestId);
						}
					}
					if (quest.FollowupQuestId != 0)
					{
						// follow up quest requires this one to be finished before it can be taken
						var followupQuest = GetTemplate(quest.FollowupQuestId);
						if (followupQuest != null)
						{
							followupQuest.ReqAllFinishedQuests.AddUnique(quest.Id);
						}
					}
				}
			}

			foreach (var group in groups)
			{
				foreach (var qid in group.Value)
				{
					var quest = GetTemplate(qid);
					foreach (var qid2 in group.Value)
					{
						if (qid2 != qid)
						{
							if (group.Key > 0)
							{
								quest.ReqUndoneQuests.AddUnique(qid2);
							}
						}
					}

					if (quest.NextQuestId != 0)
					{
						var nextQuest = GetTemplate((uint)Math.Abs(quest.NextQuestId));
						if (nextQuest == null)
						{
							ContentMgr.OnInvalidDBData("NextQuestId {0} is invalid in: {1}", quest.NextQuestId, quest);
						}
						else
						{
							if (group.Key > 0)
							{
								nextQuest.ReqAllFinishedQuests.AddUnique(quest.Id);
							}
							else
							{
								nextQuest.ReqAnyFinishedQuests.AddUnique(quest.Id);
							}
						}
					}
				}
			}
		}
コード例 #34
0
        private TypeDefinition CreateProxy(ProxyBuilder proxyBuilder,
            Action<TypeCodeGenInfo, TypeDefinition> onTypeGenerated,
            TypeCodeGenInfo typeInfo,
            Dictionary<TypeCodeGenInfo, TypeDefinition> generatedTypeDict)
        {
            var targetType = typeInfo.TransformedType;
            var name = targetType.Name;

            TypeDefinition baseTypeDef = null;
            var tt = typeInfo.TransformedType;
            var rt = typeInfo.TransformedType as ResourceType;
            if (rt != null && rt.UriBaseType != null && rt.UriBaseType != rt)
            {
                var baseTypeInfo = this.clientTypeInfoDict[tt.BaseType];
                baseTypeDef = generatedTypeDict.GetOrCreate(baseTypeInfo,
                    () =>
                        CreateProxy(proxyBuilder,
                            onTypeGenerated,
                            baseTypeInfo,
                            generatedTypeDict));
            }
            var proxyType = proxyBuilder.CreateProxyType(name, typeInfo.InterfaceType.WrapAsEnumerable(), baseTypeDef);

            if (onTypeGenerated != null)
                onTypeGenerated(typeInfo, proxyType);

            return proxyType;
        }
コード例 #35
0
        private void CreateProxies(
            ProxyBuilder proxyBuilder,
            Action<TypeCodeGenInfo, TypeDefinition> onTypeGenerated,
            Func<TypeCodeGenInfo, bool> typeIsGeneratedPredicate = null)
        {
            typeIsGeneratedPredicate = typeIsGeneratedPredicate ?? (x => true);
            var generatedTypeDict = new Dictionary<TypeCodeGenInfo, TypeDefinition>();

            foreach (var typeInfo in this.clientTypeInfoDict.Values.Where(typeIsGeneratedPredicate))
            {
                generatedTypeDict.GetOrCreate(typeInfo,
                    () =>
                        CreateProxy(proxyBuilder, onTypeGenerated, typeInfo, generatedTypeDict));
            }
        }
コード例 #36
0
ファイル: AdHoc.cs プロジェクト: xeno-by/libptx
        public static Module matmul()
        {
            Type u16 = new Type { Name = TypeName.U16 }, u32 = new Type { Name = TypeName.U32 }, u64 = new Type { Name = TypeName.U64 };
            Type f32 = new Type { Name = TypeName.F32 }, f64 = new Type { Name = TypeName.F64 }, pred = new Type { Name = TypeName.Pred };

            var regs = new Dictionary<String, Reg>();
            Func<String, Reg> reg_u32 = name => new Reg{Name = name, Type = u32};
            Func<String, Reg> reg_f32 = name => new Reg{Name = name, Type = f32};
            Func<int, Reg> rh = i => regs.GetOrCreate(String.Format("%rh{0}", i), name => new Reg{Name = name, Type = u16});
            Func<int, Reg> r = i => regs.GetOrCreate(String.Format("%r{0}", i), name => new Reg{Name = name, Type = u32});
            Func<int, Reg> rd = i => regs.GetOrCreate(String.Format("%rd{0}", i), name => new Reg{Name = name, Type = u64});
            Func<int, Reg> f = i => regs.GetOrCreate(String.Format("%f{0}", i), name => new Reg{Name = name, Type = f32});
            Func<int, Reg> fd = i => regs.GetOrCreate(String.Format("%fd{0}", i), name => new Reg{Name = name, Type = f64});
            Func<int, Reg> p = i => regs.GetOrCreate(String.Format("%p{0}", i), name => new Reg{Name = name, Type = pred});

            var module = new Module(SoftwareIsa.PTX_14, HardwareIsa.SM_13);
            Func<String, Var> param_align4_b8_12 = name => new Var{Name = name, Space = space.param, Alignment = 4, Type = new Type{Name = TypeName.B8, Dims = new []{12}}};
            Var a = param_align4_b8_12("A"), b = param_align4_b8_12("B"), c = param_align4_b8_12("C");
            var kernel = module.AddEntry("MatMulKernel", a, b, c);
            var ptx = kernel.Stmts;

            Func<String, Label> label = name => new Label{Name = name};
            Label loop_body = label("$LoopBody"), after_loop = label("$AfterLoop"), exit = label("$Exit");
            Reg a_width = reg_u32("a_width"), a_height = reg_u32("a_height"), a_raw = reg_u32("a_raw");
            Reg b_width = reg_u32("b_width"), b_height = reg_u32("b_height"), b_raw = reg_u32("b_raw");
            Reg c_width = reg_u32("c_width"), c_height = reg_u32("c_height"), c_raw = reg_u32("c_raw");
            Reg row = reg_u32("row"), col = reg_u32("col"), cvalue = reg_f32("cvalue"), dim = reg_u32("dim");
            Reg a_offset = reg_u32("a_offset"), a_offset_lo = reg_u32("a_offset_lo"), a_offset_stride = reg_u32("a_offset_stride"), a_offset_hi = reg_u32("a_offset_hi");
            Reg b_offset = reg_u32("b_offset"), b_offset_lo = reg_u32("b_offset_lo"), b_offset_stride = reg_u32("b_offset_stride"), b_offset_hi = reg_u32("b_offset_hi");

            ptx.Add(new Comment{Text = Environment.NewLine});
            ptx.Add(new Comment{Text = "int row = blockIdx.y * blockDim.y + threadIdx.y;"});
            ptx.Add(new Comment{Text = "int col = blockIdx.x * blockDim.x + threadIdx.x;"});
            ptx.Add(new mov{type = u16, d = rh(1), a = new ctaid().mod(Mod.X)});
            ptx.Add(new mov{type = u16, d = rh(2), a = new ntid().mod(Mod.X)});
            ptx.Add(new mul{type = u16, mode = mulm.wide, d = r(1), a = rh(1), b = rh(2)});
            ptx.Add(new mov{type = u16, d = rh(3), a = new ctaid().mod(Mod.Y)});
            ptx.Add(new mov{type = u16, d = rh(4), a = new ntid().mod(Mod.Y)});
            ptx.Add(new mul{type = u16, mode = mulm.wide, d = r(2), a = rh(3), b = rh(4)});
            ptx.Add(new cvt{dtype = u32, atype = u16, d = r(3), a = new tid().mod(Mod.X)});
            ptx.Add(new add{type = u32, d = col, a = r(3), b = r(1)});
            ptx.Add(new cvt{dtype = u32, atype = u16, d = r(5), a = new tid().mod(Mod.Y)});
            ptx.Add(new add{type = u32, d = row, a = r(5), b = r(2)});

            ptx.Add(new Comment{Text = Environment.NewLine});
            ptx.Add(new Comment{Text = "if (A.height <= row || B.width <= col) return;"});
            ptx.Add(new ld{ss = space.param, type = u32, d = b_width, a = b + 0});
            ptx.Add(new ld{ss = space.param, type = u32, d = a_height, a = a + 4});
            ptx.Add(new setp{cmpop = cmp.le, type = u32, p = p(6), a = a_height, b = row});
            ptx.Add(new setp{cmpop = cmp.le, type = u32, p = p(7), a = b_width, b = col});
            ptx.Add(new or{type = pred, d = p(1), a = p(6), b = p(7)});
            ptx.Add(new bra{Guard = p(1), tgt = exit});

            ptx.Add(new Comment{Text = Environment.NewLine});
            ptx.Add(new Comment{Text = "float Cvalue = 0;"});
            ptx.Add(new mov{type = f32, d = cvalue, a = (Const)0f});

            ptx.Add(new Comment{Text = Environment.NewLine});
            ptx.Add(new Comment{Text = "for (int dim = 0; dim < A.width; ++dim)"});
            ptx.Add(new ld{ss = space.param, type = u32, d = a_width, a = a + 0});
            ptx.Add(new mov{type = u32, d = dim, a = (Const)0});
            ptx.Add(new setp{cmpop = cmp.le, type = u32, p = new Modded{Mod = Mod.Couple, Embedded = {p(2), p(8)}}, a = a_width, b = dim});
            ptx.Add(new bra{Guard = p(8).mod(Mod.Not), tgt = after_loop});

            ptx.Add(new Comment{Text = Environment.NewLine});
            ptx.Add(new Comment{Text = "Cvalue += A.elements[row * A.width + dim] * B.elements[dim * B.width + col];"});
            ptx.Add(new ld{ss = space.param, type = u32, d = a_raw, a = a + 8});
            ptx.Add(new mul{mode = mulm.lo, type = u32, d = r(18), a = a_width, b = row});
            ptx.Add(new mul{mode = mulm.lo, type = u32, d = a_offset_lo, a = r(18), b = (Const)4});
            ptx.Add(new add{type = u32, d = a_offset, a = a_offset_lo, b = a_raw});
            ptx.Add(new add{type = u32, d = r(21), a = r(18), b = a_width});
            ptx.Add(new mul{mode = mulm.lo, type = u32, d = r(25), a = r(21), b = (Const)4});
            ptx.Add(new add{type = u32, d = a_offset_hi, a = r(25), b = a_raw});
            ptx.Add(new ld{ss = space.param, type = u32, d = b_raw, a = b + 8});
            ptx.Add(new mul{mode = mulm.lo, type = u32, d = b_offset_lo, a = col, b = (Const)4});
            ptx.Add(new add{type = u32, d = b_offset, a = b_offset_lo, b = b_raw});
            ptx.Add(new mul{mode = mulm.lo, type = u32, d = b_offset_stride, a = b_width, b = (Const)4});

            ptx.Add(new Comment{Text = Environment.NewLine});
            ptx.Add(new Comment{Text = "Cvalue += A.elements[row * A.width + dim] * B.elements[dim * B.width + col];"});
            ptx.Add(loop_body);
            ptx.Add(new ld{ss = space.global, type = f32, d = f(2), a = a_offset});
            ptx.Add(new ld{ss = space.global, type = f32, d = f(3), a = b_offset});
            ptx.Add(new mad{type = f32, d = cvalue, a = f(3), b = f(2), c = cvalue});
            ptx.Add(new add{type = u32, d = a_offset, a = a_offset, b = (Const)4});
            ptx.Add(new add{type = u32, d = b_offset, a = b_offset, b = b_offset_stride});
            ptx.Add(new setp{cmpop = cmp.ne, type = u32, p = p(3), a = a_offset, b = a_offset_hi});
            ptx.Add(new bra{Guard = p(3), tgt = loop_body});
            ptx.Add(new bra{uni = true, tgt = after_loop});

            ptx.Add(new Comment{Text = Environment.NewLine});
            ptx.Add(new Comment{Text = "C.elements[row * C.width + col] = Cvalue;"});
            ptx.Add(after_loop);
            ptx.Add(new ld{ss = space.param, type = u32, d = c_raw, a = c + 8});
            ptx.Add(new ld{ss = space.param, type = u32, d = c_width, a = c + 0});
            ptx.Add(new mul{mode = mulm.lo, type = u32, d = r(32), a = c_width, b = row});
            ptx.Add(new add{type = u32, d = r(33), a = col, b = r(32)});
            ptx.Add(new mul{mode = mulm.lo, type = u32, d = r(34), a = r(33), b = (Const)4});
            ptx.Add(new add{type = u32, d = r(35), a = c_raw, b = r(34)});
            ptx.Add(new st{ss = space.global, type = f32, a = r(35), b = cvalue});

            ptx.Add(new Comment{Text = Environment.NewLine});
            ptx.Add(exit);
            ptx.Add(new exit());

            return module;
        }
コード例 #37
0
 public void SpecifiedValueIsIgnoredStoredWhenKeyIsPresent()
 {
     var dict = new Dictionary<string, string>();
     dict["foo"] = "bar";
     Assert.AreEqual("bar", dict.GetOrCreate("foo", "ignored"));
 }
コード例 #38
0
ファイル: LightDBMgr.cs プロジェクト: pallmall/WCell
		static void AddMapping(LightDBDefinitionSet defs, TableDefinition[] defaultTables, SimpleFlatFieldDefinition fieldDef,
			Dictionary<string, List<SimpleDataColumn>> mappedFields, IFlatDataFieldAccessor accessor, MemberInfo member)
		{
			var column = fieldDef.Column;

			var tables = defs.EnsureTables(fieldDef.Table, defaultTables);
			object defaultValue;
			if (!String.IsNullOrEmpty(fieldDef.DefaultStringValue))
			{
				defaultValue = Utility.Parse(fieldDef.DefaultStringValue, member.GetVariableType());
			}
			else
			{
				if (String.IsNullOrEmpty(column))
				{
					return;
				}
				defaultValue = null;
			}

			if (accessor.DataHolderDefinition.Type.Name.EndsWith("TrainerEntry"))
			{
				defs.ToString();
			}

			foreach (var table in tables)
			{
				var dataHolders = defs.m_tableDataHolderMap.GetOrCreate(table);
				if (!dataHolders.Contains(accessor.DataHolderDefinition))
				{
					dataHolders.Add(accessor.DataHolderDefinition);
				}

				var mappedFieldMap = mappedFields.GetOrCreate(table.Name);

				SimpleDataColumn dataColumn;

				if (String.IsNullOrEmpty(column))
				{
					// use default value
					mappedFieldMap.Add(dataColumn = new SimpleDataColumn(fieldDef.Name, defaultValue));
				}
				else
				{
					dataColumn = mappedFieldMap.Find((cmpField) => cmpField.ColumnName == column);
					if (dataColumn == null)
					{
						mappedFieldMap.Add(dataColumn = new SimpleDataColumn(column, Converters.GetReader(member.GetActualType())));
					}
				}

				dataColumn.FieldList.Add(accessor);
			}
		}
コード例 #39
0
 public void WithExistingKeyValueIsReturnedAndDelegateNotCalled()
 {
     var dict = new Dictionary<string, string>();
     dict["foo"] = "bar";
     Assert.AreEqual("bar", dict.GetOrCreate("foo", () => { throw new Exception(); }));
 }
コード例 #40
0
 public void MissingValueIsCreatedAndStoredWithConstructorConstraint()
 {
     var dict = new Dictionary<string, List<int>>();
     var list = dict.GetOrCreate("foo");
     Assert.AreSame(list, dict["foo"]);
 }
コード例 #41
0
 public void ExistingValueIsReturnedWithConstructorConstraint()
 {
     var dict = new Dictionary<string, int>();
     dict["foo"] = 5000;
     Assert.AreEqual(5000, dict.GetOrCreate("foo"));
 }
コード例 #42
0
ファイル: QuestMgr.cs プロジェクト: pallmall/WCell
		private static void CreateGraph()
		{
			var groups = new Dictionary<int, List<uint>>();
			foreach (var quest in Templates)
			{
				if (quest != null)
				{
					if (quest.ExclusiveGroup != 0)
					{
						groups.GetOrCreate(quest.ExclusiveGroup).Add(quest.Id);
					}
					else if (quest.NextQuestId != 0)
					{
						var nextQuest = GetTemplate((uint)Math.Abs(quest.NextQuestId));
						if (nextQuest == null)
						{
							ContentHandler.OnInvalidDBData("NextQuestId {0} is invalid in: {1}", quest.NextQuestId, quest);
						}
						else
						{
							if (quest.NextQuestId > 0)
							{
								nextQuest.ReqAllFinishedQuests.Add(quest.Id);
							}
							else
							{
								nextQuest.ReqAllActiveQuests.Add(quest.Id);
							}
						}
					}
					if (quest.PreviousQuestId != 0)
					{
						//var prevQuest = GetTemplate((uint)Math.Abs(quest.PreviousQuestId));
						//if (prevQuest == null)
						//{
						//    ContentHandler.OnInvalidDBData("PreviousQuestId {0} is invalid in: {1}", quest.PreviousQuestId, quest);
						//}
						//else
						if (quest.PreviousQuestId > 0)
						{
							quest.ReqAllFinishedQuests.Add((uint)quest.PreviousQuestId);
						}
						else
						{
							quest.ReqAllActiveQuests.Add((uint)-quest.PreviousQuestId);
						}
					}
				}
			}

			foreach (var group in groups)
			{
				foreach (var qid in group.Value)
				{
					var quest = GetTemplate(qid);
					foreach (var qid2 in group.Value)
					{
						if (qid2 != qid)
						{
							if (group.Key > 0)
							{
								quest.ReqUndoneQuests.Add(qid2);
							}
						}
					}

					if (quest.NextQuestId != 0)
					{
						var nextQuest = GetTemplate((uint)Math.Abs(quest.NextQuestId));
						if (nextQuest == null)
						{
							ContentHandler.OnInvalidDBData("NextQuestId {0} is invalid in: {1}", quest.NextQuestId, quest);
						}
						else
						{
							if (group.Key > 0)
							{
								nextQuest.ReqAllFinishedQuests.Add(quest.Id);
							}
							else
							{
								nextQuest.ReqAnyFinishedQuests.Add(quest.Id);
							}
						}
					}
				}
			}
		}
コード例 #43
0
 public void WithMissingKeyDelegateIsCalledAndResultStoredAndReturned()
 {
     var dict = new Dictionary<string, string>();
     Assert.AreEqual("bar", dict.GetOrCreate("foo", () => "bar"));
     Assert.AreEqual("bar", dict["foo"]);            
 }
コード例 #44
0
 public void SpecifiedValueIsReturnedAndStoredWhenKeyIsMissing()
 {
     var dict = new Dictionary<string,string>();
     Assert.AreEqual("bar", dict.GetOrCreate("foo", "bar"));
     Assert.AreEqual("bar", dict["foo"]);
 }