Example #1
0
        internal static IServiceProvider FindServiceProvider(Assembly[] assembliesToSearch = null) {
            var assemblies = new List<Assembly>();
            if (assembliesToSearch != null && assembliesToSearch.Length > 0) {
                assemblies.AddRange(assembliesToSearch);
            } else {
                try {
                    var entryAssembly = Assembly.GetEntryAssembly();
                    if (entryAssembly != null)
                        assemblies.Add(entryAssembly);
                } catch {}
            }

            var serviceProviderTypes = assemblies.SelectMany(a =>
                a.GetTypes().Where(t => !t.IsInterface && !t.IsAbstract && typeof(IBootstrappedServiceProvider).IsAssignableFrom(t)));

            foreach (var serviceProviderType in serviceProviderTypes) {
                var bootstrapper = Activator.CreateInstance(serviceProviderType) as IServiceProvider;
                if (bootstrapper != null)
                    return bootstrapper;
            }

            serviceProviderTypes = assemblies.SelectMany(a => a.GetTypes()
                .Where(t => !t.IsInterface && !t.IsAbstract && typeof(IServiceProvider).IsAssignableFrom(t)));

            foreach (var serviceProviderType in serviceProviderTypes) {
                var bootstrapper = Activator.CreateInstance(serviceProviderType) as IServiceProvider;
                if (bootstrapper != null)
                    return bootstrapper;
            }

            return new ActivatorServiceProvider();
        }
Example #2
0
        public static IServiceProvider FindAndGetServiceProvider(ILoggerFactory loggerFactory, params Assembly[] assembliesToSearch) {
            var assemblies = new List<Assembly>();
            if (assembliesToSearch != null && assembliesToSearch.Length > 0) {
                assemblies.AddRange(assembliesToSearch);
            } else {
                try {
                    var entryAssembly = Assembly.GetEntryAssembly();
                    if (entryAssembly != null)
                        assemblies.Add(entryAssembly);
                } catch { }
            }

            // try to find bootstrapped service providers first
            var serviceProviderTypes = assemblies.SelectMany(a =>
                a.GetTypes().Where(t => !t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsAbstract && typeof(IBootstrappedServiceProvider).IsAssignableFrom(t)));

            foreach (var serviceProviderType in serviceProviderTypes) {
                var serviceProvider = GetServiceProvider(serviceProviderType, loggerFactory);
                if (serviceProvider != null)
                    return serviceProvider;
            }

            // find any service providers
            serviceProviderTypes = assemblies.SelectMany(a => a.GetTypes()
                .Where(t => !t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsAbstract && typeof(IServiceProvider).IsAssignableFrom(t)));

            foreach (var serviceProviderType in serviceProviderTypes) {
                var serviceProvider = GetServiceProvider(serviceProviderType, loggerFactory);
                if (serviceProvider != null)
                    return serviceProvider;
            }

            return new ActivatorServiceProvider();
        }
