Exemple #1
1
        private static void RunManager(InputConfig config)
        {
            try
            {
                var input = new DirectInput();
                var devices = new List<DeviceInstance>(input.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices));
                devices.AddRange(input.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices));

                var registeredDevices = new List<Tuple<Config.Input, Joystick>>();

                foreach (var inp in config.Inputs)
                {
                    var device = devices.SingleOrDefault(di => di.ProductGuid == new Guid(inp.Guid));
                    if (device == null)
                    {
                        throw new Exception($"Device \"{inp.Nickname}\" not found");
                    }

                    var joy = new Joystick(input, device.InstanceGuid);

                    registeredDevices.Add(Tuple.Create(inp, joy));
                }

                while (true)
                {
                    var frame = new InputFrame();
                    frame.GenerationTime = DateTime.Now;

                    foreach (var registeredDevice in registeredDevices)
                    {
                        var state = registeredDevice.Item2.GetCurrentState();

                        switch (registeredDevice.Item1.Type.ToUpper())
                        {
                            case "JOYSTICK":
                                frame.SubFrames.Add(new JoystickSubFrame(state));
                                break;
                            case "GAMEPAD":
                                frame.SubFrames.Add(new GamepadSubFrame(state));
                                break;
                        }
                    }

                    FrameCaptured?.Invoke(frame);
                }

            }
            catch (ThreadAbortException)
            {
                Console.Error.WriteLine("Input Manager Stopped at " + DateTime.Now.ToString("G"));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex.Message}\n\nInput Manager cannot continue", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }
Exemple #2
0
        public List<CategoriaDTO> getCategoriasTreeEnEmpresa(List<CategoriaDTO> lstCatsMontos, int idEmpresa, int? id = null)
        {
            
            var result = from r in lstCatsMontos
                            where ((id == null ? r.IdCategoriaPadre == null : r.IdCategoriaPadre == id) && r.Estado && r.IdEmpresa == idEmpresa)
                            select new CategoriaDTO
                            {
                                IdCategoria = r.IdCategoria,
                                Nombre = r.Nombre,
                                Orden = r.Orden,
                                Estado = r.Estado,
                                IdCategoriaPadre = r.IdCategoriaPadre,
                                IdEmpresa = r.IdEmpresa,
                                Presupuesto = lstCatsMontos.SingleOrDefault(x => x.IdCategoria == r.IdCategoria).Presupuesto
                            };
            List<CategoriaDTO> categoriasTree = result.AsEnumerable<CategoriaDTO>().OrderBy(x => x.Orden).ToList<CategoriaDTO>();

            foreach (CategoriaDTO obj in categoriasTree)
            {
                obj.Hijos = getCategoriasTreeEnEmpresa(lstCatsMontos, idEmpresa, obj.IdCategoria);
                if(obj.Hijos.Count() > 0)
                {
                    obj.Presupuesto = lstCatsMontos.Where(x => x.IdCategoriaPadre == obj.IdCategoria).Sum(x => x.Presupuesto);
                    lstCatsMontos.SingleOrDefault(x => x.IdCategoria == obj.IdCategoria).Presupuesto = obj.Presupuesto;
                }
            }

            return categoriasTree;
        }
Exemple #3
0
        /// <summary>
        /// Devuelve los últimos resultados de la encuesta de síntomas de una ficha médica
        /// </summary>
        /// <param name="idFichaMedica">Identificador de la ficha médica</param>
        /// <returns></returns>
        public (ResultadoEncuestaSintomas Fiebre, ResultadoEncuestaSintomas Otros, ResultadoEncuestaSintomas Contacto) GetLastResultadoEncuesta(List <ResultadoEncuestaSintomas> ultimaEncuesta)
        {
            ResultadoEncuestaSintomas utiDeclFiebre  = ultimaEncuesta?.SingleOrDefault(re => re.IdTipoSintomaNavigation.Nombre == TipoSintomas.ParameterTypes.Fiebre.ToString());
            ResultadoEncuestaSintomas utiDeclOtros   = ultimaEncuesta?.SingleOrDefault(re => re.IdTipoSintomaNavigation.Nombre == TipoSintomas.ParameterTypes.OtrosSintomas.ToString());
            ResultadoEncuestaSintomas utiDeclContato = ultimaEncuesta?.SingleOrDefault(re => re.IdTipoSintomaNavigation.Nombre == TipoSintomas.ParameterTypes.Contacto.ToString());

            return(utiDeclFiebre, utiDeclOtros, utiDeclContato);
        }
Exemple #4
0
        private static void Initialize(List<Node> nodes)
        {
            foreach (var node in nodes)
            {
                var left = nodes.SingleOrDefault(n => n.Y == node.Y && n.X == (node.X - 1));
                var right = nodes.SingleOrDefault(n => n.Y == node.Y && n.X == (node.X + 1));
                var up = nodes.SingleOrDefault(n => n.X == node.X && n.Y == (node.Y - 1));
                var down = nodes.SingleOrDefault(n => n.X == node.X && n.Y == (node.Y + 1));

                if (left != null) node.Reachable.Add(left);
                if (right != null) node.Reachable.Add(right);
                if (up != null) node.Reachable.Add(up);
                if (down != null) node.Reachable.Add(down);
            }
        }
Exemple #5
0
		public virtual List<CSClass> ParseString(string data, string filePath, string projectDirectory, IEnumerable<CSClass> existingClassList)
		{
			string relativeFilePath = filePath.Replace(projectDirectory,"");
			if(relativeFilePath.StartsWith("\\"))
			{
				relativeFilePath = relativeFilePath.Substring(1);
			}
			List<CSClass> returnValue = new List<CSClass>(existingClassList ?? new CSClass[]{} );
			var parser = new CSharpParser();
			var compilationUnit = parser.Parse(data, filePath);
			var namespaceNodeList = compilationUnit.Children.Where(i=>i is NamespaceDeclaration);
			foreach(NamespaceDeclaration namespaceNode in namespaceNodeList)
			{
				var typeDeclarationNodeList = namespaceNode.Children.Where(i=>i is TypeDeclaration);
				foreach(TypeDeclaration typeDeclarationNode in typeDeclarationNodeList)
				{
					var classObject = returnValue.SingleOrDefault(i=>i.ClassName == typeDeclarationNode.Name && i.NamespaceName == namespaceNode.FullName);
					if(classObject == null)
					{
						classObject = new CSClass
						{
							NamespaceName = namespaceNode.FullName,
							ClassName = typeDeclarationNode.Name
						};
						returnValue.Add(classObject);
					}
					ClassParser.BuildClass(classObject, typeDeclarationNode, relativeFilePath);
				}
			}
			return returnValue;
		}
		internal static ShimWorkItem CreateCodeReviewResponse(int id, string state, string reviewResult)
		{
			var responseFields = new List<Field>()
				{
					new ShimField()
					{ 
						NameGet = () => CodeReviewPolicy.ClosedStatus,
						ValueGet = () => reviewResult
					}
				};
			var fakeResponseFields = new ShimFieldCollection()
			{
				ItemGetString = (s) => responseFields.SingleOrDefault(f => f.Name == s)
			};

			var responseWorkItem = new ShimWorkItem()
			{
				TypeGet = () => new ShimWorkItemType()
				{
					NameGet = () => "Code Review Response"
				},
				IdGet = () => id,
				StateGet = () => state,
				FieldsGet = () => fakeResponseFields,
			};
			return responseWorkItem;
		}
