Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def create_packages_archive(packages, filename):
import tarfile
tar = tarfile.open(filename, "w")
def add(src, dst):
logger.debug('adding to tar: %s -> %s', src, dst)
tar.add(src, dst)
def add_files_for_package(sub_package_path, root_pa... | [
"\n Create a tar archive which will contain the files for the packages listed in packages.\n "
] |
Please provide a description of the function:def flatten(sequence):
for item in sequence:
if hasattr(item, "__iter__") and not isinstance(item, str) and not isinstance(item, bytes):
for i in item:
yield i
else:
yield item | [
"\n A simple generator which flattens a sequence.\n\n Only one level is flattened.\n\n .. code-block:: python\n\n (1, (2, 3), 4) -> (1, 2, 3, 4)\n\n "
] |
Please provide a description of the function:def run_and_track_hadoop_job(arglist, tracking_url_callback=None, env=None):
logger.info('%s', subprocess.list2cmdline(arglist))
def write_luigi_history(arglist, history):
history_filename = configuration.get_config().get('core', 'history-filen... | [
"\n Runs the job by invoking the command from the given arglist.\n Finds tracking urls from the output and attempts to fetch errors using those urls if the job fails.\n Throws HadoopJobError with information about the error\n (including stdout and stderr from the process)\n on failure and returns nor... |
Please provide a description of the function:def fetch_task_failures(tracking_url):
import mechanize
timeout = 3.0
failures_url = tracking_url.replace('jobdetails.jsp', 'jobfailures.jsp') + '&cause=failed'
logger.debug('Fetching data from %s', failures_url)
b = mechanize.Browser()
b.open(fa... | [
"\n Uses mechanize to fetch the actual task logs from the task tracker.\n\n This is highly opportunistic, and we might not succeed.\n So we set a low timeout and hope it works.\n If it does not, it's not the end of the world.\n\n TODO: Yarn has a REST API that we should probably use instead:\n htt... |
Please provide a description of the function:def _get_pool(self):
if self.pool:
return self.pool
if hadoop().pool:
return hadoop().pool | [
" Protected method "
] |
Please provide a description of the function:def job_runner(self):
# We recommend that you define a subclass, override this method and set up your own config
outputs = luigi.task.flatten(self.output())
for output in outputs:
if not isinstance(output, luigi.contrib.hdfs.HdfsT... | [
"\n Get the MapReduce runner for this job.\n\n If all outputs are HdfsTargets, the DefaultHadoopJobRunner will be used.\n Otherwise, the LocalJobRunner which streams all data through the local machine\n will be used (great for testing).\n "
] |
Please provide a description of the function:def writer(self, outputs, stdout, stderr=sys.stderr):
for output in outputs:
try:
output = flatten(output)
if self.data_interchange_format == "json":
# Only dump one json string, and skip anothe... | [
"\n Writer format is a method which iterates over the output records\n from the reducer and formats them for output.\n\n The default implementation outputs tab separated items.\n "
] |
Please provide a description of the function:def incr_counter(self, *args, **kwargs):
threshold = kwargs.get("threshold", self.batch_counter_default)
if len(args) == 2:
# backwards compatibility with existing hadoop jobs
group_name, count = args
key = (group_... | [
"\n Increments a Hadoop counter.\n\n Since counters can be a bit slow to update, this batches the updates.\n "
] |
Please provide a description of the function:def _flush_batch_incr_counter(self):
for key, count in six.iteritems(self._counter_dict):
if count == 0:
continue
args = list(key) + [count]
self._incr_counter(*args)
self._counter_dict[key] = 0 | [
"\n Increments any unflushed counter values.\n "
] |
Please provide a description of the function:def _incr_counter(self, *args):
if len(args) == 2:
# backwards compatibility with existing hadoop jobs
group_name, count = args
print('reporter:counter:%s,%s' % (group_name, count), file=sys.stderr)
else:
... | [
"\n Increments a Hadoop counter.\n\n Note that this seems to be a bit slow, ~1 ms\n\n Don't overuse this function by updating very frequently.\n "
] |
Please provide a description of the function:def dump(self, directory=''):
with self.no_unpicklable_properties():
file_name = os.path.join(directory, 'job-instance.pickle')
if self.__module__ == '__main__':
d = pickle.dumps(self)
module_name = os.... | [
"\n Dump instance to file.\n "
] |
Please provide a description of the function:def _map_input(self, input_stream):
for record in self.reader(input_stream):
for output in self.mapper(*record):
yield output
if self.final_mapper != NotImplemented:
for output in self.final_mapper():
... | [
"\n Iterate over input and call the mapper for each item.\n If the job has a parser defined, the return values from the parser will\n be passed as arguments to the mapper.\n\n If the input is coded output from a previous run,\n the arguments will be splitted in key and value.\n ... |
Please provide a description of the function:def _reduce_input(self, inputs, reducer, final=NotImplemented):
for key, values in groupby(inputs, key=lambda x: self.internal_serialize(x[0])):
for output in reducer(self.deserialize(key), (v[1] for v in values)):
yield output
... | [
"\n Iterate over input, collect values with the same key, and call the reducer for each unique key.\n "
] |
Please provide a description of the function:def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout):
self.init_hadoop()
self.init_mapper()
outputs = self._map_input((line[:-1] for line in stdin))
if self.reducer == NotImplemented:
self.writer(outputs, stdout)
... | [
"\n Run the mapper on the hadoop node.\n "
] |
Please provide a description of the function:def run_reducer(self, stdin=sys.stdin, stdout=sys.stdout):
self.init_hadoop()
self.init_reducer()
outputs = self._reduce_input(self.internal_reader((line[:-1] for line in stdin)), self.reducer, self.final_reducer)
self.writer(outputs,... | [
"\n Run the reducer on the hadoop node.\n "
] |
Please provide a description of the function:def internal_reader(self, input_stream):
for input_line in input_stream:
yield list(map(self.deserialize, input_line.split("\t"))) | [
"\n Reader which uses python eval on each part of a tab separated string.\n Yields a tuple of python objects.\n "
] |
Please provide a description of the function:def internal_writer(self, outputs, stdout):
for output in outputs:
print("\t".join(map(self.internal_serialize, output)), file=stdout) | [
"\n Writer which outputs the python repr for each item.\n "
] |
Please provide a description of the function:def touch(self, connection=None):
self.create_marker_table()
if connection is None:
# TODO: test this
connection = self.connect()
connection.autocommit = True # if connection created here, we commit it here
... | [
"\n Mark this update as complete.\n\n Important: If the marker table doesn't exist, the connection transaction will be aborted\n and the connection reset.\n Then the marker table will be created.\n ",
"INSERT INTO {marker_table} (update_id, target_table)\n VALU... |
Please provide a description of the function:def connect(self):
connection = psycopg2.connect(
host=self.host,
port=self.port,
database=self.database,
user=self.user,
password=self.password)
connection.set_client_encoding('utf-8')
... | [
"\n Get a psycopg2 connection object to the database where the table is.\n "
] |
Please provide a description of the function:def create_marker_table(self):
connection = self.connect()
connection.autocommit = True
cursor = connection.cursor()
if self.use_db_timestamps:
sql = .format(marker_table=self.marker_table)
else:
sql = ... | [
"\n Create marker table if it doesn't exist.\n\n Using a separate connection since the transaction might have to be reset.\n ",
" CREATE TABLE {marker_table} (\n update_id TEXT PRIMARY KEY,\n target_table TEXT,\n inserted TIMESTAM... |
Please provide a description of the function:def rows(self):
with self.input().open('r') as fobj:
for line in fobj:
yield line.strip('\n').split('\t') | [
"\n Return/yield tuples or lists corresponding to each row to be inserted.\n "
] |
Please provide a description of the function:def map_column(self, value):
if value in self.null_values:
return r'\\N'
else:
return default_escape(six.text_type(value)) | [
"\n Applied to each column of every row returned by `rows`.\n\n Default behaviour is to escape special characters and identify any self.null_values.\n "
] |
Please provide a description of the function:def output(self):
return PostgresTarget(
host=self.host,
database=self.database,
user=self.user,
password=self.password,
table=self.table,
update_id=self.update_id,
port=self... | [
"\n Returns a PostgresTarget representing the inserted dataset.\n\n Normally you don't override this.\n "
] |
Please provide a description of the function:def run(self):
if not (self.table and self.columns):
raise Exception("table and columns need to be specified")
connection = self.output().connect()
# transform all data generated by rows() using map_column and write data
... | [
"\n Inserts data generated by rows() into target table.\n\n If the target table doesn't exist, self.create_table will be called to attempt to create the table.\n\n Normally you don't want to override this.\n "
] |
Please provide a description of the function:def get_config(parser=PARSER):
parser_class = PARSERS[parser]
_check_parser(parser_class, parser)
return parser_class.instance() | [
"Get configs singleton for parser\n "
] |
Please provide a description of the function:def add_config_path(path):
if not os.path.isfile(path):
warnings.warn("Config file does not exist: {path}".format(path=path))
return False
# select parser by file extension
_base, ext = os.path.splitext(path)
if ext and ext[1:] in PARSER... | [
"Select config parser by file extension and add path into parser.\n "
] |
Please provide a description of the function:def _setup_packages(self, sc):
packages = self.py_packages
if not packages:
return
for package in packages:
mod = importlib.import_module(package)
try:
mod_path = mod.__path__[0]
... | [
"\n This method compresses and uploads packages to the cluster\n\n "
] |
Please provide a description of the function:def main(args=None, stdin=sys.stdin, stdout=sys.stdout, print_exception=print_exception):
try:
# Set up logging.
logging.basicConfig(level=logging.WARN)
kind = args is not None and args[1] or sys.argv[1]
Runner().run(kind, stdin=stdi... | [
"\n Run either the mapper, combiner, or reducer from the class instance in the file \"job-instance.pickle\".\n\n Arguments:\n\n kind -- is either map, combiner, or reduce\n "
] |
Please provide a description of the function:def run_with_retcodes(argv):
logger = logging.getLogger('luigi-interface')
with luigi.cmdline_parser.CmdlineParser.global_instance(argv):
retcodes = retcode()
worker = None
try:
worker = luigi.interface._run(argv).worker
except luigi... | [
"\n Run luigi with command line parsing, but raise ``SystemExit`` with the configured exit code.\n\n Note: Usually you use the luigi binary directly and don't call this function yourself.\n\n :param argv: Should (conceptually) be ``sys.argv[1:]``\n "
] |
Please provide a description of the function:def find_deps_cli():
'''
Finds all tasks on all paths from provided CLI task
'''
cmdline_args = sys.argv[1:]
with CmdlineParser.global_instance(cmdline_args) as cp:
return find_deps(cp.get_task_obj(), upstream().family) | [] |
Please provide a description of the function:def get_task_output_description(task_output):
'''
Returns a task's output as a string
'''
output_description = "n/a"
if isinstance(task_output, RemoteTarget):
output_description = "[SSH] {0}:{1}".format(task_output._fs.remote_context.host, task_o... | [] |
Please provide a description of the function:def _constrain_glob(glob, paths, limit=5):
def digit_set_wildcard(chars):
chars = sorted(chars)
if len(chars) > 1 and ord(chars[-1]) - ord(chars[0]) == len(chars) - 1:
return '[%s-%s]' % (chars[0], chars[-1])
else:
... | [
"\n Tweaks glob into a list of more specific globs that together still cover paths and not too much extra.\n\n Saves us minutes long listings for long dataset histories.\n\n Specifically, in this implementation the leftmost occurrences of \"[0-9]\"\n give rise to a few separate globs that each specializ... |
Please provide a description of the function:def most_common(items):
counts = {}
for i in items:
counts.setdefault(i, 0)
counts[i] += 1
return max(six.iteritems(counts), key=operator.itemgetter(1)) | [
"\n Wanted functionality from Counters (new in Python 2.7).\n "
] |
Please provide a description of the function:def _get_per_location_glob(tasks, outputs, regexes):
paths = [o.path for o in outputs]
# naive, because some matches could be confused by numbers earlier
# in path, e.g. /foo/fifa2000k/bar/2000-12-31/00
matches = [r.search(p) for r, p in zip(regexes, pat... | [
"\n Builds a glob listing existing output paths.\n\n Esoteric reverse engineering, but worth it given that (compared to an\n equivalent contiguousness guarantee by naive complete() checks)\n requests to the filesystem are cut by orders of magnitude, and users\n don't even have to retrofit existing ta... |
Please provide a description of the function:def _get_filesystems_and_globs(datetime_to_task, datetime_to_re):
# probe some scattered datetimes unlikely to all occur in paths, other than by being sincere datetime parameter's representations
# TODO limit to [self.start, self.stop) so messages are less confu... | [
"\n Yields a (filesystem, glob) tuple per every output location of task.\n\n The task can have one or several FileSystemTarget outputs.\n\n For convenience, the task can be a luigi.WrapperTask,\n in which case outputs of all its dependencies are considered.\n "
] |
Please provide a description of the function:def _list_existing(filesystem, glob, paths):
globs = _constrain_glob(glob, paths)
time_start = time.time()
listing = []
for g in sorted(globs):
logger.debug('Listing %s', g)
if filesystem.exists(g):
listing.extend(filesystem.l... | [
"\n Get all the paths that do in fact exist. Returns a set of all existing paths.\n\n Takes a luigi.target.FileSystem object, a str which represents a glob and\n a list of strings representing paths.\n "
] |
Please provide a description of the function:def infer_bulk_complete_from_fs(datetimes, datetime_to_task, datetime_to_re):
filesystems_and_globs_by_location = _get_filesystems_and_globs(datetime_to_task, datetime_to_re)
paths_by_datetime = [[o.path for o in flatten_output(datetime_to_task(d))] for d in dat... | [
"\n Efficiently determines missing datetimes by filesystem listing.\n\n The current implementation works for the common case of a task writing\n output to a ``FileSystemTarget`` whose path is built using strftime with\n format like '...%Y...%m...%d...%H...', without custom ``complete()`` or\n ``exist... |
Please provide a description of the function:def of_cls(self):
if isinstance(self.of, six.string_types):
warnings.warn('When using Range programatically, dont pass "of" param as string!')
return Register.get_task_cls(self.of)
return self.of | [
"\n DONT USE. Will be deleted soon. Use ``self.of``!\n "
] |
Please provide a description of the function:def _emit_metrics(self, missing_datetimes, finite_start, finite_stop):
datetimes = self.finite_datetimes(
finite_start if self.start is None else min(finite_start, self.parameter_to_datetime(self.start)),
finite_stop if self.stop is N... | [
"\n For consistent metrics one should consider the entire range, but\n it is open (infinite) if stop or start is None.\n\n Hence make do with metrics respective to the finite simplification.\n "
] |
Please provide a description of the function:def missing_datetimes(self, finite_datetimes):
return [d for d in finite_datetimes if not self._instantiate_task_cls(self.datetime_to_parameter(d)).complete()] | [
"\n Override in subclasses to do bulk checks.\n\n Returns a sorted list.\n\n This is a conservative base implementation that brutally checks completeness, instance by instance.\n\n Inadvisable as it may be slow.\n "
] |
Please provide a description of the function:def _missing_datetimes(self, finite_datetimes):
try:
return self.missing_datetimes(finite_datetimes)
except TypeError as ex:
if 'missing_datetimes()' in repr(ex):
warnings.warn('In your Range* subclass, missing... | [
"\n Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015)\n "
] |
Please provide a description of the function:def parameters_to_datetime(self, p):
dt = p[self._param_name]
return datetime(dt.year, dt.month, dt.day) | [
"\n Given a dictionary of parameters, will extract the ranged task parameter value\n "
] |
Please provide a description of the function:def finite_datetimes(self, finite_start, finite_stop):
date_start = datetime(finite_start.year, finite_start.month, finite_start.day)
dates = []
for i in itertools.count():
t = date_start + timedelta(days=i)
if t >= fi... | [
"\n Simply returns the points in time that correspond to turn of day.\n "
] |
Please provide a description of the function:def finite_datetimes(self, finite_start, finite_stop):
datehour_start = datetime(finite_start.year, finite_start.month, finite_start.day, finite_start.hour)
datehours = []
for i in itertools.count():
t = datehour_start + timedelta... | [
"\n Simply returns the points in time that correspond to whole hours.\n "
] |
Please provide a description of the function:def finite_datetimes(self, finite_start, finite_stop):
# Validate that the minutes_interval can divide 60 and it is greater than 0 and lesser than 60
if not (0 < self.minutes_interval < 60):
raise ParameterException('minutes-interval must... | [
"\n Simply returns the points in time that correspond to a whole number of minutes intervals.\n "
] |
Please provide a description of the function:def finite_datetimes(self, finite_start, finite_stop):
start_date = self._align(finite_start)
aligned_stop = self._align(finite_stop)
dates = []
for m in itertools.count():
t = start_date + relativedelta(months=m)
... | [
"\n Simply returns the points in time that correspond to turn of month.\n "
] |
Please provide a description of the function:def touch(self, connection=None):
self.create_marker_table()
if connection is None:
connection = self.connect()
connection.execute_non_query(
.format(marker_table=self.marker_table),
{"update_id": self.up... | [
"\n Mark this update as complete.\n\n IMPORTANT, If the marker table doesn't exist,\n the connection transaction will be aborted and the connection reset.\n Then the marker table will be created.\n ",
"IF NOT EXISTS(SELECT 1\n FROM {marker_table}\n ... |
Please provide a description of the function:def connect(self):
connection = _mssql.connect(user=self.user,
password=self.password,
server=self.host,
port=self.port,
... | [
"\n Create a SQL Server connection and return a connection object\n "
] |
Please provide a description of the function:def create_marker_table(self):
connection = self.connect()
try:
connection.execute_non_query(
.format(marker_table=self.marker_table)
)
except _mssql.MSSQLDatabaseException as e:
... | [
"\n Create marker table if it doesn't exist.\n Use a separate connection since the transaction might have to be reset.\n ",
" CREATE TABLE {marker_table} (\n id BIGINT NOT NULL IDENTITY(1,1),\n update_id VARCHAR(128) NOT NULL,\n... |
Please provide a description of the function:def get_opener(self, name):
if name not in self.registry:
raise NoOpenerError("No opener for %s" % name)
index = self.registry[name]
return self.openers[index] | [
"Retrieve an opener for the given protocol\n\n :param name: name of the opener to open\n :type name: string\n :raises NoOpenerError: if no opener has been registered of that name\n\n "
] |
Please provide a description of the function:def add(self, opener):
index = len(self.openers)
self.openers[index] = opener
for name in opener.names:
self.registry[name] = index | [
"Adds an opener to the registry\n\n :param opener: Opener object\n :type opener: Opener inherited object\n\n "
] |
Please provide a description of the function:def open(self, target_uri, **kwargs):
target = urlsplit(target_uri, scheme=self.default_opener)
opener = self.get_opener(target.scheme)
query = opener.conform_query(target.query)
target = opener.get_target(
target.scheme... | [
"Open target uri.\n\n :param target_uri: Uri to open\n :type target_uri: string\n\n :returns: Target object\n\n "
] |
Please provide a description of the function:def conform_query(cls, query):
query = parse_qs(query, keep_blank_values=True)
# Remove any unexpected keywords from the query string.
if cls.filter_kwargs:
query = {x: y for x, y in query.items() if x in cls.allowed_kwargs}
... | [
"Converts the query string from a target uri, uses\n cls.allowed_kwargs, and cls.filter_kwargs to drive logic.\n\n :param query: Unparsed query string\n :type query: urllib.parse.unsplit(uri).query\n :returns: Dictionary of parsed values, everything in cls.allowed_kwargs\n wit... |
Please provide a description of the function:def get_target(cls, scheme, path, fragment, username,
password, hostname, port, query, **kwargs):
raise NotImplementedError("get_target must be overridden") | [
"Override this method to use values from the parsed uri to initialize\n the expected target.\n\n "
] |
Please provide a description of the function:def _schedule_and_run(tasks, worker_scheduler_factory=None, override_defaults=None):
if worker_scheduler_factory is None:
worker_scheduler_factory = _WorkerSchedulerFactory()
if override_defaults is None:
override_defaults = {}
env_params = ... | [
"\n :param tasks:\n :param worker_scheduler_factory:\n :param override_defaults:\n :return: True if all tasks and their dependencies were successfully run (or already completed);\n False if any error occurred. It will return a detailed response of type LuigiRunResult\n instead of... |
Please provide a description of the function:def run(*args, **kwargs):
luigi_run_result = _run(*args, **kwargs)
return luigi_run_result if kwargs.get('detailed_summary') else luigi_run_result.scheduling_succeeded | [
"\n Please dont use. Instead use `luigi` binary.\n\n Run from cmdline using argparse.\n\n :param use_dynamic_argparse: Deprecated and ignored\n "
] |
Please provide a description of the function:def build(tasks, worker_scheduler_factory=None, detailed_summary=False, **env_params):
if "no_lock" not in env_params:
env_params["no_lock"] = True
luigi_run_result = _schedule_and_run(tasks, worker_scheduler_factory, override_defaults=env_params)
r... | [
"\n Run internally, bypassing the cmdline parsing.\n\n Useful if you have some luigi code that you want to run internally.\n Example:\n\n .. code-block:: python\n\n luigi.build([MyTask1(), MyTask2()], local_scheduler=True)\n\n One notable difference is that `build` defaults to not using\n t... |
Please provide a description of the function:def touch(self, connection=None):
self.create_marker_table()
if connection is None:
connection = self.connect()
connection.autocommit = True # if connection created here, we commit it here
connection.cursor().execut... | [
"\n Mark this update as complete.\n\n IMPORTANT, If the marker table doesn't exist,\n the connection transaction will be aborted and the connection reset.\n Then the marker table will be created.\n ",
"INSERT INTO {marker_table} (update_id, target_table)\n VALUES (... |
Please provide a description of the function:def create_marker_table(self):
connection = self.connect(autocommit=True)
cursor = connection.cursor()
try:
cursor.execute(
.format(marker_table=self.marker_table)
)
except mysq... | [
"\n Create marker table if it doesn't exist.\n\n Using a separate connection since the transaction might have to be reset.\n ",
" CREATE TABLE {marker_table} (\n id BIGINT(20) NOT NULL AUTO_INCREMENT,\n update_id VARCHAR(128) NO... |
Please provide a description of the function:def run(self):
if not (self.table and self.columns):
raise Exception("table and columns need to be specified")
connection = self.output().connect()
# attempt to copy the data into mysql
# if it fails because the target t... | [
"\n Inserts data generated by rows() into target table.\n\n If the target table doesn't exist, self.create_table will be called to attempt to create the table.\n\n Normally you don't want to override this.\n "
] |
Please provide a description of the function:def fix_paths(job):
tmp_files = []
args = []
for x in job.args():
if isinstance(x, luigi.contrib.hdfs.HdfsTarget): # input/output
if x.exists() or not job.atomic_output(): # input
args.append(x.path)
else: #... | [
"\n Coerce input arguments to use temporary files when used for output.\n\n Return a list of temporary file pairs (tmpfile, destination path) and\n a list of arguments.\n\n Converts each HdfsTarget to a string for the path.\n "
] |
Please provide a description of the function:def get_active_queue(self):
# Get dict of active queues keyed by name
queues = {q['jobQueueName']: q for q in self._client.describe_job_queues()['jobQueues']
if q['state'] == 'ENABLED' and q['status'] == 'VALID'}
if not que... | [
"Get name of first active job queue"
] |
Please provide a description of the function:def get_job_id_from_name(self, job_name):
jobs = self._client.list_jobs(jobQueue=self._queue, jobStatus='RUNNING')['jobSummaryList']
matching_jobs = [job for job in jobs if job['jobName'] == job_name]
if matching_jobs:
return matc... | [
"Retrieve the first job ID matching the given name"
] |
Please provide a description of the function:def get_job_status(self, job_id):
response = self._client.describe_jobs(jobs=[job_id])
# Error checking
status_code = response['ResponseMetadata']['HTTPStatusCode']
if status_code != 200:
msg = 'Job status request receive... | [
"Retrieve task statuses from ECS API\n\n :param job_id (str): AWS Batch job uuid\n\n Returns one of {SUBMITTED|PENDING|RUNNABLE|STARTING|RUNNING|SUCCEEDED|FAILED}\n "
] |
Please provide a description of the function:def get_logs(self, log_stream_name, get_last=50):
response = self._log_client.get_log_events(
logGroupName='/aws/batch/job',
logStreamName=log_stream_name,
startFromHead=False)
events = response['events']
r... | [
"Retrieve log stream from CloudWatch"
] |
Please provide a description of the function:def submit_job(self, job_definition, parameters, job_name=None, queue=None):
if job_name is None:
job_name = _random_id()
response = self._client.submit_job(
jobName=job_name,
jobQueue=queue or self.get_active_queu... | [
"Wrap submit_job with useful defaults"
] |
Please provide a description of the function:def wait_on_job(self, job_id):
while True:
status = self.get_job_status(job_id)
if status == 'SUCCEEDED':
logger.info('Batch job {} SUCCEEDED'.format(job_id))
return True
elif status == 'FA... | [
"Poll task status until STOPPED"
] |
Please provide a description of the function:def register_job_definition(self, json_fpath):
with open(json_fpath) as f:
job_def = json.load(f)
response = self._client.register_job_definition(**job_def)
status_code = response['ResponseMetadata']['HTTPStatusCode']
if s... | [
"Register a job definition with AWS Batch, using a JSON"
] |
Please provide a description of the function:def main(args=sys.argv):
try:
tarball = "--no-tarball" not in args
# Set up logging.
logging.basicConfig(level=logging.WARN)
work_dir = args[1]
assert os.path.exists(work_dir), "First argument to sge_runner.py must be a direct... | [
"Run the work() method from the class instance in the file \"job-instance.pickle\".\n "
] |
Please provide a description of the function:def _get_input_schema(self):
assert avro, 'avro module required'
input_target = flatten(self.input())[0]
input_fs = input_target.fs if hasattr(input_target, 'fs') else GCSClient()
input_uri = self.source_uris()[0]
if '*' in i... | [
"Arbitrarily picks an object in input and reads the Avro schema from it."
] |
Please provide a description of the function:def print_tree(task, indent='', last=True):
'''
Return a string representation of the tasks, their statuses/parameters in a dependency tree format
'''
# dont bother printing out warnings about tasks with no output
with warnings.catch_warnings():
w... | [] |
Please provide a description of the function:def _urljoin(base, url):
parsed = urlparse(base)
scheme = parsed.scheme
return urlparse(
urljoin(parsed._replace(scheme='http').geturl(), url)
)._replace(scheme=scheme).geturl() | [
"\n Join relative URLs to base URLs like urllib.parse.urljoin but support\n arbitrary URIs (esp. 'http+unix://').\n "
] |
Please provide a description of the function:def dataset_exists(self, dataset):
try:
response = self.client.datasets().get(projectId=dataset.project_id,
datasetId=dataset.dataset_id).execute()
if dataset.location is not None:
... | [
"Returns whether the given dataset exists.\n If regional location is specified for the dataset, that is also checked\n to be compatible with the remote dataset, otherwise an exception is thrown.\n\n :param dataset:\n :type dataset: BQDataset\n "
] |
Please provide a description of the function:def table_exists(self, table):
if not self.dataset_exists(table.dataset):
return False
try:
self.client.tables().get(projectId=table.project_id,
datasetId=table.dataset_id,
... | [
"Returns whether the given table exists.\n\n :param table:\n :type table: BQTable\n "
] |
Please provide a description of the function:def make_dataset(self, dataset, raise_if_exists=False, body=None):
if body is None:
body = {}
try:
# Construct a message body in the format required by
# https://developers.google.com/resources/api-libraries/docu... | [
"Creates a new dataset with the default permissions.\n\n :param dataset:\n :type dataset: BQDataset\n :param raise_if_exists: whether to raise an exception if the dataset already exists.\n :raises luigi.target.FileAlreadyExists: if raise_if_exists=True and the dataset exists\... |
Please provide a description of the function:def delete_dataset(self, dataset, delete_nonempty=True):
if not self.dataset_exists(dataset):
return
self.client.datasets().delete(projectId=dataset.project_id,
datasetId=dataset.dataset_id,
... | [
"Deletes a dataset (and optionally any tables in it), if it exists.\n\n :param dataset:\n :type dataset: BQDataset\n :param delete_nonempty: if true, will delete any tables before deleting the dataset\n "
] |
Please provide a description of the function:def delete_table(self, table):
if not self.table_exists(table):
return
self.client.tables().delete(projectId=table.project_id,
datasetId=table.dataset_id,
tableId=t... | [
"Deletes a table, if it exists.\n\n :param table:\n :type table: BQTable\n "
] |
Please provide a description of the function:def list_datasets(self, project_id):
request = self.client.datasets().list(projectId=project_id,
maxResults=1000)
response = request.execute()
while response is not None:
for ds in r... | [
"Returns the list of datasets in a given project.\n\n :param project_id:\n :type project_id: str\n "
] |
Please provide a description of the function:def list_tables(self, dataset):
request = self.client.tables().list(projectId=dataset.project_id,
datasetId=dataset.dataset_id,
maxResults=1000)
response = reque... | [
"Returns the list of tables in a given dataset.\n\n :param dataset:\n :type dataset: BQDataset\n "
] |
Please provide a description of the function:def get_view(self, table):
request = self.client.tables().get(projectId=table.project_id,
datasetId=table.dataset_id,
tableId=table.table_id)
try:
res... | [
"Returns the SQL query for a view, or None if it doesn't exist or is not a view.\n\n :param table: The table containing the view.\n :type table: BQTable\n "
] |
Please provide a description of the function:def update_view(self, table, view):
body = {
'tableReference': {
'projectId': table.project_id,
'datasetId': table.dataset_id,
'tableId': table.table_id
},
'view': {
... | [
"Updates the SQL query for a view.\n\n If the output table exists, it is replaced with the supplied view query. Otherwise a new\n table is created with this view.\n\n :param table: The table to contain the view.\n :type table: BQTable\n :param view: The SQL query for the view.\n ... |
Please provide a description of the function:def run_job(self, project_id, body, dataset=None):
if dataset and not self.dataset_exists(dataset):
self.make_dataset(dataset)
new_job = self.client.jobs().insert(projectId=project_id, body=body).execute()
job_id = new_job['jobR... | [
"Runs a BigQuery \"job\". See the documentation for the format of body.\n\n .. note::\n You probably don't need to use this directly. Use the tasks defined below.\n\n :param dataset:\n :type dataset: BQDataset\n "
] |
Please provide a description of the function:def copy(self,
source_table,
dest_table,
create_disposition=CreateDisposition.CREATE_IF_NEEDED,
write_disposition=WriteDisposition.WRITE_TRUNCATE):
job = {
"configuration": {
"c... | [
"Copies (or appends) a table to another table.\n\n :param source_table:\n :type source_table: BQTable\n :param dest_table:\n :type dest_table: BQTable\n :param create_disposition: whether to create the table if needed\n :type create_disposition: Crea... |
Please provide a description of the function:def from_bqtable(cls, table, client=None):
return cls(table.project_id, table.dataset_id, table.table_id, client=client) | [
"A constructor that takes a :py:class:`BQTable`.\n\n :param table:\n :type table: BQTable\n "
] |
Please provide a description of the function:def source_uris(self):
return [x.path for x in luigi.task.flatten(self.input())] | [
"The fully-qualified URIs that point to your data in Google Cloud Storage.\n\n Each URI can contain one '*' wildcard character and it must come after the 'bucket' name."
] |
Please provide a description of the function:def destination_uris(self):
return [x.path for x in luigi.task.flatten(self.output())] | [
"\n The fully-qualified URIs that point to your data in Google Cloud\n Storage. Each URI can contain one '*' wildcard character and it must\n come after the 'bucket' name.\n\n Wildcarded destinationUris in GCSQueryTarget might not be resolved\n correctly and result in incomplete d... |
Please provide a description of the function:def Popen(self, cmd, **kwargs):
prefixed_cmd = self._prepare_cmd(cmd)
return subprocess.Popen(prefixed_cmd, **kwargs) | [
"\n Remote Popen.\n "
] |
Please provide a description of the function:def check_output(self, cmd):
p = self.Popen(cmd, stdout=subprocess.PIPE)
output, _ = p.communicate()
if p.returncode != 0:
raise RemoteCalledProcessError(p.returncode, cmd, self.host, output=output)
return output | [
"\n Execute a shell command remotely and return the output.\n\n Simplified version of Popen when you only want the output as a string and detect any errors.\n "
] |
Please provide a description of the function:def tunnel(self, local_port, remote_port=None, remote_host="localhost"):
tunnel_host = "{0}:{1}:{2}".format(local_port, remote_host, remote_port)
proc = self.Popen(
# cat so we can shut down gracefully by closing stdin
["-L", ... | [
"\n Open a tunnel between localhost:local_port and remote_host:remote_port via the host specified by this context.\n\n Remember to close() the returned \"tunnel\" object in order to clean up\n after yourself when you are done with the tunnel.\n "
] |
Please provide a description of the function:def isdir(self, path):
try:
self.remote_context.check_output(["test", "-d", path])
except subprocess.CalledProcessError as e:
if e.returncode == 1:
return False
else:
raise
r... | [
"\n Return `True` if directory at `path` exist, False otherwise.\n "
] |
Please provide a description of the function:def remove(self, path, recursive=True):
if recursive:
cmd = ["rm", "-r", path]
else:
cmd = ["rm", path]
self.remote_context.check_output(cmd) | [
"\n Remove file or directory at location `path`.\n "
] |
Please provide a description of the function:def getpcmd(pid):
if os.name == "nt":
# Use wmic command instead of ps on Windows.
cmd = 'wmic path win32_process where ProcessID=%s get Commandline 2> nul' % (pid, )
with os.popen(cmd, 'r') as p:
lines = [line for line in p.readl... | [
"\n Returns command of process.\n\n :param pid:\n "
] |
Please provide a description of the function:def acquire_for(pid_dir, num_available=1, kill_signal=None):
my_pid, my_cmd, pid_file = get_info(pid_dir)
# Create a pid file if it does not exist
try:
os.mkdir(pid_dir)
os.chmod(pid_dir, 0o777)
except OSError as exc:
if exc.err... | [
"\n Makes sure the process is only run once at the same time with the same name.\n\n Notice that we since we check the process name, different parameters to the same\n command can spawn multiple processes at the same time, i.e. running\n \"/usr/bin/my_process\" does not prevent anyone from launching\n ... |
Please provide a description of the function:def add_failure(self):
failure_time = time.time()
if not self.first_failure_time:
self.first_failure_time = failure_time
self.failures.append(failure_time) | [
"\n Add a failure event with the current timestamp.\n "
] |
Please provide a description of the function:def num_failures(self):
min_time = time.time() - self.window
while self.failures and self.failures[0] < min_time:
self.failures.popleft()
return len(self.failures) | [
"\n Return the number of failures in the window.\n "
] |
Please provide a description of the function:def is_trivial_worker(self, state):
if self.assistant:
return False
return all(not task.resources for task in self.get_tasks(state, PENDING)) | [
"\n If it's not an assistant having only tasks that are without\n requirements.\n\n We have to pass the state parameter for optimization reasons.\n "
] |
Please provide a description of the function:def num_pending_tasks(self):
return len(self._status_tasks[PENDING]) + len(self._status_tasks[RUNNING]) | [
"\n Return how many tasks are PENDING + RUNNING. O(1).\n "
] |
Please provide a description of the function:def _update_priority(self, task, prio, worker):
task.priority = prio = max(prio, task.priority)
for dep in task.deps or []:
t = self._state.get_task(dep)
if t is not None and prio > t.priority:
self._update_pri... | [
"\n Update priority of the given task.\n\n Priority can only be increased.\n If the task doesn't exist, a placeholder task is created to preserve priority when the task is later scheduled.\n "
] |
Please provide a description of the function:def add_task(self, task_id=None, status=PENDING, runnable=True,
deps=None, new_deps=None, expl=None, resources=None,
priority=0, family='', module=None, params=None, param_visibilities=None, accepts_messages=False,
assistant... | [
"\n * add task identified by task_id if it doesn't exist\n * if deps is not None, update dependency list\n * update status of task\n * add additional workers/stakeholders\n * update priority when needed\n "
] |
Please provide a description of the function:def _traverse_graph(self, root_task_id, seen=None, dep_func=None, include_done=True):
if seen is None:
seen = set()
elif root_task_id in seen:
return {}
if dep_func is None:
def dep_func(t):
... | [
" Returns the dependency graph rooted at task_id\n\n This does a breadth-first traversal to find the nodes closest to the\n root before hitting the scheduler.max_graph_nodes limit.\n\n :param root_task_id: the id of the graph's root\n :return: A map of task id to serialized node\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.