Example #3
0
        public static void ShowExample()
        {
            #region DATA
            PERSON p1 = new PERSON() { Name = "Martin Hromek" };
            p1.PhoneNumbers = new List<PHONENUMBER>();
            p1.PhoneNumbers.Add(new PHONENUMBER() { Number = "+420775656055" });

            PERSON p2 = new PERSON() { Name = "Eva Brezovska" };
            p2.PhoneNumbers = new List<PHONENUMBER>();
            p2.PhoneNumbers.Add(new PHONENUMBER() { Number = "+420723195654" });

            List<PERSON> list = new List<PERSON>();
            list.Add(p1);
            list.Add(p2);
            #endregion

            // SELECT
            IEnumerable<IEnumerable<PHONENUMBER>> phoneList = list.Select(p => p.PhoneNumbers);



            // SELECT MANY
            Console.WriteLine("\nSelectMany:");
            Console.WriteLine("Vstupni pole: phone list");
            Console.WriteLine("Spojim [SelectMany] seznam telefonich cisle.");
            IEnumerable<PHONENUMBER> phonesList = list.SelectMany(p => p.PhoneNumbers);
            Console.WriteLine("SelectMany: {0}", string.Join(",", phonesList));
            

            // SELECT MANY WITH ANONYMOUS CLASS
            var dictionary = list.SelectMany(p => p.PhoneNumbers, (parent, child) => new { name = parent.Name, parent.PhoneNumbers });
        }
        public SyncResponse Sync(string serverKey, List<PluginResource> discoveries = null, List<AnalyzerResult> metricResults = null, Dictionary<string, string> commandResults = null)
        {
            if (AgentContext.Current.PluginBlacklist != null)
            {
                discoveries = discoveries.Where(p => !AgentContext.Current.PluginBlacklist.Contains(p.Category, StringComparer.InvariantCultureIgnoreCase)).ToList();
            }

            // build payload
            var payLoad = new SyncRequest();
            payLoad.AddPluginResources(discoveries);
            payLoad.AddCommandResults(commandResults);

            if (metricResults != null && metricResults.Any())
            {
                payLoad.AddCollectedMetrics(metricResults.SelectMany(r => r.Metrics).ToList());
                payLoad.AddAnomalies(metricResults.SelectMany(r => r.Anomalies).ToList());
            }

            payLoad.AddRegisteredCustomMetrics();

            payLoad.AddUpdateConfig();

            payLoad.AddAgentVersion();

            Log.DebugFormat("Syncing payload with cloud service:\n{0}", JsonConvert.SerializeObject(payLoad, Formatting.Indented));

            // send request
            var response = RestHelper.Post<JObject>("sync", new AggregatorAuthenticator(serverKey), r => r.AddBody(payLoad), r =>
            {
                Log.ErrorFormat("Call to /sync resulted in an error with status code {0} ({1})", r.StatusCode, r.StatusDescription);
            });

            // parse response
            if (response != null)
            {
                Log.DebugFormat("Received sync response from cloud:\n{0}", response.ToString(Formatting.Indented));

                var syncResponse = new SyncResponse();

                if (response["schedules"] != null)
                {
                    var newSchedules = ParsePluginResourceSchedulesFromJson(response["schedules"]);
                    if (newSchedules.Any())
                    {
                        syncResponse.PluginResourcesSchedules = newSchedules;
                    }
                }

                var newCommands = response["commands"];
                if (newCommands != null && newCommands.Any())
                {
                    syncResponse.AdminCommands = ((IDictionary<string, JToken>)newCommands).ToDictionary(c => c.Key, c => c.Value.Value<string>());
                }

                return syncResponse;
            }

            return null;
        }
        public static DependencyGraph Filter(DependencyGraph graph, List<OutputEntry> warnings)
        {
            var projs = new HashSet<Library>(warnings.SelectMany(w => w.Projects)
                .Concat(warnings.SelectMany(w => w.Dependencies.SelectMany(d => new[] { d.Source, d.Target }))));

            var deps = new HashSet<Dependency>(warnings.SelectMany(w => w.Dependencies));

            var filtered = new DependencyGraph();
            filtered.AddVertexRange(projs);
            //filtered.AddEdgeRange(graph.Edges.Where(d => projs.Contains(d.Source) && projs.Contains(d.Target)));
            filtered.AddEdgeRange(deps);
            return filtered;
        }
Example #6
0
        public void Run(List<SampleTri> mesh)
        {
            Parallel.ForEach(mesh.SelectMany(m => m.Samples).Distinct().ToList(), sample =>
            {
                var neighbours = sample.DepthNeighbours(Depth);

                var colors = neighbours.Select(s => s.Color).OrderByDescending(c => c.Saturation).ToList();

                sample.NewColor = colors.Last();
            });
            Parallel.ForEach(mesh.SelectMany(m => m.Samples).Distinct().ToList(), sample =>
            {
                sample.Color = sample.NewColor;
            });
        }
Example #7
0
 private FileToWrite GetFileForNamespaceGroup(string @namespace, List<ToTypeScript> toTypeScripts)
 {
     bool containsControllers = toTypeScripts.Any(obj => obj.ObjectType == ObjectType.Controller);
     // add static import only if the files is going to contains controllers
     var extraImport = containsControllers ? new[] { $"import {{ RestApi, RequestConfig }} from '../Nimrod';" } : new string[0];
     var imports = toTypeScripts
                 .SelectMany(t => t.GetImports())
                 // do not write import for the same namespace
                 .Where(import => import.Namespace != @namespace)
                 .GroupBy(import => import.Namespace)
                 .Select(grp => $"import * as {grp.Key.Replace('.', '_')} from './{ grp.Key}';")
                 .OrderBy(importLine => importLine);
     var content = toTypeScripts.SelectMany(t => t.GetLines());
     return new FileToWrite($"{@namespace}", extraImport.Concat(imports).Concat(content));
 }
