コード例 #1
0
		/// <summary>
		///   Initializes a new instance.
		/// </summary>
		/// <param name="createModel">Creates the model that should be checked.</param>
		/// <param name="output">The callback that should be used to output messages.</param>
		/// <param name="configuration">The analysis configuration that should be used.</param>
		internal ModelTraverser(Func<AnalysisModel> createModel, Action<string> output, AnalysisConfiguration configuration)
		{
			Requires.NotNull(createModel, nameof(createModel));
			Requires.NotNull(output, nameof(output));
			TransitionCollection.ValidateTransitionSizes();

			var tasks = new Task[configuration.CpuCount];
			var stacks = new StateStack[configuration.CpuCount];

			_loadBalancer = new LoadBalancer(stacks);
			Context = new TraversalContext(_loadBalancer, configuration, output);
			_workers = new Worker[configuration.CpuCount];

			for (var i = 0; i < configuration.CpuCount; ++i)
			{
				var index = i;
				tasks[i] = Task.Factory.StartNew(() =>
				{
					stacks[index] = new StateStack(configuration.StackCapacity);
					_workers[index] = new Worker(index, Context, stacks[index], createModel());
				});
			}

			Task.WaitAll(tasks);

			_states = new StateStorage(_workers[0].Model.StateVectorSize, configuration.StateCapacity);
			Context.States = _states;
		}
コード例 #2
0
ファイル: thread.cs プロジェクト: ahorn/z3test
    public void Run()
    {
        const int num_workers = 4;
        Worker[] workers = new Worker[num_workers];
        Thread[] threads = new Thread[num_workers];

        for (int i = 0; i < num_workers; i++)
        {
            workers[i] = new Worker(i, 50);
            threads[i] = new Thread(workers[i].Run);
            threads[i].Start();
        }

        foreach (Thread t in threads)
            t.Join();

        foreach (Worker w in workers)
        {
            foreach (Expr e in w.result)
                Console.Write(" " + e);
            Console.WriteLine();
        }

        Console.WriteLine("done");
    }
コード例 #3
0
ファイル: ThreadStartStop.cs プロジェクト: jetlive/skiaming
    static void Main()
    {
        // 创建线程对象。这不会启动该线程。
        Worker workerObject = new Worker();
        Thread workerThread = new Thread(workerObject.DoWork);

        // 启动辅助线程。
        workerThread.Start();
        Console.WriteLine("main thread: Starting worker thread...");

        // 循环直至辅助线程激活。
        while (!workerThread.IsAlive);

        // 为主线程设置 1 毫秒的休眠,
        // 以使辅助线程完成某项工作。
        Thread.Sleep(1);

        // 请求辅助线程自行停止:
        workerObject.RequestStop();

        // 使用 Join 方法阻塞当前线程,
        // 直至对象的线程终止。
        workerThread.Join();
        Console.WriteLine("main thread: Worker thread has terminated.");
    }
コード例 #4
0
        public void ConvertWorkerViewModel_WhenValidViewModel_ReturnEntity()
        {
            var adrConv = new AddressConverter();
            var compConv = new CompetenceConverter();
            var converter = new WorkerConverter(adrConv,compConv,new ImageConverter());

            var viewModel = new WorkerViewModel
            {
                FirstName = "Filip",
                LastName = "Skurniak",
                Pesel = "632964328947",
                RelianceRating = 10,
                WorkerCompetences = new List<CompetenceViewModel>()
                {
                    new CompetenceViewModel
                    {
                        Id = 100
                    }
                }
            };
            var entity = new Worker();

            converter.ConvertViewModelToEntity(viewModel, entity);

            Assert.AreEqual(entity.FirstName, viewModel.FirstName);
        }
コード例 #5
0
ファイル: Backend.cs プロジェクト: atorres757/resque-sharp
 public Backend(Exception exception, Worker worker, String queue, Object payload)
 {
     this.exception = exception;
     this.worker = worker;
     this.queue = queue;
     this.payload = payload;
 }
コード例 #6
0
ファイル: Task.cs プロジェクト: Lukaszpg/PP___PW_2015
  public static int Main ()
  {
    Console.WriteLine ("Input file: ");
    string filename = Console.ReadLine ();
    int[] input;

    using (StreamReader sr = new StreamReader (filename)) {
      int noElements = Int32.Parse (sr.ReadLine ());
      input = new int[noElements];
      for (int i = 0; i < noElements; i++) {
        input [i] = Int32.Parse (sr.ReadLine ());
      }
    }

    Worker[] workers = new Worker[10];

    Thread[] threads;

    // Start the thread
    //threadx.Start ();

    // Waiting for thread to become alive
    //while (!threadx.IsAlive);

    // In miliseconds
    Thread.Sleep (1);

    // Stop threadx
    //threadx.Abort ();

    //threadx.Join ();
    return 0;
  }
コード例 #7
0
ファイル: Backend.cs プロジェクト: atorres757/csharp-resque
 protected Backend(Object payload, Exception exception, Worker worker, String queue)
 {
     Exception = exception;
     Worker = worker;
     Queue = queue;
     Payload = payload;
 }
