コード例 #1
0
ファイル: FilterReadsUtil.cs プロジェクト: cpatmoore/bio
        /// <summary>
        /// Process the command line arguments.
        /// </summary>
        /// <param name="args">commandline arguments.</param>
        /// <returns>Command line options.</returns>
        private static CommandLineOptions ProcessCommandLine(string[] args)
        {
            CommandLineOptions filterReadsParams = new CommandLineOptions();
            CommandLineArguments parser = new CommandLineArguments();

            // Add parameters
            parser.Parameter(ArgumentType.DefaultArgument, "Filename", ArgumentValueType.String, "", "Input fasta file to filter reads.");
            parser.Parameter(ArgumentType.Optional, "AmbiguousOutputFile", ArgumentValueType.String, "a", "Filtered ambiguous reads output file");
            parser.Parameter(ArgumentType.Optional, "OutputFile", ArgumentValueType.String, "o", "Output file");
            parser.Parameter(ArgumentType.Optional, "FilterAmbiguousReads", ArgumentValueType.Bool, "fa", "Filter ambiguous reads");
            parser.Parameter(ArgumentType.Optional, "Verbose", ArgumentValueType.Bool, "v", "Display Verbose logging");
            parser.Parameter(ArgumentType.Optional, "Help", ArgumentValueType.Bool, "h", "Show the help information with program options and a description of program operation.");

            try
            {
                parser.Parse(args, filterReadsParams);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("\nException while processing Command Line arguments [{0}]", e.Message);
                Console.Error.WriteLine(Properties.Resource.FilterReadsUtilHelp);
                Environment.Exit(-1);
            }

            if (filterReadsParams.OutputFile != null)
            {   // redirect stdout
                FileStream fsConsoleOut = new FileStream(filterReadsParams.OutputFile, FileMode.Create);
                StreamWriter swConsoleOut = new StreamWriter(fsConsoleOut);
                Console.SetOut(swConsoleOut);
                swConsoleOut.AutoFlush = true;
            }

            return (filterReadsParams);
        }
コード例 #2
0
        private static void ProcessAssembly( CommandLineOptions options )
        {
            AssemblyDefinition assembly = ReadAssembly( options.AssemblyPath );

            string attributeToStrip = "System.Runtime.CompilerServices.ExtensionAttribute";

            var query = assembly.MainModule.Types.Where( x => x.FullName == attributeToStrip );

            if (!query.Any())
            {
                Console.WriteLine( "Nothing to do, no definition of {0} found.", attributeToStrip );
                Console.WriteLine( "Just round-tripping the assembly." );
            }
            else
            {
                AttributeStripper stripper = new AttributeStripper( query.Single() );
                stripper.Process( assembly );
            }

            PrepareOutputDirectory( options.OutputDirectory );

            string targetPath = Path.Combine( options.OutputDirectory, Path.GetFileName( options.AssemblyPath ) );
            StrongNameKeyPair snk = options.SigningKeyPairFile != null ? new StrongNameKeyPair( File.ReadAllBytes( options.SigningKeyPairFile ) ) : null;

            WriteAssembly( assembly, targetPath, snk );
        }
コード例 #3
0
ファイル: options.cs プロジェクト: jantolenaar/kiezellisp
        public static CommandLineOptions ParseArgs(string[] args)
        {
            var options = new CommandLineOptions();
            var parser = new CommandLineParser();

            parser.AddOption("--debug");
            parser.AddOption("--release");

            parser.Parse(args);

            var s = parser.GetArgument(0);

            if (s != null)
            {
                options.ScriptName = s;
                options.Debug = false;
                options.UserArguments = Runtime.AsList(parser.GetArgumentArray(1));
            }

            if (parser.GetOption("release") != null)
            {
                options.Debug = false;
            }

            if (parser.GetOption("debug") != null)
            {
                options.Debug = true;
            }

            return options;
        }
コード例 #4
0
        public void WhenTimeoutIsSpecified_RunSettingsIncludeIt()
        {
            var options = new CommandLineOptions("test.dll", "--timeout=50");
            var settings = TextUI.MakeRunSettings(options);

            Assert.That(settings.ContainsKey("DefaultTimeout"));
            Assert.AreEqual(50, settings["DefaultTimeout"]);
        }
コード例 #5
0
        public void WhenWorkDirectoryIsSpecified_RunSettingsIncludeIt()
        {
            var options = new CommandLineOptions("test.dll", "--work=results");
            var settings = TextUI.MakeRunSettings(options);

            Assert.That(settings.ContainsKey("WorkDirectory"));
            Assert.AreEqual(Path.GetFullPath("results"), settings["WorkDirectory"]);
        }
コード例 #6
0
        public void WhenSeedIsSpecified_RunSettingsIncludeIt()
        {
            var options = new CommandLineOptions("test.dll", "--seed=1234");
            var settings = TextUI.MakeRunSettings(options);

            Assert.That(settings.ContainsKey("RandomSeed"));
            Assert.AreEqual(1234, settings["RandomSeed"]);
        }
コード例 #7
0
		public GitHubWorker(CommandLineOptions options)
		{
			_options = options;

			var credentials = new Credentials(_options.GitHubAccessToken);
			var connection = new Connection(new ProductHeaderValue("CodeplexIssueMigrator")) { Credentials = credentials };
			_gitHubClient = new GitHubClient(connection);
		}
