コード例 #1
1
ファイル: MenuForm.cs プロジェクト: gitter-badger/dot-imaging
        /// <summary>
        /// Creates a new menu form.
        /// </summary>
        /// <param name="title">Window title.</param>
        /// <param name="itemNames">Item names.</param>
        /// <param name="actions">Actions.</param>
        public MenuForm(string title, string[] itemNames, Action[] actions)
        {
            Title = title;
            SelectedIndex = -1;

            if (itemNames == null || actions == null)
                return;
            if (itemNames.Length != actions.Length)
                return;

            var stackLayout = new StackLayout {Orientation = Orientation.Vertical, HorizontalContentAlignment = HorizontalAlignment.Stretch };

            for (int i = 0; i < itemNames.Length; i++)
            {
                var idx = i;

                var button = new Button { Text = itemNames[idx], Size = new Size(240, 60) }; 
                button.Click += (s, e) =>
                {
                    actions[idx]();
                    SelectedIndex = idx;
                    this.Close();
                };

                stackLayout.Items.Add(new StackLayoutItem(button, true));
            }

            Content = stackLayout;
            Size = new Size(-1, -1);
        }
コード例 #2
1
ファイル: SortingTests.cs プロジェクト: mmoroney/Algorithms
        public void SortingTest()
        {
            Action<int[]>[] actions = new Action<int[]>[]
            {
                BubbleSort.Sort,
                data => BucketSort.Sort(data, SortingTests.MaxValue),
                data => CountingSort.Sort(data, SortingTests.MaxValue),
                HeapSort.Sort,
                InsertionSort.Sort,
                MergeSort.Sort,
                QuickSort.Sort,
                data => RadixSort.Sort(data, SortingTests.MaxValue),
            };

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    int[] data = ArrayUtilities.CreateRandomArray(j, 0, SortingTests.MaxValue);
                    int[][] results = new int[actions.Length][];

                    for (int k = 0; k < actions.Length; k++)
                    {
                        results[k] = new int[data.Length];
                        Array.Copy(data, results[k], data.Length);

                        actions[k](results[k]);
                        Assert.IsTrue(ArrayUtilities.AreEqual(results[k], results[0]));
                    }
                }
            }
        }
コード例 #3
1
ファイル: SortedMerge.cs プロジェクト: mmoroney/Algorithms
        public void SortedMergeTest()
        {
            Action<int[], int[]>[] actions = new Action<int[], int[]>[]
            {
                SortedMerge.BruteForce,
                SortedMerge.SinglePass
            };

            for(int i = 0; i < 10; i++)
            {
                int[] A = ArrayUtilities.CreateRandomArray(40, 0, 20);
                int[] B = ArrayUtilities.CreateRandomArray(20, 0, 20);

                Array.Sort(A, 0, A.Length / 2);
                Array.Sort(B);

                int[][] results = new int[actions.Length][];

                for(int j = 0; j < actions.Length; j++)
                {
                    results[j] = new int[A.Length];
                    Array.Copy(A, results[j], A.Length);
                    int[] copyB = new int[B.Length];
                    Array.Copy(B, copyB, B.Length);

                    actions[j](results[j], copyB);
                    Assert.IsTrue(ArrayUtilities.AreEqual(results[0], results[j]));
                }
            }
        }
コード例 #4
1
        public void IncrementIntegerTest()
        {
            Action<List<int>>[] actions = new Action<List<int>>[]
            {
                IncrementInteger.Convert,
                IncrementInteger.SinglePass
            };

            int digits = 0;
            for (int i = 0; i <= 1000; i++)
            {
                if (i % 10 == 0)
                    digits++;

                for(int j = 0; j < actions.Length; j++)
                {
                    List<int> list = new List<int>();
                    for (int k = 0; k < digits; k++)
                        list.Insert(0, 0);

                    IncrementInteger.ToList(i, list);
                    actions[j](list);
                    Assert.AreEqual(IncrementInteger.ToInt(list), i + 1);
                }
            }
        }
コード例 #5
1
        /// <summary>
        /// Enumerates the segments in a path and calls a corresponding delegate verifier on each segment.
        /// Do not overuse this method: most test cases don't need to over-baseline what the expected segments are.
        /// </summary>
        public static void VerifyPath(ODataPath path, Action<ODataPathSegment>[] segmentVerifiers)
        {
            path.Count().Should().Be(segmentVerifiers.Count());

            var i = 0;
            foreach (var segment in path)
            {
                segmentVerifiers[i++](segment);
            }
        }
コード例 #6
1
 public EventSignal<IResponse> PostAsync(string url, Action<IRequest> prepareRequest, Dictionary<string, string> postData)
 {
     var returnSignal = new EventSignal<IResponse>();
     var signal = HttpHelper.PostAsync(url, request => prepareRequest(new HttpWebRequestWrapper(request)), postData);
     signal.Finished += (sender, e) => returnSignal.OnFinish(new HttpWebResponseWrapper(e.Result.Result) { Exception = e.Result.Exception, IsFaulted = e.Result.IsFaulted });
     return returnSignal;
 }
コード例 #7
1
        /// <summary>
        /// Adds a saved search to your twitter account
        /// </summary>
        /// <param name="query">Search query to add</param>
        /// <param name="callback">Async Callback used in Silverlight queries</param>
        /// <returns>SavedSearch object</returns>
        public static SavedSearch CreateSavedSearch(this TwitterContext ctx, string query, Action<TwitterAsyncResponse<SavedSearch>> callback)
        {
            if (string.IsNullOrEmpty(query))
            {
                throw new ArgumentException("query is required.", "query");
            }

            var savedSearchUrl = ctx.BaseUrl + "saved_searches/create.json";

            var reqProc = new SavedSearchRequestProcessor<SavedSearch>();

            ITwitterExecute exec = ctx.TwitterExecutor;
            exec.AsyncCallback = callback;
            var resultsJson =
                exec.PostToTwitter(
                    savedSearchUrl,
                    new Dictionary<string, string>
                    {
                        { "query", query }
                    },
                    response => reqProc.ProcessActionResult(response, SavedSearchAction.Create));

            SavedSearch result = reqProc.ProcessActionResult(resultsJson, SavedSearchAction.Create);
            return result;
        }
