Ejemplo n.º 1
0
 /// <summary>
 /// Filter source output with Key and SubKey
 /// </summary>
 /// <param name="source"></param>
 /// <param name="Key"></param>
 /// <param name="SubKey"></param>
 /// <returns></returns>
 public static IEnumerable <RedisInfo> FilterKeySubKey(this System.Collections.Generic.IEnumerable <RedisInfo> source, RedisInfoKeyType[] Key, RedisInfoSubkeyType[] SubKey)
 {
     return(source.Select(item =>
     {
         RedisInfo values = null;
         if (Key == null & SubKey == null)
         {
             // When both Key and Subkey not specified
             values = item;
         }
         else if (Key != null & SubKey == null)
         {
             // when Key specify and output contains it
             if (Key.Where(x => x.ToString() == item.Key).Any())
             {
                 values = item;
             }
         }
         else if (Key == null & SubKey != null)
         {
             // when Subkey specify and output contains it
             if (SubKey.Where(x => x.ToString() == item.SubKey).Any())
             {
                 values = item;
             }
         }
         else if (Key.Where(x => x.ToString() == item.Key).Any() & SubKey.Where(x => x.ToString() == item.SubKey).Any())
         {
             // when Key and Subkey specify and output contains both
             values = item;
         }
         return values;
     }));
 }
Ejemplo n.º 2
0
        public List <FarmTran> Xml_Load()
        {
            XDocument docNew = XDocument.Load(SharedDB.GetDataPath() + "FarmTransData.xml");

            //Console.WriteLine(docNew.ToString());
            System.Collections.Generic.IEnumerable <XElement> nodes = docNew.Element("DocumentElement").Elements("row");

            var nodeList = new List <FarmTran>();

            nodeList = nodes
                       .Select(node => {
                var item             = new FarmTran();
                item.transactionDate = getValue(node, "交易日期");
                item.cropCode        = getValue(node, "作物代號");
                item.cropName        = getValue(node, "作物名稱");
                item.marketCode      = getValue(node, "市場代號");
                item.marketName      = getValue(node, "市場名稱");
                item.priceHigh       = getValue(node, "上價");
                item.priceMid        = getValue(node, "中價");
                item.priceLow        = getValue(node, "下價");
                item.priceAvg        = getValue(node, "平均價");
                item.transactionNum  = getValue(node, "交易量");
                return(item);
            }).ToList();
            return(nodeList);
        }
