Example #1
1
        /// <summary>
        /// Initialises a new instance of the <see cref="TableInfo"/> class.
        /// </summary>
        /// <param name="columns">The columns that are mapped for the table.</param>
        /// <param name="identifierStrategy">The identifier strategy used by the table.</param>
        /// <param name="name">The name of the table.</param>
        /// <param name="schema">The database schema the table exists within (e.g. 'dbo'); otherwise null.</param>
        /// <exception cref="ArgumentNullException">Thrown if columns or name are null.</exception>
        /// <exception cref="MappingException">Thrown if no there is a problem with the column mappings.</exception>
        public TableInfo(
            IList<ColumnInfo> columns,
            IdentifierStrategy identifierStrategy,
            string name,
            string schema)
        {
            if (columns == null)
            {
                throw new ArgumentNullException("columns");
            }

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            this.columns = new ReadOnlyCollection<ColumnInfo>(columns);
            this.identifierStrategy = identifierStrategy;
            this.name = name;
            this.schema = schema;

            this.identifierColumn = columns.FirstOrDefault(c => c.IsIdentifier);

            this.insertColumnCount = columns.Count(c => c.AllowInsert);
            this.updateColumnCount = columns.Count(c => c.AllowUpdate);

            this.ValidateColumns();
        }
Example #2
0
        public override int Handle(IFrame frame, IList<IFrame> frames)
        {
            if (!CanHandle(frame)) return 0;

            int frameScore = Configuration.NumberOfPins;

            List<int> extraRolls = new List<int>();

            var nextFrame = frames.FirstOrDefault(f => f.Sequence == frame.Sequence + 1);
            while(nextFrame != null && extraRolls.Count < Configuration.NumberOfRollsPerFrame)
            {
                if (IsStrike(nextFrame))
                {
                    extraRolls.Add(Configuration.NumberOfPins);
                    nextFrame = frames.FirstOrDefault(f => f.Sequence == frame.Sequence + 1);
                }
                else
                {
                    extraRolls.Add(
                        nextFrame.Rolls
                            .Where(r => r.Pins.HasValue)
                            .Select(r => r.Pins.Value).ToArray()[extraRolls.Count]
                        );
                }
            }

            return frameScore + extraRolls.Sum();
        }
        public AccountTransactionDocument CreateDocument(Account account, string description, decimal amount, decimal exchangeRate, IList<AccountData> accounts, IList<ForeignCurrency> currencies)
        {
            var result = new AccountTransactionDocument { Name = Name, DocumentTypeId = Id };
            foreach (var accountTransactionType in TransactionTypes)
            {
                var transaction = AccountTransaction.Create(accountTransactionType);
                var amountRate = GetExchangeRate(accountTransactionType.ForeignCurrencyId, currencies);
                amount = amount * amountRate;
                transaction.UpdateAmount(amount, exchangeRate, accounts);
                transaction.UpdateAccount(MasterAccountTypeId, account.Id);
                if (accounts != null && accounts.Count > 0)
                {
                    if (transaction.SourceAccountTypeId != MasterAccountTypeId &&
                        transaction.SourceTransactionValue.AccountId == 0)
                    {
                        var ac = accounts.FirstOrDefault(x => x.AccountTypeId == transaction.SourceAccountTypeId);
                        if (ac != null) transaction.SetSourceAccount(ac.AccountTypeId, ac.AccountId);
                    }

                    if (transaction.TargetAccountTypeId != MasterAccountTypeId &&
                        transaction.TargetTransactionValue.AccountId == 0)
                    {
                        var ac = accounts.FirstOrDefault(x => x.AccountTypeId == transaction.TargetAccountTypeId);
                        if (ac != null) transaction.SetTargetAccount(ac.AccountTypeId, ac.AccountId);
                    }
                }
                if (!string.IsNullOrEmpty(description))
                {
                    transaction.UpdateDescription(description);
                }
                result.AccountTransactions.Add(transaction);
            }
            return result;
        }
