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 view_path(self): """ It returns view's view path """
if self.scheme_name is None or self.scheme_name == "": return self.view.view_path else: return self.scheme_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_absolute_url(self): """ It returns absolute url defined by node related to this page """
try: node = Node.objects.select_related().filter(page=self)[0] return node.get_absolute_url() except Exception, e: raise ValueError(u"Error in {0}.{1}: {2}".format(self.__module__, self.__class__.__name__, e)) return u""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_static_vars(self, node): """ This function check if a Page has static vars """
if self.static_vars == "" and hasattr(self, "template"): self.static_vars = { 'upy_context': { 'template_name': u"{}/{}".format(self.template.app_name, self.template.file_name) } } elif hasattr(self, "template"): se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rehash(self): """ Rehashes the IRCd's configuration file. """
with self.lock: self.send('REHASH') if self.readable(): msg = self._recv(expected_replies=('382',)) if msg[0] == '382': 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 generate_token(self): """Make request in API to generate a token."""
response = self._make_request() self.auth = response self.token = response['token']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linreg_ols_svd(y, X, rcond=1e-15): """Linear Regression, OLS, inv by SVD Properties * Numpy's lstsq is based on LAPACK's _gelsd what applies SVD * SVD invers...
import numpy as np try: # solve OLS formula beta, _, _, singu = np.linalg.lstsq(b=y, a=X, rcond=rcond) except np.linalg.LinAlgError: print("LinAlgError: computation does not converge.") return None # check singu if np.any(singu < 0.0): print("Error: A singular valu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genrepl(scope): """Replacement function with specific scope."""
def repl(match): """Internal replacement function.""" name = match.group('name') value = lookup(name, scope=scope) result = name.replace('.', '_') scope[result] = value return result return repl
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def image(radar, at=None): '''Retrieve a radar image. :param radar: radar station no. :param at: stat datetime, defaults to now. ''' at = round_to_5_minutes(at or datetime.utcnow()) return ''.join([ 'http://image.nmc.cn/product', '/{0}'.format(at.year), '/{0}'.format(at...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pickle_compress(obj, print_compression_info=False): """pickle and compress an object"""
p = pickle.dumps(obj) c = zlib.compress(p) if print_compression_info: print ("len = {:,d} compr={:,d} ratio:{:.6f}".format(len(p), len(c), float(len(c))/len(p))) return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_devicelist(home_hub_ip='192.168.1.254'): """Retrieve data from BT Home Hub 5 and return parsed result. """
url = 'http://{}/'.format(home_hub_ip) try: response = requests.get(url, timeout=5) except requests.exceptions.Timeout: _LOGGER.exception("Connection to the router timed out") return if response.status_code == 200: return parse_devicelist(response.text) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_devicelist(data_str): """Parse the BT Home Hub 5 data format."""
p = HTMLTableParser() p.feed(data_str) known_devices = p.tables[9] devices = {} for device in known_devices: if len(device) == 5 and device[2] != '': devices[device[2]] = device[1] return devices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comments_for(context, obj): """ Provides a generic context variable name for the object that comments are being rendered for. """
form_class = import_dotted_path(settings.COMMENT_FORM_CLASS) form = form_class(context["request"], obj) context_form = context.get("posted_comment_form", form) context.update({ 'posted_comment_form': context_form if context_form.target_object == obj else form, 'unposted_comm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comment_thread(context, parent): """ Return a list of child comments for the given parent, storing all comments in a dict in the context when first called, u...
if "all_comments" not in context: comments = defaultdict(list) if "request" in context and context["request"].user.is_staff: comments_queryset = parent.comments.all() else: comments_queryset = parent.comments.visible() for comment in comments_queryset.select_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recent_comments(context): """ Dashboard widget for displaying recent comments. """
latest = context["settings"].COMMENTS_NUM_LATEST comments = ThreadedComment.objects.all().select_related("user") context["comments"] = comments.order_by("-id")[:latest] 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 log_level(level): """ Attempt to convert the given argument into a log level. Log levels are represented as integers, where higher values are more severe. If...
from six import string_types if isinstance(level, int): return level if isinstance(level, string_types): try: return int(level) except ValueError: pass try: return getattr(logging, level.upper()) except AttributeError: pass raise ValueError("cannot convert '{...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verbosity(verbosity): """ Convert the number of times the user specified '-v' on the command-line into a log level. """
verbosity = int(verbosity) if verbosity == 0: return logging.WARNING if verbosity == 1: return logging.INFO if verbosity == 2: return logging.DEBUG if verbosity >= 3: return 0 else: raise ValueError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config(stream=sys.stderr, level=logging.NOTSET, format='%(levelname)s [%(name)s:%(lineno)s] %(message)s', file=None, file_level=None, file_format=None): """ ...
# It doesn't make sense to configure a logger with no handlers. assert file is not None or stream is not None # Set the formats. stream_format = format if file_format is None: file_format = stream_format # Get the log levels stream_level = log_level(level) if file_level is Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _log(level, message, frame_depth=2, **kwargs): """ Log the given message with the given log level using a logger named based on the scope of the calling code...
import inspect try: # Inspect variables two frames up from where we currently are (by # default). One frame up is assumed to be one of the helper methods # defined in this module, so we aren't interested in that. Two frames # up should be the frame that's actually trying t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_switch_state_changed( self, func: Callable[['BaseUnit', SwitchNumber, Optional[bool]], None]): """ Define the switch state changed callback implementation...
self._on_switch_state_changed = func
<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) -> None: """ Start monitoring the base unit. """
self._shutdown = False # Start listening (if server) / Open connection (if client) if isinstance(self._protocol, Server): self.create_task(self._async_listen) elif isinstance(self._protocol, Client): self.create_task(self._async_open) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self) -> None: """ Stop monitoring the base unit. """
self._shutdown = True # Close connection if needed self._protocol.close() # Cancel any pending tasks self.cancel_pending_tasks()
<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 async_change_device( self, device_id: int, group_number: int, unit_number: int, enable_status: ESFlags, switches: SwitchFlags) -> None: """ Change setti...
# Lookup device using zone to obtain an accurate index and current # values, which will be needed to perform the change command device = self._devices[device_id] # If it is a Special device, automatically use the other function # instead (without changing any of the special fi...
<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 async_change_special_device( self, device_id: int, group_number: int, unit_number: int, enable_status: ESFlags, switches: SwitchFlags, special_status: S...
# Lookup device using zone to obtain an accurate index and current # values, which will be needed to perform the change command device = self._devices[device_id] # Verify it is a Special device if not isinstance(device, SpecialDevice): raise ValueError("Device to b...
<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 async_delete_device(self, device_id: int) -> None: """ Delete an enrolled device. :param device_id: unique identifier for the device to be deleted """
# Lookup device using zone to obtain an accurate index, which is # needed to perform the delete command device = self._devices[device_id] response = await self._protocol.async_execute( GetDeviceCommand(device.category, device.group_number, device.unit_number)) if is...
<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 async_get_event_log(self, index: int) -> Optional[EventLogResponse]: """ Get an entry from the event log. :param index: Index for the event log entry to...
response = await self._protocol.async_execute( GetEventLogCommand(index)) if isinstance(response, EventLogResponse): return response 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: async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]: """ Get an entry from the Special sensor log. :param index: Index for the sensor ...
response = await self._protocol.async_execute( GetSensorLogCommand(index)) if isinstance(response, SensorLogResponse): return response 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: async def async_set_operation_mode( self, operation_mode: OperationMode, password: str = '') -> None: """ Set the operation mode on the base unit. :param operatio...
await self._protocol.async_execute( SetOpModeCommand(operation_mode), password=password)
<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 async_set_switch_state( self, switch_number: SwitchNumber, state: bool) -> None: """ Turn a switch on or off. :param switch_number: the switch to be set...
await self._protocol.async_execute( SetSwitchCommand( switch_number, SwitchState.On if state else SwitchState.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 as_dict(self) -> Dict[str, Any]: """Converts to a dict of attributes for easier serialization."""
def _on_filter(obj: Any, name: str) -> bool: # Filter out any callbacks if isinstance(obj, BaseUnit): if name.startswith('on_'): return False return True return serializable(self, on_filter=_on_filter)
<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): ''' Update our object's data ''' self._json = self._request( method='GET', url=self.API )._json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def address(self): ''' Return the address of this "object", minus the scheme, hostname and port of the bridge ''' return self.API.replace( 'http://{}:{}'.format( self._bridge.hostname, self._bridge.port ), '' )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _load_bundle_map(self): ''' Return a map of all bundles in the Clarify app that have an external_id set for them. The bundles with external_ids set are assumed to be the ones we have inserted from Brightcove. The external_id contains the Brightcove video id. ''' bundl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _metadata_from_video(self, video): '''Generate the searchable metadata that we'll store in the bundle for the video''' long_desc = video['long_description'] if long_desc is not None: long_desc = long_desc[:MAX_METADATA_STRING_LEN] tags = video.get('tags') metada...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _src_media_url_for_video(self, video): '''Get the url for the video media that we can send to Clarify''' src_url = None best_height = 0 best_source = None # TODO: This assumes we have ingested videos. For remote videos, check if the remote flag is True # and if so, u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _update_metadata_for_video(self, metadata_href, video): ''' Update the metadata for the video if video has been updated in Brightcove since the bundle metadata was last updated. ''' current_metadata = self.clarify_client.get_metadata(metadata_href) cur_data = current_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def options(self, parser, env=os.environ): "Add options to nosetests." parser.add_option("--%s-record" % self.name, action="store", metavar="FILE", dest="record_filename", help="Record actions to this...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_one_subscription(): """ Fixes issues caused by upstream failures that lead to users having multiple active subscriptions Runs daily """
cursor = connection.cursor() cursor.execute("UPDATE subscription_subscription SET active = False \ WHERE id NOT IN \ (SELECT MAX(id) as id FROM \ subscription_subscription GROUP BY to_addr)") affected = cursor.rowcount vumi_fire_metric.delay( ...
<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_encoding(dom, default="utf-8"): """ Try to look for meta tag in given `dom`. Args: dom (obj): pyDHTMLParser dom of HTML elements. default (default "utr...
encoding = dom.find("meta", {"http-equiv": "Content-Type"}) if not encoding: return default encoding = encoding[0].params.get("content", None) if not encoding: return default return encoding.lower().split("=")[-1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_encodnig(html): """ Look for encoding in given `html`. Try to convert `html` to utf-8. Args: html (str): HTML code as string. Returns: str: HTML code...
encoding = _get_encoding( dhtmlparser.parseString( html.split("</head>")[0] ) ) if encoding == "utf-8": return html return html.decode(encoding).encode("utf-8")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_equal_tag(element, tag_name, params, content): """ Check is `element` object match rest of the parameters. All checks are performed only if proper attribu...
if tag_name and tag_name != element.getTagName(): return False if params and not element.containsParamSubset(params): return False if content is not None and content.strip() != element.getContent().strip(): return False return 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 has_neigh(tag_name, params=None, content=None, left=True): """ This function generates functions, which matches all tags with neighbours defined by parameter...
def has_neigh_closure(element): if not element.parent \ or not (element.isTag() and not element.isEndTag()): return False # filter only visible tags/neighbours childs = element.parent.childs childs = filter( lambda x: (x.isTag() and not x.isEndTag...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def paint(self): """ Saves the wallpaper as the specified filename. """
# nice blue color self.image = Image.new(mode='RGB', size=(self.width, self.height), color=(47, 98, 135)) self.paint_pattern() self.image.save(fp=self.filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cdn_get_conf(self, cname, environment): """ Returns the existing origin configuration and token from the CDN """
response = self.client.service.cdn_get_conf(cname, environment) cdn_config = CotendoCDN(response) return cdn_config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dns_get_conf(self, domainName, environment): """ Returns the existing domain configuration and token from the ADNS """
response = self.client.service.dns_get_conf(domainName, environment) dns_config = CotendoDNS(response) return dns_config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doFlush(self, cname, flushExpression, flushType): """ doFlush method enables specific content to be "flushed" from the cache servers. * Note: The flush API i...
return self.client.service.doFlush( cname, flushExpression, flushType)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def UpdateDNS(self, domain, environment): """Pushes DNS updates"""
self.dns_set_conf(domain, self.dns.config, environment, self.dns.token)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ImportDNS(self, config, token=None): """ Import a dns configuration file into the helper Note: This requires that you have the latest token. To get the lates...
if not token: raise Exception("You must have the dns token set first.") self.dns = CotendoDNS([token, config]) return 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 get_connection(self, service_name): """ Retrieves a connection class from the cache, if available. :param service_name: The service a given ``Connection`` ta...
service = self.services.get(service_name, {}) connection_class = service.get('connection', None) if not connection_class: msg = "Connection for '{0}' is not present in the cache." raise NotCached(msg.format( service_name )) return co...
<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_connection(self, service_name, to_cache): """ Sets a connection class within the cache. :param service_name: The service a given ``Connection`` talks to....
self.services.setdefault(service_name, {}) self.services[service_name]['connection'] = to_cache
<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_resource(self, service_name, resource_name, base_class=None): """ Retrieves a resource class from the cache, if available. :param service_name: The servi...
classpath = self.build_classpath(base_class) service = self.services.get(service_name, {}) resources = service.get('resources', {}) resource_options = resources.get(resource_name, {}) resource_class = resource_options.get(classpath, None) if not resource_class: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_resource(self, service_name, resource_name, to_cache): """ Sets the resource class within the cache. :param service_name: The service a given ``Resource`...
self.services.setdefault(service_name, {}) self.services[service_name].setdefault('resources', {}) self.services[service_name]['resources'].setdefault(resource_name, {}) options = self.services[service_name]['resources'][resource_name] classpath = self.build_classpath(to_cache._...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_resource(self, service_name, resource_name, base_class=None): """ Deletes a resource class for a given service. Fails silently if no connection is found ...
# Unlike ``get_resource``, this should be fire & forget. # We don't really care, as long as it's not in the cache any longer. try: classpath = self.build_classpath(base_class) opts = self.services[service_name]['resources'][resource_name] del opts[classpath]...
<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_collection(self, service_name, collection_name, base_class=None): """ Retrieves a collection class from the cache, if available. :param service_name: The...
classpath = self.build_classpath(base_class) service = self.services.get(service_name, {}) collections = service.get('collections', {}) collection_options = collections.get(collection_name, {}) collection_class = collection_options.get(classpath, None) if not 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 set_collection(self, service_name, collection_name, to_cache): """ Sets a collection class within the cache. :param service_name: The service a given ``Colle...
self.services.setdefault(service_name, {}) self.services[service_name].setdefault('collections', {}) self.services[service_name]['collections'].setdefault(collection_name, {}) options = self.services[service_name]['collections'][collection_name] classpath = self.build_classpath(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_collection(self, service_name, collection_name, base_class=None): """ Deletes a collection for a given service. Fails silently if no collection is found ...
# Unlike ``get_collection``, this should be fire & forget. # We don't really care, as long as it's not in the cache any longer. try: classpath = self.build_classpath(base_class) opts = self.services[service_name]['collections'][collection_name] del opts[clas...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunk(seq, n): # http://stackoverflow.com/a/312464/190597 (Ned Batchelder) """ Yield successive n-sized chunks from seq."""
for i in range(0, len(seq), n): yield seq[i:i + n]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, record): """Add contextual information to the log record :param record: the log record :type record: :class:`logging.LogRecord` :returns: True, ...
record.sitename = self.sitename record.platform = self.platform record.jobid = self.jobid record.submitter = self.logname record.jobname = self.jobname record.queue = self.queue record.fqdn = self.fqdn return 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 auth_user_get_url(self): 'Build authorization URL for User Agent.' if not self.client_id: raise AuthenticationError('No client_id specified') return '{}?{}'.format(self.auth_url_user, urllib.urlencode(dict( client_id=self.client_id, state=self.auth_state_check, response_type='code', redirect_uri=self.au...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def listdir(self, folder_id='0', offset=None, limit=None, fields=None): 'Get Box object, representing list of objects in a folder.' if fields is not None\ and not isinstance(fields, types.StringTypes): fields = ','.join(fields) return self( join('folders', folder_id, 'items'), dict(offset=offset, limit=l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mkdir(self, name=None, folder_id='0'): '''Create a folder with a specified "name" attribute. folder_id allows to specify a parent folder.''' return self( 'folders', method='post', encode='json', data=dict(name=name, parent=dict(id=folder_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 auth_get_token(self, check_state=True): 'Refresh or acquire access_token.' res = self.auth_access_data_raw = yield self._auth_token_request() defer.returnValue(self._auth_token_process(res, check_state=check_state))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retry(tries, delay=0, back_off=1, raise_msg=''): """Retries a function or method until it got True. - ``delay`` sets the initial delay in seconds - ``back_of...
if back_off < 1: raise ValueError('back_off must be 1 or greater') tries = math.floor(tries) if tries < 0: raise ValueError('tries must be 0 or greater') if delay < 0: raise ValueError('delay must be 0 or greater') def deco_retry(f): def f_retry(*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 parse_to_tree(text): """Parse text using CaboCha, then return Tree instance."""
xml_text = cabocha.as_xml(text) tree = Tree(xml_text) return tree
<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, page, default = True): r""" Add a display page to the display. :param page: Page to be added :type display_id: ``DisplayPage`` :param default:...
self._pages[page.page_id] = page page._add_display(self) if default or not self._active_page: self._active_page = page
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activate_page(self, page_id): r""" Activates a display page. Content of the active page is shown in the display. :param page_id: Id of page to activate :type...
if page_id == "next": page_keys = list(self._pages.keys()) key_count = len(page_keys) if key_count > 0: idx = page_keys.index(self._active_page.page_id) if idx >= key_count-1: idx = 0 else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_font(self, size=8, name="PressStart2P.ttf"): """ Returns a font that can be used by pil image functions. This default font is "SourceSansVariable-Roman"...
import kervi.vision as vision from PIL import ImageFont vision_path = os.path.dirname(vision.__file__) fontpath = os.path.join(vision_path, "fonts", name) font = ImageFont.truetype(fontpath, size) return font
<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_publisher(details): """ Parse publisher of the book. Args: details (obj): HTMLElement containing slice of the page with details. Returns: str/None: P...
publisher = _get_td_or_none( details, "ctl00_ContentPlaceHolder1_tblRowNakladatel" ) # publisher is not specified if not publisher: return None publisher = dhtmlparser.removeTags(publisher).strip() # return None instead of blank string if not publisher: re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_pages_binding(details): """ Parse number of pages and binding of the book. Args: details (obj): HTMLElement containing slice of the page with details...
pages = _get_td_or_none( details, "ctl00_ContentPlaceHolder1_tblRowRozsahVazba" ) if not pages: return None, None binding = None # binding info and number of pages is stored in same string if "/" in pages: binding = pages.split("/")[1].strip() pages = page...
<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_ISBN_EAN(details): """ Parse ISBN and EAN. Args: details (obj): HTMLElement containing slice of the page with details. Returns: (ISBN, EAN): Tuple w...
isbn_ean = _get_td_or_none( details, "ctl00_ContentPlaceHolder1_tblRowIsbnEan" ) if not isbn_ean: return None, None ean = None isbn = None if "/" in isbn_ean: # ISBN and EAN are stored in same string isbn, ean = isbn_ean.split("/") isbn = isbn.strip() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store_value(self, name, value): """Store a value to DB"""
self.spine.send_command("storeSetting", self.group, name, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_value(self, name, default_value=None): """Retrieve a value from DB"""
value = self.spine.send_query("retrieveSetting", self.group, name, processes=["kervi-main"]) if value is None: return default_value elif isinstance(value, list) and len(value) == 0: return default_value elif isinstance(default_value, int): return int(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def teb_retry(exc=RequestException, when=dict(response__status_code=429), delay='response__headers__Retry-After', max_collisions=MAX_COLLISIONS, default_retry=DEF...
def wrap(f): @functools.wraps(f) def wrapped_f(*args, **kwargs): attempt = kwargs.pop('teb_retry_attempt', 0) try: return f(*args, **kwargs) except exc as e: if kwargsql.and_(e, **when): try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_configs(cls): """Get rate limiters configuration specified at application level :rtype: dict of configurations """
import docido_sdk.config http_config = docido_sdk.config.get('http') or {} session_config = http_config.get('session') or {} rate_limits = session_config.get('rate_limit') or {} return rate_limits
<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_config(cls, service, config=None): """Get get configuration of the specified rate limiter :param str service: rate limiter name :param config: optional g...
config = config or cls.get_configs() return config[service]
<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(cls, service, config=None, persistence_kwargs=None, **context): """Load a rate-limiter from configuration :param str service: rate limiter name to retrie...
rl_config = cls.get_config(service, config) context.update(service=service) if isinstance(rl_config, (dict, Mapping)): if persistence_kwargs is not None: rl_config.update(persistence_kwargs=persistence_kwargs) return RateLimiter(context, **rl_config) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_grading_status(section_id, act_as=None): """ Return a restclients.models.gradepage.GradePageStatus object on the given course """
url = "{}/{}".format(url_prefix, quote(section_id)) headers = {} if act_as is not None: headers["X-UW-Act-as"] = act_as response = get_resource(url, headers) return _object_from_json(url, 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 to_dict(self): """ For backwards compatibility """
plain_dict = dict() for k, v in self.items(): if self.__fields__[k].is_list: if isinstance(self.__fields__[k], ViewModelField): plain_dict[k] = tuple(vt.to_dict() for vt in v) continue plain_dict[k] = tuple(copy.deepco...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(cls, data_dict): """ Restore from previously simplified data. Data is supposed to be valid, no checks are performed! """
obj = cls.__new__(cls) # Avoid calling constructor object.__setattr__(obj, '_simplified', data_dict) object.__setattr__(obj, '_storage', dict()) 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 interrupt(self): """ Invoked by the renderering.Renderer, if the image has changed. """
self.image = io.BytesIO() self.renderer.screen.save(self.image, "png")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(): """ print the available configurations directly to stdout """
if not is_configured(): raise JutException('No configurations available, please run: `jut config add`') info('Available jut configurations:') index = 0 for configuration in _CONFIG.sections(): username = _CONFIG.get(configuration, 'username') app_url = _CONFIG.get(configuration...
<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_default(name=None, index=None): """ set the default configuration by name """
default_was_set = False count = 1 for configuration in _CONFIG.sections(): if index != None: if count == index: _CONFIG.set(configuration, 'default', True) default_was_set = True else: _CONFIG.remove_option(configuration, 'def...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(name, **kwargs): """ add a new configuration with the name specified and all of the keywords as attributes of that configuration. """
_CONFIG.add_section(name) for (key, value) in kwargs.items(): _CONFIG.set(name, key, value) with open(_CONFIG_FILEPATH, 'w') as configfile: _CONFIG.write(configfile) info('Configuration updated at %s' % _JUT_HOME)
<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_default(): """ return the attributes associated with the default configuration """
if not is_configured(): raise JutException('No configurations available, please run `jut config add`') for configuration in _CONFIG.sections(): if _CONFIG.has_option(configuration, 'default'): return dict(_CONFIG.items(configuration))
<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(name=None, index=None): """ remove the specified configuration """
removed = False count = 1 for configuration in _CONFIG.sections(): if index != None: if count == index: _CONFIG.remove_section(configuration) removed = True break if name != None: if configuration == name: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_default(name=None, index=None): """ returns True if the specified configuration is the default one """
if not is_configured(): raise JutException('No configurations available, please run `jut config add`') count = 1 for configuration in _CONFIG.sections(): if index != None: if _CONFIG.has_option(configuration, 'default') and count == index: return 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 disconnect(self, user): """ Disconnect a user and send a message to the connected clients """
self.remove_user(user) self.send_message(create_message('RoomServer', 'Please all say goodbye to {name}!'.format(name=user.id.name))) self.send_message(create_disconnect(user.id.name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user(self, username): """ gets a user with given username if connected """
for user in self.users: if user.id.name == username: return user 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 send_message(self, message): """ send a message to each of the users """
for handler in self.users: logging.info('Handler: ' + str(handler)) handler.write_message(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def welcome(self, user): """ welcomes a user to the roomserver """
self.send_message(create_message('RoomServer', 'Please welcome {name} to the server!\nThere are currently {i} users online -\n {r}\n'.format(name=user.id, i=self.amount_of_users_connected, r=' '.join(self.user_names)))) logging.debug('Welcoming user...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def float_range(string, minimum, maximum, inf, sup): """ Requires values to be a number and range in a certain range. :param string: Value to validate :param min...
return _inrange(float(string), minimum, maximum, inf, sup)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def length_range(string, minimum, maximum): """ Requires values' length to be in a certain range. :param string: Value to validate :param minimum: Minimum length...
int_range(len(string), minimum, maximum) return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collectTriggers(self, rgx, code): """Return a dictionary of triggers and their corresponding matches from the code. """
return {m.group(0): m for m in re.finditer(rgx, 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 genOutputs(self, code, match): """Return a list out template outputs based on the triggers found in the code and the template they create. """
out = sorted((k, match.output(m)) for (k, m) in self.collectTriggers(match.match, code).items()) out = list(map(lambda a: a[1], out)) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen(self, text, start=0): """Return the source code in text, filled with autogenerated code starting at start. """
for cc in self.chunkComment(text, start): c = self.extractChunkContent(cc) cc = ''.join(cc) m = self.matchComment(c) idx = text.index(cc, start) e = idx + len(cc) if m: assert text[idx:e] == cc try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def beta_pdf(x, a, b): """Beta distirbution probability density function."""
bc = 1 / beta(a, b) fc = x ** (a - 1) sc = (1 - x) ** (b - 1) return bc * fc * sc
<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_field(cls, field_name): """ Check if the current class has a field with the name "field_name" Add management of dynamic fields, to return True if the nam...
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name): return True try: cls._get_dynamic_field_for(field_name) except ValueError: return False else: return 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 _add_dynamic_field_to_model(cls, field, field_name): """ Add a copy of the DynamicField "field" to the current class and its subclasses using the "field_name...
# create the new field new_field = field._create_dynamic_version() new_field.name = field_name new_field._attach_to_model(cls) # set it as an attribute on the class, to be reachable setattr(cls, "_redis_attr_%s" % field_name, new_field) # NOTE: don't add the fi...
<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_dynamic_field_to_instance(self, field, field_name): """ Add a copy of the DynamicField "field" to the current instance using the "field_name" name """
# create the new field new_field = field._create_dynamic_version() new_field.name = field_name new_field._attach_to_instance(self) # add the field to the list to avoid doing all of this again if field_name not in self._fields: # (maybe already in it via the class) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field_name_for(cls, field_name, dynamic_part): """ Given the name of a dynamic field, and a dynamic part, return the name of the final dynamic field to u...
field = cls.get_field(field_name) return field.get_name_for(dynamic_part)
<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_image_files(directory, files): """Recursively iterate through directory tree and list all files that have a valid image file suffix Parameters directory ...
# For each file in the directory test if it is a valid image file or a # sub-directory. for f in os.listdir(directory): abs_file = os.path.join(directory, f) if os.path.isdir(abs_file): # Recursively iterate through sub-directories get_image_files(abs_file, files) ...