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 set_add(parent, idx, value): """Add an item to a list if it doesn't exist."""
lst = get_child(parent, idx) if value not in lst: lst.append(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_path(path): """Parse a rfc 6901 path."""
if not path: raise ValueError("Invalid path") if isinstance(path, str): if path == "/": raise ValueError("Invalid path") if path[0] != "/": raise ValueError("Invalid path") return path.split(_PATH_SEP)[1:] elif isinstance(path, (tuple, list)): return path else: raise ValueE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_path(root, path): """Resolve a rfc 6901 path, returning the parent and the last path part."""
path = parse_path(path) parent = root for part in path[:-1]: parent = get_child(parent, rfc_6901_replace(part)) return (parent, rfc_6901_replace(path[-1]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_all(root, path): """Get all children that satisfy the path."""
path = parse_path(path) if len(path) == 1: yield from get_children(root, path[0]) else: for child in get_children(root, path[0]): yield from find_all(child, path[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 apply_patch(document, patch): """Apply a Patch object to a document."""
# pylint: disable=too-many-return-statements op = patch.op parent, idx = resolve_path(document, patch.path) if op == "add": return add(parent, idx, patch.value) elif op == "remove": return remove(parent, idx) elif op == "replace": return replace(parent, idx, patch.value, patch.src) elif op ==...
<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_patches(document, patches): """Serially apply all patches to a document."""
for i, patch in enumerate(patches): try: result = apply_patch(document, patch) if patch.op == "test" and result is False: raise JSONPatchError("Test patch {0} failed. Cancelling entire set.".format(i + 1)) except Exception as ex: raise JSONPatchError("An error occurred with patch {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 execute(self, env, args): """ Displays task time left in minutes. `env` Runtime ``Environment`` instance. `args` Arguments object from arg parser. """
msg = u'Time Left: {0}m' if not args.short else '{0}' mins = max(0, self.total_duration - env.task.duration) env.io.write(msg.format(mins))
<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_option(self, option, block_name, *values): """ Parse duration option for timer. """
try: if len(values) != 1: raise TypeError self.total_duration = int(values[0]) if self.total_duration <= 0: raise ValueError except ValueError: pattern = u'"{0}" must be an integer > 0' raise ValueError(patte...
<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_point(self, x, y): """Adds a data point to the series. :param x: The numerical x value to be added. :param y: The numerical y value to be added."""
if not is_numeric(x): raise TypeError("x value must be numeric, not '%s'" % str(x)) if not is_numeric(y): raise TypeError("y value must be numeric, not '%s'" % str(y)) current_last_x = self._data[-1][0] self._data.append((x, y)) if x < current_last_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 remove_data_point(self, x, y): """Removes the given data point from the series. :param x: The numerical x value of the data point to be removed. :param y: Th...
if len(self._data) == 1: raise ValueError("You cannot remove a Series' last data point") self._data.remove((x, y))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def faz(input_file, variables=None): """ FAZ entry point. """
logging.debug("input file:\n {0}\n".format(input_file)) tasks = parse_input_file(input_file, variables=variables) print("Found {0} tasks.".format(len(tasks))) graph = DependencyGraph(tasks) graph.show_tasks() graph.execute()
<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_version(): """Build version number from git repository tag."""
try: f = open('eztemplate/version.py', 'r') except IOError as e: if e.errno != errno.ENOENT: raise m = None else: m = re.match('^\s*__version__\s*=\s*(?P<version>.*)$', f.read(), re.M) f.close() __version__ = ast.literal_eval(m.group('version')) if m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_long_description(): """Provide README.md converted to reStructuredText format."""
try: with open('README.md', 'r') as f: description = f.read() except OSError as e: if e.errno != errno.ENOENT: raise return None try: process = subprocess.Popen([ 'pandoc', '-f', 'markdown_github', '-t'...
<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(self): """Printing runtime statistics in JSON"""
context_data = self.get_context_data() context_data.update(getattr(self.request.app, "stats", {})) response = self.json_response(context_data) 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 _dump_list(list_data, jsonify, stream=sys.stdout): ''' Dump list to output stream, optionally encoded as JSON. Parameters ---------- list_data : list jsonify : bool stream : file-like ''' if not jsonify and list_data: print >> stream, '\n'.join(list_data) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _threaded(self, *args, **kwargs): """Call the target and put the result in the Queue."""
for target in self.targets: result = target(*args, **kwargs) self.queue.put(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 start(self, *args, **kwargs): """Start execution of the function."""
self.queue = Queue() thread = Thread(target=self._threaded, args=args, kwargs=kwargs) thread.start() return Asynchronous.Result(self.queue, thread)
<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, **options): """Configures the application."""
sd = options.setdefault conf = app.config sd('app_id', conf.get('PUSHER_APP_ID')) sd('key', conf.get('PUSHER_KEY')) sd('secret', conf.get('PUSHER_SECRET')) sd('ssl', conf.get('PUSHER_SSL', True)) sd('host', conf.get('PUSHER_HOST')) sd('port', conf.get('P...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def title_from_content(content): """ Try and extract the first sentence from a block of test to use as a title. """
for end in (". ", "?", "!", "<br />", "\n", "</p>"): if end in content: content = content.split(end)[0] + end break return strip_tags(content)
<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, conn, tmp, module_name, module_args, inject): ''' run the pause actionmodule ''' hosts = ', '.join(self.runner.host_set) args = parse_kv(template(self.runner.basedir, module_args, inject)) # Are 'minutes' or 'seconds' keys that exist in 'args'? if 'minutes' in args...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _start(self): ''' mark the time of execution for duration calculations later ''' self.start = time.time() self.result['start'] = str(datetime.datetime.now()) if not self.pause_type == 'prompt': print "(^C-c = continue early, ^C-a = abort)"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _stop(self): ''' calculate the duration we actually paused for and then finish building the task result string ''' duration = time.time() - self.start self.result['stop'] = str(datetime.datetime.now()) self.result['delta'] = int(duration) if self.duration_unit == 'mi...
<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, status_code, status_reason): """ Add data to this response. This method should be used to add data to the response. The data should be all th...
self.status_code = status_code self.status_reason = status_reason self.success = status_code == 200 if data: if not self.data: self.data = data else: self.data += data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def print_pretty(text, **kwargs): ''' Prints using pycolorterm formatting :param text: Text with formatting :type text: string :param kwargs: Keyword args that will be passed to the print function :type kwargs: dict Example:: print_pretty('Hello {BG_RED}WORLD{END}') ''' t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def any_text_to_fernet_key(self, text): """ Convert any text to a fernet key for encryption. """
md5 = fingerprint.fingerprint.of_text(text) fernet_key = base64.b64encode(md5.encode("utf-8")) return fernet_key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predecesors_pattern(element, root): """ Look for `element` by its predecesors. Args: element (obj): HTMLElement instance of the object you are looking for. ...
def is_root_container(el): return el.parent.parent.getTagName() == "" if not element.parent or not element.parent.parent or \ is_root_container(element): return [] trail = [ [ element.parent.parent.getTagName(), _params_or_none(element.parent.parent....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_document(self, document): ''' Add a document to this corpus `document' is passed to `requests.post', so it can be a file-like object, a string (that will be sent as the file content) or a tuple containing a filename followed by any of these two options. ''' ...
<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_documents(self, documents): ''' Adds more than one document using the same API call Returns two lists: the first one contains the successfully uploaded documents, and the second one tuples with documents that failed to be uploaded and the exceptions raised. ''' ...
<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_corpus(self, name, description): '''Add a corpus to your account''' corpora_url = self.base_url + self.CORPORA_PAGE data = {'name': name, 'description': description} result = self.session.post(corpora_url, data=data) if result.status_code == 201: return Corpus...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def corpora(self, full=False): '''Return list of corpora owned by user. If `full=True`, it'll download all pages returned by the HTTP server''' url = self.base_url + self.CORPORA_PAGE class_ = Corpus results = self._retrieve_resources(url, class_, full) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def documents(self, full=False): '''Return list of documents owned by user. If `full=True`, it'll download all pages returned by the HTTP server''' url = self.base_url + self.DOCUMENTS_PAGE class_ = Document results = self._retrieve_resources(url, class_, full) return re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def insert_node(**kw): "Insert a node with a name and optional value. Return the node id." with current_app.app_context(): result = db.execute(text(fetch_query_string('insert_node.sql')), **kw) # TODO: support for postgres may require using a RETURNING id; sql # statement and using the 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 insert_node_node(**kw): """ Link a node to another node. node_id -> target_node_id. Where `node_id` is the parent and `target_node_id` is the child. """
with current_app.app_context(): insert_query(name='select_link_node_from_node.sql', node_id=kw.get('node_id')) db.execute(text(fetch_query_string('insert_node_node.sql')), **kw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_node(**kw): """ Select node by id. """
with current_app.app_context(): result = db.execute(text(fetch_query_string('select_node_from_id.sql')), **kw).fetchall() 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 add_template_for_node(name, node_id): "Set the template to use to display the node" with current_app.app_context(): db.execute(text(fetch_query_string('insert_template.sql')), name=name, node_id=node_id) result = db.execute(text(fetch_query_string('select_template.sql')), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_query(**kw): """ Insert a query name for a node_id. `name` `node_id` Adds the name to the Query table if not already there. Sets the query field in No...
with current_app.app_context(): result = db.execute(text(fetch_query_string('select_query_where_name.sql')), **kw).fetchall() if result: kw['query_id'] = result[0]['id'] else: result = db.execute(text(fetch_query_string('insert_query.sql')), **kw) kw['que...
<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_subject_guide_for_section(section): """ Returns a SubjectGuide model for the passed SWS section model. """
return get_subject_guide_for_section_params( section.term.year, section.term.quarter, section.curriculum_abbr, section.course_number, section.section_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_subject_guide_for_canvas_course_sis_id(course_sis_id): """ Returns a SubjectGuide model for the passed Canvas course SIS ID. """
(year, quarter, curriculum_abbr, course_number, section_id) = course_sis_id.split('-', 4) return get_subject_guide_for_section_params( year, quarter, curriculum_abbr, course_number, section_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 update(self, pbar): """ Handle progress bar updates @type pbar: ProgressBar @rtype: str """
if pbar.label != self._label: self.label = pbar.label return self.label
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def label(self, value): """ Set the label and generate the formatted value @type value: str """
# Fixed width label formatting value = value[:self.pad_size] if self.pad_size else value try: padding = ' ' * (self.pad_size - len(value)) if self.pad_size else '' except TypeError: padding = '' self._formatted = ' {v}{p} '.format(v=value, p=padding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish(self): """ Update widgets on finish """
os.system('setterm -cursor on') if self.nl: Echo(self.label).done()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, request, *args, **kwargs): """ Does request processing for return_url query parameter and redirects with it's missing We can't do that in the ...
self.return_url = request.GET.get('return_url', None) referrer = request.META.get('HTTP_REFERER', None) # leave alone POST and ajax requests and if return_url is explicitly left empty if (request.method != "GET" or request.is_ajax() or self.return_url o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(security_token=None, key=None): """ Get information about this node """
if security_token is None: security_token = nago.core.get_my_info()['host_name'] data = node_data.get(security_token, {}) if not key: return data else: return data.get(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(node_name, key, **kwargs): """ Give the server information about this node Arguments: node -- node_name or token for the node this data belongs to key -...
node = nago.core.get_node(node_name) if not node: raise ValueError("Node named %s not found" % node_name) token = node.token node_data[token] = node_data[token] or {} node_data[token][key] = kwargs return "thanks!"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(node_name): """ Send our information to a remote nago instance Arguments: node -- node_name or token for the node this data belongs to """
my_data = nago.core.get_my_info() if not node_name: node_name = nago.settings.get('server') node = nago.core.get_node(node_name) json_params = {} json_params['node_name'] = node_name json_params['key'] = "node_info" for k, v in my_data.items(): nago.core.log("sending %s to %...
<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_obj(self, vimtype, name, folder=None): """ Return an object by name, if name is None the first found object is returned """
obj = None content = self.service_instance.RetrieveContent() if folder is None: folder = content.rootFolder container = content.viewManager.CreateContainerView(folder, [vimtype], True) for c in container.view: if c.name == name: obj = 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 _increment_current_byte(self): """ Increments the value of the current byte at the pointer. If the result is over 255, then it will overflow to 0 """
# If the current byte is uninitialized, then incrementing it will make it 1 if self.tape[self.pointer] is None: self.tape[self.pointer] = 1 elif self.tape[self.pointer] == self.MAX_CELL_SIZE: # If the current byte is already at the max, then overflow self.tape[self.poin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decrement_current_byte(self): """ Decrements the value of the current byte at the pointer. If the result is below 0, then it will overflow to 255 """
# If the current byte is uninitialized, then decrementing it will make it the max cell size # Otherwise, if it's already at the minimum cell size, then it will also make it the max cell size if self.tape[self.pointer] is None or self.tape[self.pointer] == self.MIN_CELL_SIZE: self.ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _output_current_byte(self): """ Prints out the ASCII value of the current byte """
if self.tape[self.pointer] is None: print "{}".format(chr(0)), else: print "{}".format(chr(int(self.tape[self.pointer]))),
<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_byte(self): """ Read a single byte from the user without waiting for the \n character """
from .getch import _Getch try: g = _Getch() self.tape[self.pointer] = ord(g()) except TypeError as e: print "Here's what _Getch() is giving me {}".format(g())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decompress(self, value): """ Takes the sequence of ``AssignedKeyword`` instances and splits them into lists of keyword IDs and titles each mapping to one of ...
if hasattr(value, "select_related"): keywords = [a.keyword for a in value.select_related("keyword")] if keywords: keywords = [(str(k.id), k.title) for k in keywords] self._ids, words = list(zip(*keywords)) return (",".join(self._ids), ", "...
<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_output(self, rendered_widgets): """ Wraps the output HTML with a list of all available ``Keyword`` instances that can be clicked on to toggle a keywor...
rendered = super(KeywordsWidget, self).format_output(rendered_widgets) links = "" for keyword in Keyword.objects.all().order_by("title"): prefix = "+" if str(keyword.id) not in self._ids else "-" links += ("<a href='#'>%s%s</a>" % (prefix, str(keyword))) rendered...
<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(self, request): """ Saves a new comment and sends any notification emails. """
comment = self.get_comment_object() obj = comment.content_object if request.user.is_authenticated(): comment.user = request.user comment.by_author = request.user == getattr(obj, "user", None) comment.ip_address = ip_for_request(request) comment.replied_to_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 clean(self): """ Check unauthenticated user's cookie as a light check to prevent duplicate votes. """
bits = (self.data["content_type"], self.data["object_pk"]) request = self.request self.current = "%s.%s" % bits self.previous = request.COOKIES.get("yacms-rating", "").split(",") already_rated = self.current in self.previous if already_rated and not self.request.user.is_...
<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(self): """ Saves a new rating - authenticated users can update the value if they've previously rated. """
user = self.request.user self.undoing = False rating_value = self.cleaned_data["value"] manager = self.rating_manager if user.is_authenticated(): rating_instance, created = manager.get_or_create(user=user, defaults={'value': rating_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 setup_exceptions(): """ Only print the heart of the exception and not the stack trace """
# first set up the variables needed by the _excepthook function global _print_traceback, _drill local_print_traceback = os.getenv("PYLOGCONF_PRINT_TRACEBACK") if local_print_traceback is not None: _print_traceback = _str2bool(local_print_traceback) local_drill = os.getenv("PYLOGCONF_DRILL")...
<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_logging(): """ setup the logging system """
default_path_yaml = os.path.expanduser('~/.pylogconf.yaml') default_path_conf = os.path.expanduser('~/.pylogconf.conf') # this matches the default logging level of the logging # library and makes sense... default_level = logging.WARNING dbg = os.getenv("PYLOGCONF_DEBUG", False) """ try YA...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_two_curves(curve1: Curve, curve2: Curve, qmin, qmax, qsep, use_additive_constant=False): """Merge two scattering curves :param curve1: the first curve...
curve1=curve1.sanitize() curve2=curve2.sanitize() if len(curve1.trim(qmin, qmax)) > len(curve2.trim(qmin, qmax)): curve2_interp = curve2.trim(qmin, qmax) curve1_interp = curve1.interpolate(curve2_interp.q) else: curve1_interp = curve1.trim(qmin, qmax) curve2_interp = cur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_sha(obj): """Calculates the base64-encoded SHA hash of a file."""
try: pathfile = Path(obj) except UnicodeDecodeError: pathfile = None sha = hashlib.sha256() try: if pathfile and pathfile.exists(): return base64.b64encode(pathfile.read_hash('SHA256')) except TypeError: # likely a bytestring if isinstance(obj, 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 blog_months(*args): """ Put a list of dates for blog posts into the template context. """
dates = BlogPost.objects.published().values_list("publish_date", flat=True) date_dicts = [{"date": datetime(d.year, d.month, 1)} for d in dates] month_dicts = [] for date_dict in date_dicts: if date_dict not in month_dicts: month_dicts.append(date_dict) for i, date_dict in enume...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blog_categories(*args): """ Put a list of categories for blog posts into the template context. """
posts = BlogPost.objects.published() categories = BlogCategory.objects.filter(blogposts__in=posts) return list(categories.annotate(post_count=Count("blogposts")))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blog_recent_posts(limit=5, tag=None, username=None, category=None): """ Put a list of recently published blog posts into the template context. A tag title or...
blog_posts = BlogPost.objects.published().select_related("user") title_or_slug = lambda s: Q(title=s) | Q(slug=s) if tag is not None: try: tag = Keyword.objects.get(title_or_slug(tag)) blog_posts = blog_posts.filter(keywords__keyword=tag) except Keyword.DoesNotExist:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emit(self, action, payload, level=Level.INSTANT): """Emit action."""
if level == self.Level.INSTANT: return self.emit_instantly(action, payload) elif level == self.Level.CONTEXTUAL: return self.emit_contextually(action, payload) elif level == self.Level.DELAY: return self.emit_delayed(action, payload) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emit_contextually(self, action, payload): """ Emit on exiting request context."""
self.dump(action, payload) return g.rio_client_contextual.append((action, payload, ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current(self): """A namedtuple contains `uuid`, `project`, `action`. Example:: @app.route('/webhook/broadcast-news') def broadcast_news(): if rio.current.ac...
event = request.headers.get('X-RIO-EVENT') data = dict([elem.split('=') for elem in event.split(',')]) return Current(**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 init(): "Initialize the current directory with base starting files and database." if not os.path.exists('site.cfg'): f = open('site.cfg', 'w') f.write(SITEC...
) f.close() app = make_app(config='site.cfg', DEBUG=True) with app.app_context(): app.logger.info("initializing database") init_db() homepage = insert_node(name='homepage', value=None) insert_route(path='/', node_id=homepage) insert_query(name='select_link_node...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def operate(config): "Interface to do simple operations on the database." app = make_app(config=config) print "Operate Mode" with app.app_context(): operate_menu()
<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(config): "Start the web server in the foreground. Don't use for production." app = make_app(config=config) app.run( host=app.config.get("HOST", '127.0.0.1'), port=app.config.get("PORT", 5000), use_reloader=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 serve(config): "Serve the app with Gevent" from gevent.pywsgi import WSGIServer app = make_app(config=config) host = app.config.get("HOST", '127.0.0.1') port = app.config.get("PORT", 5000) http_server = WSGIServer((host, port), app) http_server.serve_forever()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_german_date(x): """Convert a string with a German date 'DD.MM.YYYY' to Datetime objects Parameters x : str, list, tuple, numpy.ndarray, pandas.DataFram...
import numpy as np import pandas as pd from datetime import datetime def proc_elem(e): try: return datetime.strptime(e, '%d.%m.%Y') except Exception as e: print(e) return None def proc_list(x): return [proc_elem(e) for e in x] def p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mro(*bases): """Calculate the Method Resolution Order of bases using the C3 algorithm. Suppose you intended creating a class K with the given base classes. T...
seqs = [list(C.__mro__) for C in bases] + [list(bases)] res = [] while True: non_empty = list(filter(None, seqs)) if not non_empty: # Nothing left to process, we're done. return tuple(res) for seq in non_empty: # Find merge candidates among seq heads. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def printlog(self, string, verbose=None, flush=False): """Prints the given string to a logfile if logging is on, and to screen if verbosity is on."""
if self.writelog: self.logger.info(string) if verbose or (self.verbose and verbose is None): print(string, flush=flush)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exception(self, exception): """Prints the stacktrace of the given exception."""
if self.writelog: self.logger.exception(exception) if self.verbose: for line in traceback.format_exception( None, exception, exception.__traceback__): print(line, end='', file=sys.stderr, flush=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 tqdm(self, iterable, **kwargs): """Wraps the given iterable with a tqdm progress bar if this logger is set to verbose. Otherwise, returns the iterable unchan...
if 'disable' in kwargs: kwargs.pop('disable') return tqdm(iterable, disable=not self.verbose, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def respond(self, data): """ Respond to the connection accepted in this object """
self.push("%s%s" % (data, TERMINATOR)) if self.temporary: self.close_when_done()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def participant_policy(self, value): """ Changing participation policy fires a "ParticipationPolicyChanged" event """
old_policy = self.participant_policy new_policy = value self._participant_policy = new_policy notify(ParticipationPolicyChangedEvent(self, old_policy, new_policy))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define_constrained_subtype(prefix, base, blockednames, clsdict=None): """ Define a subtype which blocks a list of methods. @param prefix: The subtype name pr...
name = prefix + base.__name__ clsdict = clsdict or {} doc = clsdict.get('__doc__', '') doc = 'An {} extension of {}.\n{}'.format(prefix, base.__name__, doc) clsdict['__doc__'] = doc setitem_without_overwrite( clsdict, 'get_blocked_method_names', lambda self: iter(bloc...
<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_without_overwrite(d, *args, **kwds): """ This has the same interface as dict.update except it uses setitem_without_overwrite for all updates. Note: Th...
if args: assert len(args) == 1, \ 'At most one positional parameter is allowed: {0!r}'.format(args) (other,) = args if isinstance(other, Mapping): for key in other: setitem_without_overwrite(d, key, other[key]) elif hasattr(other, "keys"): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _step(self): """Private method do not call it directly or override it."""
try: new_value = self._device.get(self._channel) if new_value != self._value: self._callback(new_value) self._value = new_value time.sleep(self._polling_time) except: self.spine.log.exception("_PollingThread")
<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_post(self, title=None, content=None, old_url=None, pub_date=None, tags=None, categories=None, comments=None): """ Adds a post to the post list for proces...
if not title: title = strip_tags(content).split(". ")[0] title = decode_entities(title) if categories is None: categories = [] if tags is None: tags = [] if comments is None: comments = [] self.posts.append({ "t...
<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_page(self, title=None, content=None, old_url=None, tags=None, old_id=None, old_parent_id=None): """ Adds a page to the list of pages to be imported - use...
if not title: text = decode_entities(strip_tags(content)).replace("\n", " ") title = text.split(". ")[0] if tags is None: tags = [] self.pages.append({ "title": title, "content": content, "tags": tags, "old_url"...
<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_comment(self, post=None, name=None, email=None, pub_date=None, website=None, body=None): """ Adds a comment to the post provided. """
if post is None: if not self.posts: raise CommandError("Cannot add comments without posts") post = self.posts[-1] post["comments"].append({ "user_name": name, "user_email": email, "submit_date": pub_date, "user_url"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trunc(self, model, prompt, **fields): """ Truncates fields values for the given model. Prompts for a new value if truncation occurs. """
for field_name, value in fields.items(): field = model._meta.get_field(field_name) max_length = getattr(field, "max_length", None) if not max_length: continue elif not prompt: fields[field_name] = value[:max_length] ...
<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_meta(self, obj, tags, prompt, verbosity, old_url=None): """ Adds tags and a redirect for the given obj, which is a blog post or a page. """
for tag in tags: keyword = self.trunc(Keyword, prompt, title=tag) keyword, created = Keyword.objects.get_or_create_iexact(**keyword) obj.keywords.create(keyword=keyword) if created and verbosity >= 1: print("Imported tag: %s" % keyword) if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smart_content_type_for_model(model): """ Returns the Django ContentType for a given model. If model is a proxy model, the proxy model's ContentType will be r...
try: # noinspection PyPackageRequirements,PyUnresolvedReferences from django.contrib.contenttypes.models import ContentType except ImportError: print("Django is required but cannot be imported.") raise if model._meta.proxy: return ContentType.objects.get(app_label=m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_first_content(el_list, alt=None, strip=True): """ Return content of the first element in `el_list` or `alt`. Also return `alt` if the content string of f...
if not el_list: return alt content = el_list[0].getContent() if strip: content = content.strip() if not content: return alt return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_url(base_url, rel_url): """ Normalize the `url` - from relative, create absolute URL. Args: base_url (str): Domain with ``protocol://`` string rel...
if not rel_url: return None if not is_absolute_url(rel_url): rel_url = rel_url.replace("../", "/") if (not base_url.endswith("/")) and (not rel_url.startswith("/")): return base_url + "/" + rel_url.replace("../", "/") return base_url + rel_url.replace("../", "/") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_param(param): """ Generate function, which will check `param` is in html element. This function can be used as parameter for .find() method in HTMLElemen...
def has_param_closure(element): """ Look for `param` in `element`. """ if element.params.get(param, "").strip(): return True return False return has_param_closure
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def must_contain(tag_name, tag_content, container_tag_name): """ Generate function, which checks if given element contains `tag_name` with string content `tag_co...
def must_contain_closure(element): # containing in first level of childs <tag_name> tag matching_tags = element.match(tag_name, absolute=True) if not matching_tags: return False # which's content match `tag_content` if matching_tags[0].getContent() != tag_conten...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content_matchs(tag_content, content_transformer=None): """ Generate function, which checks whether the content of the tag matchs `tag_content`. Args: tag_con...
def content_matchs_closure(element): if not element.isTag(): return False cont = element.getContent() if content_transformer: cont = content_transformer(cont) return tag_content == cont return content_matchs_closure
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _removeSpecialCharacters(epub): """ Remove most of the unnecessary interpunction from epublication, which can break unimark if not used properly. """
special_chars = "/:,- " epub_dict = epub._asdict() for key in epub_dict.keys(): if isinstance(epub_dict[key], basestring): epub_dict[key] = epub_dict[key].strip(special_chars) elif type(epub_dict[key]) in [tuple, list]: out = [] for item in epub_dict[k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _import_epublication(self, epub): """ Fill internal property ._POST dictionary with data from EPublication. """
# mrs. Svobodová requires that annotation exported by us have this # prefix prefixed_annotation = ANNOTATION_PREFIX + epub.anotace self._POST["P0501010__a"] = epub.ISBN self._POST["P07012001_a"] = epub.nazev self._POST["P07032001_e"] = epub.podnazev self._POST["...
<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_mapping(self, mapping): """ Map some case specific data to the fields in internal dictionary. """
self._POST["P0100LDR__"] = mapping[0] self._POST["P0200FMT__"] = mapping[1] self._POST["P0300BAS__a"] = mapping[2] self._POST["P07022001_b"] = mapping[3] self._POST["P1501IST1_a"] = mapping[4]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _postprocess(self): """ Move data between internal fields, validate them and make sure, that everything is as it should be. """
# validate series ISBN self._POST["P0601010__a"] = self._validate_isbn( self._POST["P0601010__a"], accept_blank=True ) if self._POST["P0601010__a"] != "": self._POST["P0601010__b"] = "soubor : " + self._POST["P0601010__a"] # validate ISBN of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_required_fields(self): """ Make sure, that internal dictionary contains all fields, which are required by the webform. """
assert self._POST["P0501010__a"] != "", "ISBN is required!" # export script accepts only czech ISBNs for isbn_field_name in ("P0501010__a", "P1601ISB__a"): check = PostData._czech_isbn_check(self._POST[isbn_field_name]) assert check, "Only czech ISBN is accepted!" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_line(s, bold=False, underline=False, blinking=False, color=None, bgcolor=None, end='\n'): """ Prints a string with the given formatting. """
s = get_line(s, bold=bold, underline=underline, blinking=blinking, color=color, bgcolor=bgcolor) print(s, end=end)
<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_line(s, bold=False, underline=False, blinking=False, color=None, bgcolor=None, update_line=False): """ Returns a string with the given formatting. """
parts = [] if update_line: parts.append(_UPDATE_LINE) for val in [color, bgcolor]: if val: parts.append(val) if bold: parts.append(_TURN_BOLD_MODE_ON) if underline: parts.append(_TURN_UNDERLINE_MODE_ON) if blinking: parts.append(_TURN_BLINK...
<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_line(s, bold=False, underline=False, blinking=False, color=None, bgcolor=None): """ Overwrites the output of the current line and prints s on the same...
s = get_line(s, bold=bold, underline=underline, blinking=blinking, color=color, bgcolor=bgcolor, update_line=True) print(s, end='')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def path_list(self, sep=os.pathsep): ''' Return list of Path objects. ''' from pathlib import Path return [ Path(pathstr) for pathstr in self.split(sep) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filehandler(configurable): """Default logging file handler."""
filename = configurable.log_name.replace('.', sep) path = join(configurable.log_path, '{0}.log'.format(filename)) return FileHandler(path, mode='a+')