output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Split apart a date string.
How would you explain what the following Python 3 function does def _split_date(self, time): if isinstance(time, str): month, day, year = [int(t) for t in re.split(r'-|/', time)] if year < 100: # Quick hack for dates < 2000. year += 2000 time =...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert content to Python data structures.
Can you generate the documentation for the following Python 3 function def convert(self, content, conversion): if not conversion: data = content elif self.format == 'json': data = json.loads(content) elif self.format == 'xml': content = xml(content) ...
As a Python code composer, you craft elegant and concise scripts.
def discovery(self, url=None): """ Retrieve the standard discovery file that provides routing information. >>> Three().discovery() {'discovery': 'data'} """ if url: data = self.session.get(url).content elif self.discovery_url: resp...
Write a Python 3 function for retrieving the standard discovery file that provides routing information.
As a Python code composer, you craft elegant and concise scripts.
def services(self, code=None, **kwargs): """ Retrieve information about available services. You can also enter a specific service code argument. >>> Three().services() {'all': {'service_code': 'data'}} >>> Three().services('033') {'033': {'service_code': 'data'}}...
Write a Python 3 script to retrieve information about available services.
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieve open requests. You can also enter a specific service code argument. >>> Three('api.city.gov').requests() {'all': {'requests': 'data'}} >>> Three('api.city.gov').requests('123') {'123': {'requests': 'data'}}
Explain what the following Python 3 code does def requests(self, code=None, **kwargs): if code: kwargs['service_code'] = code data = self.get('requests', **kwargs) return data
As a Python code translator, you convert algorithms and pseudocode into Python.
Retrieve a specific request using its service code ID.
Here you have a function in Python 3, explain what it does def request(self, id, **kwargs): data = self.get('requests', id, **kwargs) return data
You are a Python code architect, reviewing and designing scalable and efficient code
Post a new Open311 request.
Can you tell what is the following Python 3 function doing def post(self, service_code='0', **kwargs): kwargs['service_code'] = service_code kwargs = self._post_keywords(**kwargs) media = kwargs.pop('media', None) if media: files = {'media': media} else: f...
You are a Python code generator, capable of creating scripts from specifications.
def _post_keywords(self, **kwargs): """Configure keyword arguments for Open311 POST requests.""" if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'address' in kwargs: address = kwargs.pop('address') kwa...
Write a Python 3 function for configuring keyword arguments for Open311 POST requests.
You are a Python code analyst, evaluating scripts for potential improvements.
Retrieve a token from a token.
Can you tell what is the following Python 3 function doing def token(self, id, **kwargs): data = self.get('tokens', id, **kwargs) return data
As a Python code composer, you craft elegant and concise scripts.
Helper function for building an attribute dictionary.
Can you generate the documentation for the following Python 3 function def build_attrs(self, base_attrs, extra_attrs=None, **kwargs): attrs = dict(base_attrs, **kwargs) if extra_attrs: attrs.update(extra_attrs) return attrs
As a Python code composer, you craft elegant and concise scripts.
def to_dataframe(self, **kwargs): """Load up the CSV file as a pandas dataframe""" return pandas.io.parsers.read_csv(self.path, sep=self.d, **kwargs)
Write a Python 3 function for loading up the CSV file as a pandas dataframe
As a python code expert, you are capable of creating scripts from specifications.
Generates a sorted list of elementary intervals
Here you have a function in Python 3, explain what it does def get_elementary_intervals(self, features): coords = [] try: for interval in features: if len(interval) != 3: raise SyntaxError('Interval malformed %s. Allways specify start and end position for ...
As a python code expert, you are capable of creating scripts from specifications.
Check if a point is within a range
Given the following Python 3 function, write the documentation def pt_within(self, pt, subject): try: if pt >= int(subject[0]) and pt <= int(subject[1]): return True except ValueError: raise ValueError('Interval start and stop has to be integers. %s' % str(subject...
You are a Python code generator, capable of creating scripts from specifications.
Check if a range is fully within another range
Can you tell what is the following Python 3 function doing def is_within(self, query, subject): if self.pt_within(query[0], subject) and self.pt_within(query[1], subject): return True return False
You are a Python code analyst, evaluating scripts for potential improvements.
loops through all the data and inserts them into the tree
Can you generate a brief explanation for the following Python 3 code def insert_data(self, node, data, start, end): for item in data: self.recursive_insert(node, [item[0], item[1]], item[-1], start, end)
You are a Python code architect, reviewing and designing scalable and efficient code
trims the tree for any empty data nodes
How would you explain what the following Python 3 function does def trim_tree(self, node): data_len = len(node[-1]) if node[1] == -1 and node[2] == -1: if data_len == 0: return 1 else: return 0 else: if self.trim_tree(node[1]) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Get core view of given model
How would you explain what the following Python 3 function does def get_model_core(model): model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name)) return registered_model_cores.get(model_label)
As a Python code composer, you craft elegant and concise scripts.
def create_repo_from_pip_url(pip_url, **kwargs): r"""Return a object representation of a VCS repository via pip-style url. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: ...
Implement a Python 3 function for returning a object representation of a VCS repository via pip - style url.
You are a Python code architect, reviewing and designing scalable and efficient code
def set_paths(self, base_dir, script_path): """Set the directory, the script path and the outfile path""" # Make absolute paths # if 'change_dir' in self.kwargs: self.kwargs['change_dir'] = DirectoryPath(os.path.abspath(self.kwargs['change_dir'])) if 'out_file' in self.kwargs...
Write a Python 3 function that can set the directory the script path and the outfile path
You are a Python code generator, capable of creating scripts from specifications.
The script to be submitted to the SLURM queue.
Make a summary of the following Python 3 code def script(self): self.shebang_header = self.shebang_headers[self.language] self.slurm_header = [self.slurm_headers[k]['tag'] % v for k,v in self.slurm_params.items()] self.script_header = self.script_headers[self.language] self.script_foo...
You are a Python code architect, reviewing and designing scalable and efficient code
Make the script and return a FilePath object pointing to the script above.
Make a summary of the following Python 3 code def make_script(self): self.script_path.write(self.script) self.script_path.permissions.make_executable() return self.script_path
You are a Python code analyst, evaluating scripts for potential improvements.
Return the status of the job.
Explain what the following Python 3 code does def status(self): # If there is no script it is either ready or a lost duplicate # if not self.script_path.exists: if self.name in jobs.names: return "DUPLICATE" if self.name not in jobs.names: return "READY" # It is submi...
As a Python code translator, you convert algorithms and pseudocode into Python.
def info(self): """Get the existing job information dictionary""" if self.name not in jobs: return {'status': self.status} else: return jobs[self.name]
Can you implement a function in Python 3 that gets the existing job information dictionary
You are a Python code analyst, evaluating scripts for potential improvements.
Will call self. launch after performing some checks
Can you tell what is the following Python 3 function doing def run(self): # Check already exists # if self.status == "READY": return self.launch() # Check name conflict # if self.status == "DUPLICATE": message = "Job with same name '%s' already in queue, but we lost the script." ...
You are a Python code generator, capable of creating scripts from specifications.
def launch(self): """Make the script file and return the newly created job id""" # Make script file # self.make_script() # Do it # sbatch_out = sh.sbatch(self.script_path) jobs.expire() # Message # print Color.i_blu + "SLURM:" + Color.end + " " + str(sbatc...
How would you implement a function in Python 3 that launches the job and return the newly created job id
You are a Python code analyst, evaluating scripts for potential improvements.
def execute_locally(self): """Runs the equivalent command locally in a blocking way.""" # Make script file # self.make_script() # Do it # with open(self.kwargs['out_file'], 'w') as handle: sh.python(self.script_path, _out=handle, _err=handle)
Create a Python 3 function for running the equivalent command locally in a blocking way.
As a Python code translator, you convert algorithms and pseudocode into Python.
def wait_locally(self): """If you have run the query in a non-blocking way, call this method to pause until the query is finished.""" try: self.thread.join(sys.maxint) # maxint timeout so that we can Ctrl-C them except KeyboardInterrupt: print "Stopped waiting on job '%s'" % self.kwargs[...
Can you write a function in Python 3 where it waits for the job to finish.
As a Python code translator, you convert algorithms and pseudocode into Python.
def replace_version_tag(self): """find the next major/minor/trivial version number if applicable""" version_tag = self.arguments.get('<version>') special_keywords = ['current', 'latest'] if version_tag in special_keywords: logger.error("releasing version '{}' is disallowed. D...
Can you implement a function in Python 3 that finds the next major minor or trivial version number if applicable
You are a Python code architect, reviewing and designing scalable and efficient code
returns a 2 - tuple containing the usage and options from a docopt string
Given the following Python 3 function, write the documentation def parse_docopt_string(docopt_string): from re import match, DOTALL only_usage_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+""" usage_and_options_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+Options:\s+(?P<options>.*)\s+""" usage, options = '', '...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns concrete widget that will be used for rendering table filter.
Make a summary of the following Python 3 code def get_widget(self, request): widget = self.widget if isinstance(widget, type): widget = widget() return widget
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the base remote media URL based on bucket names and having a specific public ACL on.
How would you explain what the following Python 3 function does def remote_media_url(self, with_ssl=False): protocol = 'http' if with_ssl is False else 'https' url = (self.aws_bucket_cname and "%s://%s" or "%s://s3.amazonaws.com/%s") % (protocol, self.aws_bucket) if self.aws_prefix: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def distroinfo(cargs, version=__version__): """ distroinfo Command-Line Interface """ code = 1 args = docopt(__doc__, argv=cargs) try: if args['--version']: if not version: version = 'N/A' print(version) code = 0 elif args['fet...
Create a Python 3 function for commanding - Line Interface for distroinfo
You are a Python code analyst, evaluating scripts for potential improvements.
Return the error response.
Here you have a function in Python 3, explain what it does def _get_error_response(self, exception): response_exceptions = { MimerDataException: HTTPBadRequestResponseException, NotAllowedException: HTTPForbiddenResponseException, UnsupportedMediaTypeException: HTTPUnsupporte...
As a Python code translator, you convert algorithms and pseudocode into Python.
def reprompt_error(self, message=None): """ Intended to be used in case of erroneous input data """ try: session_id = session.sessionId self.session_machines.rollback_fsm(session_id) current_state = self.session_machines.current_state(session_id) ...
Create a Python 3 function for intending to be used in case of erroneous input data
As a Python code composer, you craft elegant and concise scripts.
def move_to_step(self, step): """ Use in cases when you need to move in given step depending on input """ if step not in self._scenario_steps.keys(): raise UndefinedState("step {} not defined in scenario".format(step)) try: session_id = session.sessionId ...
Write a Python 3 function for moving to given step
You are a Python code generator, capable of creating scripts from specifications.
def get_current_state(self): """ Get current state for user session or None if session doesn't exist """ try: session_id = session.sessionId return self.session_machines.current_state(session_id) except UninitializedStateMachine as e: logger.er...
How would you implement a function in Python 3 that gets current state of user session or None if session doesn t exist.
You are a Python code architect, reviewing and designing scalable and efficient code
Get context help depending on the current step.
Explain what the following Python 3 code does def get_help(self): current_state = self.get_current_state() if current_state is None: return statement(INTERNAL_ERROR_MSG) else: try: return choice(self._scenario_steps[current_state]['help']) exce...
You are a Python code generator, capable of creating scripts from specifications.
Runs all enabled tests and evaluates result.
Given the following Python 3 function, write the documentation def run(self): ''' Runs all enabled tests. ''' # Run all tests. for cls in self.get_test_classes(): # Print informational message. self.logger.info('Running {cls.__name__} test...'.format(cls=...
As a Python code translator, you convert algorithms and pseudocode into Python.
def check_executable(tool_name): """Raises an warning if the executable *tool_name* is not found.""" result = subprocess.call(['which', tool_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result != 0: message = "The executable '%s' cannot be found in your $PATH" % tool_name raise ...
Can you write a function in Python 3 where it raises an exception if the executable is not found in the PATH.
As a Python code composer, you craft elegant and concise scripts.
def check_module(mod_name): """Calls sys.exit() if the module *mod_name* is not found.""" # Special cases # if mod_name in module_name: mod_name = module_name[mod_name] # Use a try except block # try: __import__(mod_name) except ImportError as e: if str(e) != 'No module named %s'...
Write a Python 3 function that can call sys. exit if the module *mod_name* is not found.
You are a Python code analyst, evaluating scripts for potential improvements.
def iiif_image_key(obj): """Generate the IIIF image key.""" if isinstance(obj, ObjectVersion): bucket_id = obj.bucket_id version_id = obj.version_id key = obj.key else: bucket_id = obj.get('bucket') version_id = obj.get('version_id') key = obj.get('key') r...
How would you implement a function in Python 3 that generates the IIIF image key.
You are a Python code architect, reviewing and designing scalable and efficient code
def ui_iiif_image_url(obj, version='v2', region='full', size='full', rotation=0, quality='default', image_format='png'): """Generate IIIF image URL from the UI application.""" return u'{prefix}{version}/{identifier}/{region}/{size}/{rotation}/' \ u'{quality}.{image_format}'.format(...
Create a Python 3 function to generate IIIF image URL from the UI application.
As a Python code composer, you craft elegant and concise scripts.
def matches(self, sexp): ''' Body of a non-terminal is always a :class:`Sequence`. For an s-expr to match, it must be of the form:: ['name'] + [sexpr-0, ..., sexpr-n] where the first list contains a name of the non-terminal, and the second one matches its body seque...
Create a Python 3 function for returning True if the given s - expression matches the current non - terminal.
As a Python code translator, you convert algorithms and pseudocode into Python.
def preview(file): """Render appropriate template with embed flag.""" params = deepcopy(current_app.config['IIIF_PREVIEWER_PARAMS']) if 'image_format' not in params: params['image_format'] = \ 'png' if file.has_extensions('.png') else 'jpg' return render_template( current_app...
Create a Python 3 function for rendering appropriate template with embed flag.
You are a Python code generator, capable of creating scripts from specifications.
Gets the translated attribute of the given instance.
Can you tell what is the following Python 3 function doing def get_translated_attribute(instance, attr): # If its class has no translatable fields, returns attribute try: if not hasattr(instance._meta, "translatable_fields") or len(getattr(instance._meta,"translatable_fields"))==0: return getattr(instance, att...
You are a Python code analyst, evaluating scripts for potential improvements.
Set an auth decorator applied for views.
Given the following Python 3 function, write the documentation def secure(view): AUTH = getattr( settings, 'SLACKCHAT_AUTH_DECORATOR', 'django.contrib.admin.views.decorators.staff_member_required' ) auth_decorator = import_class(AUTH) return method_decorator(auth_decorator, name=...
As a Python code composer, you craft elegant and concise scripts.
Import translations from a file.
Given the following Python 3 function, write the documentation def import_translations(request, language): def _import_po_file(uploadedfile, lang): lines = [] for line in uploadedfile: lines.append(line) num_lines = len(lines) prog_ctxt = re.compile(r"msgctxt\s+\"(?P<id>\d+)--(?P<model>\w+)--(?P<object_i...
You are a Python code analyst, evaluating scripts for potential improvements.
Creates a new cluster and creates a new one
Given the following Python 3 function, write the documentation def up(cloud_init, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time): try: cloud_config = CloudConfig() ci = None if cloud_init: ci = CloudInit() cloud_controller = CloudController(cloud_config)...
As a Python code analyst, you investigate and solve complex coding mysteries
def down(force): """ destroys an existing cluster """ try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.down(force) except CloudComposeException as ex: print(ex)
Create a Python 3 function to destroy an existing cluster
As a Python code composer, you craft elegant and concise scripts.
def cleanup(): """ deletes launch configs and auto scaling group """ try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.cleanup() except CloudComposeException as ex: print(ex)
Write a Python 3 function that can delete all launch configs and auto scaling group
You are a Python code architect, reviewing and designing scalable and efficient code
builds the cloud_init script
Can you generate a brief explanation for the following Python 3 code def build(): try: cloud_config = CloudConfig() config_data = cloud_config.config_data('cluster') cloud_init = CloudInit() print(cloud_init.build(config_data)) except CloudComposeException as ex: print(ex...
As a Python code composer, you craft elegant and concise scripts.
Send pending signals over the message bus.
Can you tell what is the following Python 3 function doing def flush(signal_names, exclude, wait): signalbus = current_app.extensions['signalbus'] signal_names = set(signal_names) exclude = set(exclude) models_to_flush = signalbus.get_signal_models() if signal_names and exclude: click.echo(...
You are a Python code generator, capable of creating scripts from specifications.
Flushes a potentially huge number of pending signals over the message bus.
Can you tell what is the following Python 3 function doing def flushmany(): signalbus = current_app.extensions['signalbus'] signal_count = signalbus.flushmany() logger = logging.getLogger(__name__) if signal_count == 1: logger.warning('%i signal has been successfully processed.', signal_count) ...
As a python code expert, you are capable of creating scripts from specifications.
Show all signal types.
Explain what the following Python 3 code does def signals(): signalbus = current_app.extensions['signalbus'] for signal_model in signalbus.get_signal_models(): click.echo(signal_model.__name__)
As a Python code translator, you convert algorithms and pseudocode into Python.
Show the number of pending signals by signal type.
Given the following Python 3 function, write the documentation def pending(): signalbus = current_app.extensions['signalbus'] pending = [] total_pending = 0 for signal_model in signalbus.get_signal_models(): count = signal_model.query.count() if count > 0: pending.append((co...
As a Python code analyst, you investigate and solve complex coding mysteries
Crea la clave única de la caché
Can you tell what is the following Python 3 function doing def _create_key(lang, instance): model_name = instance.__class__.__name__ return "{0}__{1}_{2}".format(lang,model_name,instance.id)
As a python code expert, you are capable of creating scripts from specifications.
def set(self, lang, instance): """ Establece en la instancia actual los atributos de traducción y la almacena en un diccionario de claves _create_key y valores el objeto con los atributos dinámicos. """ if self._cache_is_too_big(): self.cache = {} inst...
Create a Python 3 function to set the language of the given instance in the cache.
As a Python code composer, you craft elegant and concise scripts.
Get a cache entry for a given language and instance.
Can you tell what is the following Python 3 function doing def get(self, lang, instance): instance_key = TransCache._create_key(lang, instance) return self.cache[instance_key]
As a Python code analyst, you investigate and solve complex coding mysteries
Create the thumbnail for an image.
Explain what the following Python 3 code does def create_thumbnail(uuid, thumbnail_width): # size = '!' + thumbnail_width + ',' size = thumbnail_width + ',' # flask_iiif doesn't support ! at the moment thumbnail = IIIFImageAPI.get('v2', uuid, size, 0, 'default', 'jpg')
As a Python code translator, you convert algorithms and pseudocode into Python.
def price_str(raw_price, default=_not_defined, dec_point='.'): """Search and clean price value. Convert raw price string presented in any localization as a valid number string with an optional decimal point. If raw price does not contain valid price value or contains more than one price value, the...
How would you implement a function in Python 3 that converts raw price value into a string that can be used as a price value in any localization .
As a Python code translator, you convert algorithms and pseudocode into Python.
def price_dec(raw_price, default=_not_defined): """Price decimal value from raw string. Extract price value from input raw string and present as Decimal number. If raw price does not contain valid price value or contains more than one price value, then return default value. If default value no...
Write a Python 3 script for returning Decimal price value from raw string.
As a Python code composer, you craft elegant and concise scripts.
Flotify a test result.
How would you explain what the following Python 3 function does def flotify(result, num=50): results = list(TestResult.objects.filter(test=result.test, site=result.site)[:num]) results.reverse() return [[get_timestamp(result.run_date), result.duration/1000] for result in results]
As a python code expert, you are capable of creating scripts from specifications.
def __get_dynamic_attr(self, attname, arg, default=None): """ Gets "something" from self, which could be an attribute or a callable with either 0 or 1 arguments (besides self). Stolen from django.contrib.syntication.feeds.Feed. """ try: attr = getattr...
Implement a function in Python 3 to get something from self which could be an attribute or a callable with either 0 or 1 arguments.
You are a Python code architect, reviewing and designing scalable and efficient code
def metric(self, measurement_name, values, tags=None, timestamp=None): """ Append global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket """ if not measurement_name or values in (None, {}): # D...
Can you implement a function in Python 3 that appends global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket
As a Python code translator, you convert algorithms and pseudocode into Python.
def send(self, data): """ Sends the given data to the socket via UDP """ try: self.socket.sendto(data.encode('utf8') + b'\n', (self.host, self.port)) except (socket.error, RuntimeError): # Socket errors should fail silently so they don't affect anything el...
How would you implement a function in Python 3 that sends the given data to the socket via UDP.
As a Python code translator, you convert algorithms and pseudocode into Python.
Send the data in a separate thread via HTTP POST.
Given the following Python 3 function, write the documentation def send(self, data): self.future_session.post(url=self.url, data=data)
As a Python code analyst, you investigate and solve complex coding mysteries
Return an escaped string of comma separated value_name = value pairs
Can you tell what is the following Python 3 function doing def get_output_values(self): # Handle primitive values here and implicitly convert them to a dict because # it allows the API to be simpler. # Also influxDB mandates that each value also has a name so the default name # for any ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_output_tags(self): """ Return an escaped string of comma separated tag_name: tag_value pairs Tags should be sorted by key before being sent for best performance. The sort should match that from the Go bytes. Compare function (http://golang.org/pkg/bytes/#Compare). """ ...
Implement a Python 3 function for returning an escaped string of comma separated tag_name = tag_value pairs
You are a Python code generator, capable of creating scripts from specifications.
Converts the given metrics as a single line of InfluxDB line protocol.
Given the following Python 3 function, write the documentation def to_line_protocol(self): tags = self.get_output_tags() return u"{0}{1} {2}{3}".format( self.get_output_measurement(), "," + tags if tags else '', self.get_output_values(), self.get_output_t...
You are a Python code analyst, evaluating scripts for potential improvements.
def format_string(key): """ Formats either measurement names, tag names or tag values. Measurement name and any optional tags separated by commas. Measurement names, tag keys, and tag values must escape any spaces, commas or equal signs using a backslash (\). For example: \ and \,. All tag val...
Write a Python 3 function that can format a string for use in a log file.
You are a Python code architect, reviewing and designing scalable and efficient code
Format the value for the log entry.
Make a summary of the following Python 3 code def format_value(value): if isinstance(value, basestring): value = value.replace('"', '\"') value = u'"{0}"'.format(value) elif isinstance(value, bool): value = str(value) elif isinstance(value, int): value = "{0}i".format(value) ...
As a Python code composer, you craft elegant and concise scripts.
def _process_equation(value, fmt): """Processes the equation. Returns a dict containing eq properties.""" # pylint: disable=global-statement global Nreferences # Global references counter global cursec # Current section # Parse the equation attrs = value[0] # Initialize the return...
Write a Python 3 function for processing the equation and returns a dictionary containing eq properties.
As a python code expert, you are capable of creating scripts from specifications.
Processes the attributed equations.
Make a summary of the following Python 3 code def process_equations(key, value, fmt, meta): if key == 'Math' and len(value) == 3: # Process the equation eq = _process_equation(value, fmt) # Get the attributes and label attrs = eq['attrs'] label = attrs[0] if eq['is...
As a Python code translator, you convert algorithms and pseudocode into Python.
Saves metadata fields in global variables and returns a few computed fields.
Explain what the following Python 3 code does def process(meta): # pylint: disable=global-statement global capitalize global use_cleveref_default global plusname global starname global numbersections # Read in the metadata fields and do some checking for name in ['eqnos-cleveref', 'xn...
You are a Python code architect, reviewing and designing scalable and efficient code
def main(): """Filters the document AST.""" # pylint: disable=global-statement global PANDOCVERSION global AttrMath # Get the output format and document fmt = args.fmt doc = json.loads(STDIN.read()) # Initialize pandocxnos # pylint: disable=too-many-function-args PANDOCVERSION...
How would you code a function in Python 3 to filter the document AST.
You are a Python code analyst, evaluating scripts for potential improvements.
Checks that Django s template debugging is enabled and raises an exception if it is not.
Can you generate a brief explanation for the following Python 3 code def check_debug(): from django.conf import settings if not settings.configured: return False # I _think_ this check is all that's needed and the 3 "hasattr" checks # below can be removed, but it's not clear how to verify that...
You are a Python code generator, capable of creating scripts from specifications.
Read the source of a Django template returning the Unicode text.
Can you tell what is the following Python 3 function doing def read_template_source(filename): # Import this late to be sure we don't trigger settings machinery too # early. from django.conf import settings if not settings.configured: settings.configure() with open(filename, "rb") as f: ...
As a Python code composer, you craft elegant and concise scripts.
Find a line number given a line map and a character offset.
Can you tell what is the following Python 3 function doing def get_line_number(line_map, offset): for lineno, line_offset in enumerate(line_map, start=1): if line_offset > offset: return lineno return -1
As a python code expert, you are capable of creating scripts from specifications.
def dump_frame(frame, label=""): """Dump interesting information about this frame.""" locals = dict(frame.f_locals) self = locals.get('self', None) context = locals.get('context', None) if "__builtins__" in locals: del locals["__builtins__"] if label: label = " ( %s ) " % label ...
Write a Python 3 function for dumping interesting information about this frame.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a line map for filename.
Can you generate a brief explanation for the following Python 3 code def get_line_map(self, filename): if filename not in self.source_map: template_source = read_template_source(filename) if 0: # change to see the template text for i in range(0, len(template_source), 10...
You are a Python code architect, reviewing and designing scalable and efficient code
def bytes_to_file(input_data, output_file): """Save bytes to a file.""" pathlib.Path(output_file.parent).mkdir(parents=True, exist_ok=True) with open(output_file, "wb") as file: file.write(input_data)
Can you implement a function in Python 3 that saves bytes to a file.
You are a Python code generator, capable of creating scripts from specifications.
Get the album art.
Can you generate a brief explanation for the following Python 3 code def get_art(cache_dir, size, client): song = client.currentsong() if len(song) < 2: print("album: Nothing currently playing.") return file_name = f"{song['artist']}_{song['album']}_{size}.jpg".replace("/", "") file_na...
You are a Python code generator, capable of creating scripts from specifications.
def get_cover(song, size=250): """Download the cover art.""" try: data = mus.search_releases(artist=song["artist"], release=song["album"], limit=1) release_id = data["release-list"][0]["release-group"]["id"] print(f"al...
Write a Python 3 function that can download the cover art.
You are a Python code analyst, evaluating scripts for potential improvements.
Get the script arguments.
Explain what the following Python 3 code does def get_args(): description = "bum - Download and display album art \ for mpd tracks." arg = argparse.ArgumentParser(description=description) arg.add_argument("--size", metavar="\"px\"", help="what size to display the alb...
As a python code expert, you are capable of creating scripts from specifications.
def convertforinput(self,filepath, metadata): """Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file. 'filepath' is both the source and the target file, the source file will be erased and overwrit...
Can you create a Python 3 function that converts from source format into target format. Relevant if converters are used in InputTemplates.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert from one of the source formats into one of the target formats. Relevant if converters are used in OutputTemplates. Sourcefile is a CLAMOutputFile instance.
Explain what the following Python 3 code does def convertforoutput(self,outputfile): assert isinstance(outputfile, CLAMOutputFile) #metadata of the destination file (file to be generated here) if not outputfile.metadata.__class__ in self.acceptforoutput: raise Exception("Convertor " + self._...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert from source format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to - be - generated file.
Make a summary of the following Python 3 code def convertforinput(self,filepath, metadata=None): super(CharEncodingConverter,self).convertforinput(filepath, metadata) shutil.copy(filepath, filepath + '.convertsource') try: fsource = io.open(filepath + '.convertsource','r',encoding=...
You are a Python code generator, capable of creating scripts from specifications.
Convert from one of the source formats into one of the target formats. Relevant in OutputTemplates. Outputfile is a CLAMOutputFile instance.
How would you explain what the following Python 3 function does def convertforoutput(self,outputfile): super(CharEncodingConverter,self).convertforoutput(outputfile) return withheaders( flask.make_response( ( line.encode(self.charset) for line in outputfile ) ) , 'text/plain; charset=' + self.charset)
As a Python code analyst, you investigate and solve complex coding mysteries
This function reads the CLAM Data from an XML file.
Can you generate the documentation for the following Python 3 function def getclamdata(filename, custom_formats=None): global CUSTOM_FORMATS #pylint: disable=global-statement """This function reads the CLAM Data from an XML file. Use this to read the clam.xml file from your system wrapper. It returns a CLA...
As a Python code analyst, you investigate and solve complex coding mysteries
def sanitizeparameters(parameters): """Construct a dictionary of parameters, for internal use only""" if not isinstance(parameters,dict): d = {} for x in parameters: if isinstance(x,tuple) and len(x) == 2: for parameter in x[1]: d[parameter.id] = p...
How would you code a function in Python 3 to sanitize the parameters for internal use only
As a Python code analyst, you investigate and solve complex coding mysteries
def profiler(profiles, projectpath,parameters,serviceid,servicename,serviceurl,printdebug=None): """Given input files and parameters, produce metadata for outputfiles. Returns a list of matched profiles (empty if none match), and a program.""" parameters = sanitizeparameters(parameters) matched = [] p...
Write a Python 3 script for giving input files and parameters produce metadata for outputfiles. Returns a list of matched profiles and a program.
You are a Python code generator, capable of creating scripts from specifications.
def shellsafe(s, quote='', doescape=True): """Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception if the string is at risk of causing code injection""" if sys.version[0] == '2' and not isinstance(s,unicode): #pylint: disable=undefined-variable s =...
Implement a Python 3 function for returning the value string wrapped in the specified quotes if not empty
As a python code expert, you are capable of creating scripts from specifications.
def attachviewers(self, profiles): """Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate""" if self.metadata: template = None for profile in profiles: if isinstance(self, CLAMInputFile): ...
Write a Python 3 script to attach viewers and converters to file automatically scan all profiles for outputtemplate or inputtemplate
You are a Python code architect, reviewing and designing scalable and efficient code
def metafilename(self): """Returns the filename for the metadata file (not full path). Only used for local files.""" metafilename = os.path.dirname(self.filename) if metafilename: metafilename += '/' metafilename += '.' + os.path.basename(self.filename) + '.METADATA' return metaf...
Can you implement a function in Python 3 that returns the filename for the metadata file. Only used for local files. Only used for local files.
As a Python code analyst, you investigate and solve complex coding mysteries
Load metadata for this file. This is usually called automatically upon instantiation except if explicitly disabled. Works both locally as well as for clients connecting to a CLAM service.
Explain what the following Python 3 code does def loadmetadata(self): if not self.remote: metafile = self.projectpath + self.basedir + '/' + self.metafilename() if os.path.exists(metafile): f = io.open(metafile, 'r',encoding='utf-8') xml = "".join(f.readli...
You are a Python code generator, capable of creating scripts from specifications.
def read(self): """Loads all lines in memory""" lines = self.readlines() if self.metadata and 'encoding' in self.metadata: encoding = self.metadata['encoding'] else: encoding = 'utf-8' if sys.version < '3': return "\n".join( unicode(line, 'utf-...
Implement a Python 3 function for loading all lines in memory
You are a Python code architect, reviewing and designing scalable and efficient code
Copy or download this file to a new local file
Explain what the following Python 3 code does def copy(self, target, timeout=500): if self.metadata and 'encoding' in self.metadata: with io.open(target,'w', encoding=self.metadata['encoding']) as f: for line in self: f.write(line) else: with ...
As a Python code analyst, you investigate and solve complex coding mysteries
def parseresponse(self, xml, localroot = False): """Parses CLAM XML, there's usually no need to call this directly""" root = parsexmlstring(xml) if root.tag != 'clam': raise FormatError("CLAM root tag not found") self.system_id = root.attrib['id'] self.system_name = ...
Create a Python 3 function to parse CLAM XML and sets attributes of this object.
As a Python code analyst, you investigate and solve complex coding mysteries
def outputtemplate(self, template_id): """Get an output template by ID""" for profile in self.profiles: for outputtemplate in profile.outputtemplates(): if outputtemplate.id == template_id: return outputtemplate return KeyError("Outputtemplate " + ...
Create a Python 3 function for getting an output template by ID
As a Python code translator, you convert algorithms and pseudocode into Python.
def commandlineargs(self): """Obtain a string of all parameters, using the paramater flags they were defined with, in order to pass to an external command. This is shell-safe by definition.""" commandlineargs = [] for parametergroup, parameters in self.parameters: #pylint: disable=unused-variabl...
Create a Python 3 function for obtaining a string of all parameters using the paramater flags they were defined with in order to pass to an external command. This is shell - safe by definition.
As a python code expert, you are capable of creating scripts from specifications.