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 list_series(self, keys=None, tags=None, attrs=None, limit=1000): """Get a list of all series matching the given criteria. **Note:** for the key argument, the filter will return the *union* of those values. For the tag and attr arguments, the filter will return the *intersection* of those values. :param keys: filter by one or more series keys :type keys: list or string :param tags: filter by one or more tags :type tags: list or string :param dict attrs: filter by one or more key-value attributes :rtype: :class:`tempodb.protocol.cursor.SeriesCursor` with an iterator over :class:`tempodb.protocol.objects.Series` objects"""
params = { 'key': keys, 'tag': tags, 'attr': attrs, 'limit': limit } url_args = endpoint.make_url_args(params) url = '?'.join([endpoint.SERIES_ENDPOINT, url_args]) resp = self.session.get(url) return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregate_data(self, start, end, aggregation, keys=[], tags=[], attrs={}, rollup=None, period=None, interpolationf=None, interpolation_period=None, tz=None, limit=1000): """Read data from multiple series according to a filter and apply a function across all the returned series to put the datapoints together into one aggregrate series. See the :meth:`list_series` method for a description of how the filter criteria are applied, and the :meth:`read_data` method for how to work with the start, end, and tz parameters. Valid aggregation functions are the same as valid rollup functions. :param string aggregation: the aggregation to perform :param keys: (optional) filter by one or more series keys :type keys: list or string :param tags: (optional) filter by one or more tags :type tags: list or string :param dict attrs: (optional) filter by one or more key-value attributes :param start: the start time for the data points :type start: string or Datetime :param end: the end time for the data points :type end: string or Datetime :param string rollup: (optional) the name of a rollup function to use :param string period: (optional) downsampling rate for the data :param string interpolationf: (optional) an interpolation function to run over the series :param string interpolation_period: (optional) the period to interpolate data into :param string tz: (optional) the timezone to place the data into :rtype: :class:`tempodb.protocol.cursor.DataPointCursor` with an iterator over :class:`tempodb.protocol.objects.DataPoint` objects"""
url = 'segment' vstart = check_time_param(start) vend = check_time_param(end) params = { 'start': vstart, 'end': vend, 'key': keys, 'tag': tags, 'attr': attrs, 'aggregation.fold': aggregation, 'rollup.fold': rollup, 'rollup.period': period, 'interpolation.function': interpolationf, 'interpolation.period': interpolation_period, 'tz': tz, 'limit': limit } url_args = endpoint.make_url_args(params) url = '?'.join([url, url_args]) resp = self.session.get(url) return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_data(self, key, data, tags=[], attrs={}): """Write a set a datapoints into a series by its key. For now, the tags and attributes arguments are ignored. :param string key: the series to write data into :param list data: a list of DataPoints to write :rtype: :class:`tempodb.response.Response` object"""
url = make_series_url(key) url = urlparse.urljoin(url + '/', 'data') #revisit later if there are server changes to take these into #account #params = { # 'tag': tag, # 'attr': attr, #} #url_args = endpoint.make_url_args(params) #url = '?'.join([url, url_args]) dlist = [d.to_dictionary() for d in data] body = json.dumps(dlist) resp = self.session.post(url, body) return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def single_value(self, key, ts=None, direction=None): """Return a single value for a series. You can supply a timestamp as the ts argument, otherwise the search defaults to the current time. The direction argument can be one of "exact", "before", "after", or "nearest". :param string key: the key for the series to use :param ts: (optional) the time to begin searching from :type ts: ISO8601 string or Datetime object :param string direction: criterion for the search :rtype: :class:`tempodb.response.Response` with a :class:`tempodb.protocol.objects.SingleValue` object as the data payload"""
url = make_series_url(key) url = urlparse.urljoin(url + '/', 'single') if ts is not None: vts = check_time_param(ts) else: vts = None params = { 'ts': vts, 'direction': direction } url_args = endpoint.make_url_args(params) url = '?'.join([url, url_args]) resp = self.session.get(url) return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_series_single_value(self, keys=None, ts=None, direction=None, attrs={}, tags=[]): """Return a single value for multiple series. You can supply a timestamp as the ts argument, otherwise the search defaults to the current time. The direction argument can be one of "exact", "before", "after", or "nearest". The id, key, tag, and attr arguments allow you to filter for series. See the :meth:`list_series` method for an explanation of their use. :param string keys: (optional) a list of keys for the series to use :param ts: (optional) the time to begin searching from :type ts: ISO8601 string or Datetime object :param string direction: criterion for the search :param tags: filter by one or more tags :type tags: list or string :param dict attrs: filter by one or more key-value attributes :rtype: :class:`tempodb.protocol.cursor.SingleValueCursor` with an iterator over :class:`tempodb.protocol.objects.SingleValue` objects"""
url = 'single/' if ts is not None: vts = check_time_param(ts) else: vts = None params = { 'key': keys, 'tag': tags, 'attr': attrs, 'ts': vts, 'direction': direction } url_args = endpoint.make_url_args(params) url = '?'.join([url, url_args]) resp = self.session.get(url) return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def async_open(self) -> None: """Opens connection to the LifeSOS ethernet interface."""
await self._loop.create_connection( lambda: self, self._host, self._port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_abbr(abbr_file=ABBREVIATION_FILE): """ Load the abbr2long from file """
abbr2long = dict() with open(abbr_file) as f: lines = f.read().split('\n') for line in lines: m = re.match(r'(\w+)\t(.+)', line) if m: abbr2long[m.group(1)] = m.group(2) return abbr2long
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_spelling(spell_file=SPELLING_FILE): """ Load the term_freq from spell_file """
with open(spell_file) as f: tokens = f.read().split('\n') size = len(tokens) term_freq = {token: size - i for i, token in enumerate(tokens)} return term_freq
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_search_freq(fp=SEARCH_FREQ_JSON): """ Load the search_freq from JSON file """
try: with open(fp) as f: return Counter(json.load(f)) except FileNotFoundError: return Counter()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize(s): """ A simple tokneizer """
s = re.sub(r'(?a)(\w+)\'s', r'\1', s) # clean the 's from Crohn's disease #s = re.sub(r'(?a)\b', ' ', s) # split the borders of chinese and english chars split_pattern = r'[{} ]+'.format(re.escape(STOPCHARS)) tokens = [token for token in re.split(split_pattern, s) if not set(token) <= set(string.punctuation)] return tokens
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_spelling(token_folder, spelling_file): """ Generate the spelling correction file form token_folder and save to spelling_file """
token_pattern = r'[a-z]{3,}' tokens = [] for base, dirlist, fnlist in os.walk(token_folder): for fn in fnlist: fp = os.path.join(base, fn) with open(fp) as f: toks = re.findall(token_pattern, f.read()) tokens.extend(toks) token_ranked, _ = zip(*Counter(tokens).most_common()) with open(spelling_file, 'w') as f: f.write('\n'.join(token_ranked))
<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_hints(code_list, k=10, hint_folder=HINT_FOLDER, current_tokens=None): """ Fetch first k hints for given code_list """
def hint_score(v, size): """ The formula for hint score """ return 1.0 - abs(v / (size + 1) - 0.5) if len(code_list) <= 1: return [], [] if current_tokens is None: current_tokens = [] size = min(len(code_list), MAX_HINT_SMAPLING_SIZE) sample = random.sample(code_list, size) hint_list = [] capital_dict = {} for code in sample: path = gen_path(hint_folder, code) fp = os.path.join(path, code) try: with open(fp) as f: hints = set(f.read().strip().split('\n')) hint_list.extend([h.lower() for h in hints]) capital_dict.update({hint.lower(): hint for hint in hints}) except FileNotFoundError: logging.warning("FileNotFoundError: No such file: %r" % fp ) document_freq = Counter(hint_list) score = [(capital_dict[k], hint_score(v, size)) \ for k, v in document_freq.items() if k not in current_tokens] if len(score) == 0: return [], [] score.sort(key=lambda x: x[1], reverse=True) hints, scores = tuple(list(zip(*score[:k]))) return hints, scores
<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(index, tokens): """ Fetch the codes from given tokens """
if len(tokens) == 0: return set() return set.intersection(*[set(index.get(token, [])) for token in tokens])
<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_snippets(code_list, base=SNIPPET_FOLDER): """ Get the snippets """
output = [] for code in code_list: path = gen_path(base, code) fp = os.path.join(path, code) try: with open(fp) as f: output.append(f.read()) except FileNotFoundError: output.append('') logging.warning("FileNotFoundError: No such file: %r" % fp ) 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 _ed1(token): """ Return tokens the edit distance of which is one from the given token """
insertion = {letter.join([token[:i], token[i:]]) for letter in string.ascii_lowercase for i in range(1, len(token) + 1)} deletion = {''.join([token[:i], token[i+1:]]) for i in range(1, len(token) + 1)} substitution = {letter.join([token[:i], token[i+1:]]) for letter in string.ascii_lowercase for i in range(1, len(token) + 1)} transposition = {''.join([token[:i], token[i+1:i+2], token[i:i+1], token[i+2:]]) for i in range(1, len(token)-1)} return set.union(insertion, deletion, substitution, transposition)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _correct(token, term_freq): """ Correct a single token according to the term_freq """
if token.lower() in term_freq: return token e1 = [t for t in _ed1(token) if t in term_freq] if len(e1) > 0: e1.sort(key=term_freq.get) return e1[0] e2 = [t for t in _ed2(token) if t in term_freq] if len(e2) > 0: e2.sort(key=term_freq.get) return e2[0] return token
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correct(tokens, term_freq): """ Correct a list of tokens, according to the term_freq """
log = [] output = [] for token in tokens: corrected = _correct(token, term_freq) if corrected != token: log.append((token, corrected)) output.append(corrected) return output, log
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(index, query, snippet_folder=SNIPPET_FOLDER, term_freq=term_freq): """ The highest level of search function """
fallback_log = [] code_list = [] tokens = tokenize(query) tokens, abbr_log = abbr_expand(tokens) tokens, correct_log = correct(tokens, term_freq) tokens = lemmatize(tokens) tokens = filterout(tokens) while len(tokens) > 0: # Fallback mechanism code_list = fetch(index, tokens) if len(code_list) > 0: break tokens.sort(key=lambda tk:len(index.get(tk, []))) remove = tokens.pop() fallback_log.append(remove) snippets = get_snippets(code_list, snippet_folder) hints, hint_scores = get_hints(code_list, current_tokens=tokens) response = list(zip(code_list, snippets)) response.sort(key=result_sort_key, reverse=True) # Count search_frequency if len(response) <= MAX_RESULT: # the respone can be shown in one page search_freq.update(code_list) with open(SEARCH_FREQ_JSON, 'w') as f: json.dump(search_freq, f, indent=2) return response, tokens, hints, hint_scores, \ abbr_log, correct_log, fallback_log
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _do_connection(self, wgt, sig, func): """ Make a connection between a GUI widget and a callable. wgt and sig are strings with widget and signal name func is a callable for that signal """
#new style (we use this) #self.btn_name.clicked.connect(self.on_btn_name_clicked) #old style #self.connect(self.btn_name, SIGNAL('clicked()'), self.on_btn_name_clicked) if hasattr(self, wgt): wgtobj = getattr(self, wgt) if hasattr(wgtobj, sig): sigobj = getattr(wgtobj, sig) if isinstance(sigobj, Signal): sigobj.connect(func) return 0 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 _process_list(self, l): """ Processes a list of widget names. If any name is between `` then it is supposed to be a regex. """
if hasattr(self, l): t = getattr(self, l) def proc(inp): w = inp.strip() if w.startswith('`'): r = re.compile(w[1:-1]) return [u for u in [m.group() for m in [r.match(x) for x in dir(self)] if m] if isinstance(getattr(self, u), QObject)] else: return [w] return list(set([y for x in map(proc, t.split(',')) for y in x])) 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 auto_connect(self): """ Make a connection between every member function to a GUI signal. Every member function whose name is in format: '_on_' + <widget_name> + '__' + <widget_signal_name> are connected to the signal of a GUI widget if it exists. Also, every function with format: '_when_' + <group_name> + '__' + <widget_signal_name> should also define a string named: '_' + <group_name> on class level _group1 = 'btn_add, btn_remove, `btn_l.+`, btn_test' _when_group1__clicked(self): who = self.sender() #use who to discover who called this callback inside the string you can use regex surronded by `` to select related widgets """
for o in dir(self): if o.startswith('_on_') and '__' in o: func = getattr(self, o) wgt, sig = o.split('__') if self._do_connection(wgt[4:], sig, func): print('Failed to connect', o) if o.startswith('_when_') and '__' in o: func = getattr(self, o) lst, sig = o.split('__') lst = self._process_list(lst[5:]) #5 to keep _ at beggining for w in lst: if self._do_connection(w, sig, func): print('Failed to connect', o)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_signals_and_slots(self): """ List all active Slots and Signal. Credits to: http://visitusers.org/index.php?title=PySide_Recipes#Debugging """
for i in xrange(self.metaObject().methodCount()): m = self.metaObject().method(i) if m.methodType() == QMetaMethod.MethodType.Signal: print("SIGNAL: sig=", m.signature(), "hooked to nslots=", self.receivers(SIGNAL(m.signature()))) elif m.methodType() == QMetaMethod.MethodType.Slot: print("SLOT: sig=", m.signature())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_all_signals(self): """ Prints out every signal available for this widget and childs. """
for o in dir(self): obj= getattr(self, o) #print o, type(obj) div = False for c in dir(obj): cobj = getattr(obj, c) if isinstance(cobj, Signal): print('def _on_{}__{}(self):'.format(o, c)) div = True if div: print('-'*30)
<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, path, all=False): ''' Looks for files in the app directories. ''' found = os.path.join(settings.STATIC_ROOT, path) if all: return [found] else: return found
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interrupt(self): """ Invoked on a write operation into the IR of the RendererDevice. """
if(self.device.read(9) & 0x01): self.handle_request() self.device.clear_IR()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_char_screen(self): """ Draws the output buffered in the char_buffer. """
self.screen = Image.new("RGB", (self.height, self.width)) self.drawer = ImageDraw.Draw(self.screen) for sy, line in enumerate(self.char_buffer): for sx, tinfo in enumerate(line): self.drawer.text((sx * 6, sy * 9), tinfo[0], fill=tinfo[1:]) self.output_device.interrupt()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_cli(self, prefix, other_cli): """Adds the functionality of the other CLI to this one, where all commands to the other CLI are prefixed by the given prefix plus a hyphen. e.g. To execute command `greet anson 5` on other cli given prefix cli2, you can execute the following with this CLI: cli2 greet anson 5 """
if prefix not in self.clis and prefix not in self.cmds: self.clis[prefix] = other_cli else: raise ValueError('Attempting to overwrite cmd or extern CLI: %s' % prefix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dispatch(self, cmd, args): """Attempt to run the given command with the given arguments """
if cmd in self.clis: extern_cmd, args = args[0], args[1:] self.clis[cmd]._dispatch(extern_cmd, args) else: if cmd in self.cmds: callback, parser = self.cmds[cmd] try: p_args = parser.parse_args(args) except SystemExit: return callback(**dict(filter(lambda p:p[1] != None, p_args._get_kwargs()))) else: self._invalid_cmd(command=cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exec_cmd(self, cmdstr): """Parse line from CLI read loop and execute provided command """
parts = cmdstr.split() if len(parts): cmd, args = parts[0], parts[1:] self._dispatch(cmd, args) else: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_help(self): """Prints usage of all registered commands, collapsing aliases into one record """
seen_aliases = set() print('-'*80) for cmd in sorted(self.cmds): if cmd not in self.builtin_cmds: if cmd not in seen_aliases: if cmd in self.aliases: seen_aliases.update(self.aliases[cmd]) disp = '/'.join(self.aliases[cmd]) else: disp = cmd _, parser = self.cmds[cmd] usage = parser.format_usage() print('%s: %s' % (disp, ' '.join(usage.split()[2:]))) print('External CLIs: %s' % ', '.join(sorted(self.clis)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, instream=sys.stdin): """Runs the CLI, reading from sys.stdin by default """
sys.stdout.write(self.prompt) sys.stdout.flush() while True: line = instream.readline() try: self.exec_cmd(line) except Exception as e: self.errfun(e) sys.stdout.write(self.prompt) sys.stdout.flush()
<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_finder(self, manager, package_name): """ Execute finder script within the temporary venv context. """
filename = '{env_path}/results.json'.format(env_path=manager.env_path) subprocess.call([ manager.venv_python, self._finder_path, package_name, filename ]) # Load results into this context json_str = open(filename, 'r').read() return json.loads(json_str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def urltool(classqname, filt, reverse): """ Dump all urls branching from a class as OpenAPI 3 documentation The class must be given as a FQPN which points to a Klein() instance. Apply optional [FILT] as a regular expression searching within urls. For example, to match all urls beginning with api, you might use '^/api' """
filt = re.compile(filt or '.*') rootCls = namedAny(classqname) rules = list(_iterClass(rootCls)) arr = [] for item in sorted(rules): if item.subKlein: continue matched = filt.search(item.rulePath) matched = not matched if reverse else matched if matched: arr.append(tuple(item.toOpenAPIPath())) openapi3 = openapi.OpenAPI() for pathPath, pathItem in arr: if pathPath in openapi3.paths: openapi3.paths[pathPath].merge(pathItem) else: openapi3.paths[pathPath] = pathItem print(yaml.dump(openapi3, default_flow_style=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 literal_unicode_representer(dumper, data): """ Use |- literal syntax for long strings """
if '\n' in data: return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|') else: return dumper.represent_scalar(u'tag:yaml.org,2002:str', 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 wrap_job_cursor(func_, *args, **kwargs): """ wraps a filter generator. Types should be appropriate before passed to rethinkdb somewhat specific to the _jobs_cursor function :param func_: <callable function> :param args: <must have at least 3 arguments> :param kwargs: :return: returned value from func_ """
assert isinstance(args[0], str) assert isinstance(args[1], (str, type(None))) assert isinstance(args[2], (str, type(None))) if args[2] and not args[1]: raise ValueError("Must specify location if using port.") return func_(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qurl(url, add=None, exclude=None, remove=None): """ Returns the url with changed parameters """
urlp = list(urlparse(url)) qp = parse_qsl(urlp[4]) # Add parameters add = add if add else {} for name, value in add.items(): if isinstance(value, (list, tuple)): # Append mode value = [smart_str(v) for v in value] qp = [p for p in qp if p[0] != name or p[1] not in value] qp.extend([(name, smart_str(val)) for val in value]) else: # Set mode qp = [p for p in qp if p[0] != name] qp.append((name, smart_str(value))) # Exclude parameters exclude = exclude if exclude else {} for name, value in exclude.items(): if not isinstance(value, (list, tuple)): value = [value] value = [smart_str(v) for v in value] qp = [p for p in qp if p[0] != name or p[1] not in value] # Remove parameters remove = remove if remove else [] for name in remove: qp = [p for p in qp if p[0] != name] urlp[4] = urlencode(qp, True) return urlunparse(urlp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clip_adaptor(read, adaptor): """ Clip an adaptor sequence from this sequence. We assume it's in the 3' end. This is basically a convenience wrapper for clipThreePrime. It requires 8 out of 10 of the first bases in the adaptor sequence to match for clipping to occur. :param adaptor: sequence to look for. We only use the first 10 bases; must be a full Sequence object, not just a string. """
missmatches = 2 adaptor = adaptor.truncate(10) read.clip_end(adaptor, len(adaptor) - missmatches)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains_adaptor(read, adaptor): """ Check whether this sequence contains adaptor contamination. If it exists, we assume it's in the 3' end. This function requires 8 out of 10 of the first bases in the adaptor sequence to match for an occurrence to be reported. :param adaptor: sequence to look for. We only use first 10 bases; must be a full Sequence object, not just string. :return: True if there is an occurence of <adaptor>, False otherwise """
origSeq = read.sequenceData clip_adaptor(read, adaptor) res = False if read.sequenceData != origSeq: res = True read.sequenceData = origSeq 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 reverse_complement(self, is_RNA=None): """ Reverse complement this read in-place. """
Sequence.reverseComplement(self, is_RNA) self.seq_qual = self.seq_qual[::-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 split(self, point=None): """ Split this read into two halves. Original sequence is left unaltered. The name of the resultant reads will have '.1' and '.2' appended to the name from the original read. :param point: the point (index, starting from 0) at which to split this read -- everything before this index will be placed into the first sequence, and everything at or after this index will be placed in the second resultant sequence. If None (the default), then we split in the middle; if the original size is not a multiple of 2, the extra nucleotide is placed into the second resultant sequence. Must be >= 0 and <= length of sequence. :return: two NGSRead objects which correspond to the split of this sequence. """
if point is None: point = len(self) / 2 if point < 0: raise NGSReadError("Cannot split read at index less than 0 " + "(index provided: " + str(point) + ")") if point > len(self): raise NGSReadError("Cannot split read at index greater than read " + "length (index provided: " + str(point) + ")") r1 = NGSRead(self.sequenceData[:point], self.name + ".1", self.seq_qual[:point]) r2 = NGSRead(self.sequenceData[point:], self.name + ".2", self.seq_qual[point:]) return r1, r2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_slug_with_level(context, page, lang=None, fallback=True): """Display slug with level by language."""
if not lang: lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) if not page: return '' return {'content': page.slug_with_level(lang)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_get_pages_with_tag(parser, token): """ Return Pages with given tag Syntax:: {% get_pages_with_tag <tag name> as <varname> %} Example use: {% get_pages_with_tag "footer" as pages %} """
bits = token.split_contents() if 4 != len(bits): raise TemplateSyntaxError('%r expects 2 arguments' % bits[0]) if bits[-2] != 'as': raise TemplateSyntaxError( '%r expects "as" as the second last argument' % bits[0]) varname = bits[-1] tag = parser.compile_filter(bits[1]) varname = bits[-1] return GetPagesWithTagNode(tag, varname)
<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_year(name): """Removes year from input :param name: path to edit :return: inputs with no years """
for i in range(len( name) - 3): # last index is length - 3 - 1 = length - 4 if name[i: i + 4].isdigit(): name = name[:i] + name[i + 4:] return remove_year( name) # if there is a removal, start again return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_brackets(name): """Removes brackets form input :param name: path to fix :return: inputs with no brackets """
name = re.sub( r"([(\[]).*?([)\]])", r"\g<1>\g<2>", name ) # remove anything in between brackets brackets = "()[]{}" # list of brackets for bracket in brackets: name = name.replace(bracket, "") return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_name_max_chars(name, max_chars=64, blank=" "): """Extracts max chars in name truncated to nearest word :param name: path to edit :param max_chars: max chars of new name :param blank: char that represents the blank between words :return: Name edited to contain at most max_chars """
new_name = name.strip() if len(new_name) > max_chars: new_name = new_name[:max_chars] # get at most 64 chars if new_name.rfind(blank) > 0: new_name = new_name[:new_name.rfind(blank)] # nearest word return new_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parent_folder_name(file_path): """Finds parent folder of file :param file_path: path :return: Name of folder container """
return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-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 ls_dir(path, include_hidden=False): """Finds content of folder :param path: directory to get list of files and folders :param include_hidden: True iff include hidden files in list :return: List of paths in given directory """
lst = [] for file in os.listdir(path): hidden_file = FileSystem(file).is_hidden() if (hidden_file and include_hidden) or (not hidden_file): lst.append(os.path.join(path, file)) return list(set(lst))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ls_recurse(path, include_hidden=False): """Finds content of folder recursively :param path: directory to get list of files and folders :param include_hidden: True iff include hidden files in list :return: List of paths in given directory recursively """
lst = [] for file in os.listdir(path): hidden_file = FileSystem(file).is_hidden() if (hidden_file and include_hidden) or (not hidden_file): lst.append(os.path.join(path, file)) if is_folder(os.path.join(path, file)): lst += ls_recurse( os.path.join(path, file), include_hidden=include_hidden ) # get list of files in directory return list(set(lst))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_russian(self): """Checks if file path is russian :return: True iff document has a russian name """
russian_chars = 0 for char in RUSSIAN_CHARS: if char in self.name: russian_chars += 1 # found a russian char return russian_chars > len(RUSSIAN_CHARS) / 2.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 rename(self, new_path): """Renames to new path :param new_path: new path to use """
rename_path = fix_raw_path(new_path) if is_folder(self.path): os.rename(self.path, rename_path) else: os.renames(self.path, rename_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setClass(self, factoryclass): """Sets the constructor for the component type this label is to represent :param factoryclass: a class that, when called, results in an instance of the desired class :type factoryclass: callable """
self.factoryclass = factoryclass self.setText(str(factoryclass.name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getLabel(self, key): """Gets the label assigned to an axes :param key:??? :type key: str """
axisItem = self.getPlotItem().axes[key]['item'] return axisItem.label.toPlainText()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateData(self, axeskey, x, y): """Replaces the currently displayed data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param x: index values associated with y to plot :type x: numpy.ndarray :param y: values to plot at x :type y: numpy.ndarray """
if axeskey == 'stim': self.stimPlot.setData(x,y) # call manually to ajust placement of signal ranges = self.viewRange() self.rangeChange(self, ranges) if axeskey == 'response': self.clearTraces() if self._traceUnit == 'A': y = y * self._ampScalar if self.zeroAction.isChecked(): start_avg = np.mean(y[5:25]) y = y - start_avg self.tracePlot.setData(x,y*self._polarity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def appendData(self, axeskey, bins, ypoints): """Appends data to existing plotted data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param bins: bins to plot a point for :type bin: numpy.ndarray :param ypoints: iteration number of raster, *should* match bins dimension, but really takes the first value in array for iteration number and plot row at proper place for included bins :type ypoints: numpy.ndarray """
if axeskey == 'raster' and len(bins) > 0: x, y = self.rasterPlot.getData() # don't plot overlapping points bins = np.unique(bins) # adjust repetition number to response scale ypoints = np.ones_like(bins)*self.rasterYslots[ypoints[0]] x = np.append(x, bins) y = np.append(y, ypoints) self.rasterPlot.setData(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setThreshold(self, threshold): """Sets the current threshold :param threshold: the y value to set the threshold line at :type threshold: float """
self.threshLine.setValue(threshold) self.threshold_field.setValue(threshold)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setRasterBounds(self, lims): """Sets the raster plot y-axis bounds, where in the plot the raster will appear between :param lims: the (min, max) y-values for the raster plot to be placed between :type lims: (float, float) """
self.rasterBottom = lims[0] self.rasterTop = lims[1] self.updateRasterBounds()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateRasterBounds(self): """Updates the y-coordinate slots where the raster points are plotted, according to the current limits of the y-axis"""
yrange = self.viewRange()[1] yrange_size = yrange[1] - yrange[0] rmax = self.rasterTop*yrange_size + yrange[0] rmin = self.rasterBottom*yrange_size + yrange[0] self.rasterYslots = np.linspace(rmin, rmax, self.nreps) self.rasterBoundsUpdated.emit((self.rasterBottom, self.rasterTop), self.getTitle())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def askRasterBounds(self): """Prompts the user to provide the raster bounds with a dialog. Saves the bounds to be applied to the plot"""
dlg = RasterBoundsDialog(bounds= (self.rasterBottom, self.rasterTop)) if dlg.exec_(): bounds = dlg.values() self.setRasterBounds(bounds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rangeChange(self, pw, ranges): """Adjusts the stimulus signal to keep it at the top of a plot, after any ajustment to the axes ranges takes place. This is a slot for the undocumented pyqtgraph signal sigRangeChanged. From what I can tell the arguments are: :param pw: reference to the emitting object (plot widget in my case) :type pw: object :param ranges: I am only interested when this turns out to be a nested list of axis bounds :type ranges: object """
if hasattr(ranges, '__iter__'): # adjust the stim signal so that it falls in the correct range yrange_size = ranges[1][1] - ranges[1][0] stim_x, stim_y = self.stimPlot.getData() if stim_y is not None: stim_height = yrange_size*STIM_HEIGHT # take it to 0 stim_y = stim_y - np.amin(stim_y) # normalize if np.amax(stim_y) != 0: stim_y = stim_y/np.amax(stim_y) # scale for new size stim_y = stim_y*stim_height # raise to right place in plot stim_y = stim_y + (ranges[1][1] - (stim_height*1.1 + (stim_height*0.2))) self.stimPlot.setData(stim_x, stim_y) # rmax = self.rasterTop*yrange_size + ranges[1][0] # rmin = self.rasterBottom*yrange_size + ranges[1][0] self.updateRasterBounds()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_thresh(self): """Emits a Qt signal thresholdUpdated with the current threshold value"""
thresh_val = self.threshLine.value() self.threshold_field.setValue(thresh_val) self.thresholdUpdated.emit(thresh_val, self.getTitle())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateImage(self, imgdata, xaxis=None, yaxis=None): """Updates the Widget image directly. :type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageItem.setImage` :param xaxis: x-axis values, length should match dimension 1 of imgdata :param yaxis: y-axis values, length should match dimension 0 of imgdata """
imgdata = imgdata.T self.img.setImage(imgdata) if xaxis is not None and yaxis is not None: xscale = 1.0/(imgdata.shape[0]/xaxis[-1]) yscale = 1.0/(imgdata.shape[1]/yaxis[-1]) self.resetScale() self.img.scale(xscale, yscale) self.imgScale = (xscale, yscale) self.imageArray = np.fliplr(imgdata) self.updateColormap()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resetScale(self): """Resets the scale on this image. Correctly aligns time scale, undoes manual scaling"""
self.img.scale(1./self.imgScale[0], 1./self.imgScale[1]) self.imgScale = (1.,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 updateData(self, signal, fs): """Displays a spectrogram of the provided signal :param signal: 1-D signal of audio :type signal: numpy.ndarray :param fs: samplerate of signal :type fs: int """
# use a separate thread to calculate spectrogram so UI doesn't lag t = threading.Thread(target=_doSpectrogram, args=(self.spec_done, (fs, signal),), kwargs=self.specgramArgs) t.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setSpecArgs(**kwargs): """Sets optional arguments for the spectrogram appearance. Available options: :param nfft: size of FFT window to use :type nfft: int :param overlap: percent overlap of window :type overlap: number :param window: Type of window to use, choices are hanning, hamming, blackman, bartlett or none (rectangular) :type window: string :param colormap: Gets set by colormap editor. Holds the information to generate the colormap. Items: :meth:`lut<pyqtgraph:pyqtgraph.ImageItem.setLookupTable>`, :meth:`levels<pyqtgraph:pyqtgraph.ImageItem.setLevels>`, state (info for editor) :type colormap: dict """
for key, value in kwargs.items(): if key == 'colormap': SpecWidget.imgArgs['lut'] = value['lut'] SpecWidget.imgArgs['levels'] = value['levels'] SpecWidget.imgArgs['state'] = value['state'] for w in SpecWidget.instances: w.updateColormap() else: SpecWidget.specgramArgs[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 clearImg(self): """Clears the current image"""
self.img.setImage(np.array([[0]])) self.img.image = 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 editColormap(self): """Prompts the user with a dialog to change colormap"""
self.editor = pg.ImageView() # remove the ROI and Norm buttons self.editor.ui.roiBtn.setVisible(False) self.editor.ui.menuBtn.setVisible(False) self.editor.setImage(self.imageArray) if self.imgArgs['state'] is not None: self.editor.getHistogramWidget().item.gradient.restoreState(self.imgArgs['state']) self.editor.getHistogramWidget().item.setLevels(*self.imgArgs['levels']) self.editor.closeEvent = self._editor_close self.editor.setWindowModality(QtCore.Qt.ApplicationModal) self.editor.show()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateColormap(self): """Updates the currently colormap accoring to stored settings"""
if self.imgArgs['lut'] is not None: self.img.setLookupTable(self.imgArgs['lut']) self.img.setLevels(self.imgArgs['levels'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def appendData(self, xdata, ydata, color='b', legendstr=None): """Adds the data to the plot :param xdata: index values for data, plotted on x-axis :type xdata: numpy.ndarray :param ydata: value data to plot, dimension must match xdata :type ydata: numpy.ndarray """
item = self.plot(xdata, ydata, pen=color) if legendstr is not None: self.legend.addItem(item, legendstr) return 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 setLabels(self, xlabel=None, ylabel=None, title=None, xunits=None, yunits=None): """Sets the plot labels :param xlabel: X-axis label (do not include units) :type xlabel: str :param ylabel: Y-axis label (do not include units) :type ylabel: str :param title: Plot title :type title: str :param xunit: SI units for the x-axis. An appropriate label will be appended according to scale :type xunit: str :param yunit: SI units for the y-axis. An appropriate label will be appended according to scale :type yunit: str """
if xlabel is not None: self.setLabel('bottom', xlabel, units=xunits) if ylabel is not None: self.setLabel('left', ylabel, units=yunits) if title is not None: self.setTitle(title)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setPoint(self, x, group, y): """Sets the given point, connects line to previous point in group :param x: x value of point :type x: float :param group: group which plot point for :type group: float :param y: y value of point :type y: float """
if x == -1: # silence window self.plot([0],[y], symbol='o') else: yindex = self.groups.index(group) xdata, ydata = self.lines[yindex].getData() if ydata is None: xdata = [x] ydata = [y] else: xdata = np.append(xdata, x) ydata = np.append(ydata, y) self.lines[yindex].setData(xdata, ydata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setLabels(self, name): """Sets plot labels, according to predefined options :param name: The type of plot to create labels for. Options: calibration, tuning, anything else labels for spike counts :type name: str """
if name == "calibration": self.setWindowTitle("Calibration Curve") self.setTitle("Calibration Curve") self.setLabel('bottom', "Frequency", units='Hz') self.setLabel('left', 'Recorded Intensity (dB SPL)') elif name == "tuning": self.setWindowTitle("Tuning Curve") self.setTitle("Tuning Curve") self.setLabel('bottom', "Frequency", units="Hz") self.setLabel('left', "Spike Count (mean)") else: self.setWindowTitle("Spike Counts") self.setTitle("Spike Counts") self.setLabel('bottom', "Test Number", units='') self.setLabel('left', "Spike Count (mean)", units='')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadCurve(data, groups, thresholds, absvals, fs, xlabels): """Accepts a data set from a whole test, averages reps and re-creates the progress plot as the same as it was during live plotting. Number of thresholds must match the size of the channel dimension"""
xlims = (xlabels[0], xlabels[-1]) pw = ProgressWidget(groups, xlims) spike_counts = [] # skip control for itrace in range(data.shape[0]): count = 0 for ichan in range(data.shape[2]): flat_reps = data[itrace,:,ichan,:].flatten() count += len(spikestats.spike_times(flat_reps, thresholds[ichan], fs, absvals[ichan])) spike_counts.append(count/(data.shape[1]*data.shape[2])) #mean spikes per rep i = 0 for g in groups: for x in xlabels: pw.setPoint(x, g, spike_counts[i]) i +=1 return pw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def processData(self, times, response, test_num, trace_num, rep_num): """Calulate spike times from raw response data"""
# invert polarity affects spike counting response = response * self._polarity if rep_num == 0: # reset self.spike_counts = [] self.spike_latencies = [] self.spike_rates = [] fs = 1./(times[1] - times[0]) # process response; calculate spike times spike_times = spikestats.spike_times(response, self._threshold, fs) self.spike_counts.append(len(spike_times)) if len(spike_times) > 0: self.spike_latencies.append(spike_times[0]) else: self.spike_latencies.append(np.nan) self.spike_rates.append(spikestats.firing_rate(spike_times, times)) binsz = self._bins[1] - self._bins[0] response_bins = spikestats.bin_spikes(spike_times, binsz) # self.putnotify('spikes_found', (response_bins, rep_num)) self.appendData(response_bins, rep_num)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setSr(self, fs): """Sets the samplerate of the input operation being plotted"""
self.tracePlot.setSr(fs) self.stimPlot.setSr(fs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setWindowSize(self, winsz): """Sets the size of scroll window"""
self.tracePlot.setWindowSize(winsz) self.stimPlot.setWindowSize(winsz)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addSpectrogram(self, ydata, fs, title=None): """Adds a new spectorgram plot for the given image. Generates a SpecWidget :param ydata: 2-D array of the image to display :type ydata: numpy.ndarray :param fs: the samplerate of the signal in the image, used to set time/ frequency scale :type fs: int :param title: Plot title :type title: str """
p = SpecWidget() p.updateData(ydata, fs) if title is not None: p.setTitle(title) self.stacker.addWidget(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 nextPlot(self): """Moves the displayed plot to the next one"""
if self.stacker.currentIndex() < self.stacker.count(): self.stacker.setCurrentIndex(self.stacker.currentIndex()+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 prevPlot(self): """Moves the displayed plot to the previous one"""
if self.stacker.currentIndex() > 0: self.stacker.setCurrentIndex(self.stacker.currentIndex()-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 most_even_chunk(string, group): """Divide a string into a list of strings as even as possible."""
counts = [0] + most_even(len(string), group) indices = accumulate(counts) slices = window(indices, 2) return [string[slice(*one)] for one in slices]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def most_even(number, group): """Divide a number into a list of numbers as even as possible."""
count, rest = divmod(number, group) counts = zip_longest([count] * group, [1] * rest, fillvalue=0) chunks = [sum(one) for one in counts] logging.debug('chunks: %s', chunks) return chunks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def window(seq, count=2): """Slide window."""
iseq = iter(seq) result = tuple(islice(iseq, count)) if len(result) == count: yield result for elem in iseq: result = result[1:] + (elem,) yield result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_modules(path): """Finds modules in folder recursively :param path: directory :return: list of modules """
lst = [] folder_contents = os.listdir(path) is_python_module = "__init__.py" in folder_contents if is_python_module: for file in folder_contents: full_path = os.path.join(path, file) if is_file(full_path): lst.append(full_path) if is_folder(full_path): lst += _get_modules(full_path) # recurse in folder return list(set(lst))
<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(self): """Parses file contents :return: Tree hierarchy of file """
with open(self.path, "rt") as reader: return ast.parse(reader.read(), filename=self.path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_package(self, root_package): """Finds package name of file :param root_package: root package :return: package name """
package = self.path.replace(root_package, "") if package.endswith(".py"): package = package[:-3] package = package.replace(os.path.sep, MODULE_SEP) root_package = get_folder_name(root_package) package = root_package + package # add root return package
<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_instances(self, instance): """Finds all instances of instance in tree :param instance: type of object :return: list of objects in tree of same instance """
return [ x for x in self.tree.body if isinstance(x, 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 get_classes(self): """Finds classes in file :return: list of top-level classes """
instances = self._get_instances(ast.ClassDef) instances = [ PyClass(instance, self.package) for instance in instances ] return instances
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def best_assemblyfile(self): """ Determine whether the contigs.fasta output file from the assembler is present. If not, set the .bestassembly attribute to 'NA' """
for sample in self.metadata: try: # Set the name of the filtered assembly file filtered_outputfile = os.path.join(self.path, 'raw_assemblies', '{}.fasta'.format(sample.name)) # Set the name of the unfiltered spades assembly output file if os.path.isfile(sample.general.assemblyfile): size = os.path.getsize(sample.general.assemblyfile) # Ensure that the assembly isn't just an empty file if size == 0: sample.general.bestassemblyfile = 'NA' else: sample.general.bestassemblyfile = sample.general.assemblyfile shutil.copyfile(sample.general.bestassemblyfile, filtered_outputfile) else: sample.general.bestassemblyfile = 'NA' # Add the name and path of the filtered file to the metadata sample.general.filteredfile = filtered_outputfile except AttributeError: sample.general.assemblyfile = 'NA' sample.general.bestassemblyfile = 'NA'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, group_id=None, **kwargs): """Get component groups :param group_id: Component group ID (optional) :return: Component groups data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-componentgroups .. seealso:: https://docs.cachethq.io/docs/advanced-api-usage """
path = 'components/groups' if group_id is not None: path += '/%s' % group_id return self.paginate_get(path, data=kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, name, order=None, collapsed=None): """Create a new Component Group :param str name: Name of the component group :param int order: Order of the component group :param int collapsed: Collapse the group? 0-2 :return: Created component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-componentgroups """
data = ApiParams() data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._post('components/groups', data=data)['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 update(self, group_id, name=None, order=None, collapsed=None): """Update a Component Group :param int group_id: Component Group ID :param str name: Name of the component group :param int order: Order of the group :param int collapsed: Collapse the group? :return: Updated component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#put-component-group """
data = ApiParams() data['group'] = group_id data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._put('components/groups/%s' % group_id, data=data)['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 create(self, name, message, status, visible, component_id=None, component_status=None, notify=None, created_at=None, template=None, tplvars=None): """Create a new Incident :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tplvars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#incidents """
data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tplvars return self._post('incidents', data=data)['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 update(self, incident_id, name=None, message=None, status=None, visible=None, component_id=None, component_status=None, notify=None, created_at=None, template=None, tpl_vars=None): """Update an Incident :param int incident_id: Incident ID :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int component_status: The status to update the given component :param bool notify: Whether to notify subscribers :param str created_at: When the incident was created :param str template: The template slug to use :param list tpl_vars: The variables to pass to the template :return: Created incident data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#update-an-incident """
data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visible'] = visible data['component_id'] = component_id data['component_status'] = component_status data['notify'] = notify data['created_at'] = created_at data['template'] = template data['vars'] = tpl_vars return self._put('incidents/%s' % incident_id, data=data)['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 create(self, name, suffix, description, default_value, display=None): """Create a new Metric :param str name: Name of metric :param str suffix: Metric unit :param str description: Description of what the metric is measuring :param int default_value: Default value to use when a point is added :param int display: Display the chart on the status page :return: Created metric data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#metrics """
data = ApiParams() data['name'] = name data['suffix'] = suffix data['description'] = description data['default_value'] = default_value data['display'] = display return self._post('metrics', data=data)['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 create(self, metric_id, value, timestamp=None): """Add a Metric Point to a Metric :param int metric_id: Metric ID :param int value: Value to plot on the metric graph :param str timestamp: Unix timestamp of the point was measured :return: Created metric point data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-metric-points """
data = ApiParams() data['value'] = value data['timestamp'] = timestamp return self._post('metrics/%s/points' % metric_id, data=data)['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 create(self, email, verify=None, components=None): """Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#subscribers """
data = ApiParams() data['email'] = email data['verify'] = verify data['components'] = components return self._post('subscribers', data=data)['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 annotatedcore(self): """ Calculates the core genome of organisms using custom databases """
logging.info('Calculating annotated core') # Determine the total number of core genes self.total_core() # Iterate through all the samples, and process all Escherichia for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': # Create a set to store the names of all the core genes in this strain sample[self.analysistype].coreset = set() if sample.general.referencegenus == 'Escherichia': # Add the Escherichia sample to the runmetadata self.runmetadata.samples.append(sample) # Parse the BLAST report try: report = sample[self.analysistype].report self.blastparser(report=report, sample=sample, fieldnames=self.fieldnames) except KeyError: sample[self.analysistype].coreset = list() # Create the report self.reporter()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def total_core(self): """ Determine the total number of core genes present """
corefile = os.path.join(self.reffilepath, self.analysistype, 'Escherichia', 'core_combined.fasta') for record in SeqIO.parse(corefile, 'fasta'): gene_name = record.id.split('-')[0] if gene_name not in self.coregenomes: self.coregenomes.append(gene_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_simple_output(self, stderr=STDOUT): """Executes a simple external command and get its output The command contains no pipes. Error messages are redirected to the standard output by default :param stderr: where to put stderr :return: output of command """
args = shlex.split(self.cmd) proc = Popen(args, stdout=PIPE, stderr=stderr) return proc.communicate()[0].decode("utf8")
<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_complex_output(self, stderr=STDOUT): """Executes a piped command and get the lines of the output in a list :param stderr: where to put stderr :return: output of command """
proc = Popen(self.cmd, shell=True, stdout=PIPE, stderr=stderr) return proc.stdout.readlines()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keep_alive(self): """Keeps a process alive. If the process terminates, it will restart it The terminated processes become zombies. They die when their parent terminates """
while True: pid = self.execute_in_background() p = psutil.Process(pid) while p.is_running() and str(p.status) != 'zombie': os.system('sleep 5')