コード例 #8
0
ファイル: TemplateContext.cs プロジェクト: jupaol/NCastor
        /// <summary>
        /// Set the options to be used to coonfigure the current template
        /// </summary>
        /// <param name="options">The options to be used to configure the current template.</param>
        /// <returns>
        /// Gets a reference to the parent ITemplateConfigurator object
        /// </returns>
        public ITemplateConfigurator Options(CommandLineOptions options)
        {
            Condition.Requires(options, "options").IsNotNull();

            options.ProcessOptions();
            this.CurrentOptions = options;

            return this.templateConfigurator;
        }
コード例 #9
0
ファイル: frmMain.cs プロジェクト: hkiaipc/fnq
        /// <summary>
        /// 
        /// </summary>
        public frmMain(CommandLineOptions cmdLineOpt)
        {
            //btGRMain.frmLogin f = new btGRMain.frmLogin();
            //f.ShowDialog();

            InitializeComponent();
            this.Text = strings.AppText;
            this._cmdLineOpt = cmdLineOpt;
            this.mnu2Data.Visible = Config.Default.Show2DataGather;
        }
コード例 #10
0
ファイル: ParserServiceTests.cs プロジェクト: jupaol/NCastor
        public void when_not_specifying_the_solution_path_the_parser_should_return_true_because_it_is_optional()
        {
            var options = new CommandLineOptions();
            string[] args = new[] { "-p", "product", "-o de" };
            ICommandLineParser parser = new CommandLineParser();

            bool res = parser.ParseArguments(args, options);

            res.Should().BeTrue();
        }
コード例 #11
0
ファイル: ParserServiceTests.cs プロジェクト: jupaol/NCastor
        public void when_specifying_an_invalid_argument_the_parser_should_return_false()
        {
            var options = new CommandLineOptions();
            string[] args = new[] { "-de", "-o de" };
            ICommandLineParser parser = new CommandLineParser();

            bool parserResults = parser.ParseArguments(args, options);

            parserResults.Should().BeFalse();
        }
コード例 #12
0
ファイル: ParserServiceTests.cs プロジェクト: jupaol/NCastor
        public void when_specifying_the_ProductName_argument_with_a_value_the_parser_method_should_return_true()
        {
            var options = new CommandLineOptions();
            string[] args = new[] { "-p hhh", "-o de" };
            ICommandLineParser parser = new CommandLineParser();

            bool parserResults = parser.ParseArguments(args, options);

            parserResults.Should().BeTrue();
        }
コード例 #13
0
ファイル: ParserServiceTests.cs プロジェクト: jupaol/NCastor
        public void when_specifying_the_solution_path_with_a_valid_value_the_parser_should_return_true()
        {
            var options = new CommandLineOptions();
            string[] args = new[] { "-s", "solpath", "-p", "product", "-o de" };
            ICommandLineParser parser = new CommandLineParser();

            bool res = parser.ParseArguments(args, options);

            res.Should().BeTrue();
        }
コード例 #14
0
ファイル: ParserServiceTests.cs プロジェクト: jupaol/NCastor
        public void when_specifying_the_solution_path_with_incomplete_arguments_the_parser_should_return_false()
        {
            var options = new CommandLineOptions();
            string[] args = new[] { "-s", "-p", "product", "-o de" };
            ICommandLineParser parser = new CommandLineParser();

            bool res = parser.ParseArguments(args, options);

            res.Should().BeFalse();
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: Xtremrules/dot42
        /// <summary>
        /// Entry point
        /// </summary>
        public static int Main(string[] args)
        {
#if DEBUG
            for (var i = 0; i < args.Length; i++)
            {
                Console.WriteLine("args[{0}]={1}", i, args[i]);
            }
#endif
            try
            {
#if DEBUG
                if (args.Length == 0)
                {
                    var folder = Path.GetDirectoryName(typeof(Program).Assembly.Location);
                    var rootFolder = Path.GetFullPath(Path.Combine(folder, @"..\..\..\.."));
                    folder = Path.Combine(rootFolder, @"RegressionTests\Simple");
                    args = new[] {
                        ToolOptions.InputManifest.CreateArg(Path.Combine(folder, @"Out\AndroidManifest.xml")),
                        ToolOptions.InputCodeFile.CreateArg(Path.Combine(folder, @"Out\Code\classes.dex")),
                        ToolOptions.OutputPackage.CreateArg(Path.Combine(folder, @"Out\Simple.apk")),
                        ToolOptions.CertificateThumbprint.CreateArg("EF53D093F360F8941566B7924BFD11027C88FABB")
                    };
                }
#endif

                // Parse command line options
                var options = new CommandLineOptions(args);
                if (options.ShowHelp)
                {
                    options.Usage();
                    return 2;
                }

                // Compile now
                var builder = new ApkBuilder(options.ApkFile);
                builder.ManifestPath = options.ManifestFile;
                builder.DexFiles.AddRange(options.DexFiles);
                builder.ResourcesFolder = options.ResourcesFolder;
                builder.PfxFile = options.PfxFile;
                builder.PfxPassword = options.PfxPassword;
                builder.CertificateThumbprint = options.CertificateThumbprint;
                builder.Build();

                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
#if DEBUG
                Console.WriteLine(ex.StackTrace);
#endif
                return 1;
            }
        }
コード例 #16
0
            public void ProcessArgs_InvalidOptionsSpace_ExceptionThrown()
            {
                // arrange
                CommandLineOptions expected = new CommandLineOptions();
                string[] args = { };
                clp.Options = "azAz09: ";

                // act
                actual = clp.ProcessArgs(args);

                // assert -- should not get here
            }
コード例 #17
0
        private static void Main(string[] args)
        {
            var options = new CommandLineOptions();
            Parser.Default.ParseArguments(args, options);
            if (string.IsNullOrWhiteSpace(options.DataDirectory))
            {
                Console.WriteLine("Parameter directory not specified.");
                return;
            }

            if (string.IsNullOrWhiteSpace(options.Host))
            {
                Console.WriteLine("Parameter host not specified.");
                return;
            }

            var nodesXmlParser = new NodesXmlParser();
            var nodesLoader = new NodesLoader(nodesXmlParser);
            var httpClient = new BasicHttpClient();
            var uploader = new NodeUploader(httpClient, options.Host);

            Console.WriteLine("Loading files from {0}", options.DataDirectory);
            NodeContainer nodes;
            try
            {
                nodes = nodesLoader.ParseFiles(options.DataDirectory).Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
                return;
            }

            try
            {
                Console.WriteLine(uploader.Delete().Result);
                Console.WriteLine(uploader.Upload(nodes).Result);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    Console.WriteLine("Error: {0}", e.InnerException.Message);
                }
                else
                {
                    Console.WriteLine("Error: {0}", e.InnerException);
                }
                return;
            }

            Console.WriteLine("Successfully uploaded.");
        }
