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 ValueError("A path must be a string, tuple or list")
<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 == "merge": return merge(parent, idx, patch.value) elif op == "copy": sparent, sidx = resolve_path(document, patch.src) return copy(sparent, sidx, parent, idx) elif op == "move": sparent, sidx = resolve_path(document, patch.src) return move(sparent, sidx, parent, idx) elif op == "test": return test(parent, idx, patch.value) elif op == "setremove": return set_remove(parent, idx, patch.value) elif op == "setadd": return set_add(parent, idx, patch.value) else: raise JSONPatchError("Invalid operator")
<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}: {1}".format(i + 1, ex)) from ex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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(pattern.format(option))
<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: self._data = sorted(self._data, key=lambda k: k[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 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: The numerical y value of the data point to be removed. :raises ValueError: if you try to remove the last data point from\ a series."""
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 else None try: git_version = subprocess.check_output(['git', 'describe', '--dirty']) except: if __version__ is None: raise ValueError("cannot determine version number") return __version__ m = re.match(r'^\s*' r'(?P<version>\S+?)' r'(-(?P<post>\d+)-(?P<commit>g[0-9a-f]+))?' r'(-(?P<dirty>dirty))?' r'\s*$', git_version.decode()) if not m: raise ValueError("cannot parse git describe output") git_version = m.group('version') post = m.group('post') commit = m.group('commit') dirty = m.group('dirty') local = [] if post: post = int(post) if post: git_version += '.post%d' % (post,) if commit: local.append(commit) if dirty: local.append(dirty) if local: git_version += '+' + '.'.join(local) if git_version != __version__: with open('eztemplate/version.py', 'w') as f: f.write("__version__ = %r\n" % (str(git_version),)) return git_version
<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', 'rst', ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, ) except OSError as e: if e.errno == errno.ENOENT: return None raise description, __ = process.communicate(input=description) if process.poll() is None: process.kill() raise Exception("pandoc did not terminate") if process.poll(): raise Exception("pandoc terminated abnormally") return description
<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: print >> stream, json.dumps(list_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 _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('PUSHER_PORT')) sd('cluster', conf.get('PUSHER_CLUSTER')) sd('backend', conf.get('PUSHER_BACKEND')) sd('json_encoder', (conf.get('PUSHER_JSON_ENCODER') or app.json_encoder)) sd('json_decoder', (conf.get('PUSHER_JSON_DECODER') or app.json_decoder)) if conf.get('PUSHER_TIMEOUT'): sd('timeout', conf.get('PUSHER_TIMEOUT')) super(Pusher, self).__init__(**options) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['pusher'] = 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 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 or 'seconds' in args: try: if 'minutes' in args: self.pause_type = 'minutes' # The time() command operates in seconds so we need to # recalculate for minutes=X values. self.seconds = int(args['minutes']) * 60 else: self.pause_type = 'seconds' self.seconds = int(args['seconds']) self.duration_unit = 'seconds' except ValueError, e: raise ae("non-integer value given for prompt duration:\n%s" % str(e)) # Is 'prompt' a key in 'args'? elif 'prompt' in args: self.pause_type = 'prompt' self.prompt = "[%s]\n%s: " % (hosts, args['prompt']) # Is 'args' empty, then this is the default prompted pause elif len(args.keys()) == 0: self.pause_type = 'prompt' self.prompt = "[%s]\nPress enter to continue: " % hosts # I have no idea what you're trying to do. But it's so wrong. else: raise ae("invalid pause type given. must be one of: %s" % \ ", ".join(self.PAUSE_TYPES)) vv("created 'pause' ActionModule: pause_type=%s, duration_unit=%s, calculated_seconds=%s, prompt=%s" % \ (self.pause_type, self.duration_unit, self.seconds, self.prompt)) ######################################################################## # Begin the hard work! try: self._start() if not self.pause_type == 'prompt': print "[%s]\nPausing for %s seconds" % (hosts, self.seconds) time.sleep(self.seconds) else: # Clear out any unflushed buffered input which would # otherwise be consumed by raw_input() prematurely. tcflush(sys.stdin, TCIFLUSH) raw_input(self.prompt) except KeyboardInterrupt: while True: print '\nAction? (a)bort/(c)ontinue: ' c = getch() if c == 'c': # continue playbook evaluation break elif c == 'a': # abort further playbook evaluation raise ae('user requested abort!') finally: self._stop() return ReturnData(conn=conn, result=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 _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 == 'minutes': duration = round(duration / 60.0, 2) else: duration = round(duration, 2) self.result['stdout'] = "Paused for %s %s" % (duration, self.duration_unit)
<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 the data returned in one page from SpaceGDN. If this method is called before, data will be appended to the existing data with `+=`, this means dicts, for instance will not work with multiple pages. Arguments: `data` The data to add `status_code` The HTTP response code of the HTTP response containing the data `status_reason` The reason or description for the HTTP response code """
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}') ''' text = _prepare(text) print('{}{}'.format(text.format(**styles).replace(styles['END'], styles['ALL_OFF']), styles['ALL_OFF']))
<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. root (obj): Root of the `DOM`. Returns: list: ``[PathCall()]`` - list with one :class:`PathCall` object (to \ allow use with ``.extend(predecesors_pattern())``). """
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.params) ], [ element.parent.getTagName(), _params_or_none(element.parent.params) ], [element.getTagName(), _params_or_none(element.params)], ] match = root.match(*trail) if element in match: return [ PathCall("match", match.index(element), trail) ]
<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. ''' documents_url = urljoin(self.base_url, self.DOCUMENTS_PAGE) data = {"corpus": self.url} files = {"blob": document} result = self.session.post(documents_url, data=data, files=files) if result.status_code == 201: return Document(session=self.session, **result.json()) else: raise RuntimeError("Document creation failed with status " "{}. The response was: '{}'".format(result.status_code, result.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 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. ''' result, errors = [], [] for document in documents: try: result.append(self.add_document(document)) except RuntimeError as exc: errors.append((document, exc)) return result, errors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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(session=self.session, **result.json()) else: raise RuntimeError("Corpus creation failed with status " "{}. The response was: '{}'".format(result.status_code, result.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 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 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 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 inserted_primary_key? #node_id = result.inserted_primary_key node_id = result.lastrowid if (not node_id): result = result.fetchall() node_id = result[0]['id'] return node_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 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')), name=name, node_id=node_id).fetchall() if result: template_id = result[0]['id'] db.execute(text(fetch_query_string('update_template_node.sql')), template=template_id, node_id=node_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 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 Node table. """
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['query_id'] = result.lastrowid if (not kw['query_id']): result = result.fetchall() kw['query_id'] = result[0]['id'] db.execute(text(fetch_query_string('insert_query_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 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 get method, as it does not exist in the View base class and child mixins implementing get do not call super().get """
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 or referrer is None or self.return_url is None and 'return_url' in request.GET): return super().dispatch(request, *args, **kwargs) if not self.return_url: url = request.get_full_path() if url.find("?") < 0: url = "?return_url=".join((url, referrer)) else: url = "&return_url=".join((url, referrer)) return HttpResponseRedirect(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 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 -- identifiable key, that you use later to retrieve that piece of data kwargs -- the data you need to store """
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 %s" % (k, node['host_name']), level="notice") json_params[k] = v return node.send_command('info', 'post', node_name=node.token, key="node_info", **my_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 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 break container.Destroy() return obj
<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.pointer] = self.MIN_CELL_SIZE else: # increment it self.tape[self.pointer] += 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 _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.tape[self.pointer] = self.MAX_CELL_SIZE else: # decrement it self.tape[self.pointer] -= 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 _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 the form field widgets. """
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), ", ".join(words)) return ("", "")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 keyword. """
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 += mark_safe("<p class='keywords-field'>%s</p>" % links) return 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 = self.data.get("replied_to") # YaCms's duplicate check that also checks `replied_to_id`. lookup = { "content_type": comment.content_type, "object_pk": comment.object_pk, "user_name": comment.user_name, "user_email": comment.user_email, "user_url": comment.user_url, "replied_to_id": comment.replied_to_id, } for duplicate in self.get_comment_model().objects.filter(**lookup): if (duplicate.submit_date.date() == comment.submit_date.date() and duplicate.comment == comment.comment): return duplicate comment.save() comment_was_posted.send(sender=comment.__class__, comment=comment, request=request) notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS) if notify_emails: subject = ugettext("New comment for: ") + str(obj) context = { "comment": comment, "comment_url": add_cache_bypass(comment.get_absolute_url()), "request": request, "obj": obj, } send_mail_template(subject, "email/comment_notification", settings.DEFAULT_FROM_EMAIL, notify_emails, context) return comment
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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_authenticated(): raise forms.ValidationError(ugettext("Already rated.")) return self.cleaned_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 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}) if not created: if rating_instance.value == int(rating_value): # User submitted the same rating as previously, # which we treat as undoing the rating (like a toggle). rating_instance.delete() self.undoing = True else: rating_instance.value = rating_value rating_instance.save() else: rating_instance = manager.create(value=rating_value) return rating_instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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") if local_drill is not None: _drill = _str2bool(local_drill) # now that everything is ready attach the hook sys.excepthook = _excepthook
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 YAML config file first """ value = os.getenv('PYLOGCONF_YAML', None) if value is None: path = default_path_yaml else: path = value if os.path.isfile(path): _debug('found logging configuration file [{0}]...'.format(path), dbg) with open(path) as f: config = yaml.load(f.read()) logging.config.dictConfig(config) return """ Now try regular config file """ value = os.getenv('PYLOGCONF_CONF', None) if value is None: path = default_path_conf else: path = value if os.path.isfile(path): _debug('found logging configuration file [{0}]...'.format(path), dbg) logging.config.fileConfig(path) return _debug('logging with level [{0}]...'.format(default_level), dbg) logging.basicConfig(level=default_level)
<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 (longer distance) :type curve1: sastool.classes.curve.GeneralCurve :param curve2: the second curve (shorter distance) :type curve2: sastool.classes.curve.GeneralCurve :param qmin: lower bound of the interval for determining the scaling factor :type qmin: float :param qmax: upper bound of the interval for determining the scaling factor :type qmax: float :param qsep: separating (tailoring) point for the merge :type qsep: float :return: merged_curve, factor, background, stat :rtype tuple of a sastool.classes2.curve.Curve and a float """
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 = curve2.interpolate(curve1_interp.q) if use_additive_constant: bg_init = 0 else: bg_init = FixedParameter(0) factor, bg, stat = nonlinear_odr(curve2_interp.Intensity, curve1_interp.Intensity, curve2_interp.Error, curve1_interp.Error, lambda x, factor, bg: x * factor + bg, [1.0, bg_init]) return Curve.merge(curve1 - bg, curve2 * factor, qsep), factor, bg, stat
<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, string_types): pass else: raise if isinstance(obj, string_types): sha.update(obj) elif hasattr(obj, 'read'): while True: d = obj.read(8192) if not d: break sha.update(d) else: return None r = sha.digest() r = base64.b64encode(r) return r
<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 enumerate(month_dicts): month_dicts[i]["post_count"] = date_dicts.count(date_dict) return month_dicts
<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 slug, category title or slug or author's username can also be specified to filter the recent posts returned. Usage:: {% blog_recent_posts 5 as recent_posts %} {% blog_recent_posts limit=5 tag="django" as recent_posts %} {% blog_recent_posts limit=5 category="python" as recent_posts %} {% blog_recent_posts 5 username=admin as recent_posts %} """
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: return [] if category is not None: try: category = BlogCategory.objects.get(title_or_slug(category)) blog_posts = blog_posts.filter(categories=category) except BlogCategory.DoesNotExist: return [] if username is not None: try: author = User.objects.get(username=username) blog_posts = blog_posts.filter(user=author) except User.DoesNotExist: return [] return list(blog_posts[:limit])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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: raise Exception('InvalidEmitLevel: %s' % level)
<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.action.startswith('news-'): broadcast(request.get_json()) """
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(SITECFG) f.close() try: os.mkdir('queries') except OSError: pass try: os.mkdir('templates') except OSError: pass htmlfile = os.path.join('templates', 'homepage.html') if not os.path.exists(htmlfile): f = open(htmlfile, 'w') f.write(""" <!doctype html> <html> <head> <title>Chill</title> </head> <body> <p>{{ homepage_content }}</p> </body> </html> """
) 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_from_node.sql', node_id=homepage) add_template_for_node('homepage.html', homepage) homepage_content = insert_node(name='homepage_content', value="Cascading, Highly Irrelevant, Lost Llamas") insert_node_node(node_id=homepage, target_node_id=homepage_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 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.DataFrame A string with a German formated date, or an array of these strings, e.g. list, ndarray, df. Returns ------- y : str, list, tuple, numpy.ndarray, pandas.DataFrame A datetime object or array of datetime objects. Example ------- The function aims to convert a string as follows '23.09.2012' => datetime(2012, 9, 23, 0, 0) Code Example print(clean_german_date('23.09.2012')) Behavior -------- - If it is not a string with date format 'DD.MM.YYYY' then None is returned """
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 proc_ndarray(x): tmp = proc_list(list(x.reshape((x.size,)))) return np.array(tmp).reshape(x.shape) # transform string, list/tuple, numpy array, pandas dataframe if isinstance(x, str): return proc_elem(x) elif isinstance(x, (list, tuple)): return proc_list(x) elif isinstance(x, np.ndarray): return proc_ndarray(x) elif isinstance(x, pd.DataFrame): return pd.DataFrame(proc_ndarray(x.values), columns=x.columns, index=x.index) else: 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 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. This function returns the MRO which K would have, *excluding* K itself (since it doesn't yet exist), as if you had actually created the class. Another way of looking at this, if you pass a single class K, this will return the linearization of K (the MRO of K, *including* itself). Found at: http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/ """
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. candidate = seq[0] not_head = [s for s in non_empty if candidate in s[1:]] if not_head: # Reject the candidate. candidate = None else: break if not candidate: raise TypeError("inconsistent hierarchy, no C3 MRO is possible") res.append(candidate) for seq in non_empty: # Remove candidate. if seq[0] == candidate: del seq[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 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 unchanged."""
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 prefix. This is prepended to the base type name. This convention is baked in for API consistency. @param base: The base type to derive from. @param blockednames: A list of method name strings. All of these will be blocked. @param clsdict: None or a dict which will be modified to become the subtype class dict. @return: The new subtype. @raise: OverwriteError - If clsdict contains an entry in blockednames. """
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(blockednames), ) for bname in blockednames: setitem_without_overwrite( clsdict, bname, ConstraintError.block(getattr(base, bname)), ) return type(name, (base,), clsdict)
<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: The implementation is derived from collections.MutableMapping.update. """
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"): for key in other.keys(): setitem_without_overwrite(d, key, other[key]) else: for key, value in other: setitem_without_overwrite(d, key, value) for key, value in kwds.items(): setitem_without_overwrite(d, key, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 processing. - ``title`` and ``content`` are strings for the post. - ``old_url`` is a string that a redirect will be created for. - ``pub_date`` is assumed to be a ``datetime`` object. - ``tags`` and ``categories`` are sequences of strings. - ``comments`` is a sequence of dicts - each dict should be the return value of ``add_comment``. """
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({ "title": force_text(title), "publish_date": pub_date, "content": force_text(content), "categories": categories, "tags": tags, "comments": comments, "old_url": old_url, }) return self.posts[-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 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 - used by the Wordpress importer. """
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": old_url, "old_id": old_id, "old_parent_id": old_parent_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 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": website, "comment": body, })
<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] continue while len(value) > max_length: encoded_value = value.encode("utf-8") new_value = input("The value for the field %s.%s exceeds " "its maximum length of %s chars: %s\n\nEnter a new value " "for it, or press return to have it truncated: " % (model.__name__, field_name, max_length, encoded_value)) value = new_value if new_value else value[:max_length] fields[field_name] = value return fields
<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 old_url is not None: old_path = urlparse(old_url).path if not old_path.strip("/"): return redirect = self.trunc(Redirect, prompt, old_path=old_path) redirect['site'] = Site.objects.get_current() redirect, created = Redirect.objects.get_or_create(**redirect) redirect.new_path = obj.get_absolute_url() redirect.save() if created and verbosity >= 1: print("Created redirect for: %s" % 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 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 returned. This differs from Django's standard behavior - the default behavior is to return the parent ContentType for proxy models. """
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=model._meta.app_label, model=model._meta.object_name.lower()) else: return ContentType.objects.get_for_model(model)
<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 first element is blank. Args: el_list (list): List of HTMLElement objects. alt (default None): Value returner when list or content is blank. strip (bool, default True): Call .strip() to content. Returns: str or alt: String representation of the content of the first element \ or `alt` if not found. """
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_url (str): Relative or absolute url. Returns: str/None: Normalized URL or None if `url` is blank. """
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("../", "/") return rel_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 has_param(param): """ Generate function, which will check `param` is in html element. This function can be used as parameter for .find() method in HTMLElement. """
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_content` and also another tag named `container_tag_name`. This function can be used as parameter for .find() method in HTMLElement. """
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_content: return False # and also contains <container_tag_name> tag if container_tag_name and \ not element.match(container_tag_name, absolute=True): return False return True return must_contain_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 content_matchs(tag_content, content_transformer=None): """ Generate function, which checks whether the content of the tag matchs `tag_content`. Args: tag_content (str): Content of the tag which will be matched thru whole DOM. content_transformer (fn, default None): Function used to transform all tags before matching. This function can be used as parameter for .find() method in HTMLElement. """
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[key]: if not isinstance(item, Author): out.append(item) continue new_item = item._asdict() for key in new_item.keys(): new_item[key] = new_item[key].strip(special_chars) out.append(Author(**new_item)) epub_dict[key] = out return EPublication(**epub_dict)
<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["P0502010__b"] = epub.vazba self._POST["P0504010__d"] = epub.cena self._POST["P07042001_h"] = epub.castDil self._POST["P07052001_i"] = epub.nazevCasti self._POST["P0902210__c"] = epub.nakladatelVydavatel self._POST["P0903210__d"] = epub.datumVydani self._POST["P0801205__a"] = epub.poradiVydani self._POST["P1502IST1_b"] = epub.zpracovatelZaznamu self._POST["P0503010__x"] = epub.format self._POST["P110185640u"] = epub.url or "" self._POST["P0901210__a"] = epub.mistoVydani self._POST["P0601010__a"] = epub.ISBNSouboruPublikaci self._POST["P1801URL__u"] = epub.internal_url self._POST["P1001330__a"] = prefixed_annotation if epub.anotace else "" if len(epub.autori) > 3: epub.autori[2] = ", ".join(epub.autori[2:]) epub.autori = epub.autori[:3] # check whether the autors have required type (string) for author in epub.autori: error_msg = "Bad type of author (%s) (str is required)." assert isinstance(author, basestring), (error_msg % type(author)) authors_fields = ("P1301ZAK__b", "P1302ZAK__c", "P1303ZAK__c") self._POST.update(dict(zip(authors_fields, epub.autori)))
<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 the book self._POST["P0501010__a"] = self._validate_isbn( self._POST["P0501010__a"], accept_blank=False ) self._POST["P1601ISB__a"] = self._POST["P0501010__a"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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!" assert self._POST["P1601ISB__a"] != "", "Hidden ISBN field is required!" assert self._POST["P07012001_a"] != "", "Nazev is required!" assert self._POST["P0901210__a"] != "", "Místo vydání is required!" assert self._POST["P0903210__d"] != "", "Datum vydání is required!" assert self._POST["P0801205__a"] != "", "Pořadí vydání is required!" # Zpracovatel záznamu assert self._POST["P1501IST1_a"] != "", "Zpracovatel is required! (H)" assert self._POST["P1502IST1_b"] != "", "Zpracovatel is required! (V)" # vazba/forma assert self._POST["P0502010__b"] != "", "Vazba/forma is required!" # assert self._POST["P110185640u"] != "", "URL is required!" # Formát (pouze pro epublikace) if self._POST["P0502010__b"] == FormatEnum.ONLINE: assert self._POST["P0503010__x"] != "", "Format is required!" assert self._POST["P0902210__c"] != "", "Nakladatel is required!" def to_unicode(inp): try: return unicode(inp) except UnicodeDecodeError: return unicode(inp, "utf-8") # check lenght of annotation field - try to convert string to unicode, # to count characters, not combination bytes annotation_length = len(to_unicode(self._POST["P1001330__a"])) annotation_length -= len(to_unicode(ANNOTATION_PREFIX)) assert annotation_length <= 500, "Annotation is too long (> 500)."
<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_BLINKING_MODE_ON) parts.append(s) parts.append(_TURN_OFF_CHARACTER_ATTS) result = ''.join(parts) 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 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 line without a new line. """
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+')