コード例 #8
1
        public override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
        {
            if (symbol.TypeKind != TypeKind.Enum)
            {
                return;
            }

            var flagsAttribute = WellKnownTypes.FlagsAttribute(compilation);
            if (flagsAttribute == null)
            {
                return;
            }

            var zeroValuedFields = GetZeroValuedFields(symbol).ToImmutableArray();

            bool hasFlagsAttribute = symbol.GetAttributes().Any(a => a.AttributeClass == flagsAttribute);
            if (hasFlagsAttribute)
            {
                CheckFlags(symbol, zeroValuedFields, addDiagnostic);
            }
            else
            {
                CheckNonFlags(symbol, zeroValuedFields, addDiagnostic);
            }
        }
コード例 #9
1
        //public async Task<string> WebMethod2()
        public void WebMethod2(Action<string> yield)
        {
            // ThreadLocal SynchronizationContext aware ConnectionPool?
            var n = new PerformanceResourceTimingData2ApplicationPerformance();

            var rid = n.Insert(
                new PerformanceResourceTimingData2ApplicationPerformanceRow
            {
                connectStart = 5,
                connectEnd = 13,

                // conversion done in AddParameter
                // .stack rewriter needs to store struct. can we create new byref struct parameters?
                //EventTime = DateTime.Now.AddDays(-0),

                // conversion done in Insert?
                z = new XElement("goo", "foo")
            }
            );

            // { LastInsertRowId = 2 }
            Console.WriteLine("after insert " + new { rid });


            var c = new PerformanceResourceTimingData2ApplicationPerformance().Count();

            Console.WriteLine(new { c, rid });

            // I/System.Console( 7320): {{ c = 18, rid = 18 }}
            //return new { c, rid }.ToString();
            yield(
                "TestAndroidInsert " + new { c, rid }.ToString()
                );

        }
コード例 #10
1
 public static void CreateTchatCommand(string name, string help, Action<string[], Bot> action)
 {
     string commandName = name.ToLowerInvariant();
     if (m_commands.Count(entry => entry.CommandName == commandName) == 1)
         throw new InvalidOperationException(String.Format("Command {0} already exists.", name));
     m_commands.Add(new TchatCommand(name, help, action));
 }
コード例 #11
1
        public static void Invoke(this Control uiElement, Action updater, bool forceSynchronous = true)
        {
            if (uiElement == null)
            {
                throw new ArgumentNullException("uiElement");
            }

            if (uiElement.InvokeRequired)
            {
                if (forceSynchronous)
                {
                    try
                    {
                        uiElement.Invoke((Action)delegate { Invoke(uiElement, updater, forceSynchronous); });
                    }
                    catch (Exception e) { }
                }
                else
                {
                    uiElement.BeginInvoke((Action)delegate { Invoke(uiElement, updater, forceSynchronous); });
                }
            }
            else
            {
                if (!uiElement.IsDisposed)
                {
                    updater();
                }
            }
        }
コード例 #12
1
ファイル: UpdateHandler.cs プロジェクト: ifzz/FDK
        public UpdateHandler(DataTrade trade, DataFeed feed, Action<SymbolInfo[], AccountInfo, Quote> updateCallback, Processor processor)
        {
            if (trade == null)
                throw new ArgumentNullException(nameof(trade));

            if (feed == null)
                throw new ArgumentNullException(nameof(feed));

            if (updateCallback == null)
                throw new ArgumentNullException(nameof(updateCallback));

            if (processor == null)
                throw new ArgumentNullException(nameof(processor));

            this.updateCallback = updateCallback;
            this.processor = processor;

            this.SyncRoot = new object();

            feed.SymbolInfo += this.OnSymbolInfo;
            feed.Tick += this.OnTick;

            trade.AccountInfo += this.OnAccountInfo;
            trade.BalanceOperation += this.OnBalanceOperation;
            trade.ExecutionReport += this.OnExecutionReport;
            trade.PositionReport += this.OnPositionReport;
        }
コード例 #13
1
ファイル: MovieImport.cs プロジェクト: henke37/BizHawk
		public static void ProcessMovieImport(string fn, Action<string> conversionErrorCallback, Action<string> messageCallback)
		{
			var d = PathManager.MakeAbsolutePath(Global.Config.PathEntries.MoviesPathFragment, null);
			string errorMsg;
			string warningMsg;
			var m = ImportFile(fn, out errorMsg, out warningMsg);

			if (!string.IsNullOrWhiteSpace(errorMsg))
			{
				conversionErrorCallback(errorMsg);
			}

			if (!string.IsNullOrWhiteSpace(warningMsg))
			{
				messageCallback(warningMsg);

			}
			else
			{
				messageCallback(Path.GetFileName(fn) + " imported as " + m.Filename);
			}

			if (!Directory.Exists(d))
			{
				Directory.CreateDirectory(d);
			}
		}
コード例 #14
1
        /// <summary>
        /// Sets the delegate to use when configuring the application's <see cref="GlobalConfiguration.Configuration"/>.
        /// </summary>
        /// <param name="configurationDelegate">The configuration delegate.</param>
        /// <returns>Current <see cref="WebApiManagerBuilder"/> instance.</returns>
        /// <remarks></remarks>
        public ApplicationConfigurationBuilder ConfigureForIIS(Action<HttpConfiguration> configurationDelegate)
        {
            _AspNetHttpConfigurationDelegate = configurationDelegate;
            Setup();

            return Builder;
        }