コード例 #18
0
            public void ProcessArgs_NoneSupplied_NoneReturned()
            {
                // arrange
                CommandLineOptions expected = new CommandLineOptions();
                string[] args = { };

                // act
                actual = clp.ProcessArgs(args);

                // assert
                Assert.AreEqual(expected.GetNonOptions().Count, actual.GetNonOptions().Count);
                Assert.AreEqual(expected.GetOptionCount(), actual.GetOptionCount());
            }
コード例 #19
0
        public static int Main( string[] args )
        {
            Console.WriteLine();
            CommandLineOptions options = new CommandLineOptions();

            ICommandLineParser parser = new CommandLineParser( new CommandLineParserSettings( Console.Out ) );
            if (!parser.ParseArguments( args, options ))
                return 1;

            ProcessAssembly( options );

            return 0;
        }
コード例 #20
0
        /// <summary>
        /// Parses commandline arguments into a generic CommandLineOptions object.
        /// 
        /// Supported Format
        /// 
        /// [parameter1 parameter2 parameter3] /flag /flagWithValue value
        /// [parameter1 parameter2 parameter3] -flag -flagWithValue value
        /// [parameter1 parameter2 parameter3] --flag --flagWithValue value
        /// 
        /// 
        /// Specifing a flag without a value is equally as setting it to true
        /// Example
        /// '-quiet' has the same effect '-quiet true'
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static CommandLineOptions ParseCommandLineArgs(string[] args)
        {
            var commandLineOptions = new CommandLineOptions();
            var flagParser = new Regex("^[/|-](.*)$");

            string currentFlag = null;

            for (int i = 0; i != args.Length; ++i)
            {
                string current = args[i];

                if (flagParser.IsMatch(current))
                {
                    if (currentFlag != null)
                    {
                        commandLineOptions.SetParameterEnabled(currentFlag);
                    }
                    currentFlag = flagParser.Match(current).Groups[1].Value;
                }
                else
                {
                    // Simple Argument without any flag/id
                    if (currentFlag == null)
                    {
                        commandLineOptions.AddArgument(current);
                    }
                    else
                    {
                        commandLineOptions.SetParameterValue(currentFlag, current);
                        currentFlag = null;
                    }
                }
            }

            // If last param is flag without param
            if (currentFlag != null)
            {
                commandLineOptions.SetParameterEnabled(currentFlag);
            }

            return commandLineOptions;
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: praveenv4k/indriya
        private static void Main(string[] args)
        {
            _imuTrigger.motion = new GestureDescription();
            _imuTrigger.motion.name = "IMU_WAVE";
            _stopTask = false;
            Node info = null;
            var options = new CommandLineOptions();
            try
            {
                if (args.Length > 0)
                {
                    Parser.Default.ParseArguments(args, options);
                    info = MessageUtil.RequestProtoMessage<Node>(options.ParameterServer, options.Name);

                    if (info != null)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Retrieving the parameter from server failed : {0}", ex.StackTrace);
            }
            try
            {
                if (info != null)
                {
                    SendMotionRecognitionModuleInfo(info, options.ParameterServer);
                    var tasks = new List<Task>();
                    tasks.Add(Task.Run(() => CollectData(info)));
                    tasks.Add(Task.Run(() => PublishData(info)));
                    Task.WaitAll(tasks.ToArray());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception : {0}", ex.StackTrace);
            }
            Console.WriteLine("About to exit. Press enter to close the console window.");
            Console.Read();
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: tompoole/DeploymentManager
        static void Main(string[] args)
        {
            // Setup
            _defaultLogger = LogManager.GetLogger("Default");
            EnsureWorkingAreaExists();

            // Parse command line options
            CommandLineOptions options = new CommandLineOptions();
            Parser.Default.ParseArguments(args, options);

            Job currentJob = JobHelper.GetJob(options.JobId, _defaultLogger);
            if (currentJob == null) ExitProgramWithError("Job not found");

            // Intialise deployment context.
            DeploymentContext deploymentContext = DeploymentContextFactory.CreateContextForJob(currentJob);
            _statusUpdater = new DeploymentStatusUpdater(deploymentContext);

            // Checkout code from source control
            _statusUpdater.UpdateStatus(DeploymentStatuses.VscCheckout);
            GitProvider gitProvider = new GitProvider(deploymentContext);
            bool checkoutSuccess = gitProvider.Checkout();
            if (!checkoutSuccess) ExitProgramWithError("Git checkout was unsuccessful.", currentJob);

            // Load deployment conifguration
            bool configLoadSuccess = ConfigLoader.LoadConfigurationIntoContext(deploymentContext);
            if (!configLoadSuccess) ExitProgramWithError("Could not load configuration", currentJob);

            // Run Tasks
            bool taskRunResult = DeploymentTaskRunner.RunTasks(deploymentContext, _statusUpdater);

            if (taskRunResult)
            {
                _statusUpdater.Dispose();
                JobHelper.MarkJobAsComplete(currentJob);
            }
            else
            {
                ExitProgramWithError("Task did not complete.", currentJob);
            }
        }
コード例 #23
0
 public void WhenInvalidFlagSpecified_ThenParseRaisesInvalidCommandLineException()
 {
     Assert.Throws <InvalidCommandLineException>(
         () => CommandLineOptions.Parse(
             new[] { "/" }));
 }
コード例 #24
0
 /// <summary>
 /// Sets Options instance to be used by other membres.
 /// </summary>
 /// <param name="options"></param>
 public FileHelper(CommandLineOptions options)
 {
     CommandLineOptions = options;
 }
コード例 #25
0
 public void Init()
 {
     clo = new CommandLineOptions();
 }
コード例 #26
0
ファイル: Program.cs プロジェクト: eladbitton/.NET-API
		static void Main(string[] args)
		{
			// Usage:
			// SampleCode.exe -u "Your Account Username" -k "Your Account Key" --url "http://site.com/your-webpage"
			// OR 
			// SampleCode.exe -u "Your Account Username" -k "Your Account Key" --local-document "C:\your-directory\document.doc"

			CommandLineOptions options = new CommandLineOptions();
			if (!CommandLine.Parser.Default.ParseArguments(args, options))
				Environment.Exit(1);
			else if ((options.URL == null && options.LocalFile == null) || (options.URL != null && options.LocalFile != null))
			{
				Console.WriteLine("Error: You can speicfy either a URL or a local document to scan. For more information please enter '--help'.");
				Environment.Exit(1);
			}

			// For more information, visit Copyleaks "How-To page": https://api.copyleaks.com/Guides/HowToUse
			// Creating Copyleaks account: https://copyleaks.com/Account/Signup
			// Use your Copyleaks account information.
			// Generate your Account API Key: https://copyleaks.com/Account/Manage

			Scanner scanner = new Scanner(options.Username, options.ApiKey);
			uint creditsBalance = scanner.Credits;
			if (creditsBalance == 0)
			{
				Console.WriteLine("ERROR: You do not have enough credits to complete this scan. Your current credits balance = {0}).", creditsBalance);
				Environment.Exit(2);
			}

			Uri httpCallback = null;
			if (options.HttpCallback != null)
			{
				// Http callback example value:
				// https://your-website.com/copyleaks-gateway?id={PID}
				// Copyleaks server will replace the "{PID}" token with the actual process id.
				if (!Uri.TryCreate(options.HttpCallback, UriKind.Absolute, out httpCallback))
				{
					Console.WriteLine("ERROR: Bad Http-Callback.");
					Environment.Exit(3);
				}
			}

			try
			{
				ResultRecord[] results;
				if (options.URL != null)
				{
					Uri uri;
					if (!Uri.TryCreate(options.URL, UriKind.Absolute, out uri))
					{
						Console.WriteLine("ERROR: The URL ('{0}') is invalid.", options.URL); // Bad URL format.
						Environment.Exit(1);
					}

					results = scanner.ScanUrl(uri, httpCallback);
                }
				else
				{
					if (!File.Exists(options.LocalFile))
					{
						Console.WriteLine("ERROR: The file '{0}' does not exist.", options.LocalFile); // Bad URL format.
						Environment.Exit(1);
					}

					results = scanner.ScanLocalTextualFile(new FileInfo(options.LocalFile), httpCallback);
				}

				if (results.Length == 0)
				{
					Console.WriteLine("\tNo results.");
				}
				else
				{
					for (int i = 0; i < results.Length; ++i)
					{
						Console.WriteLine();
						Console.WriteLine("Result {0}:", i + 1);
						Console.WriteLine("Url: {0}", results[i].URL);
						Console.WriteLine("Precents: {0}", results[i].Precents);
						Console.WriteLine("CopiedWords: {0}", results[i].NumberOfCopiedWords);
					}
				}
			}
			catch (UnauthorizedAccessException e)
			{
				Console.WriteLine("\tFailed!");
				Console.WriteLine("+Error Description:");
				Console.WriteLine("{0}", e.Message);
			}
			catch (CommandFailedException theError)
			{
				Console.WriteLine("\tFailed!");
				Console.WriteLine("+Error Description:");
				Console.WriteLine("{0}", theError.Message);
			}
			catch (Exception ex)
			{
				Console.WriteLine("\tFailed!");
				Console.WriteLine("Unhandled Exception");
				Console.WriteLine(ex);
			}

			Environment.Exit(0);
		}
コード例 #27
0
 public DirectoryInfo GetOutputDirectory(CommandLineOptions options)
 {
     return new DirectoryInfo(options.GetOutput());
 }
コード例 #28
0
 internal CLIRunSettingsArgumentExecutor(IRunSettingsProvider runSettingsManager, CommandLineOptions commandLineOptions)
 {
     this.runSettingsManager = runSettingsManager;
     this.commandLineOptions = commandLineOptions;
 }
コード例 #29
0
 /// <summary>
 ///     Get a build asset registry only remote for a specific repo.
 /// </summary>
 /// <param name="options">Command line options</param>
 /// <param name="logger">Logger</param>
 /// <returns>New remote</returns>
 public static IRemote GetBarOnlyRemote(CommandLineOptions options, ILogger logger)
 {
     return(GetRemote(options, null, logger));
 }
コード例 #30
0
 public DirectoryInfo GetOutputDirectory(CommandLineOptions options)
 {
     return(new DirectoryInfo(options.GetInput()));
 }
コード例 #31
0
ファイル: Program.cs プロジェクト: EnoughTea/vipare
        private static void ProcessDiagrams(CommandLineOptions options)
        {
            // Read and verify passed command-line options:
            string outputFolder = Directory.GetCurrentDirectory();
            if (!string.IsNullOrWhiteSpace(options.OutputFolder) &&
                options.OutputFolder != CommandLineOptions.CurrentDirectoryMark) {
                outputFolder = Directory.CreateDirectory(options.OutputFolder).FullName;
            }

            var diagramFiles = PathTools.GatherFiles(options.VisioFiles).ToArray();

            string format = options.Format.TrimStart('.');
            if (!SupportedFormats.Contains(format)) {
                string expected = string.Join(", ", SupportedFormats.ToArray());
                throw new ArgumentException($"Passed unknown format '{format}', expected one of {{ {expected} }}.");
            }

            // We have options in check, so start actual export now:
            foreach (var diagramFile in diagramFiles) {
                Console.WriteLine($"Exporting '{diagramFile.FullName}':");
                ExportPages(diagramFile.FullName, outputFolder, format);
                Console.WriteLine($"Finished '{diagramFile}'.");
                Console.WriteLine();
            }
        }
コード例 #32
0
        static CommandLineOptions ProcessCommandLine(string[] args)
        {
            CommandLineOptions   myArgs = new CommandLineOptions();
            CommandLineArguments parser = new CommandLineArguments();

            AddParameters(parser);
            try
            {
                parser.Parse(args, myArgs);
            }

            catch (Exception e)
            {
                Console.Error.WriteLine("\nException while processing Command Line arguments [{0}]", e.Message);
                Environment.Exit(-1);
            }

            if (myArgs.help)
            {
                Console.WriteLine(Resources.MumUtilHelp);
                Environment.Exit(-1);
            }

            /*
             * Process all the arguments for 'semantic' correctness
             */
            if ((myArgs.maxmatch && myArgs.mum) ||
                (myArgs.maxmatch && myArgs.mumreference) ||
                (myArgs.mum && myArgs.mumreference)
                )
            {
                Console.Error.WriteLine("\nError: only one of -maxmatch, -mum, -mumreference options can be specified.");
                Environment.Exit(-1);
            }
            if (!myArgs.mumreference && !myArgs.mum && !myArgs.maxmatch)
            {
                myArgs.mumreference = true;
            }
            if ((myArgs.fileList == null) || (myArgs.fileList.Length < 2))
            {
                Console.Error.WriteLine("\nError: A reference file and at least 1 query file are required.");
                Environment.Exit(-1);
            }
            if ((myArgs.length <= 0) || (myArgs.length >= (8 * 1024)))   // TODO: What are real reasonable mum length limits?
            {
                Console.Error.WriteLine("\nError: mum length must be between 1 and 1024.");
                Environment.Exit(-1);
            }
            if (myArgs.both && myArgs.reverseOnly)
            {
                Console.Error.WriteLine("\nError: only one of -both or -reverseOnly options can be specified.");
                Environment.Exit(-1);
            }
            if (myArgs.c && (!myArgs.both && !myArgs.reverseOnly))
            {
                Console.Error.WriteLine("\nError: c requires one of either /b or /r options.");
                Environment.Exit(-1);
            }
            if (myArgs.outputFile != null)
            {   // redirect stdout
                fsConsoleOut = new FileStream(myArgs.outputFile, FileMode.Create);
                swConsoleOut = new StreamWriter(fsConsoleOut);
                Console.SetOut(swConsoleOut);
                swConsoleOut.AutoFlush = true;
            }

            return(myArgs);
        }
コード例 #33
0
ファイル: BoogieTest.cs プロジェクト: ccadar/symbooglix
 public static void setupCmdLineParser()
 {
     // THIS IS A HACK. Boogie's methods
     // depend on its command line parser being set!
     CommandLineOptions.Install(new Microsoft.Boogie.CommandLineOptions());
 }
コード例 #34
0
 public void WhenUrlIsInvalid_ThenParseRaisesInvalidCommandLineException()
 {
     Assert.Throws <InvalidCommandLineException>(
         () => CommandLineOptions.Parse(
             new[] { "/url", "notaurl" }));
 }
コード例 #35
0
 public FileInfo[] GetInputFiles(CommandLineOptions options)
 {
     return(GetInputFilesInDirectory(options.GetInput()));
 }
コード例 #36
0
 public void WhenUrlMissesArgument_ThenParseRaisesInvalidCommandLineException()
 {
     Assert.Throws <InvalidCommandLineException>(
         () => CommandLineOptions.Parse(
             new[] { "/url" }));
 }
コード例 #37
0
 public bool AreCompatibile(CommandLineOptions options)
 {
     return(options.GetOutput() == null && Directory.Exists(options.GetInput()));
 }
コード例 #38
0
 public void CreateOptions()
 {
     options = new CommandLineOptions("-");
 }
コード例 #39
0
 public TicExtraction(CommandLineOptions options)
     : base(options)
 {
 }
コード例 #40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ApplicationController"/> class.
        /// </summary>
        /// <param name="arguments">The arguments.</param>
        public ApplicationController(string[] arguments)
        {
            this.arguments = arguments;

            this.options = new CommandLineOptions();
        }
コード例 #41
0
            /// <inheritdoc />
            protected override async Task <CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options)
            {
                var    v1App    = PreRegisteredApps.CommonCacheTestV1;
                string resource = PreRegisteredApps.MsGraph;

                string[] scopes = new[]
                {
                    resource + "/user.read"
                };

                Logger.LogCallback = (LogLevel level, string message, bool containsPii) =>
                {
                    Console.WriteLine("{0}: {1}", level, message);
                };

                CommonCacheTestUtils.EnsureCacheFileDirectoryExists();

                var tokenCache = new TokenCache();

                FileBasedTokenCacheHelper.ConfigureUserCache(
                    options.CacheStorageType,
                    tokenCache,
                    CommonCacheTestUtils.AdalV3CacheFilePath,
                    CommonCacheTestUtils.MsalV2CacheFilePath);

                var app = new PublicClientApplication(v1App.ClientId, v1App.Authority, tokenCache)
                {
                    ValidateAuthority = true
                };

                IEnumerable <IAccount> accounts = await app.GetAccountsAsync().ConfigureAwait(false);

                try
                {
                    var result = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault(), app.Authority, false).ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.Account.Username}' from the cache");
                    return(new CacheExecutorResults(result.Account.Username, true));
                }
                catch (MsalUiRequiredException)
                {
                    var result = await app.AcquireTokenByUsernamePasswordAsync(scopes, options.Username, options.UserPassword.ToSecureString()).ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.Account.Username}' without the cache");
                    return(new CacheExecutorResults(result.Account.Username, false));
                }
            }
