Called at construction time
510214
private function initSkeletonEmbeddable(): void
    {
        $this->setSkeletonEmbeddable(
            new SkeletonEmbeddable(
                SkeletonEmbeddableInterface::DEFAULT_PROPERTY_ONE,
                SkeletonEmbeddableInterface::DEFAULT_PROPERTY_TWO
            ),
            false
        );
    }
685189
@PostConstruct
  public void setupScheduler() {
    for(SchedulerTask task : tasks) {
      if(task.getDelay() > 0 && task.getInterval() > 0) {
        executor.scheduleWithFixedDelay(task.getTask(), task.getDelay(), task.getInterval(), task.getTimeUnit());
      } else if(task.isImmediate() && task.getInterval() > 0) {
        executor.scheduleWithFixedDelay(task.getTask(), 0l, task.getInterval(), task.getTimeUnit());
      } else if(task.getDelay() > 0) {
        executor.schedule(task.getTask(), task.getDelay(), task.getTimeUnit());
      } else {
        executor.execute(task.getTask());
      }
    }
  }
273928
def on_result(self, type, task, result):
        ''''''
        status_code = result.get('status_code', 599)
        if status_code != 599:
            status_code = (int(status_code) / 100 * 100)
        self._cnt['5m'].event((task.get('project'), status_code), +1)
        self._cnt['1h'].event((task.get('project'), status_code), +1)

        if type in ('http', 'phantomjs') and result.get('time'):
            content_len = len(result.get('content', ''))
            self._cnt['5m'].event((task.get('project'), 'speed'),
                                  float(content_len) / result.get('time'))
            self._cnt['1h'].event((task.get('project'), 'speed'),
                                  float(content_len) / result.get('time'))
            self._cnt['5m'].event((task.get('project'), 'time'), result.get('time'))
            self._cnt['1h'].event((task.get('project'), 'time'), result.get('time'))
1101193
public function onReady()
    {

        // Adding listener
        // ComplexJob - STATE_WAITING
        $job = new \PHPDaemon\Core\ComplexJob(function ($job) {
            // ComplexJob - STATE_DONE
            /*array (
              'bar' =>
              array (
                    'job' => 'bar',
                    'success' => false,
                    'line' => 63,
              ),
              'foo' =>
              array (
                    'job' => 'foo',
                    'success' => true,
                    'line' => 84,
                    'arg' =>
                    array (
                      'param' => 'value',
                    ),
              ),
              'baz' =>
              array (
                    'job' => 'baz',
                    'success' => false,
                    'line' => 94,
              ),
            )*/
            \PHPDaemon\Core\Daemon::log($job->results);
        });

        // Adding listener
        // ComplexJob - STATE_WAITING
        $job->addListener(function ($job) {
            // ComplexJob - STATE_DONE
        });

        // Adding async job foo
        $job('foo', $this->foo(['param' => 'value']));

        // Adding with 1 sec delay
        \PHPDaemon\Core\Timer::add(function ($event) use ($job) {

            // Adding async job bar
            $job('bar', function ($jobname, $job) {
                \PHPDaemon\Core\Timer::add(function ($event) use ($jobname, $job) {
                    // Job done
                    $job->setResult($jobname, ['job' => 'bar', 'success' => false, 'line' => __LINE__]);
                    $event->finish();
                }, 1e3 * 50);
            });

            // Adding async job baz. Equal $job('baz', $this->baz());
            $job->addJob('baz', $this->baz());

            // Run jobs. All listeners will be called when the jobs done
            // ComplexJob - STATE_RUNNING
            $job();

            $event->finish();
        }, 1e6 * 1);
    }
687341
public function callBuild()
    {
        $eventObjectTable = $this->getEventObjectTable();
        $callback = $this->getStatement();
        $actionTiming = $this->getActionTiming();
        $event = $this->getEvent();

        $this->build(tap(
            $this->createBlueprint($this->trigger),
            function (Blueprint $blueprint) use ($eventObjectTable, $callback, $actionTiming, $event) {
                $blueprint->create();
                $blueprint->on($eventObjectTable);
                $blueprint->statement($callback);
                $blueprint->$actionTiming();
                $blueprint->$event();
            }
        ));
    }