コード例 #8
0
ファイル: MouseUp.cs プロジェクト: pbalint/Playground
        public override void Invoke(Worker.State state)
        {
            INPUT[] queue = new INPUT[1];
            queue[0] = new INPUT();

            queue[0].type = InputType.Mouse;

            switch (button)
            {
                case MouseButtons.Left:
                    queue[0].u.Mouse.Flags |= MouseFlag.LeftUp;
                    break;
                case MouseButtons.Right:
                    queue[0].u.Mouse.Flags |= MouseFlag.RightUp;
                    break;
                case MouseButtons.Middle:
                    queue[0].u.Mouse.Flags |= MouseFlag.MiddleUp;
                    break;
                case MouseButtons.XButton1:
                    queue[0].u.Mouse.Flags |= MouseFlag.XUp;
                    queue[0].u.Mouse.MouseData |= (ushort)XButton.XButton1;
                    break;
                case MouseButtons.XButton2:
                    queue[0].u.Mouse.Flags |= MouseFlag.XUp;
                    queue[0].u.Mouse.MouseData |= (ushort)XButton.XButton2;
                    break;
            }
            NativeMethods.SendInput(1, queue, Marshal.SizeOf(typeof(INPUT)));
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: gsimoes/resque-sharp
 static void Main(string[] args)
 {
     using (var worker = new Worker("localhost", "console", "failing"))
     {
         worker.Work();
     }
 }
コード例 #10
0
ファイル: MainServer.cs プロジェクト: wlsgur0726/NAT_Test
        public MainServer(IPEndPoint a_bindAddr_tcp1,
						  IPEndPoint a_bindAddr_tcp2,
						  IPEndPoint a_subServer_tcp,
						  IPEndPoint a_bindAddr_udp1,
						  IPEndPoint a_bindAddr_udp2,
						  IPEndPoint a_subServer_udp)
        {
            bool nullArg = a_bindAddr_tcp1 == null
                        || a_bindAddr_tcp2 == null
                        || a_subServer_tcp == null
                        || a_bindAddr_udp1 == null
                        || a_bindAddr_udp2 == null
                        || a_subServer_udp == null;
            if (nullArg)
                throw new ArgumentNullException();

            m_firstTcp = new Worker(ProtocolType.Tcp, a_bindAddr_tcp1, FirstWorkerRoutine);
            m_firstUdp = new Worker(ProtocolType.Udp, a_bindAddr_udp1, FirstWorkerRoutine);

            m_secondTcp = new Worker(ProtocolType.Tcp, a_bindAddr_tcp2, SecondWorkerRoutine);
            m_secondUdp = new Worker(ProtocolType.Udp, a_bindAddr_udp2, SecondWorkerRoutine);

            m_subServerAddr_tcp = a_subServer_tcp;
            m_subServerAddr_udp = a_subServer_udp;

            m_subServerTcp = new Worker(ProtocolType.Tcp, null, HeartbeatRoutine);
            m_subServerUdp = new Worker(ProtocolType.Udp, null, HeartbeatRoutine);
        }
コード例 #11
0
ファイル: Form1.cs プロジェクト: karthikkumsi/FTDI_Test-app
    static void Main()
    {
        // Create the thread object. This does not start the thread.
        Worker workerObject = new Worker();
        Thread workerThread = new Thread(workerObject.DoWork);

        // Start the worker thread.
        workerThread.Start();
        Console.WriteLine("main thread: Starting worker thread...");

        // Loop until worker thread activates.
        while (!workerThread.IsAlive) ;

        // Put the main thread to sleep for 1 millisecond to
        // allow the worker thread to do some work:
        Thread.Sleep(1);

        // Request that the worker thread stop itself:
        workerObject.RequestStop();

        // Use the Join method to block the current thread
        // until the object's thread terminates.
        workerThread.Join();
        Console.WriteLine("main thread: Worker thread has terminated.");
    }
コード例 #12
0
ファイル: TypeText.cs プロジェクト: pbalint/Playground
 public override void Invoke(Worker.State state)
 {
     foreach (char ch in text)
     {
         TypeChar(ch);
     }
 }
コード例 #13
0
		public static void Main(string[] args)
		{
			// Use Release Build to use jsc to generate java program
			// Use Debug Build to develop on .net

			Console.WriteLine("Robocode1. Crosscompiled from C# to Java.");

			// Extension methods...
			("This will take a few seconds...").ToConsole();

			Text = "Hello World";


			var w = new Worker { Count = 3, Delay = 1000 };

			w.Handler +=
				delegate
				{
					var n = DateTime.Now;

					Console.WriteLine(n.Hour + ":" + n.Minute + ":" + n.Second);
				};

			w.Invoke();

			Console.WriteLine(Text);
		}
コード例 #14
0
    public static void Main()
	{
	    var worker = new Worker();
	    worker.Start();
	    Thread.Sleep(1000);
	    worker.Stop();	   
	}
コード例 #15
0
ファイル: FormLoader.cs プロジェクト: unforbidable/patcher
        public FormLoader(Plugin plugin, RecordReader stockReader, bool lazyLoading, int backgroundJobs)
        {
            if (backgroundJobs < 0)
                throw new ArgumentException("Number of bakcground jobs must be a positive integer or zero");

            sharedData = new SharedData()
            {
                Plugin = plugin,
                StockReader = stockReader,
                LazyLoading = lazyLoading,
                FormsToLoad = new BlockingCollection<Form>(new ConcurrentQueue<Form>(), 1024),
                WorkerCompleteEvent = new AutoResetEvent(false)
            };

            this.stockReader = stockReader;
            asyncLoading = backgroundJobs > 0;

            bool useStockReader = true;
            while (backgroundJobs-- > 0)
            {
                Worker worker = new Worker(sharedData, useStockReader);
                worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
                worker.RunWorkerAsync();
                workers.Add(new WorkerInfo()
                {
                    Worker = worker
                });

                // Only the first worker can use the stock reader
                useStockReader = false;
            }
        }
        public override Worker AsWorker()
        {
            Worker worker = new Worker("OTT", "Mathias Henrik Ottosen", 18, true, "Aalborg", "12345678", false, true, true);

            worker.SetNotAvailableHours(AsIndisposeds());
            return worker;
        }
コード例 #17
0
        public static void Main()
        {
            string[] studentData = Console.ReadLine()
                .Trim()
                .Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);

            string firstStudentName = studentData[0];
            string lastStudentName = studentData[1];
            string facultyNumber = studentData[2];

            string[] workerData = Console.ReadLine()
                .Trim()
                .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            string firstWorkerName = workerData[0];
            string lastWorkerName = workerData[1];
            double salary = double.Parse(workerData[2]);
            double workingHours = double.Parse(workerData[3]);

            try
            {
                Student student = new Student(firstStudentName, lastStudentName, facultyNumber);
                Worker worker = new Worker(firstWorkerName, lastWorkerName, salary, workingHours);

                Console.WriteLine(student);
                Console.WriteLine(worker);
            }
            catch (ArgumentException ae)
            {
                Console.WriteLine(ae.Message);
            }
        }