Ejemplo n.º 3
0
 protected virtual System.Collections.Generic.IEnumerable <object> Get(System.Collections.Generic.IEnumerable <object> source, string strQuery)
 {
     if (source == null)
     {
         return(new object[0]);
     }
     return(Filter(source.Select(x => Get(x)), strQuery));
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets a directory listing from the embedded files in the Hood assembly.
        /// WARNING, this should only be used for loading files in known definite locations. as the
        /// file provider uses a flat structure, sub-directories will be returned along with the files.
        /// </summary>
        /// <param name="basePath">The base path in the form ~/path/of/the/file.extension</param>
        /// <returns></returns>
        public static string[] GetFiles(string basePath)
        {
            basePath = ReWritePath(basePath);
            EmbeddedFileProvider provider = GetProvider(Engine.Services.Resolve <IConfiguration>());

            if (provider == null)
            {
                return(new List <string>().ToArray());
            }
            IDirectoryContents contents = provider.GetDirectoryContents("");

            System.Collections.Generic.IEnumerable <IFileInfo> dir = contents.Where(p => p.Name.StartsWith(basePath));
            return(dir.Select(f => f.Name.Replace(basePath, "")).ToArray());
        }
Ejemplo n.º 5
0
        private static System.Collections.Generic.IEnumerable <byte> EncryptOutput(byte[] key, System.Collections.Generic.IEnumerable <byte> data)
        {
            byte[] s = EncryptInitalize(key);
            int    i = 0;
            int    j = 0;

            return(data.Select((b) =>
            {
                i = (i + 1) & 255;
                j = (j + s[i]) & 255;
                Swap(s, i, j);

                return (byte)(b ^ s[(s[i] + s[j]) & 255]);
            }));
        }
Ejemplo n.º 6
0
        static void ShowAgents(System.Collections.Generic.IEnumerable <Agent> AllAgents)
        {
            var agents = AllAgents.Select(a => new
            {
                Hostname     = a.Hostname,
                Ip           = a.Ip,
                Resources    = String.Join(", ", a.Resources),
                Environments = String.Join(", ", a.Environments),
                Uuid         = a.Uuid
            });

            ConsoleTableBuilder
            .From(agents.ToList())
            .WithFormat(ConsoleTableBuilderFormat.Minimal)
            .ExportAndWriteLine()
            ;
        }
        public override void Process(GetDependenciesArgs context)
        {
            Func <ItemUri, bool> func = null;

            Assert.IsNotNull(context.IndexedItem, "Indexed item is null");
            Assert.IsNotNull(context.Dependencies, "Dependencies not found");
            Item item = (Item)(context.IndexedItem as SitecoreIndexableItem);

            if (item != null)
            {
                if (func == null)
                {
                    func = uri => (bool)((uri != null) && ((bool)(uri != item.Uri)));
                }
                System.Collections.Generic.IEnumerable <ItemUri> source = Enumerable.Where <ItemUri>(from l in Globals.LinkDatabase.GetReferrers(item, FieldIDs.LayoutField) select l.GetSourceItem().Uri, func).Distinct <ItemUri>();
                context.Dependencies.AddRange(source.Select(x => (SitecoreItemUniqueId)x));
            }
        }
Ejemplo n.º 8
0
        /// <summary>Get validator duties for the requested validators.</summary>
        /// <param name="validator_pubkeys">An array of hex-encoded BLS public keys</param>
        /// <returns>Success response</returns>
        public async Task <ICollection <ValidatorDuty> > DutiesAsync(System.Collections.Generic.IEnumerable <byte[]> validator_pubkeys, ulong?epoch)
        {
            IEnumerable <BlsPublicKey> publicKeys = validator_pubkeys.Select(x => new BlsPublicKey(x));
            Epoch targetEpoch           = epoch.HasValue ? new Epoch((ulong)epoch) : Epoch.None;
            var   duties                = _beaconNode.ValidatorDutiesAsync(publicKeys, targetEpoch, CancellationToken.None);
            List <ValidatorDuty> result = new List <ValidatorDuty>();

            await foreach (var duty in duties)
            {
                ValidatorDuty validatorDuty = new ValidatorDuty();
                validatorDuty.Validator_pubkey    = duty.ValidatorPublicKey.Bytes;
                validatorDuty.Attestation_slot    = duty.AttestationSlot;
                validatorDuty.Attestation_shard   = (ulong)duty.AttestationShard;
                validatorDuty.Block_proposal_slot = duty.BlockProposalSlot == Slot.None ? null : (ulong?)duty.BlockProposalSlot;
                result.Add(validatorDuty);
            }
            return(result);
        }
Ejemplo n.º 9
0
        /// <summary>Get validator duties for the requested validators.</summary>
        /// <param name="validator_pubkeys">An array of hex-encoded BLS public keys</param>
        /// <returns>Success response</returns>
        public async Task <ICollection <ValidatorDuty> > DutiesAsync(System.Collections.Generic.IEnumerable <byte[]> validator_pubkeys, int?epoch)
        {
            IEnumerable <BlsPublicKey> publicKeys = validator_pubkeys.Select(x => new BlsPublicKey(x));
            Epoch targetEpoch = epoch.HasValue ? new Epoch((ulong)epoch) : Epoch.None;
            IList <BeaconNode.ValidatorDuty> duties = await _beaconNode.ValidatorDutiesAsync(publicKeys, targetEpoch);

            List <ValidatorDuty> result = duties.Select(x =>
            {
                ValidatorDuty validatorDuty       = new ValidatorDuty();
                validatorDuty.Validator_pubkey    = x.ValidatorPublicKey.Bytes;
                validatorDuty.Attestation_slot    = (int)x.AttestationSlot;
                validatorDuty.Attestation_shard   = (int)(ulong)x.AttestationShard;
                validatorDuty.Block_proposal_slot = x.BlockProposalSlot == Slot.None ? null : (int?)x.BlockProposalSlot;
                return(validatorDuty);
            })
                                          .ToList();

            return(result);
        }
Ejemplo n.º 10
0
 public static G[] CastToAnotherType <T, G>(this System.Collections.Generic.IEnumerable <T> v)
 {
     return(v.Select(x => (G)Convert.ChangeType(x, typeof(G))).ToArray());
 }
Ejemplo n.º 11
0
        void DropNode(HashSet <SolutionEntityItem> projectsToSave, object dataObject, HashSet <ProjectFile> groupedFiles, DragOperation operation)
        {
            FilePath targetDirectory = GetFolderPath(CurrentNode.DataItem);
            FilePath source;
            string   what;
            Project  targetProject = (Project)CurrentNode.GetParentDataItem(typeof(Project), true);
            Project  sourceProject;

            System.Collections.Generic.IEnumerable <ProjectFile> groupedChildren = null;

            if (dataObject is ProjectFolder)
            {
                source        = ((ProjectFolder)dataObject).Path;
                sourceProject = ((ProjectFolder)dataObject).Project;
                what          = Path.GetFileName(source);
            }
            else if (dataObject is ProjectFile)
            {
                ProjectFile file = (ProjectFile)dataObject;

                // if this ProjectFile is one of the grouped files being pulled in by a parent being copied/moved, ignore it
                if (groupedFiles.Contains(file))
                {
                    return;
                }

                if (file.DependsOnFile != null && operation == DragOperation.Move)
                {
                    // unlink this file from its parent (since its parent is not being moved)
                    file.DependsOn = null;

                    // if moving a linked file into its containing folder, simply unlink it from its parent
                    if (file.FilePath.ParentDirectory == targetDirectory)
                    {
                        projectsToSave.Add(targetProject);
                        return;
                    }
                }

                sourceProject = file.Project;
                if (sourceProject != null && file.IsLink)
                {
                    source = sourceProject.BaseDirectory.Combine(file.ProjectVirtualPath);
                }
                else
                {
                    source = file.FilePath;
                }
                groupedChildren = file.DependentChildren;
                what            = null;
            }
            else if (dataObject is Gtk.SelectionData)
            {
                SelectionData data = (SelectionData)dataObject;
                if (data.Type != "text/uri-list")
                {
                    return;
                }
                string sources = System.Text.Encoding.UTF8.GetString(data.Data);
                Console.WriteLine("text/uri-list:\n{0}", sources);
                string[] files = sources.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                for (int n = 0; n < files.Length; n++)
                {
                    Uri uri = new Uri(files[n]);
                    if (uri.Scheme != "file")
                    {
                        return;
                    }
                    if (Directory.Exists(uri.LocalPath))
                    {
                        return;
                    }
                    files[n] = uri.LocalPath;
                }

                IdeApp.ProjectOperations.AddFilesToProject(targetProject, files, targetDirectory);
                projectsToSave.Add(targetProject);
                return;
            }
            else
            {
                return;
            }

            var targetPath = targetDirectory.Combine(source.FileName);

            // If copying to the same directory, make a copy with a different name
            if (targetPath == source)
            {
                targetPath = ProjectOperations.GetTargetCopyName(targetPath, dataObject is ProjectFolder);
            }

            var targetChildPaths = groupedChildren != null?groupedChildren.Select(child => {
                var targetChildPath = targetDirectory.Combine(child.FilePath.FileName);

                if (targetChildPath == child.FilePath)
                {
                    targetChildPath = ProjectOperations.GetTargetCopyName(targetChildPath, false);
                }

                return(targetChildPath);
            }).ToList() : null;

            if (dataObject is ProjectFolder)
            {
                string q;
                if (operation == DragOperation.Move)
                {
                    if (targetPath.ParentDirectory == targetProject.BaseDirectory)
                    {
                        q = GettextCatalog.GetString("Do you really want to move the folder '{0}' to the root folder of project '{1}'?", what, targetProject.Name);
                    }
                    else
                    {
                        q = GettextCatalog.GetString("Do you really want to move the folder '{0}' to the folder '{1}'?", what, targetDirectory.FileName);
                    }
                    if (!MessageService.Confirm(q, AlertButton.Move))
                    {
                        return;
                    }
                }
                else
                {
                    if (targetPath.ParentDirectory == targetProject.BaseDirectory)
                    {
                        q = GettextCatalog.GetString("Do you really want to copy the folder '{0}' to the root folder of project '{1}'?", what, targetProject.Name);
                    }
                    else
                    {
                        q = GettextCatalog.GetString("Do you really want to copy the folder '{0}' to the folder '{1}'?", what, targetDirectory.FileName);
                    }
                    if (!MessageService.Confirm(q, AlertButton.Copy))
                    {
                        return;
                    }
                }
            }
            else if (dataObject is ProjectFile)
            {
                foreach (var file in new FilePath[] { targetPath }.Concat(targetChildPaths))
                {
                    if (File.Exists(file))
                    {
                        if (!MessageService.Confirm(GettextCatalog.GetString("The file '{0}' already exists. Do you want to overwrite it?", file.FileName), AlertButton.OverwriteFile))
                        {
                            return;
                        }
                    }
                }
            }

            var filesToSave = new List <Document> ();

            foreach (Document doc in IdeApp.Workbench.Documents)
            {
                if (doc.IsDirty && doc.IsFile)
                {
                    if (doc.Name == source || doc.Name.StartsWith(source + Path.DirectorySeparatorChar))
                    {
                        filesToSave.Add(doc);
                    }
                    else if (groupedChildren != null)
                    {
                        foreach (ProjectFile f in groupedChildren)
                        {
                            if (doc.Name == f.Name)
                            {
                                filesToSave.Add(doc);
                            }
                        }
                    }
                }
            }

            if (filesToSave.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Document doc in filesToSave)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(",\n");
                    }
                    sb.Append(Path.GetFileName(doc.Name));
                }

                string question;

                if (operation == DragOperation.Move)
                {
                    if (filesToSave.Count == 1)
                    {
                        question = GettextCatalog.GetString("Do you want to save the file '{0}' before the move operation?", sb.ToString());
                    }
                    else
                    {
                        question = GettextCatalog.GetString("Do you want to save the following files before the move operation?\n\n{0}", sb.ToString());
                    }
                }
                else
                {
                    if (filesToSave.Count == 1)
                    {
                        question = GettextCatalog.GetString("Do you want to save the file '{0}' before the copy operation?", sb.ToString());
                    }
                    else
                    {
                        question = GettextCatalog.GetString("Do you want to save the following files before the copy operation?\n\n{0}", sb.ToString());
                    }
                }
                AlertButton noSave = new AlertButton(GettextCatalog.GetString("Don't Save"));
                AlertButton res    = MessageService.AskQuestion(question, AlertButton.Cancel, noSave, AlertButton.Save);
                if (res == AlertButton.Cancel)
                {
                    return;
                }
                else if (res == AlertButton.Save)
                {
                    try {
                        foreach (Document doc in filesToSave)
                        {
                            doc.Save();
                        }
                    } catch (Exception ex) {
                        MessageService.ShowException(ex, GettextCatalog.GetString("Save operation failed."));
                        return;
                    }
                }
            }

            if (operation == DragOperation.Move && sourceProject != null)
            {
                projectsToSave.Add(sourceProject);
            }
            if (targetProject != null)
            {
                projectsToSave.Add(targetProject);
            }

            bool move   = operation == DragOperation.Move;
            var  opText = move ? GettextCatalog.GetString("Moving files...") : GettextCatalog.GetString("Copying files...");

            using (var monitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor(opText, MonoDevelop.Ide.Gui.Stock.CopyIcon, true)) {
                // If we drag and drop a node in the treeview corresponding to a directory, do not move
                // the entire directory. We should only move the files which exist in the project. Otherwise
                // we will need a lot of hacks all over the code to prevent us from incorrectly moving version
                // control related files such as .svn directories

                // Note: if we are transferring a ProjectFile, this will copy/move the ProjectFile's DependentChildren as well.
                IdeApp.ProjectOperations.TransferFiles(monitor, sourceProject, source, targetProject, targetPath, move, true);
            }
        }
