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 childDataReceived(self, childFD, data): """Relay data received on any file descriptor to the process """
protocol = getattr(self, 'protocol', None) if protocol: protocol.dataReceived(data) else: self.data.append((childFD, 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 publish(self, user, provider, obj, comment, **kwargs): ''' user - django User or UserSocialAuth instance provider - name of publisher provider obj - sharing object comment - string ''' social_user = self._get_social_user(user, provider) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check(self, user, provider, permission, **kwargs): ''' user - django User or UserSocialAuth instance provider - name of publisher provider permission - if backend maintains check permissions vk - binary mask in int format ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recognize_byte(self, image, timeout=10): """Process a byte image buffer."""
result = [] alpr = subprocess.Popen( self._cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) # send image try: # pylint: disable=unused-variable stdout, stderr = alpr.communic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finished(finished_status, update_interval, table, status_column, edit_at_column): """ Create text sql statement query for sqlalchemy that getting all finishe...
sql = select([table]).where( and_(*[ status_column >= finished_status, edit_at_column >= x_seconds_before_now(update_interval) ]) ) return sql
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unfinished(finished_status, update_interval, table, status_column, edit_at_column): """ Create text sql statement query for sqlalchemy that getting all unfin...
sql = select([table]).where( or_(*[ status_column < finished_status, edit_at_column < x_seconds_before_now(update_interval) ]) ) return sql
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_nearest(x, x0) -> Tuple[int, Any]: """ This find_nearest function does NOT assume sorted input inputs: x: array (float, int, datetime, h5py.Dataset) with...
x = np.asanyarray(x) # for indexing upon return x0 = np.atleast_1d(x0) # %% if x.size == 0 or x0.size == 0: raise ValueError('empty input(s)') if x0.ndim not in (0, 1): raise ValueError('2-D x0 not handled yet') # %% ind = np.empty_like(x0, dtype=int) # NOTE: not trapping Ind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_context_attribute_exists(context, name, default_value=None): """ Ensure a behave resource exists as attribute in the behave context. If this is not th...
if not hasattr(context, name): setattr(context, name, default_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 ensure_workdir_exists(context): """ Ensures that the work directory exists. In addition, the location of the workdir is stored as attribute in the context ob...
ensure_context_attribute_exists(context, "workdir", None) if not context.workdir: context.workdir = os.path.abspath(WORKDIR) pathutil.ensure_directory_exists(context.workdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_by_idx(tree, idxs): """ Delete a key entry based on numerical indexes into subtree lists. """
if len(idxs) == 0: tree['item'] = None tree['subtrees'] = [] else: hidx, tidxs = idxs[0], idxs[1:] del_by_idx(tree['subtrees'][hidx][1], tidxs) if len(tree['subtrees'][hidx][1]['subtrees']) == 0: del tree['subtrees'][hidx]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_in_tree(tree, key, perfect=False): """ Helper to perform find in dictionary tree. """
if len(key) == 0: if tree['item'] is not None: return tree['item'], () else: for i in range(len(tree['subtrees'])): if not perfect and tree['subtrees'][i][0] == '*': item, trace = find_in_tree(tree['subtrees'][i][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 find(self, key, perfect=False): """ Find a key path in the tree, matching wildcards. Return value for key, along with index path through subtree lists to the...
return find_in_tree(self.root, key, perfect)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _purge_unreachable(self, key): """ Purge unreachable dominated key paths before inserting a new key path. """
dels = [] for p in self: if dominates(key, p): dels.append(p) for k in dels: _, idxs = find_in_tree(self.root, k, perfect=True) del_by_idx(self.root, idxs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, name, namespace): """Register a new namespace with the Configuration object. Args: name (str): The name of the section/namespace. namespace (...
if name in self._NAMESPACES: raise ValueError("Namespace {0} already exists.".format(name)) if not isinstance(namespace, ns.Namespace): raise TypeError("Namespaces must be of type Namespace.") self._NAMESPACES[name] = namespace
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def napi_compare(left, ops, comparators, **kwargs): """Make pairwise comparisons of comparators."""
values = [] for op, right in zip(ops, comparators): value = COMPARE[op](left, right) values.append(value) left = right result = napi_and(values, **kwargs) if isinstance(result, ndarray): return result else: return bool(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 calc_transition_to_state(self, newstate): """Given a target state, generate the sequence of transitions that would move this state machine instance to that t...
cached_val = JTAGStateMachine._lookup_cache.\ get((self.state, newstate)) if cached_val: return cached_val if newstate not in self.states: raise ValueError("%s is not a valid state for this state " "machine"%newstate) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(): """ Initializes the hook queues for the sys module. This method will automatically be called on the first registration for a hook to the system by e...
global _displayhooks, _excepthooks if _displayhooks is not None: return _displayhooks = [] _excepthooks = [] # store any current hooks if sys.displayhook != sys.__displayhook__: _displayhooks.append(weakref.ref(sys.displayhook)) if sys.excepthook != sys.__excepthook__: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_iso8601(text): """ Maybe parse an ISO8601 datetime string into a datetime. :param text: Either a ``unicode`` string to parse or any other object (idea...
if isinstance(text, unicode): try: return parse_iso8601(text) except ValueError: raise CheckedValueTypeError( None, (datetime,), unicode, text, ) # Let pyrsistent reject it down the line. return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_path(cls, spec_path): """ Load a specification from a path. :param FilePath spec_path: The location of the specification to read. """
with spec_path.open() as spec_file: return cls.from_document(load(spec_file))
<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_document(self): """ Serialize this specification to a JSON-compatible object representing a Swagger specification. """
return dict( info=thaw(self.info), paths=thaw(self.paths), definitions=thaw(self.definitions), securityDefinitions=thaw(self.securityDefinitions), security=thaw(self.security), swagger=thaw(self.swagger), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pclass_for_definition(self, name): """ Get a ``pyrsistent.PClass`` subclass representing the Swagger definition in this specification which corresponds to th...
while True: try: cls = self._pclasses[name] except KeyError: try: original_definition = self.definitions[name] except KeyError: raise NoSuchDefinition(name) if "$ref" in original_def...
<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_for_CLASS(self, name, definition): """ Model a Swagger definition that is like a Python class. :param unicode name: The name of the definition from th...
return _ClassModel.from_swagger( self.pclass_for_definition, name, definition, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_swagger(cls, pclass_for_definition, name, definition): """ Create a new ``_ClassModel`` from a single Swagger definition. :param pclass_for_definition: ...
return cls( name=name, doc=definition.get(u"description", name), attributes=cls._attributes_for_definition( pclass_for_definition, definition, ), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pclass(self, bases): """ Create a ``pyrsistent.PClass`` subclass representing this class. :param tuple bases: Additional base classes to give the resulting c...
def discard_constant_fields(cls, **kwargs): def ctor(): return super(huh, cls).__new__(cls, **kwargs) try: return ctor() except AttributeError: if u"kind" in kwargs or u"apiVersion" in kwargs: kwargs.pop("ki...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dumps_bytes(obj): """ Serialize ``obj`` to JSON formatted ``bytes``. """
b = dumps(obj) if isinstance(b, unicode): b = b.encode("ascii") return b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def native_string_to_bytes(s, encoding="ascii", errors="strict"): """ Ensure that the native string ``s`` is converted to ``bytes``. """
if not isinstance(s, str): raise TypeError("{} must be type str, not {}".format(s, type(s))) if str is bytes: # Python 2 return s else: # Python 3 return s.encode(encoding=encoding, errors=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 native_string_to_unicode(s, encoding="ascii", errors="strict"): """ Ensure that the native string ``s`` is converted to ``unicode``. """
if not isinstance(s, str): raise TypeError("{} must be type str, not {}".format(s, type(s))) if str is unicode: # Python 3 return s else: # Python 2 return s.decode(encoding=encoding, errors=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 datetime_handler(x): """ Allow serializing datetime objects to JSON """
if isinstance(x, datetime.datetime) or isinstance(x, datetime.date): return x.isoformat() raise TypeError("Unknown type")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parsed(self): """Get the code object which represents the compiled Python file. This property is cached and only parses the content once. """
if not self._parsed: self._parsed = compile(self.content, self.path, 'exec') return self._parsed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _chunk(iterable, size): """Split an iterable into chunks of a fixed size."""
# We're going to use some star magic to chunk the iterable. We create a # copy of the iterator size times, then pull a value from each to form a # chunk. The last chunk may have some trailing Nones if the length of the # iterable isn't a multiple of size, so we filter them out. args = (iter(iterab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _matrix_add_column(matrix, column, default=0): """Given a matrix as a list of lists, add a column to the right, filling in with a default value if necessary....
height_difference = len(column) - len(matrix) # The width of the matrix is the length of its longest row. width = max(len(row) for row in matrix) if matrix else 0 # For now our offset is 0. We may need to shift our column down later. offset = 0 # If we need extra rows, add them to the top of...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vertical_graph(*args, sep='\n'): r"""Consume an iterable of integers and produce a vertical bar graph using braille characters. The graph is vertical in that...
lines = [] # If the arguments were passed as a single iterable, pull it out. # Otherwise, just use them as-is. if len(args) == 1: bars = args[0] else: bars = args # Make sure we use the default when needed if sep is None: sep = '\n' # Break the bars into group...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def horizontal_graph(*args): r"""Consume an iterable of integers and produce a horizontal bar graph using braille characters. The graph is horizontal in that its...
lines = [] # If the arguments were passed as a single iterable, pull it out. # Otherwise, just use them as-is. if len(args) == 1: bars = args[0] else: bars = args # Break the bars into groups of two, one for each column in the braille # blocks. for bar_group in _chunk...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_example(config, ext='json'): """Generate an example file based on the given Configuration object. Args: config (confpy.core.configuration.Configurat...
template_name = 'example.{0}'.format(ext.lower()) template = ENV.get_template(template_name) return template.render(config=config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _removeHeaderTag(header, tag): """Removes a tag from the beginning of a header string. :param header: str :param tag: str :returns: (str, bool), header witho...
if header.startswith(tag): tagPresent = True header = header[len(tag):] else: tagPresent = False return header, tagPresent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _idFromHeaderInfo(headerInfo, isDecoy, decoyTag): """Generates a protein id from headerInfo. If "isDecoy" is True, the "decoyTag" is added to beginning of th...
proteinId = headerInfo['id'] if isDecoy: proteinId = ''.join((decoyTag, proteinId)) return proteinId
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _nameFromHeaderInfo(headerInfo, isDecoy, decoyTag): """Generates a protein name from headerInfo. If "isDecoy" is True, the "decoyTag" is added to beginning o...
if 'name' in headerInfo: proteinName = headerInfo['name'] else: proteinName = headerInfo['id'] if isDecoy: proteinName = ''.join((decoyTag, proteinName)) return proteinName
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _addPeptide(self, sequence, proteinId, digestInfo): """Add a peptide to the protein database. :param sequence: str, amino acid sequence :param proteinId: str...
stdSequence = self.getStdSequence(sequence) if stdSequence not in self.peptides: self.peptides[stdSequence] = PeptideEntry( stdSequence, mc=digestInfo['missedCleavage'] ) if sequence not in self.peptides: self.peptides[sequence] = self.peptid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(self, options, conf): """ Configure plugin. """
super(LeakDetectorPlugin, self).configure(options, conf) if options.leak_detector_level: self.reporting_level = int(options.leak_detector_level) self.report_delta = options.leak_detector_report_delta self.patch_mock = options.leak_detector_patch_mock self.ignore_patt...
<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(self, instance, auto=False): """ Bind deps to instance :param instance: :param auto: follow update of DI and refresh binds once we will get something ne...
methods = [ (m, cls.__dict__[m]) for cls in inspect.getmro(type(instance)) for m in cls.__dict__ if inspect.isfunction(cls.__dict__[m]) ] try: deps_of_endpoints = [(method_ptr, self.entrypoint_deps(method_ptr)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_dict(self): """ create a dict based on class attributes """
odict = OrderedDict() for name in self._order: attr_value = getattr(self, name) if isinstance(attr_value, List): _list = [] for item in attr_value: _list.append((item.as_dict() if isinstance(item, Entity) else 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 map(cls, dict_entity): """ staticmethod which will be used in recursive mode in order to map dict to instance """
for key, value in dict_entity.items(): if hasattr(cls, key): if isinstance(value, list): _list = getattr(cls, key) if isinstance(_list.expected_type, list): for _dict in value: _list.append(c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generateParams(rawfilepath, outputpath, isolationWindow, coElute): """Generates a string containing the parameters for a pParse parameter file but doesn't wr...
output = str() #Basic options output = '\n'.join([output, ' = '.join(['datapath', rawfilepath])]) output = '\n'.join([output, ' = '.join(['logfilepath', outputpath])]) output = '\n'.join([output, ' = '.join(['outputpath', outputpath])]) #Advanced options output = '\n'.join([output, ' = '.jo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeParams(rawfilepath, outputpath, isolationWindow, coElute=0): """Generate and write a pParse parameter file. :param rawfilepath: location of the thermo "...
paramText = generateParams(rawfilepath, outputpath, isolationWindow, coElute) filename, fileext = os.path.splitext(os.path.basename(rawfilepath)) paramPath = aux.joinpath(outputpath, filename+'.pparse.para') with open(paramPath, 'wb') as openfile: openfile.write(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 execute(paramPath, executable='pParse.exe'): """Execute pParse with the specified parameter file. :param paramPath: location of the pParse parameter file :pa...
procArgs = [executable, paramPath] ## run it ## proc = subprocess.Popen(procArgs, stderr=subprocess.PIPE) ## But do not wait till netstat finish, start displaying output immediately ## while True: out = proc.stderr.read(1) if out == '' and proc.poll() != None: break ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanUpPparse(outputpath, rawfilename, mgf=False): """Delete temporary files generated by pparse, including the filetypes ".csv", ".ms1", ".ms2", ".xtract", ...
extensions = ['csv', 'ms1', 'ms2', 'xtract'] filename, fileext = os.path.splitext(os.path.basename(rawfilename)) additionalFiles = [aux.joinpath(outputpath, 'pParsePlusLog.txt'), aux.joinpath(outputpath, filename+'.pparse.para'), ] for ext in extensions: ...
<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_handler(cls, message_handler, buffer_size, logger): """ Class variables used here since the framework creates an instance for each connection :param m...
cls.BUFFER_SIZE = buffer_size cls.message_handler = message_handler cls.logger = logger cls.message_handler.logger = logging.getLogger(message_handler.__class__.__name__) cls.message_handler.logger.setLevel(logger.level) return 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 handle(self): """ The required handle method. """
logger = StreamHandler.logger logger.debug("handling requests with message handler %s " % StreamHandler.message_handler.__class__.__name__) message_handler = StreamHandler.message_handler try: while True: logger.debug('waiting for more 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 receiveError(self, reasonCode, description): """ Called when we receive a disconnect error message from the other side. """
error = disconnectErrors.get(reasonCode, DisconnectError) self.connectionClosed(error(reasonCode, description)) SSHClientTransport.receiveError(self, reasonCode, description)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(self, event): """ Entry point to handle user events. :param event: Received event. See a full list `here <https://dev.twitter.com/streaming/overview/m...
callback = getattr(self, 'on_{event}'.format(event=event.event), None) callback(event)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _emplace_pmrna(mrnas, parent, strict=False): """Retrieve the primary mRNA and discard all others."""
mrnas.sort(key=lambda m: (m.cdslen, m.get_attribute('ID'))) pmrna = mrnas.pop() if strict: parent.children = [pmrna] else: parent.children = [c for c in parent.children if c not in mrnas]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _emplace_transcript(transcripts, parent): """Retrieve the primary transcript and discard all others."""
transcripts.sort(key=lambda t: (len(t), t.get_attribute('ID'))) pt = transcripts.pop() parent.children = [pt]
<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_mrna(entrystream, parenttype='gene'): """ Select a single mRNA as a representative for each protein-coding gene. The primary mRNA is the one with the...
for entry in entrystream: if not isinstance(entry, tag.Feature): yield entry continue for parent in tag.select.features(entry, parenttype, traverse=True): mrnas = [f for f in parent.children if f.type == 'mRNA'] if len(mrnas) == 0: co...
<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_primary_type(ttypes, parent, logstream=stderr): """Check for multiple transcript types and, if possible, select one."""
if len(ttypes) > 1: if logstream: # pragma: no branch message = '[tag::transcript::primary_transcript]' message += ' WARNING: feature {:s}'.format(parent.slug) message += ' has multiple associated transcript types' message += ' {}'.format(ttypes) ...
<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_transcript(entrystream, parenttype='gene', logstream=stderr): """ Select a single transcript as a representative for each gene. This function is a ge...
for entry in entrystream: if not isinstance(entry, tag.Feature): yield entry continue for parent in tag.select.features(entry, parenttype, traverse=True): if parent.num_children == 0: continue transcripts = defaultdict(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 parse_parent(docname): """ Given a docname path, pick apart and return name of parent """
lineage = docname.split('/') lineage_count = len(lineage) if docname == 'index': # This is the top of the Sphinx project parent = None elif lineage_count == 1: # This is a non-index doc in root, e.g. about parent = 'index' elif lineage_count == 2 and lineage[-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 parents(self, resources): """ Split the path in name and get parents """
if self.docname == 'index': # The root has no parents return [] parents = [] parent = resources.get(self.parent) while parent is not None: parents.append(parent) parent = resources.get(parent.parent) return parents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acquire(self, resources, prop_name): """ Starting with self, walk until you find prop or None """
# Instance custom_prop = getattr(self.props, prop_name, None) if custom_prop: return custom_prop # Parents...can't use acquire as have to keep going on acquireds for parent in self.parents(resources): acquireds = parent.props.acquireds if ac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_prop_item(self, prop_name, prop_key, prop_value): """ Look for a list prop with an item where key == value """
# Image props are a sequence of dicts. We often need one of them. # Where one of the items has a dict key matching a value, and if # nothing matches, return None prop = getattr(self.props, prop_name, None) if prop: return next( (p for p in prop ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect(self, code) : """ Detect language with code """
keywords = KeywordFetcher.fetch( code ) probabilities = {} for keyword in keywords : if keyword not in self.trained_set['keywords'] : continue data = self.trained_set['keywords'][keyword] p_avg = sum(data.values()) / len(data) # Average probability of all languages for language, probability...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch(code) : """ Fetch keywords by Code """
ret = {} code = KeywordFetcher._remove_strings(code) result = KeywordFetcher.prog.findall(code) for keyword in result : if len(keyword) <= 1: continue # Ignore single-length word if keyword.isdigit(): continue # Ignore number if keyword[0] == '-' or keyword[0] == '*' : keyword = keyword[1:] # Remov...
<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_strings(code) : """ Remove strings in code """
removed_string = "" is_string_now = None for i in range(0, len(code)-1) : append_this_turn = False if code[i] == "'" and (i == 0 or code[i-1] != '\\') : if is_string_now == "'" : is_string_now = None elif is_string_now == None : is_string_now = "'" append_this_turn = True 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 getratio(self, code) : """ Get ratio of code and pattern matched """
if len(code) == 0 : return 0 code_replaced = self.prog.sub('', code) return (len(code) - len(code_replaced)) / len(code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadXmlProperty(self, xprop): """ Loads an XML property that is a child of the root data being loaded. :param xprop | <xml.etree.ElementTree.Element> """
if xprop.tag == 'property': value = self.dataInterface().fromXml(xprop[0]) self._xmlData[xprop.get('name', '')] = 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 toXml(self, xparent=None): """ Converts this object to XML. :param xparent | <xml.etree.ElementTree.Element> || None :return <xml.etree.ElementTree.Element> ...
if xparent is None: xml = ElementTree.Element('object') else: xml = ElementTree.SubElement(xparent, 'object') xml.set('class', self.__class__.__name__) for name, value in self._xmlData.items(): xprop = ElementTree.SubElement(xml, 'property') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromXml(cls, xml): """ Restores an object from XML. :param xml | <xml.etree.ElementTree.Element> :return subclass of <XmlObject> """
clsname = xml.get('class') if clsname: subcls = XmlObject.byName(clsname) if subcls is None: inst = MissingXmlObject(clsname) else: inst = subcls() else: inst = cls() inst.loadXml(xml) return inst
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def template_substitute(text, **kwargs): """ Replace placeholders in text by using the data mapping. Other placeholders that is not represented by data is left u...
for name, value in kwargs.items(): placeholder_pattern = "{%s}" % name if placeholder_pattern in text: text = text.replace(placeholder_pattern, value) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wva(values, weights): """ Calculates a weighted average """
assert len(values) == len(weights) and len(weights) > 0 return sum([mul(*x) for x in zip(values, weights)]) / sum(weights)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_one_to_many_job(parent_class=None, get_unfinished_kwargs=None, get_unfinished_limit=None, parser_func=None, parser_func_kwargs=None, build_url_func_kw...
# prepare arguments get_unfinished_kwargs = prepare_kwargs(get_unfinished_kwargs) parser_func_kwargs = prepare_kwargs(parser_func_kwargs) build_url_func_kwargs = prepare_kwargs(build_url_func_kwargs) downloader_func_kwargs = prepare_kwargs(downloader_func_kwargs) post_process_response_func_kwar...
<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_db_schema(cls, cur, schema_name): """ Create Postgres schema script and execute it on cursor """
create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name) cur.execute(create_schema_script)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def revoke_all(cls, cur, schema_name, roles): """ Revoke all privileges from schema, tables, sequences and functions for a specific role """
cur.execute('REVOKE ALL ON SCHEMA {0} FROM {1};' 'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};' 'REVOKE ALL ON ALL SEQUENCES IN SCHEMA {0} FROM {1};' 'REVOKE ALL ON ALL FUNCTIONS IN SCHEMA {0} FROM {1};'.format(schema_name, roles))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def schema_exists(cls, cur, schema_name): """ Check if schema exists """
cur.execute("SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');" .format(schema_name)) return cur.fetchone()[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 pandas(self): """Return a Pandas dataframe."""
if self._pandas is None: self._pandas = pd.DataFrame().from_records(self.list_of_dicts) return self._pandas
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(self, dialect): """Return a copy of this ResultSet in a different dialect."""
new_resultset = copy(self) new_resultset.dialect = dialect for result in new_resultset: for dimensionvalue in result.dimensionvalues: dimensionvalue.value = dimensionvalue.translate(dialect) return new_resultset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, val): """Connect any new results to the resultset. This is where all the heavy lifting is done for creating results: - We add a datatype here, s...
val.resultset = self val.dataset = self.dataset # Check result dimensions against available dimensions for this dataset if val.dataset: dataset_dimensions = self.dataset.dimensions for k, v in val.raw_dimensions.items(): if k not in dataset_dimen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allowed_values(self): """Return a list of allowed values."""
if self._allowed_values is None: self._allowed_values = ValueList() for val in self.scraper._fetch_allowed_values(self): if isinstance(val, DimensionValue): self._allowed_values.append(val) else: self._allowed_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 append(self, val): """Connect any new items to the scraper."""
val.scraper = self.scraper val._collection_path = copy(self.collection._collection_path) val._collection_path.append(val) super(ItemList, self).append(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 _move_here(self): """Move the cursor to this item."""
cu = self.scraper.current_item # Already here? if self is cu: return # A child? if cu.items and self in cu.items: self.scraper.move_to(self) return # A parent? if self is cu.parent: self.scraper.move_up() # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def items(self): """ItemList of children."""
if self.scraper.current_item is not self: self._move_here() if self._items is None: self._items = ItemList() self._items.scraper = self.scraper self._items.collection = self for i in self.scraper._fetch_itemslist(self): i.pare...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hash(self): """Return a hash for the current query. This hash is _not_ a unique representation of the dataset! """
dump = dumps(self.query, sort_keys=True) if isinstance(dump, str): dump = dump.encode('utf-8') return md5(dump).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dimensions(self): """Available dimensions, if defined."""
# First of all: Select this dataset if self.scraper.current_item is not self: self._move_here() if self._dimensions is None: self._dimensions = DimensionList() for d in self.scraper._fetch_dimensions(self): d.dataset = self d....
<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(cls, hook): """Hook decorator."""
def decorator(function_): cls._hooks[hook].append(function_) return function_ return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_to_top(self): """Move to root item."""
self.current_item = self.root for f in self._hooks["top"]: f(self) 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 move_up(self): """Move up one level in the hierarchy, unless already on top."""
if self.current_item.parent is not None: self.current_item = self.current_item.parent for f in self._hooks["up"]: f(self) if self.current_item is self.root: for f in self._hooks["top"]: f(self) 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 descendants(self): """Recursively return every dataset below current item."""
for i in self.current_item.items: self.move_to(i) if i.type == TYPE_COLLECTION: for c in self.children: yield c else: yield i self.move_up()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def children(self): """Former, misleading name for descendants."""
from warnings import warn warn("Deprecated. Use Scraper.descendants.", DeprecationWarning) for descendant in self.descendants: yield descendant
<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_python_name(s, default=None, number_prefix='N',encoding="utf-8"): """Returns a unicode string that can be used as a legal python identifier. :Arguments:...
if s in ('', None): s = default s = str(s) s = re.sub("[^a-zA-Z0-9_]", "_", s) if not re.match('\d', s) is None: s = number_prefix+s return unicode(s, encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_type(self, data_type): """Sets the data_type of this Option. :param data_type: The data_type of this Option. :type: str """
allowed_values = ["string", "number", "date", "color"] if data_type is not None and data_type not in allowed_values: raise ValueError( "Invalid value for `data_type` ({0}), must be one of {1}" .format(data_type, allowed_values) ) self._da...
<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_callable_signature_as_string(the_callable): """Return a string representing a callable. It is executed as if it would have been declared on the prompt. d...
args, varargs, varkw, defaults = inspect.getargspec(the_callable) tmp_args = list(args) args_dict = {} if defaults: defaults = list(defaults) else: defaults = [] while defaults: args_dict[tmp_args.pop()] = defaults.pop() while tmp_args: args_dict[tmp_args.po...
<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_callable_documentation(the_callable): """Return a string with the callable signature and its docstring. :param the_callable: the callable to be analyzed....
return wrap_text_in_a_box( title=get_callable_signature_as_string(the_callable), body=(getattr(the_callable, '__doc__') or 'No documentation').replace( '\n', '\n\n'), style='ascii_double')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_extension_class(ext, base, *args, **kwargs): """Instantiate the given extension class and register as a public attribute of the given base. README: ...
ext_instance = ext.plugin(base, *args, **kwargs) setattr(base, ext.name.lstrip('_'), ext_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 register_extension_method(ext, base, *args, **kwargs): """Register the given extension method as a public attribute of the given base. README: The expected p...
bound_method = create_bound_method(ext.plugin, base) setattr(base, ext.name.lstrip('_'), bound_method)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def token_auto_auth(func): """Wrap class methods with automatic token re-authentication. This wrapper will detect authentication failures coming from its wrapped...
@functools.wraps(func) def wrapper(self, *args, **kwargs): try: response = func(self, *args, **kwargs) # If auth failure occurs, attempt to re-authenticate and replay once at most. except errors.AuthFailure: # Request to have authentication refreshed. ...
<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_theme_dir(): """ Returns path to directory containing this package's theme. This is designed to be used when setting the ``html_theme_path`` option withi...
return os.path.abspath(os.path.join(os.path.dirname(__file__), "theme"))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def seconds2str(seconds): """Returns string such as 1h 05m 55s."""
if seconds < 0: return "{0:.3g}s".format(seconds) elif math.isnan(seconds): return "NaN" elif math.isinf(seconds): return "Inf" m, s = divmod(seconds, 60) h, m = divmod(m, 60) if h >= 1: return "{0:g}h {1:02g}m {2:.3g}s".format(h, m, s) elif m ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_fieldnames(string_, varname="fieldnames"): """Evaluates string_, must evaluate to list of strings. Also converts field names to uppercase"""
ff = eval(string_) if not isinstance(ff, list): raise RuntimeError("{0!s} must be a list".format(varname)) if not all([isinstance(x, str) for x in ff]): raise RuntimeError("{0!s} must be a list of strings".format(varname)) ff = [x.upper() for x in ff] return ff
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_accents(s): """ Strip accents to prepare for slugification. """
nfkd = unicodedata.normalize('NFKD', unicode(s)) return u''.join(ch for ch in nfkd if not unicodedata.combining(ch))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slugify(s): """ Converts the given string to a URL slug. """
s = strip_accents(s.replace("'", '').lower()) return re.sub('[^a-z0-9]+', ' ', s).strip().replace(' ', '-')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _legacy_status(stat): """Legacy status method from the 'qsmobile.js' library. Pass in the 'val' from &devices or the 'data' received after calling a specific...
# 2d0c00002a0000 if stat[:2] == '30' or stat[:2] == '47': # RX1 CT ooo = stat[4:5] # console.log("legstat. " + o); if ooo == '0': return 0 if ooo == '8': return 100 if stat == '7e': return 0 if stat == '7f': return 100 if 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 decode_door(packet, channel=1): """Decode a door sensor."""
val = str(packet.get(QSDATA, '')) if len(val) == 6 and val.startswith('46') and channel == 1: return val[-1] == '0' return None