771087
def run(self):
        """"""
        while True:
            if not self.task_socket.poll(-1):
                continue

            msg = self.task_socket.recv_multipart()
            msg_type = msg[1]

            if self.debug:
                self.stats.append((time.time(),
                                   msg_type,
                                   len(self.unassigned_tasks),
                                   len(self.available_workers)))
                if time.time() - self.lastDebugTs > TIME_BETWEEN_PARTIALDEBUG:
                    self.writeDebug("debug/partial-{0}".format(
                        round(time.time(), -1)
                    ))
                    self.lastDebugTs = time.time()

            # New task inbound
            if msg_type == TASK:
                task_id = msg[2]
                task = msg[3]
                self.logger.debug("Received task {0}".format(task_id))
                try:
                    address = self.available_workers.popleft()
                except IndexError:
                    self.unassigned_tasks.append((task_id, task))
                else:
                    self.logger.debug("Sent {0}".format(task_id))
                    self.task_socket.send_multipart([address, TASK, task])
                    self.assigned_tasks[address].add(task_id)

            # Request for task
            elif msg_type == REQUEST:
                address = msg[0]
                try:
                    task_id, task = self.unassigned_tasks.popleft()
                except IndexError:
                    self.available_workers.append(address)
                else:
                    self.logger.debug("Sent {0}".format(task_id))
                    self.task_socket.send_multipart([address, TASK, task])
                    self.assigned_tasks[address].add(task_id)

            # A task status request is requested
            elif msg_type == STATUS_REQ:
                self.pruneAssignedTasks()
                address = msg[0]
                task_id = msg[2]

                if any(task_id in x for x in self.assigned_tasks.values()):
                    status = STATUS_GIVEN
                elif task_id in (x[0] for x in self.unassigned_tasks):
                    status = STATUS_HERE
                else:
                    status = STATUS_NONE

                self.task_socket.send_multipart([
                    address, STATUS_ANS, task_id, status
                ])

            # A task status set (task done) is received
            elif msg_type == STATUS_DONE:
                address = msg[0]
                task_id = msg[2]

                try:
                    self.assigned_tasks[address].discard(task_id)
                except KeyError:
                    pass

            elif msg_type == STATUS_UPDATE:
                address = msg[0]
                try:
                    tasks_ids = pickle.loads(msg[2])
                except:
                    self.logger.error("Could not unpickle status update message.")
                else:
                    self.assigned_tasks[address] = tasks_ids
                    self.status_times[address] = time.time()

            # Answer needing delivery
            elif msg_type == REPLY:
                self.logger.debug("Relaying")
                destination = msg[-1]
                origin = msg[0]
                self.task_socket.send_multipart([destination] + msg[1:] + [origin])

            # Shared variable to distribute
            elif msg_type == VARIABLE:
                address = msg[4]
                value = msg[3]
                key = msg[2]
                self.shared_variables[address].update(
                    {key: value},
                )
                self.info_socket.send_multipart([VARIABLE,
                                                key,
                                                value,
                                                address])

            # Initialize the variables of a new worker
            elif msg_type == INIT:
                address = msg[0]
                try:
                    self.processConfig(pickle.loads(msg[2]))
                except pickle.PickleError:
                    continue
                self.task_socket.send_multipart([
                    address,
                    pickle.dumps(self.config,
                                 pickle.HIGHEST_PROTOCOL),
                    pickle.dumps(self.shared_variables,
                                 pickle.HIGHEST_PROTOCOL),
                ])

                self.task_socket.send_multipart([
                    address,
                    pickle.dumps(self.cluster_available,
                                 pickle.HIGHEST_PROTOCOL),
                ])

            # Add a given broker to its fellow list
            elif msg_type == CONNECT:
                try:
                    connect_brokers = pickle.loads(msg[2])
                except pickle.PickleError:
                    self.logger.error("Could not understand CONNECT message.")
                    continue
                self.logger.info("Connecting to other brokers...")
                self.addBrokerList(connect_brokers)

            # Shutdown of this broker was requested
            elif msg_type == SHUTDOWN:
                self.logger.debug("SHUTDOWN command received.")
                self.shutdown()
                break
1270166
function getCall(channel, path, options) {
  var deadline;
  var host;
  var parent;
  var propagate_flags;
  var credentials;
  if (options) {
    deadline = options.deadline;
    host = options.host;
    parent = options.parent ? options.parent.call : undefined;
    propagate_flags = options.propagate_flags;
    credentials = options.credentials;
  }
  if (deadline === undefined) {
    deadline = Infinity;
  }
  var call = channel.createCall(path, deadline, host,
                                parent, propagate_flags);
  if (credentials) {
    call.setCredentials(credentials);
  }
  return call;
}
918984
def when_done(&block)
      call_block = false
      @job_lock.synchronize do
        if completed?
          call_block = true
        else
          @when_done_callbacks << block
        end
      end
      yield if call_block
    end