コード例 #18
0
    static void Main()
    {
        // load settings from App.config
        int numThreads = int.Parse(ConfigurationManager.AppSettings["numThreads"]);
        int waitTimeMillisecs = int.Parse(ConfigurationManager.AppSettings["waitTimeMillisecs"]);
        int iterations = int.Parse(ConfigurationManager.AppSettings["iterations"]);

        List<Worker> workers = new List<Worker>();

        for (int i = 0; i < numThreads; i++)
        {
            Worker worker = new Worker(iterations, waitTimeMillisecs);
            workers.Add(worker);
            ThreadStart job = new ThreadStart(worker.Run);
            Thread t = new Thread(job);
            t.Start();
        }

        long numIterations = 0;

        while (numIterations < (iterations * numThreads))
        {
            numIterations = 0;

            foreach (Worker worker in workers)
            {
                numIterations += worker.NumIterations;
            }

            Console.WriteLine("Iterations: {0}", numIterations);

            Thread.Sleep(500);
        }
    }
コード例 #19
0
 public void Execute(Worker worker)
 {
     if (!worker.IsOnBoard)
     {
         throw new NotImplementedException();
     }
 }
コード例 #20
0
ファイル: WorkQueueLock.cs プロジェクト: SmartCloudAI/Hopac
    internal void Enter(ref Worker wr, Work work) {
      work.Next = null;

      var owner = Interlocked.Exchange(ref Tail, work);

      if (owner != null) {
        owner.Next = work;
      } else {
      Release:
        work.DoWork(ref wr);
        var prev = work;
        work = Volatile.Read(ref prev.Next);
        if (null != work)
          goto Release;

        if (prev == Interlocked.CompareExchange(ref Tail, null, prev))
          return;

      Spin:
        work = Volatile.Read(ref prev.Next);
        if (null != work)
          goto Release;
        goto Spin;
      }
    }
コード例 #21
0
ファイル: PlaneParticleSystems.cs プロジェクト: tanis2000/FEZ
 public override void Initialize()
 {
   base.Initialize();
   this.WhiteSquare = this.CMProvider.Global.Load<Texture2D>("Background Planes/white_square");
   this.liquidSplash = this.CMProvider.Global.Load<SoundEffect>("Sounds/Nature/WaterSplash");
   this.PooledParticleSystems.Size = 5;
   this.LevelManager.LevelChanged += (Action) (() =>
   {
     foreach (PlaneParticleSystem item_0 in this.ActiveParticleSystems)
     {
       item_0.Clear();
       this.PooledParticleSystems.Return(item_0);
     }
     this.ActiveParticleSystems.Clear();
     if (this.LevelManager.Rainy)
       return;
     this.PooledParticleSystems.Size = 5;
     this.OtherDeadParticleSystems.Capacity = 50;
     this.DeadParticleSystems.Capacity = 50;
     this.ActiveParticleSystems.Capacity = 100;
     while (this.PooledParticleSystems.Available > 5)
       ServiceHelper.RemoveComponent<PlaneParticleSystem>(this.PooledParticleSystems.Take());
   });
   this.otherThread = this.ThreadPool.Take<MtUpdateContext<List<PlaneParticleSystem>>>(new Action<MtUpdateContext<List<PlaneParticleSystem>>>(this.UpdateParticleSystems));
   this.otherThread.Priority = ThreadPriority.Normal;
 }
コード例 #22
0
 public void DoWork(Worker d)
 {
     if (!Thread.CurrentThread.Equals((object) this.myThread))
     this.app.Dispatcher.Invoke(DispatcherPriority.Normal, (Delegate) d);
       else
     d();
 }
コード例 #23
0
    static void Main()
    {
        Student[] students = new Student[]
        {
            new Student("Jim", "Raynor", 10),
            new Student("Sarah", "Kerrigan", 10),
            new Student("Arcturus", "Mengsk", 8),
            new Student("Valerian", "Mengsk", 12),
            new Student("Kate ", "Lockwell", 3),
            new Student("Edmund ", "Duke", 7),
            new Student("Samir", "Duran", 1),
            new Student("Alexei", "Stukov", 11),
            new Student("Tychus", "Findlay", 2),
            new Student("Nova", "Terra", 9),
        };

        Student[] sortedStudents = students.OrderBy(x => x.Grade).ToArray();

        Console.WriteLine("Students sorted by grade:");
        foreach (var student in sortedStudents)
        {
            Console.WriteLine(student);
        }
        Console.WriteLine();

        Worker[] workers = new Worker[]
        {
            new Worker("Michael", "Charles", 200M, 2),
            new Worker("James", "Gray", 430M, 8),
            new Worker("Ronald", "Frank", 500M, 6),
            new Worker("Harry", "Tyler", 320M, 4),
            new Worker("Steven", "Clarke", 800M, 12),
            new Worker("Mary", "Carter", 500M, 4),
            new Worker("Emily", "Richard", 800M, 8),
            new Worker("Linda", "Williams", 400M, 6),
            new Worker("Ashley", "Rose", 10M, 1),
            new Worker("Lisa", "Mark", 540M, 12),
        };

        Worker[] sortedWorkers = workers.OrderByDescending(x => x.MoneyPerHour()).ToArray();

        Console.WriteLine("Workers sorted by money per hour:");
        foreach (var worker in sortedWorkers)
        {
            Console.WriteLine(worker);
        }
        Console.WriteLine();

        List<Human> humans = new List<Human>(students);
        humans.AddRange(workers);
        List<Human> sortedHumans = humans.OrderBy(x => x.FirstName).ThenBy(x => x.LastName).ToList();

        Console.WriteLine("Humans sorted by name:");
        foreach (var human in sortedHumans)
        {
            Console.WriteLine(human);
        }
        Console.WriteLine();
    }
コード例 #24
0
        public void TestWorkerCompareToMethod()
        {
            Worker worker1 = new Worker("Lyubomir", "Yanchev", 350);
            Worker worker2 = new Worker("Nikolay", "Alexiev", 295);


            Assert.AreEqual(-1, worker1.CompareTo(worker2));
        }
コード例 #25
0
    /*private void CreateWorker(WorkerType type)
    {

    }*/
    // ------------------------ Worker List Management -------------------------------
    public static Worker AddWorker(GameObject newWorker, WorkerType type, int gender)
    {
        Worker worker = null;
        worker = new Worker(newWorker, type, gender);
        workers.Add(worker);

        return worker;
    }