コード例 #15
1
        private void Configure(AzureServiceBusOwinServiceConfiguration config, Action<IAppBuilder> startup)
        {
            if (startup == null)
            {
                throw new ArgumentNullException("startup");
            }

            var options = new StartOptions();
            if (string.IsNullOrWhiteSpace(options.AppStartup))
            {
                // Populate AppStartup for use in host.AppName
                options.AppStartup = startup.Method.ReflectedType.FullName;
            }

            var testServerFactory = new AzureServiceBusOwinServerFactory(config);
            var services = ServicesFactory.Create();
            var engine = services.GetService<IHostingEngine>();
            var context = new StartContext(options)
            {
                ServerFactory = new ServerFactoryAdapter(testServerFactory),
                Startup = startup
            };
            _started = engine.Start(context);
            _next = testServerFactory.Invoke;
        }
コード例 #16
1
ファイル: VnrSplitterBuilder.cs プロジェクト: dtafe/vnr
 public static SplitterBuilder VnrSplitter(this HtmlHelper helper, SplitterBuilderInfo builderInfo)
 {
     var pane = new Action<SplitterPaneFactory>(p =>
     {
         foreach (var item in builderInfo.Panes)
         {
             if (!string.IsNullOrWhiteSpace(item.Value.Content))
             {
                 p.Add()
                     .Content(item.Value.Content)
                     .Collapsible(item.Value.Collapsible)
                     .Scrollable(item.Value.Scrollable)
                     .Size(item.Value.Size)
                     .Resizable(item.Value.Resizable);
             }
             else if (!string.IsNullOrEmpty(item.Value.Controller) || !string.IsNullOrEmpty(item.Value.ActionName))
             {
                 p.Add()
                     .LoadContentFrom(item.Value.ActionName, item.Value.Controller)
                     .Collapsible(item.Value.Collapsible)
                     .Scrollable(item.Value.Scrollable)
                     .Size(item.Value.Size)
                     .Resizable(item.Value.Resizable);
             }
         }
     });
     var splitterBuilder = helper.Kendo().Splitter()
         .Orientation(builderInfo.Orientation)
         .Name(builderInfo.Name)
         .HtmlAttributes(new {style="height:"+builderInfo.Height+"px;"})
         .Panes(pane);
     return splitterBuilder;
 }
コード例 #17
1
 //Base method - most simple implementation
 static void filestream(string filePath, Action<string> callback)
 {
     byte[] buffer = new byte[BUFFER_SIZE];
     byte[] charBuffer = new byte[MAX_TOKEN_SIZE];
     int charIndex = 0;
     int bufferSize;
     using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     {
         do
         {
             bufferSize = stream.Read(buffer, 0, BUFFER_SIZE);
             for (int i = 0; i < bufferSize; i++)
             {
                 if (scannerNoMatch(buffer[i]))
                 {
                     charBuffer[charIndex++] = buffer[i];
                 }
                 else
                 {
                     callback(ENCODING.GetString(charBuffer, 0, charIndex));
                     charIndex = 0;
                 }
             }
         } while (bufferSize != 0);
     }
 }
コード例 #18
1
        public AppUpdateControl(IEnumerable<IAppVersion> appVersions, Action<IAppVersion> updateAction)
        {
            this.NewestVersion = appVersions.First();
            InitializeComponent();

            this.AppIconImage.ImageFailed += (sender, e) => { this.AppIconImage.Source = new BitmapImage(new Uri("/Assets/windows_phone.png", UriKind.RelativeOrAbsolute)); };
            this.AppIconImage.Source = new BitmapImage(new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + NewestVersion.PublicIdentifier + ".png"));

            this.ReleaseNotesBrowser.Opacity = 0;
            this.ReleaseNotesBrowser.Navigated += (sender, e) => { (this.ReleaseNotesBrowser.Resources["fadeIn"] as Storyboard).Begin(); };
            this.ReleaseNotesBrowser.NavigateToString(WebBrowserHelper.WrapContent(NewestVersion.Notes));
            this.ReleaseNotesBrowser.Navigating += (sender, e) =>
            {
                e.Cancel = true;
                WebBrowserTask browserTask = new WebBrowserTask();
                browserTask.Uri = e.Uri;
                browserTask.Show();
            };
            this.InstallAETX.Click += (sender, e) =>
            {
                WebBrowserTask webBrowserTask = new WebBrowserTask();
                webBrowserTask.Uri = new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + NewestVersion.PublicIdentifier + ".aetx", UriKind.Absolute);
                webBrowserTask.Show();
            };
            this.InstallOverApi.Click += (sender, e) => {
                this.Overlay.Visibility = Visibility.Visible;
                updateAction.Invoke(NewestVersion); 
            };
            
        }
コード例 #19
1
ファイル: SmugglerApi.cs プロジェクト: robashton/ravendb
		public SmugglerApi(SmugglerOptions smugglerOptions, IAsyncDatabaseCommands commands, Action<string> output)
			: base(smugglerOptions)
		{
			this.commands = commands;
			this.output = output;
			batch = new List<RavenJObject>();
		}
コード例 #20
1
 /// <summary>
 /// Repeats the specified <see cref="Action"/> the number of times.
 /// </summary>
 /// <param name="input">The number of times to repeat the <see cref="Action"/>.</param>
 /// <param name="action">The <see cref="Action"/> to repeat.</param>
 public static void Times(this int input, Action action)
 {
     while (input-- > 0)
     {
         action();
     }
 }
コード例 #21
1
        /// <summary>
        ///     Add a new timer and starts measuring time.
        /// </summary>
        /// <param name="duration">When the action must be started.</param>
        /// <param name="callbackAction">Action to invoke on time.</param>
        /// <param name="removeAfterCallback">Remove timer from list after execution of callback.</param>
        /// <returns>Timer instance.</returns>
        public Timer AddTimer(double duration, Action callbackAction, bool removeAfterCallback = false)
        {
            var timer = new Timer(duration, callbackAction, removeAfterCallback) {Running = true};
            timers.Add(timer);

            return timer;
        }
