Example #1
0
        public AssemblerResult Assemble(AssemblerOptions options)
        {
            if (options == null)
                throw new ArgumentNullException("options");

            List<AssemblerMessage> messages = new List<AssemblerMessage>();

            try
            {
                //Get the lines
                var sourceLines = GetSourceLines(options);

                //Do the first pass
                var pass1Result = Pass1(messages, sourceLines);

                if (messages.All(m => m.ErrorLevel != ErrorLevel.Error))
                {
                    Pass2(messages, pass1Result, options.OutputFile);
                }
            }
            catch (Exception ex)
            {
                messages.Add(new AssemblerMessage(ErrorLevel.Error, ex.Message));
            }

            //We're done here
            return new AssemblerResult()
            {
                Messages = messages.ToArray(),
                Succeeded = messages.All(m => m.ErrorLevel != ErrorLevel.Error)
            };
        }
Example #2
0
        public static string FindCommonPath(string separator, List<string> paths)
        {
            string CommonPath = string.Empty;
            List<string> SeparatedPath = paths
                .First(str => str.Length == paths.Max(st2 => st2.Length))
                .Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries)
                .ToList();

            foreach (string PathSegment in SeparatedPath.AsEnumerable())
            {
                if (CommonPath.Length == 0 && paths.All(str => str.StartsWith(PathSegment)))
                {
                    CommonPath = PathSegment;
                }
                else if (paths.All(str => str.StartsWith(CommonPath + separator + PathSegment)))
                {
                    CommonPath += separator + PathSegment;
                }
                else
                {
                    break;
                }
            }

            return CommonPath;
        }
Example #3
0
 static bool IsRoyalFlush(List<Card> hand)
 {
     var start = 10;
     var suit = hand[0].Suit;
     return hand.All(c => c.Suit == suit) &&
         hand.All(c => c.Value == start++);
 }
		public static List<IRequiredService> DetermineMissingServices(this IEnumerable<XmlModuleConfig> modules, List<string> bootStrappedServices)
		{
			var providedServices = new List<IProvidedService>();
			var requiredServices = new Dictionary<IRequiredService, XmlModuleConfig>();

			foreach (var module in modules)
			{
				foreach (IRequiredService requiredService in module.RequiredServices)
				{
					if (requiredServices.All(r => r.Key.ServiceName != requiredService.ServiceName))
					{
						requiredServices.Add(requiredService, module);
					}
				}

				foreach (IProvidedService providedService in module.ProvidedServices)
				{
					if (providedServices.All(r => r.ServiceName != providedService.ServiceName))
					{
						providedServices.Add(providedService);
					}
				}
			}

			var query =
				requiredServices.Where(
					requiredService =>
					providedServices.All(s => s.ServiceName != requiredService.Key.ServiceName)
					&& bootStrappedServices.All(s => s != requiredService.Key.ServiceName));

			return query.Select(s => s.Key).ToList();
		}
        static string FindRootPath(List<string> paths)
        {
            var separator = Path.DirectorySeparatorChar;
            var commonPath = String.Empty;
            var separatedPath = paths
                .First(str => str.Length == paths.Max(st2 => st2.Length))
                .Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries)
                .ToList();

            foreach (var pathSegment in separatedPath)
            {
                if (commonPath.Length == 0 && paths.All(str => str.StartsWith(pathSegment)))
                {
                    commonPath = pathSegment;
                }
                else if (paths.All(str => str.StartsWith(commonPath + separator + pathSegment)))
                {
                    commonPath += separator + pathSegment;
                }
                else
                {
                    break;
                }
            }

            return commonPath;
        }
Example #6
0
 private void For(int length, List<int[,]> maps, List<int> dileiPosition, List<int> notDileiPosition)
 {
     for (int i = 0; i < length; i++)
     {
         if (maps.All(map => map[0, i] > Safe)) dileiPosition.Add(i + 1);
         else if (maps.All(map => map[0, i] == Safe)) notDileiPosition.Add(i + 1);
     }
 }
Example #7
0
        public bool Launch()
        {
            var workers = new List<ChiefWorkerProcess>();
            try
            {
                _log.Debug("Loading settings...");
                var configuration = ConfigurationHelper.Load(_options.Configuration);
                _log.Debug("Starting machinery...");
                try
                {
                    foreach (var workerSettings in configuration)
                    {
                        var workerProcess = new ChiefWorkerProcess(_log, workerSettings);
                        workers.Add(workerProcess);
                        workerProcess.LaunchAsync();
                    }

                    while (workers.All(worker => worker.IsAlive && !worker.ReadyToAcceptClients))
                    {
                        Thread.Sleep(1000);
                    }

                    _log.Debug("Server(s) started...");
                    ReadyToAcceptClients();

                    while (!IsExitOnDemand() && workers.All(worker => worker.IsAlive))
                    {
                        Thread.Sleep(3000);
                    }

                    if (!workers.All(worker => worker.IsAlive))
                    {
                        var error = string.Format("The following sources does not work: {0}",
                            string.Join(
                                ", ",
                                workers
                                    .Where(worker => !worker.IsAlive)
                                    .Select(worker => worker.Name)
                                    .ToArray()));
                        _log.Error(error);
                        ErrorOccured(error);
                        return false;
                    }
                }
                finally
                {
                    workers.ForEach(item => item.Dispose());
                }
                return true;
            }
            catch (Exception unhandledException)
            {
                _log.Error(unhandledException);
                return false;
            }
        }
        public List<Ship> PlaceShips(List<int> sizes, int boardHeight, int boardWidth)
        {
            Height = boardHeight;
            Width = boardWidth;

            //var ship = new Ship
            //{
            //    Direction = Direction.Vertical,
            //    Length = 3,
            //    Location = new Point(0, 0)
            //};

            //var newShip = new Ship
            //{
            //    Direction = Direction.Vertical,
            //    Length = 3,
            //    Location = new Point(0, 3)
            //};

            //Console.WriteLine(ship.Neighbour(newShip));

            var ships = new List<Ship>();

            for (int i = 0; i < sizes.Count; i++)
            {
                var size = sizes[i];

                // Create new ship
                var newShip = new Ship
                {
                    Direction = Helpers.Random.Next(0, 1 + 1) == 0 ? Direction.Horizontal : Direction.Vertical,
                    Length = size,
                    Location = Helpers.RandomPoint(boardHeight, boardWidth)
                };

                // Check that it doesn't overlap with any other
                bool ok = ships.All(ship => !ship.Overlaps(newShip));
                ok = ok && ships.All(ship => !ship.Neighbour(newShip));

                // Do not advance to next ship,
                // repeat the same one next iteration
                if (!ok ||
                    newShip.EndPoint.X > boardWidth ||
                    newShip.EndPoint.Y >= boardHeight)
                    i--;
                else
                    ships.Add(newShip);
            }

            return ships;
        }
        public void AutofacWillDisposeAllItemsInLifetime()
        {
            List<DisposableObject> list = new List<DisposableObject>();
            using(var scope = TestSetup.Container.BeginLifetimeScope())
            {
                for (int i = 0; i < 100; i++)
                {
                    list.Add(scope.Resolve<DisposableObject>());
                }
                Assert.True(list.All(item => !item.IsDisposed));
            }

            Assert.True(list.All(item => item.IsDisposed));
        }
        public static List<Def> GetResearchRequirements( this RecipeDef recipeDef )
        {
            var researchDefs = new List< Def >();

            if( recipeDef.researchPrerequisite != null )
            {
                // Basic requirement
                researchDefs.Add( recipeDef.researchPrerequisite );

                // Advanced requirement
                var advancedResearchDefs = ResearchController.AdvancedResearch.Where( a => (
                    ( a.IsRecipeToggle )&&
                    ( !a.HideDefs )&&
                    ( a.recipeDefs.Contains( recipeDef ) )
                ) ).ToList();

                if( !advancedResearchDefs.NullOrEmpty() )
                {
                    foreach( var a in advancedResearchDefs )
                    {
                        researchDefs.Add( a );
                    }
                }

            }

            // Get list of things recipe is used on
            var thingsOn = new List< ThingDef >();
            var recipeThings = DefDatabase< ThingDef >.AllDefsListForReading.Where( t => (
                ( t.recipes != null )&&
                ( !t.IsLockedOut() )&&
                ( t.recipes.Contains( recipeDef ) )
            ) ).ToList();

            if( !recipeThings.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeThings );
            }

            // Add those linked via the recipe
            if( !recipeDef.recipeUsers.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeDef.recipeUsers );
            }

            // Make sure they all have hard requirements
            if(
                ( !thingsOn.NullOrEmpty() )&&
                ( thingsOn.All( t => t.HasResearchRequirement() ) )
            )
            {
                foreach( var t in thingsOn )
                {
                    researchDefs.AddRange( t.GetResearchRequirements() );
                }
            }

            // Return the list of research required
            return researchDefs;
        }
Example #11
0
        private List<Change> GetInsertions(string right, List<string> subMatches)
        {
            var indexesMathched = new List<int>();
            //detect
            foreach (var sub in subMatches)
            {
                var index = right.LastIndexOf(sub);

                for (var i = index; i < index + sub.Count(); i++)
                    indexesMathched.Add(i);
            }
            //calculate 
            var changes = new List<Change>();
            for (var i = 0; i < right.Count(); i++)
            {
                if (indexesMathched.All(a => a != i))
                    changes.Add(new Change
                    {
                        ChangeType = ChangeType.Insert,
                        Index = i,
                        Character = right[i]
                    });
            }
            return changes;
        }
        public ShipmentCancelValidator(IAlfrescoHttpClient alfrescoHttpClient, IIdentityUser identityUser)
        {
            RuleFor(o => o)
            .Cascade(CascadeMode.StopOnFirstFailure)
            .MustAsync(async(context, cancellationToken) =>
            {
                _groupPaging = await alfrescoHttpClient.GetPersonGroups(identityUser.Id);
                await context.NodeIds.ForEachAsync(async x => { _nodeEntries.Add(await alfrescoHttpClient.GetNodeInfo(x)); });

                return(_groupPaging != null && _nodeEntries?.Count != 0);
            })
            .WithName("Document")
            .WithMessage("Something went wrong with alfresco server.")
            .DependentRules(() =>
            {
                RuleFor(x => x)
                .Must(y => _groupPaging?.List?.Entries?.Any(q => q.Entry.Id == identityUser.RequestGroup) ?? false)
                .WithName(x => "Group")
                .WithMessage($"User isn't member of group {identityUser.RequestGroup}.");

                RuleFor(x => x)
                .Must(y => _nodeEntries?.All(q => q.Entry.NodeType.StartsWith("ssl:shipment")) ?? false)
                .WithName(x => "NodeIds")
                .WithMessage("Not all provided nodes are type of shipment.");
            });
        }
Example #13
0
		public IfStmt(Text.Span span, List<ConditionalStmt>/*!!*/ conditions)
			: base(span)
		{
			Debug.Assert(conditions != null && conditions.Count > 0);
			Debug.Assert(conditions.All((x) => x != null));
			this.conditions = conditions;
		}
        /// <summary>
        /// Alle Controller ermitteln die für das Projekt befunden werden können.
        /// </summary>
        public List<Type> GetAllProjectProxyController(ProxySettings proxySettings)
        {
            List<Type> allController = new List<Type>();

            //Alle Assemblies im aktuellen Projekt laden.
            var assemblies = Factory.CreateAssemblyManager().LoadAssemblies(proxySettings.WebProjectName, proxySettings.FullPathToTheWebProject);

            foreach (Assembly assembly in assemblies)
            {
                try
                {
                    //Nur die Assemblies heraussuchen in denen unser BasisAttribut für die Proxy Erstellung gesetzt wurde.
                    var types = assembly.GetTypes().Where(type  => type.GetMethods().Any(p => p.GetCustomAttributes(typeof (CreateProxyBaseAttribute), true).Any())).ToList();

                    foreach (Type type in types)
                    {
                        //Prüfen das jede Klasse (Controller) nur einmal unserer Liste hinzugefügt wird.
                        if (allController.All(p => p.AssemblyQualifiedName != type.AssemblyQualifiedName))
                        {
                            allController.Add(type);
                        }
                    }
                }
                catch(Exception exception)
                {
                    Trace.WriteLine("Fehler beim Auslesen der Assemblies: " + exception.Message);
                }
            }

            return allController;
        }
