Beispiel #1
11
        /// <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();
        }
Beispiel #2
1
        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();
        }
        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;
        }
Beispiel #4
0
        private static void Hydrate(IEnumerable <Session> sessions, IList <Speaker> speakers, IList <StreamUrl> streamUrls)
        {
            foreach (var session in sessions)
            {
                session.Speakers  = new List <Speaker>();
                session.StreamUrl = streamUrls?.FirstOrDefault(c => c.Name.Equals(session.Room))?.Url;

                if (session.Title is "Welcome Keynote" or "Closing / Gifts")
                {
                    session.StreamUrl = streamUrls?.FirstOrDefault(c => c.Name.Equals("Slot 1"))?.Url;
                }

                if (session.SpeakerIds == null)
                {
                    continue;
                }

                foreach (var speakerId in session.SpeakerIds)
                {
                    var speaker = speakers.FirstOrDefault(c => c.Id.Equals(speakerId));
                    if (speaker == null)
                    {
                        continue;
                    }

                    session.Speakers.Add(speaker);
                }
            }
        }
        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;
        }
Beispiel #6
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;
        }
        private static string GetFunctionKeyFromCollection(IList <Key> keys)
        {
            Key key = keys?.FirstOrDefault();

            return(keys?.FirstOrDefault(s => string.Equals(s.Name, ScriptConstants.DefaultFunctionKeyName))?.Value
                   ?? key?.Value);
        }
Beispiel #8
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();
 }
Beispiel #9
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;
        }
Beispiel #10
0
        /// <summary>
        /// Subscribes an one-way long running event.
        /// This subscription will at best be valid until the destructor of this class is called
        /// </summary>
        /// <param name="messageType">Type of the message.</param>
        /// <param name="asyncDeliveryAction">The asynchronous delivery action.</param>
        /// <param name="asyncDeliveryActionName">Name of the asynchronous delivery action.</param>
        /// <param name="unsubscribeOnMessageArrival">if set to <c>true</c> [unsubscribe on message arrival].</param>
        /// <param name="context">The context.</param>
        protected void SubscribeLongRunningEvent(Type messageType, Func <INotificationOneWayMessage, Task> asyncDeliveryAction, string asyncDeliveryActionName, bool unsubscribeOnMessageArrival = false, string context = AsyncSubscription.DefaultContext)
        {
            var equalLongSubscription = _longRunningMessageTokens?.FirstOrDefault(l => l.Token.MessageType == messageType);

            if (equalLongSubscription != null)
            {
                NotificationManager.Unsubscribe(equalLongSubscription.Token);
                _longRunningMessageTokens.Remove(equalLongSubscription);
            }

            var token = NotificationManager.Subscribe(messageType, OnLongRunningNotificationAsync, context);

            _longRunningMessageTokens.Add(new LongRunningSubscriptionToken(token, asyncDeliveryAction, asyncDeliveryActionName, unsubscribeOnMessageArrival));
        }
Beispiel #11
0
        public static async Task <TrainingModels::Export> ExportIteration(
            this ICustomVisionTrainingClient trainingApi, Guid projectId, Guid iterationId, string flavor = "onnx12", int timeoutInSecond = 30)
        {
            TimeSpan timeout = TimeSpan.FromSeconds(timeoutInSecond);

            TrainingModels::Export exportIteration = null;

            try
            {
                exportIteration = exportIteration = string.IsNullOrEmpty(flavor)
                    ? await trainingApi.ExportIterationAsync(projectId, iterationId, platform)
                    : await trainingApi.ExportIterationAsync(projectId, iterationId, platform, flavor);
            }
            catch (HttpOperationException ex)
            {
                string exceptionContent = ex?.Response?.Content ?? string.Empty;
                if (!exceptionContent.Contains("BadRequestExportAlreadyInProgress"))
                {
                    throw ex;
                }
            }

            DateTime startTime = DateTime.Now;

            while (true)
            {
                IList <TrainingModels::Export> exports = await trainingApi.GetExportsAsync(projectId, iterationId);

                exportIteration = string.IsNullOrEmpty(flavor)
                    ? exports?.FirstOrDefault(x => string.Equals(x.Platform, platform, StringComparison.OrdinalIgnoreCase))
                    : exports?.FirstOrDefault(x => string.Equals(x.Platform, platform, StringComparison.OrdinalIgnoreCase) &&
                                              string.Equals(x.Flavor, flavor, StringComparison.OrdinalIgnoreCase));

                if (exportIteration?.Status == "Exporting")
                {
                    await Task.Delay(1000);
                }
                else
                {
                    break;
                }

                if (DateTime.Now - startTime > timeout)
                {
                    throw new TimeoutException("The operation couldn't be completed due to a timeout.");
                }
            }

            return(exportIteration);
        }
        /// <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;
        }
 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;
 }