コード例 #26
0
ファイル: UslugaPrc.cs プロジェクト: pawlo57/Warsztat
        private void cbxPracownik_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbxPracownik.DisplayMember == "" || cbxPracownik.ValueMember == "") return;

            PRACOWNIK = (Worker)cbxPracownik.SelectedItem;

            cbxPracownik.BackColor = Color.White;
        }
コード例 #27
0
 public void Save(Worker obj)
 {
     if (obj.Id == 0)
         context.Entry(obj).State = System.Data.Entity.EntityState.Added;
     else
         context.Entry(obj).State = System.Data.Entity.EntityState.Modified;
     context.SaveChanges();
 }
コード例 #28
0
    // Sets the Worker Class Instance
    public void SetWorker(Worker worker)
    {
        this.worker = worker;
        worker.name = GetRandomName(worker.gender);
        name = worker.name;

        //name = GetRandomName(worker.gender);
    }
 public void GetProperty_Should_Return_Property_Value_For_Complex_Path()
 {
     var manager = new Manager("Joe", "Smith");
     var worker = new Worker("Willy", "Brown", manager);
     var expected = worker.Manager.FirstName;
     var actual = worker.GetPropertyValue<string>("Manager.FirstName");
     Assert.AreEqual(expected, actual);
 }
コード例 #30
0
		/// <summary>
		///   Processes the new <paramref name="transition" /> discovered by the <paramref name="worker " /> within the traversal
		///   <paramref name="context" />.
		/// </summary>
		/// <param name="context">The context of the model traversal.</param>
		/// <param name="worker">The worker that found the transition.</param>
		/// <param name="transition">The new transition that should be processed.</param>
		/// <param name="isInitialTransition">
		///   Indicates whether the transition is an initial transition not starting in any valid source state.
		/// </param>
		public unsafe void ProcessTransition(TraversalContext context, Worker worker, Transition* transition, bool isInitialTransition)
		{
			if (transition->Formulas[_formulaIndex])
				return;

			context.FormulaIsValid = false;
			context.LoadBalancer.Terminate();
			worker.CreateCounterExample(endsWithException: false, addAdditionalState: false);
		}
コード例 #31
0
 public void UpdateCurrentSelected(Worker employee)
 {
     currentSelectedEmployee = employee;
 }
コード例 #32
0
ファイル: Job.cs プロジェクト: HotThoughts/IGDSS20
 public void AssignWorker(Worker w)
 {
     w._employed = true;
     _worker     = w;
     _prodBuilding.WorkerAssignedToBuilding(w);
 }
コード例 #33
0
        public void AssignAddedJobToAnotherWorker_UncommittedEventsContainsAddedWorkerUnassignedAnotherWorkerAssigned(Worker anotherWorker)
        {
            Arrange_EventHistory(
                new WorkshopEvent.WorkerAdded(anotherWorker)
                );

            Act_AssignJob(anotherWorker.Id, _addedJob.Id);

            Assert_UncommittedEventsContains(
                new WorkshopEvent.JobUnassigned(_addedWorker.Id, _addedJob.Id),
                new WorkshopEvent.JobAssigned(anotherWorker.Id, _addedJob.Id)
                );
        }
コード例 #34
0
        public void AddWorker_UncommittedContainsWorkerAddedEvent(Worker worker)
        {
            Act_AddWorker(worker);

            Assert_UncommittedEventsContains(new WorkshopEvent.WorkerAdded(worker));
        }
コード例 #35
0
 public virtual bool AllowsMove(Tile tile, Worker worker)
 {
     return(AllowsMove(tile) && worker.GetTile().IsTileDirectlyNeighbouring(tile));
 }
コード例 #36
0
        private static void OnClick(MouseEvent <HTMLButtonElement> mouseEvent)
        {
            MeshType type;

            if (typePicker.SelectedIndex < 0)
            {
                type = MeshType.Square;
            }
            else
            {
                type = MeshTypeFromString(typePicker.Value);
            }
            int width;
            int height;

            if (!ParseSize(sizeInput.Value, type, out width, out height))
            {
                return;
            }
            Mesh mesh = MakeMesh(width, height, type, difficultyPicker.SelectedIndex);

            display.Mesh = mesh;

            worker = new Worker(Extensions.Window().URL.createObjectURL(new Blob(new BlobDataObject[]
            {
                @"
self.onmessage = function(e) { 
  if (e.data.href) {
    try { 
      importScripts(e.data.href);
    } catch (error) {
      console.log(e.data.href);  
      console.log(error);
    }
  } else {
    TwistNTurnBridge.WorkerSpawn.WorkerSpawn_OnMessage(e);
  }
}"
            }, new BlobPropertyBag()
            {
                Type = "text/javascript"
            })));
            progressBar                       = Document.CreateElement <HTMLProgressElement>("progress");
            progressBar.Max                   = mesh.Intersections.Count;
            progressBar.Style.Position        = Position.Absolute;
            progressBar.Style.Margin          = "auto";
            progressBar.Style.Top             = "0";
            progressBar.Style.Bottom          = "0";
            progressBar.Style.Left            = "0";
            progressBar.Style.Right           = "0";
            progressBar.Style.ZIndex          = "100";
            progressBar.Style.BackgroundColor = "white";
            displayHost.AppendChild(progressBar);
            generateButton.Disabled = true;
            worker.OnMessage       += AppWorker_OnMessage;
            string to_load = Window.Location.Href.Substring(0, Window.Location.Href.LastIndexOf('/') + 1) + "bridge.min.js";

            worker.PostMessage(new InitialReuqest()
            {
                href = to_load
            });
            to_load = Window.Location.Href.Substring(0, Window.Location.Href.LastIndexOf('/') + 1) + "bridge.console.min.js";
            worker.PostMessage(new InitialReuqest()
            {
                href = to_load
            });
            to_load = Window.Location.Href.Substring(0, Window.Location.Href.LastIndexOf('/') + 1) + "bridge.meta.min.js";
            worker.PostMessage(new InitialReuqest()
            {
                href = to_load
            });
            to_load = Window.Location.Href.Substring(0, Window.Location.Href.LastIndexOf('/') + 1) + "newtonsoft.json.min.js";
            worker.PostMessage(new InitialReuqest()
            {
                href = to_load
            });
            to_load = Window.Location.Href.Substring(0, Window.Location.Href.LastIndexOf('/') + 1) + "TwistNTurnBridge.min.js";
            worker.PostMessage(new InitialReuqest()
            {
                href = to_load
            });
            to_load = Window.Location.Href.Substring(0, Window.Location.Href.LastIndexOf('/') + 1) + "TwistNTurnBridge.meta.min.js";
            worker.PostMessage(new InitialReuqest()
            {
                href = to_load
            });
            worker.PostMessage(JsonConvert.SerializeObject(new GenerateRequest()
            {
                Width = width, Height = height, Type = type, Difficulty = difficultyPicker.SelectedIndex
            }));
        }