Example #15
0
        static int BruteForce()
        {
            var chrs = cipher.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            for (int i = 97; i <= 122; i++)
            {
                for (int j = 97; j <= 122; j++)
                {
                    for (int k = 97; k <= 122; k++)
                    {
                        var list = new List<int>();
                        for (int l = 0; l < chrs.Count; l = l + 3)
                        {
                            var item = i ^ chrs[l];
                            list.Add(item);   
                          if(l < chrs.Count -1)
                              list.Add(j ^ chrs[l + 1]);
                          if (l < chrs.Count - 1)
                            list.Add(k ^ chrs[l + 2]);   
                        }

                        if (list.All(IsChar))
                        {
                            Console.Out.WriteLine(string.Format("Get {0}{1}{2}", Convert.ToChar(i), Convert.ToChar(j), Convert.ToChar(k)));
                            return list.Sum();
                        }
                    }
                }
                
            }

            return 0;

        }
        public IEnumerable<TableInfo> GetTablesOrdered()
        {
            var notOrderedTables = new List<TableInfo>(Tables);

            int totalTablesCount = notOrderedTables.Count;
            int orderedTablesCount = 0;
            while (orderedTablesCount < totalTablesCount)
            {
                int orderedTablesCountBeforeIter = orderedTablesCount; // ensure we not in infinite loop...

                int i = 0;
                while (i < notOrderedTables.Count)
                {
                    var table = notOrderedTables[i];

                    var parentTables = TableRelations
                        .Where(x => x.FitsForTable(table.Name) && !x.IsExternal() && !x.IsSelfRelation() && x.Importance != RelationImportance.Low)
                        .Select(x => x.ParentTable);

                    if (parentTables.All(x => notOrderedTables.All(y => !string.Equals(y.Name, x, StringComparison.InvariantCultureIgnoreCase))))
                    {
                        notOrderedTables.RemoveAt(i);
                        orderedTablesCount++;
                        yield return table;
                    }
                    else
                    {
                        i++;
                    }
                }

                if (orderedTablesCountBeforeIter == orderedTablesCount) // ensure we not in infinite loop...
                    throw ThrowHelper.CantOrderTables(notOrderedTables.Select(x => x.Name));
            }
        }
Example #17
0
        static void MaximumEquality(int[] cars)
        {
            int moves = 0;
            int maxIndex, minIndex;
            List<int> c = cars.ToList();
            List<int> tempC = new List<int>();

            //Initial print
            Console.WriteLine(PrintList(c));

            while (true)
            {
                maxIndex = c.IndexOf(c.Max());
                minIndex = c.IndexOf(c.Min());

                //copy c to tempC by value
                tempC = new List<int>();
                tempC.AddRange(c);

                c[minIndex]++;
                c[maxIndex]--;
                if (tempC.All(c.Contains))
                    break;

                ++moves;
                Console.WriteLine(PrintList(c) + " move #" + moves);
            }
            var equalCars = c.GroupBy(i => i).OrderByDescending(grp => grp.Count()).Select(grp => grp.Count()).First();

            Console.WriteLine("Equal cars: {0}\nNumber of moves: {1}", equalCars, moves);
            Console.ReadLine();
        }
    static void Main()
    {
        string input = Console.ReadLine();
        int[] nums = input.Split(' ').Select(int.Parse).ToArray();

        var values = new List<int>();
        var diffs = new List<int>();
        for (int i = 0; i < nums.Length; i += 2)
        {
            values.Add(nums[i] + nums[i + 1]);
        }

        for (int i = 1; i < values.Count; i++)
        {
            diffs.Add(Math.Abs(values[i] - values[i - 1]));
        }

        if (values.All(o => o == values[0]))
        {
            Console.WriteLine("Yes, value={0}", values[0]);
        }
        else
        {
            Console.WriteLine("No, maxdiff={0}", diffs.Max());
        }
    }
Example #19
0
        /// <summary>
        /// Returns collection of Matches for every possible match with the cards in this deck
        /// and the card argument.
        /// Note that a single card may be a part of multiple potential matches,
        /// in which case it will appear in multiple Matches in the returned List.
        /// </summary>
        /// <param name="card">Card to be compared to other cards in this deck for matches.</param>
        public List<Match> GetAllMatches(Card card)
        {
            var matches = new List<Match>();

            for (var i = 0; i < Cards.Count; i++)
            {
                for (var j = i + 1; j < Cards.Count; j++)
                {
                    var firstCard = Cards[i];
                    var secondCard = Cards[j];

                    if (firstCard == secondCard || firstCard == card || secondCard == card)
                        continue;

                    if (!Card.IsMatch(firstCard, secondCard, card))
                        continue;

                    var match = new Match();
                    match.Cards[0] = firstCard;
                    match.Cards[1] = secondCard;
                    match.Cards[2] = card;

                    if (matches.All(x => x.Cards != match.Cards))
                        matches.Add(match);
                }
            }

            return matches;
        }
Example #20
0
        /// <summary>
        /// 获取某个项下所带的附件集合(去重)
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public List<PnRegDTO> GetPnRegsByItem(int itemId)
        {
            var result = new List<PnRegDTO>();
            var installControllers = _unitOfWork.CreateSet<InstallController>().Where(p => p.ItemId == itemId).ToList();
            var pnRegs = _unitOfWork.CreateSet<PnReg>().ToList();
            installControllers.ForEach(p =>
            {
                if (result.All(l => l.Id != p.PnRegId))
                {
                    var pnReg = pnRegs.FirstOrDefault(l => l.Id == p.PnRegId);
                    if (pnReg != null)
                    {
                        var dbItem = _unitOfWork.CreateSet<Item>().ToList().FirstOrDefault(l => l.Id == pnReg.ItemId);

                        var pn = new PnRegDTO
                        {
                            Id = pnReg.Id,
                            Description = pnReg.Description,
                            IsLife = pnReg.IsLife,
                            Pn = pnReg.Pn,
                            ItemId = pnReg.ItemId,
                        };
                        if (dbItem != null) pn.ItemNo = dbItem.ItemNo;
                        result.Add(pn);
                    }
                }
            });
            return result;
        }
        public SqlServerEndpoint(string name, string connectionString, bool includeSystemDatabases, IEnumerable<Database> includedDatabases, IEnumerable<string> excludedDatabaseNames)
            : base(name, connectionString)
        {
            var excludedDbs = new List<string>();
            var includedDbs = new List<Database>();

            if (excludedDatabaseNames != null)
            {
                excludedDbs.AddRange(excludedDatabaseNames);
            }

            if (includedDatabases != null)
            {
                includedDbs.AddRange(includedDatabases);
            }

            if (includeSystemDatabases && includedDbs.Any())
            {
                IEnumerable<Database> systemDbsToAdd = Constants.SystemDatabases
                                                                .Where(dbName => includedDbs.All(db => db.Name != dbName))
                                                                .Select(dbName => new Database {Name = dbName});
                includedDbs.AddRange(systemDbsToAdd);
            }
            else if (!includeSystemDatabases)
            {
                IEnumerable<string> systemDbsToAdd = Constants.SystemDatabases
                                                              .Where(dbName => excludedDbs.All(db => db != dbName));
                excludedDbs.AddRange(systemDbsToAdd);
            }

            IncludedDatabases = includedDbs.ToArray();
            ExcludedDatabaseNames = excludedDbs.ToArray();
        }
Example #22
0
        public async Task<IEnumerable<Book>> GetByName(string name)
        {
            var result = new List<Book>();
            if (name.IndexOf(" ", StringComparison.Ordinal) != 0)
            {
                var terms = name.Split(' ');
                foreach (var term in terms)
                {
                    var termLocal = term.ToLowerInvariant();
                    var matches =
                        await _context.Books.Where(x => x.Name.ToLowerInvariant().Contains(termLocal)).ToListAsync();
                    if (!matches.Any()) continue;

                    foreach (var match in matches.Where(match => result.All(x => x.BookId != match.BookId)))
                    {
                        result.Add(match);
                    }
                }
            }
            else
            {
                return await _context.Books.Where(x => x.Name.ToLowerInvariant().Contains(name)).ToListAsync();
            }

            return result;
        }
Example #23
0
        public void LoggingLevelSwitchDynamicallyChangesLevel()
        {
            var events = new List<LogEvent>();
            var sink = new DelegatingSink(events.Add);

            var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);

            var log = new LoggerConfiguration()
                .MinimumLevel.ControlledBy(levelSwitch)
                .WriteTo.Sink(sink)
                .CreateLogger()
                .ForContext<LoggerTests>();

            log.Debug("Suppressed");
            log.Information("Emitted");
            log.Warning("Emitted");

            // Change the level
            levelSwitch.MinimumLevel = LogEventLevel.Error;

            log.Warning("Suppressed");
            log.Error("Emitted");
            log.Fatal("Emitted");

            Assert.Equal(4, events.Count);
            Assert.True(events.All(evt => evt.RenderMessage() == "Emitted"));
        }
Example #24
0
        private static dynamic ReadJsonArray(JsonReader reader)
        {
            List<dynamic> vals = new List<dynamic>();

            while (reader.Read())
            {
                if (reader.TokenType == JsonToken.EndArray)
                {
                    break;
                }
                else
                {
                    vals.Add(ReadJsonValue(reader, true));
                }
            }

            if (vals.Count != 0 && vals.All(v => v is IDictionary<string, object>))
            {
                if (vals.OfType<IDictionary<string, object>>().All(v => v.ContainsKey("Key") && v.ContainsKey("Value")))
                {
                    ExpandoObject obj = new ExpandoObject();

                    foreach (IDictionary<string, object> dict in vals.OfType<IDictionary<string, object>>())
                    {
                        ((IDictionary<string, object>)obj).Add(dict["Key"].ToString(), dict["Value"]);
                    }

                    return obj;
                }
            }

            return vals;
        }
Example #25
0
    public Spell FindSpell(List<Element> elements){
        
        foreach(Spell spell in _spells){
            
            if(spell.Elements.Count != elements.Count){
                continue;
            }
            bool spellAvailable = true;
            foreach(Element el in elements)
            {
                if (!el.Available)
                    spellAvailable = false;

            }
            if (!spellAvailable)
                continue;
            bool hasElements = elements.All(el => spell.Elements.Contains(el));
            if(hasElements){
                
                    return spell;
            }
        }

        return null;
    }
            public void ConnectionsWithTheSameConnectionIdSSECloseGracefully()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<MyGroupEchoConnection>("/echo", config);

                        config.Resolver.Register(typeof(IProtectedData), () => new EmptyProtectedData());
                    });

                    string id = Guid.NewGuid().ToString("d");

                    var tasks = new List<Task>();

                    for (int i = 0; i < 1000; i++)
                    {
                        tasks.Add(ProcessRequest(host, "serverSentEvents", id));
                    }

                    ProcessRequest(host, "serverSentEvents", id);

                    Task.WaitAll(tasks.ToArray());

                    Assert.True(tasks.All(t => !t.IsFaulted));
                }
            }