コード例 #22
0
        public MyCubeGridSystems(MyCubeGrid grid)
        {
            m_cubeGrid = grid;

            m_terminalSystem_GroupAdded = TerminalSystem_GroupAdded;
            m_terminalSystem_GroupRemoved = TerminalSystem_GroupRemoved;

            GyroSystem = new MyGridGyroSystem(m_cubeGrid);
            WeaponSystem = new MyGridWeaponSystem();
            ReflectorLightSystem = new MyGridReflectorLightSystem(m_cubeGrid);
            if (MyFakes.ENABLE_WHEEL_CONTROLS_IN_COCKPIT)
            {
                WheelSystem = new MyGridWheelSystem(m_cubeGrid);
            }
            ConveyorSystem = new MyGridConveyorSystem(m_cubeGrid);
            LandingSystem = new MyGridLandingSystem();
            ControlSystem = new MyGroupControlSystem();
            CameraSystem = new MyGridCameraSystem(m_cubeGrid);

            if (MySession.Static.Settings.EnableOxygen)
            {
                GasSystem = new MyGridGasSystem(m_cubeGrid);
            }
            if (MyPerGameSettings.EnableJumpDrive)
            {
                JumpSystem = new MyGridJumpDriveSystem(m_cubeGrid);
            }
            if (MyPerGameSettings.EnableShipSoundSystem && (MyFakes.ENABLE_NEW_SMALL_SHIP_SOUNDS || MyFakes.ENABLE_NEW_LARGE_SHIP_SOUNDS) && MySandboxGame.IsDedicated == false)
            {
                ShipSoundComponent = new MyShipSoundComponent();
            }

            m_blocksRegistered = true;
        }
コード例 #23
0
        public void BackupDataBase(string destinationPath, Action<int> percentCompleteCallback, Action completeCallback)
        {
            var server = GetDbServer();

            var backup = new Backup();
            backup.Action = BackupActionType.Database;
            backup.Database = this.DatabaseName;
            backup.Devices.Add(new BackupDeviceItem(GetFileName(destinationPath, this.DatabaseName, ".bak"), DeviceType.File));
            backup.Initialize = true;
            backup.Checksum = true;
            backup.ContinueAfterError = true;
            backup.Incremental = false;
            backup.PercentCompleteNotification = 1;
            backup.LogTruncation = BackupTruncateLogType.Truncate;

            backup.Complete += (s, e) =>
            {
                if (completeCallback != null)
                {
                    completeCallback();
                }
            };

            backup.PercentComplete += (s, e) =>
            {
                if (percentCompleteCallback != null)
                {
                    percentCompleteCallback(e.Percent);
                }
            };

            backup.SqlBackupAsync(server);
        }
コード例 #24
0
ファイル: TestUtils.cs プロジェクト: soywiz/SafeILGenerator
 public static String CaptureOutput(Action Action, bool Capture = true)
 {
     if (Capture)
     {
         var OldOut = Console.Out;
         var StringWriter = new StringWriter();
         try
         {
             Console.SetOut(StringWriter);
             Action();
         }
         finally
         {
             Console.SetOut(OldOut);
         }
         try
         {
             return StringWriter.ToString();
         }
         catch
         {
             return "";
         }
     }
     else
     {
         Action();
         return "";
     }
 }
コード例 #25
0
 //This method improves upon the naive method (stringBuffer) as ENCODING.GetString
 //allocates a new character array with every invocation, and this method bypasses
 //this by reusing the same char array.  Surprisingly in tests, this method held
 //no improvement.
 static void filestream2(string filePath, Action<string> callback)
 {
     byte[] buffer = new byte[BUFFER_SIZE];
     byte[] charBuffer = new byte[MAX_TOKEN_SIZE];
     char[] encoderBuffer = new char[ENCODING.GetMaxCharCount(MAX_TOKEN_SIZE)];
     int charIndex = 0;
     int bufferSize, encodedChars;
     using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     {
         do
         {
             bufferSize = stream.Read(buffer, 0, BUFFER_SIZE);
             for (int i = 0; i < bufferSize; i++)
             {
                 if (scannerNoMatch(buffer[i]))
                 {
                     charBuffer[charIndex++] = buffer[i];
                 }
                 else
                 {
                     encodedChars = ENCODING.GetChars(charBuffer, 0, charIndex, encoderBuffer, 0);
                     callback(new string(encoderBuffer, 0, encodedChars));
                     charIndex = 0;
                 }
             }
         } while (bufferSize != 0);
     }
 }
コード例 #26
0
ファイル: PlainSocket.cs プロジェクト: toptensoftware/manos
        public override void Connect(string host, int port, Action callback)
        {
            if (state != Socket.SocketState.Invalid)
                throw new InvalidOperationException ("Socket already in use");

            int error;
            var fd = manos_socket_connect (host, port, out error);

            if (fd < 0)
                throw new Exception (String.Format ("An error occurred while trying to connect to {0}:{1} errno: {2}", host, port, error));

            stream = new PlainSocketStream (this, new IntPtr (fd));

            var connectWatcher = new IOWatcher (new IntPtr (fd), EventTypes.Write, Context.Loop, (watcher, revents) => {
                watcher.Stop ();
                watcher.Dispose ();

                this.address = host;
                this.port = port;

                this.state = Socket.SocketState.Open;

                callback ();
            });
            connectWatcher.Start ();
        }
コード例 #27
0
 /// <inheritdoc/>
 public override void Init(NLite.Mini.Activation.IActivator activator, IKernel kernel, IComponentInfo info, Action<IComponentInfo, object> onDestroying, Action<IComponentContext> onFetch)
 {
     Guard.NotNull(activator, "activator");
     Guard.NotNull(kernel, "kernel");
     Guard.NotNull(info, "info");
     Real.Init(new ProxyActivator(activator), kernel, info, onDestroying,OnFetch);
 }
コード例 #28
0
        public void GetData(Action<DataItem, Exception> callback)
        {
            // Use this to create design time data

            var item = new DataItem("Welcome to MVVM Light [design]");
            callback(item, null);
        }
コード例 #29
0
ファイル: RelayCommand.cs プロジェクト: mkrzem/AlarmWP
 /// <summary>
 /// Creates a new command.
 /// </summary>
 /// <param name="execute">The execution logic.</param>
 /// <param name="canExecute">The execution status logic.</param>
 public RelayCommand(Action<object> execute, Func<bool> canExecute)
 {
     if (execute == null)
         throw new ArgumentNullException("execute");
     _execute = execute;
     _canExecute = canExecute;
 }