Beispiel #14
0
        public static void IfParamDoesNotContain(RenderContext context, IList <object> arguments,
                                                 IDictionary <string, object> options,
                                                 RenderBlock fn, RenderBlock inverse)
        {
            var operation = arguments?.FirstOrDefault() as OpenApiOperation;

            if (operation != null)
            {
                string name = null;
                if (arguments.Count > 1)
                {
                    name = arguments[1] as string;
                }

                var found = false;

                foreach (var param in operation.Parameters)
                {
                    if (param.Name == name)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    fn(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 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 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.SecretQuestionAnswers.Select(qa => qa.Number));
       process.PendingFactors &= ~ExtraFactorTypes.SecretQuestions;
       session.SaveChanges();
       OnLoginEvent(context, LoginEventType.QuestionAnswersSucceeded, process.Login, "Secret questions check succeeded.");
       return result;
 }
Beispiel #18
0
        public void IfReturnType(RenderContext context, IList <object> arguments,
                                 IDictionary <string, object> options,
                                 RenderBlock fn, RenderBlock inverse)
        {
            var operation = arguments?.FirstOrDefault() as OpenApiOperation;

            if (operation != null)
            {
                string type = null;
                if (arguments.Count > 1)
                {
                    type = arguments[1] as string;
                }

                var rt = GetReturnType(operation, "void");
                if (type == "any" && rt != "void")
                {
                    fn(null);
                }
                else if (string.Equals(type, rt.ToLower(), StringComparison.OrdinalIgnoreCase))
                {
                    fn(null);
                }
                else if (type == "obj" && rt != "void" && rt != "Stream")
                {
                    fn(null);
                }
            }
        }
Beispiel #19
0
        public void Delete(long id)
        {
            try
            {
                var record = _dataSet?.FirstOrDefault(x => x.Id == id);

                if (record != null)
                {
                    _dataSet.Remove(record);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #20
0
        private bool IncrimentCurrentOrder(IList <OrderContent> list, IOrderContent orderContent, bool isIncriment)
        {
            var a = list?.FirstOrDefault(x => x.IdProduct == orderContent.IdProduct);

            if (a == null)
            {
                return(true);
            }
            if (isIncriment)
            {
                a.Quantity = (Convert.ToInt32(a.Quantity) + Convert.ToInt32(orderContent.Quantity)).ToString();
                UserManager.Instance.UpdateUser(new UserModel {
                    Orders = list
                });
            }
            else
            {
                if (a.Quantity == "1")
                {
                    RemoveOrder(a.IdProduct);
                }
                else
                {
                    a.Quantity = (Convert.ToInt32(a.Quantity) - Convert.ToInt32(orderContent.Quantity)).ToString();
                    UserManager.Instance.UpdateUser(new UserModel {
                        Orders = list
                    });
                }
            }

            return(false);
        }
        /// <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;
        }
Beispiel #22
0
        private bool PlayerHaveOpponents(JogadorHistorico player, IEnumerable <JogadorHistorico> team)
        {
            var opponent = _listaPartidas?.FirstOrDefault(x => x.ClubeCasaId == player.ClubeId && x.Rodada == player.RodadaId + 1)?.ClubeVisitanteId ??
                           _listaPartidas.FirstOrDefault(x => x.ClubeVisitanteId == player.ClubeId && x.Rodada == player.RodadaId + 1).ClubeCasaId;

            return(team.Any(x => x.ClubeId == opponent));
        }
        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 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);
            }
        }
Beispiel #25
0
        public JwtAuthResult GenerateTokens(long userId, string username, IList <Claim> claims, DateTime now)
        {
            var shouldAddAudienceClaim = string.IsNullOrWhiteSpace(claims?.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Aud)?.Value);
            var jwtToken = new JwtSecurityToken(
                _jwtTokenConfig.Issuer,
                shouldAddAudienceClaim ? _jwtTokenConfig.Audience : string.Empty,
                claims,
                expires: now.AddMinutes(_jwtTokenConfig.AccessTokenExpiration),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(_secret), SecurityAlgorithms.HmacSha256Signature));
            var accessToken = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            var refreshToken = new RefreshToken
            {
                UserId      = userId,
                TokenString = GenerateRefreshTokenString(),
                ExpireAt    = now.AddMinutes(_jwtTokenConfig.RefreshTokenExpiration)
            };

            _usersRefreshTokens.AddOrUpdate(refreshToken.TokenString, refreshToken, (s, t) => refreshToken);

            return(new JwtAuthResult
            {
                AccessToken = accessToken,
                RefreshToken = refreshToken
            });
        }