Example #27
0
        public void UpdateData(ILongPollServerUpdates longPollServerUpdates)
        {
            if (longPollServerUpdates.FriendOnlineStatuses.Any())
            {
                _friendsService.UpdateOnline(longPollServerUpdates.FriendOnlineStatuses);
            }

            if (longPollServerUpdates.ReceivedMessages.Any())
            {
                _oldMessageIds = _dialogMessagesRepo.GetIncomingUnreadedMessages()
                    .Select(x => x.VkId)
                    .ToList();

                _dialogMessagesRepo.Add(_sessionInfoRepo.UserId, longPollServerUpdates.ReceivedMessages);

                if(_dialogMessagesRepo.GetIncomingUnreadedMessages().Any(x => _oldMessageIds.All(y => y != x.VkId)))
                    Task.Run(() => _mp3Player.Play());

                Task.Run(() => _dialogMessagesService.SaveToDB());
            }

            if (longPollServerUpdates.DroppedMessageFlags.Any())
            {
                _dialogMessagesRepo.DropFlags(longPollServerUpdates.DroppedMessageFlags);
                Task.Run(() => _dialogMessagesService.SaveToDB());
            }
        }
Example #28
0
        /// <summary>
        /// Execute KMeans algorithm with given points and centroids.
        /// </summary>
        /// <param name="vectorPoints">List of all points (as Vectors) available</param>
        /// <param name="vectorCentroids">List of centroids</param>
        /// <returns>List of the calculated centroids</returns>
        public static List<Vector2D> DoKMeans(List<Vector2D> vectorPoints, List<Vector2D> vectorCentroids)
        {
            var movedCentroids = new List<Vector2D>();
            var oldCentroids = new List<Vector2D>();
            vectorCentroids.ForEach((e)=>oldCentroids.Add(e.Copy()));
            var finish = true;

            var loopCount = 0;

            //TODO Abbruchkriterium....
            while (finish)
            {
                var pointsToCentroids = MapPointsToNearestCentroids(vectorPoints, oldCentroids);
                movedCentroids = MoveCentroids(pointsToCentroids);

                finish = !movedCentroids.All(oldCentroids.Contains);

                oldCentroids.Clear();
                movedCentroids.ForEach((e)=>oldCentroids.Add(e.Copy()));
                loopCount++;
                finish = false;
            }

            return movedCentroids;
        }
Example #29
0
        public void LoadParentMaps(List<INode> maps, Guid mapId)
        {
            var viewModelMaps = new List<SuperGraph.ViewModel.Node>();

            foreach (var map in maps)
            {
                if (viewModelMaps.All(q => q.Proxy.Id != map.Id))
                {
                    var viewModelNode = new SuperGraph.ViewModel.Node(MapManager);
                    viewModelNode.LoadNode(null, map);

                    viewModelMaps.Add(viewModelNode);
                }
            }

            if (viewModelMaps.Count > 1)
            {
                var breadcrumb = new MultiBreadcrumbItem(viewModelMaps);
                if (mapId != Guid.Empty)
                {
                    var currentMap = breadcrumb.Items.FirstOrDefault(q => q.Node.Proxy.Id == mapId);
                    if (currentMap != null)
                    {
                        breadcrumb.SelectedBreadcrumb = currentMap;
                    }
                }
                Breadcrumbs.BreadcrumbTrail.Insert(breadcrumb, _parentIndex);
            }
            else if (viewModelMaps.Count == 1)
            {
                var breadcrumb = new BreadcrumbItem(viewModelMaps[0]);
                Breadcrumbs.BreadcrumbTrail.Insert(breadcrumb, _parentIndex);
            }
        }
    public HtmlString AddPrice(List<Price> oldPrices, Price newPrice)
    {
      List<Price> result = new List<Price>();
      DateTime endingDatePrevious = newPrice.StartingDate.AddDays(-1);

      if (oldPrices != null)
      {
        if (oldPrices.All(price => !price.EndingDate.HasValue || newPrice.StartingDate > price.EndingDate.Value))
        {
          Price currentPrice = oldPrices.FirstOrDefault(price => !price.EndingDate.HasValue);
          if (currentPrice != null)
          {
            currentPrice.EndingDate = endingDatePrevious;
          }
        }
        else
        {
          Price currentPrice = oldPrices.FirstOrDefault(price => price.EndingDate > newPrice.StartingDate);
          DateTime? oldEndingDate = currentPrice.EndingDate;
          currentPrice.EndingDate = endingDatePrevious;
          if (newPrice.EndingDate.HasValue && oldEndingDate > newPrice.EndingDate.Value)
          {
            result.Add(new Price() { Article = currentPrice.Article, BasePrice = currentPrice.BasePrice, StartingDate = newPrice.EndingDate.Value.AddDays(1), EndingDate = oldEndingDate });
          }
        }

        result.AddRange(oldPrices);
      }

      result.Add(newPrice);

      return result.ToHtmlJson();
    }
Example #31
0
        private List<Change> GetRemoves(string wrong, List<string> subMatches)
        {
            var indexesMathched = new List<int>();
            //detect
            foreach (var sub in subMatches)
            {
                var index = wrong.LastIndexOf(sub);

                for (var i = index; i < index + sub.Count(); i++)
                    indexesMathched.Add(i);
            }
            //calculate 
            var changes = new List<Change>();
            for (var i = 0; i < wrong.Count(); i++)
            {
                //if(i not in indexesMathched)
                if (indexesMathched.All(a => a != i))
                    changes.Add(new Change
                    {
                        ChangeType = ChangeType.Remove,
                        Index = i,
                        Character = wrong[i]
                    });
            }
            return changes;
        }
Example #32
0
        public void PokeNoNamespace()
        {
            const string query = "//variable/@Name";
            const string value = "Mert";

            XmlDocument xmlDocument = ExecuteXmlPoke(query: query, value: value);

            List <XmlAttribute> nodes = xmlDocument.SelectNodes(query)?.Cast <XmlAttribute>().ToList();

            Assert.True(nodes?.Count == 3, $"There should be 3 <variable /> elements with a Name attribute {Environment.NewLine}{xmlDocument.OuterXml}");

            Assert.True(nodes?.All(i => i.Value.Equals(value)), $"All <variable /> elements should have Name=\"{value}\" {Environment.NewLine}{xmlDocument.OuterXml}");
        }
Example #33
0
 public async Task <List <TRslt> > MulticastAsync <TRslt, TReq, TRspns>(AbstractRequestInstructions <TRslt, TReq, TRspns> request,
                                                                        List <IHost> hosts, IAggregator <TRslt> gatherer) where TReq : IRequest
 {
     if (GetTypeOfWorkload(request) == WorkloadType.Http)
     {
         if (hosts?.All(x => x.GetType() == typeof(HttpHost)) ?? false)
         {
             return(await(new HttpWorkload().DoHttpRequestForSeveralRecipientsAsync(request as HttpRequestInstructions <TRslt>,
                                                                                    hosts.Select(x => new Uri(x.Host.ToString())).ToList(), gatherer)));
         }
     }
     else
     {
         return(await(new BaseWorkload <TRslt, TReq, TRspns>().DoAsync(request, hosts, gatherer).ConfigureAwait(false)));
     }
     throw new NotImplementedException("Unable to parse the type of workload");
 }
Example #34
0
        public void PokeWithNamespace()
        {
            const string query = "//s:variable/@Name";

            XmlDocument xmlDocument = ExecuteXmlPoke(
                query: query,
                useNamespace: true,
                value: "Mert");

            XmlNamespaceManager ns = new XmlNamespaceManager(xmlDocument.NameTable);

            ns.AddNamespace("s", XmlNamespaceUsedByTests);

            List <XmlAttribute> nodes = xmlDocument.SelectNodes(query, ns)?.Cast <XmlAttribute>().ToList();

            Assert.True(nodes?.Count == 3, $"There should be 3 <variable /> elements with a Name attribute {Environment.NewLine}{xmlDocument.OuterXml}");

            Assert.True(nodes?.All(i => i.Value.Equals("Mert")), $"All <variable /> elements should have Name=\"Mert\" {Environment.NewLine}{xmlDocument.OuterXml}");
        }
Example #35
0
        private void updateTypeInfo()
        {
            if (pkm.VC && pkm.Format == 7)
            {
                EncounterMatch = Legal.getRBYStaticTransfer(pkm.Species);
            }

            if (pkm.GenNumber <= 2 && pkm.TradebackStatus == TradebackType.Any && EncountersGBMatch?.All(e => e.Generation != pkm.GenNumber) == true)
            {
                // Example: GSC Pokemon with only possible encounters in RBY, like the legendary birds
                pkm.TradebackStatus = TradebackType.WasTradeback;
            }

            MatchedType = Type = (EncounterOriginalGB ?? EncounterMatch ?? pkm.Species)?.GetType();
            var bt = Type.GetTypeInfo().BaseType;

            if (bt != null && !(bt == typeof(Array) || bt == typeof(object) || bt.GetTypeInfo().IsPrimitive)) // a parent exists
            {
                Type = bt;                                                                                    // use base type
            }
        }
Example #36
0
        public override bool Work()
        {
            var result = false;

            TargetFilePath = GetLastUpdateFilePath();
            if (string.IsNullOrEmpty(TargetFilePath) ||
                !System.IO.File.Exists(TargetFilePath))
            {
                logger.Log("EBデータ取込:取込対象となるファイルがありません。");
                return(result);
            }

            List <FileInformation> importResult = null;

            try
            {
                var setting = Screen.Util.GetEBFileSetting(Login, Setting.ImportSubType);
                if (setting == null)
                {
                    logger.Log("EBファイル設定 の取得に失敗しました。");
                    return(result);
                }

                importResult = Importer.ReadAndSaveFiles(new List <FileInformation> {
                    new FileInformation(0, TargetFilePath, setting)
                });
            }
            catch (Exception ex)
            {
                logger.Log($"取込処理に失敗しました。{Environment.NewLine}{ex.Message}");
            }
            // eb data 取込 の メッセージング
            // フォーマットエラーなど
            result = importResult?.All(x => x.Result == EbData.ImportResult.Success) ?? false;
            return(result);
        }
        public static bool IsPluginCompatible(System.Xml.XmlElement rootNode)
        {
            XmlNode versionNode = rootNode.SelectSingleNode("CompatibleVersion/Items");

            if (versionNode == null)
            {
                return(false);
            }
            var minRequiredVersion = new Version(MinRequiredVersionDefault);
            var designedForVersion = new Version(1, 0, 0, 0);

            foreach (XmlNode node in versionNode.ChildNodes)
            {
                XmlNode minVersionNode      = node.SelectSingleNode("MinRequiredVersion");
                XmlNode designedVersionNode = node.SelectSingleNode("DesignedForVersion");
                if (minVersionNode != null)
                {
                    minRequiredVersion = new Version(minVersionNode.InnerText);
                }
                if (designedForVersion == null)
                {
                    return(false);
                }
                designedForVersion = new Version(designedVersionNode.InnerText);
                break; //Break cause we only check first instance??
            }

            CheckLoadedAssemblies();
            Version lastFullyBreakingVersion;

            if (CompareVersions(AppVersion, minRequiredVersion) < 0 ||               // MP version is too old
                (SubSystemVersions.TryGetValue("*", out lastFullyBreakingVersion) &&
                 CompareVersions(lastFullyBreakingVersion, designedForVersion) > 0)) // MP breaking version after plugin released
            {
                return(false);
            }

            List <string> subsystemsUsed = new List <string>();
            XmlNode       subsystemNode  = rootNode.SelectSingleNode("SubSystemsUsed/Items");

            if (subsystemNode == null)
            {
                return(false);
            }
            foreach (XmlNode node in subsystemNode.ChildNodes)
            {
                XmlAttribute nameAttrib = node.Attributes["Name"];
                if (nameAttrib == null || string.IsNullOrEmpty(nameAttrib.InnerText))
                {
                    continue;
                }
                subsystemsUsed.Add(nameAttrib.InnerText);
            }

            if (subsystemsUsed.Count == 0)
            {
                return(true);
            }

            Version ver;

            // Have all used subsystem known versions and prior to the one the plugin was designed for?
            return(subsystemsUsed.All(attr => SubSystemVersions.TryGetValue(attr, out ver) && CompareVersions(ver, designedForVersion) <= 0));
        }