コード例 #30
0
        public void StartMoving(System.Action callback)
        {
            if (OnMovementStart != null) OnMovementStart(this);

            Triggers.ResolveTriggers(TriggerTypes.OnShipMovementStart, callback);
        }
コード例 #31
0
        /// <summary>
        /// Begins logging exchanges - writes errors to console. You should block the app using Console.ReadLine.
        /// </summary>
        /// <param name="path">Path to write files to</param>
        /// <param name="intervalSeconds">Interval in seconds in between each log calls for each exchange</param>
        /// <param name="terminateAction">Call this when the process is about to exit, like a WM_CLOSE message on Windows.</param>
        /// <param name="compress">Whether to compress the log files</param>
        /// <param name="exchangeNamesAndSymbols">Exchange names and symbols to log</param>
        public static void LogExchanges(string path, float intervalSeconds, out System.Action terminateAction, bool compress, params string[] exchangeNamesAndSymbols)
        {
            bool terminating = false;

            System.Action terminator = null;
            path = (string.IsNullOrWhiteSpace(path) ? "./" : path);
            Dictionary <ExchangeLogger, int> errors  = new Dictionary <ExchangeLogger, int>();
            List <ExchangeLogger>            loggers = new List <ExchangeLogger>();

            for (int i = 0; i < exchangeNamesAndSymbols.Length;)
            {
                loggers.Add(new ExchangeLogger(ExchangeAPI.GetExchangeAPI(exchangeNamesAndSymbols[i++]), exchangeNamesAndSymbols[i++], intervalSeconds, path, compress));
            }
            ;
            StreamWriter errorLog = File.CreateText(Path.Combine(path, "errors.txt"));

            foreach (ExchangeLogger logger in loggers)
            {
                logger.Start();
                logger.Error += (log, ex) =>
                {
                    int errorCount;
                    lock (errors)
                    {
                        if (!errors.TryGetValue(log, out errorCount))
                        {
                            errorCount = 0;
                        }
                        errors[log] = ++errorCount;
                    }
                    Console.WriteLine("Errors for {0}: {1}", log.API.Name, errorCount);
                    errorLog.WriteLine("Errors for {0}: {1}", log.API.Name, errorCount);
                };
            }
            terminator = () =>
            {
                if (!terminating)
                {
                    terminating = true;
                    foreach (ExchangeLogger logger in loggers.ToArray())
                    {
                        logger.Stop();
                        logger.Dispose();
                    }
                    loggers.Clear();
                    errorLog.Close();
                }
            };
            terminateAction = terminator;

            // make sure to close properly
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                terminator();
            };
            AppDomain.CurrentDomain.ProcessExit += (object sender, EventArgs e) =>
            {
                terminator();
            };

            Console.WriteLine("Loggers \"{0}\" started, press ENTER or CTRL-C to terminate.", string.Join(", ", loggers.Select(l => l.API.Name)));
            errorLog.WriteLine("Loggers \"{0}\" started, press ENTER or CTRL-C to terminate.", string.Join(", ", loggers.Select(l => l.API.Name)));
        }
コード例 #32
0
 /// <summary>
 /// Called by the response menu. Starts the timer. Each tick, the UpdateTimeLeft
 /// method is called.
 /// </summary>
 /// <param name="duration">Duration in seconds.</param>
 /// <param name="timeoutHandler">Handler to invoke if the timer reaches zero.</param>
 public virtual void StartCountdown(float duration, System.Action timeoutHandler)
 {
     StartCoroutine(Countdown(duration, timeoutHandler));
 }
コード例 #33
0
 public RepeatButton(System.Action clickEvent, long delay, long interval)
     : this()
 {
     SetAction(clickEvent, delay, interval);
 }
コード例 #34
0
ファイル: TestWeakRef.cs プロジェクト: zhxhxlzt/UnityPublic
 public void AddFuncWeakRef(System.Action func)
 {
     m_FuncWeakRef = new WeakReference <System.Action>(func);
 }
コード例 #35
0
 public QMToggleButton(QMNestedButton btnMenu, int btnXLocation, int btnYLocation, String btnTextOn, System.Action btnActionOn, String btnTextOff, System.Action btnActionOff, String btnToolTip, Color?btnBackgroundColor = null, Color?btnTextColor = null, bool shouldSaveInConfig = false, bool defaultPosition = false)
 {
     btnQMLoc = btnMenu.getMenuName();
     initButton(btnXLocation, btnYLocation, btnTextOn, btnActionOn, btnTextOff, btnActionOff, btnToolTip, btnBackgroundColor, btnTextColor, shouldSaveInConfig, defaultPosition);
 }
コード例 #36
0
 public QMSingleButton(string btnMenu, int btnXLocation, int btnYLocation, String btnText, System.Action btnAction, String btnToolTip, Color?btnBackgroundColor = null, Color?btnTextColor = null)
 {
     btnQMLoc = btnMenu;
     initButton(btnXLocation, btnYLocation, btnText, btnAction, btnToolTip, btnBackgroundColor, btnTextColor);
 }
コード例 #37
0
 // Call until false is returned
 public abstract IEnumerator Perform(System.Action onFinish, System.Action <int> oneInTwentyStep);
コード例 #38
0
   /// <summary>
   /// Displays a modal dialog in Editor
   /// </summary>
   /// <param name="title"></param>
   /// <param name="message"></param>
   /// <param name="ok"></param>
   /// <param name="cancel"></param>
   /// <param name="onOk"></param>
   public static void Dialog(string title, string message, string ok, string cancel, System.Action onOk = null)
   {
 #if UNITY_EDITOR
       if (UnityEditor.EditorUtility.DisplayDialog(title, message, ok, cancel))
       {
           onOk?.Invoke();
       }
 #endif
   }
