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 convert_to_uri(self, value, strip_iri=True):
''' converts a prefixed rdf ns equivalent value to its uri form.
If not found returns the value as is
args:
value: the URI/IRI to convert
strip_iri: removes the < and > signs
rdflib_uri: ret... |
<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_uri_parts(self, value):
"""takes an value and returns a tuple of the parts args: value: a uri in any form pyuri, ttl or full IRI """ |
if value.startswith('pyuri_'):
value = self.rpyhttp(value)
parts = self.parse_uri(value)
try:
return (self.ns_dict[parts[0]], parts[1])
except KeyError:
try:
return (self.ns_dict[parts[0].lower()], parts[1])
except KeyError... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rpyhttp(value):
""" converts a no namespace pyuri back to a standard uri """ |
if value.startswith("http"):
return value
try:
parts = value.split("_")
del parts[0]
_uri = base64.b64decode(parts.pop(0)).decode()
return _uri + "_".join(parts)
except (IndexError, UnicodeDecodeError, binascii.Error):
# if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyhttp(self, value):
""" converts a no namespaces uri to a python excessable name """ |
if value.startswith("pyuri_"):
return value
parts = self.parse_uri(value)
return "pyuri_%s_%s" % (base64.b64encode(bytes(parts[0],
"utf-8")).decode(),
parts[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 iri(uri_string):
"""converts a string to an IRI or returns an IRI if already formated Args: uri_string: uri in string format Returns: formated uri with <> ""... |
uri_string = str(uri_string)
if uri_string[:1] == "?":
return uri_string
if uri_string[:1] == "[":
return uri_string
if uri_string[:1] != "<":
uri_string = "<{}".format(uri_string.strip())
if uri_string[len(uri_string)-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 convert_to_ttl(self, value):
''' converts a value to the prefixed rdf ns equivalent. If not found
returns the value as is.
args:
value: the value to convert
'''
parsed = self.parse_uri(value)
try:
rtn_val = "%s:%s" % (self.uri_dict[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 convert_to_ns(self, value):
''' converts a value to the prefixed rdf ns equivalent. If not found
returns the value as is
args:
value: the value to convert
'''
parsed = self.parse_uri(value)
try:
rtn_val = "%s_%s" % (self.uri_dict[parsed[0... |
<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_stack_frame(stacklevel):
""" utility functions to get a stackframe, skipping internal frames. """ |
stacklevel = stacklevel + 1
if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)):
# If frame is too small to care or if the warning originated in
# internal code, then do not try to hide any frames.
frame = sys._getframe(stacklevel)
else:
frame = sys._getframe(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 warn(message, category=None, stacklevel=1, emitstacklevel=1):
"""Issue a warning, or maybe ignore it or raise an exception. Duplicate of the standard library... |
# Check if message is already a Warning object
####################
### Get category ###
####################
if isinstance(message, Warning):
category = message.__class__
# Check category argument
if category is None:
category = UserWarning
if not (isinstance(category,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_proxy_filter(warningstuple):
"""set up a proxy that store too long warnings in a separate map""" |
if len(warningstuple) > 5:
key = len(_proxy_map)+1
_proxy_map[key] = warningstuple
# always is pass-through further in the code.
return ('always', re_matchall, ProxyWarning, re_matchall, key)
else:
return warningstuple |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(ctx, deploy=False, test=False, version=''):
"""Tag release, run Travis-CI, and deploy to PyPI """ |
if test:
run("python setup.py check")
run("python setup.py register sdist upload --dry-run")
if deploy:
run("python setup.py check")
if version:
run("git checkout master")
run("git tag -a v{ver} -m 'v{ver}'".format(ver=version))
run("git push... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def squarify_table(table):
'''
Updates a table so that all rows are the same length by filling smaller
rows with 'None' objects up to the length of the largest row.
'''
max_length = 0
min_length = maxsize
for row in table:
row_len = len(row)
if row_len > max_length:
... |
<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_process_cwd(pid):
""" Returns the working directory for the provided process identifier. `pid` System process identifier. Returns string or ``None``. No... |
cmd = 'lsof -a -p {0} -d cwd -Fn'.format(pid)
data = common.shell_process(cmd)
if not data is None:
lines = str(data).split('\n')
# the cwd is the second line with 'n' prefix removed from value
if len(lines) > 1:
return lines[1][1:] or None
return 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 _get_checksum(path):
""" Generates a md5 checksum of the file at the specified path. `path` Path to file for checksum. Returns string or ``None`` """ |
# md5 uses a 512-bit digest blocks, let's scale by defined block_size
_md5 = hashlib.md5()
chunk_size = 128 * _md5.block_size
try:
with open(path, 'rb') as _file:
for chunk in iter(lambda: _file.read(chunk_size), ''):
_md5.update(chunk)
return _md5.hexdiges... |
<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_user_processes():
""" Gets process information owned by the current user. Returns generator of tuples: (``psutil.Process`` instance, path). """ |
uid = os.getuid()
for proc in psutil.process_iter():
try:
# yield processes that match current user
if proc.uids.real == uid:
yield (proc, proc.exe)
except psutil.AccessDenied:
# work around for suid/sguid processes and MacOS X restrictions... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stop_processes(paths):
""" Scans process list trying to terminate processes matching paths specified. Uses checksums to identify processes that are duplicat... |
def cache_checksum(path):
""" Checksum provided path, cache, and return value.
"""
if not path:
return None
if not path in _process_checksums:
checksum = _get_checksum(path)
_process_checksums[path] = checksum
return _process_checks... |
<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_apps(self, paths):
""" Runs apps for the provided paths. """ |
for path in paths:
common.shell_process(path, background=True)
time.sleep(0.2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def norm_mle(data, algorithm='Nelder-Mead', debug=False):
"""Estimate Mean and Std.Dev. of the Normal Distribution Parameters: data : list, tuple, ndarray vector... |
import scipy.stats as sstat
import scipy.optimize as sopt
def objective_nll_norm_uni(theta, data):
return -1.0 * sstat.norm.logpdf(
data, loc=theta[0], scale=theta[1]).sum()
# check eligible algorithm
if algorithm not in ('Nelder-Mead', 'CG', 'BFGS'):
raise Exception('... |
<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, status_item):
""" queries the database and returns that status of the item. args: status_item: the name of the item to check """ |
lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
lg.setLevel(self.log_level)
sparql = '''
SELECT ?loaded
WHERE {{
kdr:{0} kds:{1} ?loaded .
}}'''
value = self.conn.query(sparql=sparql.format(self.group, status_item))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def local_machine_uuid():
"""Return local machine unique identifier. """ |
result = subprocess.check_output(
'hal-get-property --udi '
'/org/freedesktop/Hal/devices/computer '
'--key system.hardware.uuid'.split()
).strip()
return uuid.UUID(hex=result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, required=False):
"""Read Zookeeper state. Read in the current Zookeeper state for this node. This operation should be called prior to other intera... |
self._pristine_cache = {}
self._cache = {}
try:
data, stat = yield self._client.get(self._path)
data = yaml.load(data)
if data:
self._pristine_cache = data
self._cache = data.copy()
except NoNodeException:
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 write(self):
"""Write object state to Zookeeper. This will write the current state of the object to Zookeeper, taking the final merged state as the new one, ... |
self._check()
cache = self._cache
pristine_cache = self._pristine_cache
self._pristine_cache = cache.copy()
# Used by `apply_changes` function to return the changes to
# this scope.
changes = []
def apply_changes(content, stat):
"""Apply the... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printif(self, obj_print, tipo_print=None):
"""Color output & logging.""" |
if self.verbose:
print(obj_print)
if tipo_print == 'ok':
logging.info(obj_print)
elif tipo_print == 'error':
logging.error(obj_print)
elif tipo_print == 'warning':
logging.warning(obj_print) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info_data(self, data_info=None, completo=True, key=None, verbose=True):
"""Show some info.""" |
def _info_dataframe(data_frame):
if completo:
print('\n', data_frame.info(), '\n', data_frame.describe(), '\n')
print(data_frame.head())
print(data_frame.tail())
if verbose:
if data_info is None:
_info_dataframe(self.data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_services():
""" returns list of available services """ |
for importer, modname, ispkg in pkgutil.iter_modules(services.__path__):
if ispkg is False:
importer.find_module(modname).load_module(modname)
services_list = list()
for s in services.serviceBase.__subclasses__():
services_list.append(s.__name__.lower())
return services_li... |
<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_model_class(cls, name, table_name, attrs, validations=None, *, otherattrs=None, other_bases=None):
"""Creates a new class derived from ModelBase.""" |
members = dict(table_name=table_name, attrs=attrs, validations=validations or [])
if otherattrs:
members.update(otherattrs)
return type(name, other_bases or (), members) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_attr(cls, attr_name):
"""Check to see if an attribute is defined for the model.""" |
if attr_name in cls.attrs:
return True
if isinstance(cls.primary_key_name, str) and cls.primary_key_name == attr_name:
return True
if isinstance(cls.primary_key_name, tuple) and attr_name in cls.primary_key_name:
return True
if cls.timestamps is not None and attr_name in cls.timest... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def primary_key(self):
"""Returns either the primary key value, or a tuple containing the primary key values in the case of a composite primary key. """ |
pkname = self.primary_key_name
if pkname is None:
return None
elif isinstance(pkname, str):
return getattr(self, pkname)
else:
return tuple((getattr(self, pkn) for pkn in pkname)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self, data_access=None):
"""Run the class validations against the instance. If the validations require database access, pass in a DataAccess derived... |
self.clear_errors()
self.before_validation()
self.validator.validate(self, data_access)
return not self.has_errors |
<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_error(self, property_name, message):
"""Add an error for the given property.""" |
if property_name not in self.errors:
self.errors[property_name] = []
self.errors[property_name].append(message) |
<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_errors(self, joiner="; "):
"""Returns a string representation of all errors recorded for the instance.""" |
parts = []
for pname, errs in self.errors.items():
for err in errs:
parts.append("{0}: {1}".format(pname, err))
return joiner.join(parts) |
<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_dict(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True):
"""Converts the class to a dictionary. :include_keys: if not None, only th... |
data = self.__dict__
if include_keys:
return pick(data, include_keys, transform=self._other_to_dict)
else:
skeys = self.exclude_keys_serialize if use_default_excludes else None
ekeys = exclude_keys
return exclude(
data,
lambda k: (skeys is not None and k in skeys) ... |
<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_json(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True, pretty=False):
"""Converts the response from to_dict to a JSON string. If p... |
return to_json(
self.to_dict(
include_keys=include_keys,
exclude_keys=exclude_keys,
use_default_excludes=use_default_excludes),
pretty=pretty) |
<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, data_=None, **kwargs):
"""Update the object with the given data object, and with any other key-value args. Returns a set containing all the prop... |
if data_ is None:
data_ = dict()
else:
data_ = dict(data_)
data_.update(**kwargs)
changes = set()
for attr_name in data_:
if hasattr(self, attr_name):
if getattr(self, attr_name) != data_[attr_name]:
changes.add(attr_name)
setattr(self, attr_name, data_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(self, args):
""" Calls proper method depending on command-line arguments. """ |
if not args.list and not args.group:
if not args.font and not args.char and not args.block:
self.info()
return
else:
args.list = args.group = True
self._display = {k: args.__dict__[k] for k in ('list', 'group', 'omit_summary')}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chars(self, font, block):
""" Analyses characters in single font or all fonts. """ |
if font:
font_files = self._getFont(font)
else:
font_files = fc.query()
code_points = self._getFontChars(font_files)
if not block:
blocks = all_blocks
ranges_column = map(itemgetter(3), blocks)
overlapped = Ranges(code_points)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def char(self, char):
""" Shows all system fonts that contain given character. """ |
font_files = fc.query()
if self._display['group']:
font_files = self._getCharFont(font_files, char)
font_families = self._groupFontByFamily(font_files)
for font_family in sorted(font_families):
print(font_family)
if self._display['list... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fontChar(self, font, char):
""" Checks if characters occurs in the given font. """ |
font_files = self._getCharFont(self._getFont(font), char)
print('The character is {0}present in this font.'.format('' if font_files else 'not ')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _charInfo(self, point, padding):
""" Displays character info. """ |
print('{0:0>4X} '.format(point).rjust(padding), ud.name(chr(point), '<code point {0:0>4X}>'.format(point))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _charSummary(self, char_count, block_count=None):
""" Displays characters summary. """ |
if not self._display['omit_summary']:
if block_count is None:
print('Total code points:', char_count)
else:
print('Total {0} code point{1} in {2} block{3}'.format(
char_count,
's' if char_count != 1 else '',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fontSummary(self, font_file_count, font_family_count=None):
""" Displays fonts summary. """ |
if not self._display['omit_summary']:
if font_family_count is None:
print('Total font files:', font_file_count)
else:
print('The character is present in {0} font file{1} and {2} font famil{3}'.format(
font_file_count,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getChar(self, char_spec):
""" Returns character from given code point or character. """ |
if len(char_spec) >= 4 and all(c in string.hexdigits for c in char_spec):
char_number = int(char_spec, 16)
if char_number not in range(0x110000):
raise ValueError('No such character')
return chr(char_number)
elif len(char_spec) == 1:
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getBlock(self, block_spec):
""" Returns block info from given block start code point or block name. """ |
if block_spec is None:
return
if all(c in string.hexdigits for c in block_spec):
block_spec = block_spec.upper()
ix = 0
else:
ix = 2
for block in all_blocks:
if block[ix] == block_spec:
return block
rais... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getFont(self, font):
""" Returns font paths from font name or path """ |
if os.path.isfile(font):
font_files = [font]
else:
font_files = fc.query(family=font)
if not font_files:
raise ValueError('No such font')
return font_files |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getFontChars(self, font_files):
""" Returns code points of characters included in given font files. """ |
code_points = set()
for font_file in font_files:
face = ft.Face(font_file)
charcode, agindex = face.get_first_char()
while agindex != 0:
code_points.add(charcode)
charcode, agindex = face.get_next_char(charcode, agindex)
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getCharFont(self, font_files, code_point):
""" Returns font files containing given code point. """ |
return_font_files = []
for font_file in font_files:
face = ft.Face(font_file)
if face.get_char_index(code_point):
return_font_files.append(font_file)
return return_font_files |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _groupFontByFamily(self, font_files):
""" Returns font files grouped in dict by font family. """ |
font_families = defaultdict(list)
for font_file in font_files:
font = fc.FcFont(font_file)
font_families[font.family[0][1]].append(font_file)
return font_families |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ListField(field):
""" This wraps a field so that when get_from_instance is called, the field's values are iterated over """ |
# alter the original field's get_from_instance so it iterates over the
# values that the field's get_from_instance() method returns
original_get_from_instance = field.get_from_instance
def get_from_instance(self, instance):
for value in original_get_from_instance(instance):
yield v... |
<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_from_instance(self, instance):
""" Given an object to index with ES, return the value that should be put into ES for this field """ |
# walk the attribute path to get the value. Similarly to Django, first
# try getting the value from a dict, then as a attribute lookup, and
# then as a list index
for attr in self._path:
try: # dict lookup
instance = instance[attr]
except (TypeErr... |
<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_query_series(queries, conn):
""" Iterates through a list of queries and runs them through the connection Args: ----- queries: list of strings or tuples c... |
results = []
for item in queries:
qry = item
kwargs = {}
if isinstance(item, tuple):
qry = item[0]
kwargs = item[1]
result = conn.update_query(qry, **kwargs)
# pdb.set_trace()
results.append(result)
return results |
<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_item_data(items, conn, graph=None, output='json', **kwargs):
""" queries a triplestore with the provided template or uses a generic template that ret... |
# set the jinja2 template to use
if kwargs.get('template'):
template = kwargs.pop('template')
else:
template = "sparqlAllItemDataTemplate.rq"
# build the keyword arguments for the templace
template_kwargs = {"prefix": NSM.prefix(), "output": output}
if isinstance(items, list):
... |
<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_graph(graph, conn, **kwargs):
""" Returns all the triples for a specific are graph args: graph: the URI of the graph to retreive conn: the rdfframework t... |
sparql = render_without_request("sparqlGraphDataTemplate.rq",
prefix=NSM.prefix(),
graph=graph)
return conn.query(sparql, **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 make_sparql_filter(filters):
""" Make the filter section for a query template args: filters: list of dictionaries to generate the filter example: filters = [... |
def make_filter_str(variable, operator, union_type, values):
""" generates a filter string for a sparql query
args:
variable: the variable to reference
operator: '=' or '!='
union_type" '&&' or '||'
values: list of values to apply the filter
... |
<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_sparql_line_nums(sparql):
""" Returns a sparql query with line numbers prepended """ |
lines = sparql.split("\n")
return "\n".join(["%s %s" % (i + 1, line) for i, line in enumerate(lines)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string_value(node):
"""Compute the string-value of a node.""" |
if (node.nodeType == node.DOCUMENT_NODE or
node.nodeType == node.ELEMENT_NODE):
s = u''
for n in axes['descendant'](node):
if n.nodeType == n.TEXT_NODE:
s += n.data
return s
elif node.nodeType == node.ATTRIBUTE_NODE:
return node.value
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def document_order(node):
"""Compute a document order value for the node. cmp(document_order(a), document_order(b)) will return -1, 0, or 1 if a is before, ident... |
# Attributes: parent-order + [-1, attribute-name]
if node.nodeType == node.ATTRIBUTE_NODE:
order = document_order(node.ownerElement)
order.extend((-1, node.name))
return order
# The document root (hopefully): []
if node.parentNode is None:
return []
# Determine wh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string(v):
"""Convert a value to a string.""" |
if nodesetp(v):
if not v:
return u''
return string_value(v[0])
elif numberp(v):
if v == float('inf'):
return u'Infinity'
elif v == float('-inf'):
return u'-Infinity'
elif str(v) == 'nan':
return u'NaN'
elif int(v) =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def boolean(v):
"""Convert a value to a boolean.""" |
if nodesetp(v):
return len(v) > 0
elif numberp(v):
if v == 0 or v != v:
return False
return True
elif stringp(v):
return v != ''
return v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def number(v):
"""Convert a value to a number.""" |
if nodesetp(v):
v = string(v)
try:
return float(v)
except ValueError:
return float('NaN') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def numberp(v):
"""Return true iff 'v' is a number.""" |
return (not(isinstance(v, bool)) and
(isinstance(v, int) or isinstance(v, float))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def axisfn(reverse=False, principal_node_type=xml.dom.Node.ELEMENT_NODE):
"""Axis function decorator. An axis function will take a node as an argument and return... |
def decorate(f):
f.__name__ = f.__name__.replace('_', '-')
f.reverse = reverse
f.principal_node_type = principal_node_type
return f
return decorate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_axes():
"""Define functions to walk each of the possible XPath axes.""" |
@axisfn()
def child(node):
return node.childNodes
@axisfn()
def descendant(node):
for child in node.childNodes:
for node in descendant_or_self(child):
yield node
@axisfn()
def parent(node):
if node.parentNode is not None:
yield ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_into_nodeset(target, source):
"""Place all the nodes from the source node-set into the target node-set, preserving document order. Both node-sets must ... |
if len(target) == 0:
target.extend(source)
return
source = [n for n in source if n not in target]
if len(source) == 0:
return
# If the last node in the target set comes before the first node in the
# source set, then we can just concatenate the sets. Otherwise, we
# w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_response(self, msg):
""" setup response if correlation id is the good one """ |
LOGGER.debug("natsd.Requester.on_response: " + str(sys.getsizeof(msg)) + " bytes received")
working_response = json.loads(msg.data.decode())
working_properties = DriverTools.json2properties(working_response['properties'])
working_body = b''+bytes(working_response['body'], 'utf8') if 'bo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ttl(self):
"""Get actual ttl in seconds. :return: actual ttl. :rtype: float """ |
# result is self ts
result = getattr(self, Annotation.__TS, None)
# if result is not None
if result is not None:
# result is now - result
now = time()
result = result - now
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ttl(self, value):
"""Change self ttl with input value. :param float value: new ttl in seconds. """ |
# get timer
timer = getattr(self, Annotation.__TIMER, None)
# if timer is running, stop the timer
if timer is not None:
timer.cancel()
# initialize timestamp
timestamp = None
# if value is None
if value is None:
# nonify timer
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_memory(self, value):
"""Add or remove self from global memory. :param bool value: if True(False) ensure self is(is not) in memory. """ |
self_class = self.__class__
memory = Annotation.__ANNOTATIONS_IN_MEMORY__
if value:
annotations_memory = memory.setdefault(self_class, set())
annotations_memory.add(self)
else:
if self_class in memory:
annotations_memory = memory[se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind_target(self, target, ctx=None):
"""Bind self annotation to target. :param target: target to annotate. :param ctx: target ctx. :return: bound target. """ |
# process self _bind_target
result = self._bind_target(target=target, ctx=ctx)
# fire on bind target event
self.on_bind_target(target=target, ctx=ctx)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bind_target(self, target, ctx=None):
"""Method to override in order to specialize binding of target. :param target: target to bind. :param ctx: target ctx. ... |
result = target
try:
# get annotations from target if exists.
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__, [], ctx=ctx
)
except TypeError:
raise TypeError('target {0} must be hashable.'.format(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 on_bind_target(self, target, ctx=None):
"""Fired after target is bound to self. :param target: newly bound target. :param ctx: target ctx. """ |
_on_bind_target = getattr(self, Annotation._ON_BIND_TARGET, None)
if _on_bind_target is not None:
_on_bind_target(self, target=target, ctx=ctx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_from(self, target, ctx=None):
"""Remove self annotation from target annotations. :param target: target from where remove self annotation. :param ctx: ... |
annotations_key = Annotation.__ANNOTATIONS_KEY__
try:
# get local annotations
local_annotations = get_local_property(
target, annotations_key, ctx=ctx
)
except TypeError:
raise TypeError('target {0} must be hashable'.format(targe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def free_memory(cls, exclude=None):
"""Free global annotation memory.""" |
annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__
exclude = () if exclude is None else exclude
for annotation_cls in list(annotations_in_memory.keys()):
if issubclass(annotation_cls, exclude):
continue
if issubclass(annotation_cls, cls):
... |
<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_memory_annotations(cls, exclude=None):
"""Get annotations in memory which inherits from cls. :param tuple/type exclude: annotation type(s) to exclude fro... |
result = set()
# get global dictionary
annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__
exclude = () if exclude is None else exclude
# iterate on annotation classes
for annotation_cls in annotations_in_memory:
# if annotation class is exclude... |
<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_local_annotations( cls, target, exclude=None, ctx=None, select=lambda *p: True ):
"""Get a list of local target annotations in the order of their definit... |
result = []
# initialize exclude
exclude = () if exclude is None else exclude
try:
# get local annotations
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__, result, ctx=ctx
)
if not local_an... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(cls, target, exclude=None, ctx=None, select=lambda *p: True):
"""Remove from target annotations which inherit from cls. :param target: target from whe... |
# initialize exclude
exclude = () if exclude is None else exclude
try:
# get local annotations
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__
)
except TypeError:
raise TypeError('target {0... |
<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_annotations( cls, target, exclude=None, ctx=None, select=lambda *p: True, mindepth=0, maxdepth=0, followannotated=True, public=True, _history=None ):
"""... |
result = []
if mindepth <= 0:
try:
annotations_by_ctx = get_property(
elt=target, key=Annotation.__ANNOTATIONS_KEY__, ctx=ctx
)
except TypeError:
annotations_by_ctx = {}
if not annotations_by_ct... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rand_chol(X, rho):
"""Transform C uncorrelated random variables into correlated data X : ndarray C univariate correlated random variables with N observations... |
import numpy as np
return np.dot(X, np.linalg.cholesky(rho).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 login_required(func, permission=None):
""" decorate with this function in order to require a valid token for any view If no token is present you will be sent... |
@wraps(func)
def decorated_function(*args, **kwargs):
if not check_token():
return login()
elif not nago.core.has_access(session.get('token')):
return http403()
return func(*args, **kwargs)
return decorated_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 list_nodes():
""" Return a list of all nodes """ |
token = session.get('token')
node = nago.core.get_node(token)
if not node.get('access') == 'master':
return jsonify(status='error', error="You need master access to view this page")
nodes = nago.core.get_nodes().values()
return render_template('nodes.html', **locals()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_detail(node_name):
""" View one specific node """ |
token = session.get('token')
node = nago.core.get_node(token)
if not node.get('access') == 'master':
return jsonify(status='error', error="You need master access to view this page")
node = nago.core.get_node(node_name)
return render_template('node_detail.html', node=node) |
<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_filenames(dirname):
"""Return all model output filenames inside a model output directory, sorted by iteration number. Parameters dirname: str A path to a... |
filenames = glob.glob('{}/*.pkl'.format(dirname))
return sorted(filenames, key=_f_to_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 get_output_every(dirname):
"""Get how many iterations between outputs have been done in a directory run. If there are multiple values used in a run, raise an... |
fnames = get_filenames(dirname)
i_s = np.array([_f_to_i(fname) for fname in fnames])
everys = list(set(np.diff(i_s)))
if len(everys) > 1:
raise TypeError('Multiple values for `output_every` '
'found, {}.'.format(everys))
return everys[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model_to_file(model, filename):
"""Dump a model to a file as a pickle file. Parameters model: Model Model instance. filename: str A path to the file in which... |
with open(filename, 'wb') as f:
pickle.dump(model, f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sparsify(dirname, output_every):
"""Remove files from an output directory at regular interval, so as to make it as if there had been more iterations between ... |
fnames = get_filenames(dirname)
output_every_old = get_output_every(dirname)
if output_every % output_every_old != 0:
raise ValueError('Directory with output_every={} cannot be coerced to'
'desired new value.'.format(output_every_old))
keep_every = output_every // outpu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, url, body):
"""Perform a POST request to the given resource with the given body. The "url" argument will be joined to the base URL this object was... |
to_hit = urlparse.urljoin(self.base_url, url)
resp = self.pool.post(to_hit, data=body, auth=self.auth)
return 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 get(self, url):
"""Perform a GET request to the given resource with the given URL. The "url" argument will be joined to the base URL this object was initiali... |
to_hit = urlparse.urljoin(self.base_url, url)
resp = self.pool.get(to_hit, auth=self.auth)
return 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 SWdensityFromCTD(SA, t, p, potential=False):
'''Calculate seawater density at CTD depth
Args
----
SA: ndarray
Absolute salinity, g/kg
t: ndarray
In-situ temperature (ITS-90), degrees C
p: ndarray
Sea pressure (absolute pressure minus 10.1325 dbar), dbar
Returns
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_editable(obj, request):
""" Returns ``True`` if the object is editable for the request. First check for a custom ``editable`` handler on the object, other... |
if hasattr(obj, "is_editable"):
return obj.is_editable(request)
else:
codename = get_permission_codename("change", obj._meta)
perm = "%s.%s" % (obj._meta.app_label, codename)
return (request.user.is_authenticated() and
has_site_permission(request.user) and
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_spam(request, form, url):
""" Main entry point for spam handling - called from the comment view and page processor for ``yacms.forms``, to check if posted... |
for spam_filter_path in settings.SPAM_FILTERS:
spam_filter = import_dotted_path(spam_filter_path)
if spam_filter(request, form, url):
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paginate(objects, page_num, per_page, max_paging_links):
""" Return a paginated page for the given objects, giving it a custom ``visible_page_range`` attribu... |
if not per_page:
return Paginator(objects, 0)
paginator = Paginator(objects, per_page)
try:
page_num = int(page_num)
except ValueError:
page_num = 1
try:
objects = paginator.page(page_num)
except (EmptyPage, InvalidPage):
objects = paginator.page(paginato... |
<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(request, templates, dictionary=None, context_instance=None, **kwargs):
""" Mimics ``django.shortcuts.render`` but uses a TemplateResponse for ``yacms.... |
warnings.warn(
"yacms.utils.views.render is deprecated and will be removed "
"in a future version. Please update your project to use Django's "
"TemplateResponse, which now provides equivalent functionality.",
DeprecationWarning
)
dictionary = dictionary or {}
if conte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_cookie(response, name, value, expiry_seconds=None, secure=False):
""" Set cookie wrapper that allows number of seconds to be given as the expiry time, an... |
if expiry_seconds is None:
expiry_seconds = 90 * 24 * 60 * 60 # Default to 90 days.
expires = datetime.strftime(datetime.utcnow() +
timedelta(seconds=expiry_seconds),
"%a, %d-%b-%Y %H:%M:%S GMT")
# Django doesn't seem to support unico... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getter(self, fget):
""" Change the getter for this descriptor to use to get the value :param fget: Function to call with an object as its only argument :type... |
if getattr(self, '__doc__', None) is None:
self.__doc__ = getattr(fget, _FUNC_DOC, None)
if self.name is None:
self.name = getattr(fget, _FUNC_NAME, None)
self._getter = fget
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 setter(self, can_set=None):
""" Like `CachedProp.deleter` is for `CachedProp.can_delete`, but for `can_set` :param can_set: boolean to change to it, and None... |
if can_set is None:
self._setter = not self._setter
else:
self._setter = bool(can_set)
# For use as decorator
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 deleter(self, can_delete=None):
""" Change if this descriptor's can be invalidated through `del obj.attr`. `cached_prop.deleter(True)` and:: @cached_prop.del... |
if can_delete is None:
self._deleter = not self._deleter
else:
self._deleter = bool(can_delete)
# For use as decorator
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 write(self):
""" Write the file, forcing the proper permissions """ |
with root():
self._write_log()
with open(self.path, 'w') as f:
# file owner
os.chown(self.path, self.uid(), self.gid())
# mode
if self.mode:
oldmask = os.umask(0)
os.chmod(self.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 _write_log(self):
""" Write log info """ |
logger.info("Writing config file %s" % self.path)
if settings.DEBUG:
try:
old_content = open(self.path, 'r').readlines()
except IOError:
old_content = ''
new_content = self.contents().splitlines(True)
diff = difflib.unifi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetAmi(ec2, ami_spec):
""" Get the boto ami object given a AmiSpecification object. """ |
images = ec2.get_all_images(owners=[ami_spec.owner_id] )
requested_image = None
for image in images:
if image.name == ami_spec.ami_name:
requested_image = image
break
return requested_image |
<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(self):
""" Build the Amazon Machine Image. """ |
template_instance = None
res = self.ec2.get_all_instances( \
filters={'tag-key': 'spec',
'tag-value' : self.ami_spec.ami_name,
'instance-state-name' : 'running'})
if res:
running_template_instances = res[0].instances
if running_template... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_env_gte(desired):
""" Boolean check if the current environment LOGLEVEL is at least as verbose as a desired LOGLEVEL :param desired: <str> one of 9 keys ... |
return LOGLEVELS.get(check_log_env()) >= LOGLEVELS.get(desired, LOGLEVELS[TEST]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.