コード例 #42
0
ファイル: Program.cs プロジェクト: jango2015/servant-agent
        static void Main(string[] args)
        {
            TinyIoCContainer.Current.Register(ConfigManager.GetConfigurationFromDisk());
            TinyIoCContainer.Current.Register(typeof(ConsoleManager)).AsSingleton();
            TinyIoCContainer.Current.Register<Deployer>().AsSingleton();
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;

            var config = TinyIoCContainer.Current.Resolve<ServantAgentConfiguration>();
            #if !DEBUG
            if (Environment.UserInteractive)
            {
                var options = new CommandLineOptions();
                if (CommandLine.Parser.Default.ParseArguments(args, options))
                {
                    if (options.Install)
                    {
                        ServiceHelper.Install();
                    }
                    else if (options.Uninstall)
                    {
                        ServiceHelper.Uninstall();
                    }

                    if (options.Key != null)
                    {
                        config.ServantIoKey = options.Key;
                        ConfigManager.UpdateConfiguration(config);
                    }
                }

                return;
            }
            #endif

            #if DEBUG
            if (string.IsNullOrWhiteSpace(config.ServantIoKey))
            {
                Console.WriteLine("There's no Servant.io key defined. Please enter one here:");
                Console.Write(">");
                var key = Console.ReadLine();

                if (string.IsNullOrWhiteSpace(key))
                {
                    return;
                }

                config.ServantIoKey = key;
                ConfigManager.UpdateConfiguration(config);
            }

            Servant.Start();
            Console.ReadLine();
            #else
            var servicesToRun = new ServiceBase[]
            {
                new ServantAgentService()
            };

            ServiceBase.Run(servicesToRun);
            #endif
        }