Beispiel #26
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 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 void ApplyLoadshopFee(string usersPrimaryScac, ILoadFeeData load, IList <CustomerEntity> customers)
        {
            // get the customer
            var customer = customers?.FirstOrDefault(_ => load.CustomerId == _.CustomerId);

            if (customer == null)
            {
                throw new Exception("Customer not found");
            }

            var inNetwork  = customer.CustomerCarrierScacContracts?.Any(_ => _.Scac == (load.Scac ?? usersPrimaryScac)) ?? false;
            var flatFee    = inNetwork ? customer.InNetworkFlatFee : customer.OutNetworkFlatFee;
            var percentFee = inNetwork ? customer.InNetworkPercentFee : customer.OutNetworkPercentFee;
            var feeAdd     = inNetwork ? customer.InNetworkFeeAdd : customer.OutNetworkFeeAdd;
            var fee        = flatFee + Math.Round(percentFee * (load.LineHaulRate + load.FuelRate), 2, MidpointRounding.AwayFromZero);

            if (!feeAdd)
            {
                load.LineHaulRate -= fee;
            }

            load.FeeData = new LoadshopFeeData
            {
                LoadshopFlatFee    = flatFee,
                LoadshopPercentFee = percentFee,
                LoadshopFee        = fee,
                LoadshopFeeAdd     = feeAdd
            };
        }
        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");
        }
Beispiel #30
0
 public PearsonCorrelationGroupDescription(
     IList<VariableDescription> variables,
     IList<VariableDescription> targetVariables)
     : base(variables, targetVariables.FirstOrDefault())
 {
     TargetVariables = targetVariables;
 }
Beispiel #31
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;
            }
        }
        /// <inheritdoc/>
        public async override Task <string> RetrieveSerializedEntityState(EntityId entityId, JsonSerializerSettings serializerSettings)
        {
            var instanceId = EntityId.GetSchedulerIdFromEntityId(entityId);
            IList <OrchestrationState> stateList = await this.serviceClient.GetOrchestrationStateAsync(instanceId, false);

            OrchestrationState state = stateList?.FirstOrDefault();

            if (state != null &&
                state.OrchestrationInstance != null &&
                state.Input != null)
            {
                string serializedState;

                if (state.Input.StartsWith("http"))
                {
                    serializedState = await this.serviceClient.DownloadBlobAsync(state.Input);
                }
                else
                {
                    serializedState = state.Input;
                }

                var schedulerState = JsonConvert.DeserializeObject <SchedulerState>(serializedState, serializerSettings);

                if (schedulerState.EntityExists)
                {
                    return(schedulerState.EntityState);
                }
            }

            return(null);
        }
        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);
        }
Beispiel #34
0
        public Attachment CreateBatonsAttachment(IList <FirebaseObject <BatonQueue> > batons)
        {
            // combine path for cross platform support
            string[] paths            = { ".", "Resources", "batonQueue.json" };
            var      adaptiveCardJson = File.ReadAllText(Path.Combine(paths));

            var listBuilder    = new StringBuilder();
            var headerBuilder  = new StringBuilder();
            var commentBuilder = new StringBuilder();

            foreach (var baton in batonList.GetBatons())
            {
                //Get the batonqueue
                var batonQueue = batons?.FirstOrDefault(x => x.Object.Name == baton.Shortname);
                listBuilder.Append(FormatQueue(batonQueue?.Object));
                headerBuilder.Append(FormatHeader(batonQueue?.Object));
                commentBuilder.Append(FormatComments(batonQueue?.Object));
            }

            adaptiveCardJson = adaptiveCardJson.Replace("\"{QueueData}\"", listBuilder.ToString());
            adaptiveCardJson = adaptiveCardJson.Replace("\"{HeaderData}\"", headerBuilder.ToString());
            adaptiveCardJson = adaptiveCardJson.Replace("\"{CommentsData}\"", commentBuilder.ToString());

            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content     = JsonConvert.DeserializeObject(adaptiveCardJson),
            };

            return(adaptiveCardAttachment);
        }
        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;
            }

        }
