text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _collect_variables(names, expressions=None): """ Map labels and expressions to registered variables. Handles argument matching. Example: _collect_variables(n...
# Map registered variable labels to expressions. if not expressions: expressions = [] offset = len(names) - len(expressions) labels_map = dict(tz.concatv( tz.compatibility.zip(names[:offset], names[:offset]), tz.compatibility.zip(names[offset:], expressions))) all_variables...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_table( table_name, table, cache=False, cache_scope=_CS_FOREVER, copy_col=True): """ Register a table with Orca. Parameters table_name : str Should be glo...
if isinstance(table, Callable): table = TableFuncWrapper(table_name, table, cache=cache, cache_scope=cache_scope, copy_col=copy_col) else: table = DataFrameWrapper(table_name, table, copy_col=copy_col) # clear any cached data from a previously registered ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table( table_name=None, cache=False, cache_scope=_CS_FOREVER, copy_col=True): """ Decorates functions that return DataFrames. Decorator version of `add_table...
def decorator(func): if table_name: name = table_name else: name = func.__name__ add_table( name, func, cache=cache, cache_scope=cache_scope, copy_col=copy_col) return func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_table(table_name): """ Get a registered table. Decorated functions will be converted to `DataFrameWrapper`. Parameters table_name : str Returns ------- t...
table = get_raw_table(table_name) if isinstance(table, TableFuncWrapper): table = table() return table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_type(table_name): """ Returns the type of a registered table. The type can be either "dataframe" or "function". Parameters table_name : str Returns ---...
table = get_raw_table(table_name) if isinstance(table, DataFrameWrapper): return 'dataframe' elif isinstance(table, TableFuncWrapper): return 'function'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_column( table_name, column_name, column, cache=False, cache_scope=_CS_FOREVER): """ Add a new column to a table from a Series or callable. Parameters tab...
if isinstance(column, Callable): column = \ _ColumnFuncWrapper( table_name, column_name, column, cache=cache, cache_scope=cache_scope) else: column = _SeriesWrapper(table_name, column_name, column) # clear any cached data from a previously regist...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column(table_name, column_name=None, cache=False, cache_scope=_CS_FOREVER): """ Decorates functions that return a Series. Decorator version of `add_column`. ...
def decorator(func): if column_name: name = column_name else: name = func.__name__ add_column( table_name, name, func, cache=cache, cache_scope=cache_scope) return func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _columns_for_table(table_name): """ Return all of the columns registered for a given table. Parameters table_name : str Returns ------- columns : dict of col...
return {cname: col for (tname, cname), col in _COLUMNS.items() if tname == table_name}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_raw_column(table_name, column_name): """ Get a wrapped, registered column. This function cannot return columns that are part of wrapped DataFrames, it's ...
try: return _COLUMNS[(table_name, column_name)] except KeyError: raise KeyError('column {!r} not found for table {!r}'.format( column_name, table_name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _memoize_function(f, name, cache_scope=_CS_FOREVER): """ Wraps a function for memoization and ties it's cache into the Orca cacheing system. Parameters f : f...
cache = {} @wraps(f) def wrapper(*args, **kwargs): try: cache_key = ( args or None, frozenset(kwargs.items()) if kwargs else None) in_cache = cache_key in cache except TypeError: raise TypeError( 'function arguments must b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_injectable( name, value, autocall=True, cache=False, cache_scope=_CS_FOREVER, memoize=False): """ Add a value that will be injected into other functions....
if isinstance(value, Callable): if autocall: value = _InjectableFuncWrapper( name, value, cache=cache, cache_scope=cache_scope) # clear any cached data from a previously registered value value.clear_cached() elif not autocall and memoize: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def injectable( name=None, autocall=True, cache=False, cache_scope=_CS_FOREVER, memoize=False): """ Decorates functions that will be injected into other function...
def decorator(func): if name: n = name else: n = func.__name__ add_injectable( n, func, autocall=autocall, cache=cache, cache_scope=cache_scope, memoize=memoize) return func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_injectable_func_source_data(name): """ Return data about an injectable function's source, including file name, line number, and source code. Parameters n...
if injectable_type(name) != 'function': raise ValueError('injectable {!r} is not a function'.format(name)) inj = get_raw_injectable(name) if isinstance(inj, _InjectableFuncWrapper): return utils.func_source_data(inj._func) elif hasattr(inj, '__wrapped__'): return utils.func_so...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_step(step_name, func): """ Add a step function to Orca. The function's argument names and keyword argument values will be matched to registered variables...
if isinstance(func, Callable): logger.debug('registering step {!r}'.format(step_name)) _STEPS[step_name] = _StepFuncWrapper(step_name, func) else: raise TypeError('func must be a callable')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def step(step_name=None): """ Decorates functions that will be called by the `run` function. Decorator version of `add_step`. step name defaults to name of funct...
def decorator(func): if step_name: name = step_name else: name = func.__name__ add_step(name, func) return func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def broadcast(cast, onto, cast_on=None, onto_on=None, cast_index=False, onto_index=False): """ Register a rule for merging two tables by broadcasting one onto th...
logger.debug( 'registering broadcast of table {!r} onto {!r}'.format(cast, onto)) _BROADCASTS[(cast, onto)] = \ Broadcast(cast, onto, cast_on, onto_on, cast_index, onto_index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_broadcasts(tables): """ Get the broadcasts associated with a set of tables. Parameters tables : sequence of str Table names for which broadcasts have be...
tables = set(tables) casts = tz.keyfilter( lambda x: x[0] in tables and x[1] in tables, _BROADCASTS) if tables - set(tz.concat(casts.keys())): raise ValueError('Not enough links to merge all tables.') return casts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_broadcast(cast_name, onto_name): """ Get a single broadcast. Broadcasts are stored data about how to do a Pandas join. A Broadcast object is a namedtuple...
if is_broadcast(cast_name, onto_name): return _BROADCASTS[(cast_name, onto_name)] else: raise KeyError( 'no rule found for broadcasting {!r} onto {!r}'.format( cast_name, onto_name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _all_reachable_tables(t): """ A generator that provides all the names of tables that can be reached via merges starting at the given target table. """
for k, v in t.items(): for tname in _all_reachable_tables(v): yield tname yield k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recursive_getitem(d, key): """ Descend into a dict of dicts to return the one that contains a given key. Every value in the dict must be another dict. """
if key in d: return d else: for v in d.values(): return _recursive_getitem(v, key) else: raise KeyError('Key not found: {}'.format(key))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _next_merge(merge_node): """ Gets a node that has only leaf nodes below it. This table and the ones below are ready to be merged to make a new leaf node. """
if all(_is_leaf_node(d) for d in _dict_value_to_pairs(merge_node)): return merge_node else: for d in tz.remove(_is_leaf_node, _dict_value_to_pairs(merge_node)): return _next_merge(d) else: raise OrcaError('No node found for next merge.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_step_table_names(steps): """ Returns a list of table names injected into the provided steps. Parameters steps: list of str Steps to gather table inputs f...
table_names = set() for s in steps: table_names |= get_step(s)._tables_used() return list(table_names)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_tables(fname, table_names=None, prefix=None, compress=False, local=False): """ Writes tables to a pandas.HDFStore file. Parameters fname : str File nam...
if table_names is None: table_names = list_tables() tables = (get_table(t) for t in table_names) key_template = '{}/{{}}'.format(prefix) if prefix is not None else '{}' # set compression options to zlib level-1 if compress arg is True complib = compress and 'zlib' or None complevel = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(steps, iter_vars=None, data_out=None, out_interval=1, out_base_tables=None, out_run_tables=None, compress=False, out_base_local=True, out_run_local=True):...
iter_vars = iter_vars or [None] max_i = len(iter_vars) # get the tables to write out if out_base_tables is None or out_run_tables is None: step_tables = get_step_table_names(steps) if out_base_tables is None: out_base_tables = step_tables if out_run_tables is None...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def injectables(**kwargs): """ Temporarily add injectables to the pipeline environment. Takes only keyword arguments. Injectables will be returned to their origi...
global _INJECTABLES original = _INJECTABLES.copy() _INJECTABLES.update(kwargs) yield _INJECTABLES = original
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def temporary_tables(**kwargs): """ Temporarily set DataFrames as registered tables. Tables will be returned to their original state when the context manager exi...
global _TABLES original = _TABLES.copy() for k, v in kwargs.items(): if not isinstance(v, pd.DataFrame): raise ValueError('tables only accepts DataFrames') add_table(k, v) yield _TABLES = original
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_variable(name, **kwargs): """ Execute a single variable function registered with Orca and return the result. Any keyword arguments are temporarily set a...
with injectables(**kwargs): vars = _collect_variables([name], [name]) return vars[name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_frame(self, columns=None): """ Make a DataFrame with the given columns. Will always return a copy of the underlying table. Parameters columns : sequence o...
extra_cols = _columns_for_table(self.name) if columns is not None: columns = [columns] if isinstance(columns, str) else columns columns = set(columns) set_extra_cols = set(extra_cols) local_cols = set(self.local.columns) & columns - set_extra_cols ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_col(self, column_name, series): """ Add or replace a column in the underlying DataFrame. Parameters column_name : str Column to add or replace. series...
logger.debug('updating column {!r} in table {!r}'.format( column_name, self.name)) self.local[column_name] = series
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column_type(self, column_name): """ Report column type as one of 'local', 'series', or 'function'. Parameters column_name : str Returns ------- col_type : {'...
extra_cols = list_columns_for_table(self.name) if column_name in extra_cols: col = _COLUMNS[(self.name, column_name)] if isinstance(col, _SeriesWrapper): return 'series' elif isinstance(col, _ColumnFuncWrapper): return 'function' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_col_from_series(self, column_name, series, cast=False): """ Update existing values in a column from another series. Index values must match in both co...
logger.debug('updating column {!r} in table {!r}'.format( column_name, self.name)) col_dtype = self.local[column_name].dtype if series.dtype != col_dtype: if cast: series = series.astype(col_dtype) else: err_msg = "Data type m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_cached(self): """ Remove cached results from this table's computed columns. """
_TABLE_CACHE.pop(self.name, None) for col in _columns_for_table(self.name).values(): col.clear_cached() logger.debug('cleared cached columns for table {!r}'.format(self.name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _call_func(self): """ Call the wrapped function and return the result wrapped by DataFrameWrapper. Also updates attributes like columns, index, and length. "...
if _CACHING and self.cache and self.name in _TABLE_CACHE: logger.debug('returning table {!r} from cache'.format(self.name)) return _TABLE_CACHE[self.name].value with log_start_finish( 'call function to get frame for table {!r}'.format( self.n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_cached(self): """ Remove any cached result of this column. """
x = _COLUMN_CACHE.pop((self.table_name, self.name), None) if x is not None: logger.debug( 'cleared cached value for column {!r} in table {!r}'.format( self.name, self.table_name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_cached(self): """ Clear a cached result for this injectable. """
x = _INJECTABLE_CACHE.pop(self.name, None) if x: logger.debug( 'injectable {!r} removed from cache'.format(self.name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tables_used(self): """ Tables injected into the step. Returns ------- tables : set of str """
args = list(self._argspec.args) if self._argspec.defaults: default_args = list(self._argspec.defaults) else: default_args = [] # Combine names from argument names and argument default values. names = args[:len(args) - len(default_args)] + default_args ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qbe_tree(graph, nodes, root=None): """ Given a graph, nodes to explore and an optinal root, do a breadth-first search in order to return the tree. """
if root: start = root else: index = random.randint(0, len(nodes) - 1) start = nodes[index] # A queue to BFS instead DFS to_visit = deque() cnodes = copy(nodes) visited = set() # Format is (parent, parent_edge, neighbor, neighbor_field) to_visit.append((None, None...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine(items, k=None): """ Create a matrix in wich each row is a tuple containing one of solutions or solution k-esima. """
length_items = len(items) lengths = [len(i) for i in items] length = reduce(lambda x, y: x * y, lengths) repeats = [reduce(lambda x, y: x * y, lengths[i:]) for i in range(1, length_items)] + [1] if k is not None: k = k % length # Python division by default is integer ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pickle_encode(session_dict): "Returns the given session dictionary pickled and encoded as a string." pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) return base64.encodestring(pickled + get_query_hash(pickled).encode())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def func_source_data(func): """ Return data about a function source, including file name, line number, and source code. Parameters func : object May be anything ...
filename = inspect.getsourcefile(func) lineno = inspect.getsourcelines(func)[1] source = inspect.getsource(func) return filename, lineno, source
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(self): """ Checks that there is almost one field to select """
if any(self.errors): # Don't bother validating the formset unless each form is valid on # its own return (selects, aliases, froms, wheres, sorts, groups_by, params) = self.get_query_parts() if not selects: validation_message = _(u"At leas...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_results(self, limit=None, offset=None, query=None, admin_name=None, row_number=False): """ Fetch all results after perform SQL query and """
add_extra_ids = (admin_name is not None) if not query: sql = self.get_raw_query(limit=limit, offset=offset, add_extra_ids=add_extra_ids) else: sql = query if settings.DEBUG: print(sql) cursor = self._db_con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_content_type(content_type): """ Return a tuple of content type and charset. :param content_type: A string describing a content type. """
if '; charset=' in content_type: return tuple(content_type.split('; charset=')) else: if 'text' in content_type: encoding = 'ISO-8859-1' else: try: format = formats.find_by_content_type(content_type) except formats.UnknownFormat: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_http_accept_header(header): """ Return a list of content types listed in the HTTP Accept header ordered by quality. :param header: A string describing ...
components = [item.strip() for item in header.split(',')] l = [] for component in components: if ';' in component: subcomponents = [item.strip() for item in component.split(';')] l.append( ( subcomponents[0], # eg. 'text/html' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_multipart_data(request): """ Parse a request with multipart data. :param request: A HttpRequest instance. """
return MultiPartParser( META=request.META, input_data=StringIO(request.body), upload_handlers=request.upload_handlers, encoding=request.encoding ).parse()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def override_supported_formats(formats): """ Override the views class' supported formats for the decorated function. Arguments: formats -- A list of strings desc...
def decorator(function): @wraps(function) def wrapper(self, *args, **kwargs): self.supported_formats = formats return function(self, *args, **kwargs) return wrapper return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def route(regex, method, name): """ Route the decorated view. :param regex: A string describing a regular expression to which the request path will be matched. :...
def decorator(function): function.route = routes.route( regex = regex, view = function.__name__, method = method, name = name ) @wraps(function) def wrapper(self, *args, **kwargs): return function(self, *args, **kwargs) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def before(method_name): """ Run the given method prior to the decorated view. If you return anything besides ``None`` from the given method, its return values w...
def decorator(function): @wraps(function) def wrapper(self, *args, **kwargs): returns = getattr(self, method_name)(*args, **kwargs) if returns is None: return function(self, *args, **kwargs) else: if isinstance(returns, HttpRespon...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index(self, request): """Render a list of objects."""
objects = self.model.objects.all() return self._render( request = request, template = 'index', context = { cc2us(pluralize(self.model.__name__)): objects, }, status = 200 )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new(self, request): """Render a form to create a new object."""
form = (self.form or generate_form(self.model))() return self._render( request = request, template = 'new', context = { 'form': form }, status = 200 )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit(self, request, id): """Render a form to edit an object."""
try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'error': 'The %s could not be found.' % self.model.__name__.lower...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, request, id): """Update an object."""
try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'error': 'The %s could not be found.' % self.model.__name__.lower...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(self, request, id): """Replace an object."""
try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'error': 'The %s could not be found.' % self.model.__name__.lower...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_q(fields_dict, params_dict, request=None): """ Returns a Q object from filters config and actual parmeters. """
# Building search query # queries generated by different search_fields are ANDed # if a search field is defined for more than one field, are put together with OR and_query = Q() for fieldname in fields_dict: search_field = fields_dict[fieldname] if fieldname in params_dict and para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_search_fields(cls): """ Returns search fields in sfdict """
sfdict = {} for klass in tuple(cls.__bases__) + (cls, ): if hasattr(klass, 'search_fields'): sfdict.update(klass.search_fields) return sfdict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(identifier): """ Find and return a format by name, acronym or extension. :param identifier: A string describing the format. """
for format in FORMATS: if identifier in [format.name, format.acronym, format.extension]: return format raise UnknownFormat('No format found with name, acronym or extension "%s"' % identifier)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by_name(name): """ Find and return a format by name. :param name: A string describing the name of the format. """
for format in FORMATS: if name == format.name: return format raise UnknownFormat('No format found with name "%s"' % name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by_extension(extension): """ Find and return a format by extension. :param extension: A string describing the extension of the format. """
for format in FORMATS: if extension in format.extensions: return format raise UnknownFormat('No format found with extension "%s"' % extension)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by_content_type(content_type): """ Find and return a format by content type. :param content_type: A string describing the internet media type of the for...
for format in FORMATS: if content_type in format.content_types: return format raise UnknownFormat('No format found with content type "%s"' % content_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def options(self, request, map, *args, **kwargs): """List communication options."""
options = {} for method, function in map.items(): options[method] = function.__doc__ return self._render( request = request, template = 'options', context = { 'options': options }, status = 200, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_format(self, request): """ Determine and return a 'formats.Format' instance describing the most desired response format that is supported by these views...
# Derive a list of 'formats.Format' instances from the list of formats these views support. supported_formats = [formats.find(format) for format in self.supported_formats] # Determine format by extension... if '.' in request.path: extension = request.path.split('.')[-1] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render(self, request, template=None, status=200, context={}, headers={}, prefix_template_path=True): """ Render a HTTP response. :param request: A django.ht...
format = self._get_format(request) # Render 406 Not Acceptable if the requested format isn't supported. if not format: return HttpResponse(status=406) if template: if prefix_template_path: template_path = '%s.%s' % (self.template_path + templa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _error(self, request, status, headers={}, prefix_template_path=False, **kwargs): """ Convenience method to render an error response. The template is inferred...
return self._render( request = request, template = str(status), status = status, context = { 'error': kwargs }, headers = headers, prefix_template_path = prefix_template_path )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(format): """ Find and return a serializer for the given format. Arguments: format -- A Format instance. """
try: serializer = SERIALIZERS[format] except KeyError: raise UnknownSerializer('No serializer found for %s' % format.acronym) return serializer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the search form. """
update_data ={} sfdict = self.filter_class.get_search_fields() for fieldname in sfdict: try: has_multiple = sfdict[fieldname].get('multiple', False) except: has_multiple = False if has_multiple: value = self.re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pluralize(word) : """Pluralize an English noun."""
rules = [ ['(?i)(quiz)$' , '\\1zes'], ['^(?i)(ox)$' , '\\1en'], ['(?i)([m|l])ouse$' , '\\1ice'], ['(?i)(matr|vert|ind)ix|ex$' , '\\1ices'], ['(?i)(x|ch|ss|sh)$' , '\\1es'], ['(?i)([^aeiouy]|qu)ies$' , '\\1y'], ['(?i)([^aeiouy]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def us2mc(string): """Transform an underscore_case string to a mixedCase string"""
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_form(model, form=None, fields=False, exclude=False): """ Generate a form from a model. :param model: A Django model. :param form: A Django form. :pa...
_model, _fields, _exclude = model, fields, exclude class Form(form or forms.ModelForm): class Meta: model = _model if _fields is not False: fields = _fields if _exclude is not False: exclude = _exclude return Form
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_double_norm(mean, std_upper, std_lower, size): """Note that this function requires Scipy."""
from scipy.special import erfinv # There's probably a better way to do this. We first draw percentiles # uniformly between 0 and 1. We want the peak of the distribution to occur # at `mean`. However, if we assign 50% of the samples to the lower half # and 50% to the upper half, the side with the s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_gamma_params(mode, std): """Given a modal value and a standard deviation, compute corresponding parameters for the gamma distribution. Intended to be us...
if mode < 0: raise ValueError('input mode must be positive for gamma; got %e' % mode) var = std**2 beta = (mode + np.sqrt(mode**2 + 4 * var)) / (2 * var) j = 2 * var / mode**2 alpha = (j + 1 + np.sqrt(2 * j + 1)) / j if alpha <= 1: raise ValueError('couldn\'t compute self-cons...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lval_add_towards_polarity(x, polarity): """Compute the appropriate Lval "kind" for the limit of value `x` towards `polarity`. Either 'toinf' or 'pastzero' d...
if x < 0: if polarity < 0: return Lval('toinf', x) return Lval('pastzero', x) elif polarity > 0: return Lval('toinf', x) return Lval('pastzero', x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def limtype(msmt): """Return -1 if this value is some kind of upper limit, 1 if this value is some kind of lower limit, 0 otherwise."""
if np.isscalar(msmt): return 0 if isinstance(msmt, Uval): return 0 if isinstance(msmt, Lval): if msmt.kind == 'undef': raise ValueError('no simple limit type for Lval %r' % msmt) # Quasi-hack here: limits of ('tozero', [positive number]) are # reported ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_pcount(nevents): """We assume a Poisson process. nevents is the number of events in some interval. The distribution of values is the distribution of the...
if nevents < 0: raise ValueError('Poisson parameter `nevents` must be nonnegative') return Uval(np.random.gamma(nevents + 1, size=uval_nsamples))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repvals(self, method): """Compute representative statistical values for this Uval. `method` may be either 'pct' or 'gauss'. Returns (best, plus_one_sigma, mi...
if method == 'pct': return pk_scoreatpercentile(self.d, [50., 84.134, 15.866]) if method == 'gauss': m, s = self.d.mean(), self.d.std() return np.asarray([m, m + s, m - s]) raise ValueError('unknown representative-value method "%s"' % method)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repval(self, limitsok=False): """Get a best-effort representative value as a float. This can be DANGEROUS because it discards limit information, which is rar...
if not limitsok and self.dkind in ('lower', 'upper'): raise LimitError() if self.dkind == 'unif': lower, upper = map(float, self.data) v = 0.5 * (lower + upper) elif self.dkind in _noextra_dkinds: v = float(self.data) elif self.dkind in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def moreland_adjusthue (msh, m_unsat): """Moreland's AdjustHue procedure to adjust the hue value of an Msh color *msh* should be of of shape (3, ). *m_unsat* is ...
if msh[M] >= m_unsat: return msh[H] # "Best we can do" hspin = (msh[S] * np.sqrt (m_unsat**2 - msh[M]**2) / (msh[M] * np.sin (msh[S]))) if msh[H] > -np.pi / 3: # "Spin away from purple" return msh[H] + hspin return msh[H] - hspin
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_datasets_in_nodes(): """ Get the node associated with each dataset. Some datasets will have an ambiguous node since they exists in more than one node. ""...
data_dir = os.path.join(scriptdir, "..", "usgs", "data") cwic = map(lambda d: d["datasetName"], api.datasets(None, CWIC_LSI_EXPLORER_CATALOG_NODE)['data']) ee = map(lambda d: d["datasetName"], api.datasets(None, EARTH_EXPLORER_CATALOG_NODE)['data']) hdds = map(lambda d: d["datasetName"], api.datasets...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pivot_wavelength_ee(bpass): """Compute pivot wavelength assuming equal-energy convention. `bpass` should have two properties, `resp` and `wlen`. The units of...
from scipy.integrate import simps return np.sqrt(simps(bpass.resp, bpass.wlen) / simps(bpass.resp / bpass.wlen**2, bpass.wlen))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_std_registry(): """Get a Registry object pre-filled with information for standard telescopes. """
from six import itervalues reg = Registry() for fn in itervalues(builtin_registrars): fn(reg) return reg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pivot_wavelength(self): """Get the bandpass' pivot wavelength. Unlike calc_pivot_wavelength(), this function will use a cached value if available. """
wl = self.registry._pivot_wavelengths.get((self.telescope, self.band)) if wl is not None: return wl wl = self.calc_pivot_wavelength() self.registry.register_pivot_wavelength(self.telescope, self.band, wl) return wl
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_halfmax_points(self): """Calculate the wavelengths of the filter half-maximum values. """
d = self._ensure_data() return interpolated_halfmax_points(d.wlen, d.resp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def halfmax_points(self): """Get the bandpass' half-maximum wavelengths. These can be used to compute a representative bandwidth, or for display purposes. Unlike...
t = self.registry._halfmaxes.get((self.telescope, self.band)) if t is not None: return t t = self.calc_halfmax_points() self.registry.register_halfmaxes(self.telescope, self.band, t[0], t[1]) return t
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bands(self, telescope): """Return a list of bands associated with the specified telescope."""
q = self._seen_bands.get(telescope) if q is None: return [] return list(q)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_pivot_wavelength(self, telescope, band, wlen): """Register precomputed pivot wavelengths."""
if (telescope, band) in self._pivot_wavelengths: raise AlreadyDefinedError('pivot wavelength for %s/%s already ' 'defined', telescope, band) self._note(telescope, band) self._pivot_wavelengths[telescope,band] = wlen return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_halfmaxes(self, telescope, band, lower, upper): """Register precomputed half-max points."""
if (telescope, band) in self._halfmaxes: raise AlreadyDefinedError('half-max points for %s/%s already ' 'defined', telescope, band) self._note(telescope, band) self._halfmaxes[telescope,band] = (lower, upper) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_bpass(self, telescope, klass): """Register a Bandpass class."""
if telescope in self._bpass_classes: raise AlreadyDefinedError('bandpass class for %s already ' 'defined', telescope) self._note(telescope, None) self._bpass_classes[telescope] = klass return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, telescope, band): """Get a Bandpass object for a known telescope and filter."""
klass = self._bpass_classes.get(telescope) if klass is None: raise NotDefinedError('bandpass data for %s not defined', telescope) bp = klass() bp.registry = self bp.telescope = telescope bp.band = band return bp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_data(self, band): """From the WISE All-Sky Explanatory Supplement, IV.4.h.i.1, and Jarrett+ 2011. These are relative response per erg and so can be int...
# `band` should be 1, 2, 3, or 4. df = bandpass_data_frame('filter_wise_' + str(band) + '.dat', 'wlen resp uncert') df.wlen *= 1e4 # micron to Angstrom df.uncert *= df.resp / 1000. # parts per thou. to absolute values. lo, hi = self._filter_subsets[band] df = df[lo:hi] #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_comment_body(body): """Returns given comment HTML as plaintext. Converts all HTML tags and entities within 4chan comments into human-readable text equi...
body = _parser.unescape(body) body = re.sub(r'<a [^>]+>(.+?)</a>', r'\1', body) body = body.replace('<br>', '\n') body = re.sub(r'<.+?>', '', body) return body
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_wcs (fitsheader): """For compatibility between astropy and pywcs."""
wcsmodule = _load_wcs_module () is_pywcs = hasattr (wcsmodule, 'UnitConverter') wcs = wcsmodule.WCS (fitsheader) wcs.wcs.set () wcs.wcs.fix () # I'm interested in MJD computation via datfix() if hasattr (wcs, 'wcs_pix2sky'): wcs.wcs_pix2world = wcs.wcs_pix2sky wcs.wcs_world2pi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanitize_unicode(item): """Safely pass string values to the CASA tools. item A value to be passed to a CASA tool. In Python 2, the bindings to CASA tasks exp...
if isinstance(item, text_type): return item.encode('utf8') if isinstance(item, dict): return dict((sanitize_unicode(k), sanitize_unicode(v)) for k, v in six.iteritems(item)) if isinstance(item,(list, tuple)): return item.__class__(sanitize_unicode(x) for x in item) from ...io i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def datadir(*subdirs): """Get a path within the CASA data directory. subdirs Extra elements to append to the returned path. This function locates the directory w...
import os.path data = None if 'CASAPATH' in os.environ: data = os.path.join(os.environ['CASAPATH'].split()[0], 'data') if data is None: # The Conda CASA directory layout: try: import casadef except ImportError: pass else: dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logger(filter='WARN'): """Set up CASA to write log messages to standard output. filter The log level filter: less urgent messages will not be shown. Valid va...
import os, shutil, tempfile cwd = os.getcwd() tempdir = None try: tempdir = tempfile.mkdtemp(prefix='casautil') try: os.chdir(tempdir) sink = tools.logsink() sink.setlogfile(sanitize_unicode(os.devnull)) try: os.unlink('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forkandlog(function, filter='INFO5', debug=False): """Fork a child process and read its CASA log output. function A function to run in the child process filt...
import sys, os readfd, writefd = os.pipe() pid = os.fork() if pid == 0: # Child process. We never leave this branch. # # Log messages of priority >WARN are sent to stderr regardless of the # status of log.showconsole(). The idea is for this subprocess to be # s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_extended(scene, resp): """ Parse metadata returned from the metadataUrl of a USGS scene. :param scene: Dictionary representation of a USGS scene :param ...
root = ElementTree.fromstring(resp.text) items = root.findall("eemetadata:metadataFields/eemetadata:metadataField", NAMESPACES) scene['extended'] = {item.attrib.get('name').strip(): xsi.get(item[0]) for item in items} return scene
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _async_requests(urls): """ Sends multiple non-blocking requests. Returns a list of responses. :param urls: List of urls """
session = FuturesSession(max_workers=30) futures = [ session.get(url) for url in urls ] return [ future.result() for future in futures ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metadata(dataset, node, entityids, extended=False, api_key=None): """ Request metadata for a given scene in a USGS dataset. :param dataset: :param node: :par...
api_key = _get_api_key(api_key) url = '{}/metadata'.format(USGS_API) payload = { "jsonRequest": payloads.metadata(dataset, node, entityids, api_key=api_key) } r = requests.post(url, payload) response = r.json() _check_for_usgs_error(response) if extended: metadata_url...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reraise_context(fmt, *args): """Reraise an exception with its message modified to specify additional context. This function tries to help provide context whe...
import sys if len(args): cstr = fmt % args else: cstr = text_type(fmt) ex = sys.exc_info()[1] if isinstance(ex, EnvironmentError): ex.strerror = '%s: %s' % (cstr, ex.strerror) ex.args = (ex.errno, ex.strerror) else: if len(ex.args): cstr = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """Return a shallow copy of this object. """
new = self.__class__() new.__dict__ = dict(self.__dict__) return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_boards(*args, **kwargs): """Returns every board on 4chan. Returns: dict of :class:`basc_py4chan.Board`: All boards. """
# Use https based on how the Board class instances are to be instantiated https = kwargs.get('https', args[1] if len(args) > 1 else False) # Dummy URL generator, only used to generate the board list which doesn't # require a valid board name url_generator = Url(None, https) _fetch_boards_metad...