コード例 #43
0
        private static void WriteMums(IEnumerable <Match> mums, Sequence refSequence, Sequence querySequence, CommandLineOptions myArgs)
        {
            // write the QuerySequenceId
            string DisplayID = querySequence.ID;

            Console.Write("> {0}", DisplayID);
            if (myArgs.displayQueryLength)
            {
                Console.Write(" " + querySequence.Count);
            }
            Console.WriteLine();

            // DISCUSSION:
            //   If a ReverseComplement sequence, MUMmer has the option to print the index start point relative
            //   to the original sequence we tagged the reversed DisplayID with " Reverse" so _if_ we find a
            //   " Reverse" on the end of the ID, assume it is a ReverseComplement and reverse the index
            bool isReverseComplement = myArgs.c && querySequence.IsMarkedAsReverseComplement();

            // Start is 1 based in literature but in programming (e.g. MaxUniqueMatch) they are 0 based.
            // Add 1
            Stopwatch swInterval = new Stopwatch();

            swInterval.Start();

            foreach (Match match in mums)
            {
                swInterval.Stop();
                // Add time taken by GetMatches().
                mummerTime = mummerTime.Add(swInterval.Elapsed);


                swInterval.Restart();
                Console.WriteLine("{0,8}  {1,8}  {2,8}",
                                  match.ReferenceSequenceOffset + 1,
                                  !isReverseComplement ? match.QuerySequenceOffset + 1 : querySequence.Count - match.QuerySequenceOffset,
                                  match.Length);
                if (myArgs.showMatchingString)
                {
                    StringBuilder sb = new StringBuilder((int)match.Length);
                    for (int i = 0; i < match.Length; ++i)
                    {
                        sb.Append((char)querySequence[match.QuerySequenceOffset + i]);
                    }

                    Console.WriteLine(sb.ToString());
                }

                swInterval.Stop();
                writetime = writetime.Add(swInterval.Elapsed);
                swInterval.Restart();
            }
        }