Beispiel #36
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 IList <ControlResult> Evaluate(IList <ResourceControlSet> resourceControlSets, JObject resource)
        {
            var type = resource.GetValueCaseInsensitive <string>("type");
            //var apiVersion = resource.GetValueCaseInsensitive<string>("apiVersion");
            var controlSet = resourceControlSets?.FirstOrDefault(
                x => x.supportedResourceTypes.Any(y => y.Equals(type, StringComparison.OrdinalIgnoreCase)));

            if (controlSet == null)
            {
                return(new List <ControlResult> {
                    ControlResult.NotSupported(resource)
                });
            }
            var results = new List <ControlResult>();

            foreach (var control in controlSet.Controls)
            {
                control.FeatureName        = controlSet.FeatureName;
                control.SupportedResources = controlSet.supportedResourceTypes.ToArray().ToSingleString(" , ");
                var controlResult = _controlEvaluator.Evaluate(control, resource);
                results.Add(controlResult);
            }
            EvaluateNestedResources(controlSet, resource, results);
            return(results);
        }
Beispiel #38
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}");
         }
     }
 }
Beispiel #39
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;
        }
        public IList <ControlResult> Evaluate(IList <ResourceControlSet> resourceControlSets, List <ResourceModel> resources)
        {
            var featureName = resources?.First().FeatureName;
            var controlSet  = resourceControlSets?.FirstOrDefault(x => x.FeatureName.Equals(featureName, StringComparison.OrdinalIgnoreCase));
            var results     = new List <ControlResult>();

            foreach (var control in controlSet.Controls)
            {
                List <string> resourcePathList = new List <string>();
                ControlResult controlResult    = null;
                foreach (var resource in resources)
                {
                    controlResult = _controlEvaluator.Evaluate(control, resource.Resource);
                    resourcePathList.Add(controlResult.ResourceDataMarker.JsonPath);
                    if (!controlResult.IsTokenNotFound)
                    {
                        break;
                    }
                }
                if (controlResult != null)
                {
                    if (controlResult.IsTokenNotFound)
                    {
                        controlResult.ResourceDataMarker.JsonPath = resourcePathList.ToArray().ToSingleString(" , ");
                    }
                    results.Add(controlResult);
                }
            }
            foreach (var resource in resources)
            {
                EvaluateNestedResources(controlSet, resource.Resource, results);
            }

            return(results);
        }
        /// <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);
            }
        }
 public ProcessingDialogViewModel()
 {
     LoadParameters = new DelegateCommand<MassSpecStudio.Core.Domain.Algorithm>(OnLoadParameters);
     _algorithms = ServiceLocator.Current.GetAllInstances<IAlgorithm>().ToList();
     _selectedAlgorithm = _algorithms.FirstOrDefault();
     _recentAlgorithmsUsed = RecentAlgorithms.Read();
 }
Beispiel #43
0
        public static IList <StudentPanoramaCalendarViewData> Create(IList <StudentAbsenceInfo> absences, IList <StudentInfractionInfo> studentInfractions
                                                                     , IList <Date> allSchoolDays, IEnumerable <SchoolYear> schoolYears)
        {
            var res = new List <StudentPanoramaCalendarViewData>();

            schoolYears = schoolYears.OrderByDescending(sy => sy.AcadYear);
            foreach (var schoolYear in schoolYears)
            {
                var syDays = allSchoolDays.Where(sy => sy.SchoolYearRef == schoolYear.Id);
                var items  = syDays.Select(day =>
                {
                    var absence        = absences?.FirstOrDefault(a => a.Date == day.Day);
                    var dayInfractions = studentInfractions?.Where(i => i.OccurrenceDate == day.Day).ToList();
                    return(StudentPanoramaCalendarItemViewData.Create(absence, dayInfractions, day));
                }).ToList();
                res.Add(new StudentPanoramaCalendarViewData
                {
                    AcadYear       = schoolYear.AcadYear,
                    SchoolYearName = schoolYear.Name,
                    SchoolYearId   = schoolYear.Id,
                    CalendarItems  = items
                });
            }
            return(res);
        }