Example #38
0
        private async Task <List <ValidacionesRequisicionViewModel> > AddOrUpdateAsync(
            int idRequisicion,
            string userName,
            List <ValidaRequisicion> validaciones)
        {
            validaciones = this.TopeSalarial(validaciones);

            var saved = await this.validacionRepository.ListAsync(new ValidaRequisicionSpecification(idRequisicion));

            if ((bool)validaciones?.All(v => v.Id != 0) &&
                saved.Any() &&
                validaciones.Any() &&
                saved.Count() == validaciones.Count)
            {
                return(await this.UpdateAsync(idRequisicion, userName, validaciones).ConfigureAwait(false));
            }

            await this.UpdateAsync(
                idRequisicion,
                userName,
                validaciones.Where(v => v.Id != 0 && v.EstadoValidacion != EEstadoValidacion.Pendiente).ToList())
            .ConfigureAwait(false);

            foreach (var validaRequisicion in saved.Where(
                         v => v.Id != 0 && v.EstadoValidacion == EEstadoValidacion.Pendiente))
            {
                validaRequisicion.Active = false;
                await this.validacionRepository.UpdateAsync(validaRequisicion).ConfigureAwait(false);
            }

            foreach (var validacion in validaciones.Where(
                         v => v != null && (v.Id == 0 || v.EstadoValidacion == EEstadoValidacion.Pendiente)))
            {
                validacion.RequisicionId = idRequisicion;
                validacion.CreatedBy     = userName;
                validacion.Comentario    = null;
                validacion.Id            = 0;
                await this.validacionRepository.AddAsync(validacion).ConfigureAwait(false);
            }

            saved = await this.validacionRepository.ListAsync(new ValidaRequisicionSpecification(idRequisicion));

            var actual = validaciones.FirstOrDefault(v => v.EstadoValidacion == EEstadoValidacion.Actual);

            if (actual != null)
            {
                var toEdit = saved.FirstOrDefault(
                    v => v.AprobadorUserName == actual.AprobadorUserName &&
                    v.NivelValidacion == actual.NivelValidacion);

                toEdit.EstadoValidacion = EEstadoValidacion.Actual;

                await this.validacionRepository.UpdateAsync(toEdit);
            }

            validaciones = await this.validacionRepository.ListAsync(new ValidaRequisicionSpecification(idRequisicion));

            var result = this.mapper.Map <List <ValidacionesRequisicionViewModel> >(validaciones);

            return(result);
        }
Example #39
0
        public static async Task <IAnalyzerResult> Analyze(ApiToken apiToken, StructuredQuery query, string[] queryParts)
        {
            query = QueryBuilder.RemoveProject(query);
            query = QueryBuilder.RemoveSummarize(query);
            var        isExceptionsQuery = query.FirstOrDefault()?.Trim().StartsWith("exceptions", StringComparison.OrdinalIgnoreCase) == true;
            QueryGroup queryGroup;

            var whereQuery = @"
                | project itemCount, message = strcat(outerMessage, ' \n\n ', customDimensions['AdditionalErrorDetails'], ' \n\n ', customDimensions['additionalDetails'])
                | project itemCount, message = replace(@'[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}', '[GUID]', message) 
                | project itemCount, message = replace(@'(^|[ ''])(http:|https:)*[/]{1,2}(.*?)([ ]|$|\n)', ' [URL] ', message)
                | project itemCount, message = replace(@'[0-9]', '[X]', message)
                | where message !contains 'username' or message !contains 'password' 
                | summarize sum(itemCount) by message
                | order by sum_itemCount desc
                | take 20";

            if (isExceptionsQuery)
            {
                queryGroup = new QueryGroup(query);
                queryGroup.AddParts(queryParts);
                queryGroup.Append(QueryBuilder.Parse(whereQuery));
            }
            else
            {
                var exceptionsQuery = QueryBuilder.Parse(
                    $@"
                exceptions
                | {query.First(q => q.Contains("timestamp >"))}
                {whereQuery}");

                queryGroup = new QueryGroup(exceptionsQuery);
                queryGroup.Replace(query.First().Trim(), query);
                queryGroup.AddParts(queryParts);
            }

            var queryString = queryGroup.ToString();
            var result      = await AppInsightsClient.GetTableQuery(apiToken, queryString);

            result.Columns[0].Name = "Exception message";
            result.Columns[1].Name = "Count";

            foreach (var row in result.Rows)
            {
                var rowText     = (string)row[0];
                var commandText = ((string)row[0]).Trim();

                rowText = rowText.Replace("[X]", "X");
                rowText = Regex.Replace(rowText, "[X]+", "X");

                var lines = new List <string>();

                foreach (var line in Regex.Split(rowText, @"\n").SelectMany(line => Regex.Split(Regex.Replace(line, @"\. ", ".. "), @"\. ")))
                {
                    var trimmedLine = Regex.Replace(line, @"^[ ]*\[[A-Z]+\][ ]*", "").Trim();
                    if (!string.IsNullOrWhiteSpace(trimmedLine) && lines.All(l => l != trimmedLine))
                    {
                        lines.Add(trimmedLine);
                    }
                }

                rowText = string.Join("\n", lines);
                row[0]  = rowText.Trim();

                var matches = Regex.Matches(commandText, @"(^|\])(.*?)($|\[)");

                if (matches.Any(match => match.Groups[2].Length > 10))
                {
                    commandText = matches
                                  .First(match => match.Groups[2].Length > 10)
                                  .Groups[2].Value.Trim();
                }

                commandText = commandText.Replace("'", @"\'");
                row.Add($"where outerMessage contains '{commandText}' or customDimensions['AdditionalErrorDetails'] contains '{commandText}' or customDimensions['additionalDetails'] contains '{commandText}'");
                row.Add($"where outerMessage !contains '{commandText}' and customDimensions['AdditionalErrorDetails'] !contains '{commandText}' and customDimensions['additionalDetails'] !contains '{commandText}'");
            }

            return(new TableAnalyzerResult("Exception messages", true, result));
        }
Example #40
0
 public void CalculateAllHandlers()
 {
     _respond?.Invoke(_handlers.All(item => item.CalculateResult()));
 }
        /// <summary>
        /// Applies a transform to the columns of this <see cref="VertexBufferColumns"/>
        /// </summary>
        /// <param name="transform">A Mesh transformer object</param>
        /// <remarks>
        /// This is a one time operation.
        /// Once it's applied, skinning and morphing columns are removed, since they're baked
        /// into the position, normal and tangent columns.
        /// </remarks>
        private void _ApplyTransform(Transforms.IGeometryTransform transform)
        {
            Guard.NotNull(this.Positions, nameof(this.Positions), "Missing Positions column");
            if (this.Normals != null)
            {
                Guard.IsTrue(this.Positions.Count == this.Normals.Count, nameof(this.Normals), ERR_COLUMNLEN);
            }
            if (this.Tangents != null)
            {
                Guard.IsTrue(this.Positions.Count == this.Tangents.Count, nameof(this.Tangents), ERR_COLUMNLEN);
            }
            if (this.Colors0 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.Colors0.Count, nameof(this.Colors0), ERR_COLUMNLEN);
            }
            if (this.Colors1 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.Colors1.Count, nameof(this.Colors1), ERR_COLUMNLEN);
            }
            if (this.TexCoords0 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.TexCoords0.Count, nameof(this.TexCoords0), ERR_COLUMNLEN);
            }
            if (this.TexCoords1 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.TexCoords1.Count, nameof(this.TexCoords1), ERR_COLUMNLEN);
            }
            if (this.TexCoords2 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.TexCoords2.Count, nameof(this.TexCoords2), ERR_COLUMNLEN);
            }
            if (this.TexCoords3 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.TexCoords3.Count, nameof(this.TexCoords3), ERR_COLUMNLEN);
            }
            if (this.Joints0 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.Joints0.Count, nameof(this.Joints0), ERR_COLUMNLEN);
            }
            if (this.Joints1 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.Joints1.Count, nameof(this.Joints1), ERR_COLUMNLEN);
            }
            if (this.Weights0 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.Weights0.Count, nameof(this.Weights0), ERR_COLUMNLEN);
            }
            if (this.Weights1 != null)
            {
                Guard.IsTrue(this.Positions.Count == this.Weights1.Count, nameof(this.Weights1), ERR_COLUMNLEN);
            }

            // since the attributes we want to overwrite might be bound directly to the model's buffer
            // data, and we don't want to modify the source data, we isolate the columns to be overwritten.

            this.Positions = _IsolateColumn(this.Positions);
            this.Normals   = _IsolateColumn(this.Normals);
            this.Tangents  = _IsolateColumn(this.Tangents);
            this.Colors0   = _IsolateColumn(this.Colors0);

            // prepare animation data, if available

            var skinning = default(Transforms.SparseWeight8);

            Vector3[] morphPositions = null;
            Vector3[] morphNormals   = null;
            Vector3[] morphTangents  = null;
            Vector4[] morphColors0   = null; // we clone it because it can be affected by morph targets

            if (_MorphTargets != null)
            {
                if (_MorphTargets.All(item => item.Positions != null))
                {
                    morphPositions = new Vector3[this.MorphTargets.Count];
                }
                if (_MorphTargets.All(item => item.Normals != null))
                {
                    morphNormals = new Vector3[this.MorphTargets.Count];
                }
                if (_MorphTargets.All(item => item.Tangents != null))
                {
                    morphTangents = new Vector3[this.MorphTargets.Count];
                }
                if (_MorphTargets.All(item => item.Colors0 != null))
                {
                    morphColors0 = new Vector4[this.MorphTargets.Count];
                }
            }

            // loop over every vertex

            int vcount = this.Positions.Count;

            for (int i = 0; i < vcount; ++i)
            {
                if (this.Joints0 != null)
                {
                    if (this.Joints1 != null)
                    {
                        skinning = Transforms.SparseWeight8.Create(Joints0[i], Joints1[i], Weights0[i], Weights1[i]);
                    }
                    else
                    {
                        skinning = Transforms.SparseWeight8.Create(Joints0[i], Weights0[i]);
                    }
                }

                if (this.Positions != null)
                {
                    _FillMorphData(morphPositions, vc => vc.Positions[i]);
                    Positions[i] = transform.TransformPosition(Positions[i], morphPositions, skinning);
                }

                if (this.Normals != null)
                {
                    _FillMorphData(morphNormals, vc => vc.Normals[i]);
                    Normals[i] = transform.TransformNormal(Normals[i], morphNormals, skinning);
                }

                if (this.Tangents != null)
                {
                    _FillMorphData(morphTangents, vc => vc.Tangents[i]);
                    Tangents[i] = transform.TransformTangent(Tangents[i], morphTangents, skinning);
                }

                if (this.Colors0 != null)
                {
                    _FillMorphData(morphColors0, vc => vc.Colors0[i]);
                    Colors0[i] = transform.MorphColors(Colors0[i], morphColors0);
                }
            }

            // we've just applied the transform, so we make this a rigid geometry.

            _MorphTargets = null;

            Joints0  = null;
            Joints1  = null;
            Weights0 = null;
            Weights1 = null;
        }
 public bool HasListOfProviders(IEnumerable <Provider> providers) =>
 _providers.All(x => providers.Any(s => s.Id == x.Id));
