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 ExecuteCmd(cmd, quiet=False): """ Run a command in a shell. """
result = None if quiet: with open(os.devnull, "w") as fnull: result = subprocess.call(cmd, shell=True, stdout=fnull, stderr=fnull) else: result = subprocess.call(cmd, shell=True) 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 CheckOutput(*popenargs, **kwargs): """ Run command with arguments and return its output as a byte string. Backported from Python 2.7 as it's implemented as pure python on stdlib. """
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, _ = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] error = subprocess.CalledProcessError(retcode, cmd) error.output = output raise error return retcode, output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def UrlGet(url, timeout=10, retries=0): """ Retrieve content from the given URL. """
# in Python 2.6 we can pass timeout to urllib2.urlopen socket.setdefaulttimeout(timeout) attempts = 0 content = None while not content: try: content = urllib2.urlopen(url).read() except urllib2.URLError: attempts = attempts + 1 if attempts > retries: raise IOError('Failed to fetch url: %s' % url) return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ReadRemoteFile(remote_file_path, hostname, ssh_key): """ Reads a remote file into a string. """
cmd = 'sudo cat %s' % remote_file_path exit_code, output = RunCommandOnHost(cmd, hostname, ssh_key) if exit_code: raise IOError('Can not read remote path: %s' % (remote_file_path)) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __RemoteExecuteHelper(args): """ Helper for multiprocessing. """
cmd, hostname, ssh_key = args #Random.atfork() # needed to fix bug in old python 2.6 interpreters private_key = paramiko.RSAKey.from_private_key(StringIO.StringIO(ssh_key)) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) while True: try: client.connect(hostname, username='ubuntu', pkey=private_key, allow_agent=False, look_for_keys=False) break except socket.error as e: print '.' time.sleep(5) except paramiko.AuthenticationException as e: print e time.sleep(5) channel = client.get_transport().open_session() channel.exec_command(cmd) exit_code = channel.recv_exit_status() output = channel.recv(1000000) client.close() return exit_code, output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def WaitForHostsReachable(hostnames, ssh_key): """ Blocks until host is reachable via ssh. """
while True: unreachable = GetUnreachableHosts(hostnames, ssh_key) if unreachable: print 'waiting for unreachable hosts: %s' % unreachable time.sleep(5) else: break return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetUnreachableInstances(instances, ssh_key): """ Returns list of instances unreachable via ssh. """
hostnames = [i.private_ip for i in instances] ssh_status = AreHostsReachable(hostnames, ssh_key) assert(len(hostnames) == len(ssh_status)) nonresponsive_instances = [instance for (instance, ssh_ok) in zip(instances, ssh_status) if not ssh_ok] return nonresponsive_instances
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetUnreachableHosts(hostnames, ssh_key): """ Returns list of hosts unreachable via ssh. """
ssh_status = AreHostsReachable(hostnames, ssh_key) assert(len(hostnames) == len(ssh_status)) nonresponsive_hostnames = [host for (host, ssh_ok) in zip(hostnames, ssh_status) if not ssh_ok] return nonresponsive_hostnames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AreHostsReachable(hostnames, ssh_key): """ Returns list of bools indicating if host reachable via ssh. """
# validate input for hostname in hostnames: assert(len(hostname)) ssh_ok = [exit_code == 0 for (exit_code, _) in RunCommandOnHosts('echo test > /dev/null', hostnames, ssh_key)] return ssh_ok
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AmiName(ami_release_name, ubuntu_release_name, virtualization_type, mapr_version, role): """ Returns AMI name using Cirrus ami naming convention. """
if not role in valid_instance_roles: raise RuntimeError('Specified role (%s) not a valid role: %s' % (role, valid_instance_roles)) if virtualization_type not in valid_virtualization_types: raise RuntimeError('Specified virtualization type (%s) not valid: %s' % (virtualization_type, valid_virtualization_types)) ami_name = 'cirrus-%s-ubuntu-%s-%s-mapr%s-%s' % (ami_release_name, ubuntu_release_name, virtualization_type, mapr_version, role) return ami_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 LookupCirrusAmi(ec2, instance_type, ubuntu_release_name, mapr_version, role, ami_release_name, ami_owner_id): """ Returns AMI satisfying provided constraints. """
if not role in valid_instance_roles: raise RuntimeError('Specified role (%s) not a valid role: %s' % (role, valid_instance_roles)) virtualization_type = 'paravirtual' if IsHPCInstanceType(instance_type): virtualization_type = 'hvm' assert(ami_owner_id) images = ec2.get_all_images(owners=[ami_owner_id]) ami = None ami_name = AmiName(ami_release_name, ubuntu_release_name, virtualization_type, mapr_version, role) for image in images: if image.name == ami_name: ami = image break return ami
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetRegion(region_name): """ Converts region name string into boto Region object. """
regions = boto_ec2.regions() region = None valid_region_names = [] for r in regions: valid_region_names.append(r.name) if r.name == region_name: region = r break if not region: logging.info( 'invalid region name: %s ' % (region_name)) logging.info( 'Try one of these:\n %s' % ('\n'.join(valid_region_names))) assert(False) return region
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PrivateToPublicOpenSSH(key, host): """ Computes the OpenSSH public key format given a private key. """
# Create public key from private key. ssh_rsa = '00000007' + base64.b16encode('ssh-rsa') # Exponent. exponent = '%x' % (key.e,) if len(exponent) % 2: exponent = '0' + exponent ssh_rsa += '%08x' % (len(exponent) / 2,) ssh_rsa += exponent modulus = '%x' % (key.n,) if len(modulus) % 2: modulus = '0' + modulus if modulus[0] in '89abcdef': modulus = '00' + modulus ssh_rsa += '%08x' % (len(modulus) / 2,) ssh_rsa += modulus hash_string = base64.b64encode(base64.b16decode(ssh_rsa.upper())) public_key = 'ssh-rsa %s %s' % (hash_string, host) return public_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 InitKeypair(aws_id, aws_secret, ec2, s3, keypair_name, src_region, dst_regions): """ Returns the ssh private key for the given keypair name Cirrus created bucket. Creates the keypair if it doesn't yet exist and stores private key in S3. """
# check if a keypair has been created metadata = CirrusAccessIdMetadata(s3, aws_id) keypair = ec2.get_key_pair(keypair_name) ssh_key = None if keypair: # if created, check that private key is available in s3 ssh_key = metadata.GetSshKey(keypair_name) # if the private key is not created or not available in s3, recreate it if not ssh_key: if keypair: ec2.delete_key_pair(keypair_name) print 'Recreating keypair: %s' % (keypair_name) # create new key in current region_name keypair = ec2.create_key_pair(keypair_name) ssh_key = keypair.material metadata.SetSshKey(keypair_name, ssh_key) DistributeKeyToRegions(src_region, dst_regions, keypair, aws_id, aws_secret) assert(keypair) assert(ssh_key) return ssh_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 __WaitForVolume(volume, desired_state): """ Blocks until EBS volume is in desired state. """
print 'Waiting for volume %s to be %s...' % (volume.id, desired_state) while True: volume.update() sys.stdout.write('.') sys.stdout.flush() #print 'status is: %s' % volume.status if volume.status == desired_state: break time.sleep(5) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def WaitForSnapshotCompleted(snapshot): """ Blocks until snapshot is complete. """
print 'Waiting for snapshot %s to be completed...' % (snapshot) while True: snapshot.update() sys.stdout.write('.') sys.stdout.flush() #print 'status is: %s' % snapshot.status if snapshot.status == 'completed': break time.sleep(5) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __WaitForInstance(instance, desired_state): """ Blocks until instance is in desired_state. """
print 'Waiting for instance %s to change to %s' % (instance.id, desired_state) while True: try: instance.update() state = instance.state sys.stdout.write('.') sys.stdout.flush() if state == desired_state: break except boto_exception.EC2ResponseError as e: logging.info(e) #except boto_exception.ResponseError as e: # This is an alias # logging.info(e) time.sleep(5) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SearchUbuntuAmiDatabase(release_name, region_name, root_store_type, virtualization_type): """ Returns the ubuntu created ami matching the given criteria. """
ami_list_url = 'http://cloud-images.ubuntu.com/query/%s/server/released.txt' \ % (release_name) url_file = urllib2.urlopen(ami_list_url) # The mapping of columns names to col ids in the ubuntu release txt file. release_name_col = 0 release_tag_col = 2 release_date_col = 3 root_store_type_col = 4 arch_col = 5 region_col = 6 ami_col = 7 matching_amis = [] # list of tuples (ami_id, tokens) for line in url_file: tokens = line.split() # lines have different number of columns (one fewer for hvm) if (len(tokens) == 9): virtualization_type_col = 8 elif (len(tokens) == 10): virtualization_type_col = 9 else: raise RuntimeError('invalid line format: %s' % line) if tokens[release_name_col] == release_name \ and tokens[release_tag_col] == 'release' \ and tokens[root_store_type_col] == root_store_type \ and tokens[arch_col] == 'amd64' \ and tokens[region_col] == region_name \ and tokens[virtualization_type_col] == virtualization_type: matching_amis.append((tokens[ami_col], tokens)) matching_amis.sort(key=lambda (ami, tokens) : tokens[release_date_col], reverse=True) # order newest first if not matching_amis: params = [release_name, root_store_type, region_name, virtualization_type] raise RuntimeError('Failed to find matching ubuntu ami: %s', params) selected_ami = matching_amis[0][0] return selected_ami
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def render(self, request, context, status=codes.ok, content_type=None, args=None, kwargs=None): "Expects the method handler to return the `context` for the template." if isinstance(self.template_name, (list, tuple)): template = loader.select_template(self.template_name) elif self.template_name: template = loader.get_template(self.template_name) else: template = loader.Template(self.template_string) context = RequestContext(request, context) content = template.render(context) return HttpResponse(content, status=status, content_type=content_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 prompt_autocomplete(prompt, complete, default=None, contains_spaces=True, show_default=True, prompt_suffix=': ', color=None): """ Prompt a string with autocompletion :param complete: A function that returns a list of possible strings that should be completed on a given text. """
def real_completer(text, state): possibilities = complete(text) + [None] if possibilities: return possibilities[state] return None readline.set_completer_delims('\t\n' + ' ' * (not contains_spaces)) readline.parse_and_bind("tab: complete") readline.set_completer(real_completer) if default is not None and show_default: prompt += ' [%s]' % default prompt += prompt_suffix colors = { 'red': Fore.RED, 'blue': Fore.BLUE, 'green': Fore.GREEN, 'cyan': Fore.CYAN, 'magenta': Fore.MAGENTA, 'yellow': Fore.YELLOW, 'white': Fore.WHITE, 'black': Fore.LIGHTBLACK_EX } if color: prompt = colors[color.lower()] + prompt + Fore.RESET if default is not None: r = input(prompt) else: while True: r = input(prompt) if r: break r = r or default # remove the autocompletion before quitting for future input() readline.parse_and_bind('tab: self-insert') readline.set_completer(None) return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_file(prompt, default=None, must_exist=True, is_dir=False, show_default=True, prompt_suffix=': ', color=None): """ Prompt a filename using using glob for autocompetion. If must_exist is True (default) then you can be sure that the value returned is an existing filename or directory name. If is_dir is True, this will show only the directories for the completion. """
if must_exist: while True: r = prompt_autocomplete(prompt, path_complete(is_dir), default, show_default=show_default, prompt_suffix=prompt_suffix, color=color) if os.path.exists(r): break print('This path does not exist.') else: r = prompt_autocomplete(prompt, path_complete(is_dir), default, show_default=show_default, prompt_suffix=prompt_suffix, color=color) return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_choice(prompt, possibilities, default=None, only_in_poss=True, show_default=True, prompt_suffix=': ', color=None): """ Prompt for a string in a given range of possibilities. This also sets the history to the list of possibilities so the user can scroll is with the arrow to find what he wants, If only_in_poss is False, you are not guaranteed that this will return one of the possibilities. """
assert len(possibilities) >= 1 assert not only_in_poss or default is None or default in possibilities, '$s not in possibilities' % default contains_spaces = any(' ' in poss for poss in possibilities) possibilities = sorted(possibilities) readline.clear_history() for kw in possibilities: readline.add_history(kw) def complete(text): return [t for t in possibilities if t.startswith(text)] while 1: r = prompt_autocomplete(prompt, complete, default, contains_spaces=contains_spaces, show_default=show_default, prompt_suffix=prompt_suffix, color=color) if not only_in_poss or r in possibilities: break print('%s is not a possibility.' % r) readline.clear_history() return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_glide_depths(depths, mask_tag_filt): '''Plot depth at glides Args ---- depths: ndarray Depth values at each sensor sampling mask_tag_filt: ndarray Boolean mask to slice filtered sub-glides from tag data ''' import numpy from . import plotutils fig, ax = plt.subplots() ax = plotutils.plot_noncontiguous(ax, depths, numpy.where(mask_tag_filt)[0]) ax.invert_yaxis() plt.show() 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 verify_keys(self): """Verify that the public and private key combination is valid; raises MollomAuthenticationError otherwise"""
verify_keys_endpoint = Template("${rest_root}/site/${public_key}") url = verify_keys_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key) data = { "clientName": "mollom_python", "clientVersion": "1.0" } self._client.headers["Content-Type"] = "application/x-www-form-urlencoded" response = self._client.post(url, data, timeout=self._timeout) if response.status_code != 200: raise MollomAuthenticationError 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 check_captcha(self, captcha_id, solution, author_name=None, author_url=None, author_mail=None, author_ip=None, author_id=None, author_open_id=None, honeypot=None ): """Checks a CAPTCHA that was solved by the end-user. Keyword arguments: captcha_id -- Unique identifier of the CAPTCHA solved. solution -- Solution provided by the end-user for the CAPTCHA. author_name -- The name of the content author. author_url -- The homepage/website URL of the content author. author_mail -- The e-mail address of the content author. author_ip -- The IP address of the content author. author_id -- The local user ID on the client site of the content author. author_open_id -- List of Open IDs of the content author. honeypot -- The value of a client-side honeypot form element, if non-empty. Returns: solved -- Boolean whether or not the CAPTCHA was solved correctly. If the CAPTCHA is associated with an unsure contents, it is recommended to recheck the content. """
check_catpcha_endpoint = Template("${rest_root}/captcha/${captcha_id}") url = check_catpcha_endpoint.substitute(rest_root=self._rest_root, captcha_id=captcha_id) data = {"solution": solution} response = self.__post_request(url, data) # Mollom returns "1" for success and "0" for failure return response["captcha"]["solved"] == "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 get_blacklist_entries(self): """Get a list of all blacklist entries. """
get_blacklist_entries_endpoint = Template("${rest_root}/blacklist/${public_key}/") url = get_blacklist_entries_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key) response = self.__get_request(url) return response["list"]["entry"]
<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_blacklist_entry(self, blacklist_entry_id): """Get a single blacklist entry Keyword arguments: blacklist_entry_id -- The unique identifier of the blacklist entry to get. """
get_blacklist_entries_endpoint = Template("${rest_root}/blacklist/${public_key}/${blacklist_entry_id}") url = get_blacklist_entries_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key, blacklist_entry_id=blacklist_entry_id) response = self.__get_request(url) return response["entry"]
<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_deployment(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ create a deployment with the specified name """
headers = token_manager.get_access_token_headers() payload = { 'name': deployment_name, 'isAdmin': True } deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.post('%s/api/v1/deployments' % deployment_url, data=json.dumps(payload), headers=headers) if response.status_code == 201: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.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 get_deployments(token_manager=None, app_url=defaults.APP_URL): """ return the list of deployments that the current access_token gives you access to """
headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments' % deployment_url, headers=headers) if response.status_code == 200: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.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 get_deployment_id(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return the deployment id for the deployment with the specified name """
headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments' % deployment_url, headers=headers) if response.status_code == 200: deployments = response.json() for deployment in deployments: if deployment['name'] == deployment_name: return deployment['deployment_id'] raise JutException('Unable to find deployment with name %s' % deployment_name) else: raise JutException('Error %s: %s' % (response.status_code, response.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 get_space_id(deployment_name, space_name, token_manager=None, app_url=defaults.APP_URL): """ get the space id that relates to the space name provided """
spaces = get_spaces(deployment_name, token_manager=token_manager, app_url=app_url) for space in spaces: if space['name'] == space_name: return space['id'] raise JutException('Unable to find space "%s" within deployment "%s"' % (space_name, deployment_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 create_space(deployment_name, space_name, security_policy='public', events_retention_days=0, metrics_retention_days=0, token_manager=None, app_url=defaults.APP_URL): """ create a space within the deployment specified and with the various rentention values set """
deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) payload = { 'name': space_name, 'security_policy': security_policy, 'events_retention_days': events_retention_days, 'metrics_retention_days': metrics_retention_days, } headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.post('%s/api/v1/deployments/%s/spaces' % (deployment_url, deployment_id), data=json.dumps(payload), headers=headers) if response.status_code == 201: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.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 get_users(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ get all users in the deployment specified """
deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments/%s/accounts' % (deployment_url, deployment_id), headers=headers) if response.status_code == 200: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.text))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_user(username, deployment_name, token_manager=None, app_url=defaults.APP_URL): """ add user to deployment """
deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) account_id = accounts.get_account_id(username, token_manager=token_manager, app_url=app_url) headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.put('%s/api/v1/deployments/%s/accounts/%s' % (deployment_url, deployment_id, account_id), headers=headers) if response.status_code == 204: return response.text else: raise JutException('Error %s: %s' % (response.status_code, response.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 as_ul(self, current_linkable=False, class_current="active_link", before_1="", after_1="", before_all="", after_all=""): """ It returns menu as ul """
return self.__do_menu("as_ul", current_linkable, class_current, before_1=before_1, after_1=after_1, before_all=before_all, after_all=after_all)
<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_string(self, chars, current_linkable=False, class_current="active_link"): """ It returns menu as string """
return self.__do_menu("as_string", current_linkable, class_current, chars)
<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_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as ul """
return self.__do_menu("as_ul", show_leaf, current_linkable, class_current)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as p """
return self.__do_menu("as_p", show_leaf, current_linkable, class_current)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_string(self, chars, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as string """
return self.__do_menu("as_string", show_leaf, current_linkable, class_current, chars)
<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_config(filename, header): """ Parses the provided filename and returns ``SettingParser`` if the parsing was successful and header matches the header defined in the file. Returns ``SettingParser`` instance. * Raises a ``ParseError`` exception if header doesn't match or parsing fails. """
parser = SettingParser(filename) if parser.header != header: header_value = parser.header or '' raise ParseError(u"Unexpected header '{0}', expecting '{1}'" .format(common.from_utf8(header_value), header)) return parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_variable(obj, **kwargs): """Print the variable out. Limit the string length to, by default, 300 characters."""
variable_print_length = kwargs.get("variable_print_length", 1000) s = str(obj) if len(s) < 300: return "Printing the object:\n" + str(obj) else: return "Printing the object:\n" + str(obj)[:variable_print_length] + ' ...'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encompasses(self, span): """ Returns true if the given span fits inside this one """
if isinstance(span, list): return [sp for sp in span if self._encompasses(sp)] return self._encompasses(span)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encompassed_by(self, span): """ Returns true if the given span encompasses this span. """
if isinstance(span, list): return [sp for sp in span if sp.encompasses(self)] return span.encompasses(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 adds(self, string): """ Add a string child. """
if isinstance(string, unicode): string = string.encode("utf-8") self.children.append((STRING, str(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 delete(self): """ Delete this record without deleting any dependent or child records. This can orphan records, so use with care. """
if self.id: with Repo.db: Repo(self.__table).where(id=self.id).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 shorten(string, max_length=80, trailing_chars=3): ''' trims the 'string' argument down to 'max_length' to make previews to long string values ''' assert type(string).__name__ in {'str', 'unicode'}, 'shorten needs string to be a string, not {}'.format(type(string)) assert type(max_length) == int, 'shorten needs max_length to be an int, not {}'.format(type(max_length)) assert type(trailing_chars) == int, 'shorten needs trailing_chars to be an int, not {}'.format(type(trailing_chars)) assert max_length > 0, 'shorten needs max_length to be positive, not {}'.format(max_length) assert trailing_chars >= 0, 'shorten needs trailing_chars to be greater than or equal to 0, not {}'.format(trailing_chars) return ( string ) if len(string) <= max_length else ( '{before:}...{after:}'.format( before=string[:max_length-(trailing_chars+3)], after=string[-trailing_chars:] if trailing_chars>0 else '' ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_prettytable(string): """ returns true if the input looks like a prettytable """
return type(string).__name__ in {'str','unicode'} and ( len(string.splitlines()) > 1 ) and ( all(string[i] == string[-i-1] for i in range(3)) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_published_ships_basic(db_connection): """ Gets a list of all published ships and their basic information. :return: Each result has a tuple of (typeID, typeName, groupID, groupName, categoryID, and categoryName). :rtype: list """
if not hasattr(get_all_published_ships_basic, '_results'): sql = 'CALL get_all_published_ships_basic();' results = execute_sql(sql, db_connection) get_all_published_ships_basic._results = results return get_all_published_ships_basic._results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ships_that_have_variations(db_connection): """ Gets a list of all published ship type IDs that have at least 3 variations. :return: :rtype: list """
if not hasattr(get_ships_that_have_variations, '_results'): sql = 'CALL get_ships_that_have_variations();' results = execute_sql(sql, db_connection) get_ships_that_have_variations._results = results return get_ships_that_have_variations._results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def c14n(xml): ''' Applies c14n to the xml input @param xml: str @return: str ''' tree = etree.parse(StringIO(xml)) output = StringIO() tree.write_c14n(output, exclusive=False, with_comments=True, compression=0) output.flush() c14nized = output.getvalue() output.close() return c14nized
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sign(xml, private, public): ''' Return xmldsig XML string from xml_string of XML. @param xml: str of bytestring xml to sign @param private: publicKey Private key @param public: publicKey Public key @return str: signed XML byte string ''' xml = xml.encode('utf-8', 'xmlcharrefreplace') signed_info_xml = _generate_signed_info(xml) signer = PKCS1_v1_5.PKCS115_SigScheme(private) signature_value = signer.sign(SHA.new(c14n(signed_info_xml))) signature_xml = PTN_SIGNATURE_XML % { 'signed_info_xml': signed_info_xml, 'signature_value': binascii.b2a_base64(signature_value)[:-1], 'key_info_xml': _generate_key_info_xml_rsa(public.key.n, public.key.e) } position = xml.rfind('</') return xml[0:position] + signature_xml + xml[position:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def verify(xml): '''Verifies whether the validity of the signature contained in an XML document following the XMLDSig standard''' try: from cStringIO import cStringIO as StringIO except ImportError: from StringIO import StringIO xml = xml.encode('utf-8', 'xmlcharrefreplace') tree = etree.parse(StringIO(xml)) try: '''Isolating the Signature element''' signature_tree = tree.xpath('xmldsig:Signature', namespaces=NAMESPACES)[0] '''Removing the Signature element from the main tree to compute a new digest value with the actual content of the XML.''' signature_tree.getparent().remove(signature_tree) signed_info = _generate_signed_info(etree.tostring(tree)) '''Constructing the key from the Modulus and Exponent stored in the Signature/KeyInfo/KeyValue/RSAKeyValue element''' from Crypto.PublicKey import RSA modulus = signature_tree.xpath(KEY_INFO_PATH + '/xmldsig:Modulus', namespaces=NAMESPACES)[0].text exponent = signature_tree.xpath(KEY_INFO_PATH + '/xmldsig:Exponent', namespaces=NAMESPACES)[0].text public_key = RSA.construct((b64d(modulus), b64d(exponent))) '''Isolating the signature value to verify''' signature = signature_tree.xpath('xmldsig:SignatureValue', namespaces=NAMESPACES)[0].text except IndexError: raise RuntimeError('XML does not contain a properly formatted ' \ ' Signature element') verifier = PKCS1_v1_5.PKCS115_SigScheme(public_key) return verifier.verify(SHA.new(c14n(signed_info)), binascii.a2b_base64(signature))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autodiscover(): """ Perform an autodiscover of an api.py file in the installed apps to generate the routes of the registered viewsets. """
for app in settings.INSTALLED_APPS: try: import_module('.'.join((app, 'api'))) except ImportError as e: if e.msg != "No module named '{0}.api'".format(app): print(e.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 identify_module(arg): """Import and return the Python module named in `arg`. If the module cannot be imported, a `pywhich.ModuleNotFound` exception is raised. """
try: __import__(arg) except Exception: exc = sys.exc_info()[1] raise ModuleNotFound("%s: %s" % (type(exc).__name__, str(exc))) mod = sys.modules[arg] return mod
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def identify_modules(*args, **kwargs): """Find the disk locations of the given named modules, printing the discovered paths to stdout and errors discovering paths to stderr. Any provided keyword arguments are passed to `identify_filepath()`. """
if len(args) == 1: path_template = "%(file)s" error_template = "Module '%(mod)s' not found (%(error)s)" else: path_template = "%(mod)s: %(file)s" error_template = "%(mod)s: not found (%(error)s)" for modulename in args: try: filepath = identify_filepath(modulename, **kwargs) except ModuleNotFound: exc = sys.exc_info()[1] sys.stderr.write(error_template % { 'mod': modulename, 'error': str(exc), }) sys.stderr.write('\n') else: print(path_template % { 'mod': modulename, 'file': filepath })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_version(*args): """Find the versions of the given named modules, printing the discovered versions to stdout and errors discovering versions to stderr."""
if len(args) == 1: ver_template = "%(version)s" error_template = "Distribution/module '%(mod)s' not found (%(error)s)" else: ver_template = "%(mod)s: %(version)s" error_template = "%(mod)s: not found (%(error)s)" import pkg_resources for modulename in args: try: try: dist = pkg_resources.get_distribution(modulename) except pkg_resources.DistributionNotFound: mod = identify_module(modulename) # raises ModuleNotFound if not hasattr(mod, '__version__'): raise ModuleNotFound('module has no __version__') version = mod.__version__ else: version = dist.version except ModuleNotFound: exc = sys.exc_info()[1] sys.stderr.write(error_template % { 'mod': modulename, 'error': str(exc), }) sys.stderr.write('\n') else: print(ver_template % { 'mod': modulename, 'version': version, })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(argv=None): """Run the pywhich command as if invoked with arguments `argv`. If `argv` is `None`, arguments from `sys.argv` are used. """
if argv is None: argv = sys.argv parser = OptionParser() parser.add_option('-v', '--verbose', dest="verbose", action="count", default=2, help="be chattier (stackable)") def quiet(option, opt_str, value, parser): parser.values.verbose -= 1 parser.add_option('-q', '--quiet', action="callback", callback=quiet, help="be less chatty (stackable)") parser.add_option('-r', action="store_true", dest="real_path", default=False, help="dereference symlinks") parser.add_option('-b', action="store_true", dest="show_directory", default=False, help="show directory instead of filename") parser.add_option('-i', '--hide-init', action="store_true", dest="hide_init", default=False, help="show directory if the module ends in __init__.py") parser.add_option('-s', '--source', action="store_true", dest="find_source", default=False, help="find .py files for .pyc/.pyo files") parser.add_option('--ver', action="store_true", dest="find_version", default=False, help="find the version of the named package, not the location on disk") opts, args = parser.parse_args() verbose = max(0, min(4, opts.verbose)) log_levels = (logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG) logging.basicConfig() log.setLevel(log_levels[verbose]) if opts.find_version: find_version(*args) else: kwargs = dict((fld, getattr(opts, fld)) for fld in ('real_path', 'show_directory', 'find_source', 'hide_init')) identify_modules(*args, **kwargs) return 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 read_json_file(cls, path): """ Read an instance from a JSON-formatted file. :return: A new instance """
with open(path, 'r') as f: return cls.from_dict(json.load(f))
<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_json_file(self, path): """ Write the instance in JSON format to a file. """
with open(path, 'w') as f: json.dump(self.to_dict(), f, indent=2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(email): """Email address validation method. :param email: Email address to be saved. :type email: basestring :returns: True if email address is correct, False otherwise. :rtype: bool """
if isinstance(email, basestring) and EMAIL_RE.match(email): 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 check_password(self, raw_password): """Validates the given raw password against the intance's encrypted one. :param raw_password: Raw password to be checked against. :type raw_password: unicode :returns: True if comparison was successful, False otherwise. :rtype: bool :raises: :exc:`ImportError` if `py-bcrypt` was not found. """
bcrypt = self.get_bcrypt() return bcrypt.hashpw(raw_password, self.value)==self.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 is_archlinux(): """return True if the current distribution is running on debian like OS."""
if platform.system().lower() == 'linux': if platform.linux_distribution() == ('', '', ''): # undefined distribution. Fixed in python 3. if os.path.exists('/etc/arch-release'): 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 create_or_clear(self, path, **kwargs): """Create path and recursively clear contents."""
try: yield self.create(path, **kwargs) except NodeExistsException: children = yield self.get_children(path) for name in children: yield self.recursive_delete(path + "/" + 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 recursive_delete(self, path, **kwargs): """Recursively delete path."""
while True: try: yield self.delete(path, **kwargs) except NoNodeException: break except NotEmptyException: children = yield self.get_children(path) for name in children: yield self.recursive_delete(path + "/" + name) else: break
<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_path(self, path, **kwargs): """Create nodes required to complete path."""
i = 0 while i < len(path): i = path.find("/", i) if i < 0: return subpath = path[:i] if i > 0: try: yield self.create(subpath, **kwargs) except NodeExistsException: pass i += 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_or_create(self, path, *args, **kwargs): """Sets the data of a node at the given path, or creates it."""
d = self.set(path, *args, **kwargs) @d.addErrback def _error(result): return self.create(path, *args, **kwargs) return 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 get_or_wait(self, path, name): """Get data of node under path, or wait for it."""
# First, get children and watch folder. d, watch = self.get_children_and_watch(path) deferred = Deferred() path += "/" + name @watch.addCallback def _notify(event): if event.type_name == "child": d = self.get(path) d.addCallback(deferred.callback) # Retrieve children. children = yield d if name in children: watch.cancel() deferred = self.get(path) result = yield deferred returnValue(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 contiguous_regions(condition): '''Finds contiguous True regions of the boolean array 'condition'. Args ---- condition: numpy.ndarray, dtype bool boolean mask array, but can pass the condition itself (e.g. x > 5) Returns ------- start_ind: numpy.ndarray, dtype int array with the start indices for each contiguous region stop_ind: numpy.ndarray, dtype int array with the stop indices for each contiguous region Notes ----- This function is adpated from Joe Kington's answer on StackOverflow: http://stackoverflow.com/a/4495197/943773 ''' import numpy if condition.ndim > 1: raise IndexError('contiguous_regions(): condition must be 1-D') # Find the indicies of changes in 'condition' idx = numpy.diff(condition).nonzero()[0] if condition[0]: # If the start of condition is True prepend a 0 idx = numpy.r_[0, idx] if condition[-1]: # If the end of condition is True, append the length of the array idx = numpy.r_[idx, condition.size] # Edit # Reshape the result into two columns idx.shape = (-1,2) # We need to start things after the change in 'condition'. Therefore, # we'll shift the index by 1 to the right. start_ind = idx[:,0] + 1 # keep the stop ending just before the change in condition stop_ind = idx[:,1] # remove reversed or same start/stop index good_vals = (stop_ind-start_ind) > 0 start_ind = start_ind[good_vals] stop_ind = stop_ind[good_vals] return start_ind, stop_ind
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rm_regions(a, b, a_start_ind, a_stop_ind): '''Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has occured Args ---- a: ndarray Boolean array with regions of contiguous `True` values b: ndarray Boolean array with regions of contiguous `True` values a_start_ind: ndarray indices of start of `a` regions a_stop_ind: ndarray indices of stop of `a` regions Returns ------- a: ndarray Boolean array with regions for which began before a complimentary region in `b` have occured ''' import numpy for i in range(len(a_stop_ind)): next_a_start = numpy.argmax(a[a_stop_ind[i]:]) next_b_start = numpy.argmax(b[a_stop_ind[i]:]) if next_b_start > next_a_start: a[a_start_ind[i]:a_stop_ind[i]] = False return a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def recursive_input(input_label, type_class): '''Recursive user input prompter with type checker Args ---- type_class: type name of python type (e.g. float, no parentheses) Returns ------- output: str value entered by user converted to type `type_class` Note ---- Use `ctrl-c` to exit input cycling ''' import sys type_str = str(type_class).split("'")[1] msg = 'Enter {} (type `{}`): '.format(input_label, type_str) # Catch `Ctrl-c` keyboard interupts try: output = input(msg) print('') # Type class input, else cycle input function again try: output = type_class(output) return output except: print('Input must be of type `{}`\n'.format(type_str)) return recursive_input(input_label, type_class) # Keyboard interrupt passed, exit recursive input except KeyboardInterrupt: return sys.exit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def models_for_pages(*args): """ Create a select list containing each of the models that subclass the ``Page`` model. """
from warnings import warn warn("template tag models_for_pages is deprectaed, use " "PageAdmin.get_content_models instead") from yacms.pages.admin import PageAdmin return PageAdmin.get_content_models()
<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_model_permissions(context, token): """ Assigns a permissions dict to the given model, much like Django does with its dashboard app list. Used within the change list for pages, to implement permission checks for the navigation tree. """
model = context[token.split_contents()[1]] opts = model._meta perm_name = opts.app_label + ".%s_" + opts.object_name.lower() request = context["request"] setattr(model, "perms", {}) for perm_type in ("add", "change", "delete"): model.perms[perm_type] = request.user.has_perm(perm_name % perm_type) return ""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_page_permissions(context, token): """ Assigns a permissions dict to the given page instance, combining Django's permission for the page's model and a permission check against the instance itself calling the page's ``can_add``, ``can_change`` and ``can_delete`` custom methods. Used within the change list for pages, to implement permission checks for the navigation tree. """
page = context[token.split_contents()[1]] model = page.get_content_model() try: opts = model._meta except AttributeError: if model is None: error = _("Could not load the model for the following page, " "was it removed?") obj = page else: # A missing inner Meta class usually means the Page model # hasn't been directly subclassed. error = _("An error occured with the following class. Does " "it subclass Page directly?") obj = model.__class__.__name__ raise ImproperlyConfigured(error + " '%s'" % obj) perm_name = opts.app_label + ".%s_" + opts.object_name.lower() request = context["request"] setattr(page, "perms", {}) for perm_type in ("add", "change", "delete"): perm = request.user.has_perm(perm_name % perm_type) perm = perm and getattr(model, "can_%s" % perm_type)(request) page.perms[perm_type] = perm return ""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, *args, **kwargs): """ Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fields. """
if kwargs.has_key('author'): kwargs['created_by'] = kwargs['author'] kwargs['last_modified_by'] = kwargs['author'] del kwargs['author'] return super(CMSPageManager, self).create(*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 get_template_options(): """ Returns a list of all templates that can be used for CMS pages. The paths that are returned are relative to TURRENTINE_TEMPLATE_ROOT. """
template_root = turrentine_settings.TURRENTINE_TEMPLATE_ROOT turrentine_dir = turrentine_settings.TURRENTINE_TEMPLATE_SUBDIR output = [] for root, dirs, files in os.walk(turrentine_dir): for file_name in files: full_path = os.path.join(root, file_name) relative_path = os.path.relpath(full_path, template_root) output.append(relative_path) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def launch_shell(username, hostname, password, port=22): """ Launches an ssh shell """
if not username or not hostname or not password: return False with tempfile.NamedTemporaryFile() as tmpFile: os.system(sshCmdLine.format(password, tmpFile.name, username, hostname, port)) 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_match(self, key): """ Gets a MatchObject for the given key. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match. """
return self._get_string_match(key=key) or \ self._get_non_string_match(key=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 _get_non_string_match(self, key): """ Gets a MatchObject for the given key, assuming a non-string value. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match. """
expression = r'(?:\s*)'.join([ '^', 'define', r'\(', '\'{}\''.format(key), ',', r'(.*)', r'\)', ';' ]) pattern = re.compile(expression, re.MULTILINE) return pattern.search(self._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 _get_string_match(self, key): """ Gets a MatchObject for the given key, assuming a string value. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match. """
expression = r'(?:\s*)'.join([ '^', 'define', r'\(', '\'{}\''.format(key), ',', r'\'(.*)\'', r'\)', ';' ]) pattern = re.compile(expression, re.MULTILINE) return pattern.search(self._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 _get_value_from_match(self, key, match): """ Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match (MatchObject): The matched property. Return: The discovered value, as a string or boolean. """
value = match.groups(1)[0] clean_value = str(value).lstrip().rstrip() if clean_value == 'true': self._log.info('Got value of "%s" as boolean true.', key) return True if clean_value == 'false': self._log.info('Got value of "%s" as boolean false.', key) return False try: float_value = float(clean_value) self._log.info('Got value of "%s" as float "%f".', key, float_value) return float_value except ValueError: self._log.info('Got value of "%s" as string "%s".', key, clean_value) return clean_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 get(self, key): """ Gets the value of the property of the given key. Args: key (str): Key of the property to look-up. """
match = self._get_match(key=key) if not match: return None return self._get_value_from_match(key=key, match=match)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, key, value): """ Updates the value of the given key in the loaded content. Args: key (str): Key of the property to update. value (str): New value of the property. Return: bool: Indicates whether or not a change was made. """
match = self._get_match(key=key) if not match: self._log.info('"%s" does not exist, so it will be added.', key) if isinstance(value, str): self._log.info('"%s" will be added as a PHP string value.', key) value_str = '\'{}\''.format(value) else: self._log.info('"%s" will be added as a PHP object value.', key) value_str = str(value).lower() new = 'define(\'{key}\', {value});'.format( key=key, value=value_str) self._log.info('"%s" will be added as: %s', key, new) replace_this = '<?php\n' replace_with = '<?php\n' + new + '\n' self._content = self._content.replace(replace_this, replace_with) self._log.info('Content string has been updated.') return True if self._get_value_from_match(key=key, match=match) == value: self._log.info('"%s" is already up-to-date.', key) return False self._log.info('"%s" exists and will be updated.', key) start_index = match.start(1) end_index = match.end(1) if isinstance(value, bool): value = str(value).lower() self._log.info('"%s" will be updated with boolean value: %s', key, value) else: self._log.info('"%s" will be updated with string value: %s', key, value) start = self._content[:start_index] end = self._content[end_index:] self._content = start + value + end 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_buildout_config(buildout_filename): """Parse buildout config with zc.buildout ConfigParser """
print("[localhost] get_buildout_config: {0:s}".format(buildout_filename)) buildout = Buildout(buildout_filename, [('buildout', 'verbosity', '-100')]) while True: try: len(buildout.items()) break except OSError: pass return buildout
<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_buildout_parts(buildout, query=None): """Return buildout parts matching the given query """
parts = names = (buildout['buildout'].get('parts') or '').split('\n') for name in names: part = buildout.get(name) or {} for key, value in (query or {}).items(): if value not in (part.get(key) or ''): parts.remove(name) break return parts
<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_buildout_eggs(buildout, query=None): """Return buildout eggs matching the parts for the given query """
eggs = set() for name in get_buildout_parts(buildout, query=query): if name == 'buildout': continue # skip eggs from the buildout script itself path = os.path.join(buildout['buildout'].get('bin-directory'), name) if os.path.isfile(path): eggs.update(parse_eggs_list(path)) return list(eggs)
<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_eggs_list(path): """Parse eggs list from the script at the given path """
with open(path, 'r') as script: data = script.readlines() start = 0 end = 0 for counter, line in enumerate(data): if not start: if 'sys.path[0:0]' in line: start = counter + 1 if counter >= start and not end: if ']' in line: end = counter script_eggs = tidy_eggs_list(data[start:end]) return script_eggs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tidy_eggs_list(eggs_list): """Tidy the given eggs list """
tmp = [] for line in eggs_list: line = line.lstrip().rstrip() line = line.replace('\'', '') line = line.replace(',', '') if line.endswith('site-packages'): continue tmp.append(line) return tmp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, filename=None): """Download an attachment. The files are currently not cached since they can be overwritten on the server. Parameters filename : string, optional Optional name for the file on local disk. Returns ------- string Path to downloaded temporary file on disk """
tmp_file, f_suffix = download_file(self.url) if not filename is None: shutil.move(tmp_file, filename) return filename else: return tmp_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 attach_file(self, filename, resource_id=None): """Upload an attachment for the model run. Paramerers filename : string Path to uploaded file resource_id : string Identifier of the attachment. If None, the filename will be used as resource identifier. Returns ------- ModelRunHandle Refreshed run handle. """
# Use file base name as resource identifier if none given if resource_id is None: resource_id = os.path.basename(filename) # Need to append resource identifier to base attachment Url upload_url = self.links[REF_MODEL_RUN_ATTACHMENTS] + '/' + resource_id # Upload model output response = requests.post( upload_url, files={'file': open(filename, 'rb')} ) if response.status_code != 200: try: raise ValueError(json.loads(response.text)['message']) except KeyError as ex: raise ValueError('invalid state change: ' + str(response.text)) # Returned refreshed verion of the handle return self.refresh()
<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(url, model_id, name, arguments, properties=None): """Create a new model run using the given SCO-API create model run Url. Parameters url : string Url to POST model run create model run request model_id : string Unique model identifier name : string User-defined name for model run arguments : Dictionary Dictionary of arguments for model run properties : Dictionary, optional Set of additional properties for created mode run. Returns ------- string Url of created model run resource """
# Create list of model run arguments. Catch TypeErrors if arguments is # not a list. obj_args = [] try: for arg in arguments: obj_args.append({'name' : arg, 'value' : arguments[arg]}) except TypeError as ex: raise ValueError('invalid argument set') # Create request body and send POST request to given Url body = { 'model' : model_id, 'name' : name, 'arguments' : obj_args, } # Create list of properties if given. Catch TypeErrors if properties is # not a list. if not properties is None: obj_props = [] try: for key in properties: if key != 'name': obj_props.append({'key':key, 'value':properties[key]}) except TypeError as ex: raise ValueError('invalid property set') body['properties'] = obj_props # POST create model run request try: req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(body)) except urllib2.URLError as ex: raise ValueError(str(ex)) # Get model run self reference from successful response return references_to_dict(json.load(response)['links'])[REF_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 update_state(url, state_obj): """Update the state of a given model run. The state object is a Json representation of the state as created by the SCO-Server. Throws a ValueError if the resource is unknown or the update state request failed. Parameters url : string Url to POST model run create model run request state_obj : Json object State object serialization as expected by the API. """
# POST update run state request try: req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(state_obj)) except urllib2.URLError as ex: raise ValueError(str(ex)) # Throw exception if resource was unknown or update request failed if response.code == 400: raise ValueError(response.message) elif response.code == 404: raise ValueError('unknown model run')
<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_state_active(self): """Update the state of the model run to active. Raises an exception if update fails or resource is unknown. Returns ------- ModelRunHandle Refreshed run handle. """
# Update state to active self.update_state(self.links[REF_UPDATE_STATE_ACTIVE], {'type' : RUN_ACTIVE}) # Returned refreshed verion of the handle return self.refresh()
<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_state_error(self, errors): """Update the state of the model run to 'FAILED'. Expects a list of error messages. Raises an exception if update fails or resource is unknown. Parameters errors : List(string) List of error messages Returns ------- ModelRunHandle Refreshed run handle. """
# Update state to active self.update_state( self.links[REF_UPDATE_STATE_ERROR], {'type' : RUN_FAILED, 'errors' : errors} ) # Returned refreshed verion of the handle return self.refresh()
<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_state_success(self, model_output): """Update the state of the model run to 'SUCCESS'. Expects a model output result file. Will upload the file before changing the model run state. Raises an exception if update fails or resource is unknown. Parameters model_output : string Path to model run output file Returns ------- ModelRunHandle Refreshed run handle. """
# Upload model output response = requests.post( self.links[REF_UPDATE_STATE_SUCCESS], files={'file': open(model_output, 'rb')} ) if response.status_code != 200: try: raise ValueError(json.loads(response.text)['message']) except ValueError as ex: raise ValueError('invalid state change: ' + str(response.text)) # Returned refreshed verion of the handle return self.refresh()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CirrusIamUserReady(iam_aws_id, iam_aws_secret): """ Returns true if provided IAM credentials are ready to use. """
is_ready = False try: s3 = core.CreateTestedS3Connection(iam_aws_id, iam_aws_secret) if s3: if core.CirrusAccessIdMetadata(s3, iam_aws_id).IsInitialized(): is_ready = True except boto.exception.BotoServerError as e: print e return is_ready
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def NoSuchEntityOk(f): """ Decorator to remove NoSuchEntity exceptions, and raises all others. """
def ExceptionFilter(*args): try: return f(*args) except boto.exception.BotoServerError as e: if e.error_code == 'NoSuchEntity': pass else: raise except: raise return False return ExceptionFilter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __IsInitialized(self): """ Returns true if IAM user initialization has completed. """
is_initialized = False iam_id = self.GetAccessKeyId() if iam_id: if core.CirrusAccessIdMetadata(self.s3, iam_id).IsInitialized(): is_initialized = True return is_initialized
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __GetInstances(self, group_name = None, state_filter=None): """ Get all the instances in a group, filtered by state. @param group_name: the name of the group @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states """
all_instances = self.ec2.get_all_instances() instances = [] for res in all_instances: for group in res.groups: if group_name and group.name != group_name: continue for instance in res.instances: if state_filter == None or instance.state == state_filter: instances.append(instance) return instances
<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(self, mkey, mdesc, mdict=None, merge=False): ''' Loads a dictionary into current meta :param mkey: Type of data to load. Is be used to reference the data from the 'header' within meta :param mdesc: Either filename of json-file to load or further description of imported data when `mdict` is used :param dict mdict: Directly pass data as dictionary instead of loading it from a json-file. Make sure to set `mkey` and `mdesc` accordingly :param merge: Merge received data into current meta or place it under 'import' within meta :returns: The loaded (or directly passed) content ''' j = mdict if mdict else read_json(mdesc) if j and isinstance(j, dict): self.__meta['header'].update({mkey: mdesc}) if merge: self.__meta = dict_merge(self.__meta, j) else: self.__meta['import'][mkey] = j self.log = shell_notify( 'load %s data and %s it into meta' % ( 'got' if mdict else 'read', 'merged' if merge else 'imported' ), more=dict(mkey=mkey, mdesc=mdesc, merge=merge), verbose=self.__verbose ) return j
<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, user_id=None, user_name=None): """ Get a user object from the API. If no ``user_id`` or ``user_name`` is specified, it will return the User object for the currently authenticated user. Args: user_id (int): User ID of the user for whom you want to get information. [Optional] user_name(str): Username for the user for whom you want to get information. [Optional] Returns: A User object. """
if user_id: endpoint = '/api/user_id/{0}'.format(user_id) elif user_name: endpoint = '/api/user_name/{0}'.format(user_name) else: # Return currently authorized user endpoint = '/api/user' data = self._make_request(verb="GET", endpoint=endpoint) try: return User.NewFromJSON(data) except: return data