コード例 #44
0
 public void Dispose()
 {
     clo = null;
 }
コード例 #45
0
        static void Main(string[] args)
        {
            try
            {
                //            DateTime dStart = DateTime.Now;
                Stopwatch swMumUtil  = Stopwatch.StartNew();
                Stopwatch swInterval = new Stopwatch();

                Console.Error.WriteLine(SplashString());
                if (args.Length > 0)
                {
                    CommandLineOptions myArgs = ProcessCommandLine(args);
                    if (myArgs.help)
                    {
                        Console.WriteLine(Resources.MumUtilHelp);
                    }
                    else
                    {
                        FileInfo refFileinfo   = new FileInfo(myArgs.fileList[0]);
                        long     refFileLength = refFileinfo.Length;
                        refFileinfo = null;

                        swInterval.Restart();
                        IEnumerable <ISequence> referenceSequences = ParseFastA(myArgs.fileList[0]);
                        Sequence referenceSequence = referenceSequences.First() as Sequence;
                        swInterval.Stop();
                        if (myArgs.verbose)
                        {
                            Console.Error.WriteLine();
                            Console.Error.WriteLine("  Processed Reference FastA file: {0}", Path.GetFullPath(myArgs.fileList[0]));
                            Console.Error.WriteLine("        Length of first Sequence: {0:#,000}", referenceSequence.Count);
                            Console.Error.WriteLine("            Read/Processing time: {0}", swInterval.Elapsed);
                            Console.Error.WriteLine("            File size           : {0:#,000} bytes", refFileLength);
                        }

                        FileInfo queryFileinfo   = new FileInfo(myArgs.fileList[1]);
                        long     queryFileLength = queryFileinfo.Length;
                        refFileinfo = null;

                        IEnumerable <ISequence> parsedQuerySequences = ParseFastA(myArgs.fileList[1]);

                        IEnumerable <ISequence> querySequences = parsedQuerySequences;

                        if (myArgs.reverseOnly)
                        {
                            // convert to reverse complement sequences
                            querySequences = ReverseComplementSequenceList(parsedQuerySequences);
                        }
                        else if (myArgs.both)
                        {
                            // add the reverse complement sequences along with query sequences.
                            querySequences = AddReverseComplementsToSequenceList(parsedQuerySequences);
                        }

                        // DISCUSSION:
                        // Three possible outputs desired.  Globally unique 'mum' (v1), unique in reference sequence (v2),
                        //   or get the maximum matches of length or greater.
                        //
                        mummerTime = new TimeSpan();
                        writetime  = new TimeSpan();
                        IEnumerable <Match> mums;
                        long memoryAtStart = 0;
                        long memoryAtEnd   = 0;
                        if (myArgs.verbose)
                        {
                            swMumUtil.Stop();
                            memoryAtStart = GC.GetTotalMemory(true);
                            swMumUtil.Start();
                        }

                        swInterval.Restart();
                        MultiWaySuffixTree suffixTreee = new MultiWaySuffixTree(referenceSequence);
                        swInterval.Stop();

                        if (myArgs.verbose)
                        {
                            swMumUtil.Stop();
                            memoryAtEnd = GC.GetTotalMemory(true);
                            swMumUtil.Start();
                        }

                        MUMmer mummer = new MUMmer(suffixTreee);

                        if (myArgs.verbose)
                        {
                            Console.Error.WriteLine();
                            Console.Error.WriteLine("Suffix tree construction time   : {0}", swInterval.Elapsed);
                            Console.Error.WriteLine("Memory consumed by Suffix tree  : {0:#,000}", memoryAtEnd - memoryAtStart);
                            Console.Error.WriteLine("Total edges created             : {0:#,000}", suffixTreee.EdgesCount);
                            Console.Error.WriteLine("Memory per edge                 : {0:#,000.00} bytes", (((double)(memoryAtEnd - memoryAtStart)) / suffixTreee.EdgesCount));
                            Console.Error.WriteLine();
                            Console.Error.WriteLine("      Processed Query FastA file: {0}", Path.GetFullPath(myArgs.fileList[1]));
                            Console.Error.WriteLine("            File Size           : {0:#,000} bytes", queryFileLength);
                        }

                        mummer.LengthOfMUM = myArgs.length;
                        mummer.NoAmbiguity = myArgs.noAmbiguity;

                        long     querySeqCount  = 0;
                        double   sumofSeqLength = 0;
                        TimeSpan totalTimetakenToProcessQuerySequences = new TimeSpan();
                        string   outputOption = string.Empty;

                        if (myArgs.maxmatch)
                        {
                            outputOption = "GetMumsMaxMatch()";
                            swInterval.Restart();
                            foreach (Sequence qSeq in querySequences)
                            {
                                // Stop the wath after each query sequence parsed.
                                swInterval.Stop();

                                // Add total time to process query sequence.
                                // if reverse complement option is set, includes reverse complement time also.
                                totalTimetakenToProcessQuerySequences = totalTimetakenToProcessQuerySequences.Add(swInterval.Elapsed);

                                mums = mummer.GetMatches(qSeq);

                                WriteMums(mums, referenceSequence, qSeq, myArgs);

                                querySeqCount++;
                                sumofSeqLength += qSeq.Count;

                                // Start the watch for next query sequence parse.
                                swInterval.Restart();
                            }

                            swInterval.Stop();
                        }
                        else if (myArgs.mum)
                        {
                            // mums = mum3.GetMumsMum( referenceSequences[0], querySequences);
                            outputOption = "GetMumsMum()";
                            swInterval.Restart();
                            foreach (Sequence qSeq in querySequences)
                            {
                                // Stop the wath after each query sequence parsed.
                                swInterval.Stop();

                                // Add total time to process query sequence.
                                // if reverse complement option is set, includes reverse complement time also.
                                totalTimetakenToProcessQuerySequences = totalTimetakenToProcessQuerySequences.Add(swInterval.Elapsed);

                                swInterval.Restart();
                                // TODO: After implementing GetMatchesUniqueInBothReferenceAndQuery() in MUMmer
                                ////       GetMatchesUniqueInReference() with GetMatchesUniqueInBothReferenceAndQuery() in the line below.
                                mums = mummer.GetMatchesUniqueInReference(qSeq);
                                swInterval.Stop();

                                // Add time taken by GetMatchesUniqueInBothReferenceAndQuery().
                                mummerTime = mummerTime.Add(swInterval.Elapsed);

                                swInterval.Restart();
                                WriteMums(mums, referenceSequence, qSeq, myArgs);
                                swInterval.Stop();

                                // Add time taken by write matches.
                                writetime = writetime.Add(swInterval.Elapsed);

                                querySeqCount++;
                                sumofSeqLength += qSeq.Count;

                                // Start the watch for next query sequence parse.
                                swInterval.Restart();
                            }

                            swInterval.Stop();
                        }
                        else if (myArgs.mumreference)
                        {
                            // NOTE:
                            //     mum3.GetMUMs() this really implements the GetMumReference() functionality
                            // mums = mum3.GetMumsReference( referenceSequences[0], querySequences);     // should be
                            //swInterval.Restart();
                            outputOption = "GetMumsReference()";
                            swInterval.Restart();
                            foreach (Sequence qSeq in querySequences)
                            {
                                // Stop the watch after each query sequence parsed.
                                swInterval.Stop();

                                // Add total time to process query sequence.
                                // if reverse complement option is set, includes reverse complement time also.
                                totalTimetakenToProcessQuerySequences = totalTimetakenToProcessQuerySequences.Add(swInterval.Elapsed);

                                swInterval.Restart();
                                mums = mummer.GetMatchesUniqueInReference(qSeq);
                                swInterval.Stop();

                                // Add time taken by GetMatchesUniqueInReference().
                                mummerTime = mummerTime.Add(swInterval.Elapsed);

                                swInterval.Restart();
                                WriteMums(mums, referenceSequence, qSeq, myArgs);
                                swInterval.Stop();

                                // Add time taken by write matches.
                                writetime = writetime.Add(swInterval.Elapsed);
                                querySeqCount++;
                                sumofSeqLength += qSeq.Count;

                                // Start the watch for next query sequence parse.
                                swInterval.Restart();
                            }

                            swInterval.Stop();
                        }
                        else
                        {
                            // cannot happen as argument processing already asserted one of the three options must be specified
                            Console.Error.WriteLine("\nError: one of /maxmatch, /mum, /mumreference options must be specified.");
                            Environment.Exit(-1);
                            // kill the error about unitialized use of 'mums' in the next block...the compiler does not recognize
                            //   Environment.Exit() as a no-return function
                            throw new Exception("Never hit this");
                        }

                        if (myArgs.verbose)
                        {
                            if (myArgs.reverseOnly || myArgs.both)
                            {
                                Console.Error.WriteLine("        Read/Processing time          : {0}", timeTakenToParseQuerySequences);
                                Console.Error.WriteLine("     Reverse Complement time          : {0}", timeTakenToGetReverseComplement);
                                Console.Error.WriteLine("     Total time taken to Process reads: {0}", totalTimetakenToProcessQuerySequences);
                            }
                            else
                            {
                                Console.Error.WriteLine("        Read/Processing time          : {0}", totalTimetakenToProcessQuerySequences);
                            }

                            Console.Error.WriteLine();
                            Console.Error.WriteLine("         Number of query Sequences        : {0:#,000}", querySeqCount);
                            Console.Error.WriteLine("         Average length of query Sequences: {0:#,000}", sumofSeqLength / querySeqCount);
                            Console.Error.WriteLine();
                            Console.Error.WriteLine("Compute {0,20} time              : {1}", outputOption, mummerTime);
                            Console.Error.WriteLine("                WriteMums() time          : {0}", writetime);
                        }

                        swMumUtil.Stop();
                        if (myArgs.verbose)
                        {
                            Console.Error.WriteLine("           Total MumUtil Runtime      : {0}", swMumUtil.Elapsed);
                        }
                    }
                }
                else
                {
                    Console.WriteLine(Resources.MumUtilHelp);
                }
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }
コード例 #46
0
 public VerifyCommand(CommandLineOptions options)
 {
     this.options = options;
 }
コード例 #47
0
 public TicketConsoleExport(CommandLineOptions commandLineOptions)
 {
     this.isDetailledMode = commandLineOptions.Detailled;
 }
コード例 #48
0
 public void WhenUrlAndInvalidFlagSpecified_ThenParseRaisesInvalidCommandLineException()
 {
     Assert.Throws <InvalidCommandLineException>(
         () => CommandLineOptions.Parse(
             new[] { "/url", "iap-rdp:///project-1/us-central1-a/vm-1", "/ debug" }));
 }
コード例 #49
0
 public DeleteCommand(CommandLineOptions options, ICollection <int?> claimIds, bool all)
 {
     this.options  = options;
     this.claimIds = claimIds;
     this.all      = all;
 }
コード例 #50
0
ファイル: Program.cs プロジェクト: EnoughTea/vipare
        static void Main(string[] args)
        {
            bool debug = Debugger.IsAttached;
            if (!debug) { AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; }

            var options = new CommandLineOptions();
            if (Parser.Default.ParseArgumentsStrict(args, options)) {
                ProcessDiagrams(options);

                if (debug) { Console.ReadKey(); }
            }
        }
コード例 #51
0
 public RemoteFactory(CommandLineOptions options)
 {
     _options = options;
 }