Example #43
0
        private void _CompileToAstNodes(NodeModel node, List <AssociativeNode> resultList, bool isDeltaExecution, bool verboseLogging)
        {
            var inputAstNodes = new List <AssociativeNode>();

            foreach (int index in Enumerable.Range(0, node.InPortData.Count))
            {
                Tuple <int, NodeModel> inputTuple;

                if (node.TryGetInput(index, out inputTuple))
                {
                    int             outputIndexOfInput = inputTuple.Item1;
                    NodeModel       inputModel         = inputTuple.Item2;
                    AssociativeNode inputNode          = inputModel.GetAstIdentifierForOutputIndex(outputIndexOfInput);

#if DEBUG
                    Validity.Assert(inputNode != null,
                                    "Shouldn't have null nodes in the AST list");
#endif
                    inputAstNodes.Add(inputNode);
                }
                else
                {
                    PortData port = node.InPortData[index];
                    inputAstNodes.Add(
                        port.HasDefaultValue
                            ? AstFactory.BuildPrimitiveNodeFromObject(port.DefaultValue)
                            : new NullNode());
                }
            }

            //TODO: This should do something more than just log a generic message. --SJE
            if (node.State == ElementState.Error)
            {
                Log("Error in Node. Not sent for building and compiling");
            }

            if (isDeltaExecution)
            {
                OnAstNodeBuilding(node.GUID);
            }

#if DEBUG
            Validity.Assert(inputAstNodes.All(n => n != null),
                            "Shouldn't have null nodes in the AST list");
#endif

            var scopedNode = node as ScopedNodeModel;
            IEnumerable <AssociativeNode> astNodes =
                scopedNode != null
                    ? scopedNode.BuildAstInScope(inputAstNodes, verboseLogging, this)
                    : node.BuildAst(inputAstNodes);

            if (verboseLogging)
            {
                foreach (var n in astNodes)
                {
                    Log(n.ToString());
                }
            }

            if (null == astNodes)
            {
                resultList.AddRange(new AssociativeNode[0]);
            }
            else if (isDeltaExecution)
            {
                OnAstNodeBuilt(node.GUID, astNodes);
                resultList.AddRange(astNodes);
            }
            else //Inside custom node compilation.
            {
                bool notified = false;
                foreach (var item in astNodes)
                {
                    if (item is FunctionDefinitionNode)
                    {
                        if (!notified)
                        {
                            OnAstNodeBuilding(node.GUID);
                        }
                        notified = true;
                        //Register the function node in global scope with Graph Sync data,
                        //so that we don't have a function definition inside the function def
                        //of custom node.
                        OnAstNodeBuilt(node.GUID, new[] { item });
                    }
                    else
                    {
                        resultList.Add(item);
                    }
                }
            }
        }
        public void SystemTopicCreateGetUpdateDelete()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                this.InitializeClients(context);

                var location = this.ResourceManagementClient.GetLocationFromProvider();

                var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location);
                if (string.IsNullOrWhiteSpace(resourceGroup))
                {
                    resourceGroup = TestUtilities.GenerateName(EventGridManagementHelper.ResourceGroupPrefix);
                    this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup);
                }

                var systemTopicName = TestUtilities.GenerateName(EventGridManagementHelper.SystemTopicPrefix);

                // Temporarily commenting this out as this is not yet enabled for the new API version
                // var operationsResponse = this.EventGridManagementClient.Operations.List();

                var originalTagsDictionary = new Dictionary <string, string>()
                {
                    { "originalTag1", "originalValue1" },
                    { "originalTag2", "originalValue2" }
                };

                SystemTopic systemTopic = new SystemTopic()
                {
                    Location  = location,
                    Tags      = originalTagsDictionary,
                    TopicType = "microsoft.storage.storageaccounts",
                    Source    = "/subscriptions/5b4b650e-28b9-4790-b3ab-ddbd88d727c4/resourceGroups/testtobedeleted/providers/Microsoft.Storage/storageAccounts/trackedsource2stg" // "subscriptions/5b4b650e-28b9-4790-b3ab-ddbd88d727c4/resourceGroups/DevExpRg/providers/Microsoft.Storage/storageAccounts/devexpstg"
                };

                try
                {
                    var createSystemTopicResponse = this.EventGridManagementClient.SystemTopics.CreateOrUpdateAsync(resourceGroup, systemTopicName, systemTopic).Result;

                    Assert.NotNull(createSystemTopicResponse);
                    Assert.Equal(createSystemTopicResponse.Name, systemTopicName);

                    TestUtilities.Wait(TimeSpan.FromSeconds(5));

                    // Get the created systemTopic
                    var getSystemTopicResponse = this.EventGridManagementClient.SystemTopics.Get(resourceGroup, systemTopicName);
                    if (string.Compare(getSystemTopicResponse.ProvisioningState, "Succeeded", true) != 0)
                    {
                        TestUtilities.Wait(TimeSpan.FromSeconds(5));
                    }

                    getSystemTopicResponse = this.EventGridManagementClient.SystemTopics.Get(resourceGroup, systemTopicName);
                    Assert.NotNull(getSystemTopicResponse);
                    Assert.Equal("Succeeded", getSystemTopicResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase);
                    Assert.Equal(location, getSystemTopicResponse.Location, StringComparer.CurrentCultureIgnoreCase);

                    // Get all systemTopics created within a resourceGroup
                    IPage <SystemTopic> systemTopicsInResourceGroupPage = this.EventGridManagementClient.SystemTopics.ListByResourceGroupAsync(resourceGroup).Result;
                    var systemTopicsInResourceGroupList = new List <SystemTopic>();
                    if (systemTopicsInResourceGroupPage.Any())
                    {
                        systemTopicsInResourceGroupList.AddRange(systemTopicsInResourceGroupPage);
                        var nextLink = systemTopicsInResourceGroupPage.NextPageLink;
                        while (nextLink != null)
                        {
                            systemTopicsInResourceGroupPage = this.EventGridManagementClient.SystemTopics.ListByResourceGroupNextAsync(nextLink).Result;
                            systemTopicsInResourceGroupList.AddRange(systemTopicsInResourceGroupPage);
                            nextLink = systemTopicsInResourceGroupPage.NextPageLink;
                        }
                    }

                    Assert.NotNull(systemTopicsInResourceGroupList);
                    Assert.True(systemTopicsInResourceGroupList.Count() >= 1);
                    Assert.Contains(systemTopicsInResourceGroupList, t => t.Name == systemTopicName);
                    Assert.True(systemTopicsInResourceGroupList.All(ns => ns.Id.Contains(resourceGroup)));

                    IPage <SystemTopic> systemTopicsInResourceGroupPageWithTop = this.EventGridManagementClient.SystemTopics.ListByResourceGroupAsync(resourceGroup, null, 5).Result;
                    var systemTopicsInResourceGroupListWithTop = new List <SystemTopic>();
                    if (systemTopicsInResourceGroupPageWithTop.Any())
                    {
                        systemTopicsInResourceGroupListWithTop.AddRange(systemTopicsInResourceGroupPageWithTop);
                        var nextLink = systemTopicsInResourceGroupPageWithTop.NextPageLink;
                        while (nextLink != null)
                        {
                            systemTopicsInResourceGroupPageWithTop = this.EventGridManagementClient.SystemTopics.ListByResourceGroupNextAsync(nextLink).Result;
                            systemTopicsInResourceGroupListWithTop.AddRange(systemTopicsInResourceGroupPageWithTop);
                            nextLink = systemTopicsInResourceGroupPageWithTop.NextPageLink;
                        }
                    }

                    Assert.NotNull(systemTopicsInResourceGroupListWithTop);
                    Assert.True(systemTopicsInResourceGroupListWithTop.Count() >= 1);
                    Assert.Contains(systemTopicsInResourceGroupListWithTop, t => t.Name == systemTopicName);
                    Assert.True(systemTopicsInResourceGroupListWithTop.All(ns => ns.Id.Contains(resourceGroup)));

                    // Get all systemTopics created within the subscription irrespective of the resourceGroup
                    IPage <SystemTopic> systemTopicsInAzureSubscription = this.EventGridManagementClient.SystemTopics.ListBySubscriptionAsync(null, 100).Result;
                    var systemTopicsInAzureSubscriptionList             = new List <SystemTopic>();
                    if (systemTopicsInAzureSubscription.Any())
                    {
                        systemTopicsInAzureSubscriptionList.AddRange(systemTopicsInAzureSubscription);
                        var nextLink = systemTopicsInAzureSubscription.NextPageLink;
                        while (nextLink != null)
                        {
                            try
                            {
                                systemTopicsInAzureSubscription = this.EventGridManagementClient.SystemTopics.ListBySubscriptionNextAsync(nextLink).Result;
                                systemTopicsInAzureSubscriptionList.AddRange(systemTopicsInAzureSubscription);
                                nextLink = systemTopicsInAzureSubscription.NextPageLink;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                                break;
                            }
                        }
                    }

                    Assert.NotNull(systemTopicsInAzureSubscriptionList);
                    Assert.True(systemTopicsInAzureSubscriptionList.Count() >= 1);
                    Assert.Contains(systemTopicsInAzureSubscriptionList, t => t.Name == systemTopicName);

                    var replaceSystemTopicTagsDictionary = new Dictionary <string, string>()
                    {
                        { "replacedTag1", "replacedValue1" },
                        { "replacedTag2", "replacedValue2" }
                    };

                    // Replace the systemTopic
                    systemTopic.Tags = replaceSystemTopicTagsDictionary;
                    var replaceSystemTopicResponse = this.EventGridManagementClient.SystemTopics.CreateOrUpdateAsync(resourceGroup, systemTopicName, systemTopic).Result;

                    Assert.Contains(replaceSystemTopicResponse.Tags, tag => tag.Key == "replacedTag1");
                    Assert.DoesNotContain(replaceSystemTopicResponse.Tags, tag => tag.Key == "originalTag1");

                    // Update the systemTopic with tags & allow traffic from all ips
                    SystemTopicUpdateParameters systemTopicUpdateParameters = new SystemTopicUpdateParameters();
                    systemTopicUpdateParameters.Tags = new Dictionary <string, string>()
                    {
                        { "updatedTag1", "updatedValue1" },
                        { "updatedTag2", "updatedValue2" }
                    };

                    var updateSystemTopicResponse = this.EventGridManagementClient.SystemTopics.UpdateAsync(resourceGroup, systemTopicName, systemTopicUpdateParameters.Tags).Result;
                    Assert.Contains(updateSystemTopicResponse.Tags, tag => tag.Key == "updatedTag1");
                    Assert.DoesNotContain(updateSystemTopicResponse.Tags, tag => tag.Key == "replacedTag1");
                }
                finally
                {
                    // Delete systemTopic
                    this.EventGridManagementClient.SystemTopics.DeleteAsync(resourceGroup, systemTopicName).Wait();
                }
            }
        }
