output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def build(self, builder): """ Build XML by appending to builder """ builder.start("SourceID", {}) builder.data(self.source_id) builder.end("SourceID")
Write a Python 3 script for building the XML for this object into the given XML builder.
As a Python code translator, you convert algorithms and pseudocode into Python.
def build(self, builder): """Build XML by appending to builder""" params = {} if self.edit_point is not None: params["EditPoint"] = self.edit_point if self.used_imputation_method is not None: params['UsedImputationMethod'] = bool_to_yes_no(self.used_imputation_m...
Write a Python 3 function that can build the audit record into the XML string.
You are a Python code architect, reviewing and designing scalable and efficient code
def build(self, builder): """Build XML by appending to builder""" params = dict(Value=self.value, Status=self.status.value, ProtocolDeviationRepeatKey=self.repeat_key ) if self.code: params['Code'] = self.code ...
Can you create a Python 3 function that appends this ProtocolDeviation to the XML builder.
You are a Python code generator, capable of creating scripts from specifications.
def status(self, value): """Set Query Status""" if value is not None: if not isinstance(value, QueryStatusType): raise AttributeError("%s action type is invalid in mdsol:Query." % (value,)) self._status = value
Write a Python 3 script for setting the status of the resource.
As a Python code analyst, you investigate and solve complex coding mysteries
def build(self, builder): """ Build XML by appending to builder """ params = {} if self.value is not None: params['Value'] = str(self.value) if self.query_repeat_key is not None: params['QueryRepeatKey'] = str(self.query_repeat_key) if s...
Can you create a Python 3 function that builds the XML by appending to builder
As a Python code composer, you craft elegant and concise scripts.
Build XML object return the root
How would you explain what the following Python 3 function does def getroot(self): builder = ET.TreeBuilder() self.build(builder) return builder.close()
As a Python code analyst, you investigate and solve complex coding mysteries
def build(self, builder): """Build XML object, return the root, this is a copy for consistency and testing""" params = dict(ODMVersion="1.3", FileType=self.filetype, CreationDateTime=self.creationdatetime, Originator=self.originator, ...
How would you implement a function in Python 3 that builds the XML object and return the root element
As a Python code analyst, you investigate and solve complex coding mysteries
def _querystring(self): """Additional keyword arguments""" kw = {"studyoid": self.studyoid} if self.location_oid is not None: kw["locationoid"] = self.location_oid return kw
Write a Python 3 script for returning a dictionary of keyword arguments for the URL query string.
You are a Python code architect, reviewing and designing scalable and efficient code
Normalise the Attribute value and return the normalised value
Given the following Python 3 function, write the documentation def value(self): if isinstance(self.raw_value, (datetime.datetime, datetime.date)): return self.raw_value.isoformat() elif isinstance(self.raw_value, (bool,)): return 'Yes' if self.raw_value else 'No' return s...
As a Python code analyst, you investigate and solve complex coding mysteries
def add_attribute(self, attribute, value): """ Add an attribute to the current instance :param str attribute: Attribute name :type value: Union[datetime,bool,str] :param value: Attribute value """ class_name = self.__class__.__name__ if class_name.startsw...
Write a Python 3 function that can add an attribute to the current instance of the modm extension
As a python code expert, you are capable of creating scripts from specifications.
Merge in the MdsolAttribute for the passed parameter
Can you tell what is the following Python 3 function doing def mixin_params(self, params): if not isinstance(params, (dict,)): raise AttributeError("Cannot mixin to object of type {}".format(type(params))) for attribute in self.attributes: params.update({attribute.tag: attribute....
As a python code expert, you are capable of creating scripts from specifications.
Setter for the last_update_time attribute.
Explain what the following Python 3 code does def last_update_time(self, value): if isinstance(value, (datetime.datetime,)): self._last_update_time = value else: raise ValueError("Expect last_update_time to be a datetime")
You are a Python code architect, reviewing and designing scalable and efficient code
Set the Update Time from the local clock in UTC.
How would you explain what the following Python 3 function does def set_update_time(self, update_time=None): if update_time and isinstance(update_time, (datetime.datetime,)): self.last_update_time = update_time else: self.last_update_time = datetime.datetime.utcnow()
As a python code expert, you are capable of creating scripts from specifications.
def mixin_params(self, params): """ Add the mdsol:LastUpdateTime attribute :return: """ super(LastUpdateMixin, self).mixin_params(params) if self.last_update_time is not None: params.update({"mdsol:LastUpdateTime": self.last_update_time.isoformat()})
Can you implement a function in Python 3 that adds the mdsol : LastUpdateTime attribute to the params.
You are a Python code generator, capable of creating scripts from specifications.
Adds a milestone to the cache.
Given the following Python 3 function, write the documentation def add_milestone(self, milestone, codelistoid="MILESTONES"): """ Add a milestone :param codelistoid: specify the CodeListOID (defaults to MILESTONES) :param str milestone: Mileston...
As a Python code analyst, you investigate and solve complex coding mysteries
Add the annotations to the ODM Element
Can you generate the documentation for the following Python 3 function def mixin(self): if self.milestones: from rwslib.builders.clinicaldata import Annotation, Flag, FlagValue annotation = Annotation() for codelist, milestones in self.milestones.items(): for ...
You are a Python code generator, capable of creating scripts from specifications.
Extract environment name using studyname and protocolname
Can you generate the documentation for the following Python 3 function def getEnvironmentFromNameAndProtocol(studyname, protocolname): # StudyName = "TEST (1) (DEV)" # ProtocolName = "TEST (1)" # Raw Env = "(DEV)" raw_env = studyname[len(protocolname) :].strip() if "(" in raw_env...
As a Python code translator, you convert algorithms and pseudocode into Python.
Parse XML string and return root XML object
Can you tell what is the following Python 3 function doing def parseXMLString(xml): # Remove BOM if it exists (different requests seem to have different BOMs) unichr_captured = "" if not xml.strip(): return u"" while xml[0] != u"<": unichr_captured += xml[0] xml = xml[1:] ...
You are a Python code analyst, evaluating scripts for potential improvements.
Read properties from an XML Element to build a StudyList Item.
How would you explain what the following Python 3 function does def fromElement(cls, elem): e_global_variables = elem.find(ODM_NS + "GlobalVariables") studyname = e_global_variables.find(ODM_NS + "StudyName").text protocolname = e_global_variables.find(ODM_NS + "ProtocolName").text self ...
You are a Python code analyst, evaluating scripts for potential improvements.
def fromElement(cls, elem): """ Read properties from a MetaDataVersion element :param lxml.etree._Element elem: Source etree Element """ self = cls() self.oid = elem.get("OID") self.name = elem.get("Name") return self
Write a Python 3 script for reading properties from a MetaDataVersion element.
You are a Python code analyst, evaluating scripts for potential improvements.
Get the subject name consistently
Given the following Python 3 function, write the documentation def subject_name(self): if self.subjectkeytype and self.subjectkeytype == "SubjectUUID".lower(): # if the SubjectKeyType is "SubjectUUID", then return the SubjectName return self.subjectname else: return s...
You are a Python code analyst, evaluating scripts for potential improvements.
Read properties from an XML Element object.
Given the following Python 3 function, write the documentation def fromElement(cls, elem): self = cls() self.studyoid = elem.get("StudyOID") self.metadataversionoid = elem.get("MetaDataVersionOID") e_subjectdata = elem.findall(ODM_NS + "SubjectData")[0] self.subjectkey = e_subjec...
As a Python code analyst, you investigate and solve complex coding mysteries
Make an element with this tag and text content
Can you generate a brief explanation for the following Python 3 code def make_element(builder, tag, content): builder.start(tag, {}) builder.data(content) # Must be UTF-8 encoded builder.end(tag)
You are a Python code analyst, evaluating scripts for potential improvements.
def set_single_attribute(self, other, trigger_klass, property_name): """Used to set guard the setting of an attribute which is singular and can't be set twice""" if isinstance(other, trigger_klass): # Check property exists if not hasattr(self, property_name): ra...
Write a Python 3 function for using to set guard the setting of an attribute which is singular and can t be set twice
As a Python code composer, you craft elegant and concise scripts.
Used to set guard the setting of a list attribute.
Here you have a function in Python 3, explain what it does def set_list_attribute(self, other, trigger_klass, property_name): # Check property exists if isinstance(other, trigger_klass): if not hasattr(self, property_name): raise AttributeError("%s has no property %s" % (sel...
As a Python code translator, you convert algorithms and pseudocode into Python.
def transaction_type(self, value): """Set the TransactionType (with Input Validation)""" if value is not None: if value not in self.ALLOWED_TRANSACTION_TYPES: raise AttributeError('%s transaction_type element must be one of %s not %s' % ( self.__class__.__...
Write a Python 3 script to set the TransactionType ( with Input Validation
As a Python code translator, you convert algorithms and pseudocode into Python.
Build XML by appending to builder
Here you have a function in Python 3, explain what it does def build(self, builder): params = {} if self.study_oid: params.update(dict(StudyOID=self.study_oid)) builder.start("AdminData", params) for user in self.users: user.build(builder) for location in ...
You are a Python code analyst, evaluating scripts for potential improvements.
Build XML by appending to builder
Can you tell what is the following Python 3 function doing def build(self, builder): params = dict(StudyOID=self.study_oid, MetaDataVersionOID=self.metadata_version_oid, EffectiveDate=dt_to_iso8601(self.effective_date)) builder.start("MetaDataVersionRef", para...
As a Python code translator, you convert algorithms and pseudocode into Python.
def build(self, builder): """Build XML by appending to builder""" params = dict(OID=self.oid, Name=self.name) if self.location_type: params.update(dict(LocationType=self.location_type.value)) # mixins self.mixin() self.mixin_params(params...
Write a Python 3 script for building XML by appending to builder
As a Python code analyst, you investigate and solve complex coding mysteries
Build the XML by appending to the given XML builder.
Here you have a function in Python 3, explain what it does def build(self, builder): params = dict() builder.start(self.__class__.__name__, params) for street in self.street_names: street.build(builder) # build the children for child in ('city', 'country', 'state_prov...
You are a Python code architect, reviewing and designing scalable and efficient code
Builds the xml by appending it to the given XML builder object.
Can you generate the documentation for the following Python 3 function def build(self, builder): params = dict(OID=self.oid) if self.user_type: params.update(dict(UserType=self.user_type.value)) builder.start(self.__class__.__name__, params) # build the children for c...
You are a Python code analyst, evaluating scripts for potential improvements.
Builds this element : param builder : A builder object.
Can you tell what is the following Python 3 function doing def build(self, builder): builder.start(self.__class__.__name__) builder.data(self.country_code) builder.end(self.__class__.__name__)
You are a Python code analyst, evaluating scripts for potential improvements.
def get_next_start_id(self): """If link for next result set has been passed, extract it and get the next set start id""" link = self.rws_connection.last_result.links.get("next", None) if link: link = link['url'] p = urlparse(link) start_id = int(parse_qs(p.que...
Write a Python 3 function that can extract next start id from link for next result set and get the next start id
As a Python code analyst, you investigate and solve complex coding mysteries
def send_request(self, request_object, timeout=None, retries=1, **kwargs): """Send request to RWS endpoint. The request object passed provides the URL endpoint and the HTTP method. Takes the text response from RWS and allows the request object to modify it for return. This allows the request ...
How would you implement a function in Python 3 that sends a request to the RWS.
You are a Python code generator, capable of creating scripts from specifications.
def example_clinical_data(study_name, environment): """Test demonstrating building clinical data""" odm = ODM("test system")( ClinicalData("Mediflex", "DEV")( SubjectData("MDSOL", "IJS TEST4", transaction_type="Insert")( StudyEventData("SUBJECT")( FormData("EN", tr...
Write a Python 3 script for testing demonstrating building clinical data
As a Python code composer, you craft elegant and concise scripts.
Take a Rave CSV output ending with just EOF on it and return a DictReader
Make a summary of the following Python 3 code def getCSVReader(data, reader_type=csv.DictReader): f = StringIO(data[:-4]) # Remove \nEOF return reader_type(f)
As a Python code translator, you convert algorithms and pseudocode into Python.
Extract dataset definitions from CSV metadata
Here you have a function in Python 3, explain what it does def _setDatasets(self, metadata): # Pull the lot into a list cols = list(self.getCSVReader(metadata)) # sort the cols by view name and ordinal (they come sorted, but lets be sure) cols.sort(key=lambda x: [x['viewname'], int(x['o...
You are a Python code generator, capable of creating scripts from specifications.
def processFormData(self, data, dataset_name): """Take a string of form data as CSV and convert to insert statements, return template and data values""" # Get the cols for this dataset cols = self.datasets[dataset_name] reader = self.getCSVReader(data, reader_type=csv.reader) #...
Implement a function in Python 3 to take a string of form data as CSV and convert to insert statements return template and data values
You are a Python code generator, capable of creating scripts from specifications.
def _processDDL(self): """Generate and process table SQL, SQLLite version""" sql_statements = self._generateDDL() logging.info('Generating sqllite tables') for stmt in sql_statements: c = self.conn.cursor() c.execute(stmt) self.conn.commit()
Create a Python 3 function for generating and process SQLLite tables
You are a Python code generator, capable of creating scripts from specifications.
Generate DDL statements for SQLLite
How would you explain what the following Python 3 function does def _generateDDL(self): sql = [] # Next convert each set of columns into a table structure for dataset_name in sorted(self.datasets.keys()): # SQL to drop the table if it already exists sql.append('''drop ta...
As a Python code analyst, you investigate and solve complex coding mysteries
Overridden version of create DML for SQLLite
Make a summary of the following Python 3 code def _processDML(self, dataset_name, cols, reader): sql_template = self._generateInsertStatement(dataset_name, cols) # Now insert in batch, reader is a list of rows to insert at this point c = self.conn.cursor() c.executemany(sql_template, re...
You are a Python code architect, reviewing and designing scalable and efficient code
Generates a sql INSERT template
Here you have a function in Python 3, explain what it does def _generateInsertStatement(self, dataset_name, cols): col_names = [col["varname"] for col in cols] # Generate question mark placeholders qms = ','.join(['?' for x in col_names]) return 'INSERT INTO %s (%s) values (%s)' % (dat...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the view and type from a view name
Can you generate the documentation for the following Python 3 function def name_type_from_viewname(viewname): matched = VIEW_REX.match(viewname) return matched.group('view'), matched.group('type') or 'REGULAR'
As a Python code translator, you convert algorithms and pseudocode into Python.
def execute(self): """Generate local DB, pulling metadata and data from RWSConnection""" logging.info('Requesting view metadata for project %s' % self.project_name) project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name)) # Process it into a set of...
Implement a Python 3 function for generating local DB and metadata from RWSConnection
As a Python code translator, you convert algorithms and pseudocode into Python.
def typeof_rave_data(value): """Function to duck-type values, not relying on standard Python functions because, for example, a string of '1' should be typed as an integer and not as a string or float since we're trying to replace like with like when scrambling.""" # Test if value is a date for form...
Can you create a Python 3 function that functions to duck - type values for rave - data.
As a Python code composer, you craft elegant and concise scripts.
Return random float in specified format
Given the following Python 3 function, write the documentation def scramble_float(self, length, sd=0): if sd == 0: return str(fake.random_number(length)) else: return str(fake.pyfloat(length - sd, sd, positive=True))
As a Python code translator, you convert algorithms and pseudocode into Python.
def scramble_value(self, value): """Duck-type value and scramble appropriately""" try: type, format = typeof_rave_data(value) if type == 'float': i, f = value.split('.') return self.scramble_float(len(value) - 1, len(f)) elif type == 'i...
Create a Python 3 function for scrambling a value and return it as a string
You are a Python code generator, capable of creating scripts from specifications.
def scramble_codelist(self, codelist): """Return random element from code list""" # TODO: External code lists path = ".//{0}[@{1}='{2}']".format(E_ODM.CODELIST.value, A_ODM.OID.value, codelist) elem = self.metadata.find(path) codes = [] for c in elem.iter(E_ODM.CODELIST_...
Write a Python 3 function that can scramble a code list into a random element
As a Python code analyst, you investigate and solve complex coding mysteries
def scramble_itemdata(self, oid, value): """If metadata provided, use it to scramble the value based on data type""" if self.metadata is not None: path = ".//{0}[@{1}='{2}']".format(E_ODM.ITEM_DEF.value, A_ODM.OID.value, oid) elem = self.metadata.find(path) # for elem...
Write a Python 3 script to scramble the value based on the data type of the item.
As a Python code translator, you convert algorithms and pseudocode into Python.
def fill_empty(self, fixed_values, input): """Fill in random values for all empty-valued ItemData elements in an ODM document""" odm_elements = etree.fromstring(input) for v in odm_elements.iter(E_ODM.ITEM_DATA.value): if v.get(A_ODM.VALUE.value) == "": oid = v.get(A...
Write a Python 3 script to fill in random values for all empty - valued ItemData elements in an ODM document
You are a Python code analyst, evaluating scripts for potential improvements.
def make_int(value, missing=-1): """Convert string value to long, '' to missing""" if isinstance(value, six.string_types): if not value.strip(): return missing elif value is None: return missing return int(value)
How would you implement a function in Python 3 that converts string value to long
As a Python code translator, you convert algorithms and pseudocode into Python.
def parse(data, eventer): """Parse the XML data, firing events from the eventer""" parser = etree.XMLParser(target=ODMTargetParser(eventer)) return etree.XML(data, parser)
Implement a function in Python 3 to parse the XML data firing events from the eventer
You are a Python code analyst, evaluating scripts for potential improvements.
Emit the next element of the sequence.
Can you tell what is the following Python 3 function doing def emit(self): self.count += 1 # event_name = 'on_{0}'.format(self.context.subcategory.lower()) event_name = self.context.subcategory if hasattr(self.handler, event_name): getattr(self.handler, event_name)(self.con...
You are a Python code architect, reviewing and designing scalable and efficient code
On start of element tag
Here you have a function in Python 3, explain what it does def start(self, tag, attrib): if tag == E_CLINICAL_DATA: self.ref_state = AUDIT_REF_STATE self.context = Context(attrib[A_STUDY_OID], attrib[A_AUDIT_SUBCATEGORY_NAME], ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_parent_element(self): """Signatures and Audit elements share sub-elements, we need to know which to set attributes on""" return {AUDIT_REF_STATE: self.context.audit_record, SIGNATURE_REF_STATE: self.context.signature}[self.ref_state]
How would you code a function in Python 3 to get the parent element of the current context.
As a python code expert, you are capable of creating scripts from specifications.
Called for text between tags
Explain what the following Python 3 code does def data(self, data): if self.state == STATE_SOURCE_ID: self.context.audit_record.source_id = int(data) # Audit ids can be 64 bits elif self.state == STATE_DATETIME: dt = datetime.datetime.strptime(data, "%Y-%m-%dT%H:%M:%S") ...
As a python code expert, you are capable of creating scripts from specifications.
Validate that a field is not empty.
Explain what the following Python 3 code does def validate_not_empty(): def empty_validator(field, data): if isinstance(field.value, str) and not field.value.strip(): raise ValidationError('empty') return empty_validator
You are a Python code generator, capable of creating scripts from specifications.
Validate the length of a node with either low high or equal.
Can you tell what is the following Python 3 function doing def validate_length(low=None, high=None, equal=None): def length_validator(field, data): if field.value is None: return if equal is not None and len(field.value) != equal: raise ValidationError('length_equal', equal=e...
As a Python code analyst, you investigate and solve complex coding mysteries
def validate_one_of(values): """ Validate that a field is in one of the given values. :param values: Iterable of valid values. :raises: ``ValidationError('one_of')`` """ def one_of_validator(field, data): if field.value is None: return options = values if cal...
Can you implement a function in Python 3 that validates that a field is in one of the given values.
As a Python code composer, you craft elegant and concise scripts.
Validate that a field is not in one of the given values.
Can you generate a brief explanation for the following Python 3 code def validate_none_of(values): def none_of_validator(field, data): options = values if callable(options): options = options() if field.value in options: raise ValidationError('none_of', choices=str.jo...
You are a Python code analyst, evaluating scripts for potential improvements.
Validate that a field with either low or high or equal is present.
Given the following Python 3 function, write the documentation def validate_range(low=None, high=None): def range_validator(field, data): if field.value is None: return if low is not None and field.value < low: key = 'range_low' if high is None else 'range_between' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def validate_equal(value): """ Validate the field value is equal to the given value. Should work with anything that supports '==' operator. :param value: Value to compare. :raises: ``ValidationError('equal')`` """ def equal_validator(field, data): if field.value is None: ...
Write a Python 3 function for validating the field value is equal to the given value.
As a Python code composer, you craft elegant and concise scripts.
def validate_matches(other): """ Validate the field value is equal to another field in the data. Should work with anything that supports '==' operator. :param value: Field key to compare. :raises: ``ValidationError('matches')`` """ def matches_validator(field, data): if field.value ...
How would you code a function in Python 3 to validate that the value of a field in the data contains the value of another field in the data.
You are a Python code generator, capable of creating scripts from specifications.
Validate that the field value matches the given regular expression.
Given the following Python 3 function, write the documentation def validate_regexp(pattern, flags=0): regex = re.compile(pattern, flags) if isinstance(pattern, str) else pattern def regexp_validator(field, data): if field.value is None: return if regex.match(str(field.value)) is Non...
As a python code expert, you are capable of creating scripts from specifications.
def validate_function(method, **kwargs): """ Validate the field matches the result of calling the given method. Example:: def myfunc(value, name): return value == name validator = validate_function(myfunc, name='tim') Essentially creates a validator that only accepts the name ...
Write a Python 3 script for validating the field value matches the result of calling the given method.
As a python code expert, you are capable of creating scripts from specifications.
def validate_email(): """ Validate the field is a valid email address. :raises: ``ValidationError('email')`` """ user_regex = re.compile( r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$" r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]' r'|\\[\001-\011\013\014\016-\17...
Can you write a function in Python 3 where it validates the field is a valid email address.
You are a Python code generator, capable of creating scripts from specifications.
def validate_model_unique(lookup_field, queryset, pk_field=None, pk_value=None): """ Validate the field is a unique, given a queryset and lookup_field. Example:: validator = validate_model_unique(User.email, User.select()) Creates a validator that can validate the uniqueness of an email address. ...
Write a Python 3 script for validating the field is a unique given a queryset and lookup_field.
You are a Python code architect, reviewing and designing scalable and efficient code
def coerce_single_instance(lookup_field, value): """ Convert from whatever value is given to a scalar value for lookup_field. If value is a dict, then lookup_field.name is used to get the value from the dict. Example: lookup_field.name = 'id' value = {'id': 123, 'name': 'tim'} return...
Create a Python 3 function to coerce a value to a scalar value for lookup_field.
As a Python code composer, you craft elegant and concise scripts.
def isiterable_notstring(value): """ Returns True if the value is iterable but not a string. Otherwise returns False. :param value: Value to check. """ if isinstance(value, str): return False return isinstance(value, Iterable) or isgeneratorfunction(value) or isgenerator(value)
Implement a function in Python 3 to return True if the value is iterable but not a string. Otherwise returns False.
As a python code expert, you are capable of creating scripts from specifications.
Get the value of this field from the data.
Can you generate a brief explanation for the following Python 3 code def get_value(self, name, data): if name in data: return data.get(name) if self.default: if callable(self.default): return self.default() return self.default return None
You are a Python code analyst, evaluating scripts for potential improvements.
Check to make sure the data for this field is valid.
Can you generate the documentation for the following Python 3 function def validate(self, name, data): self.value = self.get_value(name, data) if self.value is not None: self.value = self.coerce(self.value) for method in self.validators: method(self, data)
You are a Python code architect, reviewing and designing scalable and efficient code
Validate that the related field is set.
Given the following Python 3 function, write the documentation def validate(self, name, data): super().validate(name, data) if self.value is not None: try: self.value = self.query.get(self.lookup_field == self.value) except (AttributeError, ValueError, peewee.Does...
As a python code expert, you are capable of creating scripts from specifications.
def coerce(self, value): """Convert from whatever is given to a list of scalars for the lookup_field.""" if isinstance(value, dict): value = [value] if not isiterable_notstring(value): value = [value] return [coerce_single_instance(self.lookup_field, v) for v in v...
Write a Python 3 function that can convert from whatever is given to a list of scalars for the lookup_field.
You are a Python code architect, reviewing and designing scalable and efficient code
Initialize the base_fields dictionary.
Can you generate the documentation for the following Python 3 function def initialize_fields(self): for field in dir(self): obj = getattr(self, field) if isinstance(obj, Field): self._meta.fields[field] = obj
You are a Python code analyst, evaluating scripts for potential improvements.
def validate(self, data=None, only=None, exclude=None): """ Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. This is usually the method you want to call after...
Can you create a Python 3 function that validates the data for all fields and return whether the validation was successful.
As a Python code analyst, you investigate and solve complex coding mysteries
def clean_fields(self, data): """ For each field, check to see if there is a clean_<name> method. If so, run that method and set the returned value on the self.data dict. This happens after all validations so that each field can act on the cleaned data of other fields if needed. ...
How would you implement a function in Python 3 that cleans the data of the record sets.
You are a Python code architect, reviewing and designing scalable and efficient code
def initialize_fields(self): """ Convert all model fields to validator fields. Then call the parent so that overwrites can happen if necessary for manually defined fields. :return: None """ # # Pull all the "normal" fields off the model instance meta. for name, f...
Create a Python 3 function for converting all model fields to validator fields.
As a python code expert, you are capable of creating scripts from specifications.
def convert_field(self, name, field): """ Convert a single field from a Peewee model field to a validator field. :param name: Name of the field as defined on this validator. :param name: Peewee field instance. :return: Validator field. """ if PEEWEE3: ...
How would you implement a function in Python 3 that converts a single field from a Peewee model field to a validator field.
As a Python code analyst, you investigate and solve complex coding mysteries
Validate the data for all fields and return whether the validation was successful.
Given the following Python 3 function, write the documentation def validate(self, data=None, only=None, exclude=None): data = data or {} only = only or self._meta.only exclude = exclude or self._meta.exclude for name, field in self.instance._meta.fields.items(): if name in e...
As a Python code analyst, you investigate and solve complex coding mysteries
def perform_index_validation(self, data): """ Validate any unique indexes specified on the model. This should happen after all the normal fields have been validated. This can add error messages to multiple fields. :return: None """ # Build a list of dict containi...
Implement a function in Python 3 to validate any unique indexes specified on the model.
As a Python code composer, you craft elegant and concise scripts.
Save the model and any related many - to - many fields.
Make a summary of the following Python 3 code def save(self, force_insert=False): delayed = {} for field, value in self.data.items(): model_field = getattr(type(self.instance), field, None) # If this is a many-to-many field, we cannot save it to the instance until the instance ...
As a python code expert, you are capable of creating scripts from specifications.
Given an input integer N returns the representation of N in bytes.
Here you have a function in Python 3, explain what it does def long_to_bytes(N, blocksize=1): bytestring = hex(N) bytestring = bytestring[2:] if bytestring.startswith('0x') else bytestring bytestring = bytestring[:-1] if bytestring.endswith('L') else bytestring bytestring = '0' + bytestring if (len(byt...
You are a Python code generator, capable of creating scripts from specifications.
def encrypt(self, plaintext, iv_bytes=None): """Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``. Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``. ...
Can you implement a function in Python 3 that gives a string plaintext returns a ciphertext encrypted with an authenticated - encryption scheme using the keys specified in self. K1 and self. K2.
You are a Python code architect, reviewing and designing scalable and efficient code
def decrypt(self, ciphertext): """Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``. Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string. Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative mes...
Implement a Python 3 function for giving a ciphertext returns a plaintext using the keys specified in self. _ecb_enc_K1 and self. _ecb_enc_K2.
You are a Python code architect, reviewing and designing scalable and efficient code
Given a ciphertext with a valid header returns the length of the ciphertext inclusive of ciphertext expansion.
Can you tell what is the following Python 3 function doing def getCiphertextLen(self, ciphertext): plaintext_length = self.getPlaintextLen(ciphertext) ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION return ciphertext_length
You are a Python code generator, capable of creating scripts from specifications.
def getPlaintextLen(self, ciphertext): """Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload. """ completeCiphertextHeader = (len(ciphertext) >= 16) if completeCiphertextHeader is False: raise RecoverableDecryptionError('Incomplete cipher...
Implement a function in Python 3 to give a ciphertext with a valid header returns the length of the plaintext payload.
You are a Python code analyst, evaluating scripts for potential improvements.
def _make_digest(k, **kwargs): """ Creates a digest suitable for use within an :class:`phyles.FSCache` object from the key object `k`. >>> adict = {'a' : {'b':1}, 'f': []} >>> make_digest(adict) 'a2VKynHgDrUIm17r6BQ5QcA5XVmqpNBmiKbZ9kTu0A' """ result = list() result_dict = _make_dig...
Implement a function in Python 3 to create a digest suitable for use within an object.
As a Python code translator, you convert algorithms and pseudocode into Python.
def cached_model_file(model_name='anon_model', file=None, model_code=None, cache_dir=None, fit_cachefile=None, include_prefix=False): ''' Given model name & stan model code/file, compute path to cached stan fit if include_prefix, returns (model_prefix, model_cachefile) '''...
Can you implement a function in Python 3 that gives model name and stan model code file compute path to cached stan fit if include_prefix returns ( model_prefix model_cachefile
As a Python code composer, you craft elegant and concise scripts.
def cached_stan_file(model_name='anon_model', file=None, model_code=None, cache_dir=None, fit_cachefile=None, cache_only=None, force=False, include_modelfile=False, prefix_only=False, **kwargs ): ''' Given inputs to cached_stan_fit, compute pic...
Write a Python 3 script for giving inputs to cached_stan_fit compute pickle file containing cached fit
You are a Python code generator, capable of creating scripts from specifications.
Cache fit stan model with the given model code and parameters.
Can you tell what is the following Python 3 function doing def _cached_stan_fit(model_name='anon_model', file=None, model_code=None, force=False, cache_dir=None, cache_only=None, fit_cachefile=None, **kwargs): ''' Cache fit stan model, by storing pickled objects in filesyst...
You are a Python code analyst, evaluating scripts for potential improvements.
def fit_lorentizan(curve,p0=None,N_points=1000): '''Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess. It returns a curve with N_points.''' def lorentzian(x,x0,A,gamma): return A*gamma**2/((x-x0)**2+gamma**2) N=len(curve) x=[curve[i][0] for i in range(N)] y=[curve[i][1] for i in range(N)] ...
Write a Python 3 function for fitting a lorentzian curve using p0 as an initial guess. Returns a list of N_points.
You are a Python code generator, capable of creating scripts from specifications.
def electric_field_amplitude_gaussian(P, sigmax, sigmay=None, Omega=1.0e6, units="ad-hoc"): """Return the amplitude of the electric field for a Gaussian beam. This the amplitude at the center of a laser beam of power P (in Watts) and\ a Gaussian intensity distributio...
How would you implement a function in Python 3 that returns the amplitude of the electric field for a Gaussian beam.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the amplitude of the electric field for a top hat beam of power P and a top - hat intensity distribution of radius a.
Can you tell what is the following Python 3 function doing def electric_field_amplitude_top(P, a, Omega=1e6, units="ad-hoc"): e0 = hbar*Omega/(e*a0) # This is the electric field scale. E0 = sqrt((c*mu0*P)/(Pi*a**2)) if units == "ad-hoc": E0 = E0/e0 return E0
You are a Python code generator, capable of creating scripts from specifications.
def electric_field_amplitude_intensity(s0, Isat=16.6889462814, Omega=1e6, units="ad-hoc"): """Return the amplitude of the electric field for saturation parameter. This is at a given saturation parameter s0=I/Isat, where I0 is by default \ Isat=16.6889462814 m/m^2 is ...
Write a Python 3 function that can return the amplitude of the electric field for saturation parameter.
You are a Python code analyst, evaluating scripts for potential improvements.
r Prints the expression in the notebook.
How would you explain what the following Python 3 function does def fprint(expr, print_ascii=False): if print_ascii: pprint(expr, use_unicode=False, num_columns=120) else: return expr
As a python code expert, you are capable of creating scripts from specifications.
This function calculates the global index mu for the element i j.
Given the following Python 3 function, write the documentation def Mu(i, j, s, N, excluded_mu=[]): if i == j: if s == -1: if i == 1: return 0 else: mes = 'There is no population rhoii with i='+str(i)+'.' raise ValueError(mes) mu...
You are a Python code architect, reviewing and designing scalable and efficient code
def IJ(mu, N): """Return i, j, s for any given mu.""" if mu == 0: return 1, 1, 1 if mu not in range(0, N**2): raise ValueError('mu has an invalid value mu='+str(mu)+'.') if 1 <= mu <= N-1: return mu+1, mu+1, 1 else: m = N-1 M = N*(N-1)/2 for jj in range(1, N...
Can you implement a function in Python 3 that returns i j s for any given mu.
You are a Python code generator, capable of creating scripts from specifications.
r This function reads the results stored in path under file name. dat returns them as a list of N^2 lists where N is the number of times the real part and rho_i j s is the imaginary part and s is the number of times the imaginary part.
Explain what the following Python 3 code does def read_result(path, name, i=None, j=None, s=0, N=None, excluded_mu=[], use_netcdf=True, clone=None): r"""This function reads the results stored in path under file name.dat returning them as a list of N^2 lists of the form [frequency, rho22, rho...
As a Python code composer, you craft elegant and concise scripts.
r Return the correspondance between degenerate and nondegenerate schemes.
Here you have a function in Python 3, explain what it does def calculate_iI_correspondence(omega): Ne = len(omega[0]) om = omega[0][0] correspondence = [] I = 0 for i in range(Ne): if omega[i][0] != om: om = omega[i][0] I += 1 correspondence += [(i+1, I+1)] ...
As a Python code analyst, you investigate and solve complex coding mysteries
r This function returns a list of length Nl containing the mininmal frequency that each laser excites.
Explain what the following Python 3 code does def find_omega_min(omega, Nl, detuningsij, i_d, I_nd): omega_min = [] omega_min_indices = [] for l in range(Nl): omegas = sorted([(omega[i_d(p[0]+1)-1][i_d(p[1]+1)-1], p) for p in detuningsij[l]]) omega_min += [omegas[0][...
As a python code expert, you are capable of creating scripts from specifications.