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 clistream(reporter, *args, **kwargs): """ Handle stream data on command line interface, and returns statistics of success, error, and total amount. More deta...
# Follow the rule of `parse_arguments()` files = kwargs.get('files') encoding = kwargs.get('input_encoding', DEFAULT_ENCODING) processes = kwargs.get('processes') chunksize = kwargs.get('chunksize') from clitool.processor import CliHandler, Streamer Handler = kwargs.get('Handler') if H...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def no_input(self): """Return whether the user wants to run in no-input mode. Enable this mode by adding a ``no-input`` option:: [zest.releaser] no-input = yes T...
default = False if self.config is None: return default try: result = self.config.getboolean('zest.releaser', 'no-input') except (NoSectionError, NoOptionError, ValueError): return default 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 distutils_servers(self): """Return a list of known distutils servers for collective.dist. If the config has an old pypi config, remove the default pypi serve...
if not multiple_pypi_support(): return [] try: raw_index_servers = self.config.get('distutils', 'index-servers') except (NoSectionError, NoOptionError): return [] ignore_servers = [''] if self.is_old_pypi_config(): # We have alread...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def want_release(self): """Does the user normally want to release this package. Some colleagues find it irritating to have to remember to answer the question "Ch...
default = True if self.config is None: return default try: result = self.config.getboolean('zest.releaser', 'release') except (NoSectionError, NoOptionError, ValueError): return default 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 transpose_mat44(src_mat, transpose_mat=None): """Create a transpose of a matrix."""
if not transpose_mat: transpose_mat = Matrix44() for i in range(4): for j in range(4): transpose_mat.data[i][j] = src_mat.data[j][i] return transpose_mat
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_affine_mat44(mat): """Return True if only tranlsate, rotate, and uniform scale components."""
# Ensure scale is uniform if not (mat.data[0][0] == mat.data[1][1] == mat.data[2][2]): return False # Ensure row [3] is 0, 0, 0, 1 return (mat.data[0][3] == 0 and mat.data[1][3] == 0 and mat.data[2][3] == 0 and mat.data[3][3] == 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 invert_affine_mat44(mat): """Assumes there is only rotate, translate, and uniform scale componenets to the matrix. """
inverted = Matrix44() # Transpose the 3x3 rotation component for i in range(3): for j in range(3): inverted.data[i][j] = mat.data[j][i] # Set translation: inverted_trans_vec3 = -inv(rot_mat33) * trans_vec3 for row in range(3): inverted.data[3][row] = ( -in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def almost_equal(self, mat2, places=7): """Return True if the values in mat2 equal the values in this matrix. """
if not hasattr(mat2, "data"): return False for i in range(4): if not (_float_almost_equal(self.data[i][0], mat2.data[i][0], places) and _float_almost_equal(self.data[i][1], mat2...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rot_from_vectors(start_vec, end_vec): """Return the rotation matrix to rotate from one vector to another."""
dot = start_vec.dot(end_vec) # TODO: check if dot is a valid number angle = math.acos(dot) # TODO: check if angle is a valid number cross = start_vec.cross(end_vec) cross.normalize rot_matrix = Matrix44.from_axis_angle(cross, angle) # TODO: catch except...
<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_trans(self, out_vec=None): """Return the translation portion of the matrix as a vector. If out_vec is provided, store in out_vec instead of creating a ne...
if out_vec: return out_vec.set(*self.data[3][:3]) return Vec3(*self.data[3][:3])
<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_trans(self, trans_vec): """Set the translation components of the matrix."""
# Column major, translation components in column 3. self.data[3][0] = trans_vec[0] self.data[3][1] = trans_vec[1] self.data[3][2] = trans_vec[2]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_running(self): """ True if the subprocess is running. If it's a zombie then we call :func:`desub.Desub.stop` to kill it with fire and return False. """
pp = self.pid if pp: try: proc = psutil.Process(pp) # Possible status: # "STATUS_RUNNING", "STATUS_IDLE", # "STATUS_SLEEPING", "STATUS_DISK_SLEEP", # "STATUS_STOPPED", "STATUS_TRACING_STOP", # "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pid(self): """ The integer PID of the subprocess or None. """
pf = self.path('cmd.pid') if not os.path.exists(pf): return None with open(pf, 'r') as f: return int(f.read())
<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): """Start the subprocess."""
c_out, c_err = (open(self.path('cmd.stdout'), 'w'), open(self.path('cmd.stderr'), 'w')) kw = self.kw.copy() kw['stdout'] = c_out kw['stderr'] = c_err if not kw.get('cwd', None): kw['cwd'] = os.getcwd() pr = subprocess.Popen(self.cmd_ar...
<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, timeout=15): """Stop the subprocess. Keyword Arguments **timeout** Time in seconds to wait for a process and its children to exit. """
pp = self.pid if pp: try: kill_process_nicely(pp, timeout=timeout) except psutil.NoSuchProcess: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_get_kb_by_type(kbtype): """Return a query to filter kb by type. :param kbtype: type to filter (e.g: taxonomy) :return: query to filter kb """
return models.KnwKB.query.filter_by( kbtype=models.KnwKB.KNWKB_TYPES[kbtype])
<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_kb_mapping(kb_name="", key="", value="", match_type="e", default="", limit=None): """Get one unique mapping. If not found, return default. :param kb_name...
mappings = get_kb_mappings(kb_name, key=key, value=value, match_type=match_type, limit=limit) if len(mappings) == 0: return default else: return mappings[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 add_kb_mapping(kb_name, key, value=""): """Add a new mapping to given kb. :param kb_name: the name of the kb where to insert the new value :param key: the ke...
kb = get_kb_by_name(kb_name) if key in kb.kbrvals: # update kb.kbrvals[key].m_value = value else: # insert kb.kbrvals.set(models.KnwKBRVAL(m_key=key, m_value=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 update_kb_mapping(kb_name, old_key, key, value): """Update an existing kb mapping with key old_key with a new key and value. :param kb_name: the name of the ...
db.session.query(models.KnwKBRVAL).join(models.KnwKB) \ .filter(models.KnwKB.name == kb_name, models.KnwKBRVAL.m_key == old_key) \ .update({"m_key": key, "m_value": value}, synchronize_session=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_kb(kb_name=u"Untitled", kb_type=None, tries=10): """Add a new kb in database, return the id. Add a new kb in database, and returns its id The name of the...
created = False name = kb_name i = 0 while(i < tries and created is False): try: kb = models.KnwKB(name=name, description="", kbtype=kb_type) created = True db.session.add(kb) db.session.commit() except IntegrityError: db.sessi...
<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_kb_dyn_config(kb_id, field, expression, collection=None): """Save a dynamic knowledge base configuration. :param kb_id: the id :param field: the field w...
# check that collection exists if collection: collection = Collection.query.filter_by(name=collection).one() kb = get_kb_by_id(kb_id) kb.set_dyn_config(field, expression, collection)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kb_mapping_exists(kb_name, key): """Return the information if a mapping exists. :param kb_name: knowledge base name :param key: left side (mapFrom) """
try: kb = get_kb_by_name(kb_name) except NoResultFound: return False return key in kb.kbrvals
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_kb(kb_name): """Delete given kb from database. :param kb_name: knowledge base name """
db.session.delete(models.KnwKB.query.filter_by( name=kb_name).one())
<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_kba_values(kb_name, searchname="", searchtype="s"): """Return an array of values "authority file" type = just values. :param kb_name: name of kb :param s...
if searchtype == 's' and searchname: searchname = '%'+searchname+'%' if searchtype == 'sw' and searchname: # startswith searchname = searchname+'%' if not searchname: searchname = '%' query = db.session.query(models.KnwKBRVAL).join(models.KnwKB) \ .filter(models.KnwKB...
<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_kbr_keys(kb_name, searchkey="", searchvalue="", searchtype='s'): """Return an array of keys. :param kb_name: the name of the knowledge base :param search...
if searchtype == 's' and searchkey: searchkey = '%'+searchkey+'%' if searchtype == 's' and searchvalue: searchvalue = '%'+searchvalue+'%' if searchtype == 'sw' and searchvalue: # startswith searchvalue = searchvalue+'%' if not searchvalue: searchvalue = '%' if not 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 get_kbr_values(kb_name, searchkey="", searchvalue="", searchtype='s', use_memoise=False): """Return a tuple of values from key-value mapping kb. :param kb_na...
try: if use_memoise: kb = get_kb_by_name_memoised(kb_name) else: kb = get_kb_by_name(kb_name) except NoResultFound: return [] return list(kb.get_kbr_values(searchkey, searchvalue, searchtype))
<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_kbr_items(kb_name, searchkey="", searchvalue="", searchtype='s'): """Return a list of dictionaries that match the search. :param kb_name: the name of the...
kb = get_kb_by_name(kb_name) return kb.get_kbr_items(searchkey, searchvalue, searchtype)
<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_kbd_values_json(kbname, searchwith=""): """Return values from searching a dynamic kb as a json-formatted string. This IS probably the method you want. :p...
res = get_kbd_values(kbname, searchwith) return json.dumps(res)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_kbt_items(taxonomyfilename, templatefilename, searchwith=""): """ Get items from taxonomy file using a templatefile. If searchwith is defined, return onl...
if processor_type == 1: # lxml doc = etree.XML(taxonomyfilename) styledoc = etree.XML(templatefilename) style = etree.XSLT(styledoc) result = style(doc) strres = str(result) del result del style del styledoc del doc elif processor_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_timestamp(dt): """Convert a datetime object to a unix timestamp. Note that unlike a typical unix timestamp, this is seconds since 1970 *local time*, not U...
if isinstance(dt, int): return dt return int(total_seconds(dt.replace(tzinfo=None) - datetime.datetime(1970, 1, 1)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_token(self, **kwargs): """Fetch a new token using the supplied code. :param str code: A previously obtained auth code. """
if 'client_secret' not in kwargs: kwargs.update(client_secret=self.client_secret) return self.session.fetch_token(token_url, **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 refresh_token(self, **kwargs): """Refresh the authentication token. :param str refresh_token: The refresh token to use. May be empty if retrieved with ``fetc...
if 'client_secret' not in kwargs: kwargs.update(client_secret=self.client_secret) if 'client_id' not in kwargs: kwargs.update(client_id=self.client_id) return self.session.refresh_token(token_url, **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 get_activity(self, id_num): """Return the activity with the given id. Note that this contains more detailed information than returned by `get_activities`. ""...
url = self._build_url('my', 'activities', id_num) return self._json(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_activities(self, count=10, since=None, style='summary', limit=None): """Iterate over all activities, from newest to oldest. :param count: The number of r...
params = {} if since: params.update(fromDate=to_timestamp(since)) parts = ['my', 'activities', 'search'] if style != 'summary': parts.append(style) url = self._build_url(*parts) # TODO: return an Activity (or ActivitySummary?) class that can do ...
<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_notables(self, id_num): """Return the notables of the activity with the given id. """
url = self._build_url('my', 'activities', id_num, 'notables') return self._json(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_polyline(self, id_num, style='google'): """Return the polyline of the activity with the given id. :param style: The type of polyline to return. May be on...
parts = ['my', 'activities', id_num, 'polyline'] if style != 'google': parts.append(style) url = self._build_url(*parts) return self._json(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_splits(self, id_num, unit='mi'): """Return the splits of the activity with the given id. :param unit: The unit to use for splits. May be one of 'mi' or '...
url = self._build_url('my', 'activities', id_num, 'splits', unit) return self._json(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_stats(self, year=None, month=None): """Return stats for the given year and month."""
parts = ['my', 'stats'] if month and not year: raise ValueError("month cannot be specified without year") if year: parts.append(year) if month: parts.append(year) url = self._build_url(*parts) return self._json(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 create_weight(self, weight, date=None): """Submit a new weight record. :param weight: The weight, in kilograms. :param date: The date the weight was recorded...
url = self._build_url('my', 'body', 'weight') data = {'weightInKilograms': weight} if date: if not date.is_aware(): raise ValueError("provided date is not timezone aware") data.update(date=date.isoformat()) headers = {'Content-Type': 'application/...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """press to continue"""
print('\n' + Fore.YELLOW + msg + Fore.RESET, end='') input()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allow_origin_tween_factory(handler, registry): """Allow cross origin XHR requests """
def allow_origin_tween(request): settings = request.registry.settings request_origin = request.headers.get('origin') def is_origin_allowed(origin): allowed_origins = ( request.registry.settings.get('api.allowed_origins', []) ) if isinstan...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, dbsecgroup_id, source_cidr, port=3306): """ Creates a security group rule. :param str dbsecgroup_id: The ID of the security group in which this ...
body = { "security_group_rule": { "security_group_id": dbsecgroup_id, "cidr": source_cidr, "from_port": port, "to_port": port, } } return self._create("/security-group-rul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def main(filename1, filename2, recursive=False, backup=False, suffix='~', *other_filenames): '''An example copy script with some example parameters that might be used in a file or directory copy command. :param recursive: -r --recursive copy directories recursively :param backup: -b --...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_date(my_date): """Parse a date into canonical format of datetime.dateime. :param my_date: Either datetime.datetime or string in '%Y-%m-%dT%H:%M:%SZ' fo...
if isinstance(my_date, datetime.datetime): result = my_date elif isinstance(my_date, str): result = datetime.datetime.strptime(my_date, '%Y-%m-%dT%H:%M:%SZ') else: raise ValueError('Unexpected date format for "%s" of type "%s"' % ( str(my_date...
<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_thread_info(self, enforce_re=True, latest_date=None): """Return a json list with information about threads in the group. :param enforce_re=True: Whether ...
result = [] my_re = re.compile(self.topic_re) url = '%s/issues?sort=updated' % (self.base_url) latest_date = self.parse_date(latest_date) if latest_date else None while url: kwargs = {} if not self.gh_info.user else {'auth': ( self.gh_info.user, 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 export(self, out_filename): """Export desired threads as a zipfile to out_filename. """
with zipfile.ZipFile(out_filename, 'w', zipfile.ZIP_DEFLATED) as arc: id_list = list(self.get_thread_info()) for num, my_info in enumerate(id_list): logging.info('Working on item %i : %s', num, my_info['number']) my_thread = GitHubCommentThread( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sleep_if_necessary(cls, user, token, endpoint='search', msg=''): """Sleep a little if hit github recently to honor rate limit. """
my_kw = {'auth': (user, token)} if user else {} info = requests.get('https://api.github.com/rate_limit', **my_kw) info_dict = info.json() remaining = info_dict['resources'][endpoint]['remaining'] logging.debug('Search remaining on github is at %s', remaining) if remaini...
<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_cache_key(cls, cache_key, item=None): """Get item in cache for cache_key and add item if item is not None. """
contents = cls.__thread_id_cache.get(cache_key, None) if item is not None: cls.__thread_id_cache[cache_key] = item return contents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_thread_id(self): """Lookup thread id as required by CommentThread.lookup_thread_id. This implementation will query GitHub with the required parameters...
query_string = 'in:title "%s" repo:%s/%s' % ( self.topic, self.owner, self.realm) cache_key = (self.owner, self.realm, self.topic) result = self.lookup_cache_key(cache_key) if result is not None: my_req = self.raw_pull(result) if my_req.status_code !...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw_search(cls, user, token, query, page=0): """Do a raw search for github issues. :arg user: Username to use in accessing github. :arg token: Token to use i...
page = int(page) kwargs = {} if not user else {'auth': (user, token)} my_url = cls.search_url data = {'items': []} while my_url: cls.sleep_if_necessary( user, token, msg='\nquery="%s"' % str(query)) my_req = requests.get(my_url, params={'q...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw_pull(self, topic): """Do a raw pull of data for given topic down from github. :arg topic: String topic (i.e., issue title). ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~...
assert topic is not None, 'A topic of None is not allowed' kwargs = {} if not self.user else {'auth': (self.user, self.token)} my_req = requests.get('%s/issues/%s' % ( self.base_url, topic), **kwargs) return my_req
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_comment_list(self): """Lookup list of comments for an issue. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: The pair (ISSUE, COMMENT...
if self.thread_id is None: return None, None # Just pulling a single issue here so pagination shouldn't be problem my_req = self.raw_pull(self.thread_id) if my_req.status_code != 200: raise GitHubAngry('Bad status code %s because %s' % ( my_req.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 add_comment(self, body, allow_create=False, allow_hashes=True, summary=None, hash_create=False): """Implement as required by CommentThread.add_comment. :arg ...
if self.thread_id is None: self.thread_id = self.lookup_thread_id() data = json.dumps({'body': body}) if self.thread_id is None: if allow_create: return self.create_thread(body) else: raise ValueError( 'Cann...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_hashes(self, body, allow_create=False): """Process any hashes mentioned and push them to related topics. :arg body: Body of the comment to check for ...
hash_re = re.compile(self.hashtag_re) hashes = hash_re.findall(body) done = {self.topic.lower(): True} for mention in hashes: mention = mention.strip('#') if mention.lower() in done: continue # Do not duplicate hash mentions new_threa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_attachment(self, location, data): """Upload attachment as required by CommentThread class. See CommentThread.upload_attachment for details. """
self.validate_attachment_location(location) content = data.read() if hasattr(data, 'read') else data orig_content = content if isinstance(content, bytes): content = base64.b64encode(orig_content).decode('ascii') else: pass # Should be base64 encoded alre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reconnect(self): """Closes the existing database connection and re-opens it."""
self.close() self._db = psycopg2.connect(**self._db_args) if self._search_path: self.execute('set search_path=%s;' % self._search_path) if self._timezone: self.execute("set timezone='%s';" % self._timezone)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reregister_types(self): """Registers existing types for a new connection"""
for _type in self._register_types: psycopg2.extensions.register_type(psycopg2.extensions.new_type(*_type))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_type(self, oids, name, casting): """Callback to register data types when reconnect """
assert type(oids) is tuple assert isinstance(name, basestring) assert hasattr(casting, '__call__') self._register_types.append((oids, name, casting)) psycopg2.extensions.register_type(psycopg2.extensions.new_type(oids, name, casting))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query(self, query, *parameters, **kwargs): """Returns a row list for the given query and parameters."""
cursor = self._cursor() try: self._execute(cursor, query, parameters or None, kwargs) if cursor.description: column_names = [column.name for column in cursor.description] res = [Row(zip(column_names, row)) for row in cursor.fetchall()] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter(self, query, *parameters, **kwargs): """Returns a generator for records from the query."""
cursor = self._cursor() try: self._execute(cursor, query, parameters or None, kwargs) if cursor.description: column_names = [column.name for column in cursor.description] while True: record = cursor.fetchone() ...
<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, query, *parameters, **kwargs): """Same as query, but do not process results. Always returns `None`."""
cursor = self._cursor() try: self._execute(cursor, query, parameters, kwargs) except: raise finally: cursor.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, query, *parameters, **kwargs): """Returns the first row returned for the given query."""
rows = self.query(query, *parameters, **kwargs) if not rows: return None elif len(rows) > 1: raise ValueError('Multiple rows returned for get() query') else: return rows[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 executemany(self, query, *parameters): """Executes the given query against all the given param sequences. """
cursor = self._cursor() try: self._executemany(cursor, query, parameters) if cursor.description: column_names = [column.name for column in cursor.description] res = [Row(zip(column_names, row)) for row in cursor.fetchall()] cursor....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(): """Install your package to all Python version you have installed on Windows. """
import os, shutil _ROOT = os.getcwd() _PACKAGE_NAME = os.path.basename(_ROOT) print("Installing [%s] to all python version..." % _PACKAGE_NAME) # find all Python release installed on this windows computer installed_python_version = list() for root, folder_list, _ in os.walk(r"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 namedtuple_asdict(obj): """ Serializing a nested namedtuple into a Python dict """
if obj is None: return obj if hasattr(obj, "_asdict"): # detect namedtuple return OrderedDict(zip(obj._fields, (namedtuple_asdict(item) for item in obj))) if isinstance(obj, str): # iterables - strings return obj if hasattr(obj, "ke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(cls, json_dump): """ How to get a context from a json dump """
context = cls() if json_dump is None: return None ctxt = json.loads(json_dump) for k in ctxt: context[k] = ctxt[k] return context
<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_tendril(cls, proto, addr): """ Finds the tendril corresponding to the protocol and address tuple. Returns the Tendril object, or raises KeyError if the ...
# First, normalize the proto proto = proto.lower() # Now, find and return the tendril return cls._tendrils[proto][addr]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _track_tendril(self, tendril): """ Adds the tendril to the set of tracked tendrils. """
self.tendrils[tendril._tendril_key] = tendril # Also add to _tendrils self._tendrils.setdefault(tendril.proto, weakref.WeakValueDictionary()) self._tendrils[tendril.proto][tendril._tendril_key] = tendril
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _untrack_tendril(self, tendril): """ Removes the tendril from the set of tracked tendrils. """
try: del self.tendrils[tendril._tendril_key] except KeyError: pass # Also remove from _tendrils try: del self._tendrils[tendril.proto][tendril._tendril_key] except KeyError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_local_addr(self, timeout=None): """ Retrieve the current local address. :param timeout: If not given or given as ``None``, waits until the local address ...
# If we're not running, just return None if not self.running: return None # OK, we're running; wait on the _local_addr_event if not self._local_addr_event.wait(timeout): # Still not set after timeout return None # We have a local address! ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, target, acceptor, wrapper=None): """ Initiate a connection from the tendril manager's endpoint. Once the connection is completed, a Tendril obj...
if not self.running: raise ValueError("TendrilManager not running") # Check the target address fam = utils.addr_info(target) # Verify that we're in the right family if self.addr_family != fam: raise ValueError("address family mismatch")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, *args, **kwargs): """Reads the node as a file """
with self.open('r') as f: return f.read(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ls(self): """List the children entities of the directory. Raises exception if the object is a file. :return: """
if self.isfile(): raise NotDirectoryError('Cannot ls() on non-directory node: {path}'.format(path=self._pyerarchy_path)) return os.listdir(self._pyerarchy_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkdir(self, children, mode=0o0755, return_node=True): """Creates child entities in directory. Raises exception if the object is a file. :param children: The ...
result = None if isinstance(children, (str, unicode)): if os.path.isabs(children): raise BadValueError('Cannot mkdir an absolute path: {path}'.format(path=self._pyerarchy_path)) rel_path = os.path.join(self._pyerarchy_path, children) os.makedirs(rel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capitalize( full_name, articles=None, separator_characters=None, ignore_worls=None, ): """Returns the correct writing of a compound name, respecting the firs...
if articles is None: articles = _ARTICLES if separator_characters is None: separator_characters = _SEPARATOR_CHARACTERS if ignore_worls is None: ignore_worls = _IGNORE_WORLS new_full_name = full_name if hasattr(new_full_name, 'strip'): new_full_name = new_full_name.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 deep_unicode(s, encodings=None): """decode "DEEP" S using the codec registered for encoding."""
if encodings is None: encodings = ['utf-8', 'latin-1'] if isinstance(s, (list, tuple)): return [deep_unicode(i) for i in s] if isinstance(s, dict): return dict([ (deep_unicode(key), deep_unicode(s[key])) for key in s ]) # in_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 deep_encode(s, encoding='utf-8', errors='strict'): """Encode "DEEP" S using the codec registered for encoding."""
# encoding defaults to the default encoding. errors may be given to set # a different error handling scheme. Default is 'strict' meaning # that encoding errors raise # a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and # 'xmlcharrefreplace' as well as any other name registered ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def namespace(self, key, glob=False): """Return a namespace for keyring"""
if not self.name: self.name = os.environ['DJANGO_SETTINGS_MODULE'] ns = '.'.join([key, self._glob]) if glob else '.'.join([self.name, self._glob]) return ns
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, prompt_default='', prompt_help=''): """Return a value from the environ or keyring"""
value = os.getenv(key) if not value: ns = self.namespace(key) value = self.keyring.get_password(ns, key) else: ns = 'environ' if not value: ns = self.namespace(key, glob=True) value = self.keyring.get_password(ns, 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 set(self, key, value, glob=False): """Set the key value pair in a local or global namespace"""
ns = self.namespace(key, glob) self.keyring.set_password(ns, 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 remove(self, key, glob=False): """Remove key value pair in a local or global namespace."""
ns = self.namespace(key, glob) try: self.keyring.delete_password(ns, key) except PasswordDeleteError: # OSX and gnome have no delete method self.set(key, '', glob)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, prompt_default='', prompt_help=''): """ Return the value for key from the environment or keyring. The keyring value is resolved from a local n...
value = super(DjSecret, self).get(key, prompt_default, prompt_help='') if not value and self.raise_on_none: error_msg = "The %s setting is undefined in the environment and djset %s" % (key, self._glob) raise self.raise_on_none(error_msg) return 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 draw(self): """Draws the button in its current state. Should be called every time through the main loop """
if not self.visible: return # Blit the button's current appearance to the surface. if self.isEnabled: if self.mouseIsDown: if self.mouseOverButton and self.lastMouseDownOverButton: self.window.blit(self.surfaceDown, self.loc) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _debug(self): """This is just for debugging, so we can see what buttons would be drawn. Not intended to be used in production."""
self.window.blit(self.surfaceUp, (self.loc[0], 10)) self.window.blit(self.surfaceOver, (self.loc[0], 60)) self.window.blit(self.surfaceDown, (self.loc[0], 110)) self.window.blit(self.surfaceDisabled, (self.loc[0], 160))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self): """Draws the checkbox."""
if not self.visible: return # Blit the current checkbox's image. if self.isEnabled: if self.mouseIsDown and self.lastMouseDownOverButton and self.mouseOverButton: if self.value: self.window.blit(self.surfaceOnDown, self.loc)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getSelectedRadioButton(self): """Returns the nickname of the currently selected radio button."""
radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group] for radioButton in radioButtonListInGroup: if radioButton.getValue(): selectedNickname = radioButton.getNickname() return selectedNickname ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enableGroup(self): """Enables all radio buttons in the group."""
radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group] for radioButton in radioButtonListInGroup: radioButton.enable()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disableGroup(self): """Disables all radio buttons in the group"""
radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group] for radioButton in radioButtonListInGroup: radioButton.disable()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self): """Draws the current text in the window"""
if not self.visible: return self.window.blit(self.textImage, self.loc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _updateImage(self): """Internal method to render text as an image."""
# Fill the background of the image if self.backgroundColor is not None: self.textImage.fill(self.backgroundColor) # Render the text as a single line, and blit it onto the textImage surface if self.mask is None: lineSurface = self.font.render(self.text, Tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self): """Draws the Text in the window."""
if not self.visible: return # If this input text has focus, draw an outline around the text image if self.focus: pygame.draw.rect(self.window, self.focusColor, self.focusedImageRect, 1) # Blit in the image of text (set earlier in _updateImage) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setValue(self, newText): """Sets new text into the field"""
self.text = newText self.cursorPosition = len(self.text) self._updateImage()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clearText(self, keepFocus=False): """Clear the text in the field"""
self.text = '' self.focus = keepFocus self._updateImage()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resetToPreviousLoc(self): """Resets the loc of the dragger to place where dragging started. This could be used in a test situation if the dragger was dra...
self.rect.left = self.startDraggingX self.rect.top = self.startDraggingY
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self): """Draws the dragger at the current mouse location. Should be called in every frame. """
if not self.visible: return if self.isEnabled: # Draw the dragger's current appearance to the window. if self.dragging: self.window.blit(self.surfaceDown, self.rect) else: # mouse is up if self.mouseOve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flipHorizontal(self): """ flips an image object horizontally """
self.flipH = not self.flipH self._transmogrophy(self.angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flipVertical(self): """ flips an image object vertically """
self.flipV = not self.flipV self._transmogrophy(self.angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _transmogrophy(self, angle, percent, scaleFromCenter, flipH, flipV): ''' Internal method to scale and rotate ''' self.angle = angle % 360 self.percent = percent self.scaleFromCenter = scaleFromCenter previousRect = self.rect previousCente...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self): """Draws the image at the given location."""
if not self.visible: return self.window.blit(self.image, self.loc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play(self): """Starts an animation playing."""
if self.state == PygAnimation.PLAYING: pass # nothing to do elif self.state == PygAnimation.STOPPED: # restart from beginning of animation self.index = 0 # first image in list self.elapsed = 0 self.playingStartTime = time.time() se...