Example #45
0
        public ActionResult Detail(ApplicationUser user, int?id)
        {
            if (!id.HasValue)
            {
                return(Request.IsAjaxRequest() ? null : RedirectToAction("Index"));
            }
            var material = _materialRepository.FindById(id.Value);

            if (material == null)
            {
                return(HttpNotFound());
            }

            ViewBag.WishList = user?.WishList;

            ViewBag.IsStudent = user?.Type == Type.Student;

            var periods   = new List <MaterialReservationDetailsView>();
            var hulpLijst = new List <Reservation>();

            material.Identifiers.ToList().ForEach(i => {
                foreach (var reservatieDetail in i.ReservationDetails.Where(reservatieDetail => hulpLijst.All(r => r.Id != reservatieDetail.Reservation.Id))
                         .Where(reservatieDetail => reservatieDetail.Reservation.StartDate >= DateTime.Now))
                {
                    hulpLijst.Add(reservatieDetail.Reservation);
                    periods.Add(new MaterialReservationDetailsView(reservatieDetail,
                                                                   reservatieDetail.Reservation.Details.Count(d => d.MaterialIdentifier.Material == material),
                                                                   _reservationRepository));
                }
            });

            ViewBag.ShowReturnButton = !Request.IsAjaxRequest();
            var mvm = new MaterialViewModel(material, periods);

            return(Request.IsAjaxRequest() ? (ActionResult)PartialView(mvm) : View(mvm));
        }
        public async Task <List <DispatchChannel> > ConfigureDispatchChannels(List <Dispatch> dispatches, List <DeliveryPlan> deliveryPlans, List <Question> preFillQuestions)
        {
            List <DispatchChannel> dispatchChannels = new List <DispatchChannel>();

            foreach (Dispatch dispatch in dispatches)
            {
                DeliveryPlan         deliveryPlan   = deliveryPlans.Find(x => x.id == dispatch.DeliveryPlanId);
                List <StaticPrefill> staticPrefills = preFillQuestions
                                                      .Where(x => x.DisplayLocation?.Contains(dispatch.QuestionnaireName, StringComparer.InvariantCultureIgnoreCase) ?? false)?
                                                      .Select(x => new StaticPrefill {
                    Note = x.Note, PrefillValue = null, QuestionId = x.Id
                })?
                                                      .ToList() ?? new List <StaticPrefill>();
                DispatchChannel dispatchChannel = new DispatchChannel
                {
                    ChannelDetails = new ChannelDetails
                    {
                        Email = new Channel
                        {
                            IsValid    = deliveryPlan?.schedule?.Any(x => x.onChannel?.StartsWith("email") ?? false) ?? false ? true : false,
                            Vendorname = null
                        },
                        Sms = new Channel
                        {
                            IsValid    = deliveryPlan?.schedule?.Any(x => x.onChannel?.StartsWith("sms") ?? false) ?? false ? true : false,
                            Vendorname = null
                        }
                    },
                    DispatchId     = dispatch.Id,
                    DispatchName   = dispatch.Name + (dispatch.IsLive == true ? string.Empty : " [PAUSED]"),
                    StaticPrefills = staticPrefills,
                    Notify         = new Notify
                    {
                        D = null,
                        E = null,
                        F = null,
                        I = null,
                        W = null
                    }
                };
                dispatchChannels.Add(dispatchChannel);
            }

            AccountConfiguration accountConfiguration = await ViaMongoDB.GetAccountConfiguration();

            if (accountConfiguration.DispatchChannels == null)
            {
                accountConfiguration.DispatchChannels = dispatchChannels;
            }
            else
            {
                foreach (DispatchChannel dc in dispatchChannels)
                {
                    int index1 = accountConfiguration.DispatchChannels.FindIndex(x => x.DispatchId == dc.DispatchId);
                    if (index1 == -1)                                                                                   //Add new dispatch channel
                    {
                        accountConfiguration.DispatchChannels.Add(dc);
                    }
                    else                                                                                                //Update existing dispatch channel
                    {
                        accountConfiguration.DispatchChannels[index1].ChannelDetails.Email.IsValid = dc.ChannelDetails.Email.IsValid;
                        accountConfiguration.DispatchChannels[index1].ChannelDetails.Sms.IsValid   = dc.ChannelDetails.Sms.IsValid;

                        accountConfiguration.DispatchChannels[index1].DispatchName = dc.DispatchName;

                        foreach (StaticPrefill sp in dc.StaticPrefills)
                        {
                            int index2 = accountConfiguration.DispatchChannels[index1].StaticPrefills.FindIndex(x => x.QuestionId == sp.QuestionId);
                            if (index2 == -1)
                            {
                                accountConfiguration.DispatchChannels[index1].StaticPrefills.Add(sp);                   //Add new static prefill
                            }
                            else
                            {
                                accountConfiguration.DispatchChannels[index1].StaticPrefills[index2].Note = sp.Note;    //Update existing static prefill
                            }
                        }
                        accountConfiguration.DispatchChannels[index1].
                        StaticPrefills.RemoveAll(x => dc.StaticPrefills.All(y => y.QuestionId != x.QuestionId));        //Remove old static prefills

                        if (accountConfiguration.DispatchChannels[index1].Notify == default)
                        {
                            accountConfiguration.DispatchChannels[index1].Notify = dc.Notify;
                        }
                    }
                }
                accountConfiguration.DispatchChannels                                                                   //Remove old dispatch channels
                .RemoveAll(x => dispatchChannels.All(y => y.DispatchId != x.DispatchId));
            }
            return((await ViaMongoDB.UpdateAccountConfiguration_DispatchChannels(accountConfiguration.DispatchChannels)).DispatchChannels);
        }
Example #47
0
        public static bool CompareSolutions(List <Assignment> left, List <Assignment> right)
        {
            bool res = left.Count == right.Count && left.All(l => right.Any(r => CompareAssignments(l, r)));

            return(res);
        }
Example #48
0
        protected override bool EvaluateTokenCore(JsonToken token, object value, int depth)
        {
            int relativeDepth = depth - InitialDepth;

            if (relativeDepth == 0)
            {
                EnsureEnum(token, value);

                switch (token)
                {
                case JsonToken.StartObject:
                    TestType(Schema, JSchemaType.Object, null);
                    return(false);

                case JsonToken.EndObject:
                    if (_requiredProperties != null && _requiredProperties.Count > 0)
                    {
                        RaiseError("Required properties are missing from object: {0}.".FormatWith(CultureInfo.InvariantCulture, StringHelpers.Join(", ", _requiredProperties)), ErrorType.Required, Schema, _requiredProperties, null);
                    }

                    if (Schema.MaximumProperties != null && _propertyCount > Schema.MaximumProperties)
                    {
                        RaiseError("Object property count {0} exceeds maximum count of {1}.".FormatWith(CultureInfo.InvariantCulture, _propertyCount, Schema.MaximumProperties), ErrorType.MaximumProperties, Schema, _propertyCount, null);
                    }

                    if (Schema.MinimumProperties != null && _propertyCount < Schema.MinimumProperties)
                    {
                        RaiseError("Object property count {0} is less than minimum count of {1}.".FormatWith(CultureInfo.InvariantCulture, _propertyCount, Schema.MinimumProperties), ErrorType.MinimumProperties, Schema, _propertyCount, null);
                    }

                    if (_readProperties != null)
                    {
                        foreach (string readProperty in _readProperties)
                        {
                            object dependency;
                            if (Schema._dependencies.TryGetValue(readProperty, out dependency))
                            {
                                List <string> requiredProperties = dependency as List <string>;
                                if (requiredProperties != null)
                                {
                                    if (!requiredProperties.All(r => _readProperties.Contains(r)))
                                    {
                                        List <string> missingRequiredProperties = requiredProperties.Where(r => !_readProperties.Contains(r)).ToList();
                                        string        message = "Dependencies for property '{0}' failed. Missing required keys: {1}.".FormatWith(CultureInfo.InvariantCulture, readProperty, StringHelpers.Join(", ", missingRequiredProperties));

                                        RaiseError(message, ErrorType.Dependencies, Schema, readProperty, null);
                                    }
                                }
                                else
                                {
                                    SchemaScope dependencyScope = _dependencyScopes[readProperty];
                                    if (dependencyScope.Context.HasErrors)
                                    {
                                        string message = "Dependencies for property '{0}' failed.".FormatWith(CultureInfo.InvariantCulture, readProperty);
                                        RaiseError(message, ErrorType.Dependencies, Schema, readProperty, ((ConditionalContext)dependencyScope.Context).Errors);
                                    }
                                }
                            }
                        }
                    }
                    return(true);

                default:
                    throw new InvalidOperationException("Unexpected token when evaluating object: " + token);
                }
            }

            if (relativeDepth == 1)
            {
                if (token == JsonToken.PropertyName)
                {
                    _propertyCount++;
                    _currentPropertyName = (string)value;

                    if (_requiredProperties != null)
                    {
                        _requiredProperties.Remove(_currentPropertyName);
                    }
                    if (_readProperties != null)
                    {
                        _readProperties.Add(_currentPropertyName);
                    }

                    if (!Schema.AllowAdditionalProperties)
                    {
                        if (!IsPropertyDefinied(Schema, _currentPropertyName))
                        {
                            string message = "Property '{0}' has not been defined and the schema does not allow additional properties.".FormatWith(CultureInfo.InvariantCulture, _currentPropertyName);
                            RaiseError(message, ErrorType.AdditionalProperties, Schema, _currentPropertyName, null);
                        }
                    }
                }
                else
                {
                    if (JsonTokenHelpers.IsPrimitiveOrStartToken(token))
                    {
                        bool matched = false;
                        if (Schema._properties != null)
                        {
                            JSchema propertySchema;
                            if (Schema._properties.TryGetValue(_currentPropertyName, out propertySchema))
                            {
                                CreateScopesAndEvaluateToken(token, value, depth, propertySchema);
                                matched = true;
                            }
                        }

                        if (Schema._patternProperties != null)
                        {
                            foreach (KeyValuePair <string, JSchema> patternProperty in Schema._patternProperties)
                            {
                                if (Regex.IsMatch(_currentPropertyName, patternProperty.Key))
                                {
                                    CreateScopesAndEvaluateToken(token, value, depth, patternProperty.Value);
                                    matched = true;
                                }
                            }
                        }

                        if (!matched)
                        {
                            if (Schema.AllowAdditionalProperties && Schema.AdditionalProperties != null)
                            {
                                CreateScopesAndEvaluateToken(token, value, depth, Schema.AdditionalProperties);
                            }
                        }
                    }
                }
            }

            return(false);
        }
Example #49
0
        private static void Check()
        {
            try
            {
                using var c = MiscUtils.GetDefaultWebClient();
                var sMsg = c.DownloadString(new Uri(Url));
                var jMsg = JObject.Parse(sMsg);

                var newNotices = new List <NoticeBase>();

                var jNotices = jMsg["notices"];
                if (jNotices == null)
                {
                    return;
                }
                foreach (var jNotice in jNotices)
                {
                    var jType = jNotice["Type"];
                    if (jType == null)
                    {
                        continue;
                    }
                    var type = jType.Value <string>();

                    var jDetails = jNotice["Details"];
                    if (jDetails == null)
                    {
                        continue;
                    }

                    // todo: maybe use a factory
                    var jEnabled = jNotice[nameof(NoticeBase.Enabled)];
                    var jTrigger = jNotice[nameof(NoticeBase.Trigger)];
                    var jTitle   = jDetails[nameof(NoticeBase.Title)];
                    var jContent = jDetails[nameof(NoticeBase.Content)];

                    if (jEnabled == null || jTrigger == null || jTitle == null || jContent == null)
                    {
                        continue;
                    }
                    var notice = new NoticeBase
                    {
                        Enabled = jEnabled.Value <bool>(),
                        Trigger = (NoticeTrigger)jTrigger.Value <int>(),
                        Title   = jTitle.Value <string>(),
                        Content = jContent.Value <string>()
                    };

                    var duration     = jDetails[nameof(NotificationNotice.Duration)]?.Value <int>() ?? 0;
                    var intNotifType = jDetails[nameof(NotificationNotice.NotificationType)]?.Value <int>() ?? 0;
                    var notifType    = (NotificationType)intNotifType;

                    notice = type switch
                    {
                        nameof(NotificationNotice) => new NotificationNotice(notice)
                        {
                            Duration         = duration,
                            NotificationType = notifType
                        },
                        nameof(MessageBoxNotice) => new MessageBoxNotice(notice),
                        _ => notice
                    };

                    newNotices.Add(notice);
                }

                _notices = _notices.Where(existing => newNotices.All(n => n.Content != existing.Content)).ToList();

                foreach (var newNotice in newNotices)
                {
                    _notices.Add(newNotice);
                }
            }
            catch (Exception e)
            {
                Log.F($"Failed to check for messages. {e}");
            }
        }
Example #50
0
        //Checks if all the elements in a sequence satisfies the specified condition
        public bool All()
        {
            var result = listPersonalInfo.All(x => x.Savings > 0 && x.Savings > 10000);

            return(result);
        }
