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"): self.static_vars = literal_eval(self.static_vars) self.static_vars['upy_context']['template_name'] = u"{}/{}".format( self.template.app_name, self.template.file_name ) self.static_vars['upy_context']['NODE'] = node self.static_vars['upy_context']['PAGE'] = 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 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 inverse might be slow (complex Landau O) * speed might decline during forward selection * no overhead or other computations Example: -------- beta = lin_ols_svd(y,X) """
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 value of X is numerically not well-behaved.") return None # return estimated model parameters return beta
<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.strftime('%Y%m')), '/{0}'.format(at.strftime('%Y%m%d')), '/RDCP/medium/SEVP_AOC_RDCP_SLDAS_EBREF_', '{0}_L88_PI_'.format(radar), '{0}00000.GIF'.format(at.strftime('%Y%m%d%H%M')) ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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: _LOGGER.error("Invalid response from Home Hub: %s", 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 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_comment_form': form, 'comment_url': reverse("comment"), 'object_for_comments': obj, }) 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 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, using parents as keys for retrieval on subsequent recursive calls from the comments template. """
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_related("user"): comments[comment.replied_to_id].append(comment) context["all_comments"] = comments parent_id = parent.id if isinstance(parent, ThreadedComment) else None try: replied_to = int(context["request"].POST["replied_to"]) except KeyError: replied_to = 0 context.update({ "comments_for_thread": context["all_comments"].get(parent_id, []), "no_comments": parent_id is None and not context["all_comments"], "replied_to": replied_to, }) 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 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 the given level is already an integer, it is simply returned. If the given level is a string that can be converted into an integer, it is converted and that value is returned. Finally, if the given level is a string naming one of the levels defined in the logging module, return that level. If none of those conditions are met, raise a ValueError. """
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 '{}' into a log level".format(level))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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): """ Configure logging to stream and file concurrently. Allows setting a file and stream to log to concurrently with differing level if desired. Must provide either stream or file. Parameters stream: File like: Stream to write file to [Default: sys.stderr]. If none, will not write to stream. level: str|int Log level. Allowable levels are those recognized by the logging module. format: str Format string for the emitted logs. Default: 'log_level [logger_name] message' file: str Path to write log to file. If None, will not log to file. file_level: str|int|None Overwrite log level for the file. Will default to `level` if None. file_format: str|None Overwrite format of logs for file. Will default to `format` if 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 None: file_level = stream_level else: file_level = log_level(file_level) # Everything falls to pieces if I don't use basicConfig. if stream is not None: logging.basicConfig(stream=stream, level=stream_level, format=stream_format) # Configure file if file is not None: file = logging.FileHandler(filename=file) file.setLevel(file_level) file.setFormatter(logging.Formatter(file_format)) logging.getLogger().addHandler(file) elif file is not None: logging.basicConfig(filename=file, level=file_level, format=file_format)
<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. This saves you time because you will be able to see where all your log messages are being generated from without having to type anything. This function is meant to be called by one or more wrapper functions, so the `frame_depth` argument is provided to specify which scope should be used to name the logger. """
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 to log something. frame = inspect.stack()[frame_depth][0] frame_below = inspect.stack()[frame_depth-1][0] # Collect all the variables in the scope of the calling code, so they # can be substituted into the message. scope = {} scope.update(frame.f_globals) scope.update(frame.f_locals) # If the calling frame is inside a class (deduced based on the presence # of a 'self' variable), name the logger after that class. Otherwise # if the calling frame is inside a function, name the logger after that # function. Otherwise name it after the module of the calling scope. self = frame.f_locals.get('self') function = inspect.getframeinfo(frame).function module = frame.f_globals['__name__'] if self is not None: name = '.'.join([ self.__class__.__module__, self.__class__.__name__ ]) elif function != '<module>': name = '.'.join([module, function]) else: name = module # Trick the logging module into reading file names and line numbers # from the correct frame by monkey-patching logging.currentframe() with # a function that returns the frame below the real calling frame (this # indirection is necessary because the logging module will look one # frame above whatever this function returns). Undo all this after # logging our message, to avoid interfering with other loggers. with _temporarily_set_logging_frame(frame_below): logger = logging.getLogger(name) logger.log(level, message.format(**scope), **kwargs) finally: try: del frame except UnboundLocalError: 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 on_switch_state_changed( self, func: Callable[['BaseUnit', SwitchNumber, Optional[bool]], None]): """ Define the switch state changed callback implementation. Expected signature is: switch_state_changed_callback(base_unit, switch_number, state) base_unit: the device instance for this callback switch_number: the switch whose state has changed state: True if switch turned on, or False if switch turned off """
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: raise NotImplementedError
<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 settings for a device on the base unit. :param device_id: unique identifier for the device to be changed :param group_number: group number the device is to be assigned to :param unit_number: unit number the device is to be assigned to :param enable_status: flags indicating settings to enable :param switches: indicates switches that will be activated when device is triggered """
# 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 fields) if isinstance(device, SpecialDevice): await self.async_change_special_device( device_id, group_number, unit_number, enable_status, switches, device.special_status, device.high_limit, device.low_limit, device.control_high_limit, device.control_low_limit) return response = await self._protocol.async_execute( GetDeviceCommand(device.category, device.group_number, device.unit_number)) if isinstance(response, DeviceInfoResponse): response = await self._protocol.async_execute( ChangeDeviceCommand( device.category, response.index, group_number, unit_number, enable_status, switches)) if isinstance(response, DeviceSettingsResponse): device._handle_response(response) # pylint: disable=protected-access if isinstance(response, DeviceNotFoundResponse): raise ValueError("Device to be changed was not found")
<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: SSFlags, high_limit: Optional[Union[int, float]], low_limit: Optional[Union[int, float]], control_high_limit: Optional[Union[int, float]], control_low_limit: Optional[Union[int, float]]) -> None: """ Change settings for a 'Special' device on the base unit. :param device_id: unique identifier for the device to be changed :param group_number: group number the device is to be assigned to :param unit_number: unit number the device is to be assigned to :param enable_status: flags indicating settings to enable :param switches: indicates switches that will be activated when device is triggered :param special_status: flags indicating 'Special' settings to enable :param high_limit: triggers on readings higher than value :param low_limit: triggers on readings lower than value :param control_high_limit: trigger switch for readings higher than value :param control_low_limit: trigger switch for readings lower than value """
# 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 be changed is not a Special device") response = await self._protocol.async_execute( GetDeviceCommand(device.category, device.group_number, device.unit_number)) if isinstance(response, DeviceInfoResponse): # Control limits only specified when they are supported if response.control_limit_fields_exist: command = ChangeSpecial2DeviceCommand( device.category, response.index, group_number, unit_number, enable_status, switches, response.current_status, response.down_count, response.message_attribute, response.current_reading, special_status, high_limit, low_limit, control_high_limit, control_low_limit) else: command = ChangeSpecialDeviceCommand( device.category, response.index, group_number, unit_number, enable_status, switches, response.current_status, response.down_count, response.message_attribute, response.current_reading, special_status, high_limit, low_limit) response = await self._protocol.async_execute(command) if isinstance(response, DeviceSettingsResponse): device._handle_response(response) # pylint: disable=protected-access if isinstance(response, DeviceNotFoundResponse): raise ValueError("Device to be changed was not found")
<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 isinstance(response, DeviceInfoResponse): response = await self._protocol.async_execute( DeleteDeviceCommand(device.category, response.index)) if isinstance(response, DeviceDeletedResponse): self._devices._delete(device) # pylint: disable=protected-access if self._on_device_deleted: try: self._on_device_deleted(self, device) # pylint: disable=protected-access except Exception: # pylint: disable=broad-except _LOGGER.error( "Unhandled exception in on_device_deleted callback", exc_info=True) if isinstance(response, DeviceNotFoundResponse): raise ValueError("Device to be deleted was not found")
<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 be obtained. :return: Response containing the event log entry, or None if not found. """
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 log entry to be obtained. :return: Response containing the sensor log entry, or None if not found. """
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 operation_mode: the operation mode to change to :param password: if specified, will be used instead of the password property when issuing the command """
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. :param state: True to turn on, False to turn off. """
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. ''' bundle_map = {} next_href = None has_next = True while has_next: bundles = self.clarify_client.get_bundle_list(href=next_href, embed_items=True) items = get_embedded_items(bundles) for item in items: bc_video_id = item.get('external_id') if bc_video_id is not None and len(bc_video_id) > 0: bundle_map[bc_video_id] = item next_href = get_link_href(bundles, 'next') if next_href is None: has_next = False return bundle_map
<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') metadata = { 'name': default_to_empty_string(video.get('name')), 'description': default_to_empty_string(video.get('description')), 'long_description': default_to_empty_string(long_desc), 'tags': tags if tags is not None else [], 'updated_at': video.get('updated_at'), 'created_at': video.get('created_at'), 'state': video.get('state') } return metadata
<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, use the src url from the Asset endpoint. video_sources = self.bc_client.get_video_sources(video['id']) # Look for codec H264 with good resolution for source in video_sources: height = source.get('height', 0) codec = source.get('codec') if source.get('src') and codec and codec.upper() == 'H264' and height <= 1080 and height > best_height: best_source = source if best_source is not None: src_url = best_source['src'] return src_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 _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_metadata.get('data') if cur_data.get('updated_at') != video['updated_at']: self.log('Updating metadata for video {0}'.format(video['id'])) if not self.dry_run: metadata = self._metadata_from_video(video) self.clarify_client.update_metadata(metadata_href, metadata=metadata) self.sync_stats['updated'] += 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 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 file.") parser.add_option("--%s-playback" % self.name, action="store", metavar="FILE", dest="playback_filename", help="Playback actions from this file.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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( metric="subscription.duplicates", value=affected, agg="last") return affected
<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-8"): What to use if encoding is not found in `dom`. Returns: str/default: Given encoding or `default` parameter if not found. """
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 encoded in UTF. """
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 attribute is set in the HTMLElement. Args: element (obj): HTMLElement instance. tag_name (str): Tag name. params (dict): Parameters of the tag. content (str): Content of the tag. Returns: bool: True if everyhing matchs, False otherwise. """
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 parameters. Args: tag_name (str): Tag has to have neighbour with this tagname. params (dict): Tag has to have neighbour with this parameters. params (str): Tag has to have neighbour with this content. left (bool, default True): Tag has to have neigbour on the left, or right (set to ``False``). Returns: bool: True for every matching tag. Note: This function can be used as parameter for ``.find()`` method in HTMLElement. """
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()) \ or x.getContent().strip() or x is element, childs ) if len(childs) <= 1: return False ioe = childs.index(element) if left and ioe > 0: return is_equal_tag(childs[ioe - 1], tag_name, params, content) if not left and ioe + 1 < len(childs): return is_equal_tag(childs[ioe + 1], tag_name, params, content) return False return has_neigh_closure
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 is limited to 1,000 flush invocations per hour (each flush invocation may include several objects). * """
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 latest token, run the GrabDNS command first. """
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`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :returns: A <kotocore.connection.Connection> subclass """
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 connection_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_connection(self, service_name, to_cache): """ Sets a connection class within the cache. :param service_name: The service a given ``Connection`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param to_cache: The class to be cached for the service. :type to_cache: class """
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 service a given ``Resource`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param resource_name: The name of the ``Resource``. Ex. ``Queue``, ``Notification``, ``Table``, etc. :type resource_name: string :param base_class: (Optional) The base class of the object. Prevents "magically" loading the wrong class (one with a different base). Default is ``default``. :type base_class: class :returns: A <kotocore.resources.Resource> subclass """
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: msg = "Resource '{0}' for {1} is not present in the cache." raise NotCached(msg.format( resource_name, service_name )) return 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`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param resource_name: The name of the ``Resource``. Ex. ``Queue``, ``Notification``, ``Table``, etc. :type resource_name: string :param to_cache: The class to be cached for the service. :type to_cache: class """
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.__bases__[0]) if classpath == 'kotocore.resources.Resource': classpath = 'default' options[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 in the cache. :param service_name: The service a given ``Resource`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param base_class: (Optional) The base class of the object. Prevents "magically" loading the wrong class (one with a different base). Default is ``default``. :type base_class: class """
# 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] 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_collection(self, service_name, collection_name, base_class=None): """ Retrieves a collection class from the cache, if available. :param service_name: The service a given ``Collection`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param collection_name: The name of the ``Collection``. Ex. ``QueueCollection``, ``NotificationCollection``, ``TableCollection``, etc. :type collection_name: string :param base_class: (Optional) The base class of the object. Prevents "magically" loading the wrong class (one with a different base). Default is ``default``. :type base_class: class :returns: A <kotocore.collections.Collection> subclass """
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_class: msg = "Collection '{0}' for {1} is not present in the cache." raise NotCached(msg.format( collection_name, service_name )) return collection_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_collection(self, service_name, collection_name, to_cache): """ Sets a collection class within the cache. :param service_name: The service a given ``Collection`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param collection_name: The name of the ``Collection``. Ex. ``QueueCollection``, ``NotificationCollection``, ``TableCollection``, etc. :type collection_name: string :param to_cache: The class to be cached for the service. :type to_cache: class """
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(to_cache.__bases__[0]) if classpath == 'kotocore.collections.Collection': classpath = 'default' options[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_collection(self, service_name, collection_name, base_class=None): """ Deletes a collection for a given service. Fails silently if no collection is found in the cache. :param service_name: The service a given ``Collection`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param collection_name: The name of the ``Collection``. Ex. ``QueueCollection``, ``NotificationCollection``, ``TableCollection``, etc. :type collection_name: string :param base_class: (Optional) The base class of the object. Prevents "magically" loading the wrong class (one with a different base). Default is ``default``. :type base_class: class """
# 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[classpath] 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 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, if log should get sent :rtype: :class:`bool` :raises: None """
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.auth_redirect_uri )))
<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=limit, fields=fields) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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_off`` sets the factor by which - ``raise_msg`` if not '', it'll raise an Exception """
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): max_tries, max_delay = tries, delay # make mutable while max_tries > 0: rv = f(*args, **kwargs) # first attempt if rv: # Done on success return rv max_tries -= 1 # consume an attempt time.sleep(max_delay) # wait... max_delay *= back_off # make future wait longer else: if raise_msg: raise Exception(raise_msg) return return f_retry # true decorator -> decorated function return deco_retry
<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: True if this page should be shown upon initialization. :type name: ``bool`` """
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 page_id: ``str`` """
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: idx += 1 self._active_page = self._pages[page_keys[idx]] self._active_page._render() self._page_changed(self._active_page) elif page_id in self._pages: self._active_page = self._pages[page_id] self._page_changed(self._active_page) else: raise ValueError("Page with {page_id} not found in page list".format(page_id = page_id))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_font(self, size=8, name="PressStart2P.ttf"): """ Returns a font that can be used by pil image functions. This default font is "SourceSansVariable-Roman" that is available on all platforms. """
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: Publisher's name as string or None if not found. """
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: return None return publisher
<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. Returns: (pages, binding): Tuple with two string or two None. """
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 = pages.split("/")[0].strip() if not pages: pages = None return pages, binding
<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 with two string or two None. """
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() ean = ean.strip() else: isbn = isbn_ean.strip() if not isbn: isbn = None return isbn, ean
<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(value) elif isinstance(default_value, float): return float(value) else: 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 teb_retry(exc=RequestException, when=dict(response__status_code=429), delay='response__headers__Retry-After', max_collisions=MAX_COLLISIONS, default_retry=DEFAULT_RETRY): """Decorator catching rate limits exceed events during a crawl task. It retries the task later on, following a truncated exponential backoff. """
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: retry_after = kwargsql.get(e, delay) except: retry_after = default_retry else: if retry_after is not None: retry_after = int(retry_after) else: retry_after = default_retry countdown = retry_after + truncated_exponential_backoff( retry_after, attempt % max_collisions) raise Retry(kwargs=dict(attempt=attempt + 1), countdown=countdown) else: raise e, None, sys.exc_info()[2] # flake8: noqa. return wrapped_f return wrap
<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 global rate limiters configuration. If not specified, then use rate limiters configuration specified at application level """
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 retrieve :param dict config: alternate configuration object to use. If `None`, then use the global application configuration :context: Uniquely describe the consumed resource. Used by the persistence layer to forge the URI describing the resource. :rtype: :py:class:`RateLimiter` or :py:class:`MultiRateLimiter` """
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) else: def _rl(conf): conf.setdefault('persistence_kwargs', persistence_kwargs or {}) return RateLimiter(context, **conf) return MultiRateLimiter( [_rl(config) for config in 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.deepcopy(vt) for vt in v) continue if isinstance(self.__fields__[k], ViewModelField): plain_dict[k] = v.to_dict() continue plain_dict[k] = copy.deepcopy(v) return plain_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 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, 'app_url') if app_url != defaults.APP_URL: if _CONFIG.has_option(configuration, 'default'): info(' %d: %s@%s (default)', index + 1, username, app_url) else: info(' %d: %s@%s', index + 1, username, app_url) else: if _CONFIG.has_option(configuration, 'default'): info(' %d: %s (default)' % (index + 1, username)) else: info(' %d: %s' % (index + 1, username)) index += 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 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, 'default') if name != None: if configuration == name: _CONFIG.set(configuration, 'default', True) default_was_set = True else: _CONFIG.remove_option(configuration, 'default') count += 1 if not default_was_set: raise JutException('Unable to find %s configuration' % name) 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 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: _CONFIG.remove_section(configuration) removed = True break count += 1 if not removed: raise JutException('Unable to find %s configuration' % name) with open(_CONFIG_FILEPATH, 'w') as configfile: _CONFIG.write(configfile)
<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 if name != None: if _CONFIG.has_option(configuration, 'default') and configuration == name: return True count += 1 return 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 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 {user} to {room}'.format(user=user.id.name, room=self.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 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 minimum: Minimum value to accept :param maximum: Maximum value to accept :param inf: Infimum value to accept :param sup: Supremum value to accept :type string: str :type minimum: float :type maximum: float :type inf: float :type sup: float """
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 to accept :param maximum: Maximum length to accept :type string: str :type minimum: int :type maximum: int """
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: end = text.index('\n\n', e - 1) + 1 except ValueError: end = len(text) text = text[:e] + text[end:] new = self.genOutputs(self.code(text), m) new = ''.join(new) text = text[:e] + new + text[e:] return self.gen(text, e + len(new)) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 name matches an existing dynamic field without existing copy for this name. """
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" 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 field to the "_fields" list, to avoid use extra # memory to each future instance that will create a field for each # dynamic one created # # add the field to the list to avoid to done all of this again # # (_fields is already on this class only, not subclasses) # cls._fields.append(field_name) # each subclass needs its own copy for subclass in cls.__subclasses__(): subclass._add_dynamic_field_to_model(field, field_name) return new_field
<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) if id(self._fields) == id(self.__class__._fields): # unlink the list from the class self._fields = list(self._fields) self._fields.append(field_name) # if the field is an hashable field, add it to the list to allow calling # hmget on these fields if isinstance(field, limpyd_fields.InstanceHashField): if id(self._instancehash_fields) == id(self.__class__._instancehash_fields): # unlink the link from the class self._instancehash_fields = list(self._instancehash_fields) self._instancehash_fields.append(field_name) # set it as an attribute on the instance, to be reachable setattr(self, field_name, new_field) return new_field
<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 use. It will then be used with get_field. """
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 : directory Path to directory on disk files : List(string) List of file names Returns ------- List(string) List of files that have a valid image suffix """
# 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) else: # Add to file collection if has valid suffix if '.' in f and '.' + f.rsplit('.', 1)[1] in VALID_IMGFILE_SUFFIXES: files.append(abs_file) return files