Example #8
0
        static void Main(string[] args)
        {
            // parse args
            string cwd = Environment.CurrentDirectory;
            var testdirs = new List<string>();
            string phpexepath = Path.Combine(cwd, "php.exe");

            foreach (var arg in args)
            {
                if (arg.EndsWith("php.exe", StringComparison.OrdinalIgnoreCase))
                {
                    phpexepath = arg;
                }
                else
                {
                    testdirs.Add(Path.GetFullPath(Path.Combine(cwd, arg)));
                }
            }

            // run tests lazily
            var tests = testdirs
                .SelectMany(dir => ExpandTestDir(dir));

            // output results
            foreach (var test in tests)
            {
                Console.Write($"{test} ... ");
                Console.WriteLine(TestCore(test, phpexepath));
            }
        }
Example #9
0
        private static void feed_Loaded(object sender, SyndicationResourceLoadedEventArgs e)
        {
            var feed = (RssFeed)sender;
            feed.Loaded -= feed_Loaded;

            Console.WriteLine("RSS Feed loaded at " + DateTime.UtcNow);
            List<string[]> allLines = new List<string[]>();
            foreach (var rssItem in feed.Channel.Items)
            {
                string title = rssItem.Title;
                title = RemoveHtml(title);
                if (m_includeDescription)
                {
                    string description = rssItem.Description;
                    description = RemoveHtml(description);
                    allLines.Add(new string[] { title + ": " + description });
                }
                else
                {
                    allLines.Add(new string[] { title });
                }
            }

            lock (m_forecastFeedLines)
            {
                m_forecastFeedLines.Clear();
                m_forecastFeedLines.AddRange(allLines.SelectMany(s => s));
            }

            UpdateAllFeedLines();
        }
Example #10
0
        public override Population Run()
        {
            var m = GetOption("select_count", Math.Ceiling((double) (Population.Osobi.Count/20)));
            if (Population.Osobi.Count < m) return Population;
            var groups =new List < List<Unit> >();
            var tempc = 0;
            var templ = new List<Unit>();
            for (int i = 0; i < Population.Osobi.Count; i++)
            {
                var unit = Population.Osobi[i];
                if (tempc>=m)
                {
                    groups.Add(templ);
                    templ=new List<Unit>();
                    tempc = 0;
                }
                templ.Add(unit);
                tempc++;

            }
            if (templ.Count > 0) { groups.Add(templ);templ=new List<Unit>();}

            var goods=groups.SelectMany(u => u.Where(u1 => u1.Function == u.Max(u2 => u2.Function)));
            Population.TempPopulation = goods.Select(u=>u.Id).ToList();
            return Population;
        }
Example #11
0
        /// <summary>
        /// Gets the metro applications.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<MetroApplication> GetApplications()
        {
            var packages = new PackageManager()
                .FindPackagesForUser(WindowsIdentity.GetCurrent().User.Value);

            var metroPackages = new List<MetroPackage>();

            foreach (var package in packages)
            {
                var metroPackage = new MetroPackage(package);

                if (metroPackage.Applications.Any())
                {
                    metroPackages.Add(new MetroPackage(package));
                }
            }

            var metroApplications = metroPackages
                .SelectMany(package => package.Applications)
                .Where(
                    application =>
                        !string.IsNullOrEmpty(application.AppUserModelId) &&
                        !string.IsNullOrEmpty(application.Name));

            return metroApplications;
        }