330600
def on_task_status(self, task):
        """"""
        if not self.interactive:
            super(OneScheduler, self).on_task_status(task)

        try:
            procesok = task['track']['process']['ok']
        except KeyError as e:
            logger.error("Bad status pack: %s", e)
            return None

        if procesok:
            ret = self.on_task_done(task)
        else:
            ret = self.on_task_failed(task)
        if task['track']['fetch'].get('time'):
            self._cnt['5m_time'].event((task['project'], 'fetch_time'),
                                       task['track']['fetch']['time'])
        if task['track']['process'].get('time'):
            self._cnt['5m_time'].event((task['project'], 'process_time'),
                                       task['track']['process'].get('time'))
        self.projects[task['project']].active_tasks.appendleft((time.time(), task))
        return ret
828878
def update(call_time, exclusive_time = nil)
      self.call_count += 1
      self.total_call_time += call_time
      self.total_exclusive_time += exclusive_time

      t = @scoped ? exclusive_time : call_time
      self.min_call_time = t if call_count == 0 || t < min_call_time
      self.max_call_time = t if t > max_call_time
    end
720886
public function onConstruct()
    {
        //early return on OPTIONS calls in dev, so they follow the correct spec and don't die for missing credentials
        if ($this->request->getMethod() == 'OPTIONS' && APPLICATION_ENV != 'production') {
            return;
        }

        $config = $this->getDI()->get('config');
        $auth = $this->getDI()->get('auth');

        switch ($config['security']) {
            case true:
                $token = $this->getAuthToken();

                // check for a valid session
                if ($auth->isLoggedIn($token)) {
                    // continue
                } else {
                    throw new HTTPException('Unauthorized, please authenticate first.', 401, [
                        'dev' => 'Must be authenticated to access.',
                        'code' => '30945680384502037'
                    ]);
                }
                break;

            case false:
                // if security is off, then create a fake user profile to trick the api
                // todo figure out a way to do this w/o this assumption
                // notice the specific requirement to a client application
                if ($auth->isLoggedIn('HACKYHACKERSON')) {
                    // continue
                } else {
                    throw new HTTPException('Security False is not loading a valid user.', 401, [
                        'dev' => 'The authenticator isn\'t loading a valid user.',
                        'code' => '23749873490704'
                    ]);
                }
                break;

            default:
                throw new HTTPException('Bad security value supplied', 500, ['code' => '280273409724075']);
                break;
        }

        // continue after security is worked out
        parent::onConstruct();
    }
700317
public void autoSchedulePipelinesFromRequestBuffer() {
        synchronized (autoScheduleMutex) {
            try {
                for (Entry<CaseInsensitiveString, BuildCause> entry : pipelineScheduleQueue.toBeScheduled().entrySet()) {
                    CaseInsensitiveString pipelineName = entry.getKey();
                    BuildCause buildCause = entry.getValue();

                    LOGGER.info("[Pipeline Schedule] Scheduling pipeline {} with build cause {}", pipelineName, buildCause);

                    long schedulingStartTime = System.currentTimeMillis();
                    Pipeline pipeline = schedulePipeline(pipelineName, buildCause);
                    long schedulingEndTime = System.currentTimeMillis();

                    if (pipeline != null) {
                        schedulingPerformanceLogger.scheduledPipeline(pipelineName, pipelineScheduleQueue.toBeScheduled().size(), schedulingStartTime, schedulingEndTime);
                    }
                }
            } catch (Throwable e) {
                LOGGER.error("[Pipeline Schedule] An exception occurred while scheduling the pipeline. {}", e);
            }
        }
    }
751434
private void waitForComponentToComeUp() {
        LOGGER.entering();
        for (int i = 0; i < 60; i++) {
            try {
                // Sleep for 3 seconds.
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
            if (getLauncher().isRunning()) {
                LOGGER.exiting();
                return;
            }
        }
        throw new IllegalStateException(String.format("%s can not be contacted.", getLocalServerComponent().getClass()
                .getSimpleName()));
    }
1181524
def call(severity, time, progname, msg)
      sprintf("%s: %s\n", time.strftime("%H:%M:%S"), hide_inputs(msg2str(msg)))
    end
505598
function done(error) {
    if (error) {
      errors.push(error);
    }
    if (--initializing <= 0) {
      if (errors && errors.length) {
        var errorResult = new Error('Errors occurred during initialization.');
        errorResult.initializationErrors = errors;
        callback(errorResult);
      } else {
        processPostInitializeQueue(postInitializeQueue, callback);
      }
    }
  }
309159
def on_finish(self):
        
        r = self.response
        r.request_time = time.time() - self.start_time
        if self.callback:
            self.callback(r)
134333
def on_put(self, req, resp, **kwargs):
        """"""
        validated = self.require_validated(req)
        return super().on_put(
            req, resp,
            handler=partial(self._update, validated=validated),
            **kwargs
        )