rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
self._ackqueue, self._pool, self._ack_handler, self._worker_handler, self._task_handler, | self._pool, self._worker_handler, self._task_handler, | def __init__(self, processes=None, initializer=None, initargs=(), maxtasksperchild=None, timeout=None, soft_timeout=None): self._setup_queues() self._taskqueue = Queue.Queue() self._cache = {} self._state = RUN self.timeout = timeout self.soft_timeout = soft_timeout self._maxtasksperchild = maxtasksperchild self._initi... |
args=(self._inqueue, self._outqueue, self._ackqueue, | args=(self._inqueue, self._outqueue, | def _create_worker_process(self): w = self.Process( target=worker, args=(self._inqueue, self._outqueue, self._ackqueue, self._initializer, self._initargs, self._maxtasksperchild), ) self._pool.append(w) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() return w |
return len(self._pool) < self._processes | if cleaned: for job in self._cache.values(): for worker_pid in job.worker_pids(): if worker_pid in cleaned: err = WorkerLostError("Worker exited prematurely.") job._set(None, (False, err)) continue return True return False | def _join_exited_workers(self): """Cleanup after any worker processes which have exited due to reaching their specified lifetime. Returns True if any workers were cleaned up. """ for i in reversed(range(len(self._pool))): worker = self._pool[i] if worker.exitcode is not None: # worker exited debug('cleaning up worker %... |
self._ackqueue = SimpleQueue() | def _setup_queues(self): from multiprocessing.queues import SimpleQueue self._inqueue = SimpleQueue() self._outqueue = SimpleQueue() self._ackqueue = SimpleQueue() self._quick_put = self._inqueue._writer.send self._quick_get = self._outqueue._reader.recv self._quick_get_ack = self._ackqueue._reader.recv | |
self._quick_get_ack = self._ackqueue._reader.recv | def _poll_result(timeout): if self._outqueue._reader.poll(timeout): return True, self._quick_get() return False, None self._poll_result = _poll_result | def _setup_queues(self): from multiprocessing.queues import SimpleQueue self._inqueue = SimpleQueue() self._outqueue = SimpleQueue() self._ackqueue = SimpleQueue() self._quick_put = self._inqueue._writer.send self._quick_get = self._outqueue._reader.recv self._quick_get_ack = self._ackqueue._reader.recv |
for p in self._pool: | for i, p in enumerate(self._pool): debug('joining worker %s/%s (%r)' % (i, len(self._pool), p, )) | def join(self): assert self._state in (CLOSE, TERMINATE) self._worker_handler.join() self._task_handler.join() self._result_handler.join() for p in self._pool: p.join() debug('after join()') |
debug('after join()') | def join(self): assert self._state in (CLOSE, TERMINATE) self._worker_handler.join() self._task_handler.join() self._result_handler.join() for p in self._pool: p.join() debug('after join()') | |
def _terminate_pool(cls, taskqueue, inqueue, outqueue, ackqueue, pool, ack_handler, worker_handler, task_handler, | def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, worker_handler, task_handler, | def _terminate_pool(cls, taskqueue, inqueue, outqueue, ackqueue, pool, ack_handler, worker_handler, task_handler, result_handler, cache, timeout_handler): |
ack_handler.terminate() ackqueue.put(None) | def _terminate_pool(cls, taskqueue, inqueue, outqueue, ackqueue, pool, ack_handler, worker_handler, task_handler, result_handler, cache, timeout_handler): | |
debug('joining ack handler') ack_handler.join(1e100) | def _terminate_pool(cls, taskqueue, inqueue, outqueue, ackqueue, pool, ack_handler, worker_handler, task_handler, result_handler, cache, timeout_handler): | |
self._accepted = False self._accept_pid = None self._time_accepted = None | def __init__(self, cache, callback, accept_callback=None, timeout_callback=None, error_callback=None): self._cond = threading.Condition(threading.Lock()) self._job = job_counter.next() self._cache = cache self._accepted = False self._accept_pid = None self._time_accepted = None self._ready = False self._callback = call... | |
self._accept_callback = accept_callback | def __init__(self, cache, callback, accept_callback=None, timeout_callback=None, error_callback=None): self._cond = threading.Condition(threading.Lock()) self._job = job_counter.next() self._cache = cache self._accepted = False self._accept_pid = None self._time_accepted = None self._ready = False self._callback = call... | |
del self._cache[self._job] | self._cache.pop(self._job, None) | def _set(self, i, obj): self._success, self._value = obj if self._callback and self._success: self._callback(self._value) if self._errback and not self._success: self._errback(self._value) self._cond.acquire() try: self._ready = True self._cond.notify() finally: self._cond.release() if self._accepted: del self._cache[s... |
self._accept_pid = pid | self._worker_pid = pid | def _ack(self, i, time_accepted, pid): self._accepted = True self._time_accepted = time_accepted self._accept_pid = pid if self._accept_callback: self._accept_callback() if self._ready: del self._cache[self._job] |
del self._cache[self._job] | self._cache.pop(self._job, None) | def _ack(self, i, time_accepted, pid): self._accepted = True self._time_accepted = time_accepted self._accept_pid = pid if self._accept_callback: self._accept_callback() if self._ready: del self._cache[self._job] |
del self._cache[self._job] | if self._accepted: self._cache.pop(self._job, None) | def _set(self, i, success_result): success, result = success_result if success: self._value[i*self._chunksize:(i+1)*self._chunksize] = result self._number_left -= 1 if self._number_left == 0: if self._callback: self._callback(self._value) del self._cache[self._job] self._cond.acquire() try: self._ready = True self._con... |
self._ackqueue = Queue.Queue() | def _setup_queues(self): self._inqueue = Queue.Queue() self._outqueue = Queue.Queue() self._ackqueue = Queue.Queue() self._quick_put = self._inqueue.put self._quick_get = self._outqueue.get self._quick_get_ack = self._ackqueue.get | |
self._quick_get_ack = self._ackqueue.get | def _poll_result(timeout): try: return True, self._quick_get(timeout=timeout) except Queue.Empty: return False, None self._poll_result = _poll_result | def _setup_queues(self): self._inqueue = Queue.Queue() self._outqueue = Queue.Queue() self._ackqueue = Queue.Queue() self._quick_put = self._inqueue.put self._quick_get = self._outqueue.get self._quick_get_ack = self._ackqueue.get |
def maybe_conn_error(self, predicate, fun): if predicate: try: fun() except Exception: pass | def maybe_conn_error(self, fun): try: fun() except Exception: pass | def maybe_conn_error(self, predicate, fun): if predicate: try: fun() except Exception: # TODO kombu.connection_errors pass |
self.task_consumer = self.maybe_conn_error(self.task_consumer, self.task_consumer.close) | if self.task_consumer: self.task_consumer = \ self.maybe_conn_error(self.task_consumer.close) | def close_connection(self): self.logger.debug("CarrotListener: " "Closing consumer channel...") self.task_consumer = self.maybe_conn_error(self.task_consumer, self.task_consumer.close) self.logger.debug("CarrotListener: " "Closing connection to broker...") self.connection = self.maybe_conn_error(self.connection, self.c... |
self.connection = self.maybe_conn_error(self.connection, self.connection.close) | if self.connection: self.connection = self.maybe_conn_error(self.connection.close) | def close_connection(self): self.logger.debug("CarrotListener: " "Closing consumer channel...") self.task_consumer = self.maybe_conn_error(self.task_consumer, self.task_consumer.close) self.logger.debug("CarrotListener: " "Closing connection to broker...") self.connection = self.maybe_conn_error(self.connection, self.c... |
self.maybe_conn_error(self.task_consumer, self.task_consumer.cancel) | if self.task_consumer: self.maybe_conn_error(self.task_consumer.cancel) | def stop_consumers(self, close=True): """Stop consuming.""" if not self._state == RUN: return self._state = CLOSE |
self.event_dispatcher = self.maybe_conn_error( self.event_dispatcher, self.event_dispatcher.close) | self.event_dispatcher = \ self.maybe_conn_error(self.event_dispatcher.close) | def stop_consumers(self, close=True): """Stop consuming.""" if not self._state == RUN: return self._state = CLOSE |
self.publisher.send(Event(type, hostname=self.hostname, **fields)) | try: self.publisher.send(event) except Exception, exc: self._outbound_buffer.append((event, exc)) | def send(self, type, **fields): """Send event. |
cp -r '%s/*' . && \ | cp -r %s/* . && \ | def ghdocs(options): builtdocs = sphinx_builddir(options) sh("sphinx-to-github", cwd=builtdocs) sh("git checkout gh-pages && \ cp -r '%s/*' . && \ git commit . -m 'Rendered documentation for Github Pages.' && \ git push origin gh-pages && \ git checkout master" % builtdocs) |
current_loader.on_worker_init() | current_loader().on_worker_init() | def run_clockservice(loglevel=conf.CELERYBEAT_LOG_LEVEL, logfile=conf.CELERYBEAT_LOG_FILE, schedule=conf.CELERYBEAT_SCHEDULE_FILENAME, **kwargs): """Starts the celerybeat clock server.""" print("celerybeat %s is starting." % __version__) # Setup logging if not isinstance(loglevel, int): loglevel = conf.LOG_LEVELS[log... |
class Worker(Thing): | class Worker(Element): """Worker State.""" | def update(self, fields, **extra): for field_name, field_value in dict(fields, **extra).items(): setattr(self, field_name, field_value) |
class Task(Thing): | class Task(Element): """Task State.""" | def alive(self): return (self.heartbeats and time.time() < self.heartbeats[0] + HEARTBEAT_EXPIRE) |
return platform.set_process_title(prog, info=info) | return platforms.set_process_title(prog, info=info) | def set_process_status(self, prog, info=""): prog = "%s:%s" % (self.prog_name, prog) info = "%s %s" % (info, platforms.strargv(sys.argv)) return platform.set_process_title(prog, info=info) |
counter = count(1).next | counter = 1 inc_counter = count(2).next | def format_declare_queue(ret): return "ok. queue:%s messages:%s consumers:%s." % ret |
return parts[0], " ".join(parts[1:]), line | if parts: return parts[0], " ".join(parts[1:]), line return "", "", line | def parseline(self, line): """Parse input line. |
return self.prompt_fmt % self.counter() | return self.prompt_fmt % self.counter | def prompt(self): return self.prompt_fmt % self.counter() |
def upgrade_and_install(install): | class upgrade_and_install(install): | def upgrade_and_install(install): def run(self, *args, **kwargs): Upgrade().run() install.run(self, *args, **kwargs) |
Examples:: >>> remaining(datetime.now(), ends_in=timedelta(seconds=30)) '0:0:29.999948' >>> str(remaining(datetime.now() - timedelta(minutes=29), ends_in=timedelta(hours=2))) '1:30:59.999938' >>> str(remaining(datetime.now() - timedelta(minutes=29), ends_in=timedelta(hours=2), relative=False)) '1:11:18.458437' | def remaining(start, ends_in, now=None, relative=True): """Calculate the remaining time for a start date and a timedelta. E.g. "how many seconds left for 30 seconds after ``start``?" :param start: Start :class:`datetime.datetime`. :param ends_in: The end delta as a :class:`datetime.timedelta`. :keyword relative: If ... | |
debug('repopulating pool') | def _repopulate_pool(self): """Bring the number of pool processes up to the specified number, for use after reaping workers which have exited. """ debug('repopulating pool') for i in range(self._processes - len(self._pool)): if self._state != RUN: return self._create_worker_process() debug('added worker') | |
self.assertGreater(states.SUCCESS, states.PENDING) self.assertGreater(states.FAILURE, states.RECEIVED) self.assertGreater(states.REVOKED, states.STARTED) self.assertGreater(states.SUCCESS, states.state("CRASHED")) self.assertGreater(states.FAILURE, states.state("CRASHED")) self.assertFalse(states.REVOKED > states.state... | self.assertGreater(state(states.SUCCESS), state(states.PENDING)) self.assertGreater(state(states.FAILURE), state(states.RECEIVED)) self.assertGreater(state(states.REVOKED), state(states.STARTED)) self.assertGreater(state(states.SUCCESS), state("CRASHED")) self.assertGreater(state(states.FAILURE), state("CRASHED")) self... | def test_gt(self): self.assertGreater(states.SUCCESS, states.PENDING) self.assertGreater(states.FAILURE, states.RECEIVED) self.assertGreater(states.REVOKED, states.STARTED) self.assertGreater(states.SUCCESS, states.state("CRASHED")) self.assertGreater(states.FAILURE, states.state("CRASHED")) self.assertFalse(states.REV... |
def test_freeze_thaw__buffering(self): s = State() r = ev_snapshot(s) s.freeze(buffer=True) self.assertTrue(s._buffering) r.play() self.assertStateEmpty(s) self.assertTrue(s.buffer) s.thaw() self.assertState(s) self.assertFalse(s.buffer) | def test_freeze_thaw__buffering(self): s = State() r = ev_snapshot(s) s.freeze(buffer=True) self.assertTrue(s._buffering) | |
def test_thaw__no_replay(self): s = State() r = ev_snapshot(s) s.freeze(buffer=True) r.play() s.thaw(replay=False) self.assertFalse(s.buffer) self.assertStateEmpty(s) | def test_thaw__no_replay(self): s = State() r = ev_snapshot(s) s.freeze(buffer=True) | |
r.play() self.assertStateEmpty(s) s.freeze_while(work) self.assertState(s) def test_freeze_thaw__not_buffering(self): s = State() r = ev_snapshot(s) s.freeze(buffer=False) self.assertFalse(s._buffering) r.play() s.thaw(replay=True) self.assertFalse(s.buffer) self.assertStateEmpty(s) | pass s.freeze_while(work, clear_after=True) self.assertFalse(s.event_count) | def work(): r.play() self.assertStateEmpty(s) |
if task_id in self._cache: cached_meta = self._cache[task_id] | cached_meta = self._cache.get(task_id) | def wait_for(self, task_id, timeout=None, cache=True): if task_id in self._cache: cached_meta = self._cache[task_id] |
def import_from_cwd(self, module, imp=import_module): | def import_from_cwd(self, module, imp=None): | def import_from_cwd(self, module, imp=import_module): """Import module, but make sure it finds modules located in the current directory. |
presult2 = task.apply_async(t1, kwargs=dict(name="George Costanza"), | presult2 = apply_async(t1, kwargs=dict(name="George Costanza"), | def test_regular_task(self): T1 = self.createTaskCls("T1", "c.unittest.t.t1") self.assertIsInstance(T1(), T1) self.assertTrue(T1().run()) self.assertTrue(callable(T1()), "Task class is callable()") self.assertTrue(T1()(), "Task class runs run() when called") |
task.apply_async(t1) | apply_async(t1) | def test_regular_task(self): T1 = self.createTaskCls("T1", "c.unittest.t.t1") self.assertIsInstance(T1(), T1) self.assertTrue(T1().run()) self.assertTrue(callable(T1()), "Task class is callable()") self.assertTrue(T1()(), "Task class runs run() when called") |
if multiprocessing.current_process().name == 'MainProcess': worker.logger.warn("celeryd: Cold shutdown (%s)" % \ (current_process().name)) | process_name = multiprocessing.current_process().name if process_name == "MainProcess": worker.logger.warn("celeryd: Cold shutdown (%s)" % ( process_name)) | def _stop(signum, frame): if multiprocessing.current_process().name == 'MainProcess': worker.logger.warn("celeryd: Cold shutdown (%s)" % \ (current_process().name)) worker.terminate() raise SystemExit() |
route = routes.MapRoute({"celery.ping": "foo"}) | route = routes.MapRoute({"celery.ping": {"queue": "foo"}}) | def test_route_for_task_expanded_route(self): expand = E(conf.QUEUES) route = routes.MapRoute({"celery.ping": "foo"}) self.assertDictContainsSubset(a_queue, expand(route.route_for_task("celery.ping"))) self.assertIsNone(route.route_for_task("celery.awesome")) |
route = routes.MapRoute({"a": "x"}) | route = routes.MapRoute({"a": {"queue": "x"}}) | def test_expand_route_not_found(self): expand = E(conf.QUEUES) route = routes.MapRoute({"a": "x"}) self.assertRaises(QueueNotFound, expand, route.route_for_task("a")) |
R = routes.prepare(({"celery.ping": "bar"}, {"celery.ping": "foo"})) | R = routes.prepare(({"celery.ping": {"queue": "bar"}}, {"celery.ping": {"queue": "foo"}})) | def test_lookup_takes_first(self): R = routes.prepare(({"celery.ping": "bar"}, {"celery.ping": "foo"})) router = routes.Router(R, conf.QUEUES) self.assertDictContainsSubset(b_queue, router.route({}, "celery.ping", args=[1, 2], kwargs={})) |
R = routes.prepare(({"celery.xaza": "bar"}, {"celery.ping": "foo"})) | R = routes.prepare(({"celery.xaza": {"queue": "bar"}}, {"celery.ping": {"queue": "foo"}})) | def test_lookup_paths_traversed(self): R = routes.prepare(({"celery.xaza": "bar"}, {"celery.ping": "foo"})) router = routes.Router(R, conf.QUEUES) self.assertDictContainsSubset(a_queue, router.route({}, "celery.ping", args=[1, 2], kwargs={})) self.assertEqual(router.route({}, "celery.poza"), {}) |
import warnings | def run(self): print("celery@%s v%s is starting." % (self.hostname, celery.__version__)) | |
"""Execute this task at once, by blocking until the task | """Execute this task locally, by blocking until the task | def apply(self, args=None, kwargs=None, **options): """Execute this task at once, by blocking until the task has finished executing. |
self.client = memcache.Client(servers, **options) | def __init__(self, expires=conf.TASK_RESULT_EXPIRES, backend=conf.CELERY_CACHE_BACKEND, options={}, **kwargs): super(CacheBackend, self).__init__(self, **kwargs) if isinstance(expires, timedelta): expires = timeutils.timedelta_seconds(expires) self.expires = expires self.options = dict(conf.CELERY_CACHE_BACKEND_OPTIONS... | |
>>> result = ts.run() | >>> result = ts.apply_async() | def apply_async(self, connect_timeout=conf.BROKER_CONNECTION_TIMEOUT): """Run all tasks in the taskset. |
return remote_task.run().join(timeout=timeout) | return remote_task.apply_async().join(timeout=timeout) | def map(cls, func, args, timeout=None): """Distribute processing of the arguments and collect the results.""" remote_task = cls.remote_execute(func, args) return remote_task.run().join(timeout=timeout) |
self.publisher.send(Event(type, hostname=self.hostname)) | self.publisher.send(Event(type, hostname=self.hostname, **fields)) | def send(self, type, **fields): """Send event. |
numbers represent the units of time that the crontab needs to run on. | numbers represent the units of time that the crontab needs to run on:: | def is_due(self, last_run_at): """Returns tuple of two items ``(is_due, next_time_to_run)``, where next time to run is in seconds. |
cam = ModelCamera(state) cam.install() | def eventtop(): sys.stderr.write("-> celeryev: starting capture...\n") state = State() cam = ModelCamera(state) cam.install() display = CursesMonitor(state) display.init_screen() refresher = DisplayThread(display) refresher.start() conn = establish_connection() recv = EventReceiver(conn, handlers={"*": state.event}) tr... | |
returns="%d messages deleted"), | returns=format_declare_queue), | def dump_message(message): if message is None: return "No messages in queue. basic.publish something." return {"body": message.body, "properties": message.properties, "delivery_info": message.delivery_info} |
("if_empty", bool, "no")), "queue.purge": Spec(("queue", str), returns="%d messages deleted"), | ("if_empty", bool, "no"), returns="ok. %d messages deleted."), "queue.purge": Spec(("queue", str), returns="ok. %d messages deleted."), | def dump_message(message): if message is None: return "No messages in queue. basic.publish something." return {"body": message.body, "properties": message.properties, "delivery_info": message.delivery_info} |
def multi_args(p, cmd="celeryd", prefix="", suffix=""): | def multi_args(p, cmd="celeryd", cmd_suffix="", prefix="", suffix=""): | def multi_args(p, cmd="celeryd", prefix="", suffix=""): names = p.values options = dict(p.options) ranges = len(names) == 1 if ranges: names = map(str, range(1, int(names[0]) + 1)) prefix = "celery" cmd = options.pop("--cmd", cmd) hostname = options.pop("--hostname", options.pop("-n", socket.gethostname())) prefix = op... |
for opt, value in p.optmerge(name, options).items()) | for opt, value in p.optmerge(name, options).items()) + \ " " + expand(cmd_suffix) | def multi_args(p, cmd="celeryd", prefix="", suffix=""): names = p.values options = dict(p.options) ranges = len(names) == 1 if ranges: names = map(str, range(1, int(names[0]) + 1)) prefix = "celery" cmd = options.pop("--cmd", cmd) hostname = options.pop("--hostname", options.pop("-n", socket.gethostname())) prefix = op... |
for line in task.traceback.split("\n"): | result = getattr(task, "result", None) or getattr(task, "exception", None) for line in wrap(result, mx - 2): | def alert_callback(my, mx): y = count(2).next task = self.state.tasks[self.selected_task] for line in task.traceback.split("\n"): self.win.addstr(y(), 3, line) |
info["result"] = abbr(result["info"], 16) | info["result"] = abbr(info["result"], 16) | def draw(self): win = self.win self.handle_keypress() x = 3 y = blank_line = count(2).next my, mx = win.getmaxyx() win.erase() win.bkgd(" ", curses.color_pair(1)) win.border() win.addstr(1, x, self.greet, curses.A_DIM | curses.color_pair(5)) blank_line() win.addstr(y(), x, self.format_row("UUID", "TASK", "WORKER", "TIM... |
(last_run_at.hour < max(self.hour) or execute_this_hour)) | last_run_at.hour < max(self.hour)) | def remaining_estimate(self, last_run_at): """Returns when the periodic task should run next as a timedelta.""" weekday = last_run_at.isoweekday() execute_this_hour = (weekday in self.day_of_week and last_run_at.hour in self.hour and last_run_at.minute < max(self.minute)) |
iso_next_day = min([day for day in self.day_of_week if day > weekday] or self.day_of_week) add_week = iso_next_day == weekday | next_day = min([day for day in self.day_of_week if day > weekday] or self.day_of_week) add_week = next_day == weekday | def remaining_estimate(self, last_run_at): """Returns when the periodic task should run next as a timedelta.""" weekday = last_run_at.isoweekday() execute_this_hour = (weekday in self.day_of_week and last_run_at.hour in self.hour and last_run_at.minute < max(self.minute)) |
weekday=(iso_next_day - 1) % 7, | weekday=(next_day - 1) % 7, | def remaining_estimate(self, last_run_at): """Returns when the periodic task should run next as a timedelta.""" weekday = last_run_at.isoweekday() execute_this_hour = (weekday in self.day_of_week and last_run_at.hour in self.hour and last_run_at.minute < max(self.minute)) |
except (KeyError, AttributeError), exc: | except (KeyError, AttributeError): | def run(self): debug('ack handler starting') get = self.get cache = self.cache |
debug('result handler ignoring extra sentinel') | debug('ack handler ignoring extra sentinel') | def run(self): debug('ack handler starting') get = self.get cache = self.cache |
except KeyError: | except (KeyError, AttributeError): | def run(self): debug('ack handler starting') get = self.get cache = self.cache |
if not self.running: | if not self.running and not self.is_alive(): | def enter(self, entry, eta, priority=None): if not self.running: self.start() return self.schedule.enter(entry, eta, priority) |
loader, DEFAULT_LOADER_CLASS_NAME))) return loader, DEFAULT_LOADER_CLASS_NAME | loader, _DEFAULT_LOADER_CLASS_NAME))) return loader, _DEFAULT_LOADER_CLASS_NAME | def resolve_loader(loader): loader = LOADER_ALIASES.get(loader, loader) loader_module_name, _, loader_cls_name = rpartition(loader, ".") if first_letter(loader_cls_name) not in string.uppercase: warnings.warn(DeprecationWarning( "CELERY_LOADER now needs loader class name, e.g. %s.%s" % ( loader, DEFAULT_LOADER_CLASS_NA... |
def utf8dict(self, tup): | def utf8dict(tup): | def utf8dict(self, tup): """With a dict's items() tuple return a new dict with any utf-8 keys/values encoded.""" return dict((key.encode("utf-8"), maybe_utf8(value)) for key, value in tup) |
return self._request("dump_registered_tasks") | return self._request("dump_tasks") | def registered_tasks(self): return self._request("dump_registered_tasks") |
:returns: :class:`celery.result.AsyncResult`. | :returns :class:`celery.result.AsyncResult`: | def delay_task(task_name, *args, **kwargs): """Delay a task for execution by the ``celery`` daemon. :param task_name: the name of a task registered in the task registry. :param \*args: positional arguments to pass on to the task. :param \*\*kwargs: keyword arguments to pass on to the task. :raises celery.exceptions.N... |
self.options = dict(conf.CACHE_BACKEND_OPTIONS, options) | self.options = dict(conf.CACHE_BACKEND_OPTIONS, **options) | def __init__(self, expires=conf.TASK_RESULT_EXPIRES, backend=conf.CACHE_BACKEND, options={}, **kwargs): super(CacheBackend, self).__init__(self, **kwargs) if isinstance(expires, timedelta): expires = timeutils.timedelta_seconds(expires) self.expires = expires self.options = dict(conf.CACHE_BACKEND_OPTIONS, options) sel... |
arg_name, arg_type = self.args[index] | arg_info = self.args[index] arg_type = arg_info[1] | def coerce(self, index, value): """Coerce value for argument at index. |
router = routes.Router(R, conf.QUEUES, create_missing=True) | router = routes.Router(R, app_or_default().conf.CELERY_QUEUES, create_missing=True) | def test_expands_queue_in_options(self): R = routes.prepare(()) router = routes.Router(R, conf.QUEUES, create_missing=True) # apply_async forwards all arguments, even exchange=None etc, # so need to make sure it's merged correctly. route = router.route({"queue": "testq", "exchange": None, "routing_key": None, "immediat... |
_, mx = self.win.getmaxyx() return mx - BORDER_SPACING | _, mx = self.win.getmaxyx() return mx - BORDER_SPACING @property def display_height(self): my, _ = self.win.getmaxyx() return my - 10 | def display_width(self): _, mx = self.win.getmaxyx() return mx - BORDER_SPACING |
x = 3 | x = LEFT_BORDER_OFFSET | def draw(self): win = self.win self.handle_keypress() x = 3 y = blank_line = count(2).next my, mx = win.getmaxyx() win.erase() win.bkgd(" ", curses.color_pair(1)) win.border() win.addstr(1, x, self.greet, curses.A_DIM | curses.color_pair(5)) blank_line() win.addstr(y(), x, self.format_row("UUID", "TASK", "WORKER", "TIM... |
for uuid, task in tasks: | for row, (uuid, task) in enumerate(tasks): if row > self.display_height: break | def draw(self): win = self.win self.handle_keypress() x = 3 y = blank_line = count(2).next my, mx = win.getmaxyx() win.erase() win.bkgd(" ", curses.color_pair(1)) win.border() win.addstr(1, x, self.greet, curses.A_DIM | curses.color_pair(5)) blank_line() win.addstr(y(), x, self.format_row("UUID", "TASK", "WORKER", "TIM... |
state_color = self.state_colors.get(task.state) attr = curses.A_NORMAL if task.uuid == self.selected_task: attr = curses.A_STANDOUT timestamp = datetime.fromtimestamp( task.timestamp or time.time()) timef = timestamp.strftime("%H:%M:%S") line = self.format_row(uuid, task.name, task.worker.hostname, timef, task.state) | def draw(self): win = self.win self.handle_keypress() x = 3 y = blank_line = count(2).next my, mx = win.getmaxyx() win.erase() win.bkgd(" ", curses.color_pair(1)) win.border() win.addstr(1, x, self.greet, curses.A_DIM | curses.color_pair(5)) blank_line() win.addstr(y(), x, self.format_row("UUID", "TASK", "WORKER", "TIM... | |
win.addstr(lineno, x, line, attr) if state_color: win.addstr(lineno, len(line) - STATE_WIDTH + BORDER_SPACING - 1, task.state, state_color | attr) if task.ready: task.visited = time.time() | self.display_task_row(lineno, task) | def draw(self): win = self.win self.handle_keypress() x = 3 y = blank_line = count(2).next my, mx = win.getmaxyx() win.erase() win.bkgd(" ", curses.color_pair(1)) win.border() win.addstr(1, x, self.greet, curses.A_DIM | curses.color_pair(5)) blank_line() win.addstr(y(), x, self.format_row("UUID", "TASK", "WORKER", "TIM... |
logger = self.app.log.get_default_logger(name="celery.beat") | def setup_logging(self): handled = self.app.log.setup_logging_subsystem(loglevel=self.loglevel, logfile=self.logfile) if not handled: logger = self.app.log.get_default_logger(name="celery.beat") if self.redirect_stdouts: self.app.log.redirect_stdouts_to_logger(logger, loglevel=self.redirect_stdouts_level) return logger | |
INSTALLED_APPS = "djcelery" | import djcelery djcelery.setup_loader() INSTALLED_APPS = ("djcelery", ) to settings.py. | def _display_help(): import sys sys.stderr.write(""" |
http://github.com/ask/celery/tree/djangofree/Changelog | http://celeryproject.org/docs/changelog.html | def _display_help(): import sys sys.stderr.write(""" |
return self == other | return other == self.task_id def __copy__(self): return self.__class__(self.task_id, backend=self.backend) | def __eq__(self, other): if isinstance(other, self.__class__): return self.task_id == other.task_id return self == other |
def __init__(self, task_id): super(AsyncResult, self).__init__(task_id, backend=default_backend) | def __init__(self, task_id, backend=None): backend = backend or default_backend super(AsyncResult, self).__init__(task_id, backend) | def __init__(self, task_id): super(AsyncResult, self).__init__(task_id, backend=default_backend) |
results = dict((subtask.task_id, subtask.__class__(subtask.task_id)) | pending = list(self.subtasks) results = dict((subtask.task_id, copy(subtask)) | def iterate(self): """Iterate over the return values of the tasks as they finish one by one. |
while results: for task_id, pending_result in results.items(): if pending_result.status == states.SUCCESS: results.pop(task_id, None) yield pending_result.result elif pending_result.status == states.FAILURE: raise pending_result.result | while pending: for task_id in pending: result = results[task_id] if result.status == states.SUCCESS: try: pending.remove(task_id) except ValueError: pass yield result.result elif result.status == states.FAILURE: raise result.result | def iterate(self): """Iterate over the return values of the tasks as they finish one by one. |
:meth:`calculate_key(target)` method applied to the target | ``calculate_key(target)`` method applied to the target | def safe_ref(target, on_delete=None): """Return a *safe* weak reference to a callable target :param target: the object to be weakly referenced, if it's a bound method reference, will create a :class:`BoundMethodWeakref`, otherwise creates a simple :class:`weakref.ref`. :keyword on_delete: if provided, will have a har... |
if getattr(self.settings, "DEBUG", False): warnings.warn("Using settings.DEBUG leads to a memory leak, " "never use this setting in a production environment!") | def run(self): self.init_loader() self.init_queues() self.worker_init() self.redirect_stdouts_to_logger() print("celery@%s v%s is starting." % (self.hostname, __version__)) | |
themes = [Theme('simplui-1.0.4/themes/macos'),\ Theme('simplui-1.0.4/themes/pywidget')] | path=sys.path[0]+'/' themes = [Theme(path+'simplui-1.0.4/themes/macos'),\ Theme(path+'simplui-1.0.4/themes/pywidget')] | def button_action(button): name=button._get_text() if name=="LoadRobot": if not noTkinter: root = Tkinter.Tk() root.withdraw() filename = tkFileDialog.askopenfilename() root.destroy() self.loadRobot(filename) else: warnings.warn("Tkinter not available") elif name=="LoadMotion": if not noTkinter: root = Tkinter.Tk() roo... |
glMaterialfv(GL_FRONT_AND_BACK,\ GL_AMBIENT_AND_DIFFUSE, COLOR_GREEN) glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, COLOR_GREEN) glPushMatrix() | def on_draw_scene(self): self.w2.clear() self.count+=1 glLoadIdentity() p=self.camera.position f=self.camera.lookat u=self.camera.up gluLookAt(p[0],p[1],p[2],f[0],f[1],f[2],u[0],u[1],u[2]) draw_floor() | |
glPopMatrix() | def on_draw_scene(self): self.w2.clear() self.count+=1 glLoadIdentity() p=self.camera.position f=self.camera.lookat u=self.camera.up gluLookAt(p[0],p[1],p[2],f[0],f[1],f[2],u[0],u[1],u[2]) draw_floor() | |
warnings.warn( error ) | warnings.warn("something wrong %s"%error ) glPopMatrix() | def on_draw_scene(self): self.w2.clear() self.count+=1 glLoadIdentity() p=self.camera.position f=self.camera.lookat u=self.camera.up gluLookAt(p[0],p[1],p[2],f[0],f[1],f[2],u[0],u[1],u[2]) draw_floor() |
glPopMatrix() | def draw_skeleton(robot): # draw_skeleton a sphere at each mobile joint if robot.jointType in ["free","rotate"]: pos=robot.globalTransformation[0:3,3] glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) sphere = gluNewQuadric() gluSphere(sphere,0.01,10,10) glPopMatrix() if robot.jointType=="rotate": parent=robot.paren... | |
child.draw_skeleton() | draw_skeleton(child) | def draw_skeleton(robot): # draw_skeleton a sphere at each mobile joint if robot.jointType in ["free","rotate"]: pos=robot.globalTransformation[0:3,3] glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) sphere = gluNewQuadric() gluSphere(sphere,0.01,10,10) glPopMatrix() if robot.jointType=="rotate": parent=robot.paren... |
from collections import deque | self.joint_list=[] self.mesh_list=[] | def init(self): if self.type=="baseNode": self.update() from collections import deque pile=deque() pile.append(self) while not len(pile)==0: an_element=pile.pop() |
def __init__(self,translation=[0,0,0],rotation=[1,0,0,0],children=[]): | def __init__(self): | def __init__(self,translation=[0,0,0],rotation=[1,0,0,0],children=[]): self.type= "baseNode" self.jointType="" self.name=None self.id=-999 self.translation=translation self.rotation=rotation self.children=children self.parent=None self.localTransformation=np.zeros([4,4]) self.globalTransformation=np.zeros([4,4]) self.j... |
self.translation=translation self.rotation=rotation self.children=children | self.translation=[0,0,0] self.rotation=[1,0,0,0] self.children=[] | def __init__(self,translation=[0,0,0],rotation=[1,0,0,0],children=[]): self.type= "baseNode" self.jointType="" self.name=None self.id=-999 self.translation=translation self.rotation=rotation self.children=children self.parent=None self.localTransformation=np.zeros([4,4]) self.globalTransformation=np.zeros([4,4]) self.j... |
self.joint_list=[] | self.joint_list=list() | def __init__(self,translation=[0,0,0],rotation=[1,0,0,0],children=[]): self.type= "baseNode" self.jointType="" self.name=None self.id=-999 self.translation=translation self.rotation=rotation self.children=children self.parent=None self.localTransformation=np.zeros([4,4]) self.globalTransformation=np.zeros([4,4]) self.j... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.