Exemple #7
0
        public void ParseDeducciones(List<Empleado> employees)
        {
            Deduccion deduccion;
            IRow currentRow;
            ISheet sheet = workBook.GetSheetAt(ExcelReader.DeduccionesSheet);

            IEnumerator rowEnumator = sheet.GetRowEnumerator();

            //Ignore headers
            rowEnumator.MoveNext();

            Empleado employee;

            while (rowEnumator.MoveNext())
            {

                currentRow = rowEnumator.Current as IRow;
                deduccion = deduccionParser.Parse(currentRow);

                if (deduccion.NumEmpleado.HasValue)
                {
                    employee = employees.SingleOrDefault(emp => emp.Numero == deduccion.NumEmpleado.Value);
                    if (employee != null)
                        employee.ParsedDeducciones.Add(deduccion);
                }

            }
        }
        public async Task <Tenant> GetTenantAsync(string identifier)
        {
            string        config      = _configuration.GetSection($"devz:All:Tenants").Value;
            List <Tenant> tenantArray = null;

            if (!string.IsNullOrWhiteSpace(config))
            {
                tenantArray = JsonConvert.DeserializeObject <List <Tenant> >(config);
            }

            var tenant = tenantArray?.SingleOrDefault(t => t.Dns == identifier);

            if (identifier != null && tenant == null)
            {
                //Dev only
                tenant = new Tenant
                {
                    Id    = "8080",
                    Dns   = "localhost",
                    Items =
                    {
                        { "module",          "Wiz.Template.Module.Base.Bootstrap, Wiz.Template.Module.Base"                          },
                        { "financingMethod", "Wiz.Template.Module.Base.Services.SacFinancingMethodService, Wiz.Template.Module.Base" }
                    }
                };
            }

            return(await Task.FromResult(tenant));
        }
 public string[] GetFirstLevelDepartmentIdByDepartment(int departmentId)
 {
     string postString = string.Join("&", "url=http://service.dianping.com/ba/base/organizationalstructure/OrganizationService_1.0.0"
                                         , "method=getDepartmentHierarchy"
                                         , "parameterTypes=int"
                                         , "parameters=" + departmentId.ToString());
     byte[] postData = Encoding.UTF8.GetBytes(postString);
     List<Department> departmentList = new List<Department>();
     using (WebClient client = new WebClient())
     {
         client.Headers.Add("serialize", 7.ToString());
         client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
         byte[] responseData = client.UploadData(ORGANIZATIONAL_STRUCTURE_PIGEON, "POST", postData);//得到返回字符流
         string result = Encoding.UTF8.GetString(responseData);//解码
         departmentList = JsonConvert.DeserializeObject<List<Department>>(result);
     }
     if (departmentList == null)
     {
         return new List<string>().ToArray();
     }
     else
     {
         var firstLevelDepartment = departmentList.SingleOrDefault(_ => _.Level == 1);
         if (firstLevelDepartment == null)
         {
             return new List<string>().ToArray();
         }
         else
         {
             return new string[] { firstLevelDepartment.DepartmentId.ToString() };
         }
     }
 }
        private static List<SyndicationItem> GetUnprocessedEvents(List<SyndicationItem> events)
        {
            var lastProcessed = events.SingleOrDefault(s => s.Id == LastEventIdProcessed);
            var indexOfLastProcessedEvent = events.IndexOf(lastProcessed);

            return events.Skip(indexOfLastProcessedEvent + 1).ToList();
        }
Exemple #11
0
        void DistributeRemainingSpaceToElementsWithUndefinedWidth(Unit lineWidth, List<LayoutedElement> elementsInLine)
        {
            var elementWithUndefinedWidth = elementsInLine.SingleOrDefault(x => !x.ForcedInnerWidth.IsDefined);
            if (elementWithUndefinedWidth != null)
            {
                var containerSpaceLeft = containerInnerWidth - lineWidth;
                if (containerSpaceLeft == 0.cm())
                    containerSpaceLeft = containerInnerWidth;

                elementWithUndefinedWidth.ForcedInnerWidth = containerSpaceLeft;
            }

            var left = Unit.Zero;
            var top = Unit.Zero;
            foreach (var layoutedElement in elementsInLine)
            {
                layoutedElement.Left = left;
                left += layoutedElement.OuterWidth;

                if (containerInnerHeight != 0.cm() && top + layoutedElement.OuterHeight > containerInnerHeight)
                    layoutedElement.ForcedOuterHeight = containerInnerHeight - top;

                top += layoutedElement.OuterHeight;
            }
        }
Exemple #12
0
        public OperationResult Login(LoginModel model)
        {
            var operationResult = new OperationResult(OperationResultType.Error);
            Validator.ValidateObject(model, new ValidationContext(model));
            User user = UserFormService.Users().SingleOrDefault(m => m.usercode == model.Account);
            if (user == null)
            {
                operationResult.Message = Properties.Resources.FrmLogin_Login_UserNotExist;
                return operationResult;
            }
            if (user.userpwd != model.Password)
            {
                operationResult.Message = Properties.Resources.FrmLogin_Login_PasswordError;
                return operationResult;
            }

            var usergroups = user.UserGroups.ToList();
            var reses = new List<Res>();
            var mdls = new List<Mdl>();
            foreach (var a in usergroups)
            {
                reses.AddRange(a.Ress);
                mdls.AddRange(a.Mdls);
            }
            if (reses.SingleOrDefault(r => r.RESCODE == model.ResCode) == null)
            {
                operationResult.Message = Properties.Resources.FrmLogin_Login_UserNotRes;
                return operationResult;
            }
            operationResult.ResultType=OperationResultType.Success;
            operationResult.AppendData = mdls;
            operationResult.Message = Properties.Resources.FrmLogin_Login_LoginSuccess;
            return operationResult;
        }
        private static IList<MetricConfiguration> CombineMetricConfigurations(IList<MetricConfiguration> baseMetrics, IList<MetricConfiguration> overrideMetrics)
        {
            if (overrideMetrics.IsNull() || !overrideMetrics.Any())
            {
                return baseMetrics;
            }

            if (baseMetrics.IsNull() || !baseMetrics.Any())
            {
                return overrideMetrics;
            }

            var combinedMetricConfiguration = new List<MetricConfiguration>();

            combinedMetricConfiguration.AddRange(baseMetrics);

            foreach (var metric in overrideMetrics)
            {
                var matchingMetric = combinedMetricConfiguration.SingleOrDefault(m => m.Template.Equals(metric.Template));

                if (matchingMetric != null)
                {
                    combinedMetricConfiguration.Remove(matchingMetric);
                }

                combinedMetricConfiguration.Add(metric);
            }

            return combinedMetricConfiguration;
        }
