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: returns an rdflib URIRef ''' parsed = self.parse_uri(str(value)) try: new_uri = "%s%s" % (self.ns_dict[parsed[0]], parsed[1]) if not strip_iri: return self.iri(new_uri) return new_uri except KeyError: return self.rpyhttp(value)
<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: return ((None, parts[0]), 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 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 the value is not a pyuri return the value return value
<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:] != ">": uri_string = "{}>".format(uri_string.strip()) return uri_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 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[parsed[0]], parsed[1]) except KeyError: rtn_val = self.iri(self.rpyhttp(value)) return rtn_val
<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]], parsed[1]) except KeyError: rtn_val = self.pyhttp(value) return rtn_val
<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) # Look for one frame less since the above line starts us off. for x in range(stacklevel-1): frame = _next_external_frame(frame) if frame is None: raise ValueError return frame
<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 warn function except it takes the following argument: `emitstacklevel` : default to 1, number of stackframe to consider when matching the module that emits this warning. """
# 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, type) and issubclass(category, Warning)): raise TypeError("category must be a Warning subclass, " "not '{:s}'".format(type(category).__name__)) # Get context information try: frame = _get_stack_frame(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 else: globals = frame.f_globals lineno = frame.f_lineno try: eframe = _get_stack_frame(emitstacklevel) except ValueError: eglobals = sys.__dict__ else: eglobals = eframe.f_globals if '__name__' in eglobals: emodule = eglobals['__name__'] else: emodule = "<string>" #################### ### Get Filename ### #################### if '__name__' in globals: module = globals['__name__'] else: module = "<string>" #################### ### Get Filename ### #################### filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith(".pyc"): filename = filename[:-1] else: if module == "__main__": try: filename = sys.argv[0] except AttributeError: # embedded interpreters don't have sys.argv, see bug #839151 filename = '__main__' if not filename: filename = module registry = globals.setdefault("__warningregistry__", {}) warn_explicit(message, category, filename, lineno, module, registry, globals, emit_module=emodule)
<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") run("git push origin --tags") run("python setup.py sdist bdist_wheel") run("twine upload --skip-existing dist/*") else: print("- Have you updated the version?") print("- Have you updated CHANGELOG.md, README.md, and AUTHORS.md?") print("- Have you fixed any last minute bugs?") print("- Have you merged changes for release into the master branch?") print("If you answered yes to all of the above questions,") print("then run `inv release --deploy -vX.YY.ZZ` to:") print("- Checkout master") print("- Tag the git release with provided vX.YY.ZZ version") print("- Push the master branch and tags to repo")
<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: max_length = row_len if row_len < min_length: min_length = row_len if max_length != min_length: for row in table: row_len = len(row) if row_len < max_length: row.extend([None]*(max_length-row_len))
<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``. Note this is used as a workaround, since `psutil` isn't consistent on being able to provide this path in all cases, especially MacOS X. """
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.hexdigest() except IOError: 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_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 try: path = common.which(proc.name) # psutil doesn't support MacOS X relative paths, # let's use a workaround to merge working directory with # process relative path if not path and common.IS_MACOSX: cwd = _get_process_cwd(proc.pid) if not cwd: continue path = os.path.join(cwd, proc.cmdline[0]) yield (proc, path) except (psutil.AccessDenied, OSError): pass except psutil.NoSuchProcess: pass
<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 duplicates of those specified to terminate. `paths` List of full paths to executables for processes to terminate. """
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_checksums[path] if not paths: return target_checksums = dict((cache_checksum(p), 1) for p in paths) if not target_checksums: return for proc, path in _get_user_processes(): # path's checksum matches targets, attempt to terminate if cache_checksum(path) in target_checksums: try: proc.terminate() except (psutil.AccessDenied, psutil.NoSuchProcess): pass
<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 with samples, observations that are assumed to follow a Normal distribution. algorithm : str Optional. Default 'Nelder-Mead' (Simplex). The algorithm used in scipy.optimize.minimize debug : bool Optional. Returns: -------- mu : float Mean, 1st moment, location parameter of the Normal distribution. sd : float Standard Deviation, 2nd moment, scale parameter of the Normal distribution results : scipy.optimize.optimize.OptimizeResult Optional. If debug=True then only scipy's optimization result variable is returned. """
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('Optimization Algorithm not supported.') # set start values theta0 = [1.0, 1.0] # mu and sigma # run solver results = sopt.minimize( objective_nll_norm_uni, theta0, args=(data), method=algorithm, options={'disp': False}) # debug? if debug: return results # done return results.x[0], results.x[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 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)) if len(value) > 0 and \ cbool(value[0].get('loaded',{}).get("value",False)): return True else: return False
<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 interactions with this object. `required`: boolean indicating if the node existence should be required at read time. Normally write will create the node if the path is possible. This allows for simplified catching of errors. """
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: if required: raise StateNotFound(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(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, and resetting any write buffers. """
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 local state to the Zookeeper node state.""" del changes[:] current = yaml.load(content) if content else {} missing = object() for key in set(pristine_cache).union(cache): old_value = pristine_cache.get(key, missing) new_value = cache.get(key, missing) if old_value != new_value: if new_value != missing: current[key] = new_value if old_value != missing: changes.append( ModifiedItem(key, old_value, new_value)) else: changes.append(AddedItem(key, new_value)) elif key in current: del current[key] changes.append(DeletedItem(key, old_value)) return yaml.safe_dump(current) # Apply the change till it takes. yield retry_change(self._client, self._path, apply_changes) returnValue(changes)
<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[key or self.masterkey]) elif type(data_info) is dict: [_info_dataframe(df) for df in data_info.values()] else: _info_dataframe(data_info)
<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_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 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.timestamps: return True return False
<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 instance. """
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 the attrs given will be included. :exclude_keys: if not None, all attrs except those listed will be included, with respect to use_default_excludes. :use_default_excludes: if True, then the class-level exclude_keys_serialize will be combined with exclude_keys if given, or used in place of exlcude_keys if not given. """
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) or (ekeys is not None and k in ekeys), transform=self._other_to_dict)
<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 pretty is True then newlines, indentation and key sorting are used. """
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 property names that were changed. """
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_[attr_name]) else: if self.strict_attrs: raise Exception("Unknown attribute for {}: {}".format(self.__class__.__name__, attr_name)) return changes
<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')} if args.char: char = self._getChar(args.char) if args.font: self.fontChar(args.font, char) else: self.char(char) else: block = self._getBlock(args.block) self.chars(args.font, block)
<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).getOverlappedList(ranges_column) else: blocks = [block] overlapped = [Ranges(code_points).getOverlapped(block[3])] if self._display['group']: char_count = block_count = 0 for i, block in enumerate(blocks): o_count = len(overlapped[i]) if o_count: block_count += 1 char_count += o_count total = sum(len(r) for r in block[3]) percent = 0 if total == 0 else o_count / total print("{0:>6} {1:47} {2:>4.0%} ({3}/{4})".format(block[0], block[2], percent, o_count, total)) if self._display['list']: for point in overlapped[i]: self._charInfo(point, padding=9) self._charSummary(char_count, block_count) else: for point in code_points: self._charInfo(point, padding=7) self._charSummary(len(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']: for font_file in font_families[font_family]: print(' '+font_file) self._fontSummary(len(font_files), len(font_families)) else: font_files = self._getCharFont(font_files, char) for font_file in sorted(font_files): print(font_file) self._fontSummary(len(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 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 '', block_count, 's' if block_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, 's' if font_file_count != 1 else '', font_family_count, 'ies' if font_family_count != 1 else 'y' ))
<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: return char_spec else: raise ValueError('No such character')
<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 raise ValueError('No such block')
<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 sorted(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 _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 value field.get_from_instance = MethodType(get_from_instance, field) return field
<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 (TypeError, AttributeError, KeyError, ValueError, IndexError): try: # attr lookup instance = getattr(instance, attr) except (TypeError, AttributeError): try: # list-index lookup instance = instance[int(attr)] except (IndexError, # list index out of range ValueError, # invalid literal for int() KeyError, # current is a dict without `int(bit)` key TypeError): # unsubscriptable object raise VariableLookupError("Failed lookup for key [%s] in %r" % (attr, instance)) if callable(instance): instance = instance() elif instance is None: # no sense walking down the path any further return None return instance
<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 containing (query_string, kwargs) conn: the triplestore connection to use """
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 returns triples 3 edges out in either direction from the provided item_uri args: items: the starting uri or list of uris to the query conn: the rdfframework triplestore connection to query against output: 'json' or 'rdf' kwargs: template: template to use in place of the generic template rdfclass: rdfclass the items are based on. filters: list of filters to apply """
# 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): template_kwargs['uri_list'] = items else: template_kwargs['item_uri'] = Uri(items).sparql if kwargs.get("special_union"): template_kwargs['special_union'] = kwargs.get("special_union") if kwargs.get('rdfclass'): # pdb.set_trace() template_kwargs.update(kwargs['rdfclass'].query_kwargs) if kwargs.get("filters"): template_kwargs['filters'] = make_sparql_filter(kwargs.get('filters')) sparql = render_without_request(template, **template_kwargs) 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 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 triplestore connection """
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 = [{'variable': 'p', 'operator': '=', 'union_type': '||', 'values': ['rdf:type', 'rdfs:label']}] """
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 """ formated_vals = UniqueList() for val in values: try: formated_vals.append(val.sparql) except AttributeError: formated_vals.append(val) pre_str = "?%s%s" % (variable.replace("?", ""), operator) union = "%s\n\t\t" % union_type return "\tFilter( %s) .\n" % union.join([pre_str + val for val in formated_vals]) if not filters: return "" rtn_str = "" for param in filters: rtn_str += make_filter_str(**param) return rtn_str
<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 elif (node.nodeType == node.PROCESSING_INSTRUCTION_NODE or node.nodeType == node.COMMENT_NODE or node.nodeType == node.TEXT_NODE): return node.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 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, identical to, or after b in the document respectively. We represent document order as a list of sibling indexes. That is, the third child of the document node has an order of [2]. The first child of that node has an order of [2,0]. Attributes have a sibling index of -1 (coming before all children of their node) and are further ordered by name--e.g., [2,0,-1,'href']. """
# 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 which child this is of its parent. sibpos = 0 sib = node while sib.previousSibling is not None: sibpos += 1 sib = sib.previousSibling # Order: parent-order + [sibling-position] order = document_order(node.parentNode) order.append(sibpos) return order
<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) == v and v <= 0xffffffff: v = int(v) return unicode(v) elif booleanp(v): return u'true' if v else u'false' 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 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 a sequence over the nodes along an XPath axis. Axis functions have two extra attributes indicating the axis direction and principal node type. """
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 node.parentNode @axisfn(reverse=True) def ancestor(node): while node.parentNode is not None: node = node.parentNode yield node @axisfn() def following_sibling(node): while node.nextSibling is not None: node = node.nextSibling yield node @axisfn(reverse=True) def preceding_sibling(node): while node.previousSibling is not None: node = node.previousSibling yield node @axisfn() def following(node): while node is not None: while node.nextSibling is not None: node = node.nextSibling for n in descendant_or_self(node): yield n node = node.parentNode @axisfn(reverse=True) def preceding(node): while node is not None: while node.previousSibling is not None: node = node.previousSibling # Could be more efficient here. for n in reversed(list(descendant_or_self(node))): yield n node = node.parentNode @axisfn(principal_node_type=xml.dom.Node.ATTRIBUTE_NODE) def attribute(node): if node.attributes is not None: return (node.attributes.item(i) for i in xrange(node.attributes.length)) return () @axisfn() def namespace(node): raise XPathNotImplementedError("namespace axis is not implemented") @axisfn() def self(node): yield node @axisfn() def descendant_or_self(node): yield node for child in node.childNodes: for node in descendant_or_self(child): yield node @axisfn(reverse=True) def ancestor_or_self(node): return chain([node], ancestor(node)) # Place each axis function defined here into the 'axes' dict. for axis in locals().values(): axes[axis.__name__] = axis
<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 be in document order to begin with. """
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 # will need to sort. (We could also check to see if the last node in # the source set comes before the first node in the target set, but this # situation is very unlikely in practice.) if document_order(target[-1]) < document_order(source[0]): target.extend(source) else: target.extend(source) target.sort(key=document_order)
<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 'body' in working_response else None if DriverTools.MSG_CORRELATION_ID in working_properties: if self.corr_id == working_properties[DriverTools.MSG_CORRELATION_ID]: if DriverTools.MSG_SPLIT_COUNT in working_properties and \ int(working_properties[DriverTools.MSG_SPLIT_COUNT]) > 1: working_body_decoded = base64.b64decode(working_body) if working_body is not None else None if self.split_responses is None: self.split_responses = [] self.split_responses_mid = working_properties[DriverTools.MSG_SPLIT_MID] if working_properties[DriverTools.MSG_SPLIT_MID] == self.split_responses_mid: response = { 'properties': working_properties, 'body': working_body_decoded } self.split_responses.insert(int(working_properties[DriverTools.MSG_SPLIT_OID]), response) if self.split_responses.__len__() == int(working_properties[DriverTools.MSG_SPLIT_COUNT]): properties = {} body = b'' for num in range(0, self.split_responses.__len__()): properties.update(self.split_responses[num]['properties']) body += self.split_responses[num]['body'] self.response = { 'properties': properties, 'body': body } self.split_responses = None self.split_responses_mid = None else: LOGGER.warn("natsd.Requester.on_response - discarded response : (" + str(working_properties[DriverTools.MSG_CORRELATION_ID]) + "," + str(working_properties[DriverTools.MSG_SPLIT_MID]) + ")") LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({ 'properties': working_properties, 'body': working_body_decoded })) else: working_body_decoded = base64.b64decode(working_body) if working_body is not None else \ bytes(json.dumps({}), 'utf8') self.response = { 'properties': working_properties, 'body': working_body_decoded } else: working_body_decoded = base64.b64decode(working_body) if working_body is not None else None LOGGER.warn("natsd.Requester.on_response - discarded response : " + str(working_properties[DriverTools.MSG_CORRELATION_ID])) LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({ 'properties': working_properties, 'body': working_body_decoded })) else: working_body_decoded = base64.b64decode(working_body) if working_body is not None else None LOGGER.warn("natsd.Requester.on_response - discarded response (no correlation ID)") LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({ 'properties': working_properties, 'body': working_body_decoded }))
<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 timer = None else: # else, renew a timer # get timestamp timestamp = time() + value # start a new timer timer = Timer(value, self.__del__) timer.start() # set/update attributes setattr(self, Annotation.__TIMER, timer) setattr(self, Annotation.__TS, timestamp)
<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[self_class] while self in annotations_memory: annotations_memory.remove(self) if not annotations_memory: del memory[self_class]
<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. :return: bound target. """
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(target)) # if local_annotations do not exist, put them in target if not local_annotations: put_properties( target, properties={Annotation.__ANNOTATIONS_KEY__: local_annotations}, ctx=ctx ) # insert self at first position local_annotations.insert(0, self) # add target to self targets if target not in self.targets: self.targets.append(target) 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 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: target 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(target)) # if local annotations exist if local_annotations is not None: # if target in self.targets if target in self.targets: # remove target from self.targets self.targets.remove(target) # and remove all self annotations from local_annotations while self in local_annotations: local_annotations.remove(self) # if target is not annotated anymore, remove the empty list if not local_annotations: del_properties(target, annotations_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 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): del annotations_in_memory[annotation_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 from search. :return: found annotations which inherits from cls. :rtype: set """
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 excluded, continue if issubclass(annotation_cls, exclude): continue # if annotation class inherits from self, add it in the result if issubclass(annotation_cls, cls): result |= annotations_in_memory[annotation_cls] 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 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 definition. :param type cls: type of annotation to get from target. :param target: target from where get annotations. :param tuple/type exclude: annotation types to exclude from selection. :param ctx: target ctx. :param select: selection function which takes in parameters a target, a ctx and an annotation and returns True if the annotation has to be selected. True by default. :return: target local annotations. :rtype: list """
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_annotations: if ismethod(target): func = get_method_function(target) local_annotations = get_local_property( func, Annotation.__ANNOTATIONS_KEY__, result, ctx=ctx ) if not local_annotations: local_annotations = get_local_property( func, Annotation.__ANNOTATIONS_KEY__, result ) elif isfunction(target): local_annotations = get_local_property( target, Annotation.__ANNOTATIONS_KEY__, result ) except TypeError: raise TypeError('target {0} must be hashable'.format(target)) for local_annotation in local_annotations: # check if local annotation inherits from cls inherited = isinstance(local_annotation, cls) # and if not excluded not_excluded = not isinstance(local_annotation, exclude) # and if selected selected = select(target, ctx, local_annotation) # if three conditions, add local annotation to the result if inherited and not_excluded and selected: result.append(local_annotation) 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 remove(cls, target, exclude=None, ctx=None, select=lambda *p: True): """Remove from target annotations which inherit from cls. :param target: target from where remove annotations which inherits from cls. :param tuple/type exclude: annotation types to exclude from selection. :param ctx: target ctx. :param select: annotation selection function which takes in parameters a target, a ctx and an annotation and return True if the annotation has to be removed. """
# 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} must be hashable'.format(target)) # if there are local annotations if local_annotations is not None: # get annotations to remove which inherits from cls annotations_to_remove = [ annotation for annotation in local_annotations if ( isinstance(annotation, cls) and not isinstance(annotation, exclude) and select(target, ctx, annotation) ) ] # and remove annotations from target for annotation_to_remove in annotations_to_remove: annotation_to_remove.remove_from(target)
<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 ): """Returns all input target annotations of cls type sorted by definition order. :param type cls: type of annotation to get from target. :param target: target from where get annotations. :param tuple/type exclude: annotation types to remove from selection. :param ctx: target ctx. :param select: bool function which select annotations after applying previous type filters. Takes a target, a ctx and an annotation in parameters. True by default. :param int mindepth: minimal depth for searching annotations (default 0) :param int maxdepth: maximal depth for searching annotations (default 0) :param bool followannotated: if True (default) follow deeply only annotated members. :param bool public: if True (default) follow public members. :param list _history: private parameter which save parsed elements. :rtype: Annotation """
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_ctx: if ismethod(target): func = get_method_function(target) annotations_by_ctx = get_property( elt=func, key=Annotation.__ANNOTATIONS_KEY__, ctx=ctx ) if not annotations_by_ctx: annotations_by_ctx = get_property( elt=func, key=Annotation.__ANNOTATIONS_KEY__ ) elif isfunction(target): annotations_by_ctx = get_property( elt=target, key=Annotation.__ANNOTATIONS_KEY__ ) exclude = () if exclude is None else exclude for elt, annotations in annotations_by_ctx: for annotation in annotations: # check if annotation is a StopPropagation rule if isinstance(annotation, StopPropagation): exclude += annotation.annotation_types # ensure propagation if elt is not target and not annotation.propagate: continue # ensure overriding if annotation.override: exclude += (annotation.__class__, ) # check for annotation if (isinstance(annotation, cls) and not isinstance(annotation, exclude) and select(target, ctx, annotation)): result.append(annotation) if mindepth >= 0 or (maxdepth > 0 and (result or not followannotated)): if _history is None: _history = [target] else: _history.append(target) for name, member in getmembers(target): if (name[0] != '_' or not public) and member not in _history: if ismethod(target) and name.startswith('im_'): continue result += cls.get_annotations( target=member, exclude=exclude, ctx=ctx, select=select, mindepth=mindepth - 1, maxdepth=maxdepth - 1, followannotated=followannotated, _history=_history ) 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 rand_chol(X, rho): """Transform C uncorrelated random variables into correlated data X : ndarray C univariate correlated random variables with N observations as <N x C> matrix rho : ndarray Correlation Matrix (Pearson method) with coefficients between [-1, +1] """
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 to a login page """
@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 directory. Returns ------- filenames: list[str] Paths to all output files inside `dirname`, sorted in order of increasing iteration number. """
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 exception. Parameters dirname: str A path to a directory. Returns ------- output_every: int The inferred number of iterations between outputs. Raises ------ TypeError If there are multiple different values for `output_every` found. This usually means a run has been resumed with a different value. """
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 to store the pickle output. """
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 outputs. Can be used to reduce the storage size of a directory. If the new number of iterations between outputs is not an integer multiple of the old number, then raise an exception. Parameters dirname: str A path to a directory. output_every: int Desired new number of iterations between outputs. Raises ------ ValueError The directory cannot be coerced into representing `output_every`. """
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 // output_every_old fnames_to_keep = fnames[::keep_every] fnames_to_delete = set(fnames) - set(fnames_to_keep) for fname in fnames_to_delete: os.remove(fname)
<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 initialized with. :param string url: the URL resource to hit :param string body: the POST body for the request :rtype: requests.Response object"""
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 initialized with. :param string url: the URL resource to hit :rtype: requests.Response object"""
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 ------- rho: ndarray Seawater density, in-situ or potential, kg/m^3 ''' import numpy import gsw CT = gsw.CT_from_t(SA, t, p) # Calculate potential density (0 bar) instead of in-situ if potential: p = numpy.zeros(len(SA)) return gsw.rho(SA, CT, p)
<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, otherwise use the logged in user and check change permissions for the object's model. """
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 request.user.has_perm(perm))
<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 content is spam. Spam filters are configured via the ``SPAM_FILTERS`` setting. """
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`` attribute calculated from ``max_paging_links``. """
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(paginator.num_pages) page_range = objects.paginator.page_range if len(page_range) > max_paging_links: start = min(objects.paginator.num_pages - max_paging_links, max(0, objects.number - (max_paging_links // 2) - 1)) page_range = list(page_range)[start:start + max_paging_links] objects.visible_page_range = page_range return objects
<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.core.middleware.TemplateForDeviceMiddleware`` """
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 context_instance: context_instance.update(dictionary) else: context_instance = RequestContext(request, dictionary) return TemplateResponse(request, templates, context_instance, **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 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, and ensures values are correctly encoded. """
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 unicode cookie keys correctly on # Python 2. Work around by encoding it. See # https://code.djangoproject.com/ticket/19802 try: response.set_cookie(name, value, expires=expires, secure=secure) except (KeyError, TypeError): response.set_cookie(name.encode('utf-8'), value, expires=expires, secure=secure)
<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 fget: Callable[[Any], Any] :return: self, so this can be used as a decorator like a `property` :rtype: CachedProperty """
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 to toggle :type can_set: Optional[bool] :return: self, so this can be used as a decorator like a `property` :rtype: CachedProperty """
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.deleter def cached_prop(self): pass are equivalent to `cached_prop.can_delete = True`. :param can_delete: boolean to change to it, and None to toggle :type can_delete: Optional[bool] :return: self, so this can be used as a decorator like a `property` :rtype: CachedProperty """
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, self.mode) os.umask(oldmask) f.write(self.contents())
<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.unified_diff(old_content, new_content, fromfile=self.path, tofile=self.path) if diff: logger.debug('Diff:\n' + ''.join(diff)) else: logger.debug('File not changed')
<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_instances: assert(len(running_template_instances) == 1) template_instance = running_template_instances[0] # if there is not a currently running template instance, start one if not template_instance: template_instance = self.__CreateTemplateInstance() template_instance.add_tag('spec', self.ami_spec.ami_name) assert(template_instance) if self.ami_spec.role == 'workstation': self.__ConfigureAsWorkstation(template_instance) elif self.ami_spec.role == 'master': self.__ConfigureAsClusterMaster(template_instance) elif self.ami_spec.role == 'worker': self.__ConfigureAsClusterWorker(template_instance) else: raise RuntimeError('unknown role: %s' % (self.ami_spec.role)) print 'Please login and perform any custom manipulations before '\ 'snapshot is made!' raw_input('Press any key to shutdown and begin creating AMI. '\ '(or ctrl-c to quit and re-run config process).') self.__SecurityScrub(template_instance) ami_id = None if self.ami_spec.root_store_type == 'ebs': ami_id = self.__CreateEbsAmi(template_instance) else: logging.info('Support for creating instance-store backed images has been' ' disabled in this version because it required much greater' ' complexity.') ami_id = self.__CreateEbsAmi(template_instance) logging.info('ami id: %s' % (ami_id)) # TODO(heathkh): implement these features... #self.__SetImagePermissions(ami_id) #self.__DistributeImageToAllRegions(ami_id) print 'terminating template instance' self.ec2.terminate_instances(instance_ids=[template_instance.id]) core.WaitForInstanceTerminated(template_instance) 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 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 in <brain.environment.stage> :return: <bool> """
return LOGLEVELS.get(check_log_env()) >= LOGLEVELS.get(desired, LOGLEVELS[TEST])