output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def parameter(self, parameter_id): """Return the specified global parameter (the entire object, not just the value)""" for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: if parameter.id == parameter_id: ...
Implement a Python 3 function for returning the specified global parameter
As a Python code composer, you craft elegant and concise scripts.
Return the first parameter error
Given the following Python 3 function, write the documentation def parametererror(self): for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: if parameter.error: return parameter.error return Fals...
You are a Python code analyst, evaluating scripts for potential improvements.
def passparameters(self): """Return all parameters as {id: value} dictionary""" paramdict = {} for parametergroup, params in self.parameters: #pylint: disable=unused-variable for parameter in params: if parameter.value: if isinstance(parameter.valu...
Can you implement a function in Python 3 that returns all parameters as a dictionary
You are a Python code architect, reviewing and designing scalable and efficient code
Return all input templates as a list of InputTemplate instances
How would you explain what the following Python 3 function does def inputtemplates(self): l = [] for profile in self.profiles: l += profile.input return l
As a Python code translator, you convert algorithms and pseudocode into Python.
def inputtemplate(self,template_id): """Return the inputtemplate with the specified ID. This is used to resolve a inputtemplate ID to an InputTemplate object instance""" for profile in self.profiles: for inputtemplate in profile.input: if inputtemplate.id == template_id: ...
Write a Python 3 script to return the inputtemplate with the specified ID. This is used to resolve a inputtemplate ID to an InputTemplate object instance instance.
You are a Python code architect, reviewing and designing scalable and efficient code
Return the inputfile for the specified inputtemplate if inputtemplate = None inputfile is returned regardless of inputtemplate.
Explain what the following Python 3 code does def inputfile(self, inputtemplate=None): inputfiles = list(self.inputfiles(inputtemplate)) if len(inputfiles) < 1: raise Exception("No such input file") elif len(inputfiles) > 1: raise Exception("Multiple input files matched. ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Generator yielding all inputfiles for the specified inputtemplate.
Can you generate a brief explanation for the following Python 3 code def inputfiles(self, inputtemplate=None): if isinstance(inputtemplate, InputTemplate): #ID suffices: inputtemplate = inputtemplate.id for inputfile in self.input: if not inputtemplate or inputfile.me...
You are a Python code generator, capable of creating scripts from specifications.
Check if the profile matches all inputdata and produces output given the set parameters. Returns a boolean
Can you tell what is the following Python 3 function doing def match(self, projectpath, parameters): parameters = sanitizeparameters(parameters) mandatory_absent = [] #list of input templates that are missing but mandatory optional_absent = [] #list of absent but optional input templates ...
You are a Python code generator, capable of creating scripts from specifications.
def matchingfiles(self, projectpath): """Return a list of all inputfiles matching the profile (filenames)""" l = [] for inputtemplate in self.input: l += inputtemplate.matchingfiles(projectpath) return l
Can you implement a function in Python 3 that returns a list of all inputfiles matching the profile
As a Python code analyst, you investigate and solve complex coding mysteries
def outputtemplates(self): """Returns all outputtemplates, resolving ParameterConditions to all possibilities""" outputtemplates = [] for o in self.output: if isinstance(o, ParameterCondition): outputtemplates += o.allpossibilities() else: ...
Can you create a Python 3 function that returns all outputtemplates resolving ParameterConditions to all possibilities
You are a Python code analyst, evaluating scripts for potential improvements.
Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance.
Explain what the following Python 3 code does def generate(self, projectpath, parameters, serviceid, servicename,serviceurl): #Make dictionary of parameters parameters = sanitizeparameters(parameters) program = Program(projectpath, [self]) match, optional_absent = self.match(projectpa...
As a Python code translator, you convert algorithms and pseudocode into Python.
def xml(self, indent = ""): """Produce XML output for the profile""" xml = "\n" + indent + "<profile>\n" xml += indent + " <input>\n" for inputtemplate in self.input: xml += inputtemplate.xml(indent +" ") + "\n" xml += indent + " </input>\n" xml += indent +...
Implement a function in Python 3 to produce XML output for the profile
As a Python code translator, you convert algorithms and pseudocode into Python.
def fromxml(node): """Return a profile instance from the given XML description. Node can be a string or an etree._Element.""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) args = [] if node.tag == 'profile': ...
Create a Python 3 function to return a profile instance from the given XML description. Node can be a string or an etree. _Element.
As a Python code analyst, you investigate and solve complex coding mysteries
def add(self, outputfilename, outputtemplate, inputfilename=None, inputtemplate=None): """Add a new path to the program""" if isinstance(outputtemplate,OutputTemplate): outputtemplate = outputtemplate.id if isinstance(inputtemplate,InputTemplate): inputtemplate = inputtem...
Write a Python 3 function that can add a new path to the program
You are a Python code architect, reviewing and designing scalable and efficient code
Iterates over all output files and their output templates.
Here you have a function in Python 3, explain what it does def getoutputfiles(self, loadmetadata=True, client=None,requiremetadata=False): for outputfilename, outputtemplate in self.outputpairs(): yield CLAMOutputFile(self.projectpath, outputfilename, loadmetadata,client,requiremetadata), outputtemp...
You are a Python code analyst, evaluating scripts for potential improvements.
def getinputfiles(self, outputfile, loadmetadata=True, client=None,requiremetadata=False): """Iterates over all input files for the specified outputfile (you may pass a CLAMOutputFile instance or a filename string). Yields (CLAMInputFile,str:inputtemplate_id) tuples. The last three arguments are passed to its c...
How would you code a function in Python 3 to iterate over all input files for the specified outputfile.
As a Python code translator, you convert algorithms and pseudocode into Python.
def getinputfile(self, outputfile, loadmetadata=True, client=None,requiremetadata=False): """Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles()""" if isinstance(ou...
Can you create a Python 3 function that gets one input file for the specified output filename.
You are a Python code architect, reviewing and designing scalable and efficient code
Grabs one output file.
Can you tell what is the following Python 3 function doing def getoutputfile(self, loadmetadata=True, client=None,requiremetadata=False): return next(self.getoutputfiles(loadmetadata,client,requiremetadata))
As a Python code analyst, you investigate and solve complex coding mysteries
def xml(self, indent = ""): """Serialise provenance data to XML. This is included in CLAM Metadata files""" xml = indent + "<provenance type=\"clam\" id=\""+self.serviceid+"\" name=\"" +self.servicename+"\" url=\"" + self.serviceurl+"\" outputtemplate=\""+self.outputtemplate_id+"\" outputtemplatelabel=\...
Write a Python 3 function that can serialise provenance data to XML. This is included in CLAM Metadata files.
You are a Python code analyst, evaluating scripts for potential improvements.
Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml. etree. _Element.
Can you generate a brief explanation for the following Python 3 code def fromxml(node): if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) if node.tag == 'provenance': #pylint: disable=too-many-nested-blocks if node.attrib[...
As a python code expert, you are capable of creating scripts from specifications.
def xml(self, indent = ""): """Render an XML representation of the metadata""" #(independent of web.py for support in CLAM API) if not indent: xml = '<?xml version="1.0" encoding="UTF-8"?>\n' else: xml = "" xml += indent + "<CLAMMetaData format=\"" + self.__class_...
How would you implement a function in Python 3 that renders an XML representation of the metadata
As a Python code translator, you convert algorithms and pseudocode into Python.
Save the current metadata to a file
Here you have a function in Python 3, explain what it does def save(self, filename): with io.open(filename,'w',encoding='utf-8') as f: f.write(self.xml())
As a python code expert, you are capable of creating scripts from specifications.
def fromxml(node, file=None): """Read metadata from XML. Static method returning an CLAMMetaData instance (or rather; the appropriate subclass of CLAMMetaData) from the given XML description. Node can be a string or an etree._Element.""" if not isinstance(node,ElementTree._Element): #pylint: disable=pro...
Implement a Python 3 function for reading metadata from XML. Static method returning an CLAMMetaData instance (or rather; the appropriate subclass of CLAMMetaData) from the given XML description. Node can be a string or an etree._Element.
As a Python code composer, you craft elegant and concise scripts.
def xml(self, indent = ""): """Produce Template XML""" xml = indent + "<InputTemplate id=\""+self.id+"\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\"" if self.formatclass.mimetype: xml +=" mimetype=\""+self.formatclass.mimetype+"\"" if self.f...
How would you implement a function in Python 3 that produces XML representation of the object.
You are a Python code analyst, evaluating scripts for potential improvements.
Produce a JSON representation of the web interface
Explain what the following Python 3 code does def json(self): d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self.formatclass.mimetype, 'schema': self.formatclass.schema } if self.unique: d['unique'] = True if self.filename: d['...
As a Python code analyst, you investigate and solve complex coding mysteries
Does the specified metadata match this template? returns success metadata and parameters
How would you explain what the following Python 3 function does def match(self, metadata, user = None): assert isinstance(metadata, self.formatclass) return self.generate(metadata,user)
As a python code expert, you are capable of creating scripts from specifications.
Checks if the input conditions are satisfied. Returns a list of matching results.
Make a summary of the following Python 3 code def matchingfiles(self, projectpath): results = [] if projectpath[-1] == '/': inputpath = projectpath + 'input/' else: inputpath = projectpath + '/input/' for linkf,realf in clam.common.util.globsymlinks(inputpath + ...
You are a Python code analyst, evaluating scripts for potential improvements.
def validate(self, postdata, user = None): """Validate posted data against the inputtemplate""" clam.common.util.printdebug("Validating inputtemplate " + self.id + "...") errors, parameters, _ = processparameters(postdata, self.parameters, user) return errors, parameters
Implement a function in Python 3 to validate the posted data against the inputtemplate
You are a Python code generator, capable of creating scripts from specifications.
def generate(self, file, validatedata = None, inputdata=None, user = None): """Convert the template into instantiated metadata, validating the data in the process and returning errors otherwise. inputdata is a dictionary-compatible structure, such as the relevant postdata. Return (success, metadata, parameters...
Create a Python 3 function to convert the template into instantiated metadata validating the data in the process and returning errors otherwise.
As a Python code analyst, you investigate and solve complex coding mysteries
Serialize the metadata field to XML
Can you generate a brief explanation for the following Python 3 code def xml(self, operator='set', indent = ""): xml = indent + "<meta id=\"" + self.key + "\"" if operator != 'set': xml += " operator=\"" + operator + "\"" if not self.value: xml += " />" else: ...
You are a Python code generator, capable of creating scripts from specifications.
Static method returning an instance of MetaField from the given XML description. Node can be a string or an etree. _Element object.
Can you generate the documentation for the following Python 3 function def fromxml(node): if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) if node.tag.lower() != 'meta': raise Exception("Expected meta tag but got '" + nod...
As a Python code composer, you craft elegant and concise scripts.
def findparent(self, inputtemplates): """Find the most suitable parent, that is: the first matching unique/multi inputtemplate""" for inputtemplate in inputtemplates: if self.unique == inputtemplate.unique: return inputtemplate.id return None
Implement a Python 3 function for finding the most suitable parent for this inputtemplate
As a Python code translator, you convert algorithms and pseudocode into Python.
def getparent(self, profile): """Resolve a parent ID""" assert self.parent for inputtemplate in profile.input: if inputtemplate == self.parent: return inputtemplate raise Exception("Parent InputTemplate '"+self.parent+"' not found!")
Can you write a function in Python 3 where it resolves a parent ID
You are a Python code analyst, evaluating scripts for potential improvements.
Generate all relevant input files for this output template.
Given the following Python 3 function, write the documentation def generate(self, profile, parameters, projectpath, inputfiles, provenancedata=None): project = os.path.basename(projectpath) if self.parent: #pylint: disable=too-many-nested-blocks #We have a parent, infer the correct filenam...
You are a Python code generator, capable of creating scripts from specifications.
Generate metadata given a filename parameters and a dictionary of inputdata
Explain what the following Python 3 code does def generatemetadata(self, parameters, parentfile, relevantinputfiles, provenancedata = None): assert isinstance(provenancedata,CLAMProvenanceData) or provenancedata is None data = {} if self.copymetadata: #Copy parent metadata ...
As a Python code composer, you craft elegant and concise scripts.
def allpossibilities(self): """Returns all possible outputtemplates that may occur (recusrively applied)""" l = [] if isinstance(self.then, ParameterCondition): #recursive parametercondition l += self.then.allpossibilities() elif self.then: l.append(se...
How would you code a function in Python 3 to return all possible outputtemplates that may occur ( recusrively applied
As a Python code analyst, you investigate and solve complex coding mysteries
Evaluates the condition and returns True if there s no match or whatever the ParameterCondition evaluates to ( recursively applied!
Make a summary of the following Python 3 code def evaluate(self, parameters): if self.match(parameters): if isinstance(self.then, ParameterCondition): #recursive parametercondition return self.then.evaluate(parameters) else: return self.the...
As a Python code translator, you convert algorithms and pseudocode into Python.
Static method returning an Action instance from the given XML description. Node can be a string or an etree. _Element.
Can you tell what is the following Python 3 function doing def fromxml(node): if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) assert node.tag.lower() == 'action' kwargs = {} args = [] if 'id' in node.attrib:...
As a Python code composer, you craft elegant and concise scripts.
This is a very crude tokenizer from pynlpl
How would you explain what the following Python 3 function does def crude_tokenizer(line): tokens = [] buffer = '' for c in line.strip(): if c == ' ' or c in string.punctuation: if buffer: tokens.append(buffer) buffer = '' else: buffer ...
As a Python code composer, you craft elegant and concise scripts.
Function for converting dictionary to plaintext output optionally with some sort
Can you tell what is the following Python 3 function doing def dicttotext(d, sort=False, max = 0): if sort: f = lambda x: sorted(x, key=lambda y: -1 * y[1]) else: f = lambda x: x output = "" for i, (key, value) in enumerate(f(d.items())): output += key + "\t" + str(value) + "\n"...
As a python code expert, you are capable of creating scripts from specifications.
def initauth(self): """Initialise authentication, for internal use""" headers = {'User-agent': 'CLAMClientAPI-' + clam.common.data.VERSION} if self.oauth: if not self.oauth_access_token: r = requests.get(self.url,headers=headers, verify=self.verify) if...
Write a Python 3 function for initialising authentication for internal use
As a Python code composer, you craft elegant and concise scripts.
Issue a HTTP request and parse the response.
Given the following Python 3 function, write the documentation def request(self, url='', method = 'GET', data = None, parse=True, encoding=None): requestparams = self.initrequest(data) if method == 'POST': request = requests.post elif method == 'DELETE': request = requ...
You are a Python code architect, reviewing and designing scalable and efficient code
Parses CLAM XML data and returns a CLAMData object. For internal use. Raises ParameterError exception on parameter errors.
Can you tell what is the following Python 3 function doing def _parse(self, content): if content.find('<clam') != -1: data = clam.common.data.CLAMData(content,self, loadmetadata=self.loadmetadata) if data.errors: error = data.parametererror() if error: ...
You are a Python code generator, capable of creating scripts from specifications.
def get(self, project): """Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code""" try: data = self.request(project + '/') except: raise if not isinstance(data, clam.common.data.CLAMData): ...
Create a Python 3 function to query the project status. Returns a CLAMData instance.
As a Python code translator, you convert algorithms and pseudocode into Python.
def action(self, action_id, **kwargs): """Query an action, specify the parameters for the action as keyword parameters. An optional keyword parameter method='GET' (default) or method='POST' can be set. The character set encoding of the response can be configured using the encoding keyword parameter (defaults to...
Write a Python 3 script to query an action, specify the parameters for the action as keyword parameters. An optional keyword parameter method='GET' (default) or method='POST' can be set. The character set encoding of the response can be configured using the encoding keyword parameter (defaults to utf-8 by default)
As a Python code analyst, you investigate and solve complex coding mysteries
Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for the global parameters. Returns a ``CLAMData`` object or raises exceptions. Note that no exceptions are raised on parameter errors, you have to check for those manually! (Use startsafe instead if want Exceptions on pa...
Can you generate the documentation for the following Python 3 function def start(self, project, **parameters): #auth = None #if 'auth' in parameters: # auth = parameters['auth'] # del parameters['auth'] for key in parameters: if isinstance(parameters[key],list) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for the global parameters. Returns a ``CLAMData`` object or raises exceptions. This version, unlike ``start()``, raises Exceptions (``ParameterError``) on parameter errors. response = client.startsafe("mypro...
Can you tell what is the following Python 3 function doing def startsafe(self, project, **parameters): try: data = self.start(project, **parameters) for parametergroup, paramlist in data.parameters: #pylint: disable=unused-variable for parameter in paramlist: ...
You are a Python code generator, capable of creating scripts from specifications.
Download all output files as a single archive
Make a summary of the following Python 3 code def downloadarchive(self, project, targetfile, archiveformat = 'zip'): if isinstance(targetfile,str) or (sys.version < '3' and isinstance(targetfile,unicode)): #pylint: disable=undefined-variable targetfile = open(targetfile,'wb') r = requests.ge...
You are a Python code analyst, evaluating scripts for potential improvements.
Determine the final filename for an input file given an inputtemplate and a given filename.
Can you generate the documentation for the following Python 3 function def getinputfilename(self, inputtemplate, filename): if inputtemplate.filename: filename = inputtemplate.filename elif inputtemplate.extension: if filename.lower()[-4:] == '.zip' or filename.lower()[-7:] == '....
You are a Python code analyst, evaluating scripts for potential improvements.
Parse CLAM Upload XML Responses. For internal use.
Can you tell what is the following Python 3 function doing def _parseupload(self, node): if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access try: node = clam.common.data.parsexmlstring(node) except: raise Exception(node) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds an input file to the CLAM service.
How would you explain what the following Python 3 function does def addinputfile(self, project, inputtemplate, sourcefile, **kwargs): if isinstance( inputtemplate, str) or (sys.version < '3' and isinstance( inputtemplate, unicode)): #pylint: disable=undefined-variable data = self.get(project) #cause...
As a Python code composer, you craft elegant and concise scripts.
def addinput(self, project, inputtemplate, contents, **kwargs): """Add an input file to the CLAM service. Explictly providing the contents as a string. This is not suitable for large files as the contents are kept in memory! Use ``addinputfile()`` instead for large files. project - the ID of the projec...
Can you implement a function in Python 3 that adds an input file to the CLAM service.
You are a Python code analyst, evaluating scripts for potential improvements.
def download(self, project, filename, targetfilename, loadmetadata=None): """Download an output file""" if loadmetadata is None: loadmetadata = self.loadmetadata f = clam.common.data.CLAMOutputFile(self.url + project, filename, loadmetadata, self) f.copy(targetfilename)
Implement a function in Python 3 to download an output file from the specified project to the specified target filename.
As a Python code composer, you craft elegant and concise scripts.
This method attempts to set the value for this parameter.
Explain what the following Python 3 code does def set(self, value): if self.validate(value): #print "Parameter " + self.id + " successfully set to " + repr(value) self.hasvalue = True self.value = value return True else: #print "Parameter " + s...
As a Python code composer, you craft elegant and concise scripts.
Create a Parameter instance from a XML description. Node can be a string containing XML or an lxml _Element object.
Explain what the following Python 3 code does def fromxml(node): if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = ElementTree.parse(StringIO(node)).getroot() if node.tag in globals(): id = '' paramflag = '' name = '' ...
You are a Python code architect, reviewing and designing scalable and efficient code
Set the boolean parameter value
Explain what the following Python 3 code does def set(self, value = True): value = value in (True,1) or ( (isinstance(value, str) or (sys.version < '3' and isinstance(value, unicode))) and (value.lower() in ("1","yes","true","enabled"))) #pylint: disable=undefined-variable return super(BooleanParameter,...
You are a Python code analyst, evaluating scripts for potential improvements.
This method compiles the parameter into a syntax that can be used on the shell such as - paramflag = value
How would you explain what the following Python 3 function does def compilearg(self): if isinstance(self.value,list): value = self.delimiter.join(self.value) else: value = self.value if value.find(" ") >= 0: value = '"' + value + '"' #wrap all in quotes ...
As a Python code composer, you craft elegant and concise scripts.
This methods renders an XML representation of this parameter along with its selected value and feedback on validation errors.
Make a summary of the following Python 3 code def xml(self, indent = ""): xml = indent + "<" + self.__class__.__name__ xml += ' id="'+self.id + '"' xml += ' name="'+xmlescape(self.name) + '"' xml += ' description="'+xmlescape(self.description) + '"' if self.paramflag: ...
You are a Python code analyst, evaluating scripts for potential improvements.
This method searches the POST data and retrieves the values it needs.
Explain what the following Python 3 code does def valuefrompostdata(self, postdata): if self.multi: #multi parameters can be passed as parameterid=choiceid1,choiceid2 or by setting parameterid[choiceid]=1 (or whatever other non-zero value) found = False if self.id in postdata: ...
As a Python code analyst, you investigate and solve complex coding mysteries
This method searches the POST data and returns the value of the attribute.
Can you generate a brief explanation for the following Python 3 code def valuefrompostdata(self, postdata): if self.id in postdata and postdata[self.id] != '': return int(postdata[self.id]) else: return None
As a python code expert, you are capable of creating scripts from specifications.
This method attempts to set the value of the parameter. If validation fails the parameter will be set to int.
Here you have a function in Python 3, explain what it does def set(self, value): if self.validate(value): #print "Parameter " + self.id + " successfully set to " + repr(value) self.hasvalue = True if isinstance(value, float): self.value = round(value) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def index(credentials = None): """Get list of projects or shortcut to other functionality""" #handle shortcut shortcutresponse = entryshortcut(credentials) if shortcutresponse is not None: return shortcutresponse projects = [] user, oauth_access_token = parsecredentials(credentials) ...
Write a Python 3 function that can get list of projects or shortcut to other functionality
You are a Python code architect, reviewing and designing scalable and efficient code
Add a new file to the input file list
Can you generate the documentation for the following Python 3 function def addfile(project, filename, user, postdata, inputsource=None,returntype='xml'): #pylint: disable=too-many-return-statements def errorresponse(msg, code=403): if returntype == 'json': return withheaders(flask.make_respons...
You are a Python code generator, capable of creating scripts from specifications.
def run_wsgi(settings_module): """Run CLAM in WSGI mode""" global settingsmodule, DEBUG #pylint: disable=global-statement printdebug("Initialising WSGI service") globals()['settings'] = settings_module settingsmodule = settings_module.__name__ try: if settings.DEBUG: DEBUG ...
Can you implement a function in Python 3 that runs CLAM in WSGI mode
As a Python code analyst, you investigate and solve complex coding mysteries
def index(credentials=None): """Get list of projects""" user, oauth_access_token = parsecredentials(credentials) if not settings.ADMINS or user not in settings.ADMINS: return flask.make_response('You shall not pass!!! You are not an administrator!',403) usersprojects = {} ...
How would you implement a function in Python 3 that gets list of projects
You are a Python code architect, reviewing and designing scalable and efficient code
Get the path to the project.
Make a summary of the following Python 3 code def path(project, credentials): user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable return settings.ROOT + "projects/" + user + '/' + project + "/"
You are a Python code generator, capable of creating scripts from specifications.
Create a new project if it does not already exist.
Here you have a function in Python 3, explain what it does def create(project, credentials): #pylint: disable=too-many-return-statements if not settings.COMMAND: return flask.make_response("Projects disabled, no command configured",404) user, oauth_access_token = parsecredentials(credentia...
As a Python code composer, you craft elegant and concise scripts.
def exists(project, credentials): """Check if the project exists""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable printdebug("Checking if project " + project + " exists for " + user) return os.path.isdir(Project.path(project, user))
Create a Python 3 function for checking if the project exists
As a python code expert, you are capable of creating scripts from specifications.
Retrieve sorted index for the specified input template
Make a summary of the following Python 3 code def inputindexbytemplate(project, user, inputtemplate): index = [] #pylint: disable=redefined-outer-name prefix = Project.path(project, user) + 'input/' for linkf, f in globsymlinks(prefix + '.*.INPUTTEMPLATE.' + inputtemplate.id + '.*'): ...
You are a Python code architect, reviewing and designing scalable and efficient code
def outputindexbytemplate(project, user, outputtemplate): """Retrieve sorted index for the specified input template""" index = [] #pylint: disable=redefined-outer-name prefix = Project.path(project, user) + 'output/' for linkf, f in globsymlinks(prefix + '.*.OUTPUTTEMPLATE.' + outputtemp...
Write a Python 3 function for retrieving sorted index for the specified output template
You are a Python code analyst, evaluating scripts for potential improvements.
def new(project, credentials=None): """Create an empty project""" user, oauth_access_token = parsecredentials(credentials) response = Project.create(project, user) if response is not None: return response msg = "Project " + project + " has been created for user " + us...
Can you write a function in Python 3 where it creates an empty project
You are a Python code analyst, evaluating scripts for potential improvements.
Start execution of a project.
Can you generate the documentation for the following Python 3 function def start(project, credentials=None): #pylint: disable=too-many-return-statements #handle shortcut shortcutresponse = entryshortcut(credentials, True) #protected against endless recursion, will return None when no shortcut is found,...
You are a Python code generator, capable of creating scripts from specifications.
Delete an output file
Here you have a function in Python 3, explain what it does def deleteoutputfile(project, filename, credentials=None): user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable if filename: filename = filename.replace("..","") #Simple security if not filename or ...
As a python code expert, you are capable of creating scripts from specifications.
Reset system delete all output files and prepare for a new run
Can you generate the documentation for the following Python 3 function def reset(project, user): d = Project.path(project, user) + "output" if os.path.isdir(d): shutil.rmtree(d) os.makedirs(d) else: raise flask.abort(404) if os.path.exists(Project.path...
As a Python code composer, you craft elegant and concise scripts.
Generates and returns a download package
Given the following Python 3 function, write the documentation def getarchive(project, user, format=None): if os.path.isfile(Project.path(project, user) + '.download'): #make sure we don't start two compression processes at the same time return withheaders(flask.make_response('Another co...
You are a Python code generator, capable of creating scripts from specifications.
Delete an input file
How would you explain what the following Python 3 function does def deleteinputfile(project, filename, credentials=None): user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable filename = filename.replace("..","") #Simple security if len(filename) == 0: ...
As a python code expert, you are capable of creating scripts from specifications.
Add a new input file to the database
Can you generate the documentation for the following Python 3 function def addinputfile(project, filename, credentials=None): #pylint: disable=too-many-return-statements printdebug('Addinputfile: Initialising' ) user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def corpusindex(): """Get list of pre-installed corpora""" corpora = [] for f in glob.glob(settings.ROOT + "corpora/*"): if os.path.isdir(f): corpora.append(os.path.basename(f)) return corpora
Write a Python 3 script for getting list of pre - installed corpora
As a Python code translator, you convert algorithms and pseudocode into Python.
Does the nonce exist and is it valid for the request?
Explain what the following Python 3 code does def validate(self, nonce): if self.debug: print("Checking nonce " + str(nonce),file=sys.stderr) try: opaque, ip, expiretime = self.get(nonce) #pylint: disable=unused-variable if expiretime < time.time(): if self.debug:...
You are a Python code analyst, evaluating scripts for potential improvements.
Retrun JSON representation of this run
Explain what the following Python 3 code does def json(self): return { "id": self.ID, "steps": self.steps, "graph_source": self.source, "errored": self.errored }
As a python code expert, you are capable of creating scripts from specifications.
def new_run(self): """Creates a new RunData object and increments pointers""" self.current_run += 1 self.runs.append(RunData(self.current_run + 1))
Write a Python 3 function for creating a new RunData object and increments pointers
You are a Python code architect, reviewing and designing scalable and efficient code
Reads a logfile continuously and updates the internal graph if new step is found.
Given the following Python 3 function, write the documentation def follow_log(self): # Server needs to be up and running before starting sending POST requests time.sleep(5) try: if self.remote: logger.debug('Logfile in remote host!') cl = client.SSHCli...
As a python code expert, you are capable of creating scripts from specifications.
Updates the frontend with info from the log. i. e regular line new step.
Given the following Python 3 function, write the documentation def update_frontend(self, info): headers = {'Content-Type': 'text/event-stream'} if info.get('when'): info['when'] = info['when'].isoformat() requests.post(self.base_url + '/publish', data=json.dumps(info), headers=header...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_summary(self): """Returns some summary data for a finished analysis""" if not self.analysis_finished: return [] summary = {'times_summary': []} for i in range(len(self.runs[self.current_run].steps) - 1): step = self.runs[self.current_run].steps[i] ...
Can you implement a function in Python 3 that returns some summary data for a finished analysis
As a Python code composer, you craft elegant and concise scripts.
Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
Can you generate a brief explanation for the following Python 3 code def _grabContentFromUrl(self, url): # Defining an empty object for the response info = {} # This part has to be modified... try: # Configuring the socket quer...
You are a Python code generator, capable of creating scripts from specifications.
def _handle_rundebug_from_shell(cmd_line): """ Handles all commands that take a filename and 0 or more extra arguments. Passes the command to backend. (Debugger plugin may also use this method) """ command, args = parse_shell_command(cmd_line) if len(args) >= 1: get_workbench().get...
Create a Python 3 function for handling all commands that take a filename and 0 or more extra arguments.
As a Python code translator, you convert algorithms and pseudocode into Python.
Upload current python script to EV3
Can you generate a brief explanation for the following Python 3 code def upload_current_script(): current_editor = get_workbench().get_editor_notebook().get_current_editor() code = current_editor.get_text_widget().get("1.0", "end") try: filename= current_editor.get_filename() if (not filenam...
As a Python code composer, you craft elegant and concise scripts.
def start_current_script(): """upload current python script to EV3""" current_editor = get_workbench().get_editor_notebook().get_current_editor() code = current_editor.get_text_widget().get("1.0", "end") try: ast.parse(code) #Return None, if script is not saved and user closed file savin...
Can you create a Python 3 function that uploads current python script to EV3
You are a Python code generator, capable of creating scripts from specifications.
downloads log of given. py file from EV3
Can you generate a brief explanation for the following Python 3 code def download_log(currentfile=None): if currentfile == None: return # add ".err.log" if file doesn't end with it! if not currentfile.endswith(".err.log"): currentfile=currentfile + ".err.log" list = get_base_e...
As a Python code composer, you craft elegant and concise scripts.
download log of current python script from EV3
Can you generate a brief explanation for the following Python 3 code def download_log_of_current_script(): try: #Return None, if script is not saved and user closed file saving window, otherwise return file name. src_file = get_workbench().get_current_editor().get_filename(False) if src_fil...
As a python code expert, you are capable of creating scripts from specifications.
def load_plugin(): """Adds EV3 buttons on toolbar and commands under Run and Tools menu. Add EV3 configuration window.""" # Add EV3 configuration window workbench=get_workbench() workbench.set_default("ev3.ip", "192.168.0.1") workbench.set_default("ev3.username", "robot") workbench.set_default(...
Implement a Python 3 function for loading the plugin and adds buttons on toolbar and commands under Run and Tools menu.
As a python code expert, you are capable of creating scripts from specifications.
def init(base_url, username=None, password=None, verify=True): """Initialize ubersmith API module with HTTP request handler.""" handler = RequestHandler(base_url, username, password, verify) set_default_request_handler(handler) return handler
How would you code a function in Python 3 to initialize ubersmith API module with HTTP request handler.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the path to the configuration file or folder depending on the system.
Given the following Python 3 function, write the documentation def getConfigPath(configFileName = None): if configFileName != None: # Returning the path of the configuration file if sys.platform == 'win32': return os.path.expanduser(os.path.join('~\\', 'Deepify', configFileName)) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def getConfiguration(configPath = None): """ Reading the configuration file to look for where the different gates are running. :return: A json containing the information stored in the .cfg file. """ if configPath == None: # If a current.cfg has not been found, creating it by...
Can you create a Python 3 function that reads the configuration file and returns the dictionary containing the information stored in the. cfg file.
You are a Python code generator, capable of creating scripts from specifications.
def new_log_file(logger, suffix, file_type='tcl'): """ Create new logger and log file from existing logger. The new logger will be create in the same directory as the existing logger file and will be named as the existing log file with the requested suffix. :param logger: existing logger :param su...
Write a Python 3 function for creating a new logger and log file from an existing logger.
As a python code expert, you are capable of creating scripts from specifications.
def process_request(self, method, data=None): """Process request over HTTP to ubersmith instance. method: Ubersmith API method string data: dict of method arguments """ # make sure requested method is valid self._validate_request_method(method) # attemp...
Create a Python 3 function to process a request over HTTP to the Ubersmith instance.
As a python code expert, you are capable of creating scripts from specifications.
def dumps(self, indent=1): """ Returns nested string representation of the dictionary (like json.dumps). :param indent: indentation level. """ str_keys_dict = OrderedDict({str(k): v for k, v in self.items()}) for k, v in str_keys_dict.items(): if isinstance(v, dict)...
Create a Python 3 function for returning a nested string representation of the dictionary.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_objects_by_type(self, *types): """ Returned objects stored in memory (without re-reading them from the TGN). Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. ...
Can you implement a function in Python 3 that returns the objects of the specified types in the TGN object store.
As a Python code translator, you convert algorithms and pseudocode into Python.
get_object_by_type - Gets the first child of the requested object types.
Given the following Python 3 function, write the documentation def get_object_by_type(self, *types): children = self.get_objects_by_type(*types) return children[0] if any(children) else None
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_objects_by_type_in_subtree(self, *types): """ :param types: requested object types. :return: all children of the specified types. """ typed_objects = self.get_objects_by_type(*types) for child in self.objects.values(): typed_objects += child.get_objec...
How would you implement a function in Python 3 that gets all objects of the specified types in the tree.
You are a Python code generator, capable of creating scripts from specifications.