Exemple #14
0
        public static void Main(string[] args)
        {
            try
            {
            #if DEBUG
                //args = new string[] { "-o=unmount", @"-p=C:\Virtual Hard Disks\example.vhd" };
            #endif

                var helpOptions = new HelpOptions();

                var options = new List<IExecutable>() {
                    { helpOptions },
                    { new MountOptions() }
                };

                helpOptions.Parent = options;

                options.SingleOrDefault(option => option.Execute(args));

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Environment.Exit(1);
            }
        }
        public IEnumerable<MasterDetailsViewModel> GetMasterDetailsViewModels()
        {
            List<MasterDetailsViewModel> masterDetailsViewModelList;

            var categoryViewModels = new List<CategoryViewModel>
                            {
                                new CategoryViewModel { CategoryId=1, CategoryName = "Fruit"},
                                new CategoryViewModel {CategoryId=2, CategoryName = "Car"},
                                new CategoryViewModel {CategoryId=3, CategoryName = "Cloth"},
                            };

            // Create some products.
            var productViewModels = new List<ProductViewModel>
                        {
                            new ProductViewModel {ProductId=1, ProductName="Apple", ProductPrice=15, CategoryId=1},
                            new ProductViewModel {ProductId=2, ProductName="Mango", ProductPrice=20, CategoryId=1},
                            new ProductViewModel {ProductId=3, ProductName="Orange", ProductPrice=15, CategoryId=1},
                            new ProductViewModel {ProductId=4, ProductName="Banana", ProductPrice=20, CategoryId=1},
                            new ProductViewModel {ProductId=5, ProductName="Licho", ProductPrice=15, CategoryId=1},
                            new ProductViewModel {ProductId=6, ProductName="Jack Fruit", ProductPrice=20, CategoryId=1},

                            new ProductViewModel {ProductId=7, ProductName="Toyota", ProductPrice=15000, CategoryId=2},
                            new ProductViewModel {ProductId=8, ProductName="Nissan", ProductPrice=20000, CategoryId=2},
                            new ProductViewModel {ProductId=9, ProductName="Tata", ProductPrice=50000, CategoryId=2},
                            new ProductViewModel {ProductId=10, ProductName="Honda", ProductPrice=20000, CategoryId=2},
                            new ProductViewModel {ProductId=11, ProductName="Kimi", ProductPrice=50000, CategoryId=2},
                            new ProductViewModel {ProductId=12, ProductName="Suzuki", ProductPrice=20000, CategoryId=2},
                            new ProductViewModel {ProductId=13, ProductName="Ferrari", ProductPrice=50000, CategoryId=2},

                            new ProductViewModel {ProductId=14, ProductName="T Shirt", ProductPrice=20000, CategoryId=3},
                            new ProductViewModel {ProductId=15, ProductName="Polo Shirt", ProductPrice=50000, CategoryId=3},
                            new ProductViewModel {ProductId=16, ProductName="Shirt", ProductPrice=200, CategoryId=3},
                            new ProductViewModel {ProductId=17, ProductName="Panjabi", ProductPrice=500, CategoryId=3},
                            new ProductViewModel {ProductId=18, ProductName="Fotuya", ProductPrice=200, CategoryId=3},
                            new ProductViewModel {ProductId=19, ProductName="Shari", ProductPrice=500, CategoryId=3},
                            new ProductViewModel {ProductId=20, ProductName="Kamij", ProductPrice=400, CategoryId=3},

                        };

            var masterDetailsViewModels =
                productViewModels.Select(
                    x =>
                        {
                            var categoryViewModel = categoryViewModels.SingleOrDefault(c => c.CategoryId == x.CategoryId);
                            return categoryViewModel != null ? new MasterDetailsViewModel()
                                                                    {
                                                                        ProductId = x.ProductId,
                                                                        ProductName = x.ProductName,
                                                                        ProductPrice = x.ProductPrice,
                                                                        CategoryId = x.CategoryId,
                                                                        CategoryName =
                                                                            categoryViewModel.CategoryName
                                                                    } : null;
                        }).ToList
                    ();

            masterDetailsViewModelList = masterDetailsViewModels;

            return masterDetailsViewModelList.AsQueryable();
        }
 public void ApplyDeviceConfigurationModels(List<Engine.Data.Configuration.Device> deviceConfigurations, List<Engine.Data.Configuration.Coin> coinConfigurations)
 {
     foreach (DeviceViewModel deviceViewModel in Devices)
     {
         Engine.Data.Configuration.Device deviceConfiguration = deviceConfigurations.SingleOrDefault(dc => dc.Equals(deviceViewModel));
         if (deviceConfiguration != null)
         {
             deviceViewModel.Enabled = deviceConfiguration.Enabled;
             if (String.IsNullOrEmpty(deviceConfiguration.CoinSymbol))
             {
                 deviceViewModel.Coin = null;
             }
             else
             {
                 Engine.Data.Configuration.Coin coinConfiguration = coinConfigurations.SingleOrDefault(
                     cc => cc.CryptoCoin.Symbol.Equals(deviceConfiguration.CoinSymbol, StringComparison.OrdinalIgnoreCase));
                 if (coinConfiguration != null)
                     deviceViewModel.Coin = coinConfiguration.CryptoCoin;
             }
         }
         else
         {
             deviceViewModel.Enabled = true;
             Engine.Data.Configuration.Coin coinConfiguration = coinConfigurations.SingleOrDefault(
                 cc => cc.CryptoCoin.Symbol.Equals(KnownCoins.BitcoinSymbol, StringComparison.OrdinalIgnoreCase));
             if (coinConfiguration != null)
                 deviceViewModel.Coin = coinConfiguration.CryptoCoin;
         }
     }
 }
Exemple #17
0
        protected override void Load(ContainerBuilder builder)
        {
            #region mock IPostRepository
            Mock<IPostRepository> mockPost = new Mock<IPostRepository>();
            var posts = new List<Post>()
                            {
                                new Post() {Id = 1, Title = "first blog", Published = DateTime.Now.AddDays(-1)},
                                new Post() {Id = 2, Title = "second blog", Published = DateTime.Now.AddDays(-2)},
                                new Post() {Id = 3, Title = "third blog", Published = DateTime.Now.AddDays(-3)},

                            };
            mockPost.Setup(m => m.GetAll()).Returns(posts.AsQueryable());
            mockPost.Setup(m => m.Get(It.IsAny<int>())).Returns(posts.SingleOrDefault(p => p.Id == 1));
            builder.RegisterInstance(mockPost.Object).As<IPostRepository>().SingleInstance();
            #endregion

            #region mock IUserRepository
            Mock<IUserRepository> mockUser = new Mock<IUserRepository>();
            var users = new List<User>
                            {
                                new User()
                                    {Id = 1, Name = "sa", Email = "*****@*****.**", Username = "******", Password = "******"},
                                //new User()
                                //    {
                                //        Id = 2,
                                //        Name = "admin",
                                //        Email = "*****@*****.**",
                                //        Username = "******",
                                //        Password = "******"
                                //    }
                            };
            mockUser.Setup(m => m.GetAll()).Returns(users.AsQueryable());
            builder.RegisterInstance(mockUser.Object).As<IUserRepository>().SingleInstance();
            #endregion
        }
        public void UpdateGames(List<Game> oldGames, List<Game> newGames)
        {
            foreach (var oldGame in oldGames)
            {
                var matchingNewGame =
                    newGames.SingleOrDefault(
                        g => g.HomePlayer == oldGame.HomePlayer && g.AwayPlayer == oldGame.AwayPlayer);

                if (matchingNewGame != null)
                {
                    if (matchingNewGame.Result != Constants.NotPlayed)
                    {
                        if (oldGame.Result == Constants.NotPlayed)
                            oldGame.PlayedDate = _timeProvider.GetCurrentTime();

                        oldGame.Result = matchingNewGame.Result;
                    }
                    else
                    {
                        oldGame.Result = Constants.NotPlayed;
                        oldGame.PlayedDate = null;
                    }
                }
            }
        }
Exemple #19
0
 private static void MapSprites(List <SpriteRenderer> spriteRenderers, List <Sprite> sprites)
 {
     foreach (var part in spriteRenderers)
     {
         part.sprite = sprites?.SingleOrDefault(i => i != null && i.name == part.name.Split('[')[0]);
     }
 }
Exemple #20
0
        public void InitializeCollisionBoxes(int tileID, List<TileCollisionBox> dbCollisionBoxes)
        {
            this.TileID = tileID;
            int collisionBoxWidth = (int)MappingEnum.TileWidth / (int)MappingEnum.CollisionBoxDivisor;
            int collisionBoxHeight = (int)MappingEnum.TileHeight / (int)MappingEnum.CollisionBoxDivisor;
            int numberOfCollisionBoxesRows = (int)MappingEnum.CollisionBoxDivisor;
            int numberOfCollisionBoxesColumns = (int)MappingEnum.CollisionBoxDivisor;

            // In FRB, the origin is at the center of the sprite. We need to compensate for this by shifting
            // the collision boxes to the left (negative X) and up (positive Y)
            int offsetX = ((int)MappingEnum.TileWidth / 2) - (collisionBoxWidth / 2);
            int offsetY = ((int)MappingEnum.TileHeight / 2) - (collisionBoxHeight / 2);

            int tileLocationIndex = 1;
            for (int row = 0; row < numberOfCollisionBoxesRows; row++)
            {
                for (int column = 0; column < numberOfCollisionBoxesColumns; column++)
                {
                    TileCollisionBox dbBox = dbCollisionBoxes.SingleOrDefault(x => x.TileLocationIndex == tileLocationIndex);
                    TileCollisionBoxEntity box = TileCollisionBoxEntityFactory.CreateNew();
                    box.TileRow = row;
                    box.TileColumn = column;
                    box.TileIndex = tileLocationIndex;
                    box.IsPassable = dbBox == null ? false : dbBox.IsPassable;

                    box.X = (this.Position.X - offsetX) + (column * collisionBoxWidth);
                    box.Y = (this.Position.Y + offsetY) - (row * collisionBoxHeight);

                    tileLocationIndex++;
                }
            }
        }