Example #51
0
        public ActivityRetryHandlingForm(IEnumerable <WorkerActivityConfiguration> configurations)
        {
            InitializeComponent();
            UserInterfaceStyler.Configure(this, FormStyle.FixedDialog);

            for (int i = 1; i < main_TableLayoutPanel.RowCount; i++)
            {
                LoadActionItems((ComboBox)main_TableLayoutPanel.GetControlFromPosition(ACTION_COLUMN, i));
                LoadRetryActionItems((ComboBox)main_TableLayoutPanel.GetControlFromPosition(RETRY_ACTION_COLUMN, i));
            }

            LoadDefaultDefinitions();

            _configurations = configurations.ToList();

            List <VirtualResourceMetadataRetrySetting> failedDefinitions  = new List <VirtualResourceMetadataRetrySetting>();
            List <VirtualResourceMetadataRetrySetting> skippedDefinitions = new List <VirtualResourceMetadataRetrySetting>();
            List <VirtualResourceMetadataRetrySetting> errorDefinitions   = new List <VirtualResourceMetadataRetrySetting>();

            bool addedNew = false; // Determine if a new activity was added

            foreach (var config in _configurations)
            {
                if (config.Metadata.VirtualResourceMetadataRetrySettings == null || config.Metadata.VirtualResourceMetadataRetrySettings.Count == 0) // For unconfigured activities, instantiate a new list
                {
                    addedNew = true;
                }
                else // If they are not null, add them to the list
                {
                    failedDefinitions.AddRange(config.Metadata.VirtualResourceMetadataRetrySettings.Where(x => x.State == PluginResult.Failed.ToString()));
                    skippedDefinitions.AddRange(config.Metadata.VirtualResourceMetadataRetrySettings.Where(x => x.State == PluginResult.Skipped.ToString()));
                    errorDefinitions.AddRange(config.Metadata.VirtualResourceMetadataRetrySettings.Where(x => x.State == PluginResult.Error.ToString()));
                }
            }

            if (!addedNew)
            {
                var skipPrototype  = skippedDefinitions.First();
                var failPrototype  = failedDefinitions.First();
                var errorPrototype = errorDefinitions.First();

                // Check if all actvities are configured the same, then we can edit them all at the same time
                if (_configurations.Count == 1 || (skippedDefinitions.All(s => s == skipPrototype) && failedDefinitions.All(f => f == failPrototype) && errorDefinitions.All(e => e == errorPrototype)))
                {
                    RefreshRow(FAIL_ROW, failPrototype);
                    RefreshRow(SKIP_ROW, skipPrototype);
                    RefreshRow(ERROR_ROW, errorPrototype);
                }
            }
        }
 private static void AssertAllSamplesWithNonZeroMetric(List <MonitoringDataPoint> samples, string metricName)
 {
     Assert.IsTrue(samples.All(item => item.Metrics.Any(m => m.Name == metricName && m.Value > 0)));
 }
Example #53
0
 public void Check_Goals()
 {
     Quest_Completed = Goals.All(g => g.Completed);
 }
Example #54
0
        /// <summary>
        /// Inserts a picture
        /// </summary>
        /// <param name="formFile">Form file</param>
        /// <param name="defaultFileName">File name which will be use if IFormFile.FileName not present</param>
        /// <param name="virtualPath">Virtual path</param>
        /// <returns>Picture</returns>
        public virtual Picture InsertPicture(IFormFile formFile, string defaultFileName = "", string virtualPath = "")
        {
            var imgExt = new List <string>
            {
                ".bmp",
                ".gif",
                ".jpeg",
                ".jpg",
                ".jpe",
                ".jfif",
                ".pjpeg",
                ".pjp",
                ".png",
                ".tiff",
                ".tif"
            } as IReadOnlyCollection <string>;

            var fileName = formFile.FileName;

            if (string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(defaultFileName))
            {
                fileName = defaultFileName;
            }

            //remove path (passed in IE)
            fileName = _fileProvider.GetFileName(fileName);

            var contentType = formFile.ContentType;

            var fileExtension = _fileProvider.GetFileExtension(fileName);

            if (!string.IsNullOrEmpty(fileExtension))
            {
                fileExtension = fileExtension.ToLowerInvariant();
            }

            if (imgExt.All(ext => !ext.Equals(fileExtension, StringComparison.CurrentCultureIgnoreCase)))
            {
                return(null);
            }

            //contentType is not always available
            //that's why we manually update it here
            //http://www.sfsu.edu/training/mimetype.htm
            if (string.IsNullOrEmpty(contentType))
            {
                switch (fileExtension)
                {
                case ".bmp":
                    contentType = MimeTypes.ImageBmp;
                    break;

                case ".gif":
                    contentType = MimeTypes.ImageGif;
                    break;

                case ".jpeg":
                case ".jpg":
                case ".jpe":
                case ".jfif":
                case ".pjpeg":
                case ".pjp":
                    contentType = MimeTypes.ImageJpeg;
                    break;

                case ".png":
                    contentType = MimeTypes.ImagePng;
                    break;

                case ".tiff":
                case ".tif":
                    contentType = MimeTypes.ImageTiff;
                    break;

                default:
                    break;
                }
            }

            var picture = InsertPicture(_downloadService.GetDownloadBits(formFile), contentType, _fileProvider.GetFileNameWithoutExtension(fileName));

            if (string.IsNullOrEmpty(virtualPath))
            {
                return(picture);
            }

            picture.VirtualPath = _fileProvider.GetVirtualPath(virtualPath);
            UpdatePicture(picture);

            return(picture);
        }
Example #55
0
        public async Task <ActionResult> Import(IFormFile file)
        {
            if (!ModelState.IsValid)
            {
                throw new BindException(ModelState);
            }
            StatusFilter StatusFilter = new StatusFilter
            {
                Skip    = 0,
                Take    = int.MaxValue,
                Selects = StatusSelect.ALL
            };
            List <Status> Statuses = await StatusService.List(StatusFilter);

            List <TicketSource> TicketSources = new List <TicketSource>();

            using (ExcelPackage excelPackage = new ExcelPackage(file.OpenReadStream()))
            {
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.FirstOrDefault();
                if (worksheet == null)
                {
                    return(Ok(TicketSources));
                }
                int StartColumn       = 1;
                int StartRow          = 1;
                int IdColumn          = 0 + StartColumn;
                int NameColumn        = 1 + StartColumn;
                int OrderNumberColumn = 2 + StartColumn;
                int StatusIdColumn    = 3 + StartColumn;
                int UsedColumn        = 7 + StartColumn;

                for (int i = StartRow; i <= worksheet.Dimension.End.Row; i++)
                {
                    if (string.IsNullOrEmpty(worksheet.Cells[i + StartRow, StartColumn].Value?.ToString()))
                    {
                        break;
                    }
                    string IdValue          = worksheet.Cells[i + StartRow, IdColumn].Value?.ToString();
                    string NameValue        = worksheet.Cells[i + StartRow, NameColumn].Value?.ToString();
                    string OrderNumberValue = worksheet.Cells[i + StartRow, OrderNumberColumn].Value?.ToString();
                    string StatusIdValue    = worksheet.Cells[i + StartRow, StatusIdColumn].Value?.ToString();
                    string UsedValue        = worksheet.Cells[i + StartRow, UsedColumn].Value?.ToString();

                    TicketSource TicketSource = new TicketSource();
                    TicketSource.Name        = NameValue;
                    TicketSource.OrderNumber = long.TryParse(OrderNumberValue, out long OrderNumber) ? OrderNumber : 0;
                    Status Status = Statuses.Where(x => x.Id.ToString() == StatusIdValue).FirstOrDefault();
                    TicketSource.StatusId = Status == null ? 0 : Status.Id;
                    TicketSource.Status   = Status;

                    TicketSources.Add(TicketSource);
                }
            }
            TicketSources = await TicketSourceService.Import(TicketSources);

            if (TicketSources.All(x => x.IsValidated))
            {
                return(Ok(true));
            }
            else
            {
                List <string> Errors = new List <string>();
                for (int i = 0; i < TicketSources.Count; i++)
                {
                    TicketSource TicketSource = TicketSources[i];
                    if (!TicketSource.IsValidated)
                    {
                        string Error = $"Dòng {i + 2} có lỗi:";
                        if (TicketSource.Errors.ContainsKey(nameof(TicketSource.Id)))
                        {
                            Error += TicketSource.Errors[nameof(TicketSource.Id)];
                        }
                        if (TicketSource.Errors.ContainsKey(nameof(TicketSource.Name)))
                        {
                            Error += TicketSource.Errors[nameof(TicketSource.Name)];
                        }
                        if (TicketSource.Errors.ContainsKey(nameof(TicketSource.OrderNumber)))
                        {
                            Error += TicketSource.Errors[nameof(TicketSource.OrderNumber)];
                        }
                        if (TicketSource.Errors.ContainsKey(nameof(TicketSource.StatusId)))
                        {
                            Error += TicketSource.Errors[nameof(TicketSource.StatusId)];
                        }
                        if (TicketSource.Errors.ContainsKey(nameof(TicketSource.Used)))
                        {
                            Error += TicketSource.Errors[nameof(TicketSource.Used)];
                        }
                        Errors.Add(Error);
                    }
                }
                return(BadRequest(Errors));
            }
        }
