Exemple #1
0
        static void ConfigureLogging(Arguments arguments)
        {
            var writeActions = new List<Action<string>>
            {
                s => log.AppendLine(s)
            };

            if (arguments.Output == OutputType.BuildServer || arguments.LogFilePath == "console" || arguments.Init)
            {
                writeActions.Add(Console.WriteLine);
            }

            if (arguments.LogFilePath != null && arguments.LogFilePath != "console")
            {
                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(arguments.LogFilePath));
                    if (File.Exists(arguments.LogFilePath))
                    {
                        using (File.CreateText(arguments.LogFilePath)) { }
                    }

                    writeActions.Add(x => WriteLogEntry(arguments, x));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to configure logging: " + ex.Message);
                }
            }

            Logger.SetLoggers(
                s => writeActions.ForEach(a => a(s)),
                s => writeActions.ForEach(a => a(s)),
                s => writeActions.ForEach(a => a(s)));
        }
Exemple #2
0
        public WebBrowser(Arguments args)
            : this()
        {
            var address = args["address"].Value as string;

            DispatcherThread.StartNew(() =>
            {
                //TODO: Add ability to define browser settings.
                if (address != null)
                    m_webBrowser = new ChromiumWebBrowser(address);
                else
                    m_webBrowser = new ChromiumWebBrowser("");

            }).Wait();

            //Ensure that the web browser is initialized.
            using (var evt = new ManualResetEvent(false))
            {
                m_webBrowser.BrowserInitialized += (o, e) => evt.Set();

                DispatcherThread.StartNew(() =>
                {

                    if (m_webBrowser.IsBrowserInitialized)
                    {
                        evt.Set();
                    }
                });

                evt.WaitOne();
            }
        }
Exemple #3
0
        private static void Main(string[] args)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            arguments = new Arguments(Environment.CommandLine);

            try
            {
                GenerateAll();

                if (compiler.Templates.Count > 0)
                {
                    Console.WriteLine("Running Compiler...");
                    compiler.Run();
                    Console.WriteLine("Writing Files...");
                    foreach (Template template in compiler.Templates)
                        using (StreamWriter sw = File.CreateText(template.OutputPath))
                            sw.Write(template.FinalCode);

                    Console.WriteLine("Done!");
                }
            }
            catch (Exception x)
            {
                Console.WriteLine("Error Message: {0}", x);
                Console.ReadKey();
            }
            timer.Stop();
            Console.WriteLine("Execution Time: " + timer.ElapsedMilliseconds + "ms");
        }
 public void GenerateBuildVersion()
 {
     var arguments = new Arguments();
     var versionBuilder = new ContinuaCi(arguments);
     var continuaCiVersion = versionBuilder.GenerateSetVersionMessage("0.0.0-Beta4.7");
     Assert.AreEqual("@@continua[setBuildVersion value='0.0.0-Beta4.7']", continuaCiVersion);
 }
        public static void Run(Arguments arguments, IFileSystem fileSystem)
        {
            Logger.WriteInfo(string.Format("Running on {0}.", runningOnMono ? "Mono" : "Windows"));

            var noFetch = arguments.NoFetch;
            var authentication = arguments.Authentication;
            var targetPath = arguments.TargetPath;
            var targetUrl = arguments.TargetUrl;
            var dynamicRepositoryLocation = arguments.DynamicRepositoryLocation;
            var targetBranch = arguments.TargetBranch;
            var commitId = arguments.CommitId;
            var overrideConfig = arguments.HasOverrideConfig ? arguments.OverrideConfig : null;

            var executeCore = new ExecuteCore(fileSystem);
            var variables = executeCore.ExecuteGitVersion(targetUrl, dynamicRepositoryLocation, authentication, targetBranch, noFetch, targetPath, commitId, overrideConfig);

            if (arguments.Output == OutputType.BuildServer)
            {
                foreach (var buildServer in BuildServerList.GetApplicableBuildServers())
                {
                    buildServer.WriteIntegration(Console.WriteLine, variables);
                }
            }

            if (arguments.Output == OutputType.Json)
            {
                switch (arguments.ShowVariable)
                {
                    case null:
                        Console.WriteLine(JsonOutputFormatter.ToJson(variables));
                        break;

                    default:
                        string part;
                        if (!variables.TryGetValue(arguments.ShowVariable, out part))
                        {
                            throw new WarningException(string.Format("'{0}' variable does not exist", arguments.ShowVariable));
                        }
                        Console.WriteLine(part);
                        break;
                }
            }

            using (var assemblyInfoUpdate = new AssemblyInfoFileUpdate(arguments, targetPath, variables, fileSystem))
            {
                var execRun = RunExecCommandIfNeeded(arguments, targetPath, variables);
                var msbuildRun = RunMsBuildIfNeeded(arguments, targetPath, variables);
                if (!execRun && !msbuildRun)
                {
                    assemblyInfoUpdate.DoNotRestoreAssemblyInfo();
                    //TODO Put warning back
                    //if (!context.CurrentBuildServer.IsRunningInBuildAgent())
                    //{
                    //    Console.WriteLine("WARNING: Not running in build server and /ProjectFile or /Exec arguments not passed");
                    //    Console.WriteLine();
                    //    Console.WriteLine("Run GitVersion.exe /? for help");
                    //}
                }
            }
        }
Exemple #6
0
        static void Main(Arguments args)
        {
            if (args == null) throw new ArgumentNullException("args");

            switch (args.Operation)
            {
                case Operation.ListUsers:
                    ListUsers();
                    break;

                case Operation.ExportTileData:
                    ExportTileData(args.UserName, args.Path);
                    break;

                case Operation.ExportTile:
                    ExportTile(args.UserName, args.Path);
                    break;

                case Operation.SetUserTileData:
                    SetUserTileData(args.UserName, args.Path);
                    break;

                case Operation.SetUserTile:
                    SetUserTile(args.UserName, args.Path);
                    break;

                default:
                    ShowHelp(args);
                    break;
            }
        }
Exemple #7
0
 /// <summary>
 /// Waits until the mouse is clicked, then start another coroutine.
 /// </summary>
 /// <returns></returns>
 IEnumerator mouseClick(Arguments args)
 {
     while (!Input.GetMouseButtonDown(0)) yield return null;
     args.speed = _speed; // Use the correct speed.
     args.startPosition = Input.mousePosition; // Get first mouse position
     StartCoroutine(mouseRelease(args)); // wait for release button, then continue
 }
Exemple #8
0
        public static JSObject resolve(Arguments args)
        {
            var resolveValue = args[0];

            var resolveFunction = resolveValue as Function;
            if (resolveFunction != null)
            {
                return resolveFunction.Invoke(new Arguments());
            }

            var resolvePromise = resolveValue as Promise;
            if (resolvePromise != null)
            {
                if (resolvePromise.m_promiseTask.Status != TaskStatus.RanToCompletion)
                    return resolvePromise;

                if (resolvePromise.m_promiseTask.Status == TaskStatus.WaitingToRun)
                    resolvePromise.m_promiseTask.Start();

                resolvePromise.m_promiseTask.Wait();

                if (resolvePromise.m_promiseTask.Status == TaskStatus.RanToCompletion)
                    return resolvePromise.m_promiseTask.Result;

                return resolvePromise;
            }

            var resolveThenable = resolveValue["then"].Value as Function;
            if (resolveThenable != null)
            {
                return resolveThenable.Invoke(new Arguments());
            }

            return resolveValue;
        }
 private static OptionSet GetOptions(Arguments outputArguments)
 {
     return new OptionSet
     {
         { "h|?|help",
             "Show this help message and exit.",
             v => outputArguments.ShowHelp = v != null },
         { "i|input=",
             "The input XML file (required)",
             v => outputArguments.InputFile = v },
         { "o|output=",
             "The output SNG file",
             v => outputArguments.OutputFile = v },
         { "console",
             "Generate a big-endian (console) file instead of little-endian (PC)",
             v => { if (v != null) outputArguments.Platform = new Platform(GamePlatform.XBox360, GameVersion.None); /*Same as PS3*/ }},
         { "vocal",
             "Generate from a vocal XML file instead of a guitar XML file",
             v => { if (v != null) outputArguments.ArrangementType = ArrangementType.Vocal; }},
         { "bass",
             "Generate from a bass XML file instead of a guitar XML file",
             v => { if (v != null) outputArguments.ArrangementType = ArrangementType.Bass; }},
         { "tuning=",
             "Use an alternate tuning for this song file."
             + " Tuning parameter should be comma-separated offsets from standard EADGBe tuning."
             + " For example, Drop D looks like: tuning=-2,0,0,0,0,0",
             v => outputArguments.Tuning = ParseTuning(v) }
     };
 }