Example #12
0
        public ScanIndex()
        {
            AssemblyTypes = new Dictionary<Assembly, List<Type>>();
            TypeAssemblies = new Dictionary<Type, Assembly>();
            ImplementorsOfType = new Dictionary<Type, List<Type>>();
            TypeHierarchies = new Dictionary<Type, List<Type>>();
            Closers = new Dictionary<Type, List<Type>>();
            AssemblyExclusionList = new List<string>();
            ReferenceLookup = new Dictionary<Assembly, List<Assembly>>();
            ConfiguredSymbiotes = new Dictionary<Assembly, bool>();
            SingleImplementations = new Dictionary<Type, Type>();
            Scanner = new TypeScanner();

            InitExclusions();

            var initialList = new List<Assembly>( Scanner.GetAssembliesFromBaseDirectory().ToList() );
            var references = initialList
                .SelectMany( GetReferenceList )
                .ToList();
            initialList.AddRange( references.Where( r => !initialList.Any( a => a.FullName.Equals( r.FullName ) ) ) );

            var uniqueList = initialList.Distinct();
            var filtered = uniqueList.Where( x => !AssemblyExclusionList.Any( e => x.FullName.StartsWith( e ) ) );
            CompleteAssemblyList = new List<Assembly>( filtered.ToList() );
        }
Example #13
0
        public IEnumerable<Money> Eject(CashDeal inCash, ChangePool inReservedMoney)
        {
            try {
                if (inCash.UsedAmount == 0) {
                    return inCash.RecevedMoney.ToList();
                }

                var result = new List<KeyValuePair<Money, int>>();

                this.EjectCore(
                    inCash.ChangedAount,
                    inReservedMoney.Items.OrderByDescending(pair => pair.Key.Value()),
                    (m, totalCount, useCount) => {
                        result.Add(
                            new KeyValuePair<Money, int>(m, (int)useCount)
                        );
                    }
                );

                return result.SelectMany(r => Enumerable.Repeat(r.Key, r.Value));
            }
            finally {
                inCash.RecevedMoney.Clear();
            }
        }
        public Task Subscribe(Guid recordID, string group)
        {
            if (UserList.Any(x => x.User == Context.ConnectionId))
                return null;
            Console.WriteLine("[{0}] Client '{1}' has been added to group {2}.", DateTime.Now.ToString("dd-mm-yyyy hh:MM:ss"), Context.ConnectionId, group);
            var adv = new AdvList
            {
                Name = @group,
                User = Context.ConnectionId,
                UserRecordID = recordID,
                ListOfLanes = new List<Guid>()
            };

            List<CustomerHierarchy> chList = new List<CustomerHierarchy>();
            if(!CustomerHierarchy.Load(recordID, out chList))
            {
                Console.WriteLine("Error retrieving customer hierarchy for user " + User.LoadUser(recordID).DisplayName);
            }

            var listOfLanes = new List<Guid>();
           adv.ListOfLanes = chList.SelectMany(x => x.Equipment.Select(e => e.RecordID)).Distinct().ToList();

            UserList.Add(adv);
            Console.WriteLine("user list contains this many people on subscription" + UserList.Count());
            return Groups.Add(Context.ConnectionId, group);
        }
        public void Write(List<PackageViewModel> packages, string file)
        {
            if (string.IsNullOrWhiteSpace(file))
            {
                file = "packages.dgml";
            }

            XNamespace ns = "http://schemas.microsoft.com/vs/2009/dgml";
            var colors = new DgmlColorConfiguration();
            var nodes =
                packages
                    .Select(
                        package =>
                            new XElement(ns + "Node",
                                new XAttribute("Id", package.Id),
                                new XAttribute("Label", string.Format("{0} ({1})", package.NugetId, package.LocalVersion)),
                                new XAttribute("Background", GraphHelper.GenerateBackgroundColor(packages, package, colors))))
                    .ToList();

            var links =
                (packages
                    .SelectMany(
                        package => package.Dependencies, (package, dep) =>
                            new XElement(ns + "Link",
                                new XAttribute("Source", package.Id),
                                new XAttribute("Target", packages.Any(x => x.NugetId == dep.NugetId && x.LocalVersion == dep.Version) ? packages.First(x => x.NugetId == dep.NugetId && x.LocalVersion == dep.Version).Id : string.Format("{0} ({1})", dep.NugetId, dep.Version)))))
                .ToList();

            var document =
                new XDocument(
                    new XDeclaration("1.0", "utf-8", string.Empty),
                    new XElement(ns + "DirectedGraph", new XElement(ns + "Nodes", nodes), new XElement(ns + "Links", links)));

            document.Save(file);
        }
        public List<TextUnitScore> GetImportantTextUnits(List<Sentence> Sentences)
        {
            var textUnitFrequencyGrader = new Dictionary<TextUnit, long>();
            foreach (var tu in Sentences.SelectMany(s => s.TextUnits))
            {
                if (m_Rules.UnimportantWords.Contains(tu.FormattedValue))
                {
                    continue;
                }

                if (textUnitFrequencyGrader.ContainsKey(tu))
                {
                    textUnitFrequencyGrader[tu]++;
                }
                else
                {
                    textUnitFrequencyGrader.Add(tu, 1);
                }
            }

            return
                textUnitFrequencyGrader.OrderByDescending(kvp => kvp.Value)
                    .Select(kvp => new TextUnitScore {ScoredTextUnit = kvp.Key, Score = kvp.Value})
                    .ToList();
        }
        ///<summary>Resolves the full path to the JS file that will be loaded by a call to require().  This will always return an existing file (not directory) on disk, or null.</summary>
        ///<param name="callerPath">The path to the directory containing the file that is calling require().  This must be an absolute path.</param>
        ///<param name="modulePath">The string passed to require().  This can be a relative path, a module name, or a path within a module name.</param>
        ///<returns>The path to the fully resolved file, after resolving default extensions, default directory files, and package.json.</returns>
        public async static Task<string> ResolveModule(string callerDirectory, string modulePath)
        {
            string rawPath = ResolvePath(callerDirectory, modulePath);

            // If we couldn't locate the module at all, or if we got an actual file, stop.
            if (rawPath == null || File.Exists(rawPath))
                return rawPath;

            // Build a list of file-like paths to try with various extensions.
            // In order, try the original path, the 'package.json' main entry,
            // and any index file.
            // https://github.com/joyent/node/blob/master/lib/module.js#L155
            var potentialPaths = new List<string> { rawPath };

            // If the non-existent file is a directory, look inside.
            if (Directory.Exists(rawPath))
            {
                var mainEntry = await GetPackageMain(rawPath).ConfigureAwait(false);
                if (mainEntry != null)
                {
                    potentialPaths.Add(Path.Combine(rawPath, mainEntry));
                    potentialPaths.Add(Path.Combine(rawPath, mainEntry, "index"));
                }
                potentialPaths.Add(Path.Combine(rawPath, "index"));
            }
            // Don't try to resolve a path with a trailing / as a file.
            potentialPaths.RemoveAll(p => p.EndsWith("/", StringComparison.Ordinal));

            // Try adding the default extensions to each potential path we've found, then give up.
            return potentialPaths.SelectMany(path => ModuleExtensions.Select(e => path + e))
                                 .FirstOrDefault(File.Exists);
        }