Example #56
0
        private async Task <List <ActionStep> > PerformTaskList(ILog log, bool isPreviewOnly, bool skipDeferredTasks, CertificateRequestResult result, IEnumerable <DeploymentTaskConfig> taskList, bool forceTaskExecute = false)
        {
            if (taskList == null || !taskList.Any())
            {
                // nothing to do
                return(new List <ActionStep>());
            }

            if (log == null)
            {
                log = ManagedCertificateLog.GetLogger(result.ManagedItem.Id, _loggingLevelSwitch);
            }

            // perform or preview each task

            var deploymentTasks = new List <DeploymentTask>();
            var steps           = new List <ActionStep>();

            foreach (var taskConfig in taskList)
            {
                // add task to execution list unless the task is deferred/manual and we are currently skipping deferred tasks

                if (taskConfig.TaskTrigger != TaskTriggerType.MANUAL || (taskConfig.TaskTrigger == TaskTriggerType.MANUAL && !skipDeferredTasks))
                {
                    try
                    {
                        var provider = DeploymentTaskProviderFactory.Create(taskConfig.TaskTypeId.ToLower(), _pluginManager.DeploymentTaskProviders);

                        Dictionary <string, string> credentials = null;

                        if (!string.IsNullOrEmpty(taskConfig.ChallengeCredentialKey))
                        {
                            credentials = await _credentialsManager.GetUnlockedCredentialsDictionary(taskConfig.ChallengeCredentialKey);
                        }

                        var deploymentTask = new DeploymentTask(provider, taskConfig, credentials);

                        deploymentTasks.Add(deploymentTask);
                    }
                    catch (Exception exp)
                    {
                        steps.Add(new ActionStep {
                            HasError = true, Title = "Task: " + taskConfig.TaskName, Description = "Cannot create task provider for deployment task: " + exp.ToString()
                        });
                    }
                }
            }

            ActionStep previousActionStep   = null;
            bool       shouldRunCurrentTask = true;
            string     taskTriggerReason    = "Task will run for any status";

            foreach (var task in deploymentTasks)
            {
                if (previousActionStep != null && (previousActionStep.HasError && !task.TaskConfig.RunIfLastStepFailed))
                {
                    shouldRunCurrentTask = false;
                    taskTriggerReason    = "Task will not run because previous task failed.";
                }
                else
                {
                    if (task.TaskConfig.TaskTrigger == TaskTriggerType.ANY_STATUS)
                    {
                        shouldRunCurrentTask = true;
                        taskTriggerReason    = "Task will run for any status";
                    }
                    else if (task.TaskConfig.TaskTrigger == TaskTriggerType.NOT_ENABLED)
                    {
                        shouldRunCurrentTask = false;
                        taskTriggerReason    = "Task is not enabled and will be skipped.";
                    }
                    else if (task.TaskConfig.TaskTrigger == TaskTriggerType.ON_SUCCESS)
                    {
                        if (result != null && (!result.Abort && result.IsSuccess))
                        {
                            shouldRunCurrentTask = true;
                            taskTriggerReason    = "Task is enabled and primary request was successful.";
                        }
                        else
                        {
                            shouldRunCurrentTask = false;
                            taskTriggerReason    = "Task is enabled but will not run because primary request unsuccessful.";
                        }
                    }
                    else if (task.TaskConfig.TaskTrigger == TaskTriggerType.ON_ERROR)
                    {
                        if (result != null && (!result.Abort && result.IsSuccess))
                        {
                            shouldRunCurrentTask = false;
                            taskTriggerReason    = "Task is enabled but will not run because primary request was successful.";
                        }
                        else
                        {
                            shouldRunCurrentTask = true;
                            taskTriggerReason    = "Task is enabled and will run because primary request was unsuccessful.";
                        }
                    }
                    else if (task.TaskConfig.TaskTrigger == TaskTriggerType.MANUAL)
                    {
                        if (skipDeferredTasks)
                        {
                            shouldRunCurrentTask = false;
                            taskTriggerReason    = "Task is enabled but will not run because execution is deferred/manual.";
                        }
                        else
                        {
                            shouldRunCurrentTask = true;
                            taskTriggerReason    = "Task is enabled and will run because deferred/manual tasks are not being skipped.";
                        }
                    }
                }

                if (forceTaskExecute == true)
                {
                    if (!shouldRunCurrentTask)
                    {
                        shouldRunCurrentTask = true;
                        taskTriggerReason    = $"Task is being has been forced to run. Normal status would be [{taskTriggerReason}]";
                    }
                }

                var taskResults = new List <ActionResult>();

                if (shouldRunCurrentTask)
                {
                    log.Information($"Task [{task.TaskConfig.TaskName}] :: {taskTriggerReason}");
                    task.TaskConfig.DateLastExecuted = DateTime.Now;
                    taskResults = await task.Execute(log, result, CancellationToken.None, isPreviewOnly : isPreviewOnly);

                    if (!isPreviewOnly)
                    {
                        if (taskResults?.All(t => t.IsSuccess) == true)
                        {
                            _tc?.TrackEvent("TaskCompleted", new Dictionary <string, string> {
                                { "TaskType", task.TaskConfig.TaskTypeId }
                            });
                        }
                        else
                        {
                            if (!forceTaskExecute)
                            {
                                _tc?.TrackEvent("TaskFailed", new Dictionary <string, string> {
                                    { "TaskType", task.TaskConfig.TaskTypeId }
                                });
                            }
                        }
                    }
                }
                else
                {
                    taskResults.Add(new ActionResult($"Task [{task.TaskConfig.TaskName}] :: {taskTriggerReason}", true));
                }

                var subSteps = new List <ActionStep>();

                var stepIndex = 1;

                foreach (var r in taskResults)
                {
                    subSteps.Add(new ActionStep
                    {
                        HasError    = !r.IsSuccess,
                        Description = r.Message,
                        Title       = $"Task Step {stepIndex} of {task.TaskConfig.TaskName}",
                        Key         = task.TaskConfig.Id + "_" + stepIndex,
                        Category    = "Task Step"
                    });


                    if (r.IsSuccess)
                    {
                        log?.Information(r.Message);
                    }
                    else
                    {
                        log?.Error(r.Message);
                    }

                    stepIndex++;
                }


                var overallTaskResult = "Unknown";

                if (taskResults != null && taskResults.Any(t => t.IsSuccess == false))
                {
                    overallTaskResult = taskResults.First(t => t.IsSuccess == false).Message;
                }
                else
                {
                    if (isPreviewOnly)
                    {
                        overallTaskResult = taskTriggerReason;
                    }
                    else
                    {
                        if (shouldRunCurrentTask)
                        {
                            overallTaskResult = "Task Completed OK";
                        }
                        else
                        {
                            overallTaskResult = taskTriggerReason;
                        }
                    }
                }

                var hasError = (taskResults != null && taskResults.Any(t => t.IsSuccess == false) ? true : false);

                var currentStep = new ActionStep
                {
                    Key         = task.TaskConfig.Id,
                    Title       = task.TaskConfig.TaskName,
                    Category    = "Task",
                    HasError    = hasError,
                    Description = overallTaskResult,
                    HasWarning  = !shouldRunCurrentTask,
                    Substeps    = subSteps
                };


                task.TaskConfig.LastRunStatus = hasError ? RequestState.Error : RequestState.Success;
                task.TaskConfig.LastResult    = overallTaskResult;

                steps.Add(currentStep);

                previousActionStep = currentStep;
            }

            return(steps);
        }
 /// <summary>
 /// Check if all entities are off
 /// </summary>
 /// <param name="entities">List of entities</param>
 public static bool AreOff(this List <BinarySensorEntity> entities) => entities.All(e => e.IsOn);
Example #58
0
        public async Task UpdateEventProductsAsync(int eventId, List <Product> products)
        {
            if (products is null)
            {
                throw new ArgumentNullException(paramName: nameof(products));
            }

            await CheckEventAccessAsync(eventId);

            var originalProducts = await _context.Products
                                   .Where(p => p.EventInfoId == eventId)
                                   .Include(p => p.ProductVariants)
                                   .AsNoTracking()
                                   .ToArrayAsync();

            var originalVariants = originalProducts
                                   .SelectMany(p => p.ProductVariants)
                                   .ToArray();

            // Delete the variants that don't exist in the provided object
            var providedVariants = products
                                   .Where(p => p.ProductVariants != null)
                                   .SelectMany(p => p.ProductVariants);

            var variantsToDelete = originalVariants
                                   .Where(originalVariant => providedVariants.All(variant =>
                                                                                  variant.ProductVariantId != originalVariant.ProductVariantId))
                                   .ToList();

            if (variantsToDelete.Any())
            {
                _context.ProductVariants.AttachRange(variantsToDelete);
                _context.ProductVariants.RemoveRange(variantsToDelete);
                await _context.SaveChangesAsync();
            }

            // Delete the products that don't exist in the provided object
            var productsToDelete = originalProducts
                                   .Where(op => products.All(p =>
                                                             p.ProductId != op.ProductId)).ToList();

            if (productsToDelete.Any())
            {
                _context.Products.AttachRange(productsToDelete);
                _context.Products.RemoveRange(productsToDelete);
                await _context.SaveChangesAsync();
            }

            // Save the updates
            var info = await _context.EventInfos
                       .Where(e => e.EventInfoId == eventId)
                       .Include(ei => ei.Products)
                       .ThenInclude <EventInfo, Product, List <ProductVariant> >(p => p.ProductVariants)
                       .AsNoTracking()
                       .SingleAsync();

            info.Products = products;

            _context.DetachAllEntities();
            _context.EventInfos.Update(info);

            await _context.SaveChangesAsync();
        }
 /// <summary>
 /// Check if all entities are off
 /// </summary>
 /// <param name="entities">List of entities</param>
 public static bool AreOff(this List <SwitchEntity> entities) => entities.All(e => e.IsOn);
Example #60
0
        static void Main(string[] args)
        {
            // key is a string, but the value is a list of strings
            var definitions = new Dictionary <string, List <string> >();

            // key is martin, but the value is a collection of its own
            definitions.Add("martin", new List <string> {
                "smart", "strong", "important"
            });

            // this allows us to add something within this key
            definitions["martin"].Where(word => word.StartsWith('s'));
            Console.WriteLine(string.Join("you is ", definitions["martin"]));

            var grumpyBear  = new GrumpyBear();
            var tenderHeart = new TenderHeart();
            var tinderHeart = new TinderHeart();

            // to access lists, you must have using System.Collections.Generic;
            // we have to be explicit with the kind of things we put into Lists
            // the three items above have an "is a" relationship with the CareBearBase;
            // the curly brackets at the end of the careBears variable is called an object initializer
            var careBears = new List <CareBearBase> {
                grumpyBear, tenderHeart, tinderHeart
            };

            foreach (var bear in careBears)
            {
                bear.Care("Nathan");
                bear.Stare();
            }

            // bread and butter are going to be where and select

            // LINQ - Language integrated queries: transforming and filtering collections of things
            // LINQ allows us to use similar JS methods like map, filter, reduce

            // LINQ where() is similar to JS filter()
            // this method does not modify the original list; the variable below will have bears whose names begin with T
            var namesThatStartWithT = careBears.Where(bear => bear.Name.StartsWith('T')).ToList();
            var i = 0;

            foreach (var bear in namesThatStartWithT)
            {
                Console.WriteLine(namesThatStartWithT[i].Name);
                i++;
            }
            Console.ReadLine();

            // transforming the List. similar to map in JS. not removing things, but changing what the collection is made of
            // bear.Name tells Select that we will be returning an IEnumerable of strings
            // IEnumerable are the lowest common denominator for all of our connections
            // as long as it is an ienumerable, you can use linq on it

            var careBearNames = careBears.Select(bear => bear.Name);

            // be aware of the order in which you do things because it effects your outcome
            // this order takes the original list and filters it down to a smaller subset before filtering the smaller group down more
            var careBearNamesThatStartWithT = careBears.Where(bear => bear.Name.StartsWith('T')).Select(bear => bear.Name);

            // lambda expressions (delegates): the fat arrow occuring inside of parentheses on linq methods; it is a function reference
            // the is operator allows us to name something specifically and it returns a boolean expression representing the result
            // Any returns true if any one of the thing in the list matches
            // Any: one thing must match; as soon as it finds the first of the thing, it stops looking through the list
            var anyTinderHearts = careBears.Any(bear => bear is TinderHeart);

            Console.WriteLine(anyTinderHearts);
            // All returns true if every bear in our list if a TinderHeart
            // All: looks until it finds something that doesn't match and then exits out - short circuiting
            var allTinderHearts = careBears.All(bear => bear is TinderHeart);

            Console.WriteLine(allTinderHearts);
            Console.ReadLine();
            // when you put in your dot operator, anything with a disc and a down arrow are the linq things
            // aggragate is the same concept as JS reduce

            // first says find me the first thing in the list and return it
            var firstBear = careBears.First();

            // entering a parameter gives the method something look for;
            // if you ask for something that doesn't exist, it blows up - throws an exception
            var firstBearStartingWithT = careBears.First(bear => bear.Name.StartsWith("Te"));

            // if you create a list with nothing in it
            var otherList = new List <CareBearBase>();
            // if you ask for the first thing in a list that doesn't have anything in it, it blows up - throw an exception
            var blowsUp = otherList.First();

            // FirstOrDefault says find the first thing that matches, or give me the default of carebearbase
            // a reference type, like a class, default to null
            var works = careBears.FirstOrDefault(bear => bear.Name.StartsWith('W'));

            // skip one item and then take 2 items; throws an exception if used on a list of not three things
            var skippedGrumpy = careBears.Skip(1).Take(2);

            // return the sum of all bear name lengths
            var numberOfCharacters = careBears.Sum(bear => bear.Name.Length);

            // return the number of the longest one
            var max = careBears.Max(bear => bear.Name.Length);

            // doing transformations inside for loops is not a good idea; outdated. instead, use a select
            // LINQ takes the place of most foreach and for loops
            // data transformations - like with select - are super common. get used to it

            // order alphabetically
            var orderedBears = careBears.OrderBy(bear => bear.BellyBadge);

            // you will know something is expensive when it costs you power; micro-optimization; the order of select and where clauses, things like that

            // will find anything that has bear in it
            var anyBears = careBears.Any();

            var doNotDoThis = careBears.Where(bear => bear.Name.StartsWith('T')).Select(bear => bear.Name).Any();
        }