_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q233600 | expand_paths | train | def expand_paths(path):
"""When given a path with brackets, expands it to return all permutations
of the path with expanded brackets, similar to ant.
>>> expand_paths('../{a,b}/{c,d}')
['../a/c', '../a/d', '../b/c', '../b/d']
>>> expand_paths('../{a,b}/{a,b}.py')
['../a/a.py', '.... | python | {
"resource": ""
} |
q233601 | multiline_merge | train | def multiline_merge(lines, current_event, re_after, re_before):
""" Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match ... | python | {
"resource": ""
} |
q233602 | create_ssh_tunnel | train | def create_ssh_tunnel(beaver_config, logger=None):
"""Returns a BeaverSshTunnel object if the current config requires us to"""
if not beaver_config.use_ssh_tunnel():
return None
logger.info("Proxying transport using through local ssh tunnel")
return BeaverSshTunnel(beaver_config, logger=logger) | python | {
"resource": ""
} |
q233603 | BeaverSubprocess.poll | train | def poll(self):
"""Poll attached subprocess until it is available"""
if self._subprocess is not None:
self._subprocess.poll()
time.sleep(self._beaver_config.get('subprocess_poll_sleep')) | python | {
"resource": ""
} |
q233604 | BeaverSubprocess.close | train | def close(self):
"""Close child subprocess"""
if self._subprocess is not None:
os.killpg(self._subprocess.pid, signal.SIGTERM)
self._subprocess = None | python | {
"resource": ""
} |
q233605 | _to_unicode | train | def _to_unicode(self, data, encoding, errors='strict'):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
... | python | {
"resource": ""
} |
q233606 | StompTransport.reconnect | train | def reconnect(self):
"""Allows reconnection from when a handled
TransportException is thrown"""
try:
self.conn.close()
except Exception,e:
self.logger.warn(e)
self.createConnection()
return True | python | {
"resource": ""
} |
q233607 | RedisTransport._check_connections | train | def _check_connections(self):
"""Checks if all configured redis servers are reachable"""
for server in self._servers:
if self._is_reachable(server):
server['down_until'] = 0
else:
server['down_until'] = time.time() + 5 | python | {
"resource": ""
} |
q233608 | RedisTransport._is_reachable | train | def _is_reachable(self, server):
"""Checks if the given redis server is reachable"""
try:
server['redis'].ping()
return True
except UserWarning:
self._logger.warn('Cannot reach redis server: ' + server['url'])
except Exception:
self._logge... | python | {
"resource": ""
} |
q233609 | RedisTransport.invalidate | train | def invalidate(self):
"""Invalidates the current transport and disconnects all redis connections"""
super(RedisTransport, self).invalidate()
for server in self._servers:
server['redis'].connection_pool.disconnect()
return False | python | {
"resource": ""
} |
q233610 | RedisTransport.callback | train | def callback(self, filename, lines, **kwargs):
"""Sends log lines to redis servers"""
self._logger.debug('Redis transport called')
timestamp = self.get_timestamp(**kwargs)
if kwargs.get('timestamp', False):
del kwargs['timestamp']
namespaces = self._beaver_config.g... | python | {
"resource": ""
} |
q233611 | RedisTransport._get_next_server | train | def _get_next_server(self):
"""Returns a valid redis server or raises a TransportException"""
current_try = 0
max_tries = len(self._servers)
while current_try < max_tries:
server_index = self._raise_server_index()
server = self._servers[server_index]
... | python | {
"resource": ""
} |
q233612 | RedisTransport.valid | train | def valid(self):
"""Returns whether or not the transport can send data to any redis server"""
valid_servers = 0
for server in self._servers:
if server['down_until'] <= time.time():
valid_servers += 1
return valid_servers > 0 | python | {
"resource": ""
} |
q233613 | BaseTransport.format | train | def format(self, filename, line, timestamp, **kwargs):
"""Returns a formatted log line"""
line = unicode(line.encode("utf-8"), "utf-8", errors="ignore")
formatter = self._beaver_config.get_field('format', filename)
if formatter not in self._formatters:
formatter = self._defau... | python | {
"resource": ""
} |
q233614 | BaseTransport.get_timestamp | train | def get_timestamp(self, **kwargs):
"""Retrieves the timestamp for a given set of data"""
timestamp = kwargs.get('timestamp')
if not timestamp:
now = datetime.datetime.utcnow()
timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z"
... | python | {
"resource": ""
} |
q233615 | _make_executable | train | def _make_executable(path):
"""Make the file at path executable."""
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | python | {
"resource": ""
} |
q233616 | build_parser | train | def build_parser():
"""Build argument parser."""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Required args
parser.add_argument("--in_path", "-i", required=True,
help="file p... | python | {
"resource": ""
} |
q233617 | _read_arg | train | def _read_arg(arg):
"""
If arg is a list with 1 element that corresponds to a valid file path, use
set_io.grp to read the grp file. Otherwise, check that arg is a list of strings.
Args:
arg (list or None)
Returns:
arg_out (list or None)
"""
# If arg is None, just return it... | python | {
"resource": ""
} |
q233618 | read | train | def read(file_path):
""" Read a gmt file at the path specified by file_path.
Args:
file_path (string): path to gmt file
Returns:
gmt (GMT object): list of dicts, where each dict corresponds to one
line of the GMT file
"""
# Read in file
actual_file_path = os.path.e... | python | {
"resource": ""
} |
q233619 | verify_gmt_integrity | train | def verify_gmt_integrity(gmt):
""" Make sure that set ids are unique.
Args:
gmt (GMT object): list of dicts
Returns:
None
"""
# Verify that set ids are unique
set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt]
assert len(set(set_ids)) == len(set_ids), (
"Set identif... | python | {
"resource": ""
} |
q233620 | write | train | def write(gmt, out_path):
""" Write a GMT to a text file.
Args:
gmt (GMT object): list of dicts
out_path (string): output path
Returns:
None
"""
with open(out_path, 'w') as f:
for _, each_dict in enumerate(gmt):
f.write(each_dict[SET_IDENTIFIER_FIELD] +... | python | {
"resource": ""
} |
q233621 | parse | train | def parse(gctx_file_path, convert_neg_666=True, rid=None, cid=None,
ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False):
"""
Primary method of script. Reads in path to a gctx file and parses into GCToo object.
Input:
Mandatory:
- gctx_file_path (... | python | {
"resource": ""
} |
q233622 | check_id_idx_exclusivity | train | def check_id_idx_exclusivity(id, idx):
"""
Makes sure user didn't provide both ids and idx values to subset by.
Input:
- id (list or None): if not None, a list of string id names
- idx (list or None): if not None, a list of integer id indexes
Output:
- a tuple: first element is... | python | {
"resource": ""
} |
q233623 | parse_data_df | train | def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta):
"""
Parses in data_df from hdf5, subsetting if specified.
Input:
-data_dset (h5py dset): HDF5 dataset from which to read data_df
-ridx (list): list of indexes to subset from data_df
(may be all of them if no subsettin... | python | {
"resource": ""
} |
q233624 | get_column_metadata | train | def get_column_metadata(gctx_file_path, convert_neg_666=True):
"""
Opens .gctx file and returns only column metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num... | python | {
"resource": ""
} |
q233625 | get_row_metadata | train | def get_row_metadata(gctx_file_path, convert_neg_666=True):
"""
Opens .gctx file and returns only row metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
... | python | {
"resource": ""
} |
q233626 | multi_index_df_to_component_dfs | train | def multi_index_df_to_component_dfs(multi_index_df, rid="rid", cid="cid"):
""" Convert a multi-index df into 3 component dfs. """
# Id level of the multiindex will become the index
rids = list(multi_index_df.index.get_level_values(rid))
cids = list(multi_index_df.columns.get_level_values(cid))
# I... | python | {
"resource": ""
} |
q233627 | GCToo.check_df | train | def check_df(self, df):
"""
Verifies that df is a pandas DataFrame instance and
that its index and column values are unique.
"""
if isinstance(df, pd.DataFrame):
if not df.index.is_unique:
repeats = df.index[df.index.duplicated()].values
... | python | {
"resource": ""
} |
q233628 | are_genes_in_api | train | def are_genes_in_api(my_clue_api_client, gene_symbols):
"""determine if genes are present in the API
Args:
my_clue_api_client:
gene_symbols: collection of gene symbols to query the API with
Returns: set of the found gene symbols
"""
if len(gene_symbols) > 0:
query_gene_sym... | python | {
"resource": ""
} |
q233629 | write | train | def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"):
"""Write a gctoo object to a gct file.
Args:
gctoo (gctoo object)
out_fname (string): filename for output gct file
data_null (string): how to represent missing values in the... | python | {
"resource": ""
} |
q233630 | write_version_and_dims | train | def write_version_and_dims(version, dims, f):
"""Write first two lines of gct file.
Args:
version (string): 1.3 by default
dims (list of strings): length = 4
f (file handle): handle of output file
Returns:
nothing
"""
f.write(("#" + version + "\n"))
f.write((dims... | python | {
"resource": ""
} |
q233631 | append_dims_and_file_extension | train | def append_dims_and_file_extension(fname, data_df):
"""Append dimensions and file extension to output filename.
N.B. Dimensions are cols x rows.
Args:
fname (string): output filename
data_df (pandas df)
Returns:
out_fname (string): output filename with matrix dims and .gct appen... | python | {
"resource": ""
} |
q233632 | robust_zscore | train | def robust_zscore(mat, ctrl_mat=None, min_mad=0.1):
''' Robustly z-score a pandas df along the rows.
Args:
mat (pandas df): Matrix of data that z-scoring will be applied to
ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs
(e.g. vehicle control)
min_mad (float): M... | python | {
"resource": ""
} |
q233633 | parse | train | def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None,
row_meta_only=False, col_meta_only=False, make_multiindex=False):
"""
Identifies whether file_path corresponds to a .gct or .gctx file and calls the
correct corresponding parse method.
Input:
Mandator... | python | {
"resource": ""
} |
q233634 | get_upper_triangle | train | def get_upper_triangle(correlation_matrix):
''' Extract upper triangle from a square matrix. Negative values are
set to 0.
Args:
correlation_matrix (pandas df): Correlations between all replicates
Returns:
upper_tri_df (pandas df): Upper triangle extracted from
correlation_matrix; rid ... | python | {
"resource": ""
} |
q233635 | calculate_weights | train | def calculate_weights(correlation_matrix, min_wt):
''' Calculate a weight for each profile based on its correlation to other
replicates. Negative correlations are clipped to 0, and weights are clipped
to be min_wt at the least.
Args:
correlation_matrix (pandas df): Correlations between all replicat... | python | {
"resource": ""
} |
q233636 | agg_wt_avg | train | def agg_wt_avg(mat, min_wt = 0.01, corr_metric='spearman'):
''' Aggregate a set of replicate profiles into a single signature using
a weighted average.
Args:
mat (pandas df): a matrix of replicate profiles, where the columns are
samples and the rows are features; columns correspond to the
... | python | {
"resource": ""
} |
q233637 | get_file_list | train | def get_file_list(wildcard):
""" Search for files to be concatenated. Currently very basic, but could
expand to be more sophisticated.
Args:
wildcard (regular expression string)
Returns:
files (list of full file paths)
"""
files = glob.glob(os.path.expanduser(wildcard))
re... | python | {
"resource": ""
} |
q233638 | hstack | train | def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False):
""" Horizontally concatenate gctoos.
Args:
gctoos (list of gctoo objects)
remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos
error_... | python | {
"resource": ""
} |
q233639 | assemble_concatenated_meta | train | def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields):
""" Assemble the concatenated metadata dfs together. For example,
if horizontally concatenating, the concatenated metadata dfs are the
column metadata dfs. Both indices are sorted.
Args:
concated_meta_dfs (list of pa... | python | {
"resource": ""
} |
q233640 | assemble_data | train | def assemble_data(data_dfs, concat_direction):
""" Assemble the data dfs together. Both indices are sorted.
Args:
data_dfs (list of pandas dfs)
concat_direction (string): 'horiz' or 'vert'
Returns:
all_data_df_sorted (pandas df)
"""
if concat_direction == "horiz":
... | python | {
"resource": ""
} |
q233641 | do_reset_ids | train | def do_reset_ids(concatenated_meta_df, data_df, concat_direction):
""" Reset ids in concatenated metadata and data dfs to unique integers and
save the old ids in a metadata column.
Note that the dataframes are modified in-place.
Args:
concatenated_meta_df (pandas df)
data_df (pandas df... | python | {
"resource": ""
} |
q233642 | reset_ids_in_meta_df | train | def reset_ids_in_meta_df(meta_df):
""" Meta_df is modified inplace. """
# Record original index name, and then change it so that the column that it
# becomes will be appropriately named
original_index_name = meta_df.index.name
meta_df.index.name = "old_id"
# Reset index
meta_df.reset_index... | python | {
"resource": ""
} |
q233643 | subset_gctoo | train | def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None,
ridx=None, cidx=None, exclude_rid=None, exclude_cid=None):
""" Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
... | python | {
"resource": ""
} |
q233644 | get_rows_to_keep | train | def get_rows_to_keep(gctoo, rid=None, row_bool=None, ridx=None, exclude_rid=None):
""" Figure out based on the possible row inputs which rows to keep.
Args:
gctoo (GCToo object):
rid (list of strings):
row_bool (boolean array):
ridx (list of integers):
exclude_rid (list ... | python | {
"resource": ""
} |
q233645 | get_cols_to_keep | train | def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None):
""" Figure out based on the possible columns inputs which columns to keep.
Args:
gctoo (GCToo object):
cid (list of strings):
col_bool (boolean array):
cidx (list of integers):
exclude_cid... | python | {
"resource": ""
} |
q233646 | read | train | def read(in_path):
""" Read a grp file at the path specified by in_path.
Args:
in_path (string): path to GRP file
Returns:
grp (list)
"""
assert os.path.exists(in_path), "The following GRP file can't be found. in_path: {}".format(in_path)
with open(in_path, "r") as f:
... | python | {
"resource": ""
} |
q233647 | write | train | def write(grp, out_path):
""" Write a GRP to a text file.
Args:
grp (list): GRP object to write to new-line delimited text file
out_path (string): output path
Returns:
None
"""
with open(out_path, "w") as f:
for x in grp:
f.write(str(x) + "\n") | python | {
"resource": ""
} |
q233648 | make_specified_size_gctoo | train | def make_specified_size_gctoo(og_gctoo, num_entries, dim):
"""
Subsets a GCToo instance along either rows or columns to obtain a specified size.
Input:
- og_gctoo (GCToo): a GCToo instance
- num_entries (int): the number of entries to keep
- dim (str): the dimension along which to subset. Must be "row" or... | python | {
"resource": ""
} |
q233649 | write | train | def write(gctoo_object, out_file_name, convert_back_to_neg_666=True, gzip_compression_level=6,
max_chunk_kb=1024, matrix_dtype=numpy.float32):
"""
Writes a GCToo instance to specified file.
Input:
- gctoo_object (GCToo): A GCToo instance.
- out_file_name (str): file name to write gctoo_object to.
... | python | {
"resource": ""
} |
q233650 | write_src | train | def write_src(hdf5_out, gctoo_object, out_file_name):
"""
Writes src as attribute of gctx out file.
Input:
- hdf5_out (h5py): hdf5 file to write to
- gctoo_object (GCToo): GCToo instance to be written to .gctx
- out_file_name (str): name of hdf5 out file.
"""
if gctoo_object.src == None:
hd... | python | {
"resource": ""
} |
q233651 | calculate_elem_per_kb | train | def calculate_elem_per_kb(max_chunk_kb, matrix_dtype):
"""
Calculates the number of elem per kb depending on the max chunk size set.
Input:
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- matrix_dtype (numpy dtype, default=numpy.float32): Storage d... | python | {
"resource": ""
} |
q233652 | set_data_matrix_chunk_size | train | def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb):
"""
Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The m... | python | {
"resource": ""
} |
q233653 | LazyUserManager.convert | train | def convert(self, form):
""" Convert a lazy user to a non-lazy one. The form passed
in is expected to be a ModelForm instance, bound to the user
to be converted.
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy.
"""
if not is... | python | {
"resource": ""
} |
q233654 | LazyUserManager.generate_username | train | def generate_username(self, user_class):
""" Generate a new username for a user
"""
m = getattr(user_class, 'generate_username', None)
if m:
return m()
else:
max_length = user_class._meta.get_field(
self.username_field).max_length
... | python | {
"resource": ""
} |
q233655 | is_lazy_user | train | def is_lazy_user(user):
""" Return True if the passed user is a lazy user. """
# Anonymous users are not lazy.
if user.is_anonymous:
return False
# Check the user backend. If the lazy signup backend
# authenticated them, then the user is lazy.
backend = getattr(user, 'backend', None)
... | python | {
"resource": ""
} |
q233656 | add | train | def add(queue_name, payload=None, content_type=None, source=None, task_id=None,
build_id=None, release_id=None, run_id=None):
"""Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string... | python | {
"resource": ""
} |
q233657 | _task_to_dict | train | def _task_to_dict(task):
"""Converts a WorkQueue to a JSON-able dictionary."""
payload = task.payload
if payload and task.content_type == 'application/json':
payload = json.loads(payload)
return dict(
task_id=task.task_id,
queue_name=task.queue_name,
eta=_datetime_to_epo... | python | {
"resource": ""
} |
q233658 | lease | train | def lease(queue_name, owner, count=1, timeout_seconds=60):
"""Leases a work item from a queue, usually the oldest task available.
Args:
queue_name: Name of the queue to lease work from.
owner: Who or what is leasing the task.
count: Lease up to this many tasks. Return value will never h... | python | {
"resource": ""
} |
q233659 | _get_task_with_policy | train | def _get_task_with_policy(queue_name, task_id, owner):
"""Fetches the specified task and enforces ownership policy.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
Returns:
... | python | {
"resource": ""
} |
q233660 | heartbeat | train | def heartbeat(queue_name, task_id, owner, message, index):
"""Sets the heartbeat status of the task and extends its lease.
The task's lease is extended by the same amount as its last lease to
ensure that any operations following the heartbeat will still hold the
lock for the original lock period.
... | python | {
"resource": ""
} |
q233661 | finish | train | def finish(queue_name, task_id, owner, error=False):
"""Marks a work item on a queue as finished.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
error: Defaults to false. Tr... | python | {
"resource": ""
} |
q233662 | cancel | train | def cancel(**kwargs):
"""Cancels work items based on their criteria.
Args:
**kwargs: Same parameters as the query() method.
Returns:
The number of tasks that were canceled.
"""
task_list = _query(**kwargs)
for task in task_list:
task.status = WorkQueue.CANCELED
... | python | {
"resource": ""
} |
q233663 | handle_add | train | def handle_add(queue_name):
"""Adds a task to a queue."""
source = request.form.get('source', request.remote_addr, type=str)
try:
task_id = work_queue.add(
queue_name,
payload=request.form.get('payload', type=str),
content_type=request.form.get('content_type', typ... | python | {
"resource": ""
} |
q233664 | handle_lease | train | def handle_lease(queue_name):
"""Leases a task from a queue."""
owner = request.form.get('owner', request.remote_addr, type=str)
try:
task_list = work_queue.lease(
queue_name,
owner,
request.form.get('count', 1, type=int),
request.form.get('timeout', 6... | python | {
"resource": ""
} |
q233665 | handle_heartbeat | train | def handle_heartbeat(queue_name):
"""Updates the heartbeat message for a task."""
task_id = request.form.get('task_id', type=str)
message = request.form.get('message', type=str)
index = request.form.get('index', type=int)
try:
work_queue.heartbeat(
queue_name,
task_id... | python | {
"resource": ""
} |
q233666 | handle_finish | train | def handle_finish(queue_name):
"""Marks a task on a queue as finished."""
task_id = request.form.get('task_id', type=str)
owner = request.form.get('owner', request.remote_addr, type=str)
error = request.form.get('error', type=str) is not None
try:
work_queue.finish(queue_name, task_id, owner... | python | {
"resource": ""
} |
q233667 | view_all_work_queues | train | def view_all_work_queues():
"""Page for viewing the index of all active work queues."""
count_list = list(
db.session.query(
work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status,
func.count(work_queue.WorkQueue.task_id))
.group_by(work_queue.WorkQueue.... | python | {
"resource": ""
} |
q233668 | manage_work_queue | train | def manage_work_queue(queue_name):
"""Page for viewing the contents of a work queue."""
modify_form = forms.ModifyWorkQueueTaskForm()
if modify_form.validate_on_submit():
primary_key = (modify_form.task_id.data, queue_name)
task = work_queue.WorkQueue.query.get(primary_key)
if task:
... | python | {
"resource": ""
} |
q233669 | retryable_transaction | train | def retryable_transaction(attempts=3, exceptions=(OperationalError,)):
"""Decorator retries a function when expected exceptions are raised."""
assert len(exceptions) > 0
assert attempts > 0
def wrapper(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
for i in xrange(att... | python | {
"resource": ""
} |
q233670 | jsonify_assert | train | def jsonify_assert(asserted, message, status_code=400):
"""Asserts something is true, aborts the request if not."""
if asserted:
return
try:
raise AssertionError(message)
except AssertionError, e:
stack = traceback.extract_stack()
stack.pop()
logging.error('Assert... | python | {
"resource": ""
} |
q233671 | jsonify_error | train | def jsonify_error(message_or_exception, status_code=400):
"""Returns a JSON payload that indicates the request had an error."""
if isinstance(message_or_exception, Exception):
message = '%s: %s' % (
message_or_exception.__class__.__name__, message_or_exception)
else:
message = me... | python | {
"resource": ""
} |
q233672 | ignore_exceptions | train | def ignore_exceptions(f):
"""Decorator catches and ignores any exceptions raised by this function."""
@functools.wraps(f)
def wrapped(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
logging.exception("Ignoring exception in %r", f)
return wrapped | python | {
"resource": ""
} |
q233673 | timesince | train | def timesince(when):
"""Returns string representing "time since" or "time until".
Examples:
3 days ago, 5 hours ago, 3 minutes from now, 5 hours from now, now.
"""
if not when:
return ''
now = datetime.datetime.utcnow()
if now > when:
diff = now - when
suffix = ... | python | {
"resource": ""
} |
q233674 | human_uuid | train | def human_uuid():
"""Returns a good UUID for using as a human readable string."""
return base64.b32encode(
hashlib.sha1(uuid.uuid4().bytes).digest()).lower().strip('=') | python | {
"resource": ""
} |
q233675 | get_deployment_timestamp | train | def get_deployment_timestamp():
"""Returns a unique string represeting the current deployment.
Used for busting caches.
"""
# TODO: Support other deployment situations.
if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'):
version_id = os.environ.get('CURRENT_VERSION_ID'... | python | {
"resource": ""
} |
q233676 | real_main | train | def real_main(new_url=None,
baseline_url=None,
upload_build_id=None,
upload_release_name=None):
"""Runs the ur_pair_diff."""
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
item = UrlPairDiff(
new_url,
... | python | {
"resource": ""
} |
q233677 | fetch_internal | train | def fetch_internal(item, request):
"""Fetches the given request by using the local Flask context."""
# Break client dependence on Flask if internal fetches aren't being used.
from flask import make_response
from werkzeug.test import EnvironBuilder
# Break circular dependencies.
from dpxdt.server... | python | {
"resource": ""
} |
q233678 | fetch_normal | train | def fetch_normal(item, request):
"""Fetches the given request over HTTP."""
try:
conn = urllib2.urlopen(request, timeout=item.timeout_seconds)
except urllib2.HTTPError, e:
conn = e
except (urllib2.URLError, ssl.SSLError), e:
# TODO: Make this status more clear
item.status... | python | {
"resource": ""
} |
q233679 | FetchItem.json | train | def json(self):
"""Returns de-JSONed data or None if it's a different content type."""
if self._data_json:
return self._data_json
if not self.data or self.content_type != 'application/json':
return None
self._data_json = json.loads(self.data)
return self... | python | {
"resource": ""
} |
q233680 | CaptureAndDiffWorkflowItem.maybe_imgur | train | def maybe_imgur(self, path):
'''Uploads a file to imgur if requested via command line flags.
Returns either "path" or "path url" depending on the course of action.
'''
if not FLAGS.imgur_client_id:
return path
im = pyimgur.Imgur(FLAGS.imgur_client_id)
upload... | python | {
"resource": ""
} |
q233681 | real_main | train | def real_main(release_url=None,
tests_json_path=None,
upload_build_id=None,
upload_release_name=None):
"""Runs diff_my_images."""
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
data = open(FLAGS.tests_json_pat... | python | {
"resource": ""
} |
q233682 | clean_url | train | def clean_url(url, force_scheme=None):
"""Cleans the given URL."""
# URL should be ASCII according to RFC 3986
url = str(url)
# Collapse ../../ and related
url_parts = urlparse.urlparse(url)
path_parts = []
for part in url_parts.path.split('/'):
if part == '.':
continue
... | python | {
"resource": ""
} |
q233683 | extract_urls | train | def extract_urls(url, data, unescape=HTMLParser.HTMLParser().unescape):
"""Extracts the URLs from an HTML document."""
parts = urlparse.urlparse(url)
prefix = '%s://%s' % (parts.scheme, parts.netloc)
accessed_dir = os.path.dirname(parts.path)
if not accessed_dir.endswith('/'):
accessed_dir ... | python | {
"resource": ""
} |
q233684 | prune_urls | train | def prune_urls(url_set, start_url, allowed_list, ignored_list):
"""Prunes URLs that should be ignored."""
result = set()
for url in url_set:
allowed = False
for allow_url in allowed_list:
if url.startswith(allow_url):
allowed = True
break
... | python | {
"resource": ""
} |
q233685 | real_main | train | def real_main(start_url=None,
ignore_prefixes=None,
upload_build_id=None,
upload_release_name=None):
"""Runs the site_diff."""
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
item = SiteDiff(
start_url=... | python | {
"resource": ""
} |
q233686 | render_or_send | train | def render_or_send(func, message):
"""Renders an email message for debugging or actually sends it."""
if request.endpoint != func.func_name:
mail.send(message)
if (current_user.is_authenticated() and current_user.superuser):
return render_template('debug_email.html', message=message) | python | {
"resource": ""
} |
q233687 | send_ready_for_review | train | def send_ready_for_review(build_id, release_name, release_number):
"""Sends an email indicating that the release is ready for review."""
build = models.Build.query.get(build_id)
if not build.send_email:
logging.debug(
'Not sending ready for review email because build does not have '
... | python | {
"resource": ""
} |
q233688 | homepage | train | def homepage():
"""Renders the homepage."""
if current_user.is_authenticated():
if not login_fresh():
logging.debug('User needs a fresh token')
abort(login.needs_refresh())
auth.claim_invitations(current_user)
build_list = operations.UserOps(current_user.get_id()).g... | python | {
"resource": ""
} |
q233689 | new_build | train | def new_build():
"""Page for crediting or editing a build."""
form = forms.BuildForm()
if form.validate_on_submit():
build = models.Build()
form.populate_obj(build)
build.owners.append(current_user)
db.session.add(build)
db.session.flush()
auth.save_admin_lo... | python | {
"resource": ""
} |
q233690 | view_build | train | def view_build():
"""Page for viewing all releases in a build."""
build = g.build
page_size = min(request.args.get('page_size', 10, type=int), 50)
offset = request.args.get('offset', 0, type=int)
ops = operations.BuildOps(build.id)
has_next_page, candidate_list, stats_counts = ops.get_candidate... | python | {
"resource": ""
} |
q233691 | view_release | train | def view_release():
"""Page for viewing all tests runs in a release."""
build = g.build
if request.method == 'POST':
form = forms.ReleaseForm(request.form)
else:
form = forms.ReleaseForm(request.args)
form.validate()
ops = operations.BuildOps(build.id)
release, run_list, st... | python | {
"resource": ""
} |
q233692 | _get_artifact_context | train | def _get_artifact_context(run, file_type):
"""Gets the artifact details for the given run and file_type."""
sha1sum = None
image_file = False
log_file = False
config_file = False
if request.path == '/image':
image_file = True
if file_type == 'before':
sha1sum = run.r... | python | {
"resource": ""
} |
q233693 | get_coordinator | train | def get_coordinator():
"""Creates a coordinator and returns it."""
workflow_queue = Queue.Queue()
complete_queue = Queue.Queue()
coordinator = WorkflowThread(workflow_queue, complete_queue)
coordinator.register(WorkflowItem, workflow_queue)
return coordinator | python | {
"resource": ""
} |
q233694 | WorkItem._print_repr | train | def _print_repr(self, depth):
"""Print this WorkItem to the given stack depth.
The depth parameter ensures that we can print WorkItems in
arbitrarily long chains without hitting the max stack depth.
This can happen with WaitForUrlWorkflowItems, which
create long chains of small ... | python | {
"resource": ""
} |
q233695 | ResultList.error | train | def error(self):
"""Returns the error for this barrier and all work items, if any."""
# Copy the error from any failed item to be the error for the whole
# barrier. The first error seen "wins". Also handles the case where
# the WorkItems passed into the barrier have already completed and... | python | {
"resource": ""
} |
q233696 | Barrier.outstanding | train | def outstanding(self):
"""Returns whether or not this barrier has pending work."""
# Allow the same WorkItem to be yielded multiple times but not
# count towards blocking the barrier.
done_count = 0
for item in self:
if not self.wait_any and item.fire_and_forget:
... | python | {
"resource": ""
} |
q233697 | Barrier.get_item | train | def get_item(self):
"""Returns the item to send back into the workflow generator."""
if self.was_list:
result = ResultList()
for item in self:
if isinstance(item, WorkflowItem):
if item.done and not item.error:
result.ap... | python | {
"resource": ""
} |
q233698 | WorkflowThread.start | train | def start(self):
"""Starts the coordinator thread and all related worker threads."""
assert not self.interrupted
for thread in self.worker_threads:
thread.start()
WorkerThread.start(self) | python | {
"resource": ""
} |
q233699 | WorkflowThread.stop | train | def stop(self):
"""Stops the coordinator thread and all related threads."""
if self.interrupted:
return
for thread in self.worker_threads:
thread.interrupted = True
self.interrupted = True | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.