コード例 #39
0
 //share screenshoot
 public void ShareScreenShot(string caption, System.Action onComplete = null, System.Action onFail = null)
 {
     onShareScreenshotComplete = onComplete;
     onShareScreenshotFail     = onFail;
     StartCoroutine(TakeScreenshotAndShare(caption));
 }
コード例 #40
0
        internal static void SearchReplace(string findPattern, string replacePattern, Scope scope, FilterOptions options, System.Action UpdateStopButton, System.Action <SearchResultPad> UpdateResultPad)
        {
            if (find != null && find.IsRunning)
            {
                if (!MessageService.Confirm(GettextCatalog.GetString("There is a search already in progress. Do you want to stop it?"), AlertButton.Stop))
                {
                    return;
                }
            }
            searchTokenSource.Cancel();

            if (scope == null)
            {
                return;
            }

            find = new FindReplace();

            string pattern = findPattern;

            if (String.IsNullOrEmpty(pattern))
            {
                return;
            }
            if (!find.ValidatePattern(options, pattern))
            {
                MessageService.ShowError(GettextCatalog.GetString("Search pattern is invalid"));
                return;
            }

            if (replacePattern != null && !find.ValidatePattern(options, replacePattern))
            {
                MessageService.ShowError(GettextCatalog.GetString("Replace pattern is invalid"));
                return;
            }
            var cancelSource = new CancellationTokenSource();

            searchTokenSource = cancelSource;
            var token = cancelSource.Token;

            currentTask = Task.Run(delegate {
                using (SearchProgressMonitor searchMonitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true)) {
                    searchMonitor.PathMode = scope.PathMode;

                    if (UpdateResultPad != null)
                    {
                        Application.Invoke((o, args) => {
                            UpdateResultPad(searchMonitor.ResultPad);
                        });
                    }

                    searchMonitor.ReportStatus(scope.GetDescription(options, pattern, null));
                    if (UpdateStopButton != null)
                    {
                        Application.Invoke((o, args) => {
                            UpdateStopButton();
                        });
                    }

                    DateTime timer      = DateTime.Now;
                    string errorMessage = null;

                    try {
                        var results = new List <SearchResult> ();
                        foreach (SearchResult result in find.FindAll(scope, searchMonitor, pattern, replacePattern, options, token))
                        {
                            if (token.IsCancellationRequested)
                            {
                                return;
                            }
                            results.Add(result);
                        }
                        searchMonitor.ReportResults(results);
                    } catch (Exception ex) {
                        errorMessage = ex.Message;
                        LoggingService.LogError("Error while search", ex);
                    }

                    string message = null;
                    if (errorMessage != null)
                    {
                        message = GettextCatalog.GetString("The search could not be finished: {0}", errorMessage);
                        searchMonitor.ReportError(message, null);
                    }
                    else if (!searchMonitor.CancellationToken.IsCancellationRequested)
                    {
                        string matches = string.Format(GettextCatalog.GetPluralString("{0} match found", "{0} matches found", find.FoundMatchesCount), find.FoundMatchesCount);
                        string files   = string.Format(GettextCatalog.GetPluralString("in {0} file.", "in {0} files.", find.SearchedFilesCount), find.SearchedFilesCount);
                        message        = GettextCatalog.GetString("Search completed.") + Environment.NewLine + matches + " " + files;
                        searchMonitor.ReportSuccess(message);
                    }
                    if (message != null)
                    {
                        searchMonitor.ReportStatus(message);
                    }
                    searchMonitor.Log.WriteLine(GettextCatalog.GetString("Search time: {0} seconds."), (DateTime.Now - timer).TotalSeconds);
                }
                if (UpdateStopButton != null)
                {
                    Application.Invoke((o, args) => {
                        UpdateStopButton();
                    });
                }
            });
        }
コード例 #41
0
ファイル: LuaCsTransfer.cs プロジェクト: mengtest/HjqstSource
        public static GameObject OpenConfirmBuyShopItemTipsView(string itemName, int costResTypeValue, int costResID, int costResCount, System.Action onClickBuyButtonHandler, int consumeTipTypeValue)
        {
            GameResData costGameResData = new GameResData();

            costGameResData.type  = (BaseResType)costResTypeValue;
            costGameResData.id    = costResID;
            costGameResData.count = costResCount;
            ConsumeTipType consumeTipType = (ConsumeTipType)consumeTipTypeValue;

            return(Logic.UI.Tips.View.ConfirmBuyShopItemTipsView.Open(itemName, costGameResData, onClickBuyButtonHandler, consumeTipType).gameObject);
        }
コード例 #42
0
 public void SetAction(System.Action clickEvent, long delay, long interval)
 {
     this.RemoveManipulator(m_Clickable);
     m_Clickable = new PointerClickable(clickEvent, delay, interval);
     this.AddManipulator(m_Clickable);
 }
コード例 #43
0
 void ICommandHandler <TypeCharCommandArgs> .ExecuteCommand(TypeCharCommandArgs args, System.Action nextHandler)
 {
     AssertIsForeground();
     ExecuteCommandWorker(args, nextHandler);
 }
コード例 #44
0
ファイル: ProfileHelper.cs プロジェクト: towner-10/2d-rpg
 public void Run(System.Action action)
 {
     Start();
     action();
     Stop();
 }
コード例 #45
0
 /// <summary>
 ///   Executes the action on the UI thread asynchronously.
 /// </summary>
 /// <param name="action">The action to execute.</param>
 public virtual void BeginOnUIThread(System.Action action)
 {
     Application.SynchronizationContext.Post(s => action(), null);
 }
コード例 #46
0
 /// <inheritdoc />
 public virtual void OnUIThread(System.Action action) => platformProvider.OnUIThread(action);