コード例 #37
0
 public void WorkerAssignedToBuilding(Worker w)
 {
     workers.Add(w);
 }
コード例 #38
0
ファイル: Events.cs プロジェクト: NatalieWolfe/BaseBuilder
 public WorkerEvent(WorkerEventType type, Worker worker) :
     base(EventType.WorkerEvent)
 {
     this.workerEventType = type;
     this.worker          = worker;
 }
コード例 #39
0
 public void Put(int id, [FromBody] Worker worker)
 {
     _context.Workers.Update(worker);
     _context.SaveChanges();
 }
コード例 #40
0
 public void Post(Worker worker)
 {
     _context.Workers.Add(worker);
     _context.SaveChanges();
 }
コード例 #41
0
ファイル: Job.cs プロジェクト: HotThoughts/IGDSS20
 public void RemoveWorker(Worker w)
 {
     _worker = null;
     _prodBuilding.WorkerRemovedFromBuilding(w);
 }
コード例 #42
0
 public void RemoveWorker(Worker player)
 {
     players.Remove(player);
     base.smi.sm.playerCount.Set(players.Count, base.smi);
 }
コード例 #43
0
ファイル: OrderManagerModule.cs プロジェクト: dfgs/PIO
        public Task CreateTaskFromProduceOrder(Worker Worker, ProduceOrder ProduceOrder)
        {
            bool result;

            ResourceTypeIDs[] missingResourceTypeID;
            Building          building;
            Stack             stack;
            Task task;

            building = AssertExists <Building>(() => client.GetBuilding(ProduceOrder.BuildingID), $"BuildingID={ProduceOrder.BuildingID}");

            Log(LogLevels.Information, $"Checking if building as enough resources to produce (BuildingID={ProduceOrder.BuildingID})");
            missingResourceTypeID = Try(() => client.GetMissingResourcesToProduce(ProduceOrder.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to check resources");
            if ((missingResourceTypeID == null) || (missingResourceTypeID.Length == 0))
            {
                Log(LogLevels.Information, $"Checking if worker is on site (WorkerID={Worker.WorkerID}, BuildingID={ProduceOrder.BuildingID})");
                result = Try(() => client.WorkerIsInBuilding(Worker.WorkerID, building.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to check worker location");
                if (result)
                {
                    Log(LogLevels.Information, $"Worker is on site, creating produce task");
                    task = Try(() => client.Produce(Worker.WorkerID)).OrThrow <PIOInternalErrorException>("Failed to create task");
                }
                else
                {
                    Log(LogLevels.Information, $"Worker is not on site, creating moveto task");
                    task = Try(() => client.MoveToBuilding(Worker.WorkerID, building.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to create task");
                }
                return(task);
            }
            else
            {
                Log(LogLevels.Information, $"Checking if worker is carrying missing resource (PlanetID={Worker.PlanetID})");
                if ((Worker.ResourceTypeID != null) && missingResourceTypeID.Contains(Worker.ResourceTypeID.Value))
                {
                    Log(LogLevels.Information, $"Worker is carrying missing resource, checking if worker is on site (WorkerID={Worker.WorkerID}, BuildingID={ProduceOrder.BuildingID})");
                    result = Try(() => client.WorkerIsInBuilding(Worker.WorkerID, building.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to check worker location");
                    if (result)
                    {
                        Log(LogLevels.Information, $"Worker is on site, creating store task");
                        task = Try(() => client.Store(Worker.WorkerID)).OrThrow <PIOInternalErrorException>("Failed to create task");
                        return(task);
                    }
                    else
                    {
                        Log(LogLevels.Information, $"Worker is not on site, creating moveto task");
                        task = Try(() => client.MoveToBuilding(Worker.WorkerID, building.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to create task");
                        return(task);
                    }
                }
                else
                {
                    Log(LogLevels.Information, $"Trying to find missing resource (PlanetID={Worker.PlanetID}, ResourceTypeID={missingResourceTypeID[0]})");
                    stack = Try(() => client.FindStack(Worker.PlanetID, missingResourceTypeID[0])).OrThrow("Failed to find missing resource");
                    if (stack == null)
                    {
                        Log(LogLevels.Information, $"Missing resource not found, cannot create task");
                        return(null);
                    }
                    else
                    {
                        Log(LogLevels.Information, $"Missing resource found, checking if worker can carry to");
                        result = Try(() => client.WorkerIsInBuilding(Worker.WorkerID, stack.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to check worker location");
                        if (result)
                        {
                            Log(LogLevels.Information, $"Worker can access resource, creating take task");
                            task = Try(() => client.Take(Worker.WorkerID, missingResourceTypeID[0])).OrThrow <PIOInternalErrorException>("Failed to create task");
                            return(task);
                        }
                        else
                        {
                            Log(LogLevels.Information, $"Missing resource found, creating moveto task");
                            task = Try(() => client.MoveToBuilding(Worker.WorkerID, stack.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to create task");
                            return(task);
                        }
                    }
                }
            }
        }
コード例 #44
0
 public void WorkerRemovedFromBuilding(Worker w)
 {
     workers.Remove(w);
 }
コード例 #45
0
 public virtual bool AllowsOpponentBuild(Worker worker, Tile tile)
 {
     return(true);
 }
コード例 #46
0
ファイル: Program.cs プロジェクト: bitmory/CryptoMining
        public static void Worker1(int poolid)
        {
            var    jsonConfig = File.ReadAllText(@"Json\\f2pool.json");
            var    config     = StructuredDataConfig.ParseJsonString(jsonConfig);
            string html;
            string url = GetUrl(poolid);

            using (WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                client.Headers.Add(HttpRequestHeader.UserAgent, "");
                html = client.DownloadString(url);
            }
            //var html = File.ReadAllText(@"f2pool.html", Encoding.UTF8);

            var openScraping    = new StructuredDataExtractor(config);
            var scrapingResults = openScraping.Extract(html);

            //var json = JsonConvert.SerializeObject(scrapingResults);
            var jsonres = JsonConvert.DeserializeObject(scrapingResults.ToString());

            foreach (var item in (dynamic)jsonres)
            {
                //string checkquery = "SELECT COUNT(*) FROM worker where poolid = '" + poolid + "' and workername = '" + item.workername + "' ";
                //var count = db.Query<int>(checkquery).FirstOrDefault();
                var count = 0;

                if (count == 0)
                {
                    if (item.currenthash == "0" || item.currenthash == "0.00")
                    {
                        //
                        Worker worker = new Worker();
                        worker.poolid          = poolid;
                        worker.workername      = item.workername;
                        worker.currenthashrate = item.currenthash;
                        worker.dailyhashrate   = item.dailyhash;
                        worker.rejected        = item.rejected;
                        worker.updateat        = DateTime.Now;
                        worker.isactive        = false;
                        Add(worker);
                    }
                    else if (item.currenthash == null)
                    {
                        continue;
                    }
                    else
                    {
                        //DateTime datetime = Convert.ToDateTime(date);
                        // insert to
                        Worker worker = new Worker();
                        worker.poolid          = poolid;
                        worker.workername      = item.workername;
                        worker.currenthashrate = item.currenthash;
                        worker.dailyhashrate   = item.dailyhash;
                        worker.rejected        = item.rejected;
                        worker.updateat        = DateTime.Now;
                        worker.isactive        = true;
                        Add(worker);
                    }
                }
                else
                {
                    bool   isactive = (item.currenthash == "0" || item.currenthash == "0.00") ? false : true;
                    Worker worker   = new Worker();
                    worker.poolid          = poolid;
                    worker.workername      = item.workername;
                    worker.currenthashrate = item.currenthash;
                    worker.dailyhashrate   = item.dailyhash;
                    worker.rejected        = item.rejected;
                    worker.updateat        = DateTime.Now;
                    worker.isactive        = isactive;
                    Update(worker);
                }

                //Console.WriteLine("{0} {1} {2} {3}\n", item.workername, item.currenthash,
                //    item.dailyhash, item.rejected);
            }

            //Console.ReadKey();
        }
コード例 #47
0
 public EditWorkerPage()
 {
     this.InitializeComponent();
     workerToBeEdited = new Worker();
 }
コード例 #48
0
ファイル: Program.cs プロジェクト: bitmory/CryptoMining
        public static void Worker2(int poolid)
        {
            var    jsonConfig = File.ReadAllText(@"Json\\poolin.json");
            var    config     = StructuredDataConfig.ParseJsonString(jsonConfig);
            string html;
            string url = GetUrl(poolid);

            //using (WebClient client = new WebClient())
            //{
            //    client.Encoding = Encoding.UTF8;
            //    //client.Headers.Add(HttpRequestHeader.UserAgent, "test");
            //    //client.Credentials = CredentialCache.DefaultCredentials;
            //    html = client.DownloadString(url);
            //}

            var driver = new ChromeDriver();

            //var homeURL = "https://www.poolin.com/my/9007375/btc/miners?read_token=wowavEpSkh6wX7yePaQ4wcsfbPKPWNBlxkqppuYlJNvm4NUHUBoLCzAKhj4QTblH";
            driver.Navigate().GoToUrl(url);
            //IWebElement element = driver.FindElement(By.XPath("//table"));
            var source = driver.PageSource;

            driver.Close();
            driver.Quit();

            var openScraping    = new StructuredDataExtractor(config);
            var scrapingResults = openScraping.Extract(source);
            //var json = JsonConvert.SerializeObject(scrapingResults);
            var jsonres = JsonConvert.DeserializeObject(scrapingResults.ToString());

            foreach (var item in (dynamic)jsonres)
            {
                //string checkquery = "SELECT COUNT(*) FROM worker where poolid = '" + poolid + "' and workername = '" + item.workername + "' ";
                //var count = db.Query<int>(checkquery).FirstOrDefault();
                var count = 0;

                if (count == 0)
                {
                    if (item.currenthash == "0" || item.currenthash == "0.00")
                    {
                        //
                        Worker worker = new Worker();
                        worker.poolid          = poolid;
                        worker.workername      = item.workername;
                        worker.currenthashrate = item.currenthash;
                        worker.dailyhashrate   = item.dailyhash;
                        worker.rejected        = item.rejected;
                        worker.updateat        = DateTime.Now;
                        worker.isactive        = false;
                        Add(worker);
                    }
                    else if (item.currenthash == null)
                    {
                        continue;
                    }
                    else
                    {
                        //DateTime datetime = Convert.ToDateTime(date);
                        // insert to
                        Worker worker = new Worker();
                        worker.poolid          = poolid;
                        worker.workername      = item.workername;
                        worker.currenthashrate = item.currenthash;
                        worker.dailyhashrate   = item.dailyhash;
                        worker.rejected        = item.rejected;
                        worker.updateat        = DateTime.Now;
                        worker.isactive        = true;
                        Add(worker);
                    }
                }
                else
                {
                    bool   isactive = (item.currenthash == "0" || item.currenthash == "0.00") ? false : true;
                    Worker worker   = new Worker();
                    worker.poolid          = poolid;
                    worker.workername      = item.workername;
                    worker.currenthashrate = item.currenthash;
                    worker.dailyhashrate   = item.dailyhash;
                    worker.rejected        = item.rejected;
                    worker.updateat        = DateTime.Now;
                    worker.isactive        = isactive;
                    Update(worker);
                }

                //Console.WriteLine("{0} {1} {2} {3}\n", item.workername, item.currenthash,
                //    item.dailyhash, item.rejected);
            }

            //foreach (var item in (dynamic)jsonres)
            //{
            //    Worker worker = new Worker();
            //    worker.poolid = poolid;
            //    worker.workername = item.workername;
            //    worker.currenthashrate = item.currenthash;
            //    worker.dailyhashrate = item.dailyhash;
            //    worker.rejected = item.rejected;
            //    worker.updateat = DateTime.Now;
            //    worker.isactive = true;
            //    worker.currentcalculation = item.currenthashtotal;
            //    worker.dailycalculation = item.dailyhashtotal;
            //    UpdateSummary(worker);
            //    break;
            //}

            //Console.ReadKey();
        }
コード例 #49
0
 public void AddWorker_Succeeds(Worker worker)
 {
     Act_AddWorker(worker)
     .Assert_Succeeds();
 }
コード例 #50
0
 public void AddIdleWorker(Worker w)
 {
     Workers.Add(w);
 }
コード例 #51
0
 protected Maybe <WorkshopError> Act_AddWorker(Worker worker)
 => _sut.HandleCommand(new WorkshopCommand.AddWorker(worker));
コード例 #52
0
 public void AddAnotherWorker_Succeeds(Worker anotherWorker)
 {
     Act_AddWorker(anotherWorker)
     .Assert_Succeeds();
 }
コード例 #53
0
        public void AddAnotherWorker_UncommittedContainsAddAnotherWorkerEvent(Worker anotherWorker)
        {
            Act_AddWorker(anotherWorker);

            Assert_UncommittedEventsContains(new WorkshopEvent.WorkerAdded(anotherWorker));
        }
コード例 #54
0
ファイル: ppqueue.cs プロジェクト: mycopy/zguide
        static void Main(string[] args)
        {
            using (var context = new Context(1))
            {
                using (Socket frontend = context.Socket(SocketType.ROUTER), backend = context.Socket(SocketType.ROUTER))
                {
                    frontend.Bind("tcp://*:5555"); // For Clients
                    backend.Bind("tcp://*:5556"); // For Workers

                    //  Queue of available workers
                    var workerQueue = new List<Worker>();

                    backend.PollInHandler += (socket, revents) =>
                    {
                        var zmsg = new ZMessage(socket);

                        byte[] identity = zmsg.Unwrap();

                        //Any sign of life from worker means it's ready, Only add it to the queue if it's not in there already
                        Worker worker = null;

                        if (workerQueue.Count > 0)
                        {
                            var workers = workerQueue.Where(x => x.address.SequenceEqual(identity));

                            if (workers.Count() > 0)
                                worker = workers.Single();
                        }

                        if (worker == null)
                        {
                            workerQueue.Add(new Worker(identity));
                        }

                        //Return reply to client if it's not a control message
                        switch (Encoding.Unicode.GetString(zmsg.Address))
                        {
                            case PPP_READY:
                                Console.WriteLine("Worker " + Encoding.Unicode.GetString(identity) + " is ready...");
                                break;
                            case PPP_HEARTBEAT:
                                bool found = false;

                                //Worker Refresh
                                if (worker != null)
                                {
                                    found = true;
                                    worker.ResetExpiry();
                                }

                                if (!found)
                                {
                                    Console.WriteLine("E: worker " + Encoding.Unicode.GetString(identity) + " not ready...");
                                }
                                break;
                            default:
                                zmsg.Send(frontend);
                                break;
                        };
                    };

                    frontend.PollInHandler += (socket, revents) =>
                    {
                        //  Now get next client request, route to next worker
                        //  Dequeue and drop the next worker address
                        var zmsg = new ZMessage(socket);

                        Worker w = workerQueue[0];
                        zmsg.Wrap(w.address, new byte[0]);
                        workerQueue.RemoveAt(0);
                        
                        zmsg.Send(backend);
                    };

                    DateTime heartbeat_at = DateTime.Now.AddMilliseconds(HEARTBEAT_INTERVAL);

                    while (true)
                    {
                        //Only poll frontend only if there are workers ready
                        if (workerQueue.Count > 0)
                        {
                            List<Socket> pollItems = new List<Socket>(new Socket[] { frontend, backend });
                            Context.Poller(pollItems, HEARTBEAT_INTERVAL * 1000);
                        }
                        else
                        {
                            List<ZMQ.Socket> pollItems = new List<Socket>(new Socket[] { backend });
                            Context.Poller(pollItems, HEARTBEAT_INTERVAL * 1000);
                        }

                        //Send heartbeats to idle workers if it's time
                        if (DateTime.Now >= heartbeat_at)
                        {
                            foreach (var worker in workerQueue)
                            {
                                ZMessage zmsg = new ZMessage(PPP_HEARTBEAT);
                                zmsg.Wrap(worker.address, new byte[0]);
                                zmsg.Send(backend);
                            }

                            heartbeat_at = DateTime.Now.AddMilliseconds(HEARTBEAT_INTERVAL);
                        }
                    }
                }
            }
        }
コード例 #55
0
 public static void EmployeeAdded(Worker employee)
 {
     OnEmployeeAdded.SafeInvoke(employee);
 }
コード例 #56
0
ファイル: Basement.cs プロジェクト: sitskomickhail/C_Sharp
 public void AddSlice(Worker builder)
 {
     _crLenght++;
     _pct = (_crLenght * 100) / _fullLenght;
 }
コード例 #57
0
 public void GetWorker(Worker worker)
 {
     this.worker = worker;
 }
コード例 #58
0
ファイル: OrderManagerModule.cs プロジェクト: dfgs/PIO
        public Task CreateTaskFromBuildOrder(Worker Worker, BuildOrder BuildOrder)
        {
            Building building;
            bool     result;
            Task     task;

            ResourceTypeIDs[] missingResourceTypeID;
            Stack             stack;

            Log(LogLevels.Information, $"Checking if building exists (PlanetID={BuildOrder.PlanetID}, X={BuildOrder.X}, Y={BuildOrder.Y})");
            building = Try(() => client.GetBuildingAtPos(BuildOrder.PlanetID, BuildOrder.X, BuildOrder.Y)).OrThrow <PIOInternalErrorException>("Failed to check is building exists");
            if (building == null)
            {
                Log(LogLevels.Information, $"Checking if worker is on site (WorkerID={Worker.WorkerID}, X={BuildOrder.X}, Y={BuildOrder.X})");
                result = (Worker.X == BuildOrder.X) && (Worker.Y == BuildOrder.Y);
                if (result)
                {
                    Log(LogLevels.Information, $"Worker is on site, creating createbuilding task");
                    task = Try(() => client.CreateBuilding(Worker.WorkerID, BuildOrder.BuildingTypeID)).OrThrow <PIOInternalErrorException>("Failed to create task");
                }
                else
                {
                    Log(LogLevels.Information, $"Worker is not on site, creating moveto task");
                    task = Try(() => client.MoveTo(Worker.WorkerID, BuildOrder.X, BuildOrder.Y)).OrThrow <PIOInternalErrorException>("Failed to create task");
                }
                return(task);
            }
            else
            {
                if (building.RemainingBuildSteps == 0)
                {
                    Log(LogLevels.Information, $"Building is already built (BuildingID={building.BuildingID})");
                    return(null);
                }

                Log(LogLevels.Information, $"Checking if building as enough resources to build (BuildingID={building.BuildingID})");
                missingResourceTypeID = Try(() => client.GetMissingResourcesToBuild(building.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to check resources");
                if ((missingResourceTypeID == null) || (missingResourceTypeID.Length == 0))
                {
                    Log(LogLevels.Information, $"Checking if worker is on site (WorkerID={Worker.WorkerID}, BuildingID={building.BuildingID})");
                    result = (Worker.X == BuildOrder.X) && (Worker.Y == BuildOrder.Y);
                    if (result)
                    {
                        Log(LogLevels.Information, $"Worker is on site, creating BuildBuilding task");
                        task = Try(() => client.Build(Worker.WorkerID)).OrThrow <PIOInternalErrorException>("Failed to create task");
                    }
                    else
                    {
                        Log(LogLevels.Information, $"Worker is not on site, creating moveto task");
                        task = Try(() => client.MoveTo(Worker.WorkerID, BuildOrder.X, BuildOrder.Y)).OrThrow <PIOInternalErrorException>("Failed to create task");
                    }
                    return(task);
                }
                else
                {
                    Log(LogLevels.Information, $"Checking if worker is carrying missing resource (PlanetID={Worker.PlanetID})");
                    if ((Worker.ResourceTypeID != null) && missingResourceTypeID.Contains(Worker.ResourceTypeID.Value))
                    {
                        Log(LogLevels.Information, $"Worker is carrying missing resource, checking if worker is on site (WorkerID={Worker.WorkerID}, X={BuildOrder.X}, Y={BuildOrder.X})");
                        result = (Worker.X == BuildOrder.X) && (Worker.Y == BuildOrder.Y);
                        if (result)
                        {
                            Log(LogLevels.Information, $"Worker is on site, creating store task");
                            task = Try(() => client.Store(Worker.WorkerID)).OrThrow <PIOInternalErrorException>("Failed to create task");
                            return(task);
                        }
                        else
                        {
                            Log(LogLevels.Information, $"Worker is not on site, creating moveto task");
                            task = Try(() => client.MoveTo(Worker.WorkerID, BuildOrder.X, BuildOrder.Y)).OrThrow <PIOInternalErrorException>("Failed to create task");
                            return(task);
                        }
                    }
                    else
                    {
                        Log(LogLevels.Information, $"Trying to find missing resource (PlanetID={Worker.PlanetID}, ResourceTypeID={missingResourceTypeID[0]})");
                        stack = Try(() => client.FindStack(Worker.PlanetID, missingResourceTypeID[0])).OrThrow("Failed to find missing resource");
                        if (stack == null)
                        {
                            Log(LogLevels.Information, $"Missing resource not found, cannot create task");
                            return(null);
                        }
                        else
                        {
                            Log(LogLevels.Information, $"Missing resource found, checking if worker can carry to");
                            result = Try(() => client.WorkerIsInBuilding(Worker.WorkerID, stack.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to check worker location");
                            if (result)
                            {
                                Log(LogLevels.Information, $"Worker can access resource, creating take task");
                                task = Try(() => client.Take(Worker.WorkerID, missingResourceTypeID[0])).OrThrow <PIOInternalErrorException>("Failed to create task");
                                return(task);
                            }
                            else
                            {
                                Log(LogLevels.Information, $"Missing resource found, creating moveto task");
                                task = Try(() => client.MoveToBuilding(Worker.WorkerID, stack.BuildingID)).OrThrow <PIOInternalErrorException>("Failed to create task");
                                return(task);
                            }
                        }
                    }
                }
            }
        }
コード例 #59
0
ファイル: BirthdayHandler.cs プロジェクト: MPilinkus/Naujas
        public string Message(Worker w)
        {
            if ((DateTime.Today.Month > w.BirthdayDate.Month) || (DateTime.Today.Day > w.BirthdayDate.Day))
            {
                string dayword;
                int    day = w.BirthdayDate.Day;
                switch (day)
                {
                case 1:
                    dayword = "st";
                    break;

                case 2:
                    dayword = "nd";
                    break;

                case 3:
                    dayword = "rd";
                    break;

                default:
                    dayword = "th";
                    break;
                }
                string monthword;
                int    month = w.BirthdayDate.Month;
                switch (month)
                {
                case 1:
                    monthword = "January";
                    break;

                case 2:
                    monthword = "February";
                    break;

                case 3:
                    monthword = "March";
                    break;

                case 4:
                    monthword = "April";
                    break;

                case 5:
                    monthword = "May";
                    break;

                case 6:
                    monthword = "June";
                    break;

                case 7:
                    monthword = "July";
                    break;

                case 8:
                    monthword = "August";
                    break;

                case 9:
                    monthword = "September";
                    break;

                case 10:
                    monthword = "October";
                    break;

                case 11:
                    monthword = "November";
                    break;

                case 12:
                    monthword = "December";
                    break;

                default:
                    monthword = "";
                    break;
                }
                return(" was celebrating birthday on the " + w.BirthdayDate.Day + dayword + " of " + monthword + "!");
            }
            return(" is celebrating birthday!");
        }
コード例 #60
0
 public void AddWorker(Worker player)
 {
     players.Add(player);
     base.smi.sm.playerCount.Set(players.Count, base.smi);
 }