Example #18
0
        private static async Task<IEnumerable<MethodCountInfo>> GetClassMethodCounts(string solutionFile)
        {
            var methodCounts = new List<IEnumerable<MethodCountInfo>>();

            using (MSBuildWorkspace workspace = MSBuildWorkspace.Create())
            {
                Solution solution = await workspace.OpenSolutionAsync(solutionFile);

                foreach (var project in solution.Projects)
                {
                    Console.WriteLine("Processing: " + project.Name);

                    var compilation = await project.GetCompilationAsync();

                    foreach (var syntaxTree in compilation.SyntaxTrees)
                    {
                        var methodCounter = new MethodCountingWalker(compilation.GetSemanticModel(syntaxTree));
                        methodCounter.Visit(syntaxTree.GetRoot());
                        methodCounts.Add(methodCounter.Counts());
                    }
                }
            }

            return methodCounts.SelectMany(seq => seq);
        }
Example #19
0
        protected override void UpdateLevelsValues(List<List<SamplePrimitive>> primitives, MobileObservableCollection<SampleUnit> samples)
        {
            var dataList = primitives.SelectMany(x => x.Select(y => !((bool)y.SampleValue)));
            var dataSum = dataList.Sum(x => Convert.ToInt32(x));
            var dataCount = dataList.Count();

            var p = 0.0;
            var np = 0.0;
            var delta = 0.0;
            if (samples.Any())
            {
                p = (double) dataSum/dataCount;
                np = ParentPanel.SubgroupSize * p;
                delta = 3 * Math.Sqrt(np * (1 - p));

                Mean = Math.Round(np, 2);

                UCL = Math.Round(Mean + delta, 2);
                LCL = Math.Round(Math.Max(Mean - delta, 0), 2);
            }

            foreach (var sample in samples)
            {
                sample.SetUCL(UCL);
                sample.SetMean(Mean);
                sample.SetLCL(LCL);

                sample.SetUCL(ParentPanel.CustomUCL, true);
                sample.SetLCL(ParentPanel.CustomLCL, true);

                sample.SetUSL(ParentPanel.USL);
                sample.SetLSL(ParentPanel.LSL);
            }
        }