コード例 #47
0
        /// <summary>
        /// Populates the sources with resource clip, non-thread blocking.
        /// </summary>
        /// <param name="clipName">Clip name.</param>
        /// <param name="variation">Variation.</param>
        /// <param name="successAction">Method to execute if successful.</param>
        /// <param name="failureAction">Method to execute if not successful.</param>
        public static IEnumerator PopulateSourcesWithResourceClipAsync(string clipName, SoundGroupVariation variation,
                                                                       // ReSharper disable RedundantNameQualifier
                                                                       System.Action successAction, System.Action failureAction)
        {
            // ReSharper restore RedundantNameQualifier
            if (AudioClipsByName.ContainsKey(clipName))
            {
                if (successAction != null)
                {
                    successAction();
                }

                yield break;
            }

            var asyncRes = Resources.LoadAsync(clipName, typeof(AudioClip));

            while (!asyncRes.isDone)
            {
                yield return(MasterAudio.EndOfFrameDelay);
            }

            var resAudioClip = asyncRes.asset as AudioClip;

            if (resAudioClip == null)
            {
                MasterAudio.LogError("Resource file '" + clipName + "' could not be located.");

                if (failureAction != null)
                {
                    failureAction();
                }
                yield break;
            }

            if (!AudioResourceTargetsByName.ContainsKey(clipName))
            {
                MasterAudio.LogError("No Audio Sources found to add Resource file '" + clipName + "'.");

                if (failureAction != null)
                {
                    failureAction();
                }
                yield break;
            }

            var sources = AudioResourceTargetsByName[clipName];

            // ReSharper disable once ForCanBeConvertedToForeach
            for (var i = 0; i < sources.Count; i++)
            {
                sources[i].clip = resAudioClip;
            }

            if (!AudioClipsByName.ContainsKey(clipName))
            {
                AudioClipsByName.Add(clipName, resAudioClip);
            }

            if (successAction != null)
            {
                successAction();
            }
        }
コード例 #48
0
 private void InitializeHandlers()
 {
     System.Action valueChanged = () => IsModified = true;
     txtKana.TextChanged += (sender, e) => valueChanged();
     txtExcludeCategoryCode.TextChanged += (sender, e) => valueChanged();
 }
コード例 #49
0
        public static void social_btn(Color bordger, float xpos, float ypos, string txt, System.Action listener, Transform parent)
        {
            var BtnObj = GameObject.Find("UserInterface/MenuContent/Screens/UserInfo/User Panel/Moderator/Actions/Warn").gameObject;
            var Btn    = UnityEngine.Object.Instantiate(BtnObj, parent.transform, false).GetComponent <Button>();

            Btn.transform.localPosition = new Vector3(parent.transform.localPosition.x - 2000 + xpos, parent.transform.localPosition.y - ypos, parent.transform.localPosition.z);
            Btn.GetComponentInChildren <Text>().text = txt;
            Btn.onClick = new Button.ButtonClickedEvent();
            Btn.enabled = true; Btn.gameObject.SetActive(true);
            Btn.GetComponentInChildren <Image>().color    = bordger;
            Btn.GetComponent <RectTransform>().sizeDelta += new Vector2(0, 0);
            Btn.GetComponent <RectTransform>().sizeDelta -= new Vector2(3, 10);
            Btn.onClick.AddListener(listener);
            Btn.transform.SetParent(parent);
        }
コード例 #50
0
        /// <summary>
        /// Populates the sources with audio hosted on internet, non-thread blocking.
        /// </summary>
        /// <param name="fileUrl">URL of internet audio file.</param>
        /// <param name="variation">Variation.</param>
        /// <param name="successAction">Method to execute if successful.</param>
        /// <param name="failureAction">Method to execute if not successful.</param>
        // ReSharper disable RedundantNameQualifier
        public static IEnumerator PopulateSourceWithInternetFile(string fileUrl, SoundGroupVariation variation, System.Action successAction, System.Action failureAction)
        {
            // ReSharper restore RedundantNameQualifier
            if (AudioClipsByName.ContainsKey(fileUrl))
            {
                if (successAction != null)
                {
                    successAction();
                }

                yield break;
            }

            if (InternetFilesStartedLoading.Contains(fileUrl))   // don't download the same file multiple times.
            {
                yield break;
            }

            InternetFilesStartedLoading.Add(fileUrl);

            AudioClip internetClip;

            using (var fileRequest = new WWW(fileUrl)) {
                yield return(fileRequest);

                if (fileRequest.error != null)
                {
                    if (string.IsNullOrEmpty(fileUrl))
                    {
                        MasterAudio.LogWarning("Internet file is EMPTY for a Variation of Sound Group '" + variation.ParentGroup.name + "' could not be loaded.");
                    }
                    else
                    {
                        MasterAudio.LogWarning("Internet file '" + fileUrl + "' in a Variation of Sound Group '" + variation.ParentGroup.name + "' could not be loaded. This can happen if the URL is incorrect or you are not online.");
                    }
                    if (failureAction != null)
                    {
                        failureAction();
                    }
                    yield break;
                }

                internetClip = fileRequest.audioClip;
            }

            if (!AudioResourceTargetsByName.ContainsKey(fileUrl))
            {
                MasterAudio.LogError("No Audio Sources found to add Internet File '" + fileUrl + "' to.");

                if (failureAction != null)
                {
                    failureAction();
                }
                yield break;
            }

            var sources = AudioResourceTargetsByName[fileUrl];

            // ReSharper disable once ForCanBeConvertedToForeach
            for (var i = 0; i < sources.Count; i++)
            {
                sources[i].clip = internetClip;
                var aVar = sources[i].GetComponent <SoundGroupVariation>();

                if (aVar == null)
                {
                    continue;
                }

                aVar.internetFileLoadStatus = MasterAudio.InternetFileLoadStatus.Loaded;
            }

            if (!AudioClipsByName.ContainsKey(fileUrl))
            {
                AudioClipsByName.Add(fileUrl, internetClip);
            }

            if (successAction != null)
            {
                successAction();
            }
        }
コード例 #51
0
 void Push_System_Action(IntPtr L, System.Action o)
 {
     ToLua.Push(L, o);
 }
コード例 #52
0
 public override void ActionEffect(System.Action callBack)
 {
     Combat.CurrentDiceRoll.Change(DieSide.Blank, DieSide.Focus, 3);
     callBack();
 }