Example #4
0
        public object GetArg(IList<string> args)
        {
            if(args.Count == 0)
                throw new Exception("too few arguments");

            var first = args.FirstOrDefault();

            var projectFilename = ZMFile.DefaultFilename;

            if (first.EndsWith(".zm"))
            {
                projectFilename = first;
                args.RemoveAt(0);
            }

            var targets = args.Where(x => !x.StartsWith("{")).ToList();
            var parameterString = args.FirstOrDefault(x => x.StartsWith("{")) ?? string.Empty;
            var parameters = new JObject();

            if(!string.IsNullOrWhiteSpace(parameterString))
                parameters = JObject.Parse(parameterString);

            var result = new RunArg(projectFilename, targets, parameters);
            return result;
        }
        static IList<Edge> ExtractEdges(IList<CodeReference> references, IList<Node> nodes)
        {
            var edges = new List<Edge>();

            var id = 0;
            foreach (var reference in references)
            {
                id += 1;
                var source = nodes.FirstOrDefault(node => node.label == reference.From);
                var target = nodes.FirstOrDefault(node => node.label == reference.To);

                if (source == null || target == null)
                {
                    continue;
                }

                edges.Add(new Edge {
                    id = $"e{id}",
                    source = source.id,
                    target = target.id
                });
            }

            return edges;
        }
Example #6
0
 private RSTrackInfo findTrackContaining(IList<RSTrackInfo> songTracks, string[] preferences)
 {
     for(int i=0;i<preferences.Length;i++)
     {
         RSTrackInfo found = songTracks.FirstOrDefault(t => t.Name.Contains(preferences[i]));
         if (found != null) return found;
     }
     return songTracks.FirstOrDefault();
 }