Exemple #10
0
 public TokenValue(Arguments arguments, Block block) {
     _integer1 = 0;
     _double = 0.0;
     node = arguments;
     obj = block;
     _type = TokenValueType.None;
 }
Exemple #11
0
 public Promise(Arguments args)
 {
     m_promiseTask = new Task<JSObject>(() =>
     {
         return Undefined;
     });
 }
Exemple #12
0
        public static Arguments Load(string[] args)
        {
            if (null == args || 0 == args.Length)
            {
                return new Arguments
                {
                    Help = true
                };
            }

            var result = new Arguments();
            foreach (var arg in args)
            {
                switch (arg.ToUpperInvariant())
                {
                    case "/?":
                    case "/HELP":
                    case "-HELP":
                        result.Help = true;
                        break;

                    default:
                        result.Specs.Add(new FileSpec(arg));
                        break;
                }
            }

            return result;
        }
Exemple #13
0
        public Argument(PythonBoss pyBoss, long address, PythonDictionary spec, Process process, int depth, Arguments parent, string namePrefix)
        {
            Address = address;
            this.process = process;
            _pyBoss = pyBoss;
            _parent = parent;
            NamePrefix = namePrefix;

            // Parse the spec for this argument
            // stackspec: [{"name": "socket",
            //		      "size": 4,
            //		      "type": None,
            //		      "fuzz": NOFUZZ,
            //            "type_args": None},]

            Fuzz = (bool)spec.get("fuzz");
            Name = (string)spec.get("name");
            _argumentType = (object)spec.get("type");
            if ( spec.ContainsKey("type_args") )
            {
                _typeArgs = spec.get("type_args");
            }

            // Validate required fields
            if (Name == null)
                throw new Exception("ERROR: Argument specification must include 'name' attribute. Failed when parsing name prefix '" + namePrefix + "'.");
            else if (Fuzz == null)
                throw new Exception("ERROR: Argument specification must include 'fuzz' attribute. Failed when parsing type '" + namePrefix + Name + "'.");
            else if (spec.get("size") == null)
                throw new Exception("ERROR: Argument specification must include 'size' attribute. Failed when parsing type '" + namePrefix + Name + "'.");

            if (spec.get("size") is string)
            {
                object sizeArgument = null;
                if (parent.TryGetMemberSearchUp((string)spec.get("size"), out sizeArgument))
                    Size = ((Argument)sizeArgument).ToInt();
                else
                    throw new Exception("ERROR: Unable to load size for type '" + Name + "' from parent member named '" + (string)spec.get("size") + "'. Please make sure this field exists in the parent.");
            }
            else if (spec.get("size") is int)
            {
                Size = (int)spec.get("size");
            }
            else
            {
                throw new Exception("ERROR: Unable to load size for type '" + Name + "'. The size must be of type 'int' or type 'string'. Size is type: '" + spec.get("size").ToString() + "'" );
            }

            // Read the data
            try
            {
                Data = MemoryFunctions.ReadMemory(process.ProcessDotNet, address, (uint)Size);
            }
            catch (Exception e)
            {
                Data = null;
            }

            PointerTarget = null;
        }
        public static Arguments Load(string[] args)
        {
            var optionsSet = new OptionsSet();
            var arguments = new Arguments(optionsSet);

            optionsSet.AddOption("-a|--action=", Resources.ActionDescription, value =>
            {
                var action = PackageIndexManagerAction.Unknown;
                if (!string.IsNullOrEmpty(value))
                {
                    Enum.TryParse(value, true, out action);
                }
                arguments.Action = action;
            });
            optionsSet.AddOption("-t|--type=", Resources.TypeDescription, value => arguments.Type = value);
            optionsSet.AddOption("-p|--package=", Resources.PackageDescription, value => arguments.Package = value);
            optionsSet.AddOption("-n|--namespace=", Resources.TypeDescription, value => arguments.Namespace = value);
            optionsSet.AddOption("-e|--extension=", Resources.TypeDescription, value => arguments.Extension = value);
            optionsSet.AddOption("-df|--dumpfile=", Resources.TypeDescription, value => arguments.DumpFile = value);
            optionsSet.AddOption("-q|--quiet", Resources.QuietDescription, value => arguments.Quiet = (value != null));
            optionsSet.AddOption("-v|--verbose", Resources.VerboseDescription, value => arguments.Verbose = (value != null));
            optionsSet.AddOption("-f|--force", Resources.ForceDescription, value => arguments.Force = (value != null));
            optionsSet.AddOption("-?|--help", Resources.HelpDescription, value => arguments.ShouldHelp = (value != null));
            optionsSet.Parse(args);
            
            return arguments;
        }
    public override bool Execute(Arguments arguments)
    {
      var downloader = new RatingDownloader();
      var filename = arguments["f"];

      var ratedCards = Cards.All.Select(x => x.Name)
        .Select(x => new RatedCard {Name = x})
        .ToList();

      if (File.Exists(filename))
      {
        Console.WriteLine("Reading existing ratings from {0}...", filename);
        ReadExistingRatings(filename, ratedCards);
      }

      foreach (var ratedCard in ratedCards)
      {
        ratedCard.Rating = ratedCard.Rating ?? downloader.TryDownloadRating(ratedCard.Name) ?? 3.0m;
      }

      using (var writer = new StreamWriter(filename))
      {
        foreach (var ratedCard in ratedCards)
        {
          writer.WriteLine("{0};{1}",
            ratedCard.Rating.GetValueOrDefault()
              .ToString("f", CultureInfo.InvariantCulture), ratedCard.Name);
        }
      }

      return true;
    }
        private static bool ParseArgs(string[] args)
        {
            string configFilePath;
            Arguments CommandLine;
            XDocument configFile;

            CommandLine = new Arguments(args);

            if (String.IsNullOrWhiteSpace(CommandLine["configFilePath"]) == false)
                configFilePath = CommandLine["configFilePath"];
            else
                return false;

            configFile = XDocument.Load(configFilePath);

            _solrStorageAccName = (from eachNode in configFile.Descendants("SolrStorageAccName") select eachNode.Value).FirstOrDefault();
            _solrStorageAccKey = (from eachNode in configFile.Descendants("SolrStorageAccKey") select eachNode.Value).FirstOrDefault();
            _hostedServiceName = (from eachNode in configFile.Descendants("HostedServiceName") select eachNode.Value).FirstOrDefault();
            _subscriptionId = (from eachNode in configFile.Descendants("SubscriptionId") select eachNode.Value).FirstOrDefault();
            _certThumbprint = (from eachNode in configFile.Descendants("CertThumbprint") select eachNode.Value).FirstOrDefault();
            _deploymentName = (from eachNode in configFile.Descendants("DeploymentName") select eachNode.Value).FirstOrDefault();
            _masterWorkerRoleInstCount = (from eachNode in configFile.Descendants("SolrMasterHostWorkerRoleInstCount") select eachNode.Value).FirstOrDefault();
            _slaveWorkerRoleInstCount = (from eachNode in configFile.Descendants("SolrSlaveHostWorkerRoleInstCount") select eachNode.Value).FirstOrDefault();
            _adminWebRoleInstCount = (from eachNode in configFile.Descendants("AdminWebRoleInstCount") select eachNode.Value).FirstOrDefault();
            _deploymentPckgLoc = (from eachNode in configFile.Descendants("DeploymentPckgLoc") select eachNode.Value).FirstOrDefault();
            _cloudDriveSize = (from eachNode in configFile.Descendants("CloudDriveSize") select eachNode.Value).FirstOrDefault();
            _masterWorkerRolePort = (from eachNode in configFile.Descendants("SolrMasterHostWorkerRoleExternalEndpointPort") select eachNode.Value).FirstOrDefault();
            _slaveWorkerRolePort = (from eachNode in configFile.Descendants("SolrSlaveHostWorkerRoleExternalEndpointPort") select eachNode.Value).FirstOrDefault();
            _blobBaseUrl = (from eachNode in configFile.Descendants("BlobBaseUrl") select eachNode.Value).FirstOrDefault();

            return true;
        }
        public bool TryGetDirectories(string[] args, out Arguments arguments)
        {
            arguments = new Arguments();

              string source = string.Empty;
              string target = string.Empty;
              if (!args.Any())
            return false;
              if (args.Length %2 != 0)
            return false;
              for (var i = 0; i < args.Length; i += 2)
              {
            if (args[i].Substring(0, 8).ToLower() == "-source:")
              source = args[i].Substring(8);
            if (args[i].Substring(0, 8).ToLower() == "-target:")
              target = args[i].Substring(8);
            if (args[i+1].Substring(0, 8).ToLower() == "-source:")
              source = args[i+1].Substring(8);
            if (args[i+1].Substring(0, 8).ToLower() == "-target:")
              target = args[i+1].Substring(8);
            if ((source != target) && (source != string.Empty) && (target != string.Empty))
              arguments.SourceTargetPairs.Add(new SourceTargetPair {Source = source, Target = target});
            else
              return false;
            source = target = string.Empty;
              }
              return true;
        }
