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 add_config(): """ Prompts user for API keys, adds them in an .ini file stored in the same location as that of the script """
genius_key = input('Enter Genius key : ') bing_key = input('Enter Bing key : ') CONFIG['keys']['bing_key'] = bing_key CONFIG['keys']['genius_key'] = genius_key with open(config_path, 'w') as configfile: CONFIG.write(configfile)
<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_tracks_from_album(album_name): ''' Gets tracks from an album using Spotify's API ''' spotify = spotipy.Spotify() album = spotify.search(q='album:' + album_name, limit=1) album_id = album['tracks']['items'][0]['album']['id'] results = spotify.album_tracks(album_id=str(album_id)) ...
<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_url(song_input, auto): ''' Provides user with a list of songs to choose from returns the url of chosen song. ''' youtube_list = OrderedDict() num = 0 # List of songs index html = requests.get("https://www.youtube.com/results", params={'search_query': song_in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def prompt(youtube_list): ''' Prompts for song number from list of songs ''' option = int(input('\nEnter song number > ')) try: song_url = list(youtube_list.values())[option - 1] song_title = list(youtube_list.keys())[option - 1] except IndexError: log.log_error('Invalid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def main(): ''' Starts here, handles arguments ''' system('clear') # Must be system('cls') for windows setup() parser = argparse.ArgumentParser( description='Download songs with album art and metadata!') parser.add_argument('-c', '--config', action='store_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 getRawReportDescriptor(self): """ Return a binary string containing the raw HID report descriptor. """
descriptor = _hidraw_report_descriptor() size = ctypes.c_uint() self._ioctl(_HIDIOCGRDESCSIZE, size, True) descriptor.size = size self._ioctl(_HIDIOCGRDESC, descriptor, True) return ''.join(chr(x) for x in descriptor.value[:size.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 getName(self, length=512): """ Returns device name as an unicode object. """
name = ctypes.create_string_buffer(length) self._ioctl(_HIDIOCGRAWNAME(length), name, True) return name.value.decode('UTF-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPhysicalAddress(self, length=512): """ Returns device physical address as a string. See hidraw documentation for value signification, as it depends on dev...
name = ctypes.create_string_buffer(length) self._ioctl(_HIDIOCGRAWPHYS(length), name, True) return 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 sendFeatureReport(self, report, report_num=0): """ Send a feature report. """
length = len(report) + 1 buf = bytearray(length) buf[0] = report_num buf[1:] = report self._ioctl( _HIDIOCSFEATURE(length), (ctypes.c_char * length).from_buffer(buf), 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 every(coro, iterable, limit=1, loop=None): """ Returns `True` if every element in a given iterable satisfies the coroutine asynchronous test. If any iteratee...
assert_corofunction(coro=coro) assert_iter(iterable=iterable) # Reduced accumulator value passes = True # Handle empty iterables if len(iterable) == 0: return passes # Create concurrent executor pool = ConcurrentExecutor(limit=limit, loop=loop) # Tester function to guara...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gather(*coros_or_futures, limit=0, loop=None, timeout=None, preserve_order=False, return_exceptions=False): """ Return a future aggregating results from the ...
# If no coroutines to schedule, return empty list (as Python stdlib) if len(coros_or_futures) == 0: return [] # Support iterable as first argument for better interoperability if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): coros_or_futures = coros_or_futures[0] # Pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timeout(coro, timeout=None, loop=None): """ Wraps a given coroutine function, that when executed, if it takes more than the given timeout in seconds to execu...
@asyncio.coroutine def _timeout(coro): return (yield from asyncio.wait_for(coro, timeout, loop=loop)) @asyncio.coroutine def wrapper(*args, **kw): return (yield from _timeout(coro(*args, **kw))) return _timeout(coro) if asyncio.iscoroutine(coro) else 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 race(iterable, loop=None, timeout=None, *args, **kw): """ Runs coroutines from a given iterable concurrently without waiting until the previous one has compl...
assert_iter(iterable=iterable) # Store coros and internal state coros = [] resolved = False result = None # Resolve first yielded data from coroutine and stop pending ones @asyncio.coroutine def resolver(index, coro): nonlocal result nonlocal resolved 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 overload(fn): """ Overload a given callable object to be used with ``|`` operator overloading. This is especially used for composing a pipeline of transforma...
if not isfunction(fn): raise TypeError('paco: fn must be a callable object') spec = getargspec(fn) args = spec.args if not spec.varargs and (len(args) < 2 or args[1] != 'iterable'): raise ValueError('paco: invalid function signature or arity') @functools.wraps(fn) def decorato...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume(generator): # pragma: no cover """ Helper function to consume a synchronous or asynchronous generator. Arguments: generator (generator|asyncgenerator...
# If synchronous generator, just consume and return as list if hasattr(generator, '__next__'): return list(generator) if not PY_35: raise RuntimeError( 'paco: asynchronous iterator protocol not supported') # If asynchronous generator, consume it generator protocol manually...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isfunc(x): """ Returns `True` if the given value is a function or method object. Arguments: x (mixed): value to check. Returns: bool """
return any([ inspect.isfunction(x) and not asyncio.iscoroutinefunction(x), inspect.ismethod(x) and not asyncio.iscoroutinefunction(x) ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_corofunction(**kw): """ Asserts if a given values are a coroutine function. Arguments: **kw (mixed): value to check if it is an iterable. Raises: Typ...
for name, value in kw.items(): if not asyncio.iscoroutinefunction(value): raise TypeError( 'paco: {} must be a coroutine function'.format(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 assert_iter(**kw): """ Asserts if a given values implements a valid iterable interface. Arguments: **kw (mixed): value to check if it is an iterable. Raises...
for name, value in kw.items(): if not isiter(value): raise TypeError( 'paco: {} must be an iterable object'.format(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 interval(coro, interval=1, times=None, loop=None): """ Schedules the execution of a coroutine function every `x` amount of seconds. The function returns an `...
assert_corofunction(coro=coro) # Store maximum allowed number of calls times = int(times or 0) or float('inf') @asyncio.coroutine def schedule(times, *args, **kw): while times > 0: # Decrement times counter times -= 1 # Schedule coroutine 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 addRule(self, doc, func, _preprocess=True): """Add a grammar rules to _self.rules_, _self.rule2func_, and _self.rule2name_ Comments, lines starting with # an...
fn = func # remove blanks lines and comment lines, e.g. lines starting with "#" doc = os.linesep.join([s for s in doc.splitlines() if s and not re.match("^\s*#", s)]) rules = doc.split() index = [] for i in range(len(rules)): if rules[i] == '::=': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_rules(self, doc): """Remove a grammar rules from _self.rules_, _self.rule2func_, and _self.rule2name_ """
# remove blanks lines and comment lines, e.g. lines starting with "#" doc = os.linesep.join([s for s in doc.splitlines() if s and not re.match("^\s*#", s)]) rules = doc.split() index = [] for i in range(len(rules)): if rules[i] == '::=': index.append...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def errorstack(self, tokens, i, full=False): """Show the stacks of completed symbols. We get this by inspecting the current transitions possible and from that ex...
print("\n-- Stacks of completed symbols:") states = [s for s in self.edges.values() if s] # States now has the set of states we are in state_stack = set() for state in states: # Find rules which can follow, but keep only # the part before the dot ...
<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, tokens, debug=None): """This is the main entry point from outside. Passing in a debug dictionary changes the default debug setting. """
self.tokens = tokens if debug: self.debug = debug sets = [ [(1, 0), (2, 0)] ] self.links = {} if self.ruleschanged: self.computeNull() self.newrules = {} self.new2old = {} self.makeNewRules() self.rulesc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_grammar(self, out=sys.stdout): """ Print grammar rules """
for rule in sorted(self.rule2name.items()): out.write("%s\n" % rule2str(rule[0])) 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 profile_rule(self, rule): """Bump count of the number of times _rule_ was used"""
rule_str = self.reduce_string(rule) if rule_str not in self.profile_info: self.profile_info[rule_str] = 1 else: self.profile_info[rule_str] += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_profile_info(self): """Show the accumulated results of how many times each rule was used"""
return sorted(self.profile_info.items(), key=lambda kv: kv[1], reverse=False) 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 partial(coro, *args, **kw): """ Partial function implementation designed for coroutines, allowing variadic input arguments. This function can be used as deco...
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(*_args, **_kw): call_args = args + _args kw.update(_kw) return (yield from coro(*call_args, **kw)) 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 eval_expr(expr_str, show_tokens=False, showast=False, showgrammar=False, compile_mode='exec'): """ evaluate simple expression """
parser_debug = {'rules': False, 'transition': False, 'reduce': showgrammar, 'errorstack': True, 'context': True } parsed = parse_expr(expr_str, show_tokens=show_tokens, parser_debug=parser_debug) if showast: print(parsed) assert ...
<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(): """ Gathers all configs """
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR LOG_FILENAME = 'musicrepair_log.txt' LOG_LINE_SEPERATOR = '........................\n' CONFIG = configparser.ConfigParser() config_path = realpath(__file__).replace(basename(__file__),'') config_path = 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 matching_details(song_name, song_title, artist): ''' Provides a score out of 10 that determines the relevance of the search result ''' match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio() match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio(...
<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_lyrics_letssingit(song_name): ''' Scrapes the lyrics of a song since spotify does not provide lyrics takes song title as arguement ''' lyrics = "" url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html =...
<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_details_letssingit(song_name): ''' Gets the song details if song details not found through spotify ''' song_name = improvename.songname(song_name) url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html = ur...
<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_albumart(albumart, song_title): ''' Adds the album art to the song ''' try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: ...
<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_details(file_name, title, artist, album, lyrics=""): ''' Adds the details to song ''' tags = EasyMP3(file_name) tags["title"] = title tags["artist"] = artist tags["album"] = album tags.save() tags = ID3(file_name) uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc'...
<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(coro, iterable, limit=0, loop=None, timeout=None, return_exceptions=False, *args, **kw): """ Concurrently maps values yielded from an iterable, passing t...
# Call each iterable but collecting yielded values return (yield from each(coro, iterable, limit=limit, loop=loop, timeout=timeout, collect=True, return_exceptions=return_exceptions))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def img_search_bing(album): ''' Bing image search ''' setup() album = album + " Album Art" api_key = "Key" endpoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search" links_dict = {} headers = {'Ocp-Apim-Subscription-Key': str(BING_KEY)} param = {'q': album, 'count': '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 decorate(fn): """ Generic decorator for coroutines helper functions allowing multiple variadic initialization arguments. This function is intended to be used...
if not isfunction(fn): raise TypeError('paco: fn must be a callable object') @functools.wraps(fn) def decorator(*args, **kw): # If coroutine object is passed for arg in args: if iscoro_or_corofunc(arg): return fn(*args, **kw) # Explicit argument...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def throttle(coro, limit=1, timeframe=1, return_value=None, raise_exception=False): """ Creates a throttled coroutine function that only invokes ``coro`` at most...
assert_corofunction(coro=coro) # Store execution limits limit = max(int(limit), 1) remaning = limit # Turn seconds in milliseconds timeframe = timeframe * 1000 # Keep call state last_call = now() # Cache latest retuned result result = None def stop(): if raise_ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def whilst(coro, coro_test, assert_coro=None, *args, **kw): """ Repeatedly call `coro` coroutine function while `coro_test` returns `True`. This function is the ...
assert_corofunction(coro=coro, coro_test=coro_test) # Store yielded values by coroutine results = [] # Set assertion coroutine assert_coro = assert_coro or assert_true # Execute coroutine until a certain while (yield from assert_coro((yield from coro_test()))): results.append((yi...
<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_csv(ctx, model, path, header=None, header_exclude=None, **fmtparams): """Load a CSV from a file path. :param ctx: Anthem context :param model: Odoo mode...
if not os.path.isabs(path): if ctx.options.odoo_data_path: path = os.path.join(ctx.options.odoo_data_path, path) else: raise AnthemError( 'Got a relative path. ' 'Please, provide a value for `ODOO_DATA_PATH` ' 'in your environm...
<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_csv_stream(ctx, model, data, header=None, header_exclude=None, **fmtparams): """Load a CSV from a stream. :param ctx: current anthem context :param mode...
_header, _rows = read_csv(data, **fmtparams) header = header if header else _header if _rows: # check if passed header contains all the fields if header != _header and not header_exclude: # if not, we exclude the rest of the fields header_exclude = [x for x in _heade...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_python2_stmts(python_stmts, show_tokens=False, showast=False, showgrammar=False, compile_mode='exec'): """ formats python2 statements """
parser_debug = {'rules': False, 'transition': False, 'reduce': showgrammar, 'errorstack': True, 'context': True, 'dups': True } parsed = parse_python2(python_stmts, show_tokens=show_tokens, parser_debug=parser_debug) assert parsed == '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 songname(song_name): ''' Improves file name by removing crap words ''' try: song_name = splitext(song_name)[0] except IndexError: pass # Words to omit from song title for better results through spotify's API chars_filter = "()[]{}-:_/=+\"\'" words_filter = ('official...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def document(info=None, input=None, output=None): """ Add extra information about request handler and its params """
def wrapper(func): if info is not None: setattr(func, "_swg_info", info) if input is not None: setattr(func, "_swg_input", input) if output is not None: setattr(func, "_swg_output", output) return func 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 thunk(coro): """ A thunk is a subroutine that is created, often automatically, to assist a call to another subroutine. Creates a thunk coroutine which return...
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(): return (yield from coro()) 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 reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None): """ Apply function of two arguments cumulatively to the items of sequence, from le...
assert_corofunction(coro=coro) assert_iter(iterable=iterable) # Reduced accumulator value acc = initializer # If interable is empty, just return the initializer value if len(iterable) == 0: return initializer # Create concurrent executor pool = ConcurrentExecutor(limit=limit,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def times(coro, limit=1, raise_exception=False, return_value=None): """ Wraps a given coroutine function to be executed only a certain amount of times. If the ex...
assert_corofunction(coro=coro) # Store call times limit = max(limit, 1) times = limit # Store result from last execution result = None @asyncio.coroutine def wrapper(*args, **kw): nonlocal limit nonlocal result # Check execution limit if limit == 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 log(func=None, name=None, timing=True, timestamp=False): """ Decorator to show a description of the running function By default, it outputs the first line of...
# support to be called as @log or as @log(name='') if func is None: return functools.partial(log, name=name, timing=timing, timestamp=timestamp) @functools.wraps(func) def decorated(*args, **kwargs): assert len(args) > 0 and hasattr(args[0], '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 constant(value, delay=None): """ Returns a coroutine function that when called, always returns the provided value. This function has an alias: `paco.identity...
@asyncio.coroutine def coro(): if delay: yield from asyncio.sleep(delay) return value return coro
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dropwhile(coro, iterable, loop=None): """ Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every ...
drop = False @asyncio.coroutine def assert_fn(element): nonlocal drop if element and not drop: return False if not element and not drop: drop = True return True if drop else element @asyncio.coroutine def filter_fn(element): retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_xmlid(ctx, record, xmlid, noupdate=False): """ Add a XMLID on an existing record """
try: ref_id, __, __ = ctx.env['ir.model.data'].xmlid_lookup(xmlid) except ValueError: pass # does not exist, we'll create a new one else: return ctx.env['ir.model.data'].browse(ref_id) if '.' in xmlid: module, name = xmlid.split('.') else: module = '' ...
<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_or_update(ctx, model, xmlid, values): """ Create or update a record matching xmlid with values """
if isinstance(model, basestring): model = ctx.env[model] record = ctx.env.ref(xmlid, raise_if_not_found=False) if record: record.update(values) else: record = model.create(values) add_xmlid(ctx, record, xmlid) return record
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_record(ctx, item): """Make sure we get a record instance even if we pass an xmlid."""
if isinstance(item, basestring): return ctx.env.ref(item) 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 switch_company(ctx, company): """Context manager to switch current company. Accepts both company record and xmlid. """
current_company = ctx.env.user.company_id ctx.env.user.company_id = safe_record(ctx, company) yield ctx ctx.env.user.company_id = current_company
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(coro, *args, **kw): """ Creates a continuation coroutine function with some arguments already applied. Useful as a shorthand when combined with other c...
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(*_args, **_kw): # Explicitely ignore wrapper arguments return (yield from coro(*args, **kw)) 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 run(coro, loop=None): """ Convenient shortcut alias to ``loop.run_until_complete``. Arguments: coro (coroutine): coroutine object to schedule. loop (asyncio...
loop = loop or asyncio.get_event_loop() return loop.run_until_complete(coro)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(*coros_or_futures, limit=0, timeout=None, loop=None, return_exceptions=False, return_when='ALL_COMPLETED'): """ Wait for the Futures and coroutine objec...
# Support iterable as first argument for better interoperability if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): coros_or_futures = coros_or_futures[0] # If no coroutines to schedule, return empty list # Mimics asyncio behaviour. if len(coros_or_futures) == 0: raise ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def series(*coros_or_futures, timeout=None, loop=None, return_exceptions=False): """ Run the given coroutine functions in series, each one running once the previ...
return (yield from gather(*coros_or_futures, loop=loop, limit=1, timeout=timeout, return_exceptions=return_exceptions))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repeat(coro, times=1, step=1, limit=1, loop=None): """ Executes the coroutine function ``x`` number of times, and accumulates results in order as you would u...
assert_corofunction(coro=coro) # Iterate and attach coroutine for defer scheduling times = max(int(times), 1) iterable = range(1, times + 1, step) # Run iterable times return (yield from map(coro, iterable, limit=limit, loop=loop))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def once(coro, raise_exception=False, return_value=None): """ Wrap a given coroutine function that is restricted to one execution. Repeated calls to the coroutin...
return times(coro, limit=1, return_value=return_value, raise_exception=raise_exception)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defer(coro, delay=1): """ Returns a coroutine function wrapper that will defer the given coroutine execution for a certain amount of seconds in a non-blockin...
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(*args, **kw): # Wait until we're done yield from asyncio.sleep(delay) return (yield from coro(*args, **kw)) 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 safe_run(coro, return_exceptions=False): """ Executes a given coroutine and optionally catches exceptions, returning them as value. This function is intended...
try: result = yield from coro except Exception as err: if return_exceptions: result = err else: raise err 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 collect(coro, index, results, preserve_order=False, return_exceptions=False): """ Collect is used internally to execute coroutines and collect the returned v...
result = yield from safe_run(coro, return_exceptions=return_exceptions) if preserve_order: results[index] = result else: results.append(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 reset(self): """ Resets the executer scheduler internal state. Raises: RuntimeError: is the executor is still running. """
if self.running: raise RuntimeError('paco: executor is still running') self.pool.clear() self.observer.clear() self.semaphore = asyncio.Semaphore(self.limit, loop=self.loop)
<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(self, coro, *args, **kw): """ Adds a new coroutine function with optional variadic argumetns. Arguments: coro (coroutine function): coroutine to execute...
# Create coroutine object if a function is provided if asyncio.iscoroutinefunction(coro): coro = coro(*args, **kw) # Verify coroutine if not asyncio.iscoroutine(coro): raise TypeError('paco: coro must be a coroutine object') # Store coroutine with argum...
<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, timeout=None, return_when=None, return_exceptions=None, ignore_empty=None): """ Executes the registered coroutines in the executor queue. Arguments...
# Only allow 1 concurrent execution if self.running: raise RuntimeError('paco: executor is already running') # Overwrite ignore empty behaviour, if explicitly defined ignore_empty = (self.ignore_empty if ignore_empty is None else ignore_empty) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_interval(self, interval): """ Given a value of an interval, this function returns the next interval value """
index = np.where(self.intervals == interval) if index[0][0] + 1 < len(self.intervals): return self.intervals[index[0][0] + 1] else: raise IndexError("Ran out of intervals!")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nearest_interval(self, interval): """ This function returns the nearest interval to any given interval. """
thresh_range = 25 # in cents if interval < self.intervals[0] - thresh_range or interval > self.intervals[-1] + thresh_range: raise IndexError("The interval given is beyond " + str(thresh_range) + " cents over the range of intervals defined.") index = f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def brent_optimise(node1, node2, min_brlen=0.001, max_brlen=10, verbose=False): """ Optimise ML distance between two partials. min and max set brackets """
from scipy.optimize import minimize_scalar wrapper = BranchLengthOptimiser(node1, node2, (min_brlen + max_brlen) / 2.) n = minimize_scalar(lambda x: -wrapper(x)[0], method='brent', bracket=(min_brlen, max_brlen))['x'] if verbose: logger.info(wrapper) if n < min_brlen: n = min_brlen ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pairdists(alignment, subs_model, alpha=None, ncat=4, tolerance=1e-6, verbose=False): """ Load an alignment, calculate all pairwise distances and variances mo...
# Check if not isinstance(subs_model, phylo_utils.models.Model): raise ValueError("Can't handle this model: {}".format(model)) if alpha is None: alpha = 1.0 ncat = 1 # Set up markov model tm = TransitionMatrix(subs_model) gamma_rates = discrete_gamma(alpha, ncat) ...
<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_alignment(self, filename, file_format, interleaved=None): """ Write the alignment to file using Bio.AlignIO """
if file_format == 'phylip': file_format = 'phylip-relaxed' AlignIO.write(self._msa, filename, file_format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simulate(self, nsites, transition_matrix, tree, ncat=1, alpha=1): """ Return sequences simulated under the transition matrix's model """
sim = SequenceSimulator(transition_matrix, tree, ncat, alpha) return list(sim.simulate(nsites).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 bootstrap(self): """ Return a new Alignment that is a bootstrap replicate of self """
new_sites = sorted(sample_wr(self.get_sites())) seqs = list(zip(self.get_names(), (''.join(seq) for seq in zip(*new_sites)))) return self.__class__(seqs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simulate(self, n): """ Evolve multiple sites during one tree traversal """
self.tree._tree.seed_node.states = self.ancestral_states(n) categories = np.random.randint(self.ncat, size=n).astype(np.intc) for node in self.tree.preorder(skip_seed=True): node.states = self.evolve_states(node.parent_node.states, categories, node.pmats) if node.is_lea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ancestral_states(self, n): """ Generate ancestral sequence states from the equilibrium frequencies """
anc = np.empty(n, dtype=np.intc) _weighted_choices(self.state_indices, self.freqs, anc) return anc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sequences_to_string(self): """ Convert state indices to a string of characters """
return {k: ''.join(self.states[v]) for (k, v) in self.sequences.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 crc_srec(hexstr): """Calculate the CRC for given Motorola S-Record hexstring. """
crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc ^= 0xff return crc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crc_ihex(hexstr): """Calculate the CRC for given Intel HEX hexstring. """
crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc = ((~crc + 1) & 0xff) return crc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pack_srec(type_, address, size, data): """Create a Motorola S-Record record of given data. """
if type_ in '0159': line = '{:02X}{:04X}'.format(size + 2 + 1, address) elif type_ in '268': line = '{:02X}{:06X}'.format(size + 3 + 1, address) elif type_ in '37': line = '{:02X}{:08X}'.format(size + 4 + 1, address) else: raise Error( "expected record 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 unpack_srec(record): """Unpack given Motorola S-Record record into variables. """
# Minimum STSSCC, where T is type, SS is size and CC is crc. if len(record) < 6: raise Error("record '{}' too short".format(record)) if record[0] != 'S': raise Error( "record '{}' not starting with an 'S'".format(record)) size = int(record[2:4], 16) type_ = record[1:2...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pack_ihex(type_, address, size, data): """Create a Intel HEX record of given data. """
line = '{:02X}{:04X}{:02X}'.format(size, address, type_) if data: line += binascii.hexlify(data).decode('ascii').upper() return ':{}{:02X}'.format(line, crc_ihex(line))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack_ihex(record): """Unpack given Intel HEX record into variables. """
# Minimum :SSAAAATTCC, where SS is size, AAAA is address, TT is # type and CC is crc. if len(record) < 11: raise Error("record '{}' too short".format(record)) if record[0] != ':': raise Error("record '{}' not starting with a ':'".format(record)) size = int(record[1:3], 16) ad...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(self, size=32, alignment=1): """Return chunks of the data aligned as given by `alignment`. `size` must be a multiple of `alignment`. Each chunk is ret...
if (size % alignment) != 0: raise Error( 'size {} is not a multiple of alignment {}'.format( size, alignment)) address = self.address data = self.data # First chunk may be shorter than `size` due to alignment. ...
<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_data(self, minimum_address, maximum_address, data, overwrite): """Add given data to this segment. The added data must be adjacent to the current segment ...
if minimum_address == self.maximum_address: self.maximum_address = maximum_address self.data += data elif maximum_address == self.minimum_address: self.minimum_address = minimum_address self.data = data + self.data elif (overwrite a...
<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_data(self, minimum_address, maximum_address): """Remove given data range from this segment. Returns the second segment if the removed data splits this...
if ((minimum_address >= self.maximum_address) and (maximum_address <= self.minimum_address)): raise Error('cannot remove data that is not part of the segment') if minimum_address < self.minimum_address: minimum_address = self.minimum_address if maximum_add...
<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(self, segment, overwrite=False): """Add segments by ascending address. """
if self._list: if segment.minimum_address == self._current_segment.maximum_address: # Fast insertion for adjacent segments. self._current_segment.add_data(segment.minimum_address, segment.maximum_address, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(self, size=32, alignment=1): """Iterate over all segments and return chunks of the data aligned as given by `alignment`. `size` must be a multiple of ...
if (size % alignment) != 0: raise Error( 'size {} is not a multiple of alignment {}'.format( size, alignment)) for segment in self: for chunk in segment.chunks(size, alignment): yield chunk
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimum_address(self): """The minimum address of the data, or ``None`` if the file is empty. """
minimum_address = self._segments.minimum_address if minimum_address is not None: minimum_address //= self.word_size_bytes return minimum_address
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maximum_address(self): """The maximum address of the data, or ``None`` if the file is empty. """
maximum_address = self._segments.maximum_address if maximum_address is not None: maximum_address //= self.word_size_bytes return maximum_address
<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(self, data, overwrite=False): """Add given data string by guessing its format. The format must be Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite...
if is_srec(data): self.add_srec(data, overwrite) elif is_ihex(data): self.add_ihex(data, overwrite) elif is_ti_txt(data): self.add_ti_txt(data, overwrite) else: raise UnsupportedFileFormatError()
<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_srec(self, records, overwrite=False): """Add given Motorola S-Records string. Set `overwrite` to ``True`` to allow already added data to be overwritten. ...
for record in StringIO(records): type_, address, size, data = unpack_srec(record.strip()) if type_ == '0': self._header = data elif type_ in '123': address *= self.word_size_bytes self._segments.add(_Segment(address, ...
<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_ihex(self, records, overwrite=False): """Add given Intel HEX records string. Set `overwrite` to ``True`` to allow already added data to be overwritten. "...
extended_segment_address = 0 extended_linear_address = 0 for record in StringIO(records): type_, address, size, data = unpack_ihex(record.strip()) if type_ == IHEX_DATA: address = (address + extended_segment_address ...
<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_ti_txt(self, lines, overwrite=False): """Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
address = None eof_found = False for line in StringIO(lines): # Abort if data is found after end of file. if eof_found: raise Error("bad file terminator") line = line.strip() if len(line) < 1: raise Error("bad l...
<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_binary(self, data, address=0, overwrite=False): """Add given data at given address. Set `overwrite` to ``True`` to allow already added data to be overwri...
address *= self.word_size_bytes self._segments.add(_Segment(address, address + len(data), bytearray(data), self.word_size_bytes), overwrite)
<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_file(self, filename, overwrite=False): """Open given file and add its data by guessing its format. The format must be Motorola S-Records, Intel HEX or TI...
with open(filename, 'r') as fin: self.add(fin.read(), overwrite)
<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_srec_file(self, filename, overwrite=False): """Open given Motorola S-Records file and add its records. Set `overwrite` to ``True`` to allow already added...
with open(filename, 'r') as fin: self.add_srec(fin.read(), overwrite)
<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_ihex_file(self, filename, overwrite=False): """Open given Intel HEX file and add its records. Set `overwrite` to ``True`` to allow already added data to ...
with open(filename, 'r') as fin: self.add_ihex(fin.read(), overwrite)
<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_ti_txt_file(self, filename, overwrite=False): """Open given TI-TXT file and add its contents. Set `overwrite` to ``True`` to allow already added data to ...
with open(filename, 'r') as fin: self.add_ti_txt(fin.read(), overwrite)
<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_binary_file(self, filename, address=0, overwrite=False): """Open given binary file and add its contents. Set `overwrite` to ``True`` to allow already add...
with open(filename, 'rb') as fin: self.add_binary(fin.read(), address, overwrite)
<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_srec(self, number_of_data_bytes=32, address_length_bits=32): """Format the binary file as Motorola S-Records records and return them as a string. `number_...
header = [] if self._header is not None: record = pack_srec('0', 0, len(self._header), self._header) header.append(record) type_ = str((address_length_bits // 8) - 1) if type_ not in '123': raise Error("expected data record type 1..3, but got {}"....