Exemple #21
0
        public ManualImportItem ReprocessItem(string path, string downloadId, int movieId, string releaseGroup, QualityModel quality, List <Language> languages)
        {
            var rootFolder = Path.GetDirectoryName(path);
            var movie      = _movieService.GetMovie(movieId);

            var downloadClientItem = GetTrackedDownload(downloadId)?.DownloadItem;

            var languageParse = LanguageParser.ParseLanguages(path);

            if (languageParse.Count <= 1 && languageParse.First() == Language.Unknown && movie != null)
            {
                languageParse = new List <Language> {
                    movie.OriginalLanguage
                };
                _logger.Debug("Language couldn't be parsed from release, fallback to movie original language: {0}", movie.OriginalLanguage.Name);
            }

            var localEpisode = new LocalMovie
            {
                Movie                   = movie,
                FileMovieInfo           = Parser.Parser.ParseMoviePath(path),
                DownloadClientMovieInfo = downloadClientItem == null ? null : Parser.Parser.ParseMovieTitle(downloadClientItem.Title),
                Path         = path,
                SceneSource  = SceneSource(movie, rootFolder),
                ExistingFile = movie.Path.IsParentPath(path),
                Size         = _diskProvider.GetFileSize(path),
                Languages    = (languages?.SingleOrDefault() ?? Language.Unknown) == Language.Unknown ? languageParse : languages,
                Quality      = quality.Quality == Quality.Unknown ? QualityParser.ParseQuality(path) : quality,
                ReleaseGroup = releaseGroup.IsNullOrWhiteSpace() ? Parser.Parser.ParseReleaseGroup(path) : releaseGroup,
            };

            return(MapItem(_importDecisionMaker.GetDecision(localEpisode, downloadClientItem), rootFolder, downloadId, null));
        }
        protected void GridInventarioCarros_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            List<Carro> lstCarro = new List<Carro>();

            if (Session["Carros"] != null)
            {
                lstCarro = ((List<Carro>)Session["Carros"]);
            }

            string codigo = GridInventarioCarros.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();


            Carro CarroEncontrado = lstCarro.SingleOrDefault(s => s.Codigo == Convert.ToInt32(codigo));

            if (e.CommandName == "Editar")
            {
                txtNombreMarca.Text = CarroEncontrado.NombreMarca;
                txtModelo.Text = CarroEncontrado.Modelo.ToString();
             }

           /* if (e.CommandName == "Eliminar")
            {
                lstMatri.Remove(MatriculaEncontrada);

                //int indice =   lstFactu.IndexOf(factuEncontrada);
                //lstFactu.RemoveAt(indice);                
            }*/

            GridInventarioCarros.DataSource = lstCarro;
            GridInventarioCarros.DataKeyNames = new string[] { "Codigo" };
            GridInventarioCarros.DataBind();
        }
Exemple #23
0
        public void RavenJToken_DeepEquals_Array_Test()
        {
            var original = new {Tokens = new[] {"Token-1", "Token-2", "Token-3"}};
            var modified = new {Tokens = new[] {"Token-1", "Token-3"}};

            // In modified object we deleted one item "Token-2"

            var difference = new List<DocumentsChanges>();
            if (!RavenJToken.DeepEquals(RavenJObject.FromObject(modified), RavenJObject.FromObject(original), difference))
            {
                // OK
                // 1 difference - "Token-2" value removed
            }

            // Expecting one difference - "Token-2" ArrayValueRemoved
            Assert.True(difference.Count == 1 && difference.SingleOrDefault(x => x.Change == DocumentsChanges.ChangeType.ArrayValueRemoved &&
                                                                                 x.FieldOldValue == "Token-2") != null);

            var originalDoc = new Doc {Names = new List<PersonName> {new PersonName {Name = "Tom1"}, new PersonName {Name = "Tom2"}, new PersonName {Name = "Tom3"}}};
            var modifiedDoc = new Doc {Names = new List<PersonName> {new PersonName {Name = "Tom1"}, new PersonName {Name = "Tom3"}}};

            // In modified object we deleted one item "Tom2"

            difference = new List<DocumentsChanges>();
            if (!RavenJToken.DeepEquals(RavenJObject.FromObject(modifiedDoc), RavenJObject.FromObject(originalDoc), difference))
            {
                // SOMETHING WRONG?
                // 3 differences - "Tom1", "Tom2", "Tom3" objects removed
            }

            // Expecting one difference - "Tom2" ArrayValueRemoved
            Assert.True(difference.Count == 1 && difference.SingleOrDefault(x => x.Change == DocumentsChanges.ChangeType.ArrayValueRemoved &&
                                                                                 x.FieldOldValue == "{\r\n  \"Name\": \"Tom2\"\r\n}") != null);
        }
Exemple #24
0
        public async Task <User> AuthenticateAsync(string username, string password)
        {
            var user = _users?.SingleOrDefault(x => x.Username == username && x.Password == password);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Username.ToString()),
                    new Claim(ClaimTypes.Role, user.Roles),
                }),

                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token = tokenHandler.WriteToken(token);

            // remove password before returning
            user.Password = null;

            return(user);
        }
Exemple #25
0
        private void SetArmorParts(List <SpriteRenderer> renderers, List <Sprite> armor, Color?color)
        {
            foreach (var r in renderers)
            {
                var mapping = r.GetComponent <SpriteMapping>();
                var sprite  = armor?.SingleOrDefault(j => mapping.SpriteName == j.name || mapping.SpriteNameFallback.Contains(j.name));

                if (sprite != null)
                {
                    if (Armor == null)
                    {
                        Armor = new List <Sprite>();
                    }

                    if (sprite.name == mapping.SpriteName)
                    {
                        Armor.RemoveAll(i => i == null || i.name == mapping.SpriteName);
                    }
                    else
                    {
                        Armor.RemoveAll(i => i == null || mapping.SpriteNameFallback.Contains(i.name));
                    }

                    Armor.Add(sprite);
                }

                if (color != null)
                {
                    r.color = color.Value;
                }
            }
        }
Exemple #26
0
        public IEnumerable<ViewTopFiveVoters> Get(int Id)
        {
            List<ViewTopFiveVoters> voters = new List<ViewTopFiveVoters>();
            var output = from p in _db.VoteHistory
                         where p.ProposalId == Id
                         group p by p.UserId into g

                         select new { UserId = g.Key, NoVote = g.Count() };

            var output2 = output.OrderByDescending(c => c.NoVote).Take(5).ToList();
               int Rank = 1;
            foreach (var item in output2)
            {
                Models.User user = _db.User.FirstOrDefault(c=>c.UserId == item.UserId);

                voters.Add(new ViewTopFiveVoters { Id = item.UserId, Email = user.Email, Image = user.Image, Name = user.Name, Rank = Rank++ });
            }
            var allvoters = output.OrderByDescending(c=>c.NoVote).ToList();
            int CurentRank = allvoters.AsQueryable().Select((user, index) => new { user.UserId, index }).Where(user => user.UserId == WebSecurity.CurrentUserId).Select(c=>c.index).FirstOrDefault();//finding ranking number
            CurentRank++;
            ViewTopFiveVoters check = voters.SingleOrDefault(c => c.Id == WebSecurity.CurrentUserId);

            if (CurentRank >= 5 && check == null)
            {
                voters.RemoveAt(4);
                Models.User me = _db.User.FirstOrDefault(c=>c.UserId == WebSecurity.CurrentUserId);
                voters.Insert(4, new ViewTopFiveVoters { Id = WebSecurity.CurrentUserId, Rank = CurentRank, Email = me.Email, Image = me.Image, Name = me.Name });
            }

            return voters;
        }
