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 hasOption(self, name): """ Check whether this CLI has an option with a given name. :param name: the name of the option to check; can be short or long name. :return: true if an option exists in the UI for the given name """
name = name.strip() for o in self.options: if o.short == name or o.long == name: return True 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 addOption(self, o): """ Add a new Option to this CLI. :param o: the option to add :raise InterfaceException: if an option with that name already exists. """
if self.hasOption(o.short): raise InterfaceException("Failed adding option - already have " + str(o)) self.options.append(o)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optionIsSet(self, name): """ Check whether an option with a given name exists and has been set. :param name: the name of the option to check; can be short or long name. :return: true if an option matching the given name exists and it has had it's value set by the user """
name = name.strip() if not self.hasOption(name): return False return self.getOption(name).isSet()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getArgument(self, num): """ Get the num^th argument. :param num: Which argument to get; indexing here is from 0. :return: The num^th agument; arguments are always parsed as strings, so this will be a string. :raise InterfaceException: if there are fewer than num + 1 arguments. """
if not self.hasArgument(num): raise InterfaceException("Failed to retrieve argument " + str(num) + " -- not enough arguments provided") return self.args[num]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _optlist(self): """Get a string representation of the options in short format."""
res = "" for o in self.options: res += o.short if o.argName is not None: res += ":" return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _longoptl(self): """Get a list of string representations of the options in long format."""
res = [] for o in self.options: nm = o.long if o.argName is not None: nm += "=" res.append(nm) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pull(self): """Pull from the origin."""
repo_root = settings.REPO_ROOT pull_from_origin(join(repo_root, 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 to_package(self, repo_url): """Return the package representation of this repo."""
return Package(name=self.name, url=repo_url + 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 get_storage(clear=False): """helper function to get annotation storage on the portal :param clear: If true is passed in, annotations will be cleared :returns: portal annotations :rtype: IAnnotations """
portal = getUtility(ISiteRoot) annotations = IAnnotations(portal) if ANNOTATION_KEY not in annotations or clear: annotations[ANNOTATION_KEY] = OOBTree() return annotations[ANNOTATION_KEY]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_email(recipient, subject, message, sender="ploneintranet@netsight.co.uk"): """helper function to send an email with the sender preset """
try: api.portal.send_email( recipient=recipient, sender=sender, subject=subject, body=message) except ValueError, e: log.error("MailHost error: {0}".format(e))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent_workspace(context): """ Return containing workspace Returns None if not found. """
if IWorkspaceFolder.providedBy(context): return context for parent in aq_chain(context): if IWorkspaceFolder.providedBy(parent): return parent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_workspace_activities(brain, limit=1): """ Return the workspace activities sorted by reverse chronological order Regarding the time value: - the datetime value contains the time in international format (machine readable) - the title value contains the absolute date and time of the post """
mb = queryUtility(IMicroblogTool) items = mb.context_values(brain.getObject(), limit=limit) return [ { 'subject': item.creator, 'verb': 'published', 'object': item.text, 'time': { 'datetime': item.date.strftime('%Y-%m-%d'), 'title': item.date.strftime('%d %B %Y, %H:%M'), } } for item in items ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def my_workspaces(context): """ The list of my workspaces """
pc = api.portal.get_tool('portal_catalog') brains = pc( portal_type="ploneintranet.workspace.workspacefolder", sort_on="modified", sort_order="reversed", ) workspaces = [ { 'id': brain.getId, 'title': brain.Title, 'description': brain.Description, 'url': brain.getURL(), 'activities': get_workspace_activities(brain), 'class': escape_id_to_class(brain.getId), } for brain in brains ] return workspaces
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def existing_users(context): """ Look up the full user details for current workspace members """
members = IWorkspace(context).members info = [] for userid, details in members.items(): user = api.user.get(userid) if user is None: continue user = user.getUser() title = user.getProperty('fullname') or user.getId() or userid # XXX tbd, we don't know what a persons description is, yet description = _(u'Here we could have a nice status of this person') classes = description and 'has-description' or 'has-no-description' portal = api.portal.get() portrait = '%s/portal_memberdata/portraits/%s' % \ (portal.absolute_url(), userid) info.append( dict( id=userid, title=title, description=description, portrait=portrait, cls=classes, member=True, admin='Admins' in details['groups'], ) ) return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_weighted_choice(choices): """ Return a random key of choices, weighted by their value. :param choices: a dictionary of keys and positive integer pairs; :return: a random key of choices. """
choices, weights = zip(*choices.items()) cumdist = list(accumulate(weights)) x = random.random() * cumdist[-1] element = bisect.bisect(cumdist, x) return choices[element]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_words(lines): """ Extract from the given iterable of lines the list of words. :param lines: an iterable of lines; :return: a generator of words of lines. """
for line in lines: for word in re.findall(r"\w+", line): yield word
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def absolute_urls(html): """ Converts relative URLs into absolute URLs. Used for RSS feeds to provide more complete HTML for item descriptions, but could also be used as a general richtext filter. """
from bs4 import BeautifulSoup from yacms.core.request import current_request request = current_request() if request is not None: dom = BeautifulSoup(html, "html.parser") for tag, attr in ABSOLUTE_URL_TAGS.items(): for node in dom.findAll(tag): url = node.get(attr, "") if url: node[attr] = request.build_absolute_uri(url) html = str(dom) return html
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape(html): """ Escapes HTML according to the rules defined by the settings ``RICHTEXT_FILTER_LEVEL``, ``RICHTEXT_ALLOWED_TAGS``, ``RICHTEXT_ALLOWED_ATTRIBUTES``, ``RICHTEXT_ALLOWED_STYLES``. """
from yacms.conf import settings from yacms.core import defaults if settings.RICHTEXT_FILTER_LEVEL == defaults.RICHTEXT_FILTER_LEVEL_NONE: return html tags = settings.RICHTEXT_ALLOWED_TAGS attrs = settings.RICHTEXT_ALLOWED_ATTRIBUTES styles = settings.RICHTEXT_ALLOWED_STYLES if settings.RICHTEXT_FILTER_LEVEL == defaults.RICHTEXT_FILTER_LEVEL_LOW: tags += LOW_FILTER_TAGS attrs += LOW_FILTER_ATTRS return clean(html, tags=tags, attributes=attrs, strip=True, strip_comments=False, styles=styles)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thumbnails(html): """ Given a HTML string, converts paths in img tags to thumbnail paths, using yacms's ``thumbnail`` template tag. Used as one of the default values in the ``RICHTEXT_FILTERS`` setting. """
from django.conf import settings from bs4 import BeautifulSoup from yacms.core.templatetags.yacms_tags import thumbnail # If MEDIA_URL isn't in the HTML string, there aren't any # images to replace, so bail early. if settings.MEDIA_URL.lower() not in html.lower(): return html dom = BeautifulSoup(html, "html.parser") for img in dom.findAll("img"): src = img.get("src", "") src_in_media = src.lower().startswith(settings.MEDIA_URL.lower()) width = img.get("width") height = img.get("height") if src_in_media and width and height: img["src"] = settings.MEDIA_URL + thumbnail(src, width, height) # BS adds closing br tags, which the browser interprets as br tags. return str(dom).replace("</br>", "")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, url, method, body=None, headers=None, **kwargs): """Request without authentication."""
content_type = kwargs.pop('content_type', None) or 'application/json' headers = headers or {} headers.setdefault('Accept', content_type) if body: headers.setdefault('Content-Type', content_type) headers['User-Agent'] = self.USER_AGENT resp = requests.request( method, url, data=body, headers=headers, verify=self.verify_cert, timeout=self.timeout, **kwargs) return resp, resp.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 _extract_service_catalog(self, body): """Set the client's service catalog from the response data."""
self.auth_ref = access.create(body=body) self.service_catalog = self.auth_ref.service_catalog self.auth_token = self.auth_ref.auth_token self.auth_tenant_id = self.auth_ref.tenant_id self.auth_user_id = self.auth_ref.user_id if not self.endpoint_url: self.endpoint_url = self.service_catalog.url_for( region_name=self.region_name, service_type=self.service_type, interface=self.endpoint_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_partitioning(rdd, show=True): """Seems to be significantly more expensive on cluster than locally"""
if show: partitionCount = rdd.getNumPartitions() try: valueCount = rdd.countApprox(1000, confidence=0.50) except: valueCount = -1 try: name = rdd.name() or None except: pass name = name or "anonymous" logging.info("For RDD %s, there are %d partitions with on average %s values" % (name, partitionCount, int(valueCount/float(partitionCount))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normal_case(name): """Converts "CamelCaseHere" to "camel case here"."""
s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name) return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_config(self): """ install supervisor main config file """
text = templ_config.render(**self.options) config = Configuration(self.buildout, 'supervisord.conf', { 'deployment': self.deployment_name, 'text': text}) return [config.install()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_program(self): """ install supervisor program config file """
text = templ_program.render(**self.options) config = Configuration(self.buildout, self.program + '.conf', { 'deployment': self.deployment_name, 'directory': os.path.join(self.options['etc-directory'], 'conf.d'), 'text': text}) return [config.install()]
<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_lu(y, X): """Linear Regression, OLS, by solving linear equations and LU decomposition Properties * based on LAPACK's _gesv what applies LU decomposition * avoids using python's inverse functions * should be stable * no overhead or other computations Example: -------- beta = linreg_ols_lu(y,X) Links: ------ * http://oxyba.de/docs/linreg_ols_lu """
import numpy as np try: # solve OLS formula return np.linalg.solve(np.dot(X.T, X), np.dot(X.T, y)) except np.linalg.LinAlgError: print("LinAlgError: X*X' is singular or not square.") 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 _time_to_minutes(self, time_str): """ Convert a time string to the equivalent number in minutes as an int. Return 0 if the time_str is not a valid amount of time. 34 90 0 """
minutes = 0 try: call_time_obj = parser.parse(time_str) minutes = call_time_obj.minute minutes += call_time_obj.hour * 60 except ValueError: minutes = 0 return minutes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jumping(self, _loads=None): """ Return True if this dropzone is still making new loads, False otherwise. :param _loads: The output of the `departing_loads` function. This should be left alone except for debugging purposes. """
if _loads is None: _loads = self.departing_loads() if len(_loads) < 1: return False last_load = _loads[-1:][0] if last_load['state'].lower() in ('departed', 'closed', 'on hold'): 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 devices_by_subsystem(subsys, only=lambda x: True): """ Iterator that yields devices that belong to specified subsystem. Returned values are ``pydev.Device`` instances. The ``only`` argument can be used to further filter devices. It should be a function that takes a ``pyudev.Device`` object, and returns ``True`` or ``False`` to indicate whether device should be returned. Example:: [Device('/sys/devices/pci0000:00/0000:00:1c.3/0000:02:00.0/net/wlp2s0'), Device('/sys/devices/virtual/net/lo')] """
ctx = pyudev.Context() for d in ctx.list_devices(): if d.subsystem != subsys: continue if not only(d): continue yield d
<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_infile(filename): """Check text file exisitense. Argument: filename: text file of bulk updating """
if os.path.isfile(filename): domain = os.path.basename(filename).split('.txt')[0] return domain else: sys.stderr.write("ERROR: %s : No such file\n" % filename) sys.exit(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_json(domain, action, filename=False, record=False): """Convert text file to JSON. Arguments: domain: domain name of updating target action: True ; for PUT/POST HTTP method False; for DELETE HTTP method filename: text file of bulk updating (default is False) record: json record of updating single record (default is False) """
o = JSONConverter(domain) if filename: # for 'bulk_create/bulk_delete' with open(filename, 'r') as f: o.separate_input_file(f) for item in o.separated_list: o.read_records(item.splitlines()) o.generata_data(action) elif record: # for 'create/delete' o.read_records(record) o.generata_data(action) return o.dict_records
<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_record_params(args): """Get record parameters from command options. Argument: args: arguments object """
name, rtype, content, ttl, priority = ( args.name, args.rtype, args.content, args.ttl, args.priority) return name, rtype, content, ttl, priority
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(args): """Create records. Argument: args: arguments object """
# for PUT HTTP method action = True if ((args.__dict__.get('domain') and args.__dict__.get('name') and args.__dict__.get('rtype') and args.__dict__.get('content'))): # for create sub-command domain = args.domain o = JSONConverter(domain) name, rtype, content, ttl, priority = get_record_params(args) record_dict = o.set_record(name, rtype, content, ttl, priority) json = set_json(domain, action, record=record_dict) else: # for bulk_create sub-command if args.__dict__.get('domain'): domain = args.domain else: domain = check_infile(args.infile) json = set_json(domain, action, filename=args.infile) password = get_password(args) token = connect.get_token(args.username, password, args.server) processing.create_records(args.server, token, domain, json) if args.auto_update_soa == 'True': update_soa_serial(args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_option(prs, keyword, required=False): """Set options of command line. Arguments: prs: parser object of argparse keyword: processing keyword required: True is required option (default is False) """
if keyword == 'server': prs.add_argument( '-s', dest='server', required=True, help='specify TonicDNS Server hostname or IP address') if keyword == 'username': prs.add_argument('-u', dest='username', required=True, help='TonicDNS username') if keyword == 'password': group = prs.add_mutually_exclusive_group(required=True) group.add_argument('-p', dest='password', help='TonicDNS password') group.add_argument('-P', action='store_true', help='TonicDNS password prompt') if keyword == 'infile': prs.add_argument('infile', action='store', help='pre-converted text file') if keyword == 'domain': prs.add_argument('--domain', action='store', required=True, help='create record with specify domain') prs.add_argument('--name', action='store', required=True, help='specify with domain option') prs.add_argument('--rtype', action='store', required=True, help='specify with domain option') prs.add_argument('--content', action='store', required=True, help='specify with domain option') prs.add_argument('--ttl', action='store', default='3600', help='specify with domain option, default 3600') prs.add_argument('--priority', action='store', default=False, help='specify with domain and ' 'rtype options as MX|SRV') if keyword == 'update': prs.add_argument('--new-type', action='store', help='specify new value with domain option') prs.add_argument('--new-content', action='store', help='specify new value with domain option') prs.add_argument('--new-ttl', action='store', help='specify new value with domain option') prs.add_argument('--new-priority', action='store', help='specify new value with domain option') if keyword == 'template': msg = 'specify template identifier' if required: prs.add_argument('--template', action='store', required=True, help=msg) else: prs.add_argument('--template', action='store', help=msg) if keyword == 'search': prs.add_argument('--search', action='store', help='partial match search or refine search.\ latter syntax is "name,rtype,content"')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conn_options(prs, conn): """Set options of connecting to TonicDNS API server Arguments: prs: parser object of argparse conn: dictionary of connection information """
if conn.get('server') and conn.get('username') and conn.get('password'): prs.set_defaults(server=conn.get('server'), username=conn.get('username'), password=conn.get('password')) elif conn.get('server') and conn.get('username'): prs.set_defaults(server=conn.get('server'), username=conn.get('username')) if conn.get('auto_update_soa'): prs.set_defaults(auto_update_soa=conn.get('auto_update_soa')) else: prs.set_defaults(auto_update_soa=False) if not conn.get('server'): set_option(prs, 'server') if not conn.get('username'): set_option(prs, 'username') if not conn.get('password'): set_option(prs, 'password')
<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_options(): """Define sub-commands and command line options."""
server, username, password, auto_update_soa = False, False, False, False prs = argparse.ArgumentParser(description='usage') prs.add_argument('-v', '--version', action='version', version=__version__) if os.environ.get('HOME'): config_file = os.environ.get('HOME') + '/.tdclirc' if os.path.isfile(config_file): (server, username, password, auto_update_soa) = check_config(config_file) conn = dict(server=server, username=username, password=password, auto_update_soa=auto_update_soa) subprs = prs.add_subparsers(help='commands') # Convert and print JSON parse_show(subprs) # Retrieve records parse_get(subprs, conn) # Create record parse_create(subprs, conn) # Create bulk_records parse_bulk_create(subprs, conn) # Delete record parse_delete(subprs, conn) # Delete bulk_records parse_bulk_delete(subprs, conn) # Update a record parse_update(subprs, conn) # Update SOA serial parse_update_soa(subprs, conn) # Create zone parse_create_zone(subprs, conn) # Delete zone parse_delete_zone(subprs, conn) # Retrieve template parse_get_tmpl(subprs, conn) # Delete template parse_delete_tmpl(subprs, conn) args = prs.parse_args() return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_create(prs, conn): """Create record. Arguments: prs: parser object of argparse conn: dictionary of connection information """
prs_create = prs.add_parser( 'create', help='create record of specific zone') set_option(prs_create, 'domain') conn_options(prs_create, conn) prs_create.set_defaults(func=create)
<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_bulk_create(prs, conn): """Create bulk_records. Arguments: prs: parser object of argparse conn: dictionary of connection information """
prs_create = prs.add_parser( 'bulk_create', help='create bulk records of specific zone') set_option(prs_create, 'infile') conn_options(prs_create, conn) prs_create.add_argument('--domain', action='store', help='create records with specify zone') prs_create.set_defaults(func=create)
<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_delete(prs, conn): """Delete record. Arguments: prs: parser object of argparse conn: dictionary of connection information """
prs_delete = prs.add_parser( 'delete', help='delete a record of specific zone') set_option(prs_delete, 'domain') conn_options(prs_delete, conn) prs_delete.set_defaults(func=delete)
<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_bulk_delete(prs, conn): """Delete bulk_records. Arguments: prs: parser object of argparse conn: dictionary of connection information """
prs_delete = prs.add_parser( 'bulk_delete', help='delete bulk records of specific zone') set_option(prs_delete, 'infile') conn_options(prs_delete, conn) prs_delete.add_argument('--domain', action='store', help='delete records with specify zone') prs_delete.set_defaults(func=delete)
<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_config(filename): """Check configuration file of TonicDNS CLI. Argument: filename: config file name (default is ~/.tdclirc) """
conf = configparser.SafeConfigParser(allow_no_value=False) conf.read(filename) try: server = conf.get('global', 'server') except configparser.NoSectionError: server = False except configparser.NoOptionError: server = False try: username = conf.get('auth', 'username') except configparser.NoSectionError: username = False except configparser.NoOptionError: username = False try: password = conf.get('auth', 'password') except configparser.NoSectionError: password = False except configparser.NoOptionError: password = False try: auto_update_soa = conf.get('global', 'soa_update') except configparser.NoSectionError: auto_update_soa = False except configparser.NoOptionError: auto_update_soa = False return server, username, password, auto_update_soa
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_example_config(example_file_path: str): """ Writes an example config file using the config values declared so far :param example_file_path: path to write to """
document = tomlkit.document() for header_line in _get_header(): document.add(tomlkit.comment(header_line)) config_keys = _aggregate_config_values(ConfigValue.config_values) _add_config_values_to_toml_object(document, config_keys) _doc_as_str = document.as_string().replace(f'"{_NOT_SET}"', '') with open(example_file_path, 'w') as stream: stream.write(_doc_as_str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_message(self, message): """ Prepares the message before sending it out Returns: - message.Message: the message """
message.meta.update(path=self.path) for handler in self.handlers: handler.outgoing(message, self) return 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 on_receive(self, message=None, wire=None, event_origin=None): """ event handler bound to the receive event of the link the server is wired too. Arguments: - message (message.Message): incoming message Keyword arguments: - event_origin (connection.Link) """
self.trigger("before_call", message) fn_name = message.data pmsg = self.prepare_message try: for handler in self.handlers: handler.incoming(message, self) fn = self.get_function(fn_name, message.path) except Exception as inst: wire.respond(message, ErrorMessage(str(inst))) return if callable(fn) and getattr(fn, "exposed", False): try: r = fn(*message.args, **message.kwargs) if isinstance(r,Message): wire.respond(message, pmsg(r)) else: wire.respond(message, pmsg(Message(r))) except Exception as inst: if self.debug: wire.respond(message, pmsg(ErrorMessage(str(traceback.format_exc())))) else: wire.respond(message, pmsg(ErrorMessage(str(inst)))) else: wire.respond( message, pmsg( ErrorMessage("action '%s' not exposed on API (%s)" % (fn_name, self.__class__.__name__))) ) self.trigger("after_call", 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 detach_remote(self, id, name): """ destroy remote instance of widget Arguments: - id (str): widget id - name (str): widget type name """
if name in self.widgets: if id in self.widgets[name]: del self.widgets[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 attach_remote(self, id, name, **kwargs): """ create remote instance of widget Arguments: - id (str): widget id - name (str): widget type name Keyword Arguments: - any further arguments you wish to pass to the widget constructor """
client_id = id.split(".")[0] widget = self.make_widget( id, name, dispatcher=ProxyDispatcher( self, link=getattr(self.clients[client_id], "link", None) ), **kwargs ) self.store_widget(widget) self.log_debug("Attached widget: %s" % 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 on_api_error(self, error_status=None, message=None, event_origin=None): """ API error handling """
if message.meta["error"].find("Widget instance not found on server") > -1: # widget is missing on the other side, try to re-attach # then try again error_status["retry"] = True self.comm.attach_remote( self.id, self.remote_name, remote_name=self.name, **self.init_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 write_message(self, message): """ Writes a message to this chat connection's handler """
logging.debug("Sending message {mes} to {usr}".format(mes=message, usr=self.id)) self.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 join_room(self, room_name): """ Connects to a given room If it does not exist it is created"""
logging.debug('Joining room {ro}'.format(ro=room_name)) for room in self.rooms: if room.name == room_name: room.add_user(self) self._rooms[room_name] = room room.welcome(self) break else: room = Room(room_name) self.rooms.append(room) self._rooms[room_name] = room room.add_user(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_to_room(self, message, room_name): """ Sends a given message to a given room """
room = self.get_room(room_name) if room is not None: room.send_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 _send_to_all_rooms(self, message): """ Send a message to all connected rooms """
for room in self._rooms.values(): room.send_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 close(self): """ Closes the connection by removing the user from all rooms """
logging.debug('Closing for user {user}'.format(user=self.id.name)) self.id.release_name() for room in self._rooms.values(): room.disconnect(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 get_parents(obj, **kwargs):
num_of_mro = kwargs.get("num_of_mro", 5) mro = getmro(obj.__class__) mro_string = ', '.join([extract_type(str(t)) for t in mro[:num_of_mro]]) return "Hierarchy: {}".format(mro_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 lpad(s, N, char='\0'): """pads a string to the left with null-bytes or any other given character. ..note:: This is used by the :py:func:`xor` function. :param s: the string :param N: an integer of how much padding should be done :returns: the original bytes """
assert isinstance(char, bytes) and len(char) == 1, 'char should be a string with length 1' return s.rjust(N, char)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rpad(s, N, char='\0'): """pads a string to the right with null-bytes or any other given character. ..note:: This is used by the :py:func:`xor` function. :param s: the string :param N: an integer of how much padding should be done :returns: the original bytes """
assert isinstance(char, bytes) and len(char) == 1, 'char should be a string with length 1' return s.ljust(N, char)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xor(left, right): """xor 2 strings. They can be shorter than each other, in which case the shortest will be padded with null bytes at its right. :param left: a string to be the left side of the xor :param right: a string to be the left side of the xor """
maxlength = max(map(len, (left, right))) ileft = string_to_int(rpad(left, maxlength)) iright = string_to_int(rpad(right, maxlength)) xored = ileft ^ iright return int_to_string(xored)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slugify(string, repchar='_'): """replaces all non-alphanumeric chars in the string with the given repchar. :param string: the source string :param repchar: """
slug_regex = re.compile(r'(^[{0}._-]+|[^a-z-A-Z0-9_.-]+|[{0}._-]+$)'.format(repchar)) strip_regex = re.compile(r'[{0}._-]+'.format(repchar)) transformations = [ lambda x: slug_regex.sub(repchar, x), lambda x: strip_regex.sub(repchar, x), lambda x: x.strip(repchar), lambda x: x.lower(), ] result = string for process in transformations: result = process(result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, *args, **kwargs): """Find and call local method."""
action = kwargs.pop('action', 'default') action_method = getattr(self, str(action), self.default) return action_method(*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 update(self, **kwargs): """Creates or updates a property for the instance for each parameter."""
for key, value in kwargs.items(): setattr(self, key, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def template_ds(basedir, varname, vars, lookup_fatal=True, depth=0): ''' templates a data structure by traversing it and substituting for other data structures ''' if isinstance(varname, basestring): m = _varFind(basedir, varname, vars, lookup_fatal, depth) if not m: return varname if m['start'] == 0 and m['end'] == len(varname): if m['replacement'] is not None: return template_ds(basedir, m['replacement'], vars, lookup_fatal, depth) else: return varname else: return template(basedir, varname, vars, lookup_fatal) elif isinstance(varname, (list, tuple)): return [template_ds(basedir, v, vars, lookup_fatal, depth) for v in varname] elif isinstance(varname, dict): d = {} for (k, v) in varname.iteritems(): d[k] = template_ds(basedir, v, vars, lookup_fatal, depth) return d else: return varname
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def template(basedir, text, vars, lookup_fatal=True, expand_lists=False): ''' run a text buffer through the templating engine until it no longer changes ''' try: text = text.decode('utf-8') except UnicodeEncodeError: pass # already unicode text = varReplace(basedir, unicode(text), vars, lookup_fatal=lookup_fatal, expand_lists=expand_lists) 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 template_from_file(basedir, path, vars): ''' run a file through the templating engine ''' from cirruscluster.ext.ansible import utils realpath = utils.path_dwim(basedir, path) loader=jinja2.FileSystemLoader([basedir,os.path.dirname(realpath)]) environment = jinja2.Environment(loader=loader, trim_blocks=True) for filter_plugin in utils.plugins.filter_loader.all(): filters = filter_plugin.filters() if not isinstance(filters, dict): raise errors.AnsibleError("FilterModule.filters should return a dict.") environment.filters.update(filters) try: data = codecs.open(realpath, encoding="utf8").read() except UnicodeDecodeError: raise errors.AnsibleError("unable to process as utf-8: %s" % realpath) except: raise errors.AnsibleError("unable to read %s" % realpath) # Get jinja env overrides from template if data.startswith(JINJA2_OVERRIDE): eol = data.find('\n') line = data[len(JINJA2_OVERRIDE):eol] data = data[eol+1:] for pair in line.split(','): (key,val) = pair.split(':') setattr(environment,key.strip(),val.strip()) environment.template_class = J2Template t = environment.from_string(data) vars = vars.copy() try: template_uid = pwd.getpwuid(os.stat(realpath).st_uid).pw_name except: template_uid = os.stat(realpath).st_uid vars['template_host'] = os.uname()[1] vars['template_path'] = realpath vars['template_mtime'] = datetime.datetime.fromtimestamp(os.path.getmtime(realpath)) vars['template_uid'] = template_uid vars['template_fullpath'] = os.path.abspath(realpath) vars['template_run_date'] = datetime.datetime.now() managed_default = C.DEFAULT_MANAGED_STR managed_str = managed_default.format( host = vars['template_host'], uid = vars['template_uid'], file = vars['template_path'] ) vars['ansible_managed'] = time.strftime(managed_str, time.localtime(os.path.getmtime(realpath))) # This line performs deep Jinja2 magic that uses the _jinja2_vars object for vars # Ideally, this could use some API where setting shared=True and the object won't get # passed through dict(o), but I have not found that yet. res = jinja2.utils.concat(t.root_render_func(t.new_context(_jinja2_vars(basedir, vars, t.globals), shared=True))) if data.endswith('\n') and not res.endswith('\n'): res = res + '\n' return template(basedir, res, vars)
<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_locals(self, locals): ''' If locals are provided, create a copy of self containing those locals in addition to what is already in this variable proxy. ''' if locals is None: return self return _jinja2_vars(self.basedir, self.vars, self.globals, locals, *self.extras)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expire_cache(fragment_name, *args): """ Expire a cache item. @param url: The url object @param product_names: A list of product names @param start: The date from which the reporting should start. @param stop: The date at which the reporting should stop. """
cache_key = make_template_fragment_key(fragment_name, args) cache.delete(cache_key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Start the installation wizard """
self.log.debug('Starting the installation process') self.browser.open(self.url) self.system_check()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def admin(self): """ Provide admin login credentials """
self._check_title(self.browser.title()) self.browser.select_form(nr=0) # Get the admin credentials prompted = [] user = self.ctx.config.get('User', 'AdminUser') if not user: user = click.prompt('Admin display name') prompted.append('user') password = self.ctx.config.get('User', 'AdminPass') if not password: password = click.prompt('Admin password', hide_input=True, confirmation_prompt='Confirm admin password') prompted.append('password') email = self.ctx.config.get('User', 'AdminEmail') if not email: email = click.prompt('Admin email') prompted.append('email') self.browser.form[self.FIELD_ADMIN_USER] = user self.browser.form[self.FIELD_ADMIN_PASS] = password self.browser.form[self.FIELD_ADMIN_PASS_CONFIRM] = password self.browser.form[self.FIELD_ADMIN_EMAIL] = email p = Echo('Submitting admin information...') self.browser.submit() p.done() if len(prompted) >= 3: save = click.confirm('Would you like to save and use these admin credentials for future installations?') if save: self.log.info('Saving admin login credentials') self.ctx.config.set('User', 'AdminUser', user) self.ctx.config.set('User', 'AdminPass', password) self.ctx.config.set('User', 'AdminEmail', email) with open(self.ctx.config_path, 'wb') as cf: self.ctx.config.write(cf) self.install()
<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_install(self): """ Start the installation """
self._check_title(self.browser.title()) continue_link = next(self.browser.links(text_regex='Start Installation')) self.browser.follow_link(continue_link)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(self): """ Run the actual installation """
self._start_install() mr_link = self._get_mr_link() # Set up the progress bar pbar = ProgressBar(100, 'Running installation...') pbar.start() mr_j, mr_r = self._ajax(mr_link) # Loop until we get a redirect json response while True: mr_link = self._parse_response(mr_link, mr_j) stage = self._get_stage(mr_j) progress = self._get_progress(mr_j) mr_j, mr_r = self._ajax(mr_link) pbar.update(min([progress, 100]), stage) # NOTE: Response may return progress values above 100 # If we're done, finalize the installation and break redirect = self._check_if_complete(mr_link, mr_j) if redirect: pbar.finish() break p = Echo('Finalizing...') mr_r = self._request(redirect, raise_request=False) p.done() # Install developer tools if self.site.in_dev: DevToolsInstaller(self.ctx, self.site).install() # Get the link to our community homepage self._finalize(mr_r)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pipe_cloexec(): """Create a pipe with FDs set CLOEXEC."""
# Pipes' FDs are set CLOEXEC by default because we don't want them # to be inherited by other subprocesses: the CLOEXEC flag is removed # from the child's FDs by _dup2(), between fork() and exec(). # This is not atomic: we would need the pipe2() syscall for that. r, w = os.pipe() _set_cloexec_flag(r) _set_cloexec_flag(w) return r, w
<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_signature(self, base_commit=None): """Get the signature of the current state of the repository TODO right now `get_signature` is an effectful process in that it adds all untracked file to staging. This is the only way to get accruate diff on new files. This is ok because we only use it on a disposable copy of the repo. Args: base_commit - the base commit ('HEAD', sha, etc.) Returns: str """
if base_commit is None: base_commit = 'HEAD' self.run('add', '-A', self.path) sha = self.run('rev-parse', '--verify', base_commit).strip() diff = self.run('diff', sha).strip() if len(diff) == 0: try: return self.get_signature(base_commit + '~1') except CommandError: pass h = hashlib.sha1() h.update(sha) h.update(diff) return h.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_hook(self, hook_name, hook_content): """Install the repository hook for this repo. Args: hook_name (str) hook_content (str) """
hook_path = os.path.join(self.path, '.git/hooks', hook_name) with open(hook_path, 'w') as f: f.write(hook_content) os.chmod(hook_path, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)
<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_ignored_files(self): """Returns the list of files being ignored in this repository. Note that file names, not directories, are returned. So, we will get the following: a/b.txt a/c.txt instead of just: a/ Returns: List[str] - list of ignored files. The paths are absolute. """
return [os.path.join(self.path, p) for p in self.run('ls-files', '--ignored', '--exclude-standard', '--others').strip().split() ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path_is_ignored(self, path): """Given a path, check if the path would be ignored. Returns: boolean """
try: self.run('check-ignore', '--quiet', path) except CommandError as e: if e.retcode == 1: # path is ignored return False else: # fatal error raise e 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_object_pydoc_page_name(obj): """Returns fully qualified name, including module name, except for the built-in module."""
page_name = fullqualname.fullqualname(obj) if page_name is not None: page_name = _remove_builtin_prefix(page_name) return page_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 _remove_builtin_prefix(name): """Strip name of builtin module from start of name."""
if name.startswith('builtins.'): return name[len('builtins.'):] elif name.startswith('__builtin__.'): return name[len('__builtin__.'):] return 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_ns_object(shell, path): """Get object from the user namespace, given a path containing zero or more dots. Return None if the path is not valid. """
parts = path.split('.', 1) name, attr = parts[0], parts[1:] if name in shell.user_ns: if attr: try: return _getattr(shell.user_ns[name], attr[0]) except AttributeError: return None else: return shell.user_ns[name] 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 _stop_process(p, name): """Stop process, by applying terminate and kill."""
# Based on code in IPython.core.magics.script.ScriptMagics.shebang if p.poll() is not None: print("{} is already stopped.".format(name)) return p.terminate() time.sleep(0.1) if p.poll() is not None: print("{} is terminated.".format(name)) return p.kill() print("{} is killed.".format(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 pydoc_cli_monkey_patched(port): """In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process. """
# Monkey-patch input so that input does not raise EOFError when # called by pydoc.cli def input(_): # pylint: disable=W0622 """Monkey-patched version of builtins.input""" while 1: time.sleep(1.0) import builtins builtins.input = input sys.argv += ["-p", port] pydoc.cli()
<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_server_background(port): """Start the newtab server as a background process."""
if sys.version_info[0] == 2: lines = ('import pydoc\n' 'pydoc.serve({port})') cell = lines.format(port=port) else: # The location of newtabmagic (normally $IPYTHONDIR/extensions) # needs to be added to sys.path. path = repr(os.path.dirname(os.path.realpath(__file__))) lines = ('import sys\n' 'sys.path.append({path})\n' 'import newtabmagic\n' 'newtabmagic.pydoc_cli_monkey_patched({port})') cell = lines.format(path=path, port=port) # Use script cell magic so that shutting down IPython stops # the server process. line = "python --proc proc --bg --err error --out output" ip = get_ipython() ip.run_cell_magic("script", line, cell) return ip.user_ns['proc']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _port_not_in_use(): """Use the port 0 trick to find a port not in use."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 0 s.bind(('', port)) _, port = s.getsockname() return 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 start(self): """Start server if not previously started."""
msg = '' if not self.running(): if self._port == 0: self._port = _port_not_in_use() self._process = start_server_background(self._port) else: msg = 'Server already started\n' msg += 'Server running at {}'.format(self.url()) print(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self): """Read stdout and stdout pipes if process is no longer running."""
if self._process and self._process.poll() is not None: ip = get_ipython() err = ip.user_ns['error'].read().decode() out = ip.user_ns['output'].read().decode() else: out = '' err = '' return out, err
<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): """Stop server process."""
msg = '' if self._process: _stop_process(self._process, 'Server process') else: msg += 'Server not started.\n' if msg: print(msg, end='')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(self): """Show state."""
msg = '' if self._process: msg += 'server pid: {}\n'.format(self._process.pid) msg += 'server poll: {}\n'.format(self._process.poll()) msg += 'server running: {}\n'.format(self.running()) msg += 'server port: {}\n'.format(self._port) msg += 'server root url: {}\n'.format(self.url()) print(msg, end='')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """! Start all receiving threads. """
if self.isThreadsRunning: raise ThreadManagerException("Broker threads are already running") self.isThreadsRunning = True for client in self.clients: threading.Thread(target = client).start()
<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): """! Stop all receving threads. """
if not self.isThreadsRunning: raise ThreadManagerException("Broker threads are already stopped") self.isThreadsRunning = False for client in self.clients: client.stop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onConnect(self, client, userdata, flags, rc): """! The callback for when the client receives a CONNACK response from the server. @param client @param userdata @param flags @param rc """
for sub in self.subsciption: (result, mid) = self.client.subscribe(sub)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onMessage(self, client, userdata, msg): """! The callback for when a PUBLISH message is received from the server. @param client @param userdata @param msg """
dataIdentifier = DataIdentifier(self.broker, msg.topic) self.dataHandler.onNewData(dataIdentifier, msg.payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createReceiverID(self): """! Create new receiver ID. @return Receiver ID. """
_receiverID = self.receiverCounter self.receiverCounter += 1 return BrokerReceiverID(self.hostname, self.pid, _receiverID)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_actions(self, request, view): """Allow all allowed methods"""
from rest_framework.generics import GenericAPIView actions = {} excluded_methods = {'HEAD', 'OPTIONS', 'PATCH', 'DELETE'} for method in set(view.allowed_methods) - excluded_methods: view.request = clone_request(request, method) try: if isinstance(view, GenericAPIView): has_object = view.lookup_url_kwarg or view.lookup_field in view.kwargs elif method in {'PUT', 'POST'}: has_object = method in {'PUT'} else: continue # Test global permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request) # Test object permissions if has_object and hasattr(view, 'get_object'): view.get_object() except (exceptions.APIException, PermissionDenied, Http404): pass else: # If user has appropriate permissions for the view, include # appropriate metadata about the fields that should be supplied. serializer = view.get_serializer() actions[method] = self.get_serializer_info(serializer) finally: view.request = request return actions
<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_within_content_length_limit(payload, api_config): """ Check that the message content is within the configured length limit. """
length_limit = api_config.get('content_length_limit') if (length_limit is not None) and (payload["content"] is not None): content_length = len(payload["content"]) if content_length > length_limit: return "Payload content too long: %s > %s" % ( content_length, length_limit) 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 get_option(name, key_options, global_options, default=None): """ Search the key-specific options and the global options for a given setting. Either dictionary may be None. This will first search the key settings and then the global settings. :param name: The setting to search for :param key_options: The item specific settings :param global_options: General method parameters :return: The option, if found, or None """
if key_options: try: return key_options[name] except KeyError: pass if global_options: try: return global_options[name] except KeyError: pass return default
<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_quiet(mres, parent, global_options): """ Sets the 'quiet' property on the MultiResult """
quiet = global_options.get('quiet') if quiet is not None: mres._quiet = quiet else: mres._quiet = parent.quiet
<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_cas(key_options, global_options, item): """ Get the CAS from various inputs. This will properly honor the ``ignore_cas`` flag, if present. :param key_options: Key specific options :param global_options: Global options :param item: The item :return: The cas, or 0 if no cas """
if item: ign_cas = get_option('ignore_cas', key_options, globals(), False) return 0 if ign_cas else item.cas else: try: cas = key_options['cas'] except KeyError: try: cas = global_options['cas'] except KeyError: return 0 if not cas: return 0 return cas
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(context, subject, debug, no_colors): """ Eh is a terminal program that will provide you with quick reminders about a subject. To get started run: eh help To figure out what eh knows about run: eh list To update the list of subjects: eh update Note: Eh will make a directory in your userhome called .eh where it will store downloaded subjects. """
eho = Eh(debug, no_colors) if subject == 'list': eho.subject_list() exit(0) if subject == 'update': eho.update_subject_repo() exit(0) eho.run(subject) exit(0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store_data(data): """Use this function to store data in a JSON file. This function is used for loading up a JSON file and appending additional data to the JSON file. :param data: the data to add to the JSON file. :type data: dict """
with open(url_json_path) as json_file: try: json_file_data = load(json_file) json_file_data.update(data) except (AttributeError, JSONDecodeError): json_file_data = data with open(url_json_path, 'w') as json_file: dump(json_file_data, json_file, indent=4, sort_keys=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 default_to_hashed_rows(self, default=None): """ Gets the current setting with no parameters, sets it if a boolean is passed in :param default: the value to set :return: the current value, or new value if default is set to True or False """
if default is not None: self._default_to_hashed_rows = (default is True) return self._default_to_hashed_rows
<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_dict_row(self, feature_dict, key=None): """ Add a dict row to the matrix :param str key: key used when rows is a dict rather than an array :param dict feature_dict: a dictionary of features and weights """
self._update_internal_column_state(set(feature_dict.keys())) # reset the row memoization self._row_memo = {} if key is not None: if key in self._row_name_idx: self._rows[self._row_name_idx[key]] = feature_dict return else: self._row_name_idx[key] = len(self._rows) self._row_name_list.append(key) self._rows.append(feature_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 _add_list_row(self, feature_list, key=None): """ Add a list row to the matrix :param str key: key used when rows is a dict rather than an array :param feature_list: a list of features in the same order as column_names :raise IndexError: if the list doesnt match the expected number of columns """
if len(feature_list) > len(self._column_name_list): raise IndexError("Input list must have %s columns or less" % len(self._column_name_list)) # reset the row memoization self._row_memo = {} if key is not None: if key in self._row_name_idx: self._rows[self._row_name_idx[key]] = feature_list return else: self._row_name_idx[key] = len(self._rows) self._row_name_list.append(key) self._rows.append(feature_list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_row(self, list_or_dict, key=None): """ Adds a list or dict as a row in the FVM data structure :param str key: key used when rows is a dict rather than an array :param list_or_dict: a feature list or dict """
if isinstance(list_or_dict, list): self._add_list_row(list_or_dict, key) else: self._add_dict_row(list_or_dict, key)