Example #20
0
        protected override MobileObservableCollection<SampleUnit> ConvertPrimitivesToSamples(List<List<SamplePrimitive>> primitives)
        {
            var newSource = new MobileObservableCollection<SampleUnit>();

            for (var i = 0; i < primitives.Count; i++)
            {
                var data = primitives[i].Select(x => x.SampleValue).Cast<double>();

                var commonItemId = (from s in primitives[i]
                                    group s by s.ItemId into gr
                                    orderby gr.Count() descending
                                    select gr).First().First().ItemId;

                var sampleValue = ProcessSubgroup(data);

                var subgroupSample = SpcManager.CreateSample(sampleValue, commonItemId, i);
                subgroupSample.SetXLabelValue(i, LabelValueDataTypes.Number);
                subgroupSample.SetSampleSize(data.Count());
                newSource.Add(subgroupSample);
            }

            UpdateLevelsValues(primitives, newSource);

            YStep = (int)Math.Abs(primitives.SelectMany(l1 => l1.Select(l2 => l2.SampleValue)).Cast<double>().Range() / (3 * ParentPanel.HeightMultiplier));

            return newSource;
        }
Example #21
0
        protected COBSCodec() { } // not instantiable

        /**
         * Returns the encoded representation of the given bytes.
         * Inefficient method, but easy to use and understand.
         *
         * @param src the bytes to encode
         * @return the encoded bytes.
         */
        public static byte[] encode(byte[] src)
        {
            List<byte[]> dest = new List<byte[]>(maxEncodedSize(src.Length));
            encode(src, 0, src.Length, dest);
            dest.TrimExcess();
            return dest.SelectMany(a => a).ToArray();
        }
Example #22
0
    static void Main(string[] args)
    {
        const int NUMBER_OF_POSITIONS = 4;
        Console.Error.WriteLine("Using {0} positions", NUMBER_OF_POSITIONS);

        var allPositions = Enumerable.Range(0, NUMBER_OF_POSITIONS).ToArray();

        var validValues = new List<int[][]> {
            Enumerable.Repeat(Enumerable.Range(0, 10).ToArray(), NUMBER_OF_POSITIONS).ToArray()
        };

        logSolutions(validValues);

        int N = int.Parse(Console.ReadLine());
        for (int i = 0; i < N; i++)
        {
            string[] inputs = Console.ReadLine().Split(' ');
            int[] guess = inputs[0].Select(x => int.Parse(x.ToString())).ToArray();
            int bulls = int.Parse(inputs[1]);
            int cows = int.Parse(inputs[2]);
            Console.Error.WriteLine("guess {0} == {1} bulls + {2} cows", inputs[0], bulls, cows);

            validValues = validValues.SelectMany(possibility =>
                solve(possibility, guess, bulls, cows, NUMBER_OF_POSITIONS - 1)
            ).ToList();

            logSolutions(validValues);
        }

        var solution = string.Join("", validValues.Single().Select(x => x.Single()).ToArray());
        Console.WriteLine(solution);
        Console.ReadLine();
    }