Exemple #27
0
 /// <summary>
 ///     用户登录
 /// </summary>
 /// <param name="model">登录模型信息</param>
 /// <returns>业务操作结果</returns>
 public OperationResult Login(LoginModel model)
 {
     Validator.ValidateObject(model, new ValidationContext(model));
     LoginInfo2 loginInfo = new LoginInfo2
     {
         Access = model.Account,
         Password = model.Password,  
     };
     OperationResult result = base.Login(loginInfo);
     if (result.ResultType == OperationResultType.Success)
     {
         
         User user = (User)result.AppendData;
         List<UserGroup> usergroups =user.UserGroups.ToList();
         List<Res> reses = new List<Res>();
         List<Mdl> mdls = new List<Mdl>();
         foreach (var a in usergroups)
         {
             reses.AddRange(a.Ress);
             mdls.AddRange(a.Mdls);
         }
         if (reses.SingleOrDefault(r=>r.RESCODE==model.ResCode)==null)
         {
             result.ResultType = OperationResultType.Error;
             result.Message = "用户没有该资源的权限";
         }
         result.AppendData = mdls;                    
     }
     return result;
 }
        public Field GetCorrespondingField(string destinationFieldName, List<FieldMappingConfiguration> mappingConfigs)
        {
            Field sourceField;
            if (mappingConfigs != null)
            {
                var mappingConfig = mappingConfigs.SingleOrDefault(m => m.DestinationFieldName.Equals(destinationFieldName, StringComparison.InvariantCultureIgnoreCase));
                if (mappingConfig != null)
                {
                    string mapSourceFieldName = mappingConfig.SourceFieldName != null ? mappingConfig.SourceFieldName : destinationFieldName;
                    sourceField = GetField(mapSourceFieldName);
                }
                else
                {
                    string mapSourceFieldName = destinationFieldName;
                    sourceField = GetField(mapSourceFieldName);
                }
            }
            else
            {
                string mapSourceFieldName = destinationFieldName;
                sourceField = GetField(mapSourceFieldName);
            }

            return sourceField;
        }
 public void ApplyDeviceConfigurationModels(List<DeviceConfiguration> deviceConfigurations, List<CoinConfiguration> coinConfigurations)
 {
     foreach (DeviceViewModel deviceViewModel in Devices)
     {
         DeviceConfiguration deviceConfiguration = deviceConfigurations.SingleOrDefault(dc => dc.Equals(deviceViewModel));
         if (deviceConfiguration != null)
         {
             deviceViewModel.Enabled = deviceConfiguration.Enabled;
             if (!String.IsNullOrEmpty(deviceConfiguration.CoinSymbol))
             {
                 CoinConfiguration coinConfiguration = coinConfigurations.SingleOrDefault(
                     cc => cc.Coin.Symbol.Equals(deviceConfiguration.CoinSymbol, StringComparison.OrdinalIgnoreCase));
                 if (coinConfiguration != null)
                     deviceViewModel.Coin = coinConfiguration.Coin;
             }
         }
         else
         {
             deviceViewModel.Enabled = true;
             CoinConfiguration coinConfiguration = coinConfigurations.SingleOrDefault(
                 cc => cc.Coin.Symbol.Equals("BTC", StringComparison.OrdinalIgnoreCase));
             if (coinConfiguration != null)
                 deviceViewModel.Coin = coinConfiguration.Coin;
         }
     }
 }
        public override IList<HtmlCompletion> GetEntries(HtmlCompletionContext context)
        {
            var list = new List<HtmlCompletion>();
            string tagName = context.Element.Name.ToLowerInvariant();
            string attrName = context.Attribute.Name.ToLowerInvariant();


            var all = HtmlCache.Elements.Single(e => e.Name == "*").Attributes.ToList();

            HtmlElement element = HtmlCache.Elements.SingleOrDefault(e => e.Name == tagName);

            if (element != null && element.Attributes != null)
                all.AddRange(element.Attributes);

            var attributes = new List<HtmlAttribute>();

            foreach (var attribute in all)
            {
                if (!string.IsNullOrEmpty(attribute.Require))
                {
                    if (context.Element.GetAttribute(attribute.Require) != null)
                        attributes.Add(attribute);
                }
                else
                {
                    attributes.Add(attribute);
                }
            }

            var attr = attributes.SingleOrDefault(a => a.Name == attrName);

            return AddAttributeValues(context, attr?.Values);
        }
Exemple #31
0
        public static List<TagEntity> GetTagEntities(this ITag tagRepository, List<string> tags)
        {
            var newTags = new List<string>();
            var allTags = tagRepository.GetAllTags();

            var existingTags = allTags.Select(t => t.TagName.ToLower()).ToList();
            
            tags.ForEach(tag =>
                {
                    if (tag != null && tag.Trim() != string.Empty && !existingTags.Contains(tag.ToLower()) && newTags.SingleOrDefault(newtag => newtag.ToLower() == tag.ToLower()) == null)
                        newTags.Add(tag.Trim());
                });

            var allSlugs = allTags.Select(t => t.TagSlug).ToList();

            var newTagsList = new List<TagEntity>();
            newTags.ForEach(tag =>
                {
                    var slug = tag.GetUniqueSlug(allSlugs);
                    allSlugs.Add(slug);
                    newTagsList.Add(new TagEntity {TagName = tag, TagSlug = slug});
                });

            return newTagsList;
        }
        public void ProcessResults_ForWebhooks_HandlesSingleResult()
        {
            var accActReqProc = new AccountActivityRequestProcessor <AccountActivity>
            {
                BaseUrl = "https://api.twitter.com/1.1/",
                Type    = AccountActivityType.Webhooks
            };

            List <AccountActivity> accActs = accActReqProc.ProcessResults(WebhooksResponse);

            Assert.IsNotNull(accActs?.SingleOrDefault());

            AccountActivity accAct = accActs.First();

            Assert.IsNotNull(accAct);
            WebhooksValue webhooksVal = accAct.WebhooksValue;

            Assert.IsNotNull(webhooksVal);
            Webhook[] webhooks = webhooksVal.Webhooks;
            Assert.IsNotNull(webhooks);
            Assert.AreEqual(1, webhooks.Length);
            Webhook webhook = webhooks.First();

            Assert.IsNotNull(webhook);
            Assert.AreEqual("920835776169910272", webhook.ID);
            Assert.AreEqual("https://accountactivitydemo.azurewebsites.net/api/accountactivity", webhook.Url);
            Assert.IsTrue(webhook.Valid);
            Assert.AreEqual("2017-10-19 02:15:32 +0000", webhook.CreatedTimestamp);
        }
Exemple #33
0
        public static string ReplacePathSegment(string path, string value, List<object> segments)
        {
            var segment = segments.SingleOrDefault(s => s.Equals(string.Format("?{0}=", value)) || s.Equals(string.Format("&{0}=", value)));
            if (segment != null)
            {
                var index = segments.IndexOf(segment);
                path = path.Replace(string.Format("{{{0}}}", value), string.Concat(segments[index + 1]));
                segments.RemoveRange(index, 2);

                // Replace missing ? if the segment was first in the series (after format)
                if(index == 1 && segments.Count > 1)
                {
                    var first = segments[index].ToString();
                    if(first.StartsWith("&"))
                    {
                        segments[index] = string.Concat("?", first.Substring(1));
                    }
                }
            }
            else
            {
                path = path.Replace(string.Format("/{{{0}}}", value), "");
            }
            return path;
        }
        private static void InitEmployeesAndManagers()
        {
            _employees = Enumerable.Range(1, 5).Select(i =>
                        new Employee
                        {
                            ID = i,
                            FullName = "Name" + i,
                            Sex = Gender.Female,
                            Address = new Address()
                            {
                                Street = "Street" + i,
                                City = "City" + i,
                            },
                        }).ToList();
            for (int i = 6; i <= 10; i++)
            {
                _employees.Add(
                            new Manager
                            {
                                ID = i,
                                FullName = "Name" + i,
                                Sex = Gender.Male,
                                Address = new Address()
                                {
                                    Street = "Street" + i,
                                    City = "City" + i,
                                },
                            });
            }

            foreach (Employee employee in _employees)
            {
                employee.Next = _employees.SingleOrDefault(e => e.ID == employee.ID + 1);
            }

            // Setup a circular reference
            Employee employeeNo2 = _employees.Single(e => e.ID == 2);
            employeeNo2.Next = _employees.Single(e => e.ID == 1);

            // Report lines:
            // 6 -> 7 -> 8 -> 9 -> 10
            // ^    ^    ^    ^    ^
            // 1    2    3    4    5
            for (int i = 1; i <= 5; i++)
            {
                Employee employee = _employees.Single(e => e.ID == i);
                employee.Manager = _employees.Single(e => e.ID == employee.ID + 5) as Manager;
            }
            for (int i = 6; i <= 9; i++)
            {
                Employee manager = _employees.Single(e => e.ID == i);
                manager.Manager = (Manager)_employees.Single(e => e.ID == manager.ID + 1);
            }
            for (int i = 6; i <= 10; i++)
            {
                Manager manager = (Manager)_employees.Single(e => e.ID == i);
                manager.DirectReports = _employees.Where(e => e.Manager != null && e.Manager.ID == manager.ID).ToList();
            }
        }
		private static void AddItem(List<Node> nodes, Tuple<int, List<string>> item, int listIndex) {
			var n = nodes.SingleOrDefault(x => x.HandlerName == item.Item2[listIndex]);
			if (n == null)
				nodes.Add(n = new Node(item.Item2[listIndex]));
			n.StateValues.Add(item.Item1);
			if (listIndex < item.Item2.Count - 1)
				AddItem(n.Children, item, listIndex + 1);
		}
