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 wait(self, timeout=None): """ Waits for the job to finish and returns the result. # Arguments timeout (number, None): A number of seconds to wait for the re...
def cond(self): return self.__state not in (Job.PENDING, Job.RUNNING) or self.__cancelled if not wait_for_condition(self, cond, timeout): raise Job.Timeout return self.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 factory(start_immediately=True): """ This is a decorator function that creates new `Job`s with the wrapped function as the target. # Example ```python @Job.f...
def decorator(func): def wrapper(*args, **kwargs): job = Job(task=lambda j: func(j, *args, **kwargs)) if start_immediately: job.start() return job return wrapper return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self, timeout=None): """ Block until all jobs in the ThreadPool are finished. Beware that this can make the program run into a deadlock if another threa...
if not self.__running: raise RuntimeError("ThreadPool ain't running") self.__queue.wait(timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shutdown(self, wait=True): """ Shut down the ThreadPool. # Arguments wait (bool): If #True, wait until all worker threads end. Note that pending jobs are st...
if self.__running: # Add a Non-entry for every worker thread we have. for thread in self.__threads: assert thread.isAlive() self.__queue.append(None) self.__running = False if wait: self.__queue.wait() for thread in self.__threads: thread.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def new_event_type(self, name, mergeable=False): ''' Declare a new event. May overwrite an existing entry. ''' self.event_types[name] = self.EventType(name, mergeable)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pop_event(self): ''' Pop the next queued event from the queue. :raise ValueError: If there is no event queued. ''' with self.lock: if not self.events: raise ValueError('no events queued') return self.events.popleft()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logger(message, level=10): """Handle logging."""
logging.getLogger(__name__).log(level, str(message))
<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 get_data(self): """Get Tautulli data."""
try: await self.get_session_data() await self.get_home_data() await self.get_users() await self.get_user_data() except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror): msg = "Can not load data from Tautulli." logger(ms...
<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 get_session_data(self): """Get Tautulli sessions."""
cmd = 'get_activity' url = self.base_url + cmd try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(response.status)) self.tautulli_session_data = await respo...
<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 get_home_data(self): """Get Tautulli home stats."""
cmd = 'get_home_stats' url = self.base_url + cmd data = {} try: async with async_timeout.timeout(8, loop=self._loop): request = await self._session.get(url) response = await request.json() for stat in response.get('response', {...
<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 get_users(self): """Get Tautulli users."""
cmd = 'get_users' url = self.base_url + cmd users = [] try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(response.status)) all_user_data = await re...
<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 get_user_data(self): """Get Tautulli userdata."""
userdata = {} sessions = self.session_data.get('sessions', {}) try: async with async_timeout.timeout(8, loop=self._loop): for username in self.tautulli_users: userdata[username] = {} userdata[username]['Activity'] = 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 find_classes_in_module(module, clstypes): """Find classes of clstypes in module """
classes = [] for item in dir(module): item = getattr(module, item) try: for cls in clstypes: if issubclass(item, cls) and item != cls: classes.append(item) except Exception as e: pass return classes
<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_yaml_frontmatter(source, return_frontmatter=False): """If there's one, remove the YAML front-matter from the source """
if source.startswith("---\n"): frontmatter_end = source.find("\n---\n", 4) if frontmatter_end == -1: frontmatter = source source = "" else: frontmatter = source[0:frontmatter_end] source = source[frontmatter_end + 5:] if return_frontma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populate_obj(obj, attrs): """Populates an object's attributes using the provided dict """
for k, v in attrs.iteritems(): setattr(obj, k, v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_type: Type[T], logger: Logger = None) -> Parser: """ Returns the ...
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 get_capabilities_by_type(self, strict_type_matching: bool = False) -> Dict[Type, Dict[str, Dict[str, Parser]]]: """ For all types that are supported, lists al...
check_var(strict_type_matching, var_types=bool, var_name='strict_matching') res = dict() # List all types that can be parsed for typ in self.get_all_supported_types(): res[typ] = self.get_capabilities_for_type(typ, strict_type_matching) 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 get_capabilities_by_ext(self, strict_type_matching: bool = False) -> Dict[str, Dict[Type, Dict[str, Parser]]]: """ For all extensions that are supported, list...
check_var(strict_type_matching, var_types=bool, var_name='strict_matching') res = dict() # For all extensions that are supported, for ext in self.get_all_supported_exts_for_type(type_to_match=JOKER, strict=strict_type_matching): res[ext] = self.get_capabilities_for_ext(ext,...
<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_capabilities_for_ext(self, ext, strict_type_matching: bool = False) -> Dict[Type, Dict[str, Parser]]: """ Utility method to return, for a given file exten...
r = dict() # List all types that can be parsed from this extension. for typ in self.get_all_supported_types_for_ext(ext): # Use the query to fill matching = self.find_all_matching_parsers(strict_type_matching, desired_type=typ, required_ext=ext)[0] # matching...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_supported_types_for_ext(self, ext_to_match: str, strict_type_matching: bool = False) -> Set[Type]: """ Utility method to return the set of all support...
matching = self.find_all_matching_parsers(required_ext=ext_to_match, strict=strict_type_matching)[0] return {typ for types in [p.supported_types for p in (matching[0] + matching[1] + matching[2])] for typ in types}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_supported_exts_for_type(self, type_to_match: Type[Any], strict: bool) -> Set[str]: """ Utility method to return the set of all supported file extensio...
matching = self.find_all_matching_parsers(desired_type=type_to_match, strict=strict)[0] return {ext for exts in [p.supported_exts for p in (matching[0] + matching[1] + matching[2])] for ext in exts}
<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_all_matching_parsers(self, strict: bool, desired_type: Type[Any] = JOKER, required_ext: str = JOKER) \ -> Tuple[Tuple[List[Parser], List[Parser], List[Pa...
# if desired_type is JOKER and required_ext is JOKER: # # Easy : return everything (GENERIC first, SPECIFIC then) in order (make a copy first :) ) # matching_parsers_generic = self._generic_parsers.copy() # matching_parsers_approx = [] # matching_parsers_exact =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_typ: Type[T], logger: Logger = None) -> Dict[Type, Parser]: """ ...
parsers = OrderedDict() errors = OrderedDict() try: p = self.__build_parser_for_fileobject_and_desiredtype(obj_on_filesystem, object_typ=object_typ, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_conversion_chains_to_type(self, to_type: Type[Any])\ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find all conve...
return self.get_all_conversion_chains(to_type=to_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_conversion_chains_from_type(self, from_type: Type[Any]) \ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find all ...
return self.get_all_conversion_chains(from_type=from_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_conversion_chains(self, from_type: Type[Any] = JOKER, to_type: Type[Any] = JOKER)\ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Ut...
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 get_all_conversion_chains(self, from_type: Type[Any] = JOKER, to_type: Type[Any] = JOKER) \ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ U...
if from_type is JOKER and to_type is JOKER: matching_dest_generic = self._generic_nonstrict_conversion_chains.copy() + \ self._generic_conversion_chains.copy() matching_dest_approx = [] matching_dest_exact = self._specific_non_strict_conv...
<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_all_matching_parsers(self, strict: bool, desired_type: Type[Any] = JOKER, required_ext: str = JOKER) \ -> Tuple[Tuple[List[Parser], List[Parser], List[Pa...
# transform any 'Any' type requirement into the official class for that desired_type = get_validated_type(desired_type, 'desired_type', enforce_not_joker=False) # (1) call the super method to find all parsers matching, no_type_match_but_ext_match, no_ext_match_but_type_match, no_match ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _complete_parsers_with_converters(self, parser, parser_supported_type, desired_type, matching_c_generic_to_type, matching_c_approx_to_type, matching_c_exact_t...
matching_p_generic, matching_p_generic_with_approx_chain, \ matching_p_approx, matching_p_approx_with_approx_chain,\ matching_p_exact, matching_p_exact_with_approx_chain = [], [], [], [], [], [] # resolve Union and TypeVar desired_types = get_alternate_types_resolving_forwardr...
<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_changed_files(include_staged=False): """ Returns a list of the files that changed in the Git repository. This is used to check if the files that are supp...
process = subprocess.Popen(['git', 'status', '--porcelain'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, __ = process.communicate() if process.returncode != 0: raise ValueError(stdout) files = [] for line in stdout.decode().split('\n'): if not line or line.startswith('#'): continue...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_doc(docs): """ Converts a well-formed docstring into documentation to be fed into argparse. See signature_parser for details. shorts: (-k for --keywor...
name = "(?:[a-zA-Z][a-zA-Z0-9-_]*)" re_var = re.compile(r"^ *(%s)(?: */(%s))? *:(.*)$" % (name, name)) re_opt = re.compile(r"^ *(?:(-[a-zA-Z0-9]),? +)?--(%s)(?: *=(%s))? *:(.*)$" % (name, name)) shorts, metavars, helps, description, epilog = {}, {}, {}, "", "" if docs: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def quote(text): 'Handle quote characters' # Convert to unicode. if not isinstance(text, unicode): text = text.decode('utf-8') # Look for quote characters. Keep the text as is if it's already quoted. for qp in QUOTEPAIRS: if text[0] == qp[0] and text[-1] == qp[-1] and len(text) >= 2: return te...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reltags(self, src, cache=None): ''' returns all the tags that are relevant at this state cache should be a dictionary and it is updated by the function ''' if not self._tag_assocs: return set() # fucking python and it's terrible support for recursion makes this # far more comp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_log_metric(level=logging.INFO, msg="%d items in %.2f seconds"): """Make a new metric function that logs at the given level :arg int level: logging level...
def log_metric(name, count, elapsed): log_name = 'instrument.{}'.format(name) if name else 'instrument' logging.getLogger(log_name).log(level, msg, count, elapsed) return log_metric
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def DBObject(table_name, versioning=VersioningTypes.NONE): """Classes annotated with DBObject gain persistence methods."""
def wrapped(cls): field_names = set() all_fields = [] for name in dir(cls): fld = getattr(cls, name) if fld and isinstance(fld, Field): fld.name = name all_fields.append(fld) field_names.add(name) def add_miss...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def train(self, data, target, **kwargs): """ Used in the training phase. Override. """
non_predictors = [i.replace(" ", "_").lower() for i in list(set(data['team']))] + ["team", "next_year_wins"] self.column_names = [l for l in list(data.columns) if l not in non_predictors] results, folds = self.cross_validate(data, non_predictors, **kwargs) self.gather_results(results, 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 as_command(self): """Creates the click command wrapping the function """
try: params = self.unbound_func.__click_params__ params.reverse() del self.unbound_func.__click_params__ except AttributeError: params = [] help = inspect.getdoc(self.real_func) if isinstance(help, bytes): help = help.decode('u...
<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(command_line_arguments=None): """Reads score files, computes error measures and plots curves."""
args = command_line_options(command_line_arguments) # get some colors for plotting cmap = mpl.cm.get_cmap(name='hsv') count = len(args.files) + (len(args.baselines) if args.baselines else 0) colors = [cmap(i) for i in numpy.linspace(0, 1.0, count+1)] # First, read the score files logger.info("Loading ...
<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_resources(minify=False): """Find all resources which subclass ResourceBase. Keyword arguments: minify -- select minified resources if available. Returns:...
all_resources = dict() subclasses = resource_base.ResourceBase.__subclasses__() + resource_definitions.ResourceAngular.__subclasses__() for resource in subclasses: obj = resource(minify) all_resources[resource.RESOURCE_NAME] = dict(css=tuple(obj.resources_css), js=tuple(obj.resources_js)) ...
<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(self, dsl, params): """ Free queries to ES index. dsl (string): with DSL query params (list): [(key, value), (key, value)] where key is a query para...
query_parameters = [] for key, value in params: query_parameters.append(self.CITEDBY_THRIFT.kwargs(str(key), str(value))) try: result = self.client.search(dsl, query_parameters) except self.CITEDBY_THRIFT.ServerError: raise ServerError('you may tryi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raise_error(error): """Intakes a dict of remote error information and raises a DashiError """
exc_type = error.get('exc_type') if exc_type and exc_type.startswith(ERROR_PREFIX): exc_type = exc_type[len(ERROR_PREFIX):] exc_cls = ERROR_TYPE_MAP.get(exc_type, DashiError) else: exc_cls = DashiError raise exc_cls(**error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fire(self, name, operation, args=None, **kwargs): """Send a message without waiting for a reply @param name: name of destination service queue @param operati...
if args: if kwargs: raise TypeError("specify args dict or keyword arguments, not both") else: args = kwargs d = dict(op=operation, args=args) headers = {'sender': self.add_sysname(self.name)} dest = self.add_sysname(name) def _...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(self, name, operation, timeout=10, args=None, **kwargs): """Send a message and wait for reply @param name: name of destination service queue @param oper...
if args: if kwargs: raise TypeError("specify args dict or keyword arguments, not both") else: args = kwargs # create a direct queue for the reply. This may end up being a # bottleneck for performance: each rpc call gets a brand new # exc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(self, operation, operation_name=None, sender_kwarg=None): """Handle an operation using the specified function @param operation: function to call for t...
if not self._consumer: self._consumer = DashiConsumer(self, self._conn, self._name, self._exchange, sysname=self._sysname) self._consumer.add_op(operation_name or operation.__name__, operation, sender_kwarg=sender_kwarg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link_exceptions(self, custom_exception=None, dashi_exception=None): """Link a custom exception thrown on the receiver to a dashi exception """
if custom_exception is None: raise ValueError("custom_exception must be set") if dashi_exception is None: raise ValueError("dashi_exception must be set") self._linked_exceptions[custom_exception] = dashi_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 ensure(self, connection, func, *args, **kwargs): """Perform an operation until success Repeats in the face of connection errors, pursuant to retry policy. ""...
channel = None while 1: try: if channel is None: channel = connection.channel() return func(channel, *args, **kwargs), channel except (connection.connection_errors, IOError): self._call_errback() ch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def re_tab(s): """Return a tabbed string from an expanded one."""
l = [] p = 0 for i in range(8, len(s), 8): if s[i - 2:i] == " ": # collapse two or more spaces into a tab l.append(s[p:i].rstrip() + "\t") p = i if p == 0: return s else: l.append(s[p:]) return "".join(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 read_next_line(self): """Read another line from the file."""
next_line = self.file.readline() if not next_line or next_line[-1:] != '\n': # no newline on last line of file self.file = None else: # trim newline characters next_line = next_line[:-1] expanded = next_line.expandtabs() edit =...
<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_at_pos(self, pos): """Return a widget for the line number passed."""
if pos < 0: # line 0 is the start of the file, no more above return None, None if len(self.lines) > pos: # we have that line so return it return self.lines[pos], pos if self.file is None: # file is closed, so there are no more lines...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_focus(self): """Divide the focus edit widget at the cursor location."""
focus = self.lines[self.focus] pos = focus.edit_pos edit = urwid.Edit("", focus.edit_text[pos:], allow_tab=True) edit.original_text = "" focus.set_edit_text(focus.edit_text[:pos]) edit.set_edit_pos(0) self.lines.insert(self.focus + 1, edit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_focus_with_prev(self): """Combine the focus edit widget with the one above."""
above, ignore = self.get_prev(self.focus) if above is None: # already at the top return focus = self.lines[self.focus] above.set_edit_pos(len(above.edit_text)) above.set_edit_text(above.edit_text + focus.edit_text) del self.lines[self.focus] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_focus_with_next(self): """Combine the focus edit widget with the one below."""
below, ignore = self.get_next(self.focus) if below is None: # already at bottom return focus = self.lines[self.focus] focus.set_edit_text(focus.edit_text + below.edit_text) del self.lines[self.focus + 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 handle_keypress(self, k): """Last resort for keypresses."""
if k == "esc": self.save_file() raise urwid.ExitMainLoop() elif k == "delete": # delete at end of line self.walker.combine_focus_with_next() elif k == "backspace": # backspace at beginning of line self.walker.combine_focus_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_file(self): """Write the file out to disk."""
l = [] walk = self.walker for edit in walk.lines: # collect the text already stored in edit widgets if edit.original_text.expandtabs() == edit.edit_text: l.append(edit.original_text) else: l.append(re_tab(edit.edit_text)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _media(self): """ Returns a forms.Media instance with the basic editor media and media from all registered extensions. """
css = ['markymark/css/markdown-editor.css'] iconlibrary_css = getattr( settings, 'MARKYMARK_FONTAWESOME_CSS', 'markymark/fontawesome/fontawesome.min.css' ) if iconlibrary_css: css.append(iconlibrary_css) media = forms.Media( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getsuffix(subject): """ Returns the suffix of a filename. If the file has no suffix, returns None. Can return an empty string if the filenam ends with a peri...
index = subject.rfind('.') if index > subject.replace('\\', '/').rfind('/'): return subject[index+1:] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_app(self, app): """Initialize the extension."""
# Set default Flask config option. app.config.setdefault('STATICS_MINIFY', False) # Select resources. self.all_resources = ALL_RESOURCES_MINIFIED if app.config.get('STATICS_MINIFY') else ALL_RESOURCES self.all_variables = ALL_VARIABLES # Add this instance to app.extens...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def measure_board_rms(control_board, n_samples=10, sampling_ms=10, delay_between_samples_ms=0): ''' Read RMS voltage samples from control board high-voltage feedback circuit. ''' try: results = control_board.measure_impedance(n_samples, sampling_ms, ...
<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_good(control_board, actuation_steps, resistor_index, start_index, end_index): ''' Use a binary search over the range of provided actuation_steps to find the maximum actuation voltage that is measured by the board feedback circuit using the specified feedback resistor. ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resistor_max_actuation_readings(control_board, frequencies, oscope_reading_func): ''' For each resistor in the high-voltage feedback resistor bank, read the board measured voltage and the oscilloscope measured voltage for an actuation voltage that nearly saturates...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fit_feedback_params(calibration, max_resistor_readings): ''' Fit model of control board high-voltage feedback resistor and parasitic capacitance values based on measured voltage readings. ''' R1 = 10e6 # Get transfer function to compute the amplitude of the high-voltage input # to the c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update_control_board_calibration(control_board, fitted_params): ''' Update the control board with the specified fitted parameters. ''' # Update the control board with the new fitted capacitor and resistor # values for the reference load analog input (channel 0). control_board.a0_series_resis...
<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(self): """ Load each path in order. Remember paths already loaded and only load new ones. """
data = self.dict_class() for path in self.paths: if path in self.paths_loaded: continue try: with open(path, 'r') as file: path_data = yaml.load(file.read()) data = dict_merge(data, path_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 _initialize(self, settings_module): """ Initialize the settings from a given settings_module settings_module - path to settings module """
#Get the global settings values and assign them as self attributes self.settings_list = [] for setting in dir(global_settings): #Only get upper case settings if setting == setting.upper(): setattr(self, setting, getattr(global_settings, setting)) ...
<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(self): """ Perform initial setup of the settings class, such as getting the settings module and setting the settings """
settings_module = None #Get the settings module from the environment variables try: settings_module = os.environ[global_settings.MODULE_VARIABLE] except KeyError: error_message = "Settings not properly configured. Cannot find the environment variable {0}".forma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _configure_logging(self): """ Setting up logging from logging config in settings """
if not self.LOGGING_CONFIG: #Fallback to default logging in global settings if needed dictConfig(self.DEFAULT_LOGGING) else: dictConfig(self.LOGGING_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 ensure_context(**vars): """Ensures that a context is in the stack, creates one otherwise. """
ctx = _context_stack.top stacked = False if not ctx: ctx = Context() stacked = True _context_stack.push(ctx) ctx.update(vars) try: yield ctx finally: if stacked: _context_stack.pop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request_context(app, request): """Creates a Context instance from the given request object """
vars = {} if request.view_args is not None: vars.update(request.view_args) vars.update({ "request": request, "GET": AttrDict(request.args.to_dict()), "POST" : AttrDict(request.form.to_dict()), "app": app, "config": app.config, "session": session, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone(self, **override_vars): """Creates a copy of this context"""
c = Context(self.vars, self.data) c.executed_actions = set(self.executed_actions) c.vars.update(override_vars) return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mpl_get_cb_bound_below_plot(ax): """ Return the coordinates for a colorbar axes below the provided axes object. Take into account the changes of the axes due...
position = ax.get_position() figW, figH = ax.get_figure().get_size_inches() fig_aspect = figH / figW box_aspect = ax.get_data_ratio() pb = position.frozen() pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect).bounds ax_size = ax.get_position().bounds # the colorbar is set to 0.01 w...
<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(): """Generate an XLS with specified content."""
table = """<table> <thead> <tr><th>First Name</th><th>Last Name</th></tr> </thead> <tbody> <tr><td>Paul</td><td>McGrath</td></tr> <tr><td>Liam</td><td>Brady</td></tr> <tr><td>John</td><td>Giles</td></tr> </tbody> </table>""" docraptor = DocRaptor() print("Create test_ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_gc_state(): """ Restore the garbage collector state on leaving the with block. """
old_isenabled = gc.isenabled() old_flags = gc.get_debug() try: yield finally: gc.set_debug(old_flags) (gc.enable if old_isenabled else gc.disable)()
<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_view_file_mapping(self, pattern, cls): """Adds a mapping between a file and a view class. Pattern can be an extension in the form .EXT or a filename. """
if isinstance(pattern, str): if not pattern.endswith("*"): _, ext = os.path.splitext(pattern) self.allowed_extensions.add(ext) pattern = re.compile("^" + re.escape(pattern).replace("\\*", ".+") + "$", re.I) self.view_class_files_map.append((patter...
<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_file_view_cls(self, filename): """Returns the view class associated to a filename """
if filename is None: return self.default_view_class for pattern, cls in self.view_class_files_map: if pattern.match(filename): return cls return self.default_view_class
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def children(self, vertex): """ Return the list of immediate children of the given vertex. """
return [self.head(edge) for edge in self.out_edges(vertex)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parents(self, vertex): """ Return the list of immediate parents of this vertex. """
return [self.tail(edge) for edge in self.in_edges(vertex)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def descendants(self, start, generations=None): """ Return the subgraph of all nodes reachable from the given start vertex, including that vertex. If specified, ...
visited = self.vertex_set() visited.add(start) to_visit = deque([(start, 0)]) while to_visit: vertex, depth = to_visit.popleft() if depth == generations: continue for child in self.children(vertex): if child not in visi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ancestors(self, start, generations=None): """ Return the subgraph of all nodes from which the given vertex is reachable, including that vertex. If specified,...
visited = self.vertex_set() visited.add(start) to_visit = deque([(start, 0)]) while to_visit: vertex, depth = to_visit.popleft() if depth == generations: continue for parent in self.parents(vertex): if parent not in vis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _component_graph(self): """ Compute the graph of strongly connected components. Each strongly connected component is itself represented as a list of pairs, g...
sccs = [] stack = [] boundaries = [] identified = self.vertex_set() index = self.vertex_dict() to_do = [] def visit_vertex(v): index[v] = len(stack) stack.append(('VERTEX', v)) boundaries.append(index[v]) to_do.app...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def source_components(self): """ Return the strongly connected components not reachable from any other component. Any component in the graph is reachable from on...
raw_sccs = self._component_graph() # Construct a dictionary mapping each vertex to the root of its scc. vertex_to_root = self.vertex_dict() # And keep track of which SCCs have incoming edges. non_sources = self.vertex_set() # Build maps from vertices to roots, and ide...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strongly_connected_components(self): """ Return list of strongly connected components of this graph. Returns a list of subgraphs. Algorithm is based on that ...
raw_sccs = self._component_graph() sccs = [] for raw_scc in raw_sccs: sccs.append([v for vtype, v in raw_scc if vtype == 'VERTEX']) return [self.full_subgraph(scc) for scc in sccs]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_orders(self, orders): """ Each order needs to have all it's details filled with default value, or None, in case those are not already filled. """
for detail in PAYU_ORDER_DETAILS: if not any([detail in order for order in orders]): for order in orders: order[detail] = PAYU_ORDER_DETAILS_DEFAULTS.get(detail, None) return orders
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def staticfiles_url_fetcher(url): """ Returns the file matching url. This method will handle any URL resources that rendering HTML requires (eg: images pointed m...
if url.startswith('/'): base_url = staticfiles_storage.base_url filename = url.replace(base_url, '', 1) path = finders.find(filename) if path: # This should match most cases. Manifest static files with relative # URLs will only be picked up in DEBUG mode her...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_pdf( template, file_, url_fetcher=staticfiles_url_fetcher, context=None, ): """ Writes the PDF data into ``file_``. Note that ``file_`` can actually b...
context = context or {} html = get_template(template).render(context) HTML( string=html, base_url='not-used://', url_fetcher=url_fetcher, ).write_pdf( target=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 encode_bytes(src_buf, dst_file): """Encode a buffer length followed by the bytes of the buffer itself. Parameters src_buf: bytes Source bytes to be encoded. ...
if not isinstance(src_buf, bytes): raise TypeError('src_buf must by bytes.') len_src_buf = len(src_buf) assert 0 <= len_src_buf <= 2**16-1 num_written_bytes = len_src_buf + 2 len_buf = FIELD_U16.pack(len_src_buf) dst_file.write(len_buf) dst_file.write(src_buf) return num_writ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_bytes(f): """Decode a buffer length from a 2-byte unsigned int then read the subsequent bytes. Parameters f: file File-like object with read method. R...
buf = f.read(FIELD_U16.size) if len(buf) < FIELD_U16.size: raise UnderflowDecodeError() (num_bytes,) = FIELD_U16.unpack_from(buf) num_bytes_consumed = FIELD_U16.size + num_bytes buf = f.read(num_bytes) if len(buf) < num_bytes: raise UnderflowDecodeError() return num_byte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_utf8(s, f): """UTF-8 encodes string `s` to file-like object `f` according to the MQTT Version 3.1.1 specification in section 1.5.3. The maximum length...
encode = codecs.getencoder('utf8') encoded_str_bytes, num_encoded_chars = encode(s) num_encoded_str_bytes = len(encoded_str_bytes) assert 0 <= num_encoded_str_bytes <= 2**16-1 num_encoded_bytes = num_encoded_str_bytes + 2 f.write(FIELD_U8.pack((num_encoded_str_bytes & 0xff00) >> 8)) f.wri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_varint(v, f): """Encode integer `v` to file `f`. Parameters v: int Integer v >= 0. f: file Object containing a write method. Returns ------- int Numbe...
assert v >= 0 num_bytes = 0 while True: b = v % 0x80 v = v // 0x80 if v > 0: b = b | 0x80 f.write(FIELD_U8.pack(b)) num_bytes += 1 if v == 0: break return num_bytes
<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(self, struct): """Read as many bytes as are required to extract struct then unpack and return a tuple of the values. Raises ------ UnderflowDecodeErro...
v = struct.unpack(self.read(struct.size)) return v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack_bytes(self): """Unpack a utf-8 string encoded as described in MQTT Version 3.1.1 section 1.5.3 line 177. This is a 16-bit unsigned length followed by ...
num_bytes_consumed, b = decode_bytes(self.__f) self.__num_bytes_consumed += num_bytes_consumed return num_bytes_consumed, b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, num_bytes): """Read `num_bytes` and return them. Parameters num_bytes : int Number of bytes to extract from the underlying stream. Raises ------ U...
buf = self.__f.read(num_bytes) assert len(buf) <= num_bytes if len(buf) < num_bytes: raise UnderflowDecodeError() self.__num_bytes_consumed += num_bytes return buf
<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(self, value): ''' Specifies a timeout on the search query ''' if not self.params: self.params = dict(timeout=value) return self self.params['timeout'] = value return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filtered(self, efilter): ''' Applies a filter to the search ''' if not self.params: self.params={'filter' : efilter} return self if not self.params.has_key('filter'): self.params['filter'] = efilter return self self.para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def size(self,value): ''' The number of hits to return. Defaults to 10 ''' if not self.params: self.params = dict(size=value) return self self.params['size'] = value return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_offset(self, value): ''' The starting from index of the hits to return. Defaults to 0. ''' if not self.params: self.params = dict({'from':value}) return self self.params['from'] = value return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sorted(self, fsort): ''' Allows to add one or more sort on specific fields. Each sort can be reversed as well. The sort is defined on a per field level, with special field name for _score to sort by score. ''' if not self.params: self.params = dict() self.params['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def doc_create(self,index,itype,value): ''' Creates a document ''' request = self.session url = 'http://%s:%s/%s/%s/' % (self.host, self.port, index, itype) if self.verbose: print value response = request.post(url,value) return response
<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_simple(self,index,key,search_term): ''' Search the index using a simple key and search_term @param index Name of the index @param key Search Key @param search_term The term to be searched for ''' request = self.session url = 'http://%s:%s/...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def search_index_advanced(self, index, query): ''' Advanced search query against an entire index > query = ElasticQuery().query_string(query='imchi') > search = ElasticSearch() ''' request = self.session url = 'http://%s:%s/%s/_search' % (self.host, self.port, 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 map(self,index_name, index_type, map_value): ''' Enable a specific map for an index and type ''' request = self.session url = 'http://%s:%s/%s/%s/_mapping' % (self.host, self.port, index_name, index_type) content = { index_type : { 'properties' : map_value } } ...