Exemple #18
0
        private static void Main(string[] args)
        {
            var exitEvent = new ManualResetEvent(false);
            var arguments = new Arguments();

            if(!Parser.Default.ParseArguments(args, arguments))
                return;
            if(arguments.Version) {
                Out.Log(Stubby.Version);
                return;
            }

            Console.CancelKeyPress += (sender, eventArgs) => {
                eventArgs.Cancel = true;
                exitEvent.Set();
            };

            var stubby = new Stubby(arguments);
            stubby.Start();

            Out.Info("Quit: Ctrl-c");
            Out.Linefeed();

            exitEvent.WaitOne();
            stubby.Stop();
        }
Exemple #19
0
        static void Main(string[] args)
        {
            //args = new string[] { @"--input=C:\Users\ack\AppData\Local\Temp\tmp15F1.tmp", @"--output=C:\Users\ack\AppData\Local\Temp\tmp4463.tmp", "--startsuspended", "--silent" };
            //args = new string[] { @"--input=C:\Users\ack\AppData\Local\Temp\tmpCC98.tmp", @"--output=C:\Users\ack\AppData\Local\Temp\tmpA3BA.tmp" };
            //args = new string[] { @"--input=C:\Users\ack\AppData\Local\Temp\tmp639.tmp", @"--output=C:\Users\ack\AppData\Local\Temp\tmpB02D.tmp" };
            _mainThreadID = Thread.CurrentThread.ManagedThreadId;
            var parser = new ArgumentParser(args);
            _arguments = parser.Parse();
            if (_arguments.Logging)
                Logger.SetLogger(new ConsoleLogger());
            writeHeader();
            if (!File.Exists(_arguments.InputFile) || _arguments.OutputFile == null)
            {
                printUseage();
                return;
            }
            Write("Test run options:");
            Write(File.ReadAllText(_arguments.InputFile));
            if (_arguments.StartSuspended)
                Console.ReadLine();
            tryRunTests();
            Write(" ");
            if (File.Exists(_arguments.OutputFile))
            {
                Write("Test run result:");
                Write(File.ReadAllText(_arguments.OutputFile));
            }

			// We do this since NUnit threads some times keep staing in running mode even after finished.
            killHaltedThreads();
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
 /// <summary>
 /// Query server configuration, cluster status and namespace configuration.
 /// </summary>
 public override void RunExample(AerospikeClient client, Arguments args)
 {
     Node node = client.Nodes[0];
     GetServerConfig(node, args);
     console.Write("");
     GetNamespaceConfig(node, args);
 }
Exemple #21
0
        static void Main( string[ ] args )
        {
            using ( Stream stream = typeof ( Program ).Assembly.GetManifestResourceStream ( "DroidExplorer.Service.DroidExplorer.Service.log4net" ) ) {
                XmlConfigurator.Configure ( stream );
            }

            DroidExplorer.Configuration.Settings.Instance.Loaded += delegate ( object sender, EventArgs e ) {
                SetSdkPath ( );
            };

            SetSdkPath ( );

            Arguments arguments = new Arguments ( args );
            Logger.Log = LogManager.GetLogger ( MethodBase.GetCurrentMethod ( ).DeclaringType );
            Logger.Level = Logger.Levels.Info | Logger.Levels.Error | Logger.Levels.Warn;

            if ( arguments.Contains( "console" ,"c" ) ) {
                DevicesMonitor dm = new DevicesMonitor ( );
                dm.Start ( );
                Console.WriteLine ( "Press {ENTER} to exit" );
                Console.ReadLine ( );
                dm.Stop ( );
            } else {
                try {
                    // start the service.
                    System.ServiceProcess.ServiceBase.Run ( new DeviceService ( ) );
                } catch ( Exception ex ) {
                    Logger.LogError ( typeof ( Program ), ex.Message, ex );
                    throw;
                }
            }
        }
        static void Main(string[] args)
        {
            _mainThreadID = Thread.CurrentThread.ManagedThreadId;
            var parser = new ArgumentParser(args);
            _arguments = parser.Parse();
            if (_arguments.Logging)
                Logger.SetLogger(new ConsoleLogger());
            //Logger.SetLogger(new FileLogger(true, Path.Combine(getPath(), "runner.log." + DateTime.Now.Ticks.ToString())));
            writeHeader();
            if (!File.Exists(_arguments.InputFile) || _arguments.OutputFile == null)
            {
                printUseage();
                return;
            }
            Write("Test run options:");
            Write(File.ReadAllText(_arguments.InputFile));
            if (_arguments.StartSuspended)
                Console.ReadLine();
            tryRunTests();
            Write(" ");
            if (File.Exists(_arguments.OutputFile))
            {
                Write("Test run result:");
                Write(File.ReadAllText(_arguments.OutputFile));
            }

			// We do this since NUnit threads some times keep staing in running mode even after finished.
            killHaltedThreads();
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
        /// <summary>
        /// Demonstrate writing bins with replace option. Replace will cause all record bins
        /// to be overwritten.  If an existing bin is not referenced in the replace command,
        /// the bin will be deleted.
        /// <para>
        /// The replace command has a performance advantage over the default put, because 
        /// the server does not have to read the existing record before overwriting it.
        /// </para>
        /// </summary>
        public override void RunExample(AerospikeClient client, Arguments args)
        {
            // Write securities
            console.Info("Write securities");
            Security security = new Security("GE", 26.89);
            security.Write(client, args.writePolicy, args.ns, args.set);

            security = new Security("IBM", 183.6);
            security.Write(client, args.writePolicy, args.ns, args.set);

            // Write account with positions.
            console.Info("Write account with positions");
            List<Position> positions = new List<Position>(2);
            positions.Add(new Position("GE", 1000));
            positions.Add(new Position("IBM", 500));
            Account accountWrite = new Account("123456", positions);
            accountWrite.Write(client, args.writePolicy, args.ns, args.set);

            // Read account/positions and join with securities.
            console.Info("Read accounts, positions and securities");
            Account accountRead = new Account();
            accountRead.Read(client, null, args.ns, args.set, "123456");

            // Validate data
            accountWrite.Validate(accountRead);
            console.Info("Accounts match");
        }
Exemple #24
0
 static void Main(string[] args)
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Arguments = new Arguments(args);
     Application.Run(new PointTracer());
 }
        static IEnumerable<FileInfo> GetAssemblyInfoFiles(string workingDirectory, Arguments args, IFileSystem fileSystem)
        {
            if (args.UpdateAssemblyInfoFileName != null && args.UpdateAssemblyInfoFileName.Any(x => !string.IsNullOrWhiteSpace(x)))
            {
                foreach (var item in args.UpdateAssemblyInfoFileName)
                {
                    var fullPath = Path.Combine(workingDirectory, item);

                    if (EnsureVersionAssemblyInfoFile(args, fileSystem, fullPath))
                    {
                        yield return new FileInfo(fullPath);
                    }
                }
            }
            else
            {
                foreach (var item in fileSystem.DirectoryGetFiles(workingDirectory, "AssemblyInfo.*", SearchOption.AllDirectories))
                {
                    var assemblyInfoFile = new FileInfo(item);

                    if (AssemblyVersionInfoTemplates.IsSupported(assemblyInfoFile.Extension))
                        yield return assemblyInfoFile;
                }
            }
        }
Exemple #26
0
 private void ParseArgument(string option, string[] args, ref int i, Arguments result)
 {
     if ("--recursive" == option || "-r" == option)
     {
         result.Recursive = true;
     }
     else if ("--monitor" == option || "-m" == option)
     {
         result.Monitor = true;
     }
     else if ("--quiet" == option || "-q" == option)
     {
         result.Quiet = true;
     }
     else if ("--event" == option || "-e" == option)
     {
         result.Events = new List<string>(Value(args, ++i, "event").Split(','));
     }
     else if ("--format" == option)
     {
         result.Format = TokenizeFormat(Value(args, ++i, "format"));
     }
     else if (Directory.Exists(option))
     {
         result.Paths.Add(System.IO.Path.GetFullPath(option));
     }
 }
        private void RunPutGet(AsyncClient client, Arguments args, Key key, Bin bin)
        {
            console.Info("Put: namespace={0} set={1} key={2} value={3}",
                key.ns, key.setName, key.userKey, bin.value);

            client.Put(args.writePolicy, new WriteHandler(this, client, args.writePolicy, key, bin), key, bin);
        }
        private static void Main(string[] args)
        {
            using (IUnityContainer container = ContainerBuilder.BuildUnityContainer())
            {
                MappingConfiguration.Bootstrap(container);

                var logger = container.Resolve<ILogger>();

                var arguments = new Arguments(args);
                var simulationOptions = CreateSimulationOptions(arguments);

                try
                {
                    SimulationRunner.RunSimulations(simulationOptions, container, logger);
                }
                catch (Exception ex)
                {
                    logger.Log(Tag.Error, ex.GetType().Name + " " + ex.Message);
                    logger.Log(Tag.Error, ex.StackTrace);

                    if (ex.InnerException != null)
                    {
                        logger.Log(Tag.Error, ex.InnerException.GetType().Name + " " + ex.Message);
                        logger.Log(Tag.Error, ex.InnerException.StackTrace);
                    }

                    logger.Log(Tag.Error, "Exiting due to error");
                }
            }
        }
Exemple #29
0
        private static void LoadArguments(string[] args)
        {
            _arguments = new Arguments();
            if (args.Length == 0)
            {
                _arguments.CommandType = CommandType.Help;
                return;
            }
            for (var i = 0; i < args.Length; i++)
            {
                var value = args[i];
                if (i == 0)
                {
                    if (value == "-help")
                    {
                        _arguments.CommandType = CommandType.Help;
                    }
                    if (value == "-test")
                    {
                        _arguments.CommandType = CommandType.Test;
                    }
                }

                if (!string.IsNullOrWhiteSpace(value) && i == 1)
                    _arguments.Parameter = value;
            }
        }
Exemple #30
0
        static void Main(string[] args)
        {
            "Initializing Site Monitor".LogInformation();
            _monitor = new Monitor();

            _monitor.InitializeDatabase(Database.ReadDatabasePathFromConfig());
            "Database initialized".LogInformation();

            var arguments = new Arguments();

            "Parsing parameters".LogInformation();

            if (CommandLineParser.Default.ParseArguments(args, arguments))
            {
                try
                {
                    if (arguments.Monitor)
                    {
                        var interval = arguments.Interval.HasValue ? arguments.Interval.Value : 5;

                        LoadTestRunners(arguments);

                        _monitor.StartMonitoring(interval);
                    }

                    if (arguments.WebInterface)
                    {
                        "Initializing web interface".LogInformation();

                        var port = arguments.Port ?? 12345;
                        _monitor.StartAPISelfHost(port);

                        ("Web interface initialized at http://localhost:" + port.ToString()).LogInformation();
                    }

                    Console.WriteLine("Press any key to finish it");
                    Console.Read();
                }
                finally
                {
                    if (arguments.Monitor)
                    {
                        "Stoping test runners".LogInformation();
                        _monitor.StopAll();
                    }

                    if (arguments.WebInterface)
                    {
                        "Shutting web interface".LogInformation();
                        _monitor.StopAPISelfHost();
                    }
                }
            }

            "Site Monitor finished".LogInformation();

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Press any key to quit Site Monitor");
            Console.Read();
        }
Exemple #31
0
 public int Add(Arguments args)
 {
     return(args.X + args.Y);
 }
Exemple #32
0
/// <summary>
/// <para>Matches against a regular expression. If there is a match, returns an object with the fields:</para>
/// <ul>
/// <li><code>str</code>: The matched string</li>
/// <li><code>start</code>: The matched string's start</li>
/// <li><code>end</code>: The matched string's end</li>
/// <li><code>groups</code>: The capture groups defined with parentheses</li>
/// </ul>
/// <para>If no match is found, returns <code>null</code>.</para>
/// </summary>
/// <example><para>Example: Get all users whose name starts with "A". Because <code>null</code> evaluates to <code>false</code> in
/// <a href="/api/javascript/filter/">filter</a>, you can just use the result of <code>match</code> for the predicate.</para>
/// <code>r.table('users').filter(function(doc){
///     return doc('name').match("^A")
/// }).run(conn, callback)
/// </code></example>
        public Match(Arguments args, OptArgs optargs)
            : base(TermType.MATCH, args, optargs)
        {
        }
Exemple #33
0
/// <summary>
/// <para>Matches against a regular expression. If there is a match, returns an object with the fields:</para>
/// <ul>
/// <li><code>str</code>: The matched string</li>
/// <li><code>start</code>: The matched string's start</li>
/// <li><code>end</code>: The matched string's end</li>
/// <li><code>groups</code>: The capture groups defined with parentheses</li>
/// </ul>
/// <para>If no match is found, returns <code>null</code>.</para>
/// </summary>
/// <example><para>Example: Get all users whose name starts with "A". Because <code>null</code> evaluates to <code>false</code> in
/// <a href="/api/javascript/filter/">filter</a>, you can just use the result of <code>match</code> for the predicate.</para>
/// <code>r.table('users').filter(function(doc){
///     return doc('name').match("^A")
/// }).run(conn, callback)
/// </code></example>
        public Match(Arguments args) : this(args, null)
        {
        }
 public NADropTransform(IHostEnvironment env, Arguments args, IDataView input)
     : base(Contracts.CheckRef(env, nameof(env)), RegistrationName, env.CheckRef(args, nameof(args)).Column, input, TestType)
 {
     Host.CheckNonEmpty(args.Column, nameof(args.Column));
     _isNAs = InitIsNAAndMetadata();
 }
Exemple #35
0
 public int Div(Arguments args)
 {
     return(args.X / args.Y);
 }
Exemple #36
0
 public int Mul(Arguments args)
 {
     return(args.X * args.Y);
 }
Exemple #37
0
 public int Sub(Arguments args)
 {
     return(args.X - args.Y);
 }
Exemple #38
0
/// <summary>
/// <para>Gets the type of a ReQL query's return value.</para>
/// </summary>
/// <example><para>Example: Get the type of a string.</para>
/// <code>r.expr("foo").typeOf().run(conn, callback);
/// // Result passed to callback
/// "STRING"
/// </code></example>
        public TypeOf(Arguments args, OptArgs optargs)
            : base(TermType.TYPE_OF, args, optargs)
        {
        }
Exemple #39
0
        /// <summary>
        ///     helper method to construct and XmlSerializer (in case we need to change the default serializer in the future)
        /// </summary>
        /// <param name="extended">object to create a serializer for</param>
        /// <returns>xml serializer for the type of extendedObject</returns>
        private static XmlSerializer XmlSerializerFactory(object extended)
        {
            Arguments.NotNull(extended, nameof(extended));

            return(new XmlSerializer(extended.GetType()));
        }
Exemple #40
0
        public static void Execute(Arguments arguments)
        {
            if (arguments == null)
            {
                arguments = Dev();
            }

            LoggedConsole.WriteLine("DATE AND TIME:" + DateTime.Now);
            LoggedConsole.WriteLine("Syntactic Pattern Recognition\n");
            //StringBuilder sb = new StringBuilder("DATE AND TIME:" + DateTime.Now + "\n");
            //sb.Append("SCAN ALL RECORDINGS IN A DIRECTORY USING HTK-RECOGNISER\n");

            Log.Verbosity = 1;

            FileInfo      recordingPath = arguments.Source;
            FileInfo      iniPath       = arguments.Config;
            DirectoryInfo outputDir     = arguments.Output;
            string        opFName       = "SPR-output.txt";
            string        opPath        = outputDir + opFName;

            Log.WriteIfVerbose("# Output folder =" + outputDir);

            // A: READ PARAMETER VALUES FROM INI FILE
            var config = new ConfigDictionary(iniPath);
            Dictionary <string, string> dict = config.GetTable();

            Dictionary <string, string> .KeyCollection keys = dict.Keys;

            string callName     = dict[key_CALL_NAME];
            double frameOverlap = Convert.ToDouble(dict[key_FRAME_OVERLAP]);
            //SPT PARAMETERS
            double intensityThreshold   = Convert.ToDouble(dict[key_SPT_INTENSITY_THRESHOLD]);
            int    smallLengthThreshold = Convert.ToInt32(dict[key_SPT_SMALL_LENGTH_THRESHOLD]);
            //WHIPBIRD PARAMETERS
            int    whistle_MinHz          = int.Parse(dict[key_WHISTLE_MIN_HZ]);
            int    whistle_MaxHz          = int.Parse(dict[key_WHISTLE_MAX_HZ]);
            double optimumWhistleDuration = double.Parse(dict[key_WHISTLE_DURATION]);   //optimum duration of whistle in seconds
            int    whip_MinHz             = (dict.ContainsKey(key_WHIP_MIN_HZ)) ? int.Parse(dict[key_WHIP_MIN_HZ]) : 0;
            int    whip_MaxHz             = (dict.ContainsKey(key_WHIP_MAX_HZ)) ? int.Parse(dict[key_WHIP_MAX_HZ]) : 0;
            double whipDuration           = (dict.ContainsKey(key_WHIP_DURATION)) ? double.Parse(dict[key_WHIP_DURATION]) : 0.0; //duration of whip in seconds
            //CURLEW PARAMETERS
            double minDuration = (dict.ContainsKey(key_MIN_DURATION)) ? double.Parse(dict[key_MIN_DURATION]) : 0.0;              //min duration of call in seconds
            double maxDuration = (dict.ContainsKey(key_MAX_DURATION)) ? double.Parse(dict[key_MAX_DURATION]) : 0.0;              //duration of call in seconds

            double eventThreshold = double.Parse(dict[key_EVENT_THRESHOLD]);                                                     //min score for an acceptable event
            int    DRAW_SONOGRAMS = Convert.ToInt16(dict[key_DRAW_SONOGRAMS]);

            // B: CHECK to see if conversion from .MP3 to .WAV is necessary
            var destinationAudioFile = recordingPath;

            //LOAD RECORDING AND MAKE SONOGRAM
            BaseSonogram sonogram = null;

            using (var recording = new AudioRecording(destinationAudioFile.FullName))
            {
                // if (recording.SampleRate != 22050) recording.ConvertSampleRate22kHz(); // THIS METHOD CALL IS OBSOLETE

                var sonoConfig = new SonogramConfig
                {
                    NoiseReductionType = NoiseReductionType.None,
                    //NoiseReductionType = NoiseReductionType.STANDARD,
                    WindowOverlap = frameOverlap,
                };
                sonogram = new SpectrogramStandard(sonoConfig, recording.WavReader);
            }

            List <AcousticEvent> predictedEvents = null;

            double[,] hits = null;
            double[] scores = null;

            var audioFileName = Path.GetFileNameWithoutExtension(destinationAudioFile.FullName);

            if (callName.Equals("WHIPBIRD"))
            {
                //SPT
                var result1 = SPT.doSPT(sonogram, intensityThreshold, smallLengthThreshold);
                //SPR
                Log.WriteLine("SPR start: intensity threshold = " + intensityThreshold);
                int    slope       = 0;   //degrees of the circle. i.e. 90 = vertical line.
                double sensitivity = 0.7; //lower value = more sensitive
                var    mHori       = MarkLine(result1.Item1, slope, smallLengthThreshold, intensityThreshold, sensitivity);
                slope       = 87;         //84
                sensitivity = 0.8;        //lower value = more sensitive
                var mVert = MarkLine(result1.Item1, slope, smallLengthThreshold - 4, intensityThreshold + 1, sensitivity);
                Log.WriteLine("SPR finished");
                Log.WriteLine("Extract Whipbird calls - start");

                int minBound_Whistle = (int)(whistle_MinHz / sonogram.FBinWidth);
                int maxBound_Whistle = (int)(whistle_MaxHz / sonogram.FBinWidth);
                int whistleFrames    = (int)(sonogram.FramesPerSecond * optimumWhistleDuration); //86 = frames/sec.
                int minBound_Whip    = (int)(whip_MinHz / sonogram.FBinWidth);
                int maxBound_Whip    = (int)(whip_MaxHz / sonogram.FBinWidth);
                int whipFrames       = (int)(sonogram.FramesPerSecond * whipDuration); //86 = frames/sec.
                var result3          = DetectWhipBird(mHori, mVert, minBound_Whistle, maxBound_Whistle, whistleFrames, minBound_Whip, maxBound_Whip, whipFrames, smallLengthThreshold);
                scores = result3.Item1;
                hits   = DataTools.AddMatrices(mHori, mVert);

                predictedEvents = AcousticEvent.ConvertScoreArray2Events(
                    scores,
                    whip_MinHz,
                    whip_MaxHz,
                    sonogram.FramesPerSecond,
                    sonogram.FBinWidth,
                    eventThreshold,
                    minDuration,
                    maxDuration,
                    TimeSpan.Zero);
                foreach (AcousticEvent ev in predictedEvents)
                {
                    ev.FileName = audioFileName;
                    ev.Name     = callName;
                }

                sonogram.Data = result1.Item1;
                Log.WriteLine("Extract Whipbird calls - finished");
            }
            else if (callName.Equals("CURLEW"))
            {
                //SPT
                double backgroundThreshold = 4.0;
                var    result1             = SNR.NoiseReduce(sonogram.Data, NoiseReductionType.Standard, backgroundThreshold);
                //var result1 = SPT.doSPT(sonogram, intensityThreshold, smallLengthThreshold);
                //var result1 = doNoiseRemoval(sonogram, intensityThreshold, smallLengthThreshold);

                //SPR
                Log.WriteLine("SPR start: intensity threshold = " + intensityThreshold);
                int    slope       = 20;  //degrees of the circle. i.e. 90 = vertical line.
                double sensitivity = 0.8; //lower value = more sensitive
                var    mHori       = MarkLine(result1.Item1, slope, smallLengthThreshold, intensityThreshold, sensitivity);
                slope       = 160;
                sensitivity = 0.8;        //lower value = more sensitive
                var mVert = MarkLine(result1.Item1, slope, smallLengthThreshold - 3, intensityThreshold + 1, sensitivity);
                Log.WriteLine("SPR finished");

                //detect curlew calls
                int minBound_Whistle = (int)(whistle_MinHz / sonogram.FBinWidth);
                int maxBound_Whistle = (int)(whistle_MaxHz / sonogram.FBinWidth);
                int whistleFrames    = (int)(sonogram.FramesPerSecond * optimumWhistleDuration);
                var result3          = DetectCurlew(mHori, mVert, minBound_Whistle, maxBound_Whistle, whistleFrames, smallLengthThreshold);

                //process curlew scores - look for curlew characteristic periodicity
                double minPeriod        = 1.2;
                double maxPeriod        = 1.8;
                int    minPeriod_frames = (int)Math.Round(sonogram.FramesPerSecond * minPeriod);
                int    maxPeriod_frames = (int)Math.Round(sonogram.FramesPerSecond * maxPeriod);
                scores = DataTools.filterMovingAverage(result3.Item1, 21);
                scores = DataTools.PeriodicityDetection(scores, minPeriod_frames, maxPeriod_frames);

                //extract events
                predictedEvents = AcousticEvent.ConvertScoreArray2Events(
                    scores,
                    whistle_MinHz,
                    whistle_MaxHz,
                    sonogram.FramesPerSecond,
                    sonogram.FBinWidth,
                    eventThreshold,
                    minDuration,
                    maxDuration,
                    TimeSpan.Zero);
                foreach (AcousticEvent ev in predictedEvents)
                {
                    ev.FileName = audioFileName;
                    ev.Name     = callName;
                }

                hits          = DataTools.AddMatrices(mHori, mVert);
                sonogram.Data = result1.Item1;
                Log.WriteLine("Extract Curlew calls - finished");
            }
            else if (callName.Equals("CURRAWONG"))
            {
                //SPT
                var result1 = SPT.doSPT(sonogram, intensityThreshold, smallLengthThreshold);
                //SPR
                Log.WriteLine("SPR start: intensity threshold = " + intensityThreshold);
                int slope = 70;           //degrees of the circle. i.e. 90 = vertical line.
                //slope = 210;
                double sensitivity = 0.7; //lower value = more sensitive
                var    mHori       = MarkLine(result1.Item1, slope, smallLengthThreshold, intensityThreshold, sensitivity);
                slope = 110;
                //slope = 340;
                sensitivity = 0.7;        //lower value = more sensitive
                var mVert = MarkLine(result1.Item1, slope, smallLengthThreshold - 3, intensityThreshold + 1, sensitivity);
                Log.WriteLine("SPR finished");

                int minBound_Whistle = (int)(whistle_MinHz / sonogram.FBinWidth);
                int maxBound_Whistle = (int)(whistle_MaxHz / sonogram.FBinWidth);
                int whistleFrames    = (int)(sonogram.FramesPerSecond * optimumWhistleDuration); //86 = frames/sec.
                var result3          = DetectCurlew(mHori, mVert, minBound_Whistle, maxBound_Whistle, whistleFrames + 10, smallLengthThreshold);
                scores = result3.Item1;
                hits   = DataTools.AddMatrices(mHori, mVert);

                predictedEvents = AcousticEvent.ConvertIntensityArray2Events(
                    scores,
                    TimeSpan.Zero,
                    whistle_MinHz,
                    whistle_MaxHz,
                    sonogram.FramesPerSecond,
                    sonogram.FBinWidth,
                    eventThreshold,
                    0.5,
                    maxDuration);
                foreach (AcousticEvent ev in predictedEvents)
                {
                    ev.FileName = audioFileName;
                    //ev.Name = callName;
                }
            }

            //write event count to results file.
            double sigDuration = sonogram.Duration.TotalSeconds;
            //string fname = Path.GetFileName(recordingPath);
            int count = predictedEvents.Count;

            Log.WriteIfVerbose("Number of Events: " + count);
            string str = string.Format("{0}\t{1}\t{2}", callName, sigDuration, count);

            FileTools.WriteTextFile(opPath, AcousticEvent.WriteEvents(predictedEvents, str).ToString());

            // SAVE IMAGE
            string imageName = outputDir + audioFileName;
            string imagePath = imageName + ".png";

            if (File.Exists(imagePath))
            {
                int suffix = 1;
                while (File.Exists(imageName + "." + suffix.ToString() + ".png"))
                {
                    suffix++;
                }
                //{
                //    suffix = (suffix == string.Empty) ? "1" : (int.Parse(suffix) + 1).ToString();
                //}
                //File.Delete(outputDir + audioFileName + "." + suffix.ToString() + ".png");
                File.Move(imagePath, imageName + "." + suffix.ToString() + ".png");
            }
            //string newPath = imagePath + suffix + ".png";
            if (DRAW_SONOGRAMS == 2)
            {
                DrawSonogram(sonogram, imagePath, hits, scores, predictedEvents, eventThreshold);
            }
            else
            if ((DRAW_SONOGRAMS == 1) && (predictedEvents.Count > 0))
            {
                DrawSonogram(sonogram, imagePath, hits, scores, predictedEvents, eventThreshold);
            }

            Log.WriteIfVerbose("Image saved to: " + imagePath);
            //string savePath = outputDir + Path.GetFileNameWithoutExtension(recordingPath);
            //string suffix = string.Empty;
            //Image im = sonogram.GetImage(false, false);
            //string newPath = savePath + suffix + ".jpg";
            //im.Save(newPath);

            LoggedConsole.WriteLine("\nFINISHED RECORDING!");
            Console.ReadLine();
        }
Exemple #41
0
        public override void Handle(Arguments args, DotvvmProjectMetadata dotvvmProjectMetadata)
        {
            // make sure the test directory exists
            if (string.IsNullOrEmpty(dotvvmProjectMetadata.UITestProjectPath))
            {
                dotvvmProjectMetadata.UITestProjectPath = ConsoleHelpers.AskForValue($"Enter the path to the test project\n(relative to DotVVM project directory, e.g. '..\\{dotvvmProjectMetadata.ProjectName}.Tests'): ");
            }
            var testProjectDirectory = dotvvmProjectMetadata.GetUITestProjectFullPath();

            if (!Directory.Exists(testProjectDirectory))
            {
                throw new Exception($"The directory {testProjectDirectory} doesn't exist!");
            }

            // make sure we know the test project namespace
            if (string.IsNullOrEmpty(dotvvmProjectMetadata.UITestProjectRootNamespace))
            {
                var csprojService = new CSharpProjectService();
                var csproj        = csprojService.FindCsprojInDirectory(testProjectDirectory);
                if (csproj != null)
                {
                    csprojService.Load(csproj);
                    dotvvmProjectMetadata.UITestProjectRootNamespace = csprojService.GetRootNamespace();
                }
                else
                {
                    dotvvmProjectMetadata.UITestProjectRootNamespace = ConsoleHelpers.AskForValue("Enter the test project root namespace: ");
                    if (string.IsNullOrEmpty(dotvvmProjectMetadata.UITestProjectRootNamespace))
                    {
                        throw new Exception("The test project root namespace must not be empty!");
                    }
                }
            }

            // generate the test stubs
            var name  = args[0];
            var files = ExpandFileNames(name);

            foreach (var file in files)
            {
                Console.WriteLine($"Generating stub for {file}...");

                // determine full type name and target file
                var relativePath     = PathHelpers.GetDothtmlFileRelativePath(dotvvmProjectMetadata, file);
                var relativeTypeName = PathHelpers.TrimFileExtension(relativePath) + "Helper";
                var fullTypeName     = dotvvmProjectMetadata.UITestProjectRootNamespace + "." + PathHelpers.CreateTypeNameFromPath(relativeTypeName);
                var targetFileName   = Path.Combine(dotvvmProjectMetadata.UITestProjectPath, "Helpers", relativeTypeName + ".cs");

                // generate the file
                //var generator = new SeleniumHelperGenerator();
                //var config = new SeleniumGeneratorConfiguration()
                //{
                //    TargetNamespace = PathHelpers.GetNamespaceFromFullType(fullTypeName),
                //    HelperName = PathHelpers.GetTypeNameFromFullType(fullTypeName),
                //    HelperFileFullPath = targetFileName,
                //    ViewFullPath = file
                //};

                //generator.ProcessMarkupFile(DotvvmConfiguration.CreateDefault(), config);
            }
        }
Exemple #42
0
/// <summary>
/// <para>Gets the type of a ReQL query's return value.</para>
/// </summary>
/// <example><para>Example: Get the type of a string.</para>
/// <code>r.expr("foo").typeOf().run(conn, callback);
/// // Result passed to callback
/// "STRING"
/// </code></example>
        public TypeOf(Arguments args) : this(args, null)
        {
        }
 public MulticlassLogisticRegression(IHostEnvironment env, Arguments args)
     : base(args, env, LoadNameValue, Contracts.CheckRef(args, nameof(args)).ShowTrainingStats)
 {
 }
Exemple #44
0
        /// <summary>
        ///     deserializes a byte[] using XmlSerializer
        /// </summary>
        /// <typeparam name="TObject">Object Type</typeparam>
        /// <param name="extended">object being extended</param>
        /// <returns>Instance of deserialized TObject</returns>
        public static TObject?DeserializeViaXmlSerializer <TObject>(this byte[] extended)
        {
            extended = Arguments.EnsureNotNull(extended, nameof(extended));

            return((TObject?)extended.DeserializeViaXmlSerializer(typeof(TObject), Array.Empty <Type>()));
        }
Exemple #45
0
 public Executor(Arguments arguments, WorkflowRuntimeContext context)
 {
     this.arguments = arguments;
     this.context   = context;
 }
Exemple #46
0
 public static void BurstTestFunction(ref Arguments args)
 {
     CommonTestFunction(ref args);
 }
 protected override void OnCompositeStart(Arguments args)
 {
     this.childrenEnumerator = children.GetEnumerator();
 }
        static void Main(string[] args)
        {
            if (args.Count() < 1)
            {
                Console.WriteLine("need files to render...");
                Console.WriteLine("GerberToImage <files> [--dpi N] [--noxray] [--nopcb] [--silk color] [--trace color] [--copper color] [--mask color]");
                return;
            }

            int           dpi         = 400;
            Arguments     NextArg     = Arguments.None;
            bool          xray        = true;
            bool          normal      = true;
            string        pcbcolor    = "green";
            string        silkcolor   = "white";
            string        tracecolor  = "auto";
            string        coppercolor = "gold";
            List <string> RestList    = new List <string>();

            for (int i = 0; i < args.Count(); i++)
            {
                switch (NextArg)
                {
                case Arguments.dpi: dpi = Int32.Parse(args[i]); NextArg = Arguments.None; break;

                case Arguments.silk: silkcolor = args[i]; NextArg = Arguments.None; break;

                case Arguments.mask: pcbcolor = args[i]; NextArg = Arguments.None; break;

                case Arguments.trace: tracecolor = args[i]; NextArg = Arguments.None; break;

                case Arguments.copper: coppercolor = args[i]; NextArg = Arguments.None; break;

                case Arguments.None:
                    switch (args[i].ToLower())
                    {
                    case "-dpi":
                    case "--dpi": NextArg = Arguments.dpi; break;

                    case "-silk":
                    case "--silk": NextArg = Arguments.silk; break;

                    case "-trace":
                    case "--trace": NextArg = Arguments.trace; break;

                    case "-copper":
                    case "--copper": NextArg = Arguments.copper; break;

                    case "-mask":
                    case "--mask": NextArg = Arguments.mask; break;

                    case "-noxray":
                    case "--noxray": xray = false; NextArg = Arguments.None; break;

                    case "-nopcb":
                    case "--nopcb": normal = false; NextArg = Arguments.None; break;

                    default:
                        RestList.Add(args[i]); break;
                    }
                    break;
                }
            }


            Gerber.SaveIntermediateImages = false;
            Gerber.ShowProgress           = false;

            if (RestList.Count() == 1 && File.Exists(RestList[0]) && Path.GetExtension(RestList[0]).ToLower() != ".zip")
            {
                //  Gerber.WriteSanitized = true;
                Gerber.ExtremelyVerbose = false;
                //Gerber.Verbose = true;
                Gerber.WaitForKey   = true;
                Gerber.ShowProgress = true;

                CreateImageForSingleFile(new StandardConsoleLog(), RestList[0], Color.Black, Color.White);
                if (Gerber.WaitForKey)
                {
                    Console.WriteLine("Press any key to continue");
                    Console.ReadKey();
                }
                return;
            }

            GerberImageCreator GIC = new GerberImageCreator();
            string             TargetFileBaseName = "";

            if (RestList.Count() >= 1)
            {
                TargetFileBaseName = RestList[0];
            }

            List <String> FileList = new List <string>();

            foreach (var a in RestList)
            {
                if (Directory.Exists(a))
                {
                    FileList.AddRange(Directory.GetFiles(a, "*.*"));
                }
                else
                {
                    if (File.Exists(a))
                    {
                        FileList.Add(a);
                    }
                }
            }

            for (int i = 0; i < FileList.Count; i++)
            {
                if (FileList[i][FileList[i].Count() - 1] == '\\')
                {
                    FileList[i] = Path.GetDirectoryName(FileList[i]);
                }
            }
            var L = new GerberToImage(Path.GetFileNameWithoutExtension(TargetFileBaseName));

            GIC.AddBoardsToSet(FileList, new StandardConsoleLog(), true);
            BoardRenderColorSet colors = new BoardRenderColorSet();

            if (pcbcolor == "")
            {
                pcbcolor = "black";
            }
            colors.SetupColors(pcbcolor, silkcolor, tracecolor, coppercolor);


            GIC.SetColors(colors);
            GIC.WriteImageFiles(TargetFileBaseName, dpi, false, xray, normal, new StandardConsoleLog());
            Console.WriteLine("Done writing {0}", TargetFileBaseName);
        }
Exemple #49
0
/// <summary>
/// <para>Takes a stream and partitions it into multiple groups based on the
/// fields or functions provided.  Commands chained after <code>group</code> will be
/// called on each of these grouped sub-streams, producing grouped data.</para>
/// </summary>
/// <example><para>Example: What is each player's best game?</para>
/// <code>r.table('games').group('player').max('points').run(conn, callback)
/// </code></example>
        public Group(Arguments args) : this(args, null)
        {
        }
Exemple #50
0
 /// <summary>
 /// Copies the Arguments instance.
 /// </summary>
 /// <param name="fromArgumentPackage">the source Arguments instance</param>
 /// <param name="toArgumentPackage">the target Arguments instance</param>
 protected override void CopyArgumentPackageCore(Arguments fromArgumentPackage, Arguments toArgumentPackage)
 {
     DescribedArgumentsHelper.Copy(fromArgumentPackage, toArgumentPackage);
 }
Exemple #51
0
        public void Execute(Arguments arguments)
        {
            var result = AccessManager.CurrentAccess.GetDatabaseDiagramDetails(arguments.Name.Value);

            Scripter.Variables.SetVariableValue(arguments.Result.Value, new JsonStructure(JObject.FromObject(result)));
        }
Exemple #52
0
/// <summary>
/// <para>Takes a stream and partitions it into multiple groups based on the
/// fields or functions provided.  Commands chained after <code>group</code> will be
/// called on each of these grouped sub-streams, producing grouped data.</para>
/// </summary>
/// <example><para>Example: What is each player's best game?</para>
/// <code>r.table('games').group('player').max('points').run(conn, callback)
/// </code></example>
        public Group(Arguments args, OptArgs optargs)
            : base(TermType.GROUP, args, optargs)
        {
        }
Exemple #53
0
/// <summary>
/// <para>Splits a string into substrings.  Splits on whitespace when called
/// with no arguments.  When called with a separator, splits on that
/// separator.  When called with a separator and a maximum number of
/// splits, splits on that separator at most <code>max_splits</code> times.  (Can be
/// called with <code>null</code> as the separator if you want to split on whitespace
/// while still specifying <code>max_splits</code>.)</para>
/// <para>Mimics the behavior of Python's <code>string.split</code> in edge cases, except
/// for splitting on the empty string, which instead produces an array of
/// single-character strings.</para>
/// </summary>
/// <example><para>Example: Split on whitespace.</para>
/// <code>r.expr("foo  bar bax").split().run(conn, callback)
/// </code></example>
        public Split(Arguments args, OptArgs optargs)
            : base(TermType.SPLIT, args, optargs)
        {
        }
Exemple #54
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            //Setup Logger for API
            APIConfiguration.Logger = new APILogListener();

            //Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2 Loading";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            //
            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Values are available here
                if (options.Init)
                {
                    settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password);
                }
            }
            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    //If lastcoord is snipe coord, bot start from default location

                    if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000)
                    {
                        settings.LocationConfig.DefaultLatitude  = lat;
                        settings.LocationConfig.DefaultLongitude = lng;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (!_ignoreKillSwitch)
            {
                if (CheckMKillSwitch() || CheckKillSwitch())
                {
                    return;
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    )
                                .OrderBy(pt => pt.Distance)
                                .FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            //validation auth.config
            if (boolNeedsSetup)
            {
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You have selected PogoDev API but you have not provided an API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    try
                    {
                        HttpClient client = new HttpClient();
                        client.DefaultRequestHeaders.Add("X-AuthToken", apiCfg.AuthAPIKey);
                        var maskedKey = apiCfg.AuthAPIKey.Substring(0, 4) + "".PadLeft(apiCfg.AuthAPIKey.Length - 8, 'X') + apiCfg.AuthAPIKey.Substring(apiCfg.AuthAPIKey.Length - 4, 4);
                        HttpResponseMessage response = client.PostAsync("https://pokehash.buddyauth.com/api/v133_1/hash", null).Result;

                        string   AuthKey             = response.Headers.GetValues("X-AuthToken").FirstOrDefault();
                        string   MaxRequestCount     = response.Headers.GetValues("X-MaxRequestCount").FirstOrDefault();
                        DateTime AuthTokenExpiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(Convert.ToDouble(response.Headers.GetValues("X-AuthTokenExpiration").FirstOrDefault()));
                        TimeSpan Expiration          = AuthTokenExpiration - DateTime.UtcNow;
                        string   Result = $"Key: {maskedKey} RPM: {MaxRequestCount} Expiration Date: {AuthTokenExpiration.Month}/{AuthTokenExpiration.Day}/{AuthTokenExpiration.Year} ({Expiration.Days} Days {Expiration.Hours} Hours {Expiration.Minutes} Minutes)";
                        Logger.Write(Result, LogLevel.Info, ConsoleColor.Green);
                        AuthKey         = null;
                        MaxRequestCount = null;
                        Expiration      = new TimeSpan();
                        Result          = null;
                    }
                    catch
                    {
                        Logger.Write("The HashKey is invalid or has expired, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error);
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 seconds, You are running bot with Legacy API (0.45), but it will increase your risk of being banned and triggering captchas. Config Captchas in config.json to auto-resolve them",
                        LogLevel.Warning
                        );

#if RELEASE
                    Thread.Sleep(15000);
#endif
                }
                else
                {
                    Logger.Write(
                        "At least 1 authentication method must be selected, please correct your auth.json.",
                        LogLevel.Error
                        );
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            _session = new Session(settings,
                                   new ClientSettings(settings, elevationService), logicSettings, elevationService,
                                   translation
                                   );
            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            MultiAccountManager accountManager = new MultiAccountManager(settings, logicSettings.Bots);
            ioc.Register(accountManager);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;

                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            onBotStarted?.Invoke(_session, aggregator);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();
            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            var bot = accountManager.GetStartUpAccount();

            _session.ReInitSessionWithNextBot(bot);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            Logger.Write(
                $"(Start-Up Stats) User: {bot.Username} | XP: {bot.CurrentXp} | SD: {bot.Stardust}",
                LogLevel.Info, ConsoleColor
                .Magenta
                );

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token).ConfigureAwait(false); // that need to keep data live
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }


            if (_session.LogicSettings.DataSharingConfig.EnableSyncData)
            {
                BotDataSocketClient.StartAsync(_session, Properties.Resources.EncryptKey);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }

            // jjskuld - Don't await the analytics service since it starts a worker thread that never returns.
#pragma warning disable 4014
            _session.AnalyticsService.StartAsync(_session, _session.CancellationTokenSource.Token);
#pragma warning restore 4014
            _session.EventDispatcher.EventReceived += evt => AnalyticsService.Listen(evt, _session);

            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
Exemple #55
0
 public OperationsWINDOWSSERVICE(Arguments args, Action <string> log)
     : base(args, log)
 {
 }
        public static CommonOutputs.RegressionOutput TrainRegression(IHostEnvironment env, Arguments input)
        {
            Contracts.CheckValue(env, nameof(env));
            var host = env.Register("TrainOLS");

            host.CheckValue(input, nameof(input));
            EntryPointUtils.CheckInputArgs(host, input);

            return(LearnerEntryPointsUtils.Train <Arguments, CommonOutputs.RegressionOutput>(host, input,
                                                                                             () => new OlsLinearRegressionTrainer(host, input),
                                                                                             () => LearnerEntryPointsUtils.FindColumn(host, input.TrainingData.Schema, input.LabelColumn),
                                                                                             () => LearnerEntryPointsUtils.FindColumn(host, input.TrainingData.Schema, input.WeightColumn)));
        }
/// <summary>
/// <para>Create a table. A RethinkDB table is a collection of JSON documents.</para>
/// </summary>
/// <example><para>Example: Create a table named 'dc_universe' with the default settings.</para>
/// <code>&gt; r.db('heroes').tableCreate('dc_universe').run(conn, callback);
/// // Result passed to callback
/// {
///     "config_changes": [
///         {
///             "new_val": {
///                 "db": "test",
///                 "durability":  "hard",
///                 "id": "20ea60d4-3b76-4817-8828-98a236df0297",
///                 "name": "dc_universe",
///                 "primary_key": "id",
///                 "shards": [
///                     {
///                         "primary_replica": "rethinkdb_srv1",
///                         "replicas": [
///                             "rethinkdb_srv1",
///                             "rethinkdb_srv2"
///                         ]
///                     }
///                 ],
///                 "write_acks": "majority"
///             },
///             "old_val": null
///         }
///     ],
///     "tables_created": 1
/// }
/// </code></example>
        public TableCreate(Arguments args, OptArgs optargs)
            : base(TermType.TABLE_CREATE, args, optargs)
        {
        }
Exemple #58
0
/// <summary>
/// <para>Splits a string into substrings.  Splits on whitespace when called
/// with no arguments.  When called with a separator, splits on that
/// separator.  When called with a separator and a maximum number of
/// splits, splits on that separator at most <code>max_splits</code> times.  (Can be
/// called with <code>null</code> as the separator if you want to split on whitespace
/// while still specifying <code>max_splits</code>.)</para>
/// <para>Mimics the behavior of Python's <code>string.split</code> in edge cases, except
/// for splitting on the empty string, which instead produces an array of
/// single-character strings.</para>
/// </summary>
/// <example><para>Example: Split on whitespace.</para>
/// <code>r.expr("foo  bar bax").split().run(conn, callback)
/// </code></example>
        public Split(Arguments args) : this(args, null)
        {
        }
        public void Execute(Arguments arguments)
        {
            var driver = OpenCommand.GetDriver();

            driver.Quit();
        }
/// <summary>
/// <para>Create a table. A RethinkDB table is a collection of JSON documents.</para>
/// </summary>
/// <example><para>Example: Create a table named 'dc_universe' with the default settings.</para>
/// <code>&gt; r.db('heroes').tableCreate('dc_universe').run(conn, callback);
/// // Result passed to callback
/// {
///     "config_changes": [
///         {
///             "new_val": {
///                 "db": "test",
///                 "durability":  "hard",
///                 "id": "20ea60d4-3b76-4817-8828-98a236df0297",
///                 "name": "dc_universe",
///                 "primary_key": "id",
///                 "shards": [
///                     {
///                         "primary_replica": "rethinkdb_srv1",
///                         "replicas": [
///                             "rethinkdb_srv1",
///                             "rethinkdb_srv2"
///                         ]
///                     }
///                 ],
///                 "write_acks": "majority"
///             },
///             "old_val": null
///         }
///     ],
///     "tables_created": 1
/// }
/// </code></example>
        public TableCreate(Arguments args) : this(args, null)
        {
        }