Exemple #36
0
        public async Task <PlayerEntity> GetByNameHashAsync(string playerNameHash)
        {
            List <PlayerEntity> players = await GetAsync();

            PlayerEntity player = players?.SingleOrDefault(player => player.NameHash == playerNameHash);

            return(player);
        }
Exemple #37
0
        public async Task <PlayerHistoryEntity> GetByIDAsync(int playerHistoryID)
        {
            List <PlayerHistoryEntity> historyEntities = await GetAsync();

            PlayerHistoryEntity historyEntity = historyEntities?.SingleOrDefault(h => h.PlayerHistoryID == playerHistoryID);

            return(historyEntity);
        }
Exemple #38
0
        public async Task <PlayerEntity> GetByPlayerIDAsync(int playerID)
        {
            List <PlayerEntity> players = await GetAsync();

            PlayerEntity player = players?.SingleOrDefault(player => player.PlayerID == playerID);

            return(player);
        }
Exemple #39
0
        private void HandleRemoveItem()
        {
            NWPlayer    oPC     = (_.GetLastDisturbed());
            NWItem      oItem   = (_.GetInventoryDisturbItem());
            NWPlaceable device  = (Object.OBJECT_SELF);
            NWPlaceable storage = (_.GetObjectByTag("craft_temp_store"));
            var         model   = CraftService.GetPlayerCraftingData(oPC);

            if (oPC.IsBusy)
            {
                ItemService.ReturnItem(device, oItem);
                oPC.SendMessage("You are too busy right now.");
                return;
            }

            if (oItem.Resref == "cft_confirm")
            {
                oItem.Destroy();
                device.DestroyAllInventoryItems();
                device.IsLocked          = false;
                model.IsAccessingStorage = false;
                DialogService.StartConversation(oPC, device, "CraftItem");
                return;
            }

            List <NWItem> items = null;

            switch (model.Access)
            {
            case CraftingAccessType.MainComponent:
                items = model.MainComponents;
                break;

            case CraftingAccessType.SecondaryComponent:
                items = model.SecondaryComponents;
                break;

            case CraftingAccessType.TertiaryComponent:
                items = model.TertiaryComponents;
                break;

            case CraftingAccessType.Enhancement:
                items = model.EnhancementComponents;
                break;
            }

            NWItem copy     = storage.InventoryItems.SingleOrDefault(x => x.GlobalID == oItem.GlobalID);
            NWItem listItem = items?.SingleOrDefault(x => x.GlobalID == oItem.GlobalID);

            if (listItem == null || copy == null || !copy.IsValid)
            {
                return;
            }

            copy.Destroy();
            items.Remove(listItem);
        }
 public void SetRatings(ref List<WeightGenerationResultItem> items, IList<decimal> ratings)
 {
     for (int i = 0; i < Project.Factors.Count; i++)
     {
         var id = items[i].WeightGenerationResultItemId;
         var item = items.SingleOrDefault(x => x.WeightGenerationResultItemId == id);
         item.Rating = ratings[i];
     }
 }
        private const string _formatItemsRegex = @"({+)[a-zA-Z_]+(?:(?:\.[a-zA-Z_])?[a-zA-Z0-9_]*)*(?::(?:n|N))?(}+)"; // {fieldPath[:indicator]}, e.g. {field}, {field.field:n}

        public static string FormatString(string input, out IList<FormatItem> items)
        {
            Debug.Assert(input != null);

            items = new List<FormatItem>();
            var matches = Regex.Matches(input, _formatItemsRegex);
            var message = new StringBuilder();

            Match prev = null;
            for (var i = 0; i < matches.Count; i++)
            {
                var match = matches[i];
                var item = match.Value;
                var leftBraces = match.Groups[1];
                var rightBraces = match.Groups[2];

                if (leftBraces.Length != rightBraces.Length)
                    throw new FormatException("Input string was not in a correct format.");

                var start = prev != null ? prev.Index + prev.Length : 0;
                var chars = match.Index - start;
                message.Append(input.Substring(start, chars));
                prev = match;

                var added = items.SingleOrDefault(x => x.Body == item);
                if (added != null)
                {
                    message.Append(added.Uuid);
                    continue;
                }

                var length = leftBraces.Length;

                // flatten each pair of braces into single brace in order to escape them (just like string.Format() does)
                var leftBracesFlattened = new string('{', length / 2);
                var rightBracesFlattened = new string('}', length / 2);

                var uuid = Guid.NewGuid();
                var param = item.Substring(length, item.Length - 2 * length);
                var current = new FormatItem
                {
                    Uuid = uuid,
                    Body = item,
                    Constant = length % 2 == 0,
                    FieldPath = param.Contains(":") ? param.Substring(0, param.IndexOf(":", StringComparison.Ordinal)) : param,
                    Indicator = param.Contains(":") ? param.Substring(param.IndexOf(":", StringComparison.Ordinal) + 1) : null,
                    Substitute = $"{leftBracesFlattened}{(length%2 != 0 ? uuid.ToString() : param)}{rightBracesFlattened}" // for odd number of braces, substitute param with respective value (just like string.Format() does)
                };
                items.Add(current);
                message.Append(current.Uuid);
            }

            if(prev != null)            
                message.Append(input.Substring(prev.Index + prev.Length));

            return message.Length > 0 ? message.ToString() : input;
        }
Exemple #42
0
        /// <summary>
        /// Returns the matching <see cref="Product"></see> by ID, if it exists.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Product FindProduct(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(nameof(id));
            }

            return(Products?.SingleOrDefault(p => p.Id.Equals(id?.Trim())));
        }
Exemple #43
0
        private static bool IsRequiredSection(List <RoatpApplySequence> applicationSequences, Section section)
        {
            var appSequence = applicationSequences?.SingleOrDefault(appSeq => appSeq.SequenceNo == section.SequenceNo);

            var notRequired = appSequence is null ||
                              appSequence.NotRequired ||
                              appSequence.Sections is null ||
                              appSequence.Sections.Any(appSec => appSec.SectionNo == section.SectionNo && appSec.NotRequired);

            return(!notRequired);
        }
Exemple #44
0
 /// <summary>
 /// Get Sample data by Id
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public Sample GetSampleById(string id)
 {
     try
     {
         var resultSample = sampleList?.SingleOrDefault(x => x.Id == id);
         return(resultSample);
     }
     catch (Exception ex)
     {
         // Here we need log the error properly
         throw ex;
     }
 }