Example #7
0
        /// <summary>
        /// Combines and matches existing records with the updated records.
        /// </summary>
        /// <param name="updatedRecords">The calculated records with new wins, losses, and ties.</param>
        /// <param name="existingRecords">The existing records that will need to be updated.</param>
        /// <returns>List{UserRecord}. The collection of user records that should be updated or created.</returns>
        public static List<UserRecord> CombineExistingRecordsWithUpdatedRecords(IList<UserRecord> updatedRecords, IList<UserRecord> existingRecords)
        {
            var records = new List<UserRecord>();

            // Iterate through the updated records and checks if the user has a matching record that matches the record type
            foreach (var record in updatedRecords)
            {
                UserRecord recordToUpdate = null;

                if (record.RecordType == RecordType.Lifetime)
                {
                    recordToUpdate = existingRecords.FirstOrDefault(existingRecord => MatchingLifetimeCondition(existingRecord, record));
                }
                else if (record.RecordType == RecordType.Season)
                {
                    recordToUpdate = existingRecords.FirstOrDefault(existingRecord => MatchingSeasonCondition(existingRecord, record));
                }
                else if (record.RecordType == RecordType.SeasonType)
                {
                    recordToUpdate = existingRecords.FirstOrDefault(existingRecord => MatchingSeasonTypeCondition(existingRecord, record));
                }
                else if (record.RecordType == RecordType.Week)
                {
                    recordToUpdate = existingRecords.FirstOrDefault(existingRecord => MatchingWeekCondition(existingRecord, record));
                }

                // Create a new record since the user does not have an existing record for the record type
                if (recordToUpdate == null)
                {
                    recordToUpdate = new UserRecord
                        {
                            Losses = record.Losses,
                            RecordType = record.RecordType,
                            Season = record.Season,
                            SeasonType = record.SeasonType,
                            Ties = record.Ties,
                            UserId = record.UserId,
                            Week = record.Week,
                            Wins = record.Wins
                        };
                }
                // Update the existing record type's wins, losses, and ties.
                else
                {
                    recordToUpdate.Losses = record.Losses;
                    recordToUpdate.Ties = record.Ties;
                    recordToUpdate.Wins = record.Wins;
                }

                records.Add(recordToUpdate);
            }

            return records;
        }
        /// <summary>
        /// Consumes a line of data to populate a JobClass
        /// </summary>
        /// <param name="dataChunks">A collection of job class data points.</param>
        /// <param name="jobClass">A JobClass object to consume the line data.</param>
        /// <returns>Any remaining data after processing the JobClass.</returns>
        IEnumerable<string> assignClassData(IList<string> dataChunks, JobClass jobClass)
        {
            //the process order here is important, since we're relying on simple(ish) Regex
            //which may overlap one another

            // 1. code is always 4 consecutive integers
            string code = dataChunks.FirstOrDefault(c => FieldPatterns.ClassCode.IsMatch(c));
            if (!String.IsNullOrEmpty(code))
            {
                jobClass.Code = code;
                dataChunks.Remove(code);
            }
            // 2. grade is always 3 consecutive integers
            string grade = dataChunks.FirstOrDefault(c => FieldPatterns.Grade.IsMatch(c));
            if (!String.IsNullOrEmpty(grade))
            {
                jobClass.Grade = grade;
                dataChunks.Remove(grade);
            }
            // 3. bargaining unit code is always 3 consecutive capital letters
            string bu = dataChunks.FirstOrDefault(c => FieldPatterns.BargainingUnit.IsMatch(c));
            if (!String.IsNullOrEmpty(bu))
            {
                jobClass.BargainingUnit =
                    bargainingUnits.ContainsKey(bu) ?
                    bargainingUnits[bu] : new BargainingUnit() { Name = string.Empty, Code = bu };

                dataChunks.Remove(bu);
            }
            // 4. the remaining chunks are either part of the job title or part of a job step
            //    job step data is all numeric (integer or decimal numbers)
            //    so separate out the title parts and form the title
            decimal dec;
            var titleChunks = dataChunks.Where(c => !decimal.TryParse(c, out dec)).ToArray();
            string title = String.Join(" ", titleChunks).Trim();

            if (!String.IsNullOrEmpty(title))
            {
                jobClass.Title = title;
                foreach (var chunk in titleChunks)
                {
                    dataChunks.Remove(chunk);
                }
            }

            //the job step chunks are all that should remain
            return dataChunks;
        }
        /// <summary>
        /// Gets a sorted shop list from JSON string in expected format
        /// </summary>
        /// <param name="json">the json string</param>
        /// <returns>the shoplist</returns>
        public static ShopList GetShopList(string json, List<Product> allProducts, Customer customer, IList<Supermarket> markets)
        {
            JObject jObject = JObject.Parse(json);
            JToken jlistData = jObject["listData"];

            JToken jmarketName = jObject["supermarket"];
            string superName = jmarketName["superName"].ToString().Trim();
            Supermarket market = markets.FirstOrDefault(m => m.Name == superName) ?? markets[0];

            JToken jlistItems = jlistData["listItems"];//jlistData.First;
            var AllItems = jlistItems.Where(token => token.HasValues).ToList();//jlistItems.Children()[1];//.FirstOrDefault()["Id"];

            int temp;
            var tuplesStr =
                AllItems.OfType<JObject>()
                .Cast<IDictionary<string, JToken>>() //easier to handle as dictionary
                .Where(i => i.ContainsKey("Id") && i["Id"] !=null && !String.IsNullOrWhiteSpace(i["Id"].ToString())) //make sure ID is available
                .Select(i => new Tuple<string, string>( i["Id"].ToString() , i.ContainsKey("Quantity") ? i["Quantity"].ToString() : "1"))//get tuple with ID / quantity
                 .Where(t => int.TryParse(t.Item1, out temp) && int.TryParse(t.Item2, out temp))//parse to int
                 .ToList();//list is easier to debug

            var quantityByProductDic= new Dictionary<Product,int>();
            //add products to dictionary
            tuplesStr.ToList()
                .ForEach(t => quantityByProductDic.Add(allProducts.FirstOrDefault(p => p.Id == int.Parse(t.Item1)), int.Parse(t.Item2)));

            ShopList sl = Logics.GetShoppingList(quantityByProductDic, market, customer);

            return sl;
        }
        public string GetNestingParent(string potentialChildFilePath, string potentialChildDirectory, IList<string> potentialParentProjectItems)
        {
            string fileName = Path.GetFileName(potentialChildFilePath);
            if (fileName != ".bowerrc") return null;

            return potentialParentProjectItems.FirstOrDefault(x => x == "bower.json");
        }
        private void ConfirmPackList(TradevineGateway gateway, IList<Messages.SalesOrder> salesOrders, Dictionary<string, int> headerIndexes, List<string> row)
        {
            string packListID = string.Empty;

            try
            {
                packListID = row[headerIndexes["PackListID"]];
                packListID = packListID.Replace("ID:", string.Empty);
                var id = !string.IsNullOrEmpty(packListID) ? long.Parse(packListID) : (long?)null;
                var courier = row[headerIndexes["Courier"]];
                var trackingReference1 = row[headerIndexes["TrackingReference1"]];
                var trackingReference2 = row[headerIndexes["TrackingReference2"]];

                var salesOrder = salesOrders.FirstOrDefault(x => x.PackLists.Any(y => y.PackListID == id));
                if (null == salesOrder)
                    return;

                var packList = salesOrder.PackLists.Single(x => x.PackListID == id);
                packList.Courier = !string.IsNullOrEmpty(courier) ? int.Parse(courier) : (int?)null;
                packList.TrackingReference = trackingReference1;
                packList.TrackingReference2 = trackingReference2;

                packList.ConfirmOptions = new Messages.ConfirmOptions() { IsInvoiceEmailed = true, IsPackingSlipEmailed = true };

                var output = gateway.Sales.ConfirmPackList(packList);

                Console.WriteLine("Packlist {0} now has status {1}", output.PackListNumber, output.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error confirming packlist {0} : {1} : {2}", packListID, ex.Message, ex.StackTrace);
            }
        }
Example #12
0
        /// <summary>
        /// Find the node that's closest to the source node.
        /// </summary>
        /// <param name="source">The source node.</param>
        /// <param name="sharedParentNode">The parent node in common between the node in question and all the nodes in the list.</param>
        /// <param name="nodes">A list of nodes where we want to determine the closest to the source.</param>
        /// <returns>The node that is closest to the source.</returns>
        public static HtmlNode FindClosestNode(this HtmlNode source, HtmlNode sharedParentNode, IList<HtmlNode> nodes)
        {
            if (nodes.Count < 2) // don't even bother.
            {
                return nodes.FirstOrDefault();
            }
            int index = source.GetParentNodeUntil(sharedParentNode).GetIndex(); // get the index of our node, relative to the shared parent node.

            HtmlNode closest = null;
            int distance = int.MaxValue;

            foreach (HtmlNode currentNode in nodes)
            {
                int currentIndex = currentNode.GetParentNodeUntil(sharedParentNode).GetIndex(); // get the index of this node, relative to the shared parent node.
                int currentDistance;
                if (currentIndex > index)
                {
                    currentDistance = currentIndex - index;
                }
                else
                {
                    currentDistance = index - currentIndex;
                }
                if (currentDistance < distance)
                {
                    closest = currentNode;
                    distance = currentDistance;
                }
            }
            return closest;
        }
        public AlgorithmManager(IPoolManager poolManager, IObjectFactory objectFactory)
        {
            _storage = new List<IHashAlgorithmStatistics>();

            // add algorithms
            foreach (var pool in poolManager.GetAll())
            {
                var query = _storage.FirstOrDefault(x => x.Name == pool.Config.Coin.Algorithm);

                if (query != null)
                    continue;

                var statistics = objectFactory.GetHashAlgorithmStatistics(pool.Config.Coin.Algorithm);

                _storage.Add(statistics);
            }

            // assign pools to hash algorithms
            foreach (var item in _storage)
            {
                var algorithm = item;
                var pools = poolManager.GetAll().Where(p => p.Config.Coin.Algorithm == algorithm.Name);
                algorithm.AssignPools(pools);
            }
        }
 public DefaultServerGridLayoutOptions(
     ContextualizedHelpers helpers,
     IList<RowType> rows,
     IList<KeyValuePair<string, string>> toolbars,
     Template<LayoutTemplateOptions> layoutTemplate,
     IEnumerable<Template<LayoutTemplateOptions>> subTemplates, 
     IHtmlContent mainContent,
     GridType type,
     string id,
     string prefix,
     GridErrorMessages messages,
     string cssClass,
     string caption,
     Type localizerType
     ) : base(rows, toolbars, layoutTemplate, subTemplates, mainContent)
 {
     this.helpers = helpers;
     Type = type;
     Messages = messages;
     Id = id;
     Prefix = prefix;
     CssClass = cssClass;
     Caption = caption;
     var first = rows.FirstOrDefault();
     MustAddButtonColumn = first.MustAddButtonColumn(helpers, Type== GridType.Batch);
     VisibleColumns = first.VisibleColumns(helpers, Type == GridType.Batch);
     LocalizerType = localizerType;
     Localizer = LocalizerType != null ? helpers.LocalizerFactory.Create(LocalizerType) : null;
 }
        public static void SetAccessControlHeaders(this IContext context, IList<IAccessControlEntry> accessControl)
        {
            if (accessControl == null || accessControl.Count == 0) return;

            // For wildcards just add it
            if (accessControl.Count == 1 && accessControl[0].Origin == "*")
            {
                context.Response.SetAccessControl(accessControl[0]);
                return;
            }

            // If there's no Origin header in the request, no headers needed
            var origin = context.Request.GetOrigin();
            if (string.IsNullOrWhiteSpace(origin)) return;

            // If origin and host match we don't need headers
            var host = context.Request.Host;
            if (new Uri(origin).Authority.Equals(host, StringComparison.OrdinalIgnoreCase)) return;

            // Find a matching entry for the request origin
            var entry = accessControl.FirstOrDefault(e => e.Origin.Equals(origin, StringComparison.OrdinalIgnoreCase));
            if (entry != null)
            {
                context.Response.SetAccessControl(entry);
            }
        }
 public bool CheckAllSecretQuestionAnswers(ILoginProcess process, IList<SecretQuestionAnswer> answers)
 {
     var session = EntityHelper.GetSession(process);
       var context = session.Context;
       bool result = true;
       foreach(var qa in process.Login.SecretQuestionAnswers) {
     var ans = answers.FirstOrDefault(a => a.QuestionId == qa.Question.Id);
     if(ans == null)
       result = false ; //question not answered
     else
       result &= CheckUserAnswer(qa, ans.Answer);
       }
       if(!result) {
     process.FailCount++;
     session.SaveChanges();
     OnLoginEvent(context, LoginEventType.QuestionAnswersFailed, process.Login, "Secret questions check failed.");
     LogIncident(context, LoginIncidentType, "InvalidQuestionAnswer",
     "Invalid answer(s) to secret questions, user: " + process.Login.UserName, process.Login, process.Login.UserName);
     return false;
       }
       // Success
       // Save numbers of answered questions, clear flag in pending steps
       process.AnsweredQuestions = string.Join(",", process.Login.SecretQuestionAnswers.Select(qa => qa.Number));
       process.PendingFactors &= ~ExtraFactorTypes.SecretQuestions;
       session.SaveChanges();
       OnLoginEvent(context, LoginEventType.QuestionAnswersSucceeded, process.Login, "Secret questions check succeeded.");
       return result;
 }
        public static string GetCSName( this ParamFunctionOption paramFunctionOption, IList<TypeMap> typeMapList, IList<CSTypeMap> csTypeMapList,
            IList<EnumData> enumDatas)
        {
            CSTypeMap csTypeMap;
            TypeMap typeMap;
            GetTypeMap( typeMapList, csTypeMapList, out csTypeMap, out typeMap, paramFunctionOption.ParamType,
                        paramFunctionOption is ArrayParamFunctionOption );
            if (csTypeMap.Attributes.Contains( "enum" ))
            {
                if (enumDatas.FirstOrDefault(data => data.Name == paramFunctionOption.ParamType) != null)
                    return paramFunctionOption.ParamType;
            }
            if (csTypeMap.LanguageName == "void")
            {
                return "void" + new string( '*', typeMap.LanguageName.PointDeep +
                                                 (paramFunctionOption is ArrayParamFunctionOption ? 1 : 0) );
            }

            if (paramFunctionOption is ArrayParamFunctionOption &&
                (paramFunctionOption.ParamType == "charARB" || paramFunctionOption.ParamType == "char") &&
                paramFunctionOption.Direction == "out")
            {
                return "char[]";
            }

            if (paramFunctionOption is ArrayParamFunctionOption && csTypeMap.LanguageName == "string" && paramFunctionOption.ParamType != "charPointerARB")
            {
                return "string";
            }

            return csTypeMap.LanguageName + new string( '*', typeMap.LanguageName.PointDeep > 0 ? typeMap.LanguageName.PointDeep : 0 ) +
                   (paramFunctionOption is ArrayParamFunctionOption ? "[]" : "");
        }
        public ExtendedServiceBusNamespace(
            ServiceBusNamespace serviceBusNamespace,
            IList<NamespaceDescription> descriptions)
        {
            Name = serviceBusNamespace.Name;

            Region = serviceBusNamespace.Region;

            Status = serviceBusNamespace.Status;

            CreatedAt = serviceBusNamespace.CreatedAt;

            AcsManagementEndpoint = serviceBusNamespace.AcsManagementEndpoint != null ? serviceBusNamespace.AcsManagementEndpoint.ToString() : string.Empty;

            ServiceBusEndpoint = serviceBusNamespace.ServiceBusEndpoint != null ? serviceBusNamespace.ServiceBusEndpoint.ToString() : string.Empty;

            if (descriptions != null && descriptions.Count != 0)
            {
                NamespaceDescription desc = descriptions.FirstOrDefault();
                DefaultKey = this.GetKeyFromConnectionString(desc.ConnectionString);
                ConnectionString = desc.ConnectionString;
            }
            else
            {
                DefaultKey = string.Empty;
                ConnectionString = string.Empty;
            }

        }
        public PartialViewResult EditContactClosedFilter(IList<ContactFilter> filters, ContactClosedFilter filter)
        {
            filters.Remove(filters.FirstOrDefault(cf => cf.Id == filter.Id));

            filters.Add(filter);
            return PartialView("DisplayTemplates/contactClosedFilter", filter);
        }
Example #20
0
 public PearsonCorrelationGroupDescription(
     IList<VariableDescription> variables,
     IList<VariableDescription> targetVariables)
     : base(variables, targetVariables.FirstOrDefault())
 {
     TargetVariables = targetVariables;
 }
        public void MatchPlayers(IList<FantasyProsPlayer> players, IList<DraftKingsPlayer> draftKingsPlayers)
        {
            IList<string> teams = new List<string>();
            IList<FantasyProsPlayer> unMatchedPlayers = new List<FantasyProsPlayer>();

            foreach (FantasyProsPlayer player in players) {
                DraftKingsPlayer matchingDraftKingsPlayer = draftKingsPlayers.FirstOrDefault(dk => dk.Name.ToLower() == player.PlayerName.ToLower());

                if (matchingDraftKingsPlayer == null) {

                    if (!teams.Contains(player.Team)) {
                        teams.Add(player.Team);
                    }
                    unMatchedPlayers.Add(player);
                    continue;
                }

                player.DraftKingsPlayer = matchingDraftKingsPlayer;
            }

            foreach (string team in teams) {

                Console.WriteLine(team);
                foreach (var player in unMatchedPlayers.Where(p => p.Team == team)) {
                    Console.WriteLine(player.PlayerName);
                }
            }
        }
        private string GetInternalLoadBalancerIPAddress(IList<VirtualIPAddress> virtualIPs, string ilbName)
        {
            var ilbIP = virtualIPs == null || !virtualIPs.Any() ? null
                      : virtualIPs.FirstOrDefault(ip => string.Equals(ip.Name, ilbName, StringComparison.OrdinalIgnoreCase));

            return ilbIP == null ? null : ilbIP.Address;
        }
Example #23
0
        public int Run(IList<string> args)
        {
            string command = args.FirstOrDefault() ?? "";
            _stdout.WriteLine("executing subtree " + command);

            if (string.IsNullOrEmpty(Prefix))
            {
                _stdout.WriteLine("Prefix must be specified, use -p or -prefix");
                return GitTfsExitCodes.InvalidArguments;
            }

            switch (command.ToLower())
            {
                case "add":
                    return DoAdd(args.ElementAtOrDefault(1) ?? "", args.ElementAtOrDefault(2) ?? "");

                case "pull":
                    return DoPull(args.ElementAtOrDefault(1));

                case "split":
                    return DoSplit();

                default:
                    _stdout.WriteLine("Expected one of [add, pull, split]");
                    return GitTfsExitCodes.InvalidArguments;
            }
        }
Example #24
0
		void NonKeywordAttrError(IList<LNode> attrs, string stmtType)
		{
			var attr = attrs.FirstOrDefault(a => a.AttrNamed(S.TriviaWordAttribute) != null);
			if ((attr != null)) {
				Error(attr, "'{0}' appears to be a word attribute, which is not permitted before '{1}'", attr.Range.SourceText, stmtType);
			}
		}
 public ProcessingDialogViewModel()
 {
     LoadParameters = new DelegateCommand<MassSpecStudio.Core.Domain.Algorithm>(OnLoadParameters);
     _algorithms = ServiceLocator.Current.GetAllInstances<IAlgorithm>().ToList();
     _selectedAlgorithm = _algorithms.FirstOrDefault();
     _recentAlgorithmsUsed = RecentAlgorithms.Read();
 }
Example #26
0
        private Type GetMatchingFilter(Property property, IList<Type> filters)
        {
            var filterType = filters.FirstOrDefault(x => x.BaseType.GetGenericArguments()[0] == property.TypeInfo.NotNullableType);
            if (filterType != null)
                return filterType;

            filterType = filters.FirstOrDefault(x => x.BaseType.GetGenericArguments()[0].IsAssignableFrom(property.TypeInfo.NotNullableType));
            if (filterType != null)
                return filterType;

            var groupers = filters.Where(x => typeof(ITypeGrouper).IsAssignableFrom(x.BaseType.GetGenericArguments()[0])).ToList();
            if (groupers.IsNullOrEmpty() == false)
                return groupers.FirstOrDefault(x => CreateTypeGrouperInstance(x.BaseType.GetGenericArguments()[0]).Match(property.TypeInfo.NotNullableType));

            return null;
        }
Example #27
0
 /// <summary>
 /// Converts a timestamp  specified in seconds/nanoseconds to a string.
 /// </summary>
 /// <remarks>
 /// If the value is a normalized duration in the range described in <c>field_mask.proto</c>,
 /// <paramref name="diagnosticOnly"/> is ignored. Otherwise, if the parameter is <c>true</c>,
 /// a JSON object with a warning is returned; if it is <c>false</c>, an <see cref="InvalidOperationException"/> is thrown.
 /// </remarks>
 /// <param name="paths">Paths in the field mask</param>
 /// <param name="diagnosticOnly">Determines the handling of non-normalized values</param>
 /// <exception cref="InvalidOperationException">The represented duration is invalid, and <paramref name="diagnosticOnly"/> is <c>false</c>.</exception>
 internal static string ToJson(IList<string> paths, bool diagnosticOnly)
 {
     var firstInvalid = paths.FirstOrDefault(p => !ValidatePath(p));
     if (firstInvalid == null)
     {
         var writer = new StringWriter();
         JsonFormatter.WriteString(writer, string.Join(",", paths.Select(JsonFormatter.ToCamelCase)));
         return writer.ToString();
     }
     else
     {
         if (diagnosticOnly)
         {
             var writer = new StringWriter();
             writer.Write("{ \"@warning\": \"Invalid FieldMask\", \"paths\": ");
             JsonFormatter.Default.WriteList(writer, (IList)paths);
             writer.Write(" }");
             return writer.ToString();
         }
         else
         {
             throw new InvalidOperationException($"Invalid field mask to be converted to JSON: {firstInvalid}");
         }
     }
 }
Example #28
0
        /// <summary>
        /// Applies Annotations to a list of PdfColumnAttributes.
        /// </summary>
        /// <param name="bodyDataSource">Data source</param>        
        /// <param name="result">A list of PdfColumnAttributes</param>
        /// <param name="areColumnsAdHoc">It's possible to remove the MainTableColumns part completely</param>
        public static void ApplyPropertyDataAnnotations(this IDataSource bodyDataSource, IList<ColumnAttributes> result, bool areColumnsAdHoc = false)
        {
            var properties = bodyDataSource.GetPropertiesInfoOfStronglyTypedListDataSource();
            if (properties == null || !properties.Any()) return;

            var fieldsInfo = bodyDataSource.GetFieldsInfoOfStronglyTypedListDataSource();

            foreach (var property in properties)
            {
                var columnAttributes = result.FirstOrDefault(x => x.PropertyName == property.Name);
                if (columnAttributes == null) continue;

                applyPropertyName(property, columnAttributes, areColumnsAdHoc);
                applyAggregateFunction(property, columnAttributes);
                applyFixedHeight(property, columnAttributes);
                applyMinimumHeight(property, columnAttributes);
                applyCellsHorizontalAlignment(property, columnAttributes);
                applyColumnIsVisible(property, columnAttributes);
                applyOrder(property, columnAttributes);
                applyWidth(property, columnAttributes);
                applyDataFormatString(property, columnAttributes);
                applyColumnItemsTemplate(property, columnAttributes);
                applyCalculatedField(property, columnAttributes, fieldsInfo);
                applyIncludedGroupFieldEqualityComparer(property, columnAttributes, fieldsInfo);
            }
        }
Example #29
0
        public Config(ScenarioTypeAttribute scenario
            , ImplementationTypeAttribute implementation
            , uint runs, ScenarioTypeAttribute[] knownScenarios
            , ImplementationTypeAttribute[] knownImplementations
            , IList<TypeLocator> perfTests
            , string pluginPath)
        {
            Scenario = scenario;
            Implementation = implementation;
            Runs = runs;
            KnownScenarios = knownScenarios;
            KnownImplementations = knownImplementations;
            PerfTests = perfTests;
            PluginPath = pluginPath;
            Groups = new Dictionary<ScenarioTypeAttribute, IDictionary<ImplementationTypeAttribute, TypeLocator>>();

            foreach (var knownScenario in KnownScenarios)
            {
                var inner = new Dictionary<ImplementationTypeAttribute, TypeLocator>();

                foreach (var knownImplementation in KnownImplementations)
                {
                    inner[knownImplementation] = perfTests.FirstOrDefault(pt => pt.Attributes.Contains(knownImplementation) && pt.Attributes.Contains(knownScenario));
                }

                Groups[knownScenario] = inner;
            }
        }
Example #30
0
 static bool HandleLines(IList<string> lines, Market market, char[] seps, StringBuilder sb)
 {
     //Read First Line to fin Vol Surface and if its Rho or Nu
     bool isRho = true;
     InterestVolatility vol = null;
     var firstLine = lines.FirstOrDefault();
     if (string.IsNullOrEmpty(firstLine))
     {
         sb.Append("Cannot parse first line");
         return false;
     }
     var ss = firstLine.Split(seps);
     var sdate = ss[2];
     var stype = ss[3];
     var ticker = ss[4];
     var date = SimpleDate.Parse(sdate);
     isRho = stype.ToUpper().Contains("RHO");
      var isBeta = stype.ToUpper().Contains("BETA");
     ss = ticker.Split('.');
     var name = ss[0];
     var ccy = ss[1];
     var time = date.ToDateTime(23, 59, 59);
     market.Time = time;
     market.ClearMarketDatas();
     var vols = market.GetAll(true, false, false, true, false, false, false, false, false, false, false, false, false);
     foreach (var im in vols)
     {
         var ivol = im as InterestVolatility;
         if (ivol != null && ivol.Currency.Equals(ccy))
         {
             vol = ivol;
             break;
         }
     }
     if (vol == null)
     {
         sb.Append("Cannot Find Any Vol for " + ticker);
         return false;
     }
     var output = vol.Output as InterestVolatilityOutput;
     if (output == null)
     {
         sb.Append("Invalid Vol not built " + vol);
         return false;
     }
     var data = new List<SabrData>();
     foreach (var line in lines)
     {
         var d = new SabrData();
         ss = line.Split(seps);
         var tick = ss[4];
         d.Date = SimpleDate.Parse(ss[2]).ToDateTime();
         d.ComponentTicker = tick;
         d.InstrumentType = ss[3];
         d.Value = Convert.ToDouble(ss[5]);
         data.Add(d);
     }
     return HandleData(vol, isRho, isBeta, data, market, sb);
 }