コード例 #53
0
    public void ShareLink(string link = "", string title = "", string description = "", string linkImage = "", System.Action onComplete = null, System.Action onFail = null)
    {
        onShareLinkComplete = onComplete;
        onShareLinkFail     = onFail;

        if (link == "")
        {
            //link = Master.instance.linkInMarket;
            link = linkAppInvite;
        }

        if (title == "")
        {
            title = titleShareLink;
        }

        if (linkImage == "")
        {
            linkImage = linkImageShare;
        }

        if (description == "")
        {
            description = descriptionShareLink;
        }
        Debug.Log("ShareFacebook: Title: " + title + "| Des: " + description + " | Link: " + link + " | AppID: " + FB.AppId);
        FB.ShareLink(
            new Uri(link),
            title,
            description,
            new Uri(linkImage),
            callback: ShareLinkCallback
            );
    }
コード例 #54
0
        public static void TakeLock(DirectoryReference LockDirectory, TimeSpan Timeout, System.Action Callback)
        {
            string LockFilePath = Path.Combine(LockDirectory.FullName, ".lock");

            FileStream Stream    = null;
            DateTime   StartTime = DateTime.Now;
            DateTime   Deadline  = StartTime.Add(Timeout);

            try
            {
                DirectoryReference.CreateDirectory(LockDirectory);

                for (int Iterations = 0; ; ++Iterations)
                {
                    // Attempt to create the lock file. Ignore any IO exceptions. Stream will be null if this fails.
                    try { Stream = new FileStream(LockFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, FileOptions.DeleteOnClose); }
                    catch (IOException) { }

                    if (Stream != null)
                    {
                        // If we have a stream, we've taken the lock.
                        try
                        {
                            // Write the machine name to the file.
                            Stream.Write(Encoding.UTF8.GetBytes(Environment.MachineName));
                            Stream.Flush();
                            break;
                        }
                        catch
                        {
                            throw new AutomationException("Failed to write to the lock file '{0}'.", LockFilePath);
                        }
                    }

                    // We've failed to take the lock. Throw an exception if the timeout has elapsed.
                    // Otherwise print a log message and retry.
                    var CurrentTime = DateTime.Now;
                    if (CurrentTime >= Deadline)
                    {
                        throw new AutomationException("Couldn't create lock file '{0}' after {1} seconds.", LockFilePath, CurrentTime.Subtract(StartTime).TotalSeconds);
                    }

                    if (Iterations == 0)
                    {
                        CommandUtils.Log("Waiting for lock file '{0}' to be removed...", LockFilePath);
                    }
                    else if ((Iterations % 30) == 0)
                    {
                        CommandUtils.Log("Still waiting for lock file '{0}' after {1} seconds.", LockFilePath, CurrentTime.Subtract(StartTime).TotalSeconds);
                    }

                    // Wait for a while before retrying.
                    Thread.Sleep(1000);
                }

                // Invoke the user callback now that we own the lock.
                Callback();
            }
            finally
            {
                // Always dispose the lock file stream if we took the lock.
                // The file will delete on close.
                if (Stream != null)
                {
                    Stream.Dispose();
                    Stream = null;
                }
            }
        }
コード例 #55
0
        // TRIGGERS

        public void CallManeuverIsReadyToBeRevealed(System.Action callBack)
        {
            if (OnManeuverIsReadyToBeRevealed != null) OnManeuverIsReadyToBeRevealed(this);

            Triggers.ResolveTriggers (TriggerTypes.OnManeuverIsReadyToBeRevealed, callBack);
        }
コード例 #56
0
 public DisposableAction(System.Action disposeAction)
 {
     _disposeAction = disposeAction;
 }
コード例 #57
0
ファイル: LuaCsTransfer.cs プロジェクト: mengtest/HjqstSource
 public static GameObject OpenCommonExpandBagTipsView(int bagTypeValue, int cost, System.Action confirmAction, int ConsumeTipTypeValue)
 {
     return(Logic.UI.Tips.View.CommonExpandBagTipsView.Open(bagTypeValue, cost, confirmAction, ConsumeTipTypeValue).gameObject);
 }
コード例 #58
0
ファイル: UIUtils.cs プロジェクト: AndreasGoettig/cmn6302
        public static void DragAndDropArea(Rect area, Action <UnityEngine.Object> onObjectDragged, System.Action onDragPerformed)
        {
            Event evt = Event.current;

            UnityEngine.Object[] objects = new UnityEngine.Object[0];
            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (!area.Contains(evt.mousePosition))
                {
                    return;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                if (evt.type == EventType.DragPerform)
                {
                    objects = DragAndDrop.objectReferences;
                    for (int i = 0; i < objects.Length; i++)
                    {
                        if (PrefabUtility.GetPrefabAssetType(objects[i]) != PrefabAssetType.NotAPrefab)
                        {
                            onObjectDragged(objects[i]);
                        }
                    }
                    onDragPerformed();
                    DragAndDrop.AcceptDrag();
                }
                break;
            }
        }
コード例 #59
0
        /// <summary>
        /// Emitted at the end of a GraphNode movement.
        /// </summary>
        /// <returns>Unsubscribe callback</returns>
        public static VoidFunc OnEndNodeMove(this GraphEdit edit, VoidFunc action)
        {
            var callback = edit.Subscribe(EndNodeMoveSignal, action);

            return(() => edit.Unsubscribe(EndNodeMoveSignal, callback));
        }
コード例 #60
-1
 public static PushStreamContent Create(string fileName, ITracer tracer, Action<ZipArchive> onZip)
 {
     var content = new PushStreamContent((outputStream, httpContent, transportContext) =>
     {
         using (tracer.Step("ZipStreamContent.OnZip"))
         {
             try
             {
                 using (var zip = new ZipArchive(new StreamWrapper(outputStream), ZipArchiveMode.Create, leaveOpen: false))
                 {
                     onZip(zip);
                 }
             }
             catch (Exception ex)
             {
                 tracer.TraceError(ex);
                 throw;
             }
         }
     });
     content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
     content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
     content.Headers.ContentDisposition.FileName = fileName;
     return content;
 }