Exemple #45
0
        private dynamic GetJsonValue(List <Answer> answers, Question question)
        {
            var json = answers?.SingleOrDefault(a => a?.QuestionId == question.QuestionId)?.Value;

            try
            {
                JToken.Parse(json);
                return(JsonConvert.DeserializeObject <dynamic>(json));
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemple #46
0
        public async Task NextRunAsync(CommandContext ctx, [RemainingText, Description("The id of the reminder.")]
                                       string id)
        {
            string
                cleanId = id
                          .Trim('\"'); // Because the id is flagged with remainder we need to strip leading and trailing " if entered by the user

            if (cleanId.IsEmpty())
            {
                await ctx.ErrorAsync("You need to specify an ID for the reminder!");

                return;
            }

            try
            {
                List <Reminder> reminders = await _reminderService.GetRemindersForGuildAsync(ctx.Guild.Id);

                Reminder reminder = reminders?.SingleOrDefault(reminder => reminder.Name == cleanId);

                if (reminder == null)
                {
                    await ctx.ErrorAsync("The specified reminder does not exist");

                    return;
                }

                DateTime nextRun = await _reminderService.GetNextOccurenceAsync(cleanId, ctx.Guild.Id);

                await ctx.RespondAsync(nextRun.ToString());

                DiscordChannel channel = ctx.Guild.GetChannel(reminder.ChannelId);

                if (reminder.Type == ReminderType.Recurring)
                {
                    await ctx.RespondAsync(
                        $"Recurring reminder with ID: \"{reminder.Name}\" will run next at {nextRun} in channel {channel?.Name} with message: \"{reminder.Message}\"");
                }
                else if (reminder.Type == ReminderType.Once)
                {
                    await ctx.RespondAsync(
                        $"Single reminder with ID: \"{reminder.Name}\" will run once at {nextRun} in channel {channel?.Name} with message: \"{reminder.Message}\"");
                }
            }
            catch (Exception ex)
            {
                await ctx.ErrorAsync(ex.Message);
            }
        }
        /// <summary>
        /// Get the transaction for the the given application id
        /// </summary>
        /// <param name="id">application id</param>
        /// <returns></returns>
        public TransactionModel GetTrasactionByID(int id)
        {
            TransactionModel transaction = null;

            try
            {
                transaction = allTransactions?.SingleOrDefault(x => x.ApplicationId == id);
                return(transaction);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(transaction);
        }
        public KeyValue this[string key]
        {
            get
            {
                var child = Children?.SingleOrDefault(
                    c => string.Compare(c.Name, key, StringComparison.InvariantCultureIgnoreCase) == 0);

                if (child == null)
                {
                    return(Invalid);
                }

                return(child);
            }
        }
Exemple #49
0
        private void SetArmorParts(string part, List <Sprite> armor)
        {
            var sprite = armor?.SingleOrDefault(j => j.name == part);

            Armor?.RemoveAll(i => i == null || i.name == part);

            if (sprite != null)
            {
                if (Armor == null)
                {
                    Armor = new List <Sprite>();
                }

                Armor.Add(sprite);
            }
        }
Exemple #50
0
        // start drawing TODO move to drawing lib
        private int DrawRow(SKCanvas canvas, List <string> row, int rowId, int padding, int currentHeight, List <int> widths, bool isTitle = false)
        {
            float highestSize       = 0;
            int   currentWidthStart = padding;

            for (int i = 0; i < row.Count; i++)
            {
                int cellWidth = widths.ElementAt(i);

                string text = row.ElementAt(i);

                var paint = isTitle ? DrawingHelper.TitleTextPaint : DrawingHelper.DefaultTextPaint;

                var tableInfo = TableRowInfo?.SingleOrDefault(i => i.RowId == rowId);
                if (tableInfo?.Cells != null)
                {
                    if (tableInfo.Value.Cells?.Any(c => c.ColumnId == i) ?? false)
                    {
                        var cellInfo = tableInfo.Value.Cells.Single(c => c.ColumnId == i);
                        paint.Color = cellInfo.FontColor;
                    }
                }

                int usedHeight = (int)DrawTextArea(canvas, paint, currentWidthStart + 5, currentHeight, widths[i], paint.TextSize, text);

                if (usedHeight > highestSize)
                {
                    highestSize = usedHeight;
                }

                currentWidthStart += cellWidth;
            }

            //currentHeight = (int)highestSize + padding / 5;

            currentWidthStart = padding;

            for (int i = 0; i < row.Count; i++)
            {
                currentWidthStart += widths.ElementAt(i);
            }


            return((int)highestSize);
        }
        public void ProcessResults_ForSubscriptions_HandlesResult()
        {
            var accActReqProc = new AccountActivityRequestProcessor <AccountActivity>
            {
                BaseUrl   = "https://api.twitter.com/1.1/",
                Type      = AccountActivityType.Subscriptions,
                WebhookID = 1
            };

            List <AccountActivity> accActs = accActReqProc.ProcessResults("");

            AccountActivity accAct = accActs?.SingleOrDefault();

            Assert.IsNotNull(accAct);
            SubscriptionValue subsVal = accAct.SubscriptionValue;

            Assert.IsNotNull(subsVal);
            Assert.IsTrue(subsVal.IsSubscribed);
        }
Exemple #52
0
        public async Task ShouldPostBookWithSingleAuthorAndGenre()
        {
            var authorList = new List <BookAuthorEntity>();
            var genreList  = new List <BookGenreEntity>();

            authorList.Add(new BookAuthorEntity {
                AuthorId = (await PostAuthor()).Id
            });
            genreList.Add(new BookGenreEntity {
                GenreId = (await PostGenre()).Id
            });

            var book = new BookEntity //Criando o livro
            {
                Name           = "HarryPotter I",
                Price          = 10,
                ListBookAuthor = authorList,
                ListBookGenres = genreList
            };

            var postResponse = (ObjectResult)await _bookController.Post(book);  //Inserindo no banco na mémoria

            book = (BookEntity)postResponse.Value;

            var getResponse = (ObjectResult)await _bookController.Get(book.Id);

            var bookResponse = (BookEntity)getResponse.Value;

            var bookAuthorId = bookResponse.ListBookAuthor.SingleOrDefault()?.AuthorId;
            var authorId     = authorList.SingleOrDefault()?.AuthorId;

            var bookGenreId = bookResponse.ListBookGenres.SingleOrDefault()?.GenreId;
            var genreId     = genreList?.SingleOrDefault()?.GenreId;

            Assert.AreEqual(200, postResponse.StatusCode);
            Assert.AreEqual(200, getResponse.StatusCode);
            Assert.AreEqual(bookResponse.Id, book.Id);
            Assert.AreEqual(bookAuthorId, authorId);
            Assert.AreEqual(bookGenreId, genreId);
        }
Exemple #53
0
        public ManualImportItem ReprocessItem(string path, string downloadId, int movieId, QualityModel quality, List <Language> languages)
        {
            var rootFolder = Path.GetDirectoryName(path);
            var movie      = _movieService.GetMovie(movieId);

            var downloadClientItem = GetTrackedDownload(downloadId)?.DownloadItem;

            var localEpisode = new LocalMovie
            {
                Movie                   = movie,
                FileMovieInfo           = Parser.Parser.ParseMoviePath(path),
                DownloadClientMovieInfo = downloadClientItem == null ? null : Parser.Parser.ParseMovieTitle(downloadClientItem.Title),
                Path         = path,
                SceneSource  = SceneSource(movie, rootFolder),
                ExistingFile = movie.Path.IsParentPath(path),
                Size         = _diskProvider.GetFileSize(path),
                Languages    = (languages?.SingleOrDefault() ?? Language.Unknown) == Language.Unknown ? LanguageParser.ParseLanguages(path) : languages,
                Quality      = quality.Quality == Quality.Unknown ? QualityParser.ParseQuality(path) : quality
            };

            return(MapItem(_importDecisionMaker.GetDecision(localEpisode, downloadClientItem), rootFolder, downloadId, null));
        }
Exemple #54
0
        //makes a list with all artists and songs saved
        private async Task GetSavedList(List <SongBundle> songList)
        {
            artistList = new List <Artist>();

            Log(Type.Processing, "Starting foreach loop");
            foreach (SongBundle s in songList)
            {
                //finds the first Artist that matches the artist name from the song
                Artist existingArtist = artistList?.SingleOrDefault(x => x.Name == s.Normal.Artist);

                //! I think this is from StackOverflow, in a question I asked...
                //checks if the Artist was found in "artistList", adds them if it wasn't
                if (existingArtist != null)
                {
                    existingArtist.Songs.Add(s);
                    if (s.Normal.Romanized && s.Romanized != null && string.IsNullOrEmpty(s.Romanized.Artist))
                    {
                        existingArtist.RomanizedName = s.Romanized.Artist;
                    }
                }
                else
                {
                    Artist artist = new Artist
                    {
                        Name  = s.Normal.Artist,
                        Songs = new List <SongBundle>()
                    };

                    if (s.Normal.Romanized && s.Romanized != null && !string.IsNullOrEmpty(s.Romanized.Artist))
                    {
                        artist.RomanizedName = s.Romanized.Artist;
                    }

                    artist.Songs.Add(s);
                    artistList.Add(artist);
                }
            }
        }
Exemple #55
0
 private static SearchResults GenerateSearchResults(
     List <Shirt> shirts           = null,
     List <ColorCount> colorCounts = null,
     List <SizeCount> sizeCounts   = null)
 {
     return(new SearchResults
     {
         Shirts = shirts ?? new List <Shirt>(),
         ColorCounts = Color.All.Select(color =>
                                        colorCounts?.SingleOrDefault(colorCount => colorCount.Color == color)
                                        ?? new ColorCount {
             Color = color, Count = 0
         })
                       .ToList(),
         SizeCounts = Size.All.Select(size =>
                                      sizeCounts?.SingleOrDefault(sizeCount => sizeCount.Size == size)
                                      ?? new SizeCount()
         {
             Size = size, Count = 0
         })
                      .ToList()
     });
 }
Exemple #56
0
        public void ProcessResults_ForList_HandlesMultipleResults()
        {
            var dmReqProc = new DirectMessageEventsRequestProcessor <DirectMessageEvents>
            {
                BaseUrl = "https://api.twitter.com/1.1/",
                Type    = DirectMessageEventsType.List
            };

            List <DirectMessageEvents> dms = dmReqProc.ProcessResults(TestQueryMultipleResponses);

            Assert.IsNotNull(dms?.SingleOrDefault());

            DirectMessageEvents dmEvt = dms.First();

            Assert.IsNotNull(dmEvt);
            DirectMessageEventsValue dmVal = dmEvt.Value;

            Assert.IsNotNull(dmVal);
            List <DMEvent> evts = dmVal.DMEvents;

            Assert.IsNotNull(evts);
            Assert.AreEqual(2, evts.Count);
            Assert.AreEqual("OTE3ODE0NTUzMzExOTMyNDIy", dmVal.NextCursor);
        }
Exemple #57
0
 /// <summary>
 /// 获取选项值
 /// </summary>
 /// <param name="key">选项KEY</param>
 /// <param name="userId">用户ID</param>
 /// <returns>选项值</returns>
 public string getParam(string key, string userId = null)
 {
     return(parms?.SingleOrDefault(i => i.key == key && i.userId == userId)?.value);
 }
Exemple #58
0
        private void SetupPage(Page page, List <ValidationErrorDetail> errorMessages)
        {
            Title       = page.Title;
            InfoText    = page.InfoText;
            LinkTitle   = page.LinkTitle;
            DisplayType = page.DisplayType;
            PageId      = page.PageId;

            Feedback    = page.Feedback;
            HasFeedback = page.HasFeedback;

            BodyText = page.BodyText;
            Details  = page.Details;

            PageOfAnswers = page.PageOfAnswers ?? new List <PageOfAnswers>();

            var answers = new List <Answer>();

            // Grab the latest answer for each question stored within the page
            foreach (var pageAnswer in page.PageOfAnswers.SelectMany(poa => poa.Answers))
            {
                var currentAnswer = answers.FirstOrDefault(a => a.QuestionId == pageAnswer.QuestionId);
                if (currentAnswer is null)
                {
                    answers.Add(new Answer()
                    {
                        QuestionId = pageAnswer.QuestionId, Value = pageAnswer.Value
                    });
                }
                else
                {
                    currentAnswer.Value = pageAnswer.Value;
                }
            }

            Questions = new List <QuestionViewModel>();
            Questions.AddRange(page.Questions.Select(q => new QuestionViewModel()
            {
                Label            = q.Label,
                ShortLabel       = q.ShortLabel,
                QuestionBodyText = q.QuestionBodyText,
                QuestionId       = q.QuestionId,
                Type             = q.Input.Type,
                InputClasses     = q.Input.InputClasses,
                InputPrefix      = q.Input.InputPrefix,
                InputSuffix      = q.Input.InputSuffix,
                Hint             = q.Hint,
                Options          = q.Input.Options,
                Validations      = q.Input.Validations,
                Value            = answers?.SingleOrDefault(a => a?.QuestionId == q.QuestionId)?.Value,
                JsonValue        = GetJsonValue(answers, q),
                ErrorMessages    = errorMessages?.Where(f => f.Field.Split("_Key_")[0] == q.QuestionId).ToList(),
                SequenceId       = SequenceId,
                SectionId        = SectionId,
                ApplicationId    = ApplicationId,
                PageId           = PageId,
                RedirectAction   = RedirectAction
            }));

            foreach (var question in Questions)
            {
                if (question.Options == null)
                {
                    continue;
                }
                foreach (var option in question.Options)
                {
                    if (option.FurtherQuestions == null)
                    {
                        continue;
                    }
                    foreach (var furtherQuestion in option.FurtherQuestions)
                    {
                        furtherQuestion.Value = answers
                                                ?.SingleOrDefault(a => a?.QuestionId == furtherQuestion.QuestionId.ToString())?.Value;
                    }
                }
            }

            SetupCallToActionButton();
        }
Exemple #59
0
        public async Task <MatchDetails> GetAsync(string id)
        {
            List <MatchDetails> matchDetailss = await GetMatchDetailssAsync();

            return(matchDetailss?.SingleOrDefault(m => m.Id == id));
        }
        public override Task <List <Class> > FindBlocks(List <string> lines)
        {
            var classes = new List <Class>();

            lines = lines.CleanListOfStrings().ToList();
            var classTableStart = lines.FindIndex(f => f.Equals(Localization.PHBClassesTableStart));
            var classTableEnd   = lines.FindIndex(classTableStart, f => f.Equals(string.Empty));
            var classTableLines = lines.Skip(classTableStart + 3).Take(classTableEnd - (classTableStart + 3)).ToList();

            var classNames = classTableLines.Select(s => s.Split('|')[1].Trim()).ToList();

            classNames.Sort();

            foreach (var classTableLine in classTableLines)
            {
                var classTableLineSplit = classTableLine.Split('|');

                var starWarsClass = new Class
                {
                    Name               = classTableLineSplit[1].Trim(),
                    Summary            = classTableLineSplit[2].Trim(),
                    HitDiceDieTypeEnum = (DiceType)int.Parse(Regex.Match(classTableLineSplit[3], @"\d+").Value),
                    PrimaryAbility     = classTableLineSplit[4].Trim(),
                    SavingThrows       = classTableLineSplit[5].Split('&').Select(s => s.Trim()).ToList()
                };

                var classLinesStart = lines.FindIndex(f => f.StartsWith($"## {starWarsClass.Name}"));
                var nextClassName   = classNames.ElementAtOrDefault(classNames.IndexOf(starWarsClass.Name) + 1);
                var classLines      = lines.Skip(classLinesStart).ToList();
                if (nextClassName != null)
                {
                    var classLinesEnd = lines.FindIndex(classLinesStart, f => f.Equals($"## {nextClassName}"));
                    classLines = lines.Skip(classLinesStart).Take(classLinesEnd - classLinesStart).ToList();
                }

                if (_classImageLus != null)
                {
                    foreach (var classImageLu in _classImageLus.Where(c => c.Class == starWarsClass.Name))
                    {
                        starWarsClass.ImageUrls.Add(classImageLu.URL);
                    }
                }

                if (_multiclassProficiencyLus != null)
                {
                    foreach (var multiclassProficiencyLu in _multiclassProficiencyLus.Where(m => m.Class == starWarsClass.Name))
                    {
                        starWarsClass.MultiClassProficiencies.Add(multiclassProficiencyLu.Proficiency);
                    }
                }

                var casterRatio = _casterRatioLus?.SingleOrDefault(c => c.Name == starWarsClass.Name);
                if (casterRatio != null)
                {
                    starWarsClass.CasterRatio    = casterRatio.Ratio;
                    starWarsClass.CasterTypeEnum = casterRatio.CasterTypeEnum;
                }

                classes.Add(ParseClass(classLines.CleanListOfStrings().ToList(), starWarsClass, ContentType.Core));
            }

            return(Task.FromResult(classes));
        }