Beispiel #44
0
        /// <summary>
        /// Calculates total word score
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        public async Task <Score> CalculateScoreAsync(string word)
        {
            if (string.IsNullOrWhiteSpace(word))
            {
                return(new Score(word, "Word is blank."));
            }
            if (word.Length == 2)
            {
                return(new Score(word, $"\"{word}\" was skipped."));
            }

            word = word.Trim().ToUpper();
            IList <WordDefinitionsSyllablesPartsOfSpeech> result = await _wordLookup.GetWordDefinitionSyllableCountAsync(word);

            WordDefinitionsSyllablesPartsOfSpeech firstResult = result?.FirstOrDefault();

            if (word != firstResult?.Word?.ToUpper())
            {
                return(new Score(word, $"\"{word}\" is not found in the dictionary."));
            }

            if (IsProperNoun(firstResult.PartsOfSpeech))
            {
                return(new Score(word, $"\"{word}\" is a proper noun."));
            }

            int pointsPerLetter    = CalculatePointsPerLetter(word);
            int extraPoints        = CalculateExtraPoints(word);
            var syllablePoints     = (int)firstResult?.NumSyllables;
            int doubleLetterPoints = CalculateDoubleLetterPoints(word);

            var score = new Score(word, pointsPerLetter, extraPoints, syllablePoints, doubleLetterPoints, 0);

            return(score);
        }
Beispiel #45
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;
            }
        }
        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;
        }
        private void CheckAllTables(IDataTable[] tables, Migration mode, Boolean dbExit)
        {
            // 数据库表进入字典
            //var dic = new Dictionary<String, IDataTable>(StringComparer.OrdinalIgnoreCase);
            IList <IDataTable> dbtables = null;

            if (dbExit)
            {
                dbtables = OnGetTables(tables.Select(t => t.TableName).ToArray());
                //if (dbtables != null && dbtables.Count > 0)
                //{
                //    foreach (var item in dbtables)
                //    {
                //        //dic.Add(item.TableName, item);
                //        dic[item.TableName] = item;
                //    }
                //}
            }

            foreach (var item in tables)
            {
                try
                {
                    // 在MySql中,可能存在同名表(大小写不一致),需要先做确定查找,再做不区分大小写的查找
                    var dbtable = dbtables?.FirstOrDefault(e => e.TableName == item.TableName);
                    if (dbtable == null)
                    {
                        dbtable = dbtables?.FirstOrDefault(e => e.TableName.EqualIgnoreCase(item.TableName));
                    }

                    // 判断指定表是否存在于数据库中,以决定是创建表还是修改表
                    //if (dic.TryGetValue(item.TableName, out var dbtable))
                    if (dbtable != null)
                    {
                        CheckTable(item, dbtable, mode);
                    }
                    else
                    {
                        CheckTable(item, null, mode);
                    }
                }
                catch (Exception ex)
                {
                    WriteLog(ex.ToString());
                }
            }
        }
Beispiel #48
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);
 }
Beispiel #49
0
        public string GetImageUrl(IList <ImageItem> images)
        {
            var image = images?
                        .FirstOrDefault();
            var imageUrl = image?.PathMini;

            return(imageUrl);
        }
        protected void Reset()
        {
            IChannelGroup channelGroup = ChannelGroup;

            if (channelGroup == null)
            {
                ChannelGroup = _channelGroups.FirstOrDefault();
            }
            Channel       = _channels?.FirstOrDefault();
            RecordingType = ScheduleRecordingType.Once;

            DateTime now   = DateTime.Now;
            DateTime start = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0, now.Kind);

            StartTime = start;
            EndTime   = start.AddHours(1);
        }
Beispiel #51
0
 private CalendarPropertyParameter FindParameter(string paramName)
 {
     if (paramName == null)
     {
         throw new ArgumentNullException(nameof(paramName));
     }
     paramName = paramName.ToLowerInvariant();
     return(Parameters?.FirstOrDefault(item => item.Name?.ToLowerInvariant() == paramName));
 }
        public async Task <IGamePlugin> GetActiveGamePluginAsync()
        {
            if (_activeGamePlugins == null)
            {
                await ReloadGamesAsync();
            }

            return(_activeGamePlugins?.FirstOrDefault(plugin => plugin.IsRunning()));
        }
