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) backend = self.get_backend(social_user, provider, context=kwargs) return backend.publish(obj, comment)
<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 facebook - scope string ''' try: social_user = self._get_social_user(user, provider) if not social_user: return False except SocialUserDoesNotExist: return False backend = self.get_backend(social_user, provider, context=kwargs) return backend.check(permission)
<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.communicate(input=image, timeout=10) stdout = io.StringIO(str(stdout, 'utf-8')) except subprocess.TimeoutExpired: _LOGGER.error("Alpr process timeout!") alpr.kill() return None tmp_res = {} while True: line = stdout.readline() if not line: if len(tmp_res) > 0: result.append(tmp_res) break new_plate = self.__re_plate.search(line) new_result = self.__re_result.search(line) # found a new plate if new_plate and len(tmp_res) > 0: result.append(tmp_res) tmp_res = {} continue # found plate result if new_result: try: tmp_res[new_result.group(1)] = float(new_result.group(2)) except ValueError: continue _LOGGER.debug("Process alpr with result: %s", result) 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 finished(finished_status, update_interval, table, status_column, edit_at_column): """ Create text sql statement query for sqlalchemy that getting all finished task. :param finished_status: int, status code that greater or equal than this will be considered as finished. :param update_interval: int, the record will be updated every x seconds. :return: sqlalchemy text sql statement. **中文文档** 状态码大于某个值, 并且, 更新时间在最近一段时间以内. """
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 unfinished task. :param finished_status: int, status code that less than this will be considered as unfinished. :param update_interval: int, the record will be updated every x seconds. :return: sqlalchemy text sql statement. **中文文档** 状态码小于某个值, 或者, 现在距离更新时间已经超过一定阈值. """
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) within which to search for x0 x0: singleton or array of values to search for in x outputs: idx: index of flattened x nearest to x0 (i.e. works with higher than 1-D arrays also) xidx: x[idx] Observe how bisect.bisect() gives the incorrect result! idea based on: http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array """
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 IndexError (all-nan) becaues returning None can surprise with slice indexing for i, xi in enumerate(x0): if xi is not None and (isinstance(xi, (datetime.datetime, datetime.date, np.datetime64)) or np.isfinite(xi)): ind[i] = np.nanargmin(abs(x-xi)) else: raise ValueError('x0 must NOT be None or NaN to avoid surprising None return value') return ind.squeeze()[()], x[ind].squeeze()[()]
<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 the case, the attribute is created by using the default_value. """
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 object. """
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], (), perfect) return item, (i,) + trace raise KeyError(key) else: head, tail = key[0], key[1:] for i in range(len(tree['subtrees'])): if tree['subtrees'][i][0] == head or \ not perfect and tree['subtrees'][i][0] == '*': try: item, trace = find_in_tree(tree['subtrees'][i][1], tail, perfect) return item, (i,) + trace except KeyError: pass raise KeyError(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 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 result. Throw ``KeyError`` if the key path doesn't exist in the tree. """
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 (namespace.Namespace): The Namespace object to store. Raises: TypeError: If the namespace is not a Namespace object. ValueError: If the namespace is already registered. """
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 target state. Args: newstate: A str state name to calculate the path to. Returns: A bitarray containing the bits that would transition this state machine to the target state. The bits read from right to left. For efficiency, this retulting bitarray is cached. Do not edit this bitarray, or it will cause undefined behavior. """
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) path = self._find_shortest_path(self._statestr, newstate) if not path: raise ValueError("No path to the requested state.") res = self._get_steps_from_nodes_path(path) res.reverse() JTAGStateMachine._lookup_cache[(self.state, newstate)] = res return res
<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 either the registerDisplay or registerExcept functions. """
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__: _excepthooks.append(weakref.ref(sys.excepthook)) # replace the current hooks sys.displayhook = displayhook sys.excepthook = 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 (ideally a ``datetime`` instance) to pass through. :return: A ``datetime.datetime`` representing ``text``. Or ``text`` if it was anything but a ``unicode`` string. """
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 the given name. :param unicode name: The name of the definition to use. :return: A Python class which can be used to represent the Swagger definition of the given name. """
while True: try: cls = self._pclasses[name] except KeyError: try: original_definition = self.definitions[name] except KeyError: raise NoSuchDefinition(name) if "$ref" in original_definition: # Identify definitions that are merely a reference to # another and restart processing. There is some # duplication of logic between this and the $ref handling # in _ClassModel. It would be nice to eliminate this # duplication. name = original_definition[u"$ref"] assert name.startswith(u"#/definitions/") name = name[len(u"#/definitions/"):] continue definition = self.transform_definition(name, original_definition) kind = self._identify_kind(definition) if kind is None: raise NotClassLike(name, definition) generator = getattr(self, "_model_for_{}".format(kind)) model = generator(name, definition) bases = tuple(self._behaviors.get(name, [])) cls = model.pclass(bases) self._pclasses[name] = cls 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 _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 the specification. :param pyrsistent.PMap definition: A Swagger definition to categorize. This will be a value like the one found at ``spec["definitions"][name]``. """
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: A callable like ``Swagger.pclass_for_definition`` which can be used to resolve type references encountered in the definition. :param unicode name: The name of the definition. :param definition: The Swagger definition to model. This will be a value like the one found at ``spec["definitions"][name]``. :return: A new model for the given 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 class. These will appear to the left of ``PClass``. """
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("kind", None) kwargs.pop("apiVersion", None) return ctor() raise def lt_pclass(self, other): if isinstance(other, self.__class__): return sorted(self.serialize().items()) < sorted(other.serialize().items()) return NotImplemented def eq_pclass(self, other): if isinstance(other, self.__class__): return sorted(self.serialize().items()) == sorted(other.serialize().items()) return NotImplemented content = { attr.name: attr.pclass_field_for_attribute() for attr in self.attributes } content["__doc__"] = nativeString(self.doc) content["serialize"] = _serialize_with_omit content["__new__"] = discard_constant_fields content["__lt__"] = lt_pclass content["__eq__"] = eq_pclass content["__hash__"] = PClass.__hash__ content = total_ordering(content) huh = type(nativeString(self.name), bases + (PClass,), content) return huh
<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(iterable),) * size return ( # pylint: disable=star-args itertools.takewhile(lambda x: x is not None, group) for group in itertools.zip_longest(*args) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 the matrix. if height_difference > 0: for _ in range(height_difference): matrix.insert(0, [default] * width) # If the column is shorter, we'll need to shift it down. if height_difference < 0: offset = -height_difference #column = ([default] * offset) + column for index, value in enumerate(column): # The row index is the index in the column plus our offset. row_index = index + offset row = matrix[row_index] # If this row is short, pad it with default values. width_difference = width - len(row) row.extend([default] * width_difference) row.append(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 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 its dependent axis is the vertical axis. Thus each value is represented as a row running left to right, and values are listed top to bottom. If the iterable contains more than four integers, it will be chunked into groups of four, separated with newlines by default. '⣷⣄' '⣷⣄\n⠛⠛⠓' ⣷⣄ ⠛⠛⠓ Alternately, the arguments can be passed directly: '⣷⣄' The optional sep parameter controls how groups are separated. If sep is not passed (or if it is None), they are put on their own lines. For example, to keep everything on one line, space could be used: '⡯⠥ ⣿⣛⣓⠒⠂' """
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 groups of four, one for each row in the braille # blocks. for bar_group in _chunk(bars, 4): line = [] for braille_row, bar_value in enumerate(bar_group): # The number of full braille blocks needed to draw this bar. Each # block is two dots wide. full_blocks_needed = bar_value // 2 # The number of braille blocks needed to draw this bar. The second # term accounts for a possible half row. blocks_needed = full_blocks_needed + (bar_value % 2) # The number of braille blocks we'll need to append to the current # line to accomodate this bar extra_blocks_needed = blocks_needed - len(line) # If we need extra blocks, add them. if extra_blocks_needed > 0: line.extend([_BRAILLE_EMPTY_BLOCK] * extra_blocks_needed) # Fill in the majority of the bar with full braille rows (two dots). for block_index in range(full_blocks_needed): line[block_index] += _BRAILLE_FULL_ROW[braille_row] # If the bar's value is odd, we'll need to add a single dot at the # end. if bar_value % 2: line[full_blocks_needed] += _BRAILLE_HALF_ROW[braille_row] # Wrap up this line by converting all the code points to characters # and concatenating them. lines.append(''.join(chr(code) for code in line)) # Join all the lines to make the final graph return sep.join(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 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 dependent axis is the horizontal axis. Thus each value is represented as a column running bottom to top, and values are listed left to right. The graph is anchored to the bottom, so columns fill in from the bottom of the current braille character and the next character is added on top when needed. For columns with no dots, the blank braille character is used, not a space character. '⣠⣾' '⠀⠀⣠\n⣠⣾⣿' ⠀⠀⣠ ⣠⣾⣿ Alternately, the arguments can be passed directly: '⣠⣾' """
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(bars, 2): column = [] for braille_col, bar_value in enumerate(bar_group): # The number of full braille blocks needed to draw this bar. Each # block is four dots tall. full_blocks_needed = bar_value // 4 # The number of braille blocks needed to draw this bar. This # accounts for a possible partial block. blocks_needed = full_blocks_needed + (1 if bar_value % 4 else 0) # The number of new lines we'll need to prepend to accomodate this # bar extra_blocks_needed = blocks_needed - len(column) # If we need extra blocks, add them. column = ([_BRAILLE_EMPTY_BLOCK] * extra_blocks_needed) + column # Fill in the majority of the column with full braille colums (four # dots). We negate the index to access from the end of the list. for block_index in range(-full_blocks_needed, 0, 1): column[block_index] += _BRAILLE_FULL_COL[braille_col] # If we need a partial column, fill it in. We negate the index to # access from the end of the list. if bar_value % 4: partial_index = (bar_value % 4) - 1 column[-blocks_needed] += ( _BRAILLE_PARTIAL_COL[braille_col][partial_index] ) # Add this column to the lines. _matrix_add_column(lines, column, default=_BRAILLE_EMPTY_BLOCK) # Convert all the code points into characters, concatenate them into lines, # then concatenate all the lines to make the final graph. return '\n'.join(''.join(chr(code) for code in line) for line in 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 generate_example(config, ext='json'): """Generate an example file based on the given Configuration object. Args: config (confpy.core.configuration.Configuration): The configuration object on which to base the example. ext (str): The file extension to render. Choices: JSON and INI. Returns: str: The text of the example file. """
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 without the tag and a bool that indicates wheter the tag was present. """
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 the generated protein id. :param headerInfo: dict, must contain a key "id" :param isDecoy: bool, determines if the "decoyTag" is added or not. :param decoyTag: str, a tag that identifies decoy / reverse protein entries. :returns: str, protein id """
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 of the generated protein name. :param headerInfo: dict, must contain a key "name" or "id" :param isDecoy: bool, determines if the "decoyTag" is added or not. :param decoyTag: str, a tag that identifies decoy / reverse protein entries. :returns: str, protein name """
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, proteinId :param digestInfo: dict, contains information about the in silico digest must contain the keys 'missedCleavage', 'startPos' and 'endPos' """
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.peptides[stdSequence] if proteinId not in self.peptides[stdSequence].proteins: #FUTURE: peptide can appear at multiple positions per protein. #peptideEntry.addSource(proteinId, startPos, endPos) self.peptides[stdSequence].proteins.add(proteinId) self.peptides[stdSequence].proteinPositions[proteinId] = ( digestInfo['startPos'], digestInfo['endPos'] ) self.proteins[proteinId].peptides.add(sequence)
<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_patterns = options.leak_detector_ignore_patterns self.save_traceback = options.leak_detector_save_traceback self.multiprocessing_enabled = bool(getattr(options, 'multiprocess_workers', 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 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 new :return: """
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)) for (method_name, method_ptr) in methods] for (method_ptr, method_deps) in deps_of_endpoints: if len(method_deps) > 0: method_ptr(instance, **method_deps) except KeyError: pass if auto and instance not in self.current_scope.get_auto_bind_list(): self.current_scope.auto_bind(instance) 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 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)) odict[name] = _list elif isinstance(attr_value, Entity): odict[name] = attr_value.as_dict() else: odict[name] = getattr(self, name) return odict
<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(cls.map(_list.typeof(), _dict)) elif isinstance(value, dict): attr = getattr(cls, key) instance = attr.expected_type() Entity.map(instance, value) setattr(cls, key, instance) else: setattr(cls, key, value) else: setattr(cls, key, 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 generateParams(rawfilepath, outputpath, isolationWindow, coElute): """Generates a string containing the parameters for a pParse parameter file but doesn't write any file yet. :param rawfilepath: location of the thermo ".raw" file :param outputpath: path to the output directory of pParse :param isolationWindow: MSn isolation window that was used for the aquisition of the specified thermo raw file :param coElute: 0 or 1, see "[Advanced Options]" below :returns: string containing pParse parameters .. note: # pParse.para params template # For help: mail to tuhuijun@ict.ac.cn # Time: 2014.12.08 [Basic Options] datapath = C:\filedirectory\filename logfilepath = C:\filedirectory outputpath = C:\filedirectory [Advanced Options] co-elute = 1 # 0, output single precursor for single scan; # 1, output all co-eluted precursors. input_format = raw # raw / ms1 isolation_width = 1.6 # 2 / 2.5 / 3 / 4 mars_threshold = -0.5 ipv_file = .\IPV.txt trainingset = EmptyPath [Internal Switches] output_mars_y = 0 delete_msn = 0 output_mgf = 1 output_pf = 1 debug_mode = 0 check_activationcenter = 1 output_all_mars_y = 0 rewrite_files = 0 export_unchecked_mono = 0 cut_similiar_mono = 1 mars_model = 4 output_trainingdata = 0 """
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, ' = '.join(['co-elute', str(coElute)])]) output = '\n'.join([output, ' = '.join(['input_format', 'raw'])]) output = '\n'.join([output, ' = '.join(['isolation_width', str(isolationWindow)] )]) output = '\n'.join([output, ' = '.join(['mars_threshold', '-0.5'])]) output = '\n'.join([output, ' = '.join(['ipv_file', '.\IPV.txt'])]) output = '\n'.join([output, ' = '.join(['trainingset', 'EmptyPath'])]) #Internal Switches output = '\n'.join([output, ' = '.join(['output_mars_y', '0'])]) output = '\n'.join([output, ' = '.join(['delete_msn', '0'])]) output = '\n'.join([output, ' = '.join(['output_mgf', '1'])]) output = '\n'.join([output, ' = '.join(['output_pf', '0'])]) output = '\n'.join([output, ' = '.join(['debug_mode', '0'])]) output = '\n'.join([output, ' = '.join(['check_activationcenter', '1'])]) output = '\n'.join([output, ' = '.join(['output_all_mars_y', '0'])]) output = '\n'.join([output, ' = '.join(['rewrite_files', '0'])]) output = '\n'.join([output, ' = '.join(['export_unchecked_mono', '0'])]) output = '\n'.join([output, ' = '.join(['cut_similiar_mono', '1'])]) output = '\n'.join([output, ' = '.join(['mars_model', '4'])]) output = '\n'.join([output, ' = '.join(['output_trainingdata', '0'])]) return output
<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 ".raw" file :param outputpath: path to the output directory of pParse :param isolationWindow: MSn isolation window that was used for the aquisition of the specified thermo raw file :param coElute: :returns: file path of the pParse parameter file """
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(paramText) return paramPath
<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 :param executable: must specify the complete file path of the pParse.exe if its location is not in the ``PATH`` environment variable. :returns: :func:`subprocess.Popen` return code, 0 if pParse was executed successful """
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 if out != '': sys.stdout.write(out) sys.stdout.flush() return proc.returncode
<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", the files "pParsePlusLog.txt" and "pParse.para" and optionally also the ".mgf" file generated by pParse. .. warning: When the parameter "mgf" is set to "True" all files ending with ".mgf" and containing the specified "filename" are deleted. This could potentially also affect MGF files not generated by pParse. :param outputpath: path to the output directory of pParse :param rawfilename: filename of the thermo ".raw" file :param mgf: bool, if True the ".mgf" file generated by pParse is also removed """
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: filepath = aux.joinpath(outputpath, '.'.join([filename, ext])) if os.path.isfile(filepath): print('Removing file: ', filepath) os.remove(filepath) for filepath in additionalFiles: if os.path.isfile(filepath): print('Removing file: ', filepath) os.remove(filepath) if mgf: for _filename in os.listdir(outputpath): _basename, _fileext = os.path.splitext(_filename) if _fileext.lower() != '.mgf': continue if _basename.find(basename) != -1 and _basename != basename: filepath = aux.joinpath(outputpath, _filename) print('Removing file: ', filepath) os.remove(filepath)
<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 message_handler: the MessageHandler used to process each message. :param buffer_size: the TCP buffer size. :param logger: the global logger. :return: this class. """
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') if not message_handler.handle(self.request, StreamHandler.BUFFER_SIZE): break logger.warning("connection closed from %s" % (self.client_address[0])) self.request.close() except: logger.exception("connection closed from %s" % (self.client_address[0])) finally: self.request.close()
<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/messages-types#Events_event>`_. """
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 longest translation product. In cases where multiple isoforms have the same translated length, the feature ID is used for sorting. This function **does not** return only mRNA features, it returns all GFF3 entry types (pragmas, features, sequences, etc). The function **does** modify the gene features that pass through to ensure that they have at most a single mRNA feature. """
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: continue _emplace_pmrna(mrnas, parent) yield entry
<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) print(message, file=logstream) if 'mRNA' not in ttypes: message = ( 'cannot resolve multiple transcript types if "mRNA" is' ' not one of those types {}'.format(ttypes) ) raise Exception(message) ttypes = ['mRNA'] return ttypes[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 primary_transcript(entrystream, parenttype='gene', logstream=stderr): """ Select a single transcript as a representative for each gene. This function is a generalization of the `primary_mrna` function that attempts, under certain conditions, to select a single transcript as a representative for each gene. If a gene encodes multiple transcript types, one of those types must be **mRNA** or the function will complain loudly and fail. For mRNAs, the primary transcript is selected according to translated length. For all other transcript types, the length of the transcript feature itself is used. I'd be eager to hear suggestions for alternative selection criteria. Like the `primary_mrna` function, this function **does not** return only transcript features. It **does** modify gene features to ensure that each has at most one transcript feature. In cases where the direct children of a gene feature have heterogenous types, the `primary_mrna` function will only discard mRNA features. This function, however, will discard all direct children of the gene that are not the primary transcript, including non-transcript children. This is a retty subtle distinction, and anecdotal experience suggests that cases in which the distinction actually matters are extremely rare. """
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) for child in parent.children: if child.type in type_terms: transcripts[child.type].append(child) if len(transcripts) == 0: continue ttypes = list(transcripts.keys()) ttype = _get_primary_type(ttypes, parent) transcript_list = transcripts[ttype] if ttype == 'mRNA': _emplace_pmrna(transcript_list, parent, strict=True) else: _emplace_transcript(transcript_list, parent) yield entry
<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] == 'index': # This is blog/index, parent is the root parent = 'index' elif lineage_count == 2: # This is blog/about parent = lineage[0] + '/index' elif lineage[-1] == 'index': # This is blog/sub/index parent = '/'.join(lineage[:-2]) + '/index' else: # This should be blog/sub/about parent = '/'.join(lineage[:-1]) + '/index' return parent
<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 acquireds: # First try in the per-type acquireds rtype_acquireds = acquireds.get(self.rtype) if rtype_acquireds: prop_acquired = rtype_acquireds.get(prop_name) if prop_acquired: return prop_acquired # Next in the "all" section of acquireds all_acquireds = acquireds.get('all') if all_acquireds: prop_acquired = all_acquireds.get(prop_name) if prop_acquired: return prop_acquired 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 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 if getattr(p, prop_key) == prop_value), 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 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 in data.items() : # By Naïve Bayes Classification p = probability / p_avg probabilities[ language ] = probabilities.get(language, 0) + math.log(1 + p) for pattern, data in self.trained_set['patterns'].items() : matcher = PatternMatcher(pattern) p0 = matcher.getratio(code) for language, p_avg in data.items() : if language not in probabilities : continue p = 1 - abs(p_avg - p0) probabilities[ language ] *= p # Convert `log` operated probability to percentile sum_val = 0 for language, p in probabilities.items() : sum_val += math.pow(math.e / 2, p) for language, p in probabilities.items() : probabilities[language] = math.pow(math.e / 2, p) / sum_val * 100 return sorted(probabilities.items(), key=lambda a: a[1], reverse=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 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:] # Remove first char if string is starting by '-' or '*' (Pointer or Negative numbers) if keyword[-1] == '-' or keyword[-1] == '*' : keyword = keyword[0:-1] # Remove last char if string is finished by '-' or '*' if len(keyword) <= 1: continue ret[ keyword ] = ret.get(keyword, 0) + 1 # `ret[ keyword ] += 1` with initial value return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 elif 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 if is_string_now == None or append_this_turn == True : removed_string += code[i] return removed_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 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') xprop.set('name', name) XmlDataIO.toXml(value, xprop) return xml
<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 untouched. :param text: Text to search and replace placeholders. :param data: Data mapping/dict for placeholder key and values. :return: Potentially modified text with replaced placeholders. """
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_kwargs=None, downloader_func=None, downloader_func_kwargs=None, post_process_response_func=None, post_process_response_func_kwargs=None, process_item_func_kwargs=None, logger=None, sleep_time=None): """ A standard one-to-many crawling workflow. :param parent_class: :param get_unfinished_kwargs: :param get_unfinished_limit: :param parser_func: html parser function. :param parser_func_kwargs: other keyword arguments for ``parser_func`` :param build_url_func_kwargs: other keyword arguments for ``parent_class().build_url(**build_url_func_kwargs)`` :param downloader_func: a function that taking ``url`` as first arg, make http request and return response/html. :param downloader_func_kwargs: other keyword arguments for ``downloader_func`` :param post_process_response_func: a callback function taking response/html as first argument. You can put any logic in it. For example, you can make it sleep if you detect that you got banned. :param post_process_response_func_kwargs: other keyword arguments for ``post_process_response_func`` :param process_item_func_kwargs: other keyword arguments for ``ParseResult().process_item(**process_item_func_kwargs)`` :param logger: :param sleep_time: default 0, wait time before making each request. """
# 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_kwargs = prepare_kwargs( post_process_response_func_kwargs) process_item_func_kwargs = prepare_kwargs(process_item_func_kwargs) if post_process_response_func is None: def post_process_response_func(response, **kwargs): pass if not isinstance(logger, SpiderLogger): raise TypeError if sleep_time is None: sleep_time = 0 # do the real job query_set = parent_class.get_all_unfinished(**get_unfinished_kwargs) if get_unfinished_limit is not None: query_set = query_set.limit(get_unfinished_limit) todo = list(query_set) logger.log_todo_volumn(todo) for parent_instance in todo: url = parent_instance.build_url(**build_url_func_kwargs) logger.log_to_crawl_url(url) logger.log_sleeper(sleep_time) time.sleep(sleep_time) try: response_or_html = downloader_func(url, **downloader_func_kwargs) if isinstance(response_or_html, string_types): parser_func_kwargs["html"] = response_or_html else: parser_func_kwargs["response"] = response_or_html post_process_response_func( response_or_html, **post_process_response_func_kwargs) except Exception as e: logger.log_error(e) continue try: parse_result = parser_func( parent=parent_instance, **parser_func_kwargs ) parse_result.process_item(**process_item_func_kwargs) logger.log_status(parse_result) except Exception as e: logger.log_error(e) continue
<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, so that each result can handle validation etc independently. This is so that scraper authors don't need to worry about creating and passing around datatype objects. - As the scraper author yields result objects, we append them to a resultset. - This is also where we normalize dialects. """
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_dimensions: d = Dimension(k) else: d = dataset_dimensions[k] # Normalize if we have a datatype and a foreign dialect normalized_value = unicode(v) if d.dialect and d.datatype: if d.dialect in d.datatype.dialects: for av in d.allowed_values: # Not all allowed_value have all dialects if unicode(v) in av.dialects.get(d.dialect, []): normalized_value = av.value # Use first match # We do not support multiple matches # This is by design. break # Create DimensionValue object if isinstance(v, DimensionValue): dim = v v.value = normalized_value else: if k in dataset_dimensions: dim = DimensionValue(normalized_value, d) else: dim = DimensionValue(normalized_value, Dimension()) val.dimensionvalues.append(dim) # Add last list of dimension values to the ResultSet # They will usually be the same for each result self.dimensionvalues = val.dimensionvalues super(ResultSet, 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 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_values.append(DimensionValue(val, Dimension())) return self._allowed_values
<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() # A sibling? if self.parent and self in self.parent.items: self.scraper.move_up() self.scraper.move_to(self) return # Last resort: Move to top and all the way down again self.scraper.move_to_top() for step in self.path: self.scraper.move_to(step)
<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.parent = self if i.type == TYPE_DATASET and i.dialect is None: i.dialect = self.scraper.dialect self._items.append(i) return self._items
<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.scraper = self.scraper self._dimensions.append(d) return self._dimensions
<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: *s* string *default* use *default* if *s* is ``None`` *number_prefix* string to prepend if *s* starts with a number """
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._data_type = data_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 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. def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd) :param the_callable: the callable to be analyzed. :type the_callable: function/callable. :return: the signature. """
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.pop()] = None args_list = [] for arg in args: if args_dict[arg] is not None: args_list.append("%s=%s" % (arg, repr(args_dict[arg]))) else: args_list.append(arg) if varargs: args_list.append("*%s" % varargs) if varkw: args_list.append("**%s" % varkw) args_string = ', '.join(args_list) return "def %s(%s)" % (the_callable.__name__, args_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 get_callable_documentation(the_callable): """Return a string with the callable signature and its docstring. :param the_callable: the callable to be analyzed. :type the_callable: function/callable. :return: the signature. """
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: The expected protocol here is to instantiate the given extension and pass the base object as the first positional argument, then unpack args and kwargs as additional arguments to the extension's constructor. """
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 protocol here is that the given extension method is an unbound function. It will be bound to the specified base as a method, and then set as a public attribute of that base. """
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 method. When one is caught, it will request a new token, and simply replay the original request. The one constraint that this wrapper has is that the wrapped method's class must have the :py:class:`objectrocket.client.Client` object embedded in it as the property ``_client``. Such is the design of all current client operations layers. """
@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. self._client.auth._refresh() # Replay original request. response = func(self, *args, **kwargs) return response # TODO(TheDodd): match func call signature and docs. return wrapper
<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 within Sphinx's ``conf.py`` file. """
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 >= 1: return "{0:02g}m {1:.3g}s".format(m, s) else: return "{0:.3g}s".format(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 ID. """
# 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(stat) == 6: # old try: val = int(stat[4:], 16) except ValueError: val = 0 hwt = stat[:2] if hwt == '01': # old dim return round(((125 - val) / 125) * 100) if hwt == '02': # old rel return 100 if val == 127 else 0 if hwt == '28': # LED DIM if stat[2:4] == '01': if stat[4:] == '78': return 0 return round(((120 - val) / 120) * 100) # Additional decodes not part of qsmobile.js if stat.upper().find('ON') >= 0: # Relay return 100 if (not stat) or stat.upper().find('OFF') >= 0: return 0 if stat.endswith('%'): # New style dimmers if stat[:-1].isdigit: return int(stat[:-1]) _LOGGER.debug("val='%s' used a -1 fallback in legacy_status", stat) return -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 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