Example #23
0
        public static Blockchain RandomBlockchain(RandomDataOptions options = default(RandomDataOptions))
        {
            //TODO blockCount algorithm isn't exact
            var blockCount = random.Next((options != null ? options.BlockCount : null) ?? 100) + ((options != null ? options.MinimumBlockCount : null) ?? 1);
            var blockList = new List<Block>(blockCount);
            var chainedBlockList = new List<ChainedBlock>(blockCount);

            var previousBlockHash = UInt256.Zero;
            var totalWork = new BigInteger(0);
            for (var i = 0; i < blockCount; i++)
            {
                var block = RandomData.RandomBlock(options);
                block = block.With(Header: block.Header.With(PreviousBlock: previousBlockHash));
                blockList.Add(block);

                previousBlockHash = block.Hash;
                totalWork += block.Header.CalculateWork();

                chainedBlockList.Add(new ChainedBlock(block.Hash, block.Header.PreviousBlock, i, totalWork));
            }

            var blockListHashes = blockList.Select(x => x.Hash).ToImmutableHashSet();
            var utxo = blockList.SelectMany(block =>
                block.Transactions.Select((tx, txIndex) =>
                    new UnspentTx(block.Hash, (UInt32)txIndex, tx.Hash, random.NextImmutableBitArray((options != null ? options.TxOutputCount : null) ?? 100))))
                .ToImmutableDictionary(unspentTx => unspentTx.TxHash, unspentTx => unspentTx);

            return new Blockchain
            (
                chainedBlockList.ToImmutableList(),
                blockListHashes,
                utxo
            );
        }
Example #24
0
 public byte[] GetBytes(float mul = 1.0f)
 {
     List<byte[]> data = new List<byte[]>();
     data.Add(X.GetBytes(mul));
     data.Add(Y.GetBytes(mul));
     return data.SelectMany(_ => _).ToArray();
 }
        public virtual async Task<CodeAction> GetFixAsync(
            ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap,
            FixAllContext fixAllContext)
        {
            if (documentsAndDiagnosticsToFixMap != null && documentsAndDiagnosticsToFixMap.Any())
            {
                fixAllContext.CancellationToken.ThrowIfCancellationRequested();

                var documents = documentsAndDiagnosticsToFixMap.Keys.ToImmutableArray();
                var fixesBag = new List<CodeAction>[documents.Length];
                var options = new ParallelOptions() { CancellationToken = fixAllContext.CancellationToken };
                Parallel.ForEach(documents, options, (document, state, index) =>
                {
                    fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                    fixesBag[index] = new List<CodeAction>();
                    this.AddDocumentFixesAsync(document, documentsAndDiagnosticsToFixMap[document], fixesBag[index].Add, fixAllContext).Wait(fixAllContext.CancellationToken);
                });

                if (fixesBag.Any(fixes => fixes.Count > 0))
                {
                    return await this.TryGetMergedFixAsync(fixesBag.SelectMany(i => i), fixAllContext).ConfigureAwait(false);
                }
            }

            return null;
        }
Example #26
0
        static void Main()
        {
            var groups = new List<List<string[]>>();
            var strings = File.ReadAllLines("Test.txt");
            var n = 0;

            foreach (var l in strings)
            {
                if (l.StartsWith("[") && l.EndsWith("]"))
                {
                    n = int.Parse(l.Trim('[', ']')) - 1;
                    groups.Add(new List<string[]>());
                    continue;
                }
                groups[n].Add(l.Split('\t'));
            }

            var lines = groups.SelectMany(g => g);

            var ids = lines.Select(l => l[0])
                           .Distinct();

            var paths = ids.Select(id => GetNodes(id, lines).Reverse()).ToList();

            var pairs = paths.Select(p => Tuple.Create(p.Count(), GetPartCount(p, lines)))
                             .ToList();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1(pairs));
        }
