output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def _check_above_value_float(string, minimum): """ Checks that the number parsed from the string is above a minimum. This is used on compulsory numeric fields. If the value is not above the minimum an exception is thrown. :param string: the field value :param minimum: minimum value """ ...
How would you implement a function in Python 3 that checks that the value parsed from the string is above a minimum value.
As a Python code translator, you convert algorithms and pseudocode into Python.
def boolean(name=None): """ Creates the grammar for a Boolean (B) field, accepting only 'Y' or 'N' :param name: name for the field :return: grammar for the flag field """ if name is None: name = 'Boolean Field' # Basic field field = pp.Regex('[YN]') # Parse action fie...
Implement a Python 3 function for returning the grammar for a Boolean field
As a Python code analyst, you investigate and solve complex coding mysteries
Transforms a string into a boolean value.
Here you have a function in Python 3, explain what it does def _to_boolean(string): if string == 'Y': result = True elif string == 'N': result = False else: raise pp.ParseException(string, msg='Is not a valid boolean value') return result
You are a Python code generator, capable of creating scripts from specifications.
Returns the grammar for a Flag field.
Given the following Python 3 function, write the documentation def flag(name=None): if name is None: name = 'Flag Field' # Basic field field = pp.Regex('[YNU]') # Name field.setName(name) field.leaveWhitespace() return field
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a grammar for a Date field.
Can you tell what is the following Python 3 function doing def date(name=None): if name is None: name = 'Date Field' # Basic field # This regex allows values from 00000101 to 99991231 field = pp.Regex('[0-9][0-9][0-9][0-9](0[1-9]|1[0-2])' '(0[1-9]|[1-2][0-9]|3[0-1])') ...
You are a Python code architect, reviewing and designing scalable and efficient code
def time(name=None): """ Creates the grammar for a Time or Duration (T) field, accepting only numbers in a certain pattern. :param name: name for the field :return: grammar for the date field """ if name is None: name = 'Time Field' # Basic field # This regex allows values...
Can you write a function in Python 3 where it returns a grammar for a Time or Duration field.
As a Python code translator, you convert algorithms and pseudocode into Python.
def lookup(values, name=None): """ Creates the grammar for a Lookup (L) field, accepting only values from a list. Like in the Alphanumeric field, the result will be stripped of all heading and trailing whitespaces. :param values: values allowed :param name: name for the field :return: ...
How would you implement a function in Python 3 that creates a grammar for a Lookup field.
As a Python code analyst, you investigate and solve complex coding mysteries
def blank(columns=1, name=None): """ Creates the grammar for a blank field. These are for constant empty strings which should be ignored, as they are used just as fillers. :param columns: number of columns, which is the required number of whitespaces :param name: name for the field :re...
Implement a function in Python 3 to return a grammar for a blank field.
As a Python code analyst, you investigate and solve complex coding mysteries
This method returns a list of GFF objects with the given attribute and if supplied those objects with the specified value. If not supplied those objects with the given value are returned.
Here you have a function in Python 3, explain what it does def get_attribute(self, attribute, value=None, features=False): if attribute in self.filters: valid_gff_objects = self.fast_attributes[attribute] if not value else\ [i for i in self.fast_attributes[attribute] if i.attributes....
As a Python code translator, you convert algorithms and pseudocode into Python.
This method returns a list of VCFEntry objects which cover a specified location.
Can you tell what is the following Python 3 function doing def contains(self, chrom, start, end, overlap=True): d = self.positions.get(chrom,[]) if overlap: return [vcf_entry for vcf_start, vcf_end in d for vcf_entry in d[(vcf_start, vcf_end)] if not (...
You are a Python code architect, reviewing and designing scalable and efficient code
Remove a list of variants from the positions we are scanning
Given the following Python 3 function, write the documentation def remove_variants(self, variants): chroms = set([i.chrom for i in variants]) for chrom in chroms: if self.append_chromosome: chrom = 'chr%s' % chrom to_delete = [pos for pos in self.positions[chrom] ...
As a Python code composer, you craft elegant and concise scripts.
Generate the path to the source file for the given loader plugin.
Can you generate the documentation for the following Python 3 function def generate_handler_sourcepath( self, toolchain, spec, loaderplugin_sourcepath): """ Attempt to locate the plugin source; returns a mapping of modnames to the absolute path of the located sources. """ ...
You are a Python code generator, capable of creating scripts from specifications.
Stores the records for the given entry_point in the package_loader_map.
Here you have a function in Python 3, explain what it does def store_records_for_package(self, entry_point, records): pkg_records_entry = self._dist_to_package_module_map(entry_point) pkg_records_entry.extend( rec for rec in records if rec not in pkg_records_entry) # TODO figure out...
As a Python code composer, you craft elegant and concise scripts.
Get default encoder cwr file
How would you explain what the following Python 3 function does def default_file_encoder(): config = CWRConfiguration() field_configs = config.load_field_config('table') field_configs.update(config.load_field_config('common')) field_values = CWRTables() for entry in field_configs.values(): ...
As a python code expert, you are capable of creating scripts from specifications.
def encode(self, tag): """ Parses a CWR file name from a FileTag object. The result will be a string following the format CWyynnnnsss_rrr.Vxx, where the numeric sequence will have the length set on the encoder's constructor. :param tag: FileTag to parse :return:...
Can you create a Python 3 function that encodes a FileTag object into a CWR file name.
You are a Python code architect, reviewing and designing scalable and efficient code
Encodes the data for a single object in the domain model.
Can you generate the documentation for the following Python 3 function def encode(self, transmission): data = '' data += self._record_encode(transmission.header) for group in transmission.groups: data += self._record_encode(group.group_header) for transaction in group.tra...
As a Python code analyst, you investigate and solve complex coding mysteries
def getScans(self, modifications=True, fdr=True): """ get a random scan """ if not self.scans: for i in self: yield i else: for i in self.scans.values(): yield i yield None
Can you write a function in Python 3 where it gets a random scan for all the tables
As a Python code composer, you craft elegant and concise scripts.
def getScan(self, title, peptide=None): """ allows random lookup """ if self.ra.has_key(title): self.filename.seek(self.ra[title][0],0) toRead = self.ra[title][1]-self.ra[title][0] info = self.filename.read(toRead) scan = self.parseScan(inf...
Write a Python 3 script to return a scan object for a given title
You are a Python code architect, reviewing and designing scalable and efficient code
Parses a scan string and returns a ScanObject object.
Can you generate a brief explanation for the following Python 3 code def parseScan(self, scan): setupScan = True foundCharge = False foundMass = False foundTitle = False scanObj = ScanObject() scanObj.ms_level = 2 for row in scan.split('\n'): if not ro...
You are a Python code generator, capable of creating scripts from specifications.
def getScan(self, specId, peptide=None): """ get a random scan """ sql = self.base_sql + " where sh.SpectrumID = %d and p.Sequence = '%s'"%(int(specId),peptide) self.cur.execute(sql) i = self.cur.fetchone() if not i: return None scan = self.par...
Can you create a Python 3 function that gets a random scan from the database
You are a Python code generator, capable of creating scripts from specifications.
get a random set of scans
Can you generate the documentation for the following Python 3 function def getScans(self, modifications=False, fdr=True): if fdr: sql = self.base_sql+"WHERE p.ConfidenceLevel >= {} and p.SearchEngineRank <= {} {}".format(self.clvl, self.srank, self.extra) try: self.cur.ex...
You are a Python code architect, reviewing and designing scalable and efficient code
Parses a full scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml
Here you have a function in Python 3, explain what it does def parseFullScan(self, i, modifications=False): scanObj = PeptideObject() peptide = str(i[1]) pid=i[2] scanObj.acc = self.protein_map.get(i[4], i[4]) if pid is None: return None if modifications: ...
You are a Python code generator, capable of creating scripts from specifications.
get a random scan from the database
Can you tell what is the following Python 3 function doing def getScans(self, modifications=True, fdr=True): if fdr: sql = "select sp.Spectrum, p.Sequence, p.PeptideID, p.SpectrumID from spectrumheaders sh left join spectra sp on (sp.UniqueSpectrumID=sh.UniqueSpectrumID) left join peptides p on (sh....
As a python code expert, you are capable of creating scripts from specifications.
def parseFullScan(self, i, modifications=True): """ parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml """ scanObj = PeptideObject() peptide = str(i[1]) pid=i[2] if modifications: sql = '...
Create a Python 3 function to parse a full scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip and parse xml
You are a Python code architect, reviewing and designing scalable and efficient code
def _cls_lookup_dist(cls): """ Attempt to resolve the distribution from the provided class in the most naive way - this assumes the Python module path to the class contains the name of the package that provided the module and class. """ frags = cls.__module__.split('.') for name in ('.'.joi...
Create a Python 3 function for attempting to resolve the distribution from the provided class in the class most naive way - this assumes that the module path to the class contains the name of the package that provided the class and the class itself.
You are a Python code analyst, evaluating scripts for potential improvements.
Verify that the provided builder has a signature that is at least compatible.
Can you generate the documentation for the following Python 3 function def verify_builder(builder): try: d = getcallargs(builder, package_names=[], export_target='some_path') except TypeError: return False return d == {'package_names': [], 'export_target': 'some_path'}
As a Python code analyst, you investigate and solve complex coding mysteries
Extract the builder result to produce a Toolchain and Spec instance.
Can you tell what is the following Python 3 function doing def extract_builder_result(builder_result, toolchain_cls=Toolchain): try: toolchain, spec = builder_result except Exception: return None, None if not isinstance(toolchain, toolchain_cls) or not isinstance(spec, Spec): return...
As a Python code composer, you craft elegant and concise scripts.
def trace_toolchain(toolchain): """ Trace the versions of the involved packages for the provided toolchain instance. """ pkgs = [] for cls in getmro(type(toolchain)): if not issubclass(cls, Toolchain): continue dist = _cls_lookup_dist(cls) value = { ...
Create a Python 3 function to trace the versions of the involved packages for the provided toolchain instance.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the path to the artifact file that should be used for the given artifact name.
Can you generate the documentation for the following Python 3 function def get_artifact_filename(self, package_name, artifact_name): project_name = self.packages.normalize(package_name) return self.records.get((project_name, artifact_name))
You are a Python code generator, capable of creating scripts from specifications.
Yields the list of paths to the artifacts that are needed for the given packages.
Make a summary of the following Python 3 code def resolve_artifacts_by_builder_compat( self, package_names, builder_name, dependencies=False): """ Yield the list of paths to the artifacts in the order of the dependency resolution Arguments: package_names ...
You are a Python code generator, capable of creating scripts from specifications.
Get the artifact metadata for the given package name.
Can you generate the documentation for the following Python 3 function def get_artifact_metadata(self, package_name): filename = self.metadata.get(package_name) if not filename or not exists(filename): return {} with open(filename, encoding='utf8') as fd: contents = fd.r...
You are a Python code generator, capable of creating scripts from specifications.
Generate the metadata entry for the entry_point.
Can you generate a brief explanation for the following Python 3 code def generate_metadata_entry(self, entry_point, toolchain, spec): export_target = spec['export_target'] toolchain_bases = trace_toolchain(toolchain) toolchain_bin_path = spec.get(TOOLCHAIN_BIN_PATH) toolchain_bin = ([ ...
As a Python code composer, you craft elegant and concise scripts.
def iter_records_for(self, package_name): """ Iterate records for a specific package. """ entry_points = self.packages.get(package_name, NotImplemented) if entry_points is NotImplemented: logger.debug( "package '%s' has not declared any entry points f...
Implement a Python 3 function for iterating records for a specific package.
You are a Python code generator, capable of creating scripts from specifications.
Yields exactly one builder for the provided entry point and export target.
Given the following Python 3 function, write the documentation def generate_builder(self, entry_point, export_target): try: builder = entry_point.resolve() except ImportError: logger.error( "unable to import the target builder for the entry point " ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Executes the builder and returns the result.
Given the following Python 3 function, write the documentation def execute_builder(self, entry_point, toolchain, spec): toolchain(spec) if not exists(spec['export_target']): logger.error( "the entry point '%s' from package '%s' failed to " "generate an artifa...
As a Python code translator, you convert algorithms and pseudocode into Python.
Process the given package and update the artifact metadata.
Can you tell what is the following Python 3 function doing def process_package(self, package_name): metadata = super(ArtifactRegistry, self).process_package(package_name) if metadata: self.update_artifact_metadata(package_name, metadata)
As a Python code analyst, you investigate and solve complex coding mysteries
def alphanum_variable(min_size, max_size, name=None): """ Creates the grammar for an alphanumeric code where the size ranges between two values. :param min_size: minimum size :param max_size: maximum size :param name: name for the field :return: grammar for an alphanumeric field of a variab...
Create a Python 3 function to create a grammar for an alphanumeric variable size.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a grammar for a field containing a year.
Make a summary of the following Python 3 code def year(columns, name=None): if columns < 0: # Can't have negative size raise BaseException() field = numeric(columns, name) # Parse action field.addParseAction(_to_year) return field
You are a Python code generator, capable of creating scripts from specifications.
def is_json_compat(value): """ Check that the value is either a JSON decodable string or a dict that can be encoded into a JSON. Raises ValueError when validation fails. """ try: value = json.loads(value) except ValueError as e: raise ValueError('JSON decoding error: ' + st...
How would you code a function in Python 3 to check that the value is a JSON decodable string or a dict that can be serialized into a JSON.
As a Python code translator, you convert algorithms and pseudocode into Python.
Check if json field is valid.
Here you have a function in Python 3, explain what it does def validate_json_field(dist, attr, value): try: is_json_compat(value) except ValueError as e: raise DistutilsSetupError("%r %s" % (attr, e)) return True
You are a Python code analyst, evaluating scripts for potential improvements.
def validate_line_list(dist, attr, value): """ Validate that the value is compatible """ # does not work as reliably in Python 2. if isinstance(value, str): value = value.split() value = list(value) try: check = (' '.join(value)).split() if check == value: ...
Create a Python 3 function for validating that the value is a list of valid identifiers
You are a Python code architect, reviewing and designing scalable and efficient code
Writes a JSON file from the package s distribution directory using the specified filename.
Explain what the following Python 3 code does def write_json_file(argname, cmd, basename, filename): value = getattr(cmd.distribution, argname, None) if isinstance(value, dict): value = json.dumps( value, indent=4, sort_keys=True, separators=(',', ': ')) cmd.write_or_delete_file(argna...
You are a Python code generator, capable of creating scripts from specifications.
Write out the retrieved value as list of lines.
Make a summary of the following Python 3 code def write_line_list(argname, cmd, basename, filename): values = getattr(cmd.distribution, argname, None) if isinstance(values, list): values = '\n'.join(values) cmd.write_or_delete_file(argname, filename, values, force=True)
As a python code expert, you are capable of creating scripts from specifications.
def find_pkg_dist(pkg_name, working_set=None): """ Locate a package's distribution by its name. """ working_set = working_set or default_working_set req = Requirement.parse(pkg_name) return working_set.find(req)
Can you write a function in Python 3 where it locates a package s distribution by its name.
You are a Python code generator, capable of creating scripts from specifications.
def convert_package_names(package_names): """ Convert package names, which can be a string of a number of package names or requirements separated by spaces. """ results = [] errors = [] for name in ( package_names.split() if hasattr(package_names, 'split') else pack...
Can you implement a function in Python 3 that converts package names which can be a string of a number of package names or requirements separated by spaces.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the entire list of dependency requirements for the given packages.
Given the following Python 3 function, write the documentation def find_packages_requirements_dists(pkg_names, working_set=None): working_set = working_set or default_working_set requirements = [ r for r in (Requirement.parse(req) for req in pkg_names) if working_set.find(r) ] return li...
You are a Python code architect, reviewing and designing scalable and efficient code
def find_packages_parents_requirements_dists(pkg_names, working_set=None): """ Leverages the `find_packages_requirements_dists` but strip out the distributions that matches pkg_names. """ dists = [] # opting for a naive implementation targets = set(pkg_names) for dist in find_packages_r...
Implement a function in Python 3 to leverage the find_packages_requirements_dists but strip out the packages that are not in pkg_names.
You are a Python code generator, capable of creating scripts from specifications.
Read a json file within an egginfo distribution.
Explain what the following Python 3 code does def read_dist_egginfo_json(dist, filename=DEFAULT_JSON): # use the given package's distribution to acquire the json file. if not dist.has_metadata(filename): logger.debug("no '%s' for '%s'", filename, dist) return try: result = dist.get...
As a Python code analyst, you investigate and solve complex coding mysteries
def read_egginfo_json(pkg_name, filename=DEFAULT_JSON, working_set=None): """ Read json from egginfo of a package identified by `pkg_name` that's already installed within the current Python environment. """ working_set = working_set or default_working_set dist = find_pkg_dist(pkg_name, working_...
Can you implement a function in Python 3 that reads json from egginfo of a package identified by pkg_name.
You are a Python code generator, capable of creating scripts from specifications.
def flatten_dist_egginfo_json( source_dists, filename=DEFAULT_JSON, dep_keys=DEP_KEYS, working_set=None): """ Flatten a distribution's egginfo json, with the depended keys to be flattened. Originally this was done for this: Resolve a distribution's (dev)dependencies through the wor...
Write a Python 3 function for flattening a distribution s egginfo json with the depended keys to be flattened.
You are a Python code architect, reviewing and designing scalable and efficient code
Generates a flattened package. json with packages pkg_names and dep_keys.
Can you generate the documentation for the following Python 3 function def flatten_egginfo_json( pkg_names, filename=DEFAULT_JSON, dep_keys=DEP_KEYS, working_set=None): """ A shorthand calling convention where the package name is supplied instead of a distribution. Originally written for this: ...
As a Python code composer, you craft elegant and concise scripts.
Build a tuple of functions that will provide the usage of the JSON egginfo based around the provided field.
Here you have a function in Python 3, explain what it does def build_helpers_egginfo_json( json_field, json_key_registry, json_filename=None): """ Return a tuple of functions that will provide the usage of the JSON egginfo based around the provided field. """ json_filename = ( json_...
You are a Python code analyst, evaluating scripts for potential improvements.
def build_helpers_module_registry_dependencies(registry_name='calmjs.module'): """ Return a tuple of funtions that will provide the functions that return the relevant sets of module registry records based on the dependencies defined for the provided packages. """ def get_module_registry_depende...
Write a Python 3 script to return a tuple of functions that will provide the functions that will provide the relevant sets of module registry records based on the given packages.
As a Python code analyst, you investigate and solve complex coding mysteries
Check that the artifact build step is there.
Can you tell what is the following Python 3 function doing def has_calmjs_artifact_declarations(cmd, registry_name='calmjs.artifacts'): return any(get(registry_name).iter_records_for( cmd.distribution.get_name()))
You are a Python code analyst, evaluating scripts for potential improvements.
Trigger the artifact build process through the setuptools.
Can you tell what is the following Python 3 function doing def build_calmjs_artifacts(dist, key, value, cmdclass=BuildCommand): if value is not True: return build_cmd = dist.get_command_obj('build') if not isinstance(build_cmd, cmdclass): logger.error( "'build' command in Distr...
As a python code expert, you are capable of creating scripts from specifications.
Returns the rule for the given field_id.
Explain what the following Python 3 code does def get_rule(self, field_id): if field_id in self._fields: # Field already exists field = self._fields[field_id] else: # Field does not exist # It is created field = self._create_field(field_id) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Creates the basic rule for the specified field.
Can you generate the documentation for the following Python 3 function def _create_field(self, field_id): # Field configuration info config = self._field_configs[field_id] adapter = self._adapters[config['type']] if 'name' in config: name = config['name'] else: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Reads a CSV file into a list of the contents.
Here you have a function in Python 3, explain what it does def read_csv_file(self, file_name): result = [] with open(os.path.join(self.__path(), os.path.basename(file_name)), 'rt') as csvfile: headers_reader = csv.reader(csvfile, delimiter=',', quotechar='|') fo...
As a Python code analyst, you investigate and solve complex coding mysteries
def read_yaml_file(self, file_name): """ Parses a YAML file into a matrix. :param file_name: name of the YAML file :return: a matrix with the file's contents """ with open(os.path.join(self.__path(), os.path.basename(file_name)), 'rt') as yamlfile: ...
How would you implement a function in Python 3 that reads a YAML file into a matrix.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_data(self, file_id): """ Acquires the data from the table identified by the id. The file is read only once, consecutive calls to this method will return the sale collection. :param file_id: identifier for the table :return: all the values from the table ...
Create a Python 3 function for reading the data from the table identified by the id.
As a Python code composer, you craft elegant and concise scripts.
Returns a grammar for the record type field.
Here you have a function in Python 3, explain what it does def record_type(values): field = basic.lookup(values, name='Record Type (one of %s)' % values) return field.setResultsName('record_type')
You are a Python code generator, capable of creating scripts from specifications.
Creates a record prefix for the specified record type.
Can you generate the documentation for the following Python 3 function def record_prefix(required_type, factory): field = record_type(required_type) field += factory.get_rule('transaction_sequence_n') field += factory.get_rule('record_sequence_n') # field.leaveWhitespace() return field
As a Python code translator, you convert algorithms and pseudocode into Python.
def expand_entity(self, entity): """ Search and return entity or sub entity that contain value of this field. :param entity: :return: entity :raise KeyError """ if self.name in entity: return entity for key, value in entity.items(): ...
How would you implement a function in Python 3 that searches and return entity or sub entity that contain value of this field.
As a Python code translator, you convert algorithms and pseudocode into Python.
Encode this :param entity: :return: cwr string
Can you generate a brief explanation for the following Python 3 code def encode(self, entity): entity = self.expand_entity(entity) value = entity[self.name] result = self.format(value) return result
As a python code expert, you are capable of creating scripts from specifications.
def read_config_file(self, file_name): """ Reads a CWR grammar config file. :param file_name: name of the text file :return: the file's contents """ with open(os.path.join(self.__path(), os.path.basename(file_name)), 'rt') as file_config: re...
Write a Python 3 script to read a CWR grammar config file.
As a python code expert, you are capable of creating scripts from specifications.
Loads the CWR default values file and creates a matrix from it and then returns this data.
Can you tell what is the following Python 3 function doing def _load_cwr_defaults(self): if self._cwr_defaults is None: self._cwr_defaults = self._reader.read_yaml_file( self._file_defaults) return self._cwr_defaults
You are a Python code analyst, evaluating scripts for potential improvements.
def load_field_config(self, file_id): """ Loads the configuration fields file for the id. :param file_id: the id for the field :return: the fields configuration """ if file_id not in self._field_configs: self._field_configs[file_id] = self._reader.read_yaml_f...
Can you implement a function in Python 3 that loads the configuration fields file for the given id.
As a Python code composer, you craft elegant and concise scripts.
Loads the configuration fields file for the group.
Can you generate a brief explanation for the following Python 3 code def load_group_config(self, file_id): if file_id not in self._group_configs: self._group_configs[file_id] = self._reader.read_config_file( 'group_config_%s.cml' % file_id) return self._group_configs[file_id...
You are a Python code analyst, evaluating scripts for potential improvements.
def load_record_config(self, file_id): """ Loads the configuration fields file for the id. :param file_id: the id for the field :return: the fields configuration """ if file_id not in self._record_configs: self._record_configs[file_id] = self._reader.read_con...
Create a Python 3 function to load the configuration fields file for the record.
You are a Python code generator, capable of creating scripts from specifications.
def load_transaction_config(self, file_id): """ Loads the configuration fields file for the id. :param file_id: the id for the field :return: the fields configuration """ if file_id not in self._transaction_configs: self._transaction_configs[file_id] = self._...
How would you code a function in Python 3 to load the configuration fields file for the id.
You are a Python code analyst, evaluating scripts for potential improvements.
def load_acknowledge_config(self, file_id): """ Loads the CWR acknowledge config :return: the values matrix """ if self._cwr_defaults is None: self._cwr_defaults = self._reader.read_yaml_file( 'acknowledge_config_%s.yml' % file_id) return self...
Create a Python 3 function to load the CWR acknowledge config file and returns the values matrix
As a python code expert, you are capable of creating scripts from specifications.
def soft_error(self, message): """ Same as error, without the dying in a fire part. """ self.print_usage(sys.stderr) args = {'prog': self.prog, 'message': message} self._print_message( _('%(prog)s: error: %(message)s\n') % args, sys.stderr)
Write a Python 3 script to print a soft error message to stderr.
You are a Python code architect, reviewing and designing scalable and efficient code
Creates a decoder which parses CWR filenames following the old or the new convention.
Can you generate a brief explanation for the following Python 3 code def default_filename_decoder(): factory = default_filename_grammar_factory() grammar_old = factory.get_rule('filename_old') grammar_new = factory.get_rule('filename_new') return FileNameDecoder(grammar_old, grammar_new)
You are a Python code analyst, evaluating scripts for potential improvements.
Parses the file and creates a CWRFile instance from it.
Can you generate a brief explanation for the following Python 3 code def decode(self, data): file_name = self._filename_decoder.decode(data['filename']) file_data = data['contents'] i = 0 max_size = len(file_data) while file_data[i:i + 1] != 'H' and i < max_size: i +...
As a Python code analyst, you investigate and solve complex coding mysteries
def decode(self, file_name): """ Parses the filename, creating a FileTag from it. It will try both the old and the new conventions, if the filename does not conform any of them, then an empty FileTag will be returned. :param file_name: filename to parse :return: a FileT...
Write a Python 3 function that can parse the filename and returns a FileTag instance.
You are a Python code architect, reviewing and designing scalable and efficient code
Finalize the environment for passing into subprocess. Popen family of external process calling methods.
Explain what the following Python 3 code does def finalize_env(env): keys = _PLATFORM_ENV_KEYS.get(sys.platform, []) if 'PATH' not in keys: # this MUST be available due to Node.js (and others really) # needing something to look for binary locations when it shells # out to other binaries...
As a Python code composer, you craft elegant and concise scripts.
def fork_exec(args, stdin='', **kwargs): """ Do a fork-exec through the subprocess.Popen abstraction in a way that takes a stdin and return stdout. """ as_bytes = isinstance(stdin, bytes) source = stdin if as_bytes else stdin.encode(locale) p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PI...
Can you write a function in Python 3 where it does a fork - exec through the subprocess. Popen abstraction in a way that takes a stdin and return stdout and stderr.
As a Python code composer, you craft elegant and concise scripts.
Raises an exception under Python 2. 7.
Can you generate the documentation for the following Python 3 function def raise_os_error(_errno, path=None): msg = "%s: '%s'" % (strerror(_errno), path) if path else strerror(_errno) raise OSError(_errno, msg)
As a Python code analyst, you investigate and solve complex coding mysteries
def which(cmd, mode=os.F_OK | os.X_OK, path=None): """ Given cmd, check where it is on PATH. Loosely based on the version in python 3.3. """ if os.path.dirname(cmd): if os.path.isfile(cmd) and os.access(cmd, mode): return cmd if path is None: path = os.environ.get(...
Write a Python 3 function that can give a command check where it is on PATH.
You are a Python code generator, capable of creating scripts from specifications.
Initialize the internal state of the internal state of the internal state of the internal state.
Can you generate the documentation for the following Python 3 function def _init(self): self._entry_points = {} for entry_point in self.raw_entry_points: if entry_point.dist.project_name != self.reserved.get( entry_point.name, entry_point.dist.project_name): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
For updating a base dict with a fresh one returns a list of tuple containing the key previous value and the fresh value.
Here you have a function in Python 3, explain what it does def dict_update_overwrite_check(base, fresh): result = [ (key, base[key], fresh[key]) for key in set(base.keys()) & set(fresh.keys()) if base[key] != fresh[key] ] base.update(fresh) return result
You are a Python code architect, reviewing and designing scalable and efficient code
def spec_update_loaderplugin_registry(spec, default=None): """ Resolve a BasePluginLoaderRegistry instance from spec, and update spec[CALMJS_LOADERPLUGIN_REGISTRY] with that value before returning it. """ registry = spec.get(CALMJS_LOADERPLUGIN_REGISTRY) if isinstance(registry, BaseLoaderPl...
Can you implement a function in Python 3 that updates the loaderplugin registry in a Spec object.
As a python code expert, you are capable of creating scripts from specifications.
def spec_update_sourcepath_filter_loaderplugins( spec, sourcepath_map, sourcepath_map_key, loaderplugin_sourcepath_map_key=LOADERPLUGIN_SOURCEPATH_MAPS): """ Take an existing spec and a sourcepath mapping (that could be produced via calmjs.dist.*_module_registry_dependencies functions) a...
Implement a Python 3 function for taking an existing spec and a sourcepath mapping (that could be produced via calmjs.dist.*_module_registry_dependencies functions) and split out the keys that does not contain loaderplugin syntax and assign it to the spec under sourcepath_key. For the parts with loader plugin syntax (i...
As a Python code analyst, you investigate and solve complex coding mysteries
This function is used to prepare the loaderplugins for a given set of sources.
Can you tell what is the following Python 3 function doing def toolchain_spec_prepare_loaderplugins( toolchain, spec, loaderplugin_read_key, handler_sourcepath_key, loaderplugin_sourcepath_map_key=LOADERPLUGIN_SOURCEPATH_MAPS): """ A standard helper function for combining the fil...
You are a Python code generator, capable of creating scripts from specifications.
def process_compile_entries( processor, spec, entries, modpath_logger=None, targetpath_logger=None): """ The generalized raw spec entry process invocation loop. """ # Contains a mapping of the module name to the compiled file's # relative path starting from the base build_dir. all_modpa...
Write a Python 3 script for processing the compile entries.
As a Python code analyst, you investigate and solve complex coding mysteries
def update_selected(self, other, selected): """ Like update, however a list of selected keys must be provided. """ self.update({k: other[k] for k in selected})
Write a Python 3 script to like update but a list of selected keys must be provided.
As a python code expert, you are capable of creating scripts from specifications.
This method is used to check if the current frame protection is allowed.
How would you explain what the following Python 3 function does def __advice_stack_frame_protection(self, frame): if frame is None: logger.debug( 'currentframe() returned None; frame protection disabled') return f_back = frame.f_back while f_back: ...
As a python code expert, you are capable of creating scripts from specifications.
def advise(self, name, f, *a, **kw): """ Add an advice that will be handled later by the handle method. Arguments: name The name of the advice group f A callable method or function. The rest of the arguments will be passed as arguments and ...
Write a Python 3 script for adding an advice to the stack of the advice group.
You are a Python code analyst, evaluating scripts for potential improvements.
def handle(self, name): """ Call all advices at the provided name. This has an analogue in the join point in aspected oriented programming, but the analogy is a weak one as we don't have the proper metaobject protocol to support this. Implementation that make use of thi...
Create a Python 3 function to call all advices at the provided name. This has an analogue in the join point in aspected oriented programming, but the analogy is a weak one as we don't have the proper metaobject protocol to support this. Implementation that make use of this system should make it clear that they will cal...
As a python code expert, you are capable of creating scripts from specifications.
def realpath(self, spec, key): """ Resolve and update the path key in the spec with its realpath, based on the working directory. """ if key not in spec: # do nothing for now return if not spec[key]: logger.warning( "c...
Write a Python 3 script for resolving and update the path key in the spec with its realpath based on the working directory.
As a Python code analyst, you investigate and solve complex coding mysteries
Set up the compile prefix sourcepath and targetpath suffix attributes which are used to retrieve the values from the generator function.
Make a summary of the following Python 3 code def setup_prefix_suffix(self): self.compile_prefix = 'compile_' self.sourcepath_suffix = '_sourcepath' self.modpath_suffix = '_modpaths' self.targetpath_suffix = '_targetpaths'
As a Python code translator, you convert algorithms and pseudocode into Python.
Validate that the target is inside the build_dir.
How would you explain what the following Python 3 function does def _validate_build_target(self, spec, target): if not realpath(target).startswith(spec[BUILD_DIR]): raise ValueError('build_target %s is outside build_dir' % target)
As a Python code composer, you craft elegant and concise scripts.
This method is called by compile_transpile_entry to process the JavaScript source file provided by some Python package through the transpiler instance.
Given the following Python 3 function, write the documentation def transpile_modname_source_target(self, spec, modname, source, target): if not isinstance(self.transpiler, BaseUnparser): _deprecation_warning( 'transpiler callable assigned to %r must be an instance of ' ...
You are a Python code analyst, evaluating scripts for potential improvements.
Compile a loader plugin entry into a dictionary.
Here you have a function in Python 3, explain what it does def compile_loaderplugin_entry(self, spec, entry): modname, source, target, modpath = entry handler = spec[CALMJS_LOADERPLUGIN_REGISTRY].get(modname) if handler: return handler(self, spec, modname, source, target, modpath) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def modname_source_to_target(self, spec, modname, source): """ Create a target file name from the input module name and its source file name. The result should be a path relative to the build_dir, and this is derived directly from the modname with NO implicit convers of path sep...
How would you code a function in Python 3 to create a target file name from the input module name and its source file name. The result should be a path relative to the build_dir, and this is derived directly from the modname with NO implicit convers of path separators (i.e. '/' or any other) into a system or OS specifi...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the path to the target file for the given module name.
Given the following Python 3 function, write the documentation def modname_source_target_modnamesource_to_modpath( self, spec, modname, source, target, modname_source): """ Typical JavaScript tools will get confused if '.js' is added, so by default the same modname is returned as pat...
As a Python code translator, you convert algorithms and pseudocode into Python.
Private generator that generates the names of the source and target modules that are used by the toolchain.
Here you have a function in Python 3, explain what it does def _gen_modname_source_target_modpath(self, spec, d): for modname_source in d.items(): try: modname = self.modname_source_to_modname(spec, *modname_source) source = self.modname_source_to_source(spec, *modna...
You are a Python code generator, capable of creating scripts from specifications.
Generic step that compiles from a spec to build the build directory.
Given the following Python 3 function, write the documentation def compile(self, spec): spec[EXPORT_MODULE_NAMES] = export_module_names = spec.get( EXPORT_MODULE_NAMES, []) if not isinstance(export_module_names, list): raise TypeError( "spec provided a '%s' but i...
You are a Python code analyst, evaluating scripts for potential improvements.
This function sets up the spec advises and returns the unique ID of the new one.
Can you tell what is the following Python 3 function doing def calf(self, spec): if not isinstance(spec, Spec): raise TypeError('spec must be of type Spec') if not spec.get(BUILD_DIR): tempdir = realpath(mkdtemp()) spec.advise(CLEANUP, shutil.rmtree, tempdir) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Transpile a module name from one source to another.
Can you tell what is the following Python 3 function doing def transpile_modname_source_target(self, spec, modname, source, target): return self.simple_transpile_modname_source_target( spec, modname, source, target)
You are a Python code generator, capable of creating scripts from specifications.