static Dictionary <CultureInfo, TypeNameConflict> TypeConflicts(LocalizedType target, LocalizedType master, List <LocalizedType> support) { if (master.Description == null) { return(null); } if (target != null && target.Description != null) { return(null); } var sentences = new Dictionary <CultureInfo, TypeNameConflict> { { master.Assembly.Culture, new TypeNameConflict { Original = master } } }; sentences.AddRange(from lt in support where lt.Description != null select KVP.Create(lt.Assembly.Culture, new TypeNameConflict { Original = lt })); return(sentences); }
//Method converts last persisted database XML file to a database public DatabaseDictionary <int, Element <int, string> > XMLtoIntDB() { XDocument IntDBXML = XDocument.Load("PersistedIntDB.xml"); var Query = from KV in IntDBXML.Elements("KeyValuePairs").Elements("KeyValuePair").Descendants() select KV; foreach (var KVP in Query) { if (KVP.Name.ToString() == "Key") { DBKey = int.Parse(KVP.FirstAttribute.Value); } if (KVP.Name.ToString() == "Value") { Element <int, string> DBElement = new Element <int, string>(); try { foreach (var Desc in KVP.Descendants()) { if (Desc.Name.ToString() == "Name") { DBElement.NAME = Desc.Value.ToString(); } if (Desc.Name.ToString() == "Description") { DBElement.DESCRIPTION = Desc.Value.ToString(); } if (Desc.Name.ToString() == "Timestamp") { DateTime timestamp = DateTime.Parse(Desc.Value); DBElement.TIMESTAMP = timestamp; } if (Desc.Name.ToString() == "Relations") { if (Desc.Descendants() == null) { DBElement.RELATIONS = null; } List <int> Relations = new List <int>(); foreach (var Relation in Desc.Descendants()) { Relations.Add(int.Parse(Relation.Value)); } DBElement.RELATIONS = Relations; } if (Desc.Name.ToString() == "Data") { DBElement.DATA = Desc.Value; } } } catch (Exception M) { Console.WriteLine(M.Message); } IntKeyDB.AddPair(DBKey, DBElement); } } return(IntKeyDB); }
public static List <LocalizedTypeChanges> GetMergeChanges(LocalizedAssembly target, LocalizedAssembly master, List <LocalizedAssembly> support) { var types = master.Types.Select(kvp => { Type type = kvp.Key; LocalizedType targetType = target.Types.TryGetC(type); LocalizedType masterType = master.Types[type]; List <LocalizedType> supportTypes = support.Select(la => la.Types.TryGetC(type)).NotNull().ToList(); Dictionary <CultureInfo, TypeNameConflict> typeConflicts = TypeConflicts(targetType, masterType, supportTypes); var memberConflicts = (from m in masterType.Members.Keys let con = MemberConflicts(m, targetType, masterType, supportTypes) where con != null select KVP.Create(m, con)).ToDictionary(); if (memberConflicts.IsEmpty() && typeConflicts == null) { return(null); } return(new LocalizedTypeChanges { Type = targetType, TypeConflict = typeConflicts, MemberConflicts = memberConflicts }); }).NotNull().ToList(); return(types); }
public static CaseFlow GetCaseFlow(CaseEntity @case) { var averages = new Dictionary <Lite <IWorkflowNodeEntity>, double?>(); averages.AddRange(@case.Workflow.WorkflowActivities().Select(a => KVP.Create((Lite <IWorkflowNodeEntity>)a.ToLite(), a.AverageDuration()))); averages.AddRange(@case.Workflow.WorkflowEvents().Where(e => e.Type == WorkflowEventType.IntermediateTimer).Select(e => KVP.Create((Lite <IWorkflowNodeEntity>)e.ToLite(), e.AverageDuration()))); var caseActivities = @case.CaseActivities().Select(ca => new CaseActivityStats { CaseActivity = ca.ToLite(), PreviousActivity = ca.Previous, WorkflowActivity = ca.WorkflowActivity.ToLite(), WorkflowActivityType = (WorkflowActivityType?)(ca.WorkflowActivity as WorkflowActivityEntity) !.Type, WorkflowEventType = (WorkflowEventType?)(ca.WorkflowActivity as WorkflowEventEntity) !.Type, SubWorkflow = (ca.WorkflowActivity as WorkflowActivityEntity).Try(wa => wa.SubWorkflow).Try(sw => sw.Workflow.ToLite()), BpmnElementId = ca.WorkflowActivity.BpmnElementId, Notifications = ca.Notifications().Count(), StartDate = ca.StartDate, DoneDate = ca.DoneDate, DoneType = ca.DoneType, DoneBy = ca.DoneBy, Duration = ca.Duration, AverageDuration = averages.TryGetS(ca.WorkflowActivity.ToLite()), EstimatedDuration = ca.WorkflowActivity is WorkflowActivityEntity ? ((WorkflowActivityEntity)ca.WorkflowActivity).EstimatedDuration : ((WorkflowEventEntity)ca.WorkflowActivity).Timer !.Duration == null ? (double?)null : ((WorkflowEventEntity)ca.WorkflowActivity).Timer !.Duration !.ToTimeSpan().TotalMinutes, }).ToDictionary(a => a.CaseActivity);
public static void Main() { var collection = Console.ReadLine().Split().Select(x => Convert.ToDouble(x)).ToList(); var kvps = new List <KVP>(); foreach (var number in collection) { KVP @new; if (!kvps.Any(x => x.K == number)) { @new = new KVP(number, 1); kvps.Add(@new); continue; } @new = kvps.FirstOrDefault(x => x.K == number); if (@new != null) { @new.V++; } } kvps = kvps.Where(x => x.V % 2 != 1).ToList(); foreach (var item in collection) { if (kvps.Any(x => x.K == item)) { Console.Write(item + " "); } } }
private void Resize(int newcapacity) { KVP[] temp = new KVP[newcapacity]; foreach (KVP p in arr) { if (p == null || p.Removed) { continue; } int pos = Math.Abs((int)Hash(p.key) % newcapacity); while (true) { if (temp[pos] == null) { break; } pos++; if (pos >= newcapacity) { pos = 0; } } temp[pos] = p; } arr = temp; }
public void add(string key, V value) { KVP p = Get(key); if (p != null && !p.Removed) { throw new Exception("Duplicate key"); } double LOAD_FACTOR = (double)Size / arr.Length; if (LOAD_FACTOR > 0.7) { Resize(2 * arr.Length); } int pos = Math.Abs((int)Hash(key) % arr.Length); while (true) { if (arr[pos] == null || arr[pos].Removed) { break; } pos++; if (pos >= arr.Length) { pos = 0; } } arr[pos] = new KVP(key, value); Size++; }
private void ParseQuestTexts(KVP entry) { Regex reg = new Regex( @"<div id=""lknlksndgg-(?<type>\w+)"" style=""display: none"">(?<text>.+)\n", RegexOptions.Multiline); MatchCollection matches = reg.Matches(Content); foreach (Match match in matches) { GroupCollection groups = match.Groups; var type = groups["type"].Value ?? string.Empty; var text = groups["text"].Value ?? string.Empty; switch (type.ToLower()) { case "progress": if ((Flag & (uint)SubParsers.RequestItemsText) != 0) WriteLine("UPDATE `quest_template` SET `RequestItemsText` = '{0}' WHERE `entry` = {1};", text.HTMLEscapeSumbols(), entry.Key); break; case "completion": if ((Flag & (uint)SubParsers.OfferRewardText) != 0) WriteLine("UPDATE `quest_template` SET `OfferRewardText` = '{0}' WHERE `entry` = {1};", text.HTMLEscapeSumbols(), entry.Key); break; } } }
static Dictionary <CultureInfo, MemberNameConflict> MemberConflicts(string member, LocalizedType target, LocalizedType master, List <LocalizedType> support) { if (master.Members.TryGetC(member) == null) { return(null); } if (target != null && target.Members.TryGetC(member) != null) { return(null); } var sentences = new Dictionary <CultureInfo, MemberNameConflict> { { master.Assembly.Culture, new MemberNameConflict { Original = master.Members.TryGetC(member) } } }; sentences.AddRange(from lt in support where lt.Members.TryGetC(member).HasText() select KVP.Create(lt.Assembly.Culture, new MemberNameConflict { Original = lt.Members.TryGetC(member) })); return(sentences); }
public AssemblyResultTS Sync(string assembly, string culture, string? @namespace = null) { Assembly ass = AssembliesToLocalize().Where(a => a.GetName().Name == assembly).SingleEx(() => "Assembly {0}".FormatWith(assembly)); CultureInfo targetCulture = CultureInfo.GetCultureInfo(culture); CultureInfo defaultCulture = CultureInfo.GetCultureInfo(ass.GetCustomAttribute <DefaultAssemblyCultureAttribute>().DefaultCulture); var cultures = TranslationLogic.CurrentCultureInfos(defaultCulture); Dictionary <CultureInfo, LocalizedAssembly> reference = (from ci in cultures let la = DescriptionManager.GetLocalizedAssembly(ass, ci) where la != null || ci == defaultCulture || ci == targetCulture select KVP.Create(ci, la ?? LocalizedAssembly.ImportXml(ass, ci, forceCreate: ci == defaultCulture || ci == targetCulture))).ToDictionary(); var master = reference.Extract(defaultCulture); var target = reference.Extract(targetCulture); var changes = TranslationSynchronizer.GetAssemblyChanges(TranslationServer.Translator, target, master, reference.Values.ToList(), null, @namespace, out int totalTypes); return(new AssemblyResultTS { totalTypes = totalTypes, cultures = cultures.Select(c => c.ToCulturesTS()).ToDictionary(a => a.name), types = changes.Types.Select(t => t.Type.Type.ToLocalizableTypeTS().Let(localizedTypes => { localizedTypes.cultures = cultures.ToDictionary(c => c.Name, c => GetLocalizedType(t, c, c.Equals(targetCulture))); return localizedTypes; })).ToDictionary(lt => lt.type), }); }
public List <string> TranslateBatch(List <string> list, string from, string to) { var alreadyTranslated = (from ass in AppDomain.CurrentDomain.GetAssemblies() let daca = ass.GetCustomAttribute <DefaultAssemblyCultureAttribute>() where daca != null && daca.DefaultCulture == @from from trans in GetAllTranslations(ass, @from, to) group trans.Value by trans.Key into g let only = g.Distinct().Only() where only != null select KVP.Create(g.Key, only)) .ToDictionary(); var dic = list.Distinct().ToDictionary(l => l, l => alreadyTranslated.TryGetC(l)); if (dic.Any(kvp => kvp.Value == null)) { var subList = dic.Where(kvp => kvp.Value == null).Select(kvp => kvp.Key).ToList(); var subResult = Inner.TranslateBatch(subList, from, to); dic.SetRange(subList, subResult); } return(list.Select(dic.GetOrThrow).ToList()); }
/// <param name="keySelector">Unique key to retrieve ids</param> /// <param name="isNewPredicate">Optional filter to query only the recently inseted entities</param> public static int BulkInsertQueryIds <T, K>(this IEnumerable <T> entities, Expression <Func <T, K> > keySelector, Expression <Func <T, bool> > isNewPredicate = null, SqlBulkCopyOptions copyOptions = SqlBulkCopyOptions.Default, bool preSaving = false, bool validateFirst = false, int?timeout = null, string message = null) where T : Entity { var t = Schema.Current.Table(typeof(T)); var list = entities.ToList(); if (isNewPredicate == null) { isNewPredicate = GetFilterAutomatic <T>(t); } var rowNum = BulkInsertTable <T>(list, copyOptions, preSaving, validateFirst, false, timeout, message); var dictionary = Database.Query <T>().Where(isNewPredicate).Select(a => KVP.Create(keySelector.Evaluate(a), a.Id)).ToDictionaryEx(); var getKeyFunc = keySelector.Compile(); list.ForEach(e => { e.SetId(dictionary.GetOrThrow(getKeyFunc(e))); }); BulkInsertMLists(list, copyOptions, timeout, message); return(rowNum); }
internal static unsafe void GetCollisionPairs(List <KVP <PhysicsBodyHandle, PhysicsBodyHandle> > pairsList) { pairsList.Clear(); PhysicsBodyHandle *outPBHArr; uint outNumPairs; // WARNING: No longer thread-safe unsafe { char *failReason = stackalloc char[InteropUtils.MAX_INTEROP_FAIL_REASON_STRING_LENGTH + 1]; bool success = NativeMethods.PhysicsManager_GetCollisionPairsArray( (IntPtr)failReason, (IntPtr)(&outPBHArr), (IntPtr)(&outNumPairs) ); if (!success) { throw new NativeOperationFailedException(Marshal.PtrToStringUni((IntPtr)failReason)); } } for (uint i = 0U; i < outNumPairs; ++i) { var newValue = new KVP <PhysicsBodyHandle, PhysicsBodyHandle>( outPBHArr[i << 1], outPBHArr[(i << 1) + 1] ); var inverse = new KVP <PhysicsBodyHandle, PhysicsBodyHandle>( newValue.Value, newValue.Key ); if (!pairsList.Contains(newValue) && !pairsList.Contains(inverse)) { pairsList.Add(newValue); } } }
public static PredictDictionary GetInputsFromRequest(this PredictorPredictContext pctx, PredictRequestTS request) { ParseValues(request, pctx); return(new PredictDictionary(pctx.Predictor, null, null) { MainQueryValues = pctx.Predictor.MainQuery.Columns .Select((col, i) => new { col, request.columns[i].value }) .Where(a => a.col !.Usage == PredictorColumnUsage.Input) .Select(a => KVP.Create(a.col !, a.value)) .ToDictionaryEx(), SubQueries = pctx.Predictor.SubQueries.Select(sq => { var sqt = request.subQueries.Single(a => a.subQuery.Is(sq)); SplitColumns(sq, out var splitKeys, out var values); return new PredictSubQueryDictionary(sq) { SubQueryGroups = sqt.rows.Select(array => KVP.Create( array.Slice(0, splitKeys.Count), values.Select((a, i) => KVP.Create(a, array[splitKeys.Count + i])).ToDictionary() )).ToDictionary(ObjectArrayComparer.Instance) }; }).ToDictionaryEx(a => a.SubQuery) });
protected virtual IEnumerable <KeyValuePair <DiffTable, MListInfo> > GetMListFields(DiffTable table) { return(from relatedTable in InverseGraph.RelatedTo(table) let mListInfo2 = GetMListInfo(relatedTable) where mListInfo2 != null && mListInfo2.BackReferenceColumn.ForeignKey.TargetTable.Equals(table.Name) select KVP.Create(relatedTable, mListInfo2)); }
public static Dictionary <string, TypeInfoTS> GetSymbolContainers(IEnumerable <Type> allTypes) { SymbolLogic.LoadAll(); var result = (from type in allTypes where type.IsStaticClass() && type.HasAttribute <AutoInitAttribute>() select KVP.Create(GetTypeName(type), OnAddTypeExtension(new TypeInfoTS { Kind = KindOfType.SymbolContainer, FullName = type.FullName, Members = type.GetFields(staticFlags) .Select(f => GetSymbolInfo(f)) .Where(s => s.FieldInfo != null && /*Duplicated like in Dynamic*/ s.IdOrNull.HasValue /*Not registered*/) .ToDictionary(s => s.FieldInfo.Name, s => OnAddFieldInfoExtension(new MemberInfoTS { NiceName = s.FieldInfo.NiceName(), Id = s.IdOrNull.Value.Object }, s.FieldInfo)) }, type))) .Where(a => a.Value.Members.Any()) .ToDictionaryEx("symbols"); return(result); }
public int Compare(object x, object y) { KVP kvpX = (KVP)x; KVP kvpY = (KVP)y; return(kvpX.Value.CompareTo(kvpY.Value)); }
static Dictionary <LocalizedInstanceKey, string> FromRoute <T>(PropertyRoute pr) where T : Entity { var selector = pr.GetLambdaExpression <T, string>(safeNullAccess: false); return((from e in Database.Query <T>() select KVP.Create(new LocalizedInstanceKey(pr, e.ToLite(), null), selector.Evaluate(e))).ToDictionary()); }
public void OnAfterDeserialize() { Clear(); #if UNITY_EDITOR if (m_AppendTemporary) { if (m_Elements.Where((kvp) => kvp.Key.Equals(m_TemporaryKVP.Key)).Any()) { Log.Warning <DefaultLogCategory>("Duplicate key added to Dictionary (overriding existing)"); } m_Elements.Add(m_TemporaryKVP); m_TemporaryKVP = default; m_AppendTemporary = false; } #endif for (int i = 0; i < m_Elements.Count; ++i) { this[m_Elements[i].Key] = m_Elements[i].Value; } m_Elements.Clear(); foreach (var kvp in this) { KVP elem = new KVP(); elem.Key = kvp.Key; elem.Value = kvp.Value; m_Elements.Add(elem); } }
public static void LoadOrders() { Dictionary <string, CustomerEntity> customers = new Dictionary <string, CustomerEntity>(); customers.AddRange(Database.Query <CompanyEntity>().Select(c => KVP.Create(c.ContactName, (CustomerEntity)c))); customers.AddRange(Database.Query <PersonEntity>().Select(p => KVP.Create(p.FirstName + " " + p.LastName, (CustomerEntity)p))); var orders = Connector.Override(Northwind.Connector).Using(_ => Database.View <Orders>().Select(o => new OrderEntity { Employee = Lite.Create <EmployeeEntity>(o.EmployeeID !.Value), OrderDate = o.OrderDate !.Value, RequiredDate = o.RequiredDate !.Value, ShippedDate = o.ShippedDate, State = o.ShippedDate.HasValue ? OrderState.Shipped : OrderState.Ordered, ShipVia = Lite.Create <ShipperEntity>(o.ShipVia !.Value), ShipName = o.ShipName, ShipAddress = new AddressEmbedded { Address = o.ShipAddress, City = o.ShipCity, Region = o.ShipRegion, PostalCode = o.ShipPostalCode, Country = o.ShipCountry, }, Freight = o.Freight !.Value, Details = Database.View <OrderDetails>().Where(od => od.OrderID == o.OrderID).Select(od => new OrderDetailEmbedded { Discount = (decimal)od.Discount, Product = Lite.Create <ProductEntity>(od.ProductID), Quantity = od.Quantity, UnitPrice = od.UnitPrice, }).ToMList(), Customer = customers.GetOrThrow(Database.View <Customers>().Where(c => c.CustomerID == o.CustomerID).Select(a => a.ContactName).SingleOrDefaultEx()), IsLegacy = true, }.SetId(o.OrderID)).ToList());
public static Dictionary <string, TypeInfoTS> GetEnums(IEnumerable <Type> allTypes) { var queries = QueryLogic.Queries; var result = (from type in allTypes where type.IsEnum let descOptions = LocalizedAssembly.GetDescriptionOptions(type) where descOptions != DescriptionOptions.None let kind = type.Name.EndsWith("Query") ? KindOfType.Query : type.Name.EndsWith("Message") ? KindOfType.Message : KindOfType.Enum select KVP.Create(GetTypeName(type), OnAddTypeExtension(new TypeInfoTS { Kind = kind, FullName = type.FullName, NiceName = descOptions.HasFlag(DescriptionOptions.Description) ? type.NiceName() : null, Members = type.GetFields(staticFlags) .Where(fi => kind != KindOfType.Query || queries.QueryDefined(fi.GetValue(null))) .ToDictionary(fi => fi.Name, fi => OnAddFieldInfoExtension(new MemberInfoTS { NiceName = fi.NiceName(), IsIgnoredEnum = kind == KindOfType.Enum && fi.HasAttribute <IgnoreAttribute>() }, fi)), }, type))).ToDictionaryEx("enums"); return(result); }
Dictionary <Lite <RoleEntity>, RoleAllowedCache> NewCache() { using (AuthLogic.Disable()) using (new EntityCache(EntityCacheType.ForceNewSealed)) { List <Lite <RoleEntity> > roles = AuthLogic.RolesInOrder().ToList(); var rules = Database.Query <RuleTypeEntity>().ToList(); var errors = GraphExplorer.FullIntegrityCheck(GraphExplorer.FromRoots(rules)); if (errors != null) { throw new IntegrityCheckException(errors); } Dictionary <Lite <RoleEntity>, Dictionary <Type, TypeAllowedAndConditions> > realRules = rules.AgGroupToDictionary(ru => ru.Role, gr => gr .SelectCatch(ru => KVP.Create(TypeLogic.EntityToType.GetOrThrow(ru.Resource), ru.ToTypeAllowedAndConditions())) .ToDictionaryEx()); Dictionary <Lite <RoleEntity>, RoleAllowedCache> newRules = new Dictionary <Lite <RoleEntity>, RoleAllowedCache>(); foreach (var role in roles) { var related = AuthLogic.RelatedTo(role); newRules.Add(role, new RoleAllowedCache(role, merger, related.Select(r => newRules.GetOrThrow(r)).ToList(), realRules.TryGetC(role))); } return(newRules); } }
public static IntervalDictionary <K, VR> Collapse <K, V, VR>(this IEnumerable <IntervalDictionary <K, V> > collection, Func <Interval <K>, IEnumerable <V>, VR> mixer) where K : struct, IComparable <K>, IEquatable <K> { #pragma warning disable CS8629 // Nullable value type may be null. Interval <K>[] keys = collection.SelectMany(a => a).SelectMany(a => a.Key.Elements()).Distinct().OrderBy().BiSelectS((min, max) => new Interval <K>(min.Value, max.Value)).ToArray(); #pragma warning restore CS8629 // Nullable value type may be null. return(new IntervalDictionary <K, VR>(keys.Select(k => KVP.Create(k, mixer(k, collection.Select(intDic => intDic.TryGetValue(k.Min)).Where(vi => vi.HasInterval).Select(vi => vi.Value)))))); }
public string GetStarterClassCode() { StringBuilder sb = new StringBuilder(); var fieldNames = this.Expressions .GroupBy(a => a.Name) .SelectMany(gr => gr.Count() == 1 ? new[] { KVP.Create(gr.SingleEx().Name + "Expression", gr.SingleEx()) } : gr.Select(a => KVP.Create(a.Name + "_" + a.FromType.RemoveChars('<', '>', '.') + "Expression", a)) ).ToDictionaryEx("DynamicExpressions"); var namesToTranslate = this.Expressions.Where(a => a.Translation == DynamicExpressionTranslation.TranslateExpressionName).Select(a => a.Name).Distinct(); if (namesToTranslate.Any()) { sb.AppendLine($"public enum CodeGenExpressionMessage"); sb.AppendLine("{"); foreach (var item in namesToTranslate) { sb.AppendLine(" " + item + ","); } sb.AppendLine("}"); sb.AppendLine(); } sb.AppendLine($"public static class CodeGenExpressionStarter"); sb.AppendLine("{"); foreach (var kvp in fieldNames) { sb.AppendLine($" static Expression<Func<{kvp.Value.FromType}, {kvp.Value.ReturnType}>> {kvp.Key} ="); sb.AppendLine($" e => {kvp.Value.Body};"); sb.AppendLine($" [ExpressionField(\"{kvp.Key}\")]"); sb.AppendLine($" public static {kvp.Value.ReturnType} {kvp.Value.Name}(this {kvp.Value.FromType} e)"); sb.AppendLine($" {{"); sb.AppendLine($" return {kvp.Key}.Evaluate(e);"); sb.AppendLine($" }}"); sb.AppendLine(""); } sb.AppendLine(" public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)"); sb.AppendLine(" {"); foreach (var kvp in fieldNames) { sb.AppendLine($" var ei = dqm.RegisterExpression(({kvp.Value.FromType} e) => e.{kvp.Value.Name}(){GetNiceNameCode(kvp.Value)});"); if (kvp.Value.Format.HasText()) { sb.AppendLine($" ei.ForceFormat = {CSharpRenderer.Value(kvp.Value.Format, typeof(string), new string[0])};"); } if (kvp.Value.Unit.HasText()) { sb.AppendLine($" ei.ForceUnit = {CSharpRenderer.Value(kvp.Value.Unit, typeof(string), new string[0])};"); } } sb.AppendLine(" }"); sb.AppendLine("}"); return(sb.ToString()); }
async public Task <bool> RegisterPlayer() { if (string.IsNullOrWhiteSpace(Email) || string.IsNullOrWhiteSpace(Alias)) { throw new Exception("Please specify an email and alias."); } var email = Email; //We toy with a copy because the two-way binding will cause the TextChanged event to fire var split = email.Split('@'); if (split.Length == 2) { if (split[1].ToLower() == "hbo.com") //GoT character { //Randomize the email (which serves as the primary key) so it doesn't conflict w/ other demo games var rand = Guid.NewGuid().ToString().Substring(0, 7).ToLower(); email = $"{split[0]}-{rand}@{split[1]}"; } } bool isAppropriate = false; var task = new Task(() => { var aliasValid = App.Instance.DataService.IsTextValidAppropriate(Alias.Trim()).Result; var emailValid = App.Instance.DataService.IsTextValidAppropriate(Email.Trim()).Result; isAppropriate = aliasValid && emailValid; }); await task.RunProtected(); if (!task.WasSuccessful()) { return(false); } if (!isAppropriate) { Hud.Instance.ShowToast("Inappropriate content was detected"); return(false); } var player = new Player { Avatar = Avatar, Email = email.Trim(), Alias = Alias.Trim(), InstallId = MobileCenter.GetInstallIdAsync().Result.ToString(), }; var args = new KVP { { "email", player.Email }, { "firstName", player.Alias }, { "avatar", player.Avatar } }; Analytics.TrackEvent("Player registered", args); App.Instance.SetPlayer(player); return(true); }
static Dictionary <LocalizedInstanceKey, string> FromRouteMList <T, M>(PropertyRoute pr) where T : Entity { var mlItemPr = pr.GetMListItemsRoute() !; var mListProperty = mlItemPr.Parent !.GetLambdaExpression <T, MList <M> >(safeNullAccess: false); var selector = pr.GetLambdaExpression <M, string>(safeNullAccess: false, skipBefore: mlItemPr); return((from mle in Database.MListQuery(mListProperty) select KVP.Create(new LocalizedInstanceKey(pr, mle.Parent.ToLite(), mle.RowId), selector.Evaluate(mle.Element))).ToDictionary()); }
public static void Start(SchemaBuilder sb, Func <CultureInfo> defaultCulture) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Include <TranslatedInstanceEntity>() .WithUniqueIndex(ti => new { ti.Culture, ti.PropertyRoute, ti.Instance, ti.RowId }) .WithQuery(() => e => new { Entity = e, e.Id, e.Culture, e.Instance, e.PropertyRoute, e.TranslatedText, e.OriginalText, }); TranslatedInstanceLogic.getDefaultCulture = defaultCulture ?? throw new ArgumentNullException(nameof(defaultCulture)); LocalizationCache = sb.GlobalLazy(() => Database.Query <TranslatedInstanceEntity>() .ToList() .AgGroupToDictionary(a => a.Culture.ToCultureInfo(), gr2 => gr2.GroupBy(a => a.PropertyRoute) .SelectMany(gr => { PropertyRoute pr = gr.Key.ToPropertyRoute(); PropertyRoute?mListRoute = pr.GetMListItemsRoute(); if (mListRoute == null) { return(gr.Select(ti => KVP.Create(new LocalizedInstanceKey(pr, ti.Instance, null), ti))); } Type type = ((FieldMList)Schema.Current.Field(mListRoute.Parent !)).TableMList.PrimaryKey.Type; return(gr.Select(ti => KVP.Create(new LocalizedInstanceKey(pr, ti.Instance, new PrimaryKey((IComparable)ReflectionTools.Parse(ti.RowId !, type) !)), ti))); }).ToDictionary()) , new InvalidateWith(typeof(TranslatedInstanceEntity))); sb.Schema.SchemaCompleted += () => { var s = Schema.Current; var prs = (from t in s.Tables.Keys from pr in PropertyRoute.GenerateRoutes(t) where pr.PropertyRouteType == PropertyRouteType.FieldOrProperty && pr.FieldInfo != null && pr.FieldInfo.FieldType == typeof(string) && s.Settings.FieldAttribute <TranslateFieldAttribute>(pr) != null && s.Settings.FieldAttribute <IgnoreAttribute>(pr) == null select KVP.Create(pr, s.Settings.FieldAttribute <TranslateFieldAttribute>(pr) !.TranslatableRouteType)).ToList(); foreach (var kvp in prs) { AddRoute(kvp.Key, kvp.Value); } }; } }
internal override IEnumerable <KeyValuePair <Table, RelationInfo> > GetTables() { yield return(KVP.Create(ColumnType.ReferenceTable, new RelationInfo { IsNullable = this.ColumnType.Nullable.ToBool(), IsLite = this.IsLite, IsImplementedByAll = true, })); }
internal override IEnumerable <KeyValuePair <Table, RelationInfo> > GetTables() { return(ImplementationColumns.Select(a => KVP.Create(a.Value.ReferenceTable, new RelationInfo { IsLite = IsLite, IsCollection = false, IsNullable = a.Value.Nullable.ToBool() }))); }
internal override IEnumerable <KeyValuePair <Table, RelationInfo> > GetTables() { yield return(KVP.Create(ReferenceTable, new RelationInfo { IsLite = IsLite, IsCollection = false, IsNullable = Nullable.ToBool() })); }
/// <summary> /// Costly /// </summary> public IEnumerable <KeyValuePair <T, E> > InverseRelatedTo(T node) { foreach (var item in adjacency) { if (item.Value.TryGetValue(node, out E edge)) { yield return(KVP.Create(item.Key, edge)); } } }
public override void Parse(KVP entry) { Regex reg = new Regex(@"new Book\({ parent: '.+', pages: \['(?<test>.+)'\]}\)", RegexOptions.Multiline); MatchCollection matches = reg.Matches(Content); foreach (Match match in matches) { GroupCollection groups = match.Groups; var typeStr = groups["test"].Value ?? string.Empty; var pages = typeStr.Split(new[] { @"','" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < pages.Length; ++i) { WriteLine(@"INSERT IGNORE INTO `page_text` VALUES ({0}, '{1}', {2});", entry.Val + i, pages[i].HTMLEscapeSumbols(), i < pages.Length - 1 ? entry.Val + i + 1 : 0); } } }
public abstract void Parse(KVP entry);
public override void Parse(KVP entry) { if ( (Flag & (uint)SubParsers.RequestItemsText) != 0 || (Flag & (uint)SubParsers.OfferRewardText) != 0) ParseQuestTexts(entry); }
public IEnumerable<XElement> Elements(IEnumerable<XElement> elements) { IQueryable<XElement> query = elements.AsQueryable<XElement>(); Expression ex = null, e; string method = "Where"; foreach (XPath_Part part in Parts) { e = null; if (part.ElementAt) { method = "ElementAt"; int i = Convert.ToInt32(part.Value); switch (part.Key) { case "last()": ex = Count.Nodes(query.Expression); // last() - 1 is the last element so it should be last() - (1 + 1) ex = Expression.Subtract(ex, Expression.Constant(i + 1)); break; default: // [1] should be 0 ex = Expression.Constant(i - 1); break; } break; // break out of foreach } FunctionBase f = part.Function; if (null == f) { if (part.KVP) f = new KVP(part); else f = new HasNode(part); // [nodeset] } e = f.GetExpression(pe); if (null == ex) ex = e; else if (AndOr) ex = Expression.AndAlso(ex, e); else ex = Expression.OrElse(ex, e); } MethodCallExpression call; // if method returns a single element if ("ElementAt" == method) { call = Expression.Call( typeof(Queryable), method, // "ElementAt" new Type[] { query.ElementType }, query.Expression, ex ); XElement result = query.Provider.Execute<XElement>(call); return new[] { result }; } else // if method returns an enumerable { call = Expression.Call( typeof(Queryable), method, // "Where" new Type[] { query.ElementType }, query.Expression, Expression.Lambda<Func<XElement, bool>>(ex, new ParameterExpression[] { pe }) ); IQueryable<XElement> results = query.Provider.CreateQuery<XElement>(call); return results; } }