Example #27
0
        public ObjectCreator(Manifest manifest, FileSystem.FileSystem modFiles)
        {
            typeCache = new Cache<string, Type>(FindType);
            ctorCache = new Cache<Type, ConstructorInfo>(GetCtor);

            // Allow mods to load types from the core Game assembly, and any additional assemblies they specify.
            var assemblyList = new List<Assembly>() { typeof(Game).Assembly };
            foreach (var path in manifest.Assemblies)
            {
                var data = modFiles.Open(path).ReadAllBytes();

                // .NET doesn't provide any way of querying the metadata of an assembly without either:
                //   (a) loading duplicate data into the application domain, breaking the world.
                //   (b) crashing if the assembly has already been loaded.
                // We can't check the internal name of the assembly, so we'll work off the data instead
                var hash = CryptoUtil.SHA1Hash(data);

                Assembly assembly;
                if (!ResolvedAssemblies.TryGetValue(hash, out assembly))
                {
                    assembly = Assembly.Load(data);
                    ResolvedAssemblies.Add(hash, assembly);
                }

                assemblyList.Add(assembly);
            }

            AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
            assemblies = assemblyList.SelectMany(asm => asm.GetNamespaces().Select(ns => Pair.New(asm, ns))).ToArray();
            AppDomain.CurrentDomain.AssemblyResolve -= ResolveAssembly;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="XElementExportProvider"/> class.
        /// Includes *.xml and *.config by default.
        /// </summary>
        /// <param name="path">The path. Defaults to Directory.GetCurrentDirectory()</param>
        /// <param name="filters">A list of additional file filters to include.</param>
        public XElementExportProvider(string path = null, IEnumerable<string> filters = null)
        {
            if (path == null)
            {
                path = Directory.GetCurrentDirectory();
            }
            List<string> include = new List<string>(new[] { "*.xml", "*.config" });
            if (filters != null)
            {
                foreach (string filter in filters.Where(filter => !string.IsNullOrWhiteSpace(filter)).Where(filter => !include.Contains(filter)))
                {
                    include.Add(filter);
                }
            }

            List<string> xmlFiles = new List<string>(include.SelectMany(ext => Directory.GetFiles(path, ext)));

            _exportsDictionary = xmlFiles.Select(filePath => new FileInfo(filePath)).ToDictionary(
                fileInfo => fileInfo.Name,
                fileInfo =>
                {
                    ExportDefinition def = new ExportDefinition(fileInfo.Name, null);
                    Export e = new Export(def, () => XElement.Load(fileInfo.FullName));
                    return e;
                });
        }
        public List<GameStats> Apply(List<DeckStats> stats)
        {
            // filter by deck first if needed
            IEnumerable<GameStats> filtered = null;
            if (Deck != null)
            {
                filtered = stats.Where<DeckStats>(d => d.DeckId.Equals(Deck)).SelectMany(d => d.Games);
            }
            else
            {
                filtered = stats.SelectMany(d => d.Games).ToList<GameStats>();
            }
            // region filter
            if (!Region.Equals(StatsRegion.All))
            {
                filtered = filtered.Where<GameStats>(g => (int)g.Region == (int)Region);
            }
            // game mode filter
            if (!Mode.Equals(GameMode.All))
            {
                filtered = filtered.Where<GameStats>(g => g.GameMode.Equals(Mode));
            }
            // time filter
            var times = GetFilterTimes(TimeFrame);
            filtered = filtered.Where<GameStats>(g => g.StartTime >= times.Item1 && g.EndTime <= times.Item2);

            // finally sort by time
            return filtered.OrderByDescending<GameStats, DateTime>(g => g.EndTime).ToList<GameStats>();
        }
        protected List<PerformanceRecord> ExecuteWriteWithParallel(IEnumerable<TestData> data, int numberOfTransactions, int itemsPerTransaction, int numberOfThreads, Func<IEnumerator<TestData>, long, long, List<PerformanceRecord>> writeFunction, out long elapsedMilliseconds)
        {
            var countdownEvent = new CountdownEvent(numberOfThreads);

            var parallelData = SplitData(data, numberOfTransactions, itemsPerTransaction, numberOfThreads);

            var records = new List<PerformanceRecord>[numberOfThreads];
            var sw = Stopwatch.StartNew();

            for (int i = 0; i < numberOfThreads; i++)
            {
                ThreadPool.QueueUserWorkItem(
                    state =>
                    {
                        var index = (int)state;
                        var pData = parallelData[index];

                        records[index] = writeFunction(pData.Enumerate(), pData.ItemsPerTransaction, pData.NumberOfTransactions);

                        countdownEvent.Signal();
                    },
                    i);
            }

            countdownEvent.Wait();
            sw.Stop();

            elapsedMilliseconds = sw.ElapsedMilliseconds;

            return records
                .SelectMany(x => x)
                .ToList();
        }