Beispiel #53
0
 internal static IAuthenticator ConvertToAuthenticator(IList <IAuthenticatorValue> authenticators, IAuthenticatorEnrollment authenticatorEnrollment)
 => new Authenticator
 {
     Id           = authenticators?.FirstOrDefault(x => x.Key == authenticatorEnrollment.Key)?.Id,
     Name         = authenticatorEnrollment.DisplayName,
     MethodTypes  = authenticatorEnrollment.Methods?.Select(x => x.Type).ToList(),
     EnrollmentId = authenticatorEnrollment.Id,
     Profile      = GetAuthenticatorProfile(authenticatorEnrollment),
 };
Beispiel #54
0
        public override void UpdateForEachOutputs(IList <Tuple <string, string> > updates)
        {
            var itemUpdate = updates?.FirstOrDefault(tuple => tuple.Item1 == Result);

            if (itemUpdate != null)
            {
                Result = itemUpdate.Item2;
            }
        }
		static XAttribute GetNotNull (IList<ParameterAnnotation> annotations, int parameterIndex)
		{
			var ann = annotations?.FirstOrDefault (a => a.ParameterIndex == parameterIndex)?.Annotations;

			if (ann?.Any (a => IsNotNullAnnotation (a)) == true)
				return new XAttribute ("not-null", "true");

			return null;
		}
Beispiel #56
0
        public bool MoveTo(TextAdventureState nextState)
        {
            if (States?.FirstOrDefault(state => state?.Id == nextState?.Id) == null)
            {
                return(false);
            }
            if (nextState?.RequiredItem != null && !_inventory.Contains(nextState?.RequiredItem))
            {
                BlockedTransition = true;
                return(false);
            }

            if (_stateMachine.MoveTo(nextState))
            {
                _inventory.Add(CurrentState.AcquiredItem);
                return(true);
            }
            return(false);
        }
        static string ToImageUrl(IList <CardImage> images)
        {
            var firstImage = images?.FirstOrDefault();

            if (firstImage == null)
            {
                return(null);
            }
            return(firstImage.Url);
        }
Beispiel #58
0
        public static string ResolveFullTypeName(IList <CssNamespace> namespaces, string cssTypeExpression)
        {
            string typename;

            if (cssTypeExpression.IndexOf('|') > -1)
            {
                var strs          = cssTypeExpression.Split('|');
                var alias         = strs[0];
                var shortTypename = strs[1];

                var namespaceUri = namespaces
                                   ?.FirstOrDefault(x => x.Alias == alias)
                                   ?.Namespace ?? namespaceMapping.First().Key;

                namespaceUri = EnsureAssemblyQualifiedName(namespaceUri, shortTypename);

                var namespaceFragments = namespaceUri
                                         .Split(separator, 2);

                if (namespaceFragments == null)
                {
                    throw new Exception($@"Namespace ""{alias}"" not found!");
                }

                typename = $"{namespaceFragments[0]}.{shortTypename},{string.Join(",", namespaceFragments.Skip(1))}";
            }
            else
            {
                var strs          = cssTypeExpression.Split('.');
                var shortTypename = strs[0];

                var namespaceUri = namespaces
                                   ?.FirstOrDefault(x => x.Alias == "")
                                   ?.Namespace ?? namespaceMapping.First().Key;

                var namespaceFragments = EnsureAssemblyQualifiedName(namespaceUri, shortTypename)
                                         .Split(separator, 2);

                typename = $"{namespaceFragments[0]}.{strs[0]},{string.Join(",", namespaceFragments.Skip(1))}";
            }

            return(typename);
        }
Beispiel #59
0
        public static void MyRemove(this IList <string> list, string value, StringComparison comparison = StringComparison.OrdinalIgnoreCase)
        {
            var theOne = list?.FirstOrDefault(x => x.MyEquals(value, comparison));

            if (theOne == null)
            {
                return;
            }
            list.Remove(theOne);
        }
Beispiel #60
0
        private GdbWorkspace GetWorkspace([NotNull] DdxModel model)
        {
            // TODO: In case it is needed before InitializeSchema() is called, allow creation of
            //       a 'lazy' workspace that is just an empty container that gets initialized
            //       with datasets from remote only when necessary.
            GdbWorkspace workspace =
                _virtualWorkspaces?.FirstOrDefault(w => w.WorkspaceHandle == model.Id);

            return(workspace);
        }