output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
start the VEP thread
Given the following Python 3 function, write the documentation def vep(self): # calculate time thread took to finish # logging.info('Starting VEP ') tstart = datetime.now() vep_obj = vep.Vep(self.vcf_file) std = vep_obj.run() # command = 'python %s/vep.py -i sanity_che...
You are a Python code analyst, evaluating scripts for potential improvements.
Decipher the VCF file and return the HI score
Explain what the following Python 3 code does def decipher(self): # calculate time thread took to finish # logging.info('Starting HI score') tstart = datetime.now() decipher_obj = decipher.Decipher(self.vcf_file) decipher_obj.run() tend = datetime.now() executi...
You are a Python code analyst, evaluating scripts for potential improvements.
Run HGMD on the vcf file and return the score
Given the following Python 3 function, write the documentation def hgmd(self): # calculate time thread took to finish # logging.info('Starting HI score') tstart = datetime.now() if os.path.isfile(settings.hgmd_file): hgmd_obj = hgmd.HGMD(self.vcf_file) hgmd_o...
You are a Python code generator, capable of creating scripts from specifications.
def snpsift(self): """SnpSift""" tstart = datetime.now() # command = 'python %s/snpsift.py -i sanity_check/checked.vcf 2>log/snpsift.log' % (scripts_dir) # self.shell(command) ss = snpsift.SnpSift(self.vcf_file) ss.run() tend = datetime.now() execution...
Can you create a Python 3 function that runs SNP - Sift on the vcf file
You are a Python code generator, capable of creating scripts from specifications.
def dbnsfp(self): """dbnsfp""" tstart = datetime.now() # python ../scripts/annotate_vcfs.py -i mm13173_14.ug.target1.vcf -r 1000genomes dbsnp138 clinvar esp6500 -a ../data/1000genomes/ALL.wgs.integrated_phase1_v3.20101123.snps_indels_sv.sites.vcf.gz ../data/dbsnp138/00-All.vcf.gz ../data/dbsnp...
Write a Python 3 script for running DBNSFP on the vcf file.
As a python code expert, you are capable of creating scripts from specifications.
def cli(ctx, settings, app): """Manage Morp application services""" if app is None and settings is None: print('Either --app or --settings must be supplied') ctx.ensure_object(dict) ctx.obj['app'] = app ctx.obj['settings'] = settings
Create a Python 3 function to manage Morp application services
As a Python code analyst, you investigate and solve complex coding mysteries
def _settings_checker(self, required_settings=None, accept_none=True): """ Take a list of required _settings dictionary keys and make sure they are set. This can be added to a custom constructor in a subclass and tested to see if it returns ``True``. :arg list required_settings:...
Can you implement a function in Python 3 that checks if all required settings exist and returns True if so returns False if not.
You are a Python code generator, capable of creating scripts from specifications.
def _get_response(self, endpoint, query, is_post=False): """Returns response or False in event of failure""" timeout_secs = self._settings.get('timeout', 10) headers = self._settings.get('request_headers', {}) try: if is_post: response = requests.post( ...
Can you implement a function in Python 3 that returns response or False in event of failure
As a python code expert, you are capable of creating scripts from specifications.
Returns a JSON object from the response.
Make a summary of the following Python 3 code def _get_json_obj(self, endpoint, query, is_post=False): response = self._get_response(endpoint, query, is_post=is_post) content = response.text try: return loads(content) except ValueError: raise Exception('Could not ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_xml_doc(self, endpoint, query, is_post=False): """ Return False if connection could not be made. Otherwise, return a minidom Document. """ response = self._get_response(endpoint, query, is_post=is_post) return minidom.parse(response.text)
Write a Python 3 script to get a minidom Document.
You are a Python code analyst, evaluating scripts for potential improvements.
This method will geocode the specified instance of a resource and return a list of Candidate objects and upstreamResponseInfo object if the API call was made.
How would you explain what the following Python 3 function does def geocode(self, pq): processed_pq = copy.copy(pq) for p in self._preprocessors: processed_pq = p.process(processed_pq) if not processed_pq: return [], None upstream_response_info = UpstreamR...
You are a Python code analyst, evaluating scripts for potential improvements.
def process(self, candidates): """ :arg list candidates: list of Candidate instances """ for c in candidates[:]: if c.locator not in self.good_locators: # TODO: search string, i.e. find "EU_Street_Name" in "EU_Street_Name.GBR_StreetName" candid...
Write a Python 3 function for processing the list of Candidates.
As a Python code analyst, you investigate and solve complex coding mysteries
def process(self, unordered_candidates): """ :arg list candidates: list of Candidate instances """ ordered_candidates = [] # make a new list of candidates in order of ordered_locators for locator in self.ordered_locators: for uc in unordered_candidates[:]: ...
Write a Python 3 function for processing the list of Candidate instances in order of locators and order of locators.
You are a Python code architect, reviewing and designing scalable and efficient code
def process(self, candidates): """ :arg list candidates: list of Candidates :returns: list of Candidates where score is at least min_score, if and only if one or more Candidates have at least min_score. Otherwise, returns original list of Candidates. "...
Can you create a Python 3 function that processes the list of Candidates by comparing the score of the Candidates with the minimum score.
As a Python code composer, you craft elegant and concise scripts.
Process a list of Candidates .
Given the following Python 3 function, write the documentation def process(self, candidates): return sorted(candidates, key=attrgetter('score'), reverse=self.reverse)
As a Python code translator, you convert algorithms and pseudocode into Python.
Get distance in meters between two lat / long points
Can you generate a brief explanation for the following Python 3 code def _get_distance(self, pnt1, pnt2): lat1, lon1 = pnt1 lat2, lon2 = pnt2 radius = 6356752 # km dlat = math.radians(lat2 - lat1) dlon = math.radians(lon2 - lon1) a = math.sin(dlat / 2) * math.sin(dlat / ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns true if lat / lon points are within given distance in metres.
Explain what the following Python 3 code does def _points_within_distance(self, pnt1, pnt2): if self._get_distance(pnt1, pnt2) <= self.distance: return True return False
As a Python code translator, you convert algorithms and pseudocode into Python.
Make a Candidate from a Google geocoder results dictionary.
Can you generate a brief explanation for the following Python 3 code def _make_candidate_from_result(self, result): candidate = Candidate() candidate.match_addr = result['formatted_address'] candidate.x = result['geometry']['location']['lng'] candidate.y = result['geometry']['location'][...
You are a Python code architect, reviewing and designing scalable and efficient code
Helper function to get a particular address component from a Google result dictionary.
Make a summary of the following Python 3 code def _get_component_from_result(self, result, lookup): for component in result['address_components']: if lookup['type'] in component['types']: return component.get(lookup['key'], '') return ''
You are a Python code generator, capable of creating scripts from specifications.
def search(self, query: Optional[dict] = None, offset: Optional[int] = None, limit: Optional[int] = None, order_by: Union[None, list, tuple] = None) -> Sequence['IModel']: """return search result based on specified rulez query""" raise NotImplementedError
Write a Python 3 script to search based on specified rulez query
As a Python code translator, you convert algorithms and pseudocode into Python.
def aggregate(self, query: Optional[dict] = None, group: Optional[dict] = None, order_by: Union[None, list, tuple] = None) -> list: """return aggregation result based on specified rulez query and group""" raise NotImplementedError
Implement a function in Python 3 to return aggregation result based on specified rulez query and group
As a Python code translator, you convert algorithms and pseudocode into Python.
def put_blob(self, field: str, fileobj: BinaryIO, filename: str, mimetype: Optional[str] = None, size: Optional[int] = None, encoding: Optional[str] = None) -> IBlob: """Receive and store blob object""" raise NotImplementedError
Create a Python 3 function for receiving and store a blob object
As a Python code translator, you convert algorithms and pseudocode into Python.
Triggered before BLOB is stored
Here you have a function in Python 3, explain what it does def before_blobput(self, field: str, fileobj: BinaryIO, filename: str, mimetype: Optional[str] = None, size: Optional[int] = None, encoding: Optional[str] = None) -> Non...
As a Python code composer, you craft elegant and concise scripts.
Search for models in the database.
Explain what the following Python 3 code does def search(self, query: Optional[dict] = None, offset: int = 0, limit: Optional[int] = None, order_by: Optional[tuple] = None, secure: bool = False) -> List[IModel]: """Search for models Filtering ...
You are a Python code architect, reviewing and designing scalable and efficient code
def aggregate(self, query: Optional[dict] = None, group: Optional[dict] = None, order_by: Optional[tuple] = None) -> List[IModel]: """Get aggregated results : param query: Rulez based query : param group: Grouping structure : param order_by: Tuple of ...
Can you implement a function in Python 3 that gets aggregated results from rulez based query
You are a Python code architect, reviewing and designing scalable and efficient code
def fetch_state_data(self): """Fetch the raw JSON game state data from EchoVR's ``/session`` API This method could be useful if you want to retrieve some API data not directly exposed by this Python wrapper. Otherwise, you should probably use :meth:`fetch_state` instead. :retur...
Create a Python 3 function for fetching the raw JSON game state data from EchoVR s session API.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert the viewbox object to a string that can be used by Bing as a query parameter.
How would you explain what the following Python 3 function does def to_bing_str(self): vb = self.convert_srs(4326) return '%s,%s,%s,%s' % (vb.bottom, vb.left, vb.top, vb.right)
You are a Python code generator, capable of creating scripts from specifications.
Convert the viewbox object to a dictionary that can be used by Pelias as a query parameter.
Can you tell what is the following Python 3 function doing def to_pelias_dict(self): vb = self.convert_srs(4326) return { 'boundary.rect.min_lat': vb.bottom, 'boundary.rect.min_lon': vb.left, 'boundary.rect.max_lat': vb.top, 'boundary.rect.max_lon': vb.rig...
As a Python code composer, you craft elegant and concise scripts.
Convert the current object to Google s bounds format
Can you tell what is the following Python 3 function doing def to_google_str(self): vb = self.convert_srs(4326) return '%s,%s|%s,%s' % (vb.bottom, vb.left, vb.top, vb.right)
You are a Python code analyst, evaluating scripts for potential improvements.
Convert Viewbox object to a string that can be used by MapQuest API
Here you have a function in Python 3, explain what it does def to_mapquest_str(self): vb = self.convert_srs(4326) return '%s,%s,%s,%s' % (vb.left, vb.top, vb.right, vb.bottom)
As a python code expert, you are capable of creating scripts from specifications.
def to_esri_wgs_json(self): """ Convert Viewbox object to a JSON string that can be used by the ESRI World Geocoding Service as a parameter. """ try: return ('{ "xmin" : %s, ' '"ymin" : %s, ' '"xmax" : %s, ' ...
Implement a Python 3 function for converting the Viewbox object to a JSON string that can be used by the ESRI World Geocoding Service as a parameter.
As a python code expert, you are capable of creating scripts from specifications.
def register(context, request, load): """Validate the username and password and create the user.""" data = request.json res = validate(data, dataclass_to_jsl( RegistrationSchema).get_schema()) if res: @request.after def set_error(response): response.status = 422 ...
Write a Python 3 script to validate the username and password and create the user.
You are a Python code analyst, evaluating scripts for potential improvements.
def process_login(context, request): """Authenticate username and password and log in user""" username = request.json['username'] password = request.json['password'] # Do the password validation. user = context.authenticate(username, password) if not user: @request.after def adj...
Implement a function in Python 3 to authenticate username and password and log in user.
You are a Python code generator, capable of creating scripts from specifications.
def logout(context, request): """Log out the user.""" @request.after def forget(response): request.app.forget_identity(response, request) return { 'status': 'success' }
Implement a function in Python 3 to log out the user.
As a python code expert, you are capable of creating scripts from specifications.
The requester shortcut to submit a http request to CloutFlare
Here you have a function in Python 3, explain what it does def request(self, url, method, data=None): method = getattr(requests, method) response = method( url, headers=self.headers, data=self.process_json_for_cloudflare(data) if data else None ) conte...
As a Python code composer, you craft elegant and concise scripts.
Get a dns record in the domain.
Explain what the following Python 3 code does def get_record(self, dns_type, name): try: record = [record for record in self.dns_records if record['type'] == dns_type and record['name'] == name][0] except IndexError: raise RecordNotFound( 'Ca...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a DNS record.
How would you explain what the following Python 3 function does def create_record(self, dns_type, name, content, **kwargs): data = { 'type': dns_type, 'name': name, 'content': content } if kwargs.get('ttl') and kwargs['ttl'] != 1: data['ttl'] = kwa...
As a Python code translator, you convert algorithms and pseudocode into Python.
def update_record(self, dns_type, name, content, **kwargs): """ Update dns record :param dns_type: :param name: :param content: :param kwargs: :return: """ record = self.get_record(dns_type, name) data = { 'type': dns_type, ...
Write a Python 3 script to update a DNS record.
You are a Python code architect, reviewing and designing scalable and efficient code
Create or update a dns record.
Explain what the following Python 3 code does def create_or_update_record(self, dns_type, name, content, **kwargs): try: return self.update_record(dns_type, name, content, **kwargs) except RecordNotFound: return self.create_record(dns_type, name, content, **kwargs)
As a Python code analyst, you investigate and solve complex coding mysteries
def delete_record(self, dns_type, name): """ Delete a dns record :param dns_type: :param name: :return: """ record = self.get_record(dns_type, name) content = self.request( urllib.parse.urljoin(self.api_url, self.zone['id'] + '/dns_records/' + ...
Can you write a function in Python 3 where it deletes a dns record.
As a Python code analyst, you investigate and solve complex coding mysteries
def _init_helper(self, vars_): """Overwrite defaults (if they exist) with arguments passed to constructor""" for k in vars_: if k == 'kwargs': for kwarg in vars_[k]: setattr(self, kwarg, vars_[k][kwarg]) elif k != 'self': setatt...
Implement a function in Python 3 to initialize the object with the passed in arguments.
As a Python code composer, you craft elegant and concise scripts.
Return the list of users in the group.
Can you generate the documentation for the following Python 3 function def list_members(context, request): members = context.members() return { 'users': [{ 'username': m.identifier, 'userid': m.userid, 'roles': context.get_member_roles(m.userid), 'links': ...
You are a Python code architect, reviewing and designing scalable and efficient code
def grant_member(context, request): """Grant member roles in the group.""" mapping = request.json['mapping'] for entry in mapping: user = entry['user'] roles = entry['roles'] username = user.get('username', None) userid = user.get('userid', None) if userid: ...
Create a Python 3 function to grant member roles in the group.
As a Python code composer, you craft elegant and concise scripts.
def revoke_member(context, request): """Revoke member roles in the group.""" mapping = request.json['mapping'] for entry in mapping: user = entry['user'] roles = entry['roles'] username = user.get('username', None) userid = user.get('userid', None) if userid: ...
Can you implement a function in Python 3 that revokes member roles in the group.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a dictionary of dictionaries with the output of MediaInfo - f file_name
How would you explain what the following Python 3 function does def call_MediaInfo(file_name, mediainfo_path=None): if mediainfo_path is None: mediainfo_path = find_MediaInfo() result = subprocess.check_output( [mediainfo_path, "-f", file_name], universal_newlines=True ) D = collections...
You are a Python code analyst, evaluating scripts for potential improvements.
Checks the given file with MediaInfo and returns the video and audio codec information if all the required parameters were found.
Explain what the following Python 3 code does def check_video(file_name, mediainfo_path=None): D = call_MediaInfo(file_name, mediainfo_path) err_msg = "Could not determine all video paramters" if ("General" not in D) or ("Video" not in D): raise MediaInfoError(err_msg) general_keys = ("Count o...
You are a Python code architect, reviewing and designing scalable and efficient code
def check_picture(file_name, mediainfo_path=None): """ Scans the given file with MediaInfo and returns the picture information if all the required parameters were found. """ D = call_MediaInfo(file_name, mediainfo_path) # Check that the file analyzed was a valid movie if ( ("Image" n...
Write a Python 3 script for checking that the given file with MediaInfo and returns the picture information if all the required parameters were found.
You are a Python code architect, reviewing and designing scalable and efficient code
Return the MD5 checksum of the file
Explain what the following Python 3 code does def md5_checksum(file_path, chunk_bytes=4194304): with open(file_path, "rb") as infile: checksum = hashlib.md5() while 1: data = infile.read(chunk_bytes) if not data: break checksum.update(data) r...
As a python code expert, you are capable of creating scripts from specifications.
Trim the given docstring into a single string.
Can you generate the documentation for the following Python 3 function def trim(docstring): if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (...
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_attributes(schema, location): """Return the schema's children, filtered by location.""" schema = DottedNameResolver(__name__).maybe_resolve(schema) def _filter(attr): if not hasattr(attr, "location"): valid_location = 'body' in location else: ...
Implement a function in Python 3 to return the schema s children filtered by location.
You are a Python code architect, reviewing and designing scalable and efficient code
def start_server(worker_actxmgr: AsyncServerContextManager, main_ctxmgr: Optional[ServerMainContextManager] = None, extra_procs: Iterable[Callable] = tuple(), stop_signals: Iterable[signal.Signals] = ( signal.SIGINT, signal.SIG...
Write a Python 3 script to start a multi - process server with the given context manager.
You are a Python code analyst, evaluating scripts for potential improvements.
def is_acquired(self): """Check if the lock is acquired""" values = self.client.get(self.key) return six.b(self._uuid) in values
How would you code a function in Python 3 to check if the lock is acquired
As a Python code analyst, you investigate and solve complex coding mysteries
Return an instance of an Etcd3Client.
Can you tell what is the following Python 3 function doing def client(host='localhost', port=2379, ca_cert=None, cert_key=None, cert_cert=None, timeout=None, protocol="http"): """Return an instance of an Etcd3Client.""" return Etcd3Client(host=host, port=port, ...
You are a Python code generator, capable of creating scripts from specifications.
def get_url(self, path): """Construct a full url to the v3alpha API given a specific path :param path: :return: url """ host = ('[' + self.host + ']' if (self.host.find(':') != -1) else self.host) base_url = self.protocol + '://' + host + ':' + str(self.p...
How would you implement a function in Python 3 that constructs a full url to the v3alpha API given a specific path
You are a Python code analyst, evaluating scripts for potential improvements.
Create a Lease object given a timeout.
Explain what the following Python 3 code does def lease(self, ttl=DEFAULT_TIMEOUT): result = self.post(self.get_url("/lease/grant"), json={"TTL": ttl, "ID": 0}) return Lease(int(result['ID']), client=self)
You are a Python code architect, reviewing and designing scalable and efficient code
def lock(self, id=str(uuid.uuid4()), ttl=DEFAULT_TIMEOUT): """Create a Lock object given an ID and timeout :param id: ID for the lock, creates a new uuid if not provided :param ttl: timeout :return: Lock object """ return Lock(id, ttl=ttl, client=self)
Can you implement a function in Python 3 that creates a Lock object given an ID and a TTL
As a Python code composer, you craft elegant and concise scripts.
Atomically create the given key only if the key doesn t exist.
Make a summary of the following Python 3 code def create(self, key, value): base64_key = _encode(key) base64_value = _encode(value) txn = { 'compare': [{ 'key': base64_key, 'result': 'EQUAL', 'target': 'CREATE', 'create_...
You are a Python code analyst, evaluating scripts for potential improvements.
Put the given key into the key - value store.
Can you generate a brief explanation for the following Python 3 code def put(self, key, value, lease=None): payload = { "key": _encode(key), "value": _encode(value) } if lease: payload['lease'] = lease.id self.post(self.get_url("/kv/put"), json=payload...
As a Python code analyst, you investigate and solve complex coding mysteries
Get the keys in the key - value store.
Make a summary of the following Python 3 code def get(self, key, metadata=False, sort_order=None, sort_target=None, **kwargs): """Range gets the keys in the range from the key-value store. :param key: :param metadata: :param sort_order: 'ascend' or 'descend' or None ...
As a Python code composer, you craft elegant and concise scripts.
def get_all(self, sort_order=None, sort_target='key'): """Get all keys currently stored in etcd. :returns: sequence of (value, metadata) tuples """ return self.get( key=_encode(b'\0'), metadata=True, sort_order=sort_order, sort_target=sort...
Create a Python 3 function for getting all keys currently stored in etcd.
You are a Python code architect, reviewing and designing scalable and efficient code
Get a range of keys with a prefix.
Here you have a function in Python 3, explain what it does def get_prefix(self, key_prefix, sort_order=None, sort_target=None): return self.get(key_prefix, metadata=True, range_end=_encode(_increment_last_byte(key_prefix)), sort_order=sort_...
As a Python code analyst, you investigate and solve complex coding mysteries
def delete(self, key, **kwargs): """DeleteRange deletes the given range from the key-value store. A delete request increments the revision of the key-value store and generates a delete event in the event history for every deleted key. :param key: :param kwargs: :return:...
Can you implement a function in Python 3 that deletes the given key - value store range.
You are a Python code generator, capable of creating scripts from specifications.
Delete a range of keys with a prefix in etcd.
Can you tell what is the following Python 3 function doing def delete_prefix(self, key_prefix): return self.delete( key_prefix, range_end=_encode(_increment_last_byte(key_prefix)))
As a Python code composer, you craft elegant and concise scripts.
Processes multiple requests in a single transaction.
Can you tell what is the following Python 3 function doing def transaction(self, txn): return self.post(self.get_url("/kv/txn"), data=json.dumps(txn))
As a Python code composer, you craft elegant and concise scripts.
Watch a key for changes and return an iterator of events and cancel.
Can you tell what is the following Python 3 function doing def watch(self, key, **kwargs): event_queue = queue.Queue() def callback(event): event_queue.put(event) w = watch.Watcher(self, key, callback, **kwargs) canceled = threading.Event() def cancel(): ...
As a Python code analyst, you investigate and solve complex coding mysteries
The same as watch but watches a range of keys with a prefix.
Can you generate the documentation for the following Python 3 function def watch_prefix(self, key_prefix, **kwargs): kwargs['range_end'] = \ _increment_last_byte(key_prefix) return self.watch(key_prefix, **kwargs)
As a Python code analyst, you investigate and solve complex coding mysteries
Watch a key and stops after the first event.
Given the following Python 3 function, write the documentation def watch_once(self, key, timeout=None, **kwargs): event_queue = queue.Queue() def callback(event): event_queue.put(event) w = watch.Watcher(self, key, callback, **kwargs) try: return event_queue.get...
You are a Python code analyst, evaluating scripts for potential improvements.
def watch_prefix_once(self, key_prefix, timeout=None, **kwargs): """Watches a range of keys with a prefix, similar to watch_once""" kwargs['range_end'] = \ _increment_last_byte(key_prefix) return self.watch_once(key_prefix, timeout=timeout, **kwargs)
How would you code a function in Python 3 to watch a range of keys with a prefix.
As a Python code composer, you craft elegant and concise scripts.
def create_timer(cb: Callable[[float], None], interval: float, delay_policy: TimerDelayPolicy = TimerDelayPolicy.DEFAULT, loop: Optional[asyncio.BaseEventLoop] = None) -> asyncio.Task: ''' Schedule a timer with the given callable and the interval in seconds. The interval va...
Can you implement a function in Python 3 that schedules a timer with the given callable and the interval in seconds.
You are a Python code architect, reviewing and designing scalable and efficient code
LeaseTimeToLive retrieves lease information.
How would you explain what the following Python 3 function does def ttl(self): result = self.client.post(self.client.get_url("/kv/lease/timetolive"), json={"ID": self.id}) return int(result['TTL'])
As a Python code composer, you craft elegant and concise scripts.
def keys(self): """Get the keys associated with this lease. :return: """ result = self.client.post(self.client.get_url("/kv/lease/timetolive"), json={"ID": self.id, "keys": True}) keys = result['keys'] if ...
Implement a Python 3 function for getting the keys associated with this lease.
You are a Python code generator, capable of creating scripts from specifications.
A coroutine function that returns a single object.
Given the following Python 3 function, write the documentation def apartial(coro, *args, **kwargs): ''' Wraps a coroutine function with pre-defined arguments (including keyword arguments). It is an asynchronous version of :func:`functools.partial`. ''' @functools.wraps(coro) async def wrapped(...
You are a Python code analyst, evaluating scripts for potential improvements.
_get makes the actual call to api. embed. ly
Can you tell what is the following Python 3 function doing def _get(self, version, method, url_or_urls, **kwargs): if not url_or_urls: raise ValueError('%s requires a url or a list of urls given: %s' % (method.title(), url_or_urls)) # a flag we can use instead o...
As a Python code composer, you craft elegant and concise scripts.
A class decorator that can be used to make a class unicode compatible.
Can you tell what is the following Python 3 function doing def python_2_unicode_compatible(klass): if sys.version_info[0] == 2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __s...
You are a Python code architect, reviewing and designing scalable and efficient code
def _encode(data): """Encode the given data using base-64 :param data: :return: base-64 encoded string """ if not isinstance(data, bytes_types): data = six.b(str(data)) return base64.b64encode(data).decode("utf-8")
Create a Python 3 function for encoding the given data using base - 64
You are a Python code architect, reviewing and designing scalable and efficient code
Decode the base - 64 encoded string
Given the following Python 3 function, write the documentation def _decode(data): if not isinstance(data, bytes_types): data = six.b(str(data)) return base64.b64decode(data.decode("utf-8"))
You are a Python code architect, reviewing and designing scalable and efficient code
Get the last byte in the array and increment it
Here you have a function in Python 3, explain what it does def _increment_last_byte(data): if not isinstance(data, bytes_types): if isinstance(data, six.string_types): data = data.encode('utf-8') else: data = six.b(str(data)) s = bytearray(data) s[-1] = s[-1] + 1 ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return dict representation of this cookbook s metadata. rb.
How would you explain what the following Python 3 function does def metadata(self): self.metadata_path = os.path.join(self.path, 'metadata.rb') if not os.path.isfile(self.metadata_path): raise ValueError("Cookbook needs metadata.rb, %s" % self.metadata_path) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Return this cookbook s Berksfile instance.
Make a summary of the following Python 3 code def berksfile(self): self.berks_path = os.path.join(self.path, 'Berksfile') if not self._berksfile: if not os.path.isfile(self.berks_path): raise ValueError("No Berksfile found at %s" % self.berks_...
You are a Python code architect, reviewing and designing scalable and efficient code
Create a MetadataRb instance from a dictionary.
Make a summary of the following Python 3 code def from_dict(cls, dictionary): cookbooks = set() # put these in order groups = [cookbooks] for key, val in dictionary.items(): if key == 'depends': cookbooks.update({cls.depends_statement(cbn, meta) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def depends_statement(cookbook_name, metadata=None): """Return a valid Ruby 'depends' statement for the metadata.rb file.""" line = "depends '%s'" % cookbook_name if metadata: if not isinstance(metadata, dict): raise TypeError("Stencil dependency options for %s " ...
Create a Python 3 function for returning a valid Ruby depends statement for the metadata. rb file.
You are a Python code generator, capable of creating scripts from specifications.
def parse(self): """Parse the metadata.rb into a dict.""" data = utils.ruby_lines(self.readlines()) data = [tuple(j.strip() for j in line.split(None, 1)) for line in data] depends = {} for line in data: if not len(line) == 2: continue ...
Write a Python 3 function that can parse the metadata. rb into a dict.
As a Python code analyst, you investigate and solve complex coding mysteries
def merge(self, other): """Add requirements from 'other' metadata.rb into this one.""" if not isinstance(other, MetadataRb): raise TypeError("MetadataRb to merge should be a 'MetadataRb' " "instance, not %s.", type(other)) current = self.to_dict() ...
Create a Python 3 function for merging two MetadataRbs into this one.
You are a Python code generator, capable of creating scripts from specifications.
def parse(self): """Parse this Berksfile into a dict.""" self.flush() self.seek(0) data = utils.ruby_lines(self.readlines()) data = [tuple(j.strip() for j in line.split(None, 1)) for line in data] datamap = {} for line in data: if len(l...
Can you implement a function in Python 3 that parses this Berksfile into a dict.
You are a Python code analyst, evaluating scripts for potential improvements.
Create a Berksfile instance from a dictionary.
Explain what the following Python 3 code does def from_dict(cls, dictionary): cookbooks = set() sources = set() other = set() # put these in order groups = [sources, cookbooks, other] for key, val in dictionary.items(): if key == 'cookbook': c...
You are a Python code architect, reviewing and designing scalable and efficient code
def cookbook_statement(cookbook_name, metadata=None): """Return a valid Ruby 'cookbook' statement for the Berksfile.""" line = "cookbook '%s'" % cookbook_name if metadata: if not isinstance(metadata, dict): raise TypeError("Berksfile dependency hash for %s " ...
Can you write a function in Python 3 where it returns a valid Ruby cookbook statement for the Berksfile.
As a Python code analyst, you investigate and solve complex coding mysteries
Merge two Berksfiles into this one.
Given the following Python 3 function, write the documentation def merge(self, other): if not isinstance(other, Berksfile): raise TypeError("Berksfile to merge should be a 'Berksfile' " "instance, not %s.", type(other)) current = self.to_dict() new = other...
You are a Python code generator, capable of creating scripts from specifications.
def get_stencil(self, stencil_name, **options): """Return a Stencil instance given a stencil name.""" if stencil_name not in self.manifest.get('stencils', {}): raise ValueError("Stencil '%s' not declared in StencilSet " "manifest." % stencil_name) stencil...
Implement a Python 3 function for returning a Stencil instance given a stencil name.
You are a Python code architect, reviewing and designing scalable and efficient code
Determine the name of the selected stencil within a set.
How would you explain what the following Python 3 function does def _determine_selected_stencil(stencil_set, stencil_definition): if 'stencil' not in stencil_definition: selected_stencil_name = stencil_set.manifest.get('default_stencil') else: selected_stencil_name = stencil_definition.get('sten...
You are a Python code analyst, evaluating scripts for potential improvements.
def _build_template_map(cookbook, cookbook_name, stencil): """Build a map of variables for this generated cookbook and stencil. Get template variables from stencil option values, adding the default ones like cookbook and cookbook year. """ template_map = { 'cookbook': {"name": cookbook_name...
Write a Python 3 function for building a map of variables for this generated cookbook and stencil.
As a python code expert, you are capable of creating scripts from specifications.
Write binary contents from filetable into files.
Explain what the following Python 3 code does def _render_binaries(files, written_files): for source_path, target_path in files.items(): needdir = os.path.dirname(target_path) assert needdir, "Target should have valid parent dir" try: os.makedirs(needdir) except OSError a...
You are a Python code architect, reviewing and designing scalable and efficient code
def _render_templates(files, filetable, written_files, force, open_mode='w'): """Write template contents from filetable into files. Using filetable for the rendered templates, and the list of files, render all the templates into actual files on disk, forcing to overwrite the file as appropriate, and us...
How would you implement a function in Python 3 that renders all the templates in the filetable into a list of files.
As a Python code analyst, you investigate and solve complex coding mysteries
Build a new cookbook from a fastfood. json file.
Explain what the following Python 3 code does def build_cookbook(build_config, templatepack_path, cookbooks_home, force=False): """Build a cookbook from a fastfood.json file. Can build on an existing cookbook, otherwise this will create a new cookbook for you based on your templatepack. ...
You are a Python code analyst, evaluating scripts for potential improvements.
Processes the stencil requested writing any missing files as needed.
Make a summary of the following Python 3 code def process_stencil(cookbook, cookbook_name, template_pack, force_argument, stencil_set, stencil, written_files): """Process the stencil requested, writing any missing files as needed. The stencil named 'stencilset_name' should be one of tem...
As a Python code composer, you craft elegant and concise scripts.
def create_new_cookbook(cookbook_name, cookbooks_home): """Create a new cookbook. :param cookbook_name: Name of the new cookbook. :param cookbooks_home: Target dir for new cookbook. """ cookbooks_home = utils.normalize_path(cookbooks_home) if not os.path.exists(cookbooks_home): raise V...
Create a Python 3 function to create a new cookbook.
As a Python code analyst, you investigate and solve complex coding mysteries
def ruby_lines(text): """Tidy up lines from a file, honor # comments. Does not honor ruby block comments (yet). """ if isinstance(text, basestring): text = text.splitlines() elif not isinstance(text, list): raise TypeError("text should be a list or a string, not %s" ...
Create a Python 3 function to tidy up lines from a file honor comment lines.
As a python code expert, you are capable of creating scripts from specifications.
Update original dict with items from iterable update.
Can you generate a brief explanation for the following Python 3 code def deepupdate(original, update, levels=5): if not isinstance(update, dict): update = dict(update) if not levels > 0: original.update(update) else: for key, val in update.items(): if isinstance(original....
As a Python code analyst, you investigate and solve complex coding mysteries
Insert the statements into the file neatly.
Explain what the following Python 3 code does def write_statements(self, statements): self.seek(0) original_content_lines = self.readlines() new_content_lines = copy.copy(original_content_lines) # ignore blanks and sort statements to be written statements = sorted([stmnt for stmn...
As a Python code analyst, you investigate and solve complex coding mysteries
Run on fastfood build.
Here you have a function in Python 3, explain what it does def _fastfood_build(args): written_files, cookbook = food.build_cookbook( args.config_file, args.template_pack, args.cookbooks, args.force) if len(written_files) > 0: print("%s: %s files written" % (cookbook, ...
As a Python code composer, you craft elegant and concise scripts.
def _fastfood_list(args): """Run on `fastfood list`.""" template_pack = pack.TemplatePack(args.template_pack) if args.stencil_set: stencil_set = template_pack.load_stencil_set(args.stencil_set) print("Available Stencils for %s:" % args.stencil_set) for stencil in stencil_set.stencils...
Write a Python 3 script for running on fastfood list.
You are a Python code generator, capable of creating scripts from specifications.