Ejemplo n.º 12
0
        private WCFGame ConnectTask(string login, string gamePassword, string homeType)
        {
            //если дом занят или недоступен то наблюдатель
            if (homeType != null && !CheckAccessHomeFunc(login, homeType))
            {
                homeType = null;
            }

            using (Agot2p6Entities dbContext = new Agot2p6Entities())
            {
                WCFUser  profile  = GamePortalServer.GetProfileByLogin(login);
                Game     game     = dbContext.Game.Single(p => p.Id == GameId);
                GameUser gameUser = game.GameUser.SingleOrDefault(p => p.Login == login);

                //Пользователь уже принимал участие
                //_DeniedLogin.TryGetValue(login, out int liaveCount);
                IEnumerable <WCFUserGame> usergames = profile.UserGames.Where(p => p.GameId == this.GameId);
                if (usergames.Count(p => p.EndTime.HasValue && !p.IsIgnoreHonor) > GameHost.MaxLiaveCount)
                {
                    homeType = null;
                    ChatService.AddChat(new Chat()
                    {
                        Creator = "Вестерос", Message = $"dynamic_ExileEarlier*{profile.Api["FIO"]}"
                    });
                }
                else
                {
                    //потенциаьный лорд
                    if (gameUser == null || gameUser.HomeType == null)
                    {
                        //выбран дом и игра не закрыта
                        if (!string.IsNullOrEmpty(homeType) && game.CloseTime == null)
                        {
                            //пароль отсутствует или указан верно
                            if (string.IsNullOrEmpty(game.Password) || game.Password == gamePassword)
                            {
                                //Удаляем наблюдателя
                                if (gameUser != null && gameUser.HomeType == null)
                                {
                                    dbContext.GameUser.Remove(gameUser);
                                    gameUser = null;
                                }

                                //конкретный дом
                                if (homeType != "Random")
                                {
                                    gameUser       = game.HomeUsersSL.SingleOrDefault(p => p.HomeType == homeType);
                                    gameUser.Login = login;
                                }
                                //Случайный дом
                                else
                                {
                                    //Определяем свободные дома и сортируем по имени дома
                                    List <GameUser> freeHome = game.HomeUsersSL.Where(p => p.Login == null).OrderBy(p => p.HomeType).ToList();

                                    //если игрок ранее заходил в эту игру, то определяем за какой дом в последний раз он играл
                                    WCFUserGame lastgame = usergames.OrderBy(p => p.StartTime).LastOrDefault();
                                    if (lastgame != null)
                                    {
                                        //Если этот дом свободен, то отдаём его пользователю
                                        gameUser = freeHome.FirstOrDefault(p => p.HomeType == lastgame.HomeType);
                                        if (gameUser != null)
                                        {
                                            gameUser.Login = login;
                                        }
                                    }

                                    //если дом не присвоен
                                    if (gameUser == null)
                                    {
                                        //отдаём тот дом за который пользователь играл меньше всего
                                        gameUser       = freeHome.OrderBy(p => profile.UserGames.Count(p1 => p1.HomeType == p.HomeType)).First();
                                        gameUser.Login = login;
                                    }

                                    //if (lastgame == null)
                                    //{
                                    //    int index = GameHost.Rnd.Next(freeHome.Count());
                                    //    gameUser = freeHome.ElementAt(index);
                                    //    gameUser.Login = login;
                                    //}
                                }

                                ChatService.AddChat(new Chat()
                                {
                                    Creator = "Вестерос", Message = $"dynamic_hiLord*Faceless Men*homeType_{gameUser.HomeType}"
                                });                                                                                                //profile.Api["FIO"]
                                GameHost.AddUserNotifiFunc(profile, $"dynamic_inGame*{game.Name ?? "text_newGame"}*unknown home"); //{gameUser.HomeType}
                                if (game.OpenTime != null)
                                {
                                    GamePortalServer.StartUserGame(gameUser.Login, gameUser.HomeType, game.Id, game.Type + (game.RandomIndex > 0 || game.IsRandomSkull ? 1 : 0), game.NoTimer, true);
                                }
                            }
                            else
                            {
                                ChatService.AddChat(new Chat()
                                {
                                    Creator = "Вестерос", Message = $"dynamic_passwordDenied*Faceless Men"
                                });                                                                                                        //{profile.Api["FIO"]}
                            }
                        }
                    }
                }

                //наблюдатель
                if (gameUser == null)
                {
                    gameUser = new GameUser(game)
                    {
                        Login = login
                    };

                    game.GameUser.Add(gameUser);
                }

                gameUser.LastUpdate    = DateTimeOffset.UtcNow;
                gameUser.NeedReConnect = false;


                if (game.OpenTime == null && game.HomeUsersSL.All(p => !string.IsNullOrEmpty(p.Login) && (DateTimeOffset.UtcNow - p.LastUpdate) < new TimeSpan(0, 0, 5)))
                {
                    game.HomeUsersSL.ForEach(p => GamePortalServer.StartUserGame(p.Login, p.HomeType, game.Id, game.Type + (game.RandomIndex > 0 || game.IsRandomSkull ? 1 : 0), game.NoTimer));
                    game.OpenTime = DateTimeOffset.UtcNow;
                    game.NewThink();
                }

                dbContext.SaveChanges();

                System.Collections.Generic.IEnumerable <GameUser> gameUsers = game.HomeUsersSL.Where(p => p.Login != null);
                var privateDate = gameUsers.Select(p => new { gameUser = p, privateDate = GamePortalServer.GetPrivateProfileData(p.Login) }).ToList();
                var groupe      = privateDate.GroupBy(p => p.privateDate["clientId"]).Where(p => p.Count() > 1).ToList();
                groupe.AddRange(privateDate.GroupBy(p => p.privateDate["email"]).Where(p => p.Key != null && p.Count() > 1).ToList());
                groupe.AddRange(privateDate.GroupBy(p => p.privateDate["password"]).Where(p => p.Count() > 1).ToList());
                groupe.SelectMany(p => p.Select(p1 => string.Concat(p.Select(p2 => "\n" + p2.gameUser.HomeType)))).Distinct().ToList().ForEach(p =>
                {
                    ChatService.AddChat(new Chat()
                    {
                        Creator = "Вестерос", Message = $"dynamic_samePC*{p}"
                    });
                });

                return(game.ToWCFGame());
            }
        }
        public static NuGetFramework GetSuitableFrameworkFromProject(System.Collections.Generic.IEnumerable <NuGetFramework> frameworksInProject)
        {
            var nearestFramework = NuGetFrameworkUtility.GetNearest(
                frameworksInProject,
                FrameworkConstants.CommonFrameworks.NetCoreApp10,
                f => new NuGetFramework(f));

            if (nearestFramework == null)
            {
                nearestFramework = NuGetFrameworkUtility.GetNearest(
                    frameworksInProject,
                    FrameworkConstants.CommonFrameworks.Net46,
                    f => new NuGetFramework(f));
            }
            if (nearestFramework == null)
            {
                // This should never happen as long as we dispatch correctly.
                var msg = Resources.NoCompatibleFrameworks
                          + Environment.NewLine
                          + string.Format(Resources.AvailableFrameworks, string.Join($"{Environment.NewLine} -", frameworksInProject.Select(f => f.GetShortFolderName())));
                throw new InvalidOperationException(msg);
            }

            return(nearestFramework);
        }
Ejemplo n.º 14
0
 public async System.Threading.Tasks.Task <double[]> AggregateCellsBatchAsync(System.Collections.Generic.IEnumerable <ICellRequest> cells)
 {
     return(cells.Select(c => c.LatMax).ToArray());
 }
Ejemplo n.º 15
0
 public System.Collections.Generic.IEnumerable <EffectBase> ConvertExportedEffect(System.Collections.Generic.IEnumerable <EffectInstance> effects)
 {
     return(effects.Select(new Func <EffectInstance, EffectBase>(this.ConvertExportedEffect)));
 }
Ejemplo n.º 16
0
 public List <Room> ConvertListDTOToListEntity(System.Collections.Generic.IEnumerable <RoomDTO> dtos)
 => dtos.Select(dto => ConvertDTOToEntity(dto)).ToList();