output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Converts the given ECI coordinates to Geodetic coordinates at the given GMST and with .
Can you generate the documentation for the following Python 3 function def eci2geodetic (x, y, z, gmst=None, ellipsoid=None): if gmst is None: gmst = dmc.toGMST() if ellipsoid is None: ellipsoid = WGS84 a = WGS84.a b = WGS84.b f = WGS84.f r = math.sqrt((x * x) + (y * y)) e2 = (2 * ...
As a Python code composer, you craft elegant and concise scripts.
def process(self, input_data, topic=None): """ Invokes each handler in sequence. Publishes final output data. Params: input_data: message received by stream topic: name of plugin or stream message received from, if applicable ...
Implement a Python 3 function for processing the input data and publishes the final output data.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns True if the workflow is valid.
Make a summary of the following Python 3 code def valid_workflow(self): for ix, handler in enumerate(self.handlers[:-1]): next_input_type = self.handlers[ix + 1].input_type if (handler.output_type is not None and next_input_type is not None): if handl...
As a python code expert, you are capable of creating scripts from specifications.
Compresses the input file and stores the result in output_filename.
Can you generate a brief explanation for the following Python 3 code def compress (input_filename, output_filename=None, verbose=False): input_size = 0 output_size = 0 if output_filename is None: output_filename = input_fillename + '.ait-zlib' try: stream = open(input_filename , 'rb') output ...
As a python code expert, you are capable of creating scripts from specifications.
def hexdump (bytes, addr=None, preamble=None, printfunc=None, stepsize=16): """hexdump(bytes[, addr[, preamble[, printfunc[, stepsize=16]]]]) Outputs bytes in hexdump format lines similar to the following (here preamble='Bank1', stepsize=8, and len(bytes) == 15):: Bank1: 0xFD020000: 7f45 4c46 0102 0100 ...
Write a Python 3 script for dumping bytes in hexdump format.
As a Python code composer, you craft elegant and concise scripts.
def hexdumpLine (bytes, length=None): """hexdumpLine(bytes[, length]) Returns a single hexdump formatted line for bytes. If length is greater than len(bytes), the line will be padded with ASCII space characters to indicate no byte data is present. Used by hexdump(). """ line = "" if length is None: ...
Create a Python 3 function for returning a single hexdump formatted line for the given bytes.
You are a Python code architect, reviewing and designing scalable and efficient code
def parseArgs (argv, defaults): """parseArgs(argv, defaults) -> (dict, list) Parses command-line arguments according to the given defaults. For every key in defaults, an argument of the form --key=value will be parsed. Numeric arguments are converted from strings with errors reported via ait.core.log.error...
Create a Python 3 function for parsing command - line arguments according to the given defaults.
As a Python code composer, you craft elegant and concise scripts.
Print the usage statement at the top of a Python program.
Here you have a function in Python 3, explain what it does def usage (exit=False): stream = open(sys.argv[0]) for line in stream.readlines(): if line.startswith("##"): print line.replace("##", ""), stream.close() if exit: sys.exit(2)
You are a Python code generator, capable of creating scripts from specifications.
def getip(): """ getip() Returns the IP address of the computer. Helpful for those hosts that might sit behind gateways and report a hostname that is a little strange (I'm looking at you oco3-sim1). """ return [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_...
How would you implement a function in Python 3 that gets the IP address of the computer.
As a Python code analyst, you investigate and solve complex coding mysteries
def arg_parse(arguments, description=None): """ arg_parse() Parses the arguments using argparse. Returns a Namespace object. The arguments dictionary should match the argparse expected data structure: .. code-block::python arguments = { '--port': { 'type' : int, 'default' : 307...
Write a Python 3 script for parsing the arguments using argparse and returns a Namespace object.
As a Python code composer, you craft elegant and concise scripts.
def extant_file(file): """ 'Type' for argparse - checks that file exists but does not open. """ if not os.path.exists(file): # Argparse uses the ArgumentTypeError to give a rejection message like: # error: argument input: file does not exist raise argparse.ArgumentTypeError("{0} ...
Can you write a function in Python 3 where it types for argparse - checks that file exists but does not open.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the dot product of this Point with another.
Given the following Python 3 function, write the documentation def dot (self, other): if self.z: return (self.x * other.x) + (self.y * other.y) + (self.z * other.z) else: return (self.x * other.x) + (self.y * other.y)
As a Python code composer, you craft elegant and concise scripts.
Returns the slope of the current node.
How would you explain what the following Python 3 function does def slope (self): return (self.p.y - self.q.y) / (self.p.x - self.q.x)
As a Python code composer, you craft elegant and concise scripts.
def intersect (self, line): """intersect (line) -> Point | None Returns the intersection point of this line segment with another. If this line segment and the other line segment are conincident, the first point on this line segment is returned. If the line segments do not intersect, None is return...
How would you code a function in Python 3 to intersect two line segments.
You are a Python code generator, capable of creating scripts from specifications.
intersect - Returns the point at which the line segment and Plane intersect or None if the line segment and Plane intersect does not intersect.
Here you have a function in Python 3, explain what it does def intersect (self, line): eps = 1e-8 d = (line.q - line.p) dn = d.dot(self.n) point = None if abs(dn) >= eps: mu = self.n.dot(self.p - line.p) / dn if mu >= 0 and mu <= 1: point = line.p + mu * d ...
You are a Python code architect, reviewing and designing scalable and efficient code
area - Returns the area of this Polygon.
Can you generate a brief explanation for the following Python 3 code def area (self): area = 0.0 for segment in self.segments(): area += ((segment.p.x * segment.q.y) - (segment.q.x * segment.p.y))/2 return area
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the bounding rectangle for this Polygon.
Here you have a function in Python 3, explain what it does def bounds (self): if self._dirty: min = self.vertices[0].copy() max = self.vertices[0].copy() for point in self.vertices[1:]: if point.x < min.x: min.x = point.x if point.y < min.y: min.y = point.y if point.x > max...
You are a Python code generator, capable of creating scripts from specifications.
Returns the center point of this Polygon.
Given the following Python 3 function, write the documentation def center (self): Cx = 0.0 Cy = 0.0 denom = 6.0 * self.area() for segment in self.segments(): x = (segment.p.x + segment.q.x) y = (segment.p.y + segment.q.y) xy = (segment.p.x * segment.q.y) - (segment.q.x * se...
You are a Python code analyst, evaluating scripts for potential improvements.
def contains (self, p): """Returns True if point is contained inside this Polygon, False otherwise. This method uses the Ray Casting algorithm. Examples: >>> p = Polygon() >>> p.vertices = [Point(1, 1), Point(1, -1), Point(-1, -1), Point(-1, 1)] >>> p.contains( Point(0, 0) ) True...
Create a Python 3 function to return True if point is contained inside this Polygon False otherwise.
As a Python code translator, you convert algorithms and pseudocode into Python.
def segments (self): """Return the Line segments that comprise this Polygon.""" for n in xrange(len(self.vertices) - 1): yield Line(self.vertices[n], self.vertices[n + 1]) yield Line(self.vertices[-1], self.vertices[0])
Implement a Python 3 function for returning the Line segments that comprise this Polygon.
As a Python code composer, you craft elegant and concise scripts.
def contains (self, point): """contains(point) -> True | False Returns True if point is contained inside this Rectangle, False otherwise. Examples: >>> r = Rect( Point(-1, -1), Point(1, 1) ) >>> r.contains( Point(0, 0) ) True >>> r.contains( Point(2, 3) ) False """ return...
Implement a function in Python 3 to return True if point is contained inside this Rectangle False otherwise.
You are a Python code analyst, evaluating scripts for potential improvements.
def segments (self): """segments () -> [ Line, Line, Line, Line ] Return a list of Line segments that comprise this Rectangle. """ ul = self.ul lr = self.lr ur = Point(lr.x, ul.y) ll = Point(ul.x, lr.y) return [ Line(ul, ur), Line(ur, lr), Line(lr, ll), Line(ll, ul) ]
Write a Python 3 script for returning a list of Line segments that comprise this Rectangle.
As a Python code composer, you craft elegant and concise scripts.
def format_message(self, evr_hist_data): ''' Format EVR message with EVR data Given a byte array of EVR data, format the EVR's message attribute printf format strings and split the byte array into appropriately sized chunks. Supports most format strings containing length and type ...
How would you code a function in Python 3 to format an EVR message with the given byte array of EVR data.
As a python code expert, you are capable of creating scripts from specifications.
Parses a sequence header line containing name value pairs.
Can you generate the documentation for the following Python 3 function def _parseHeader (self, line, lineno, log): if line.startswith('#') and line.find(':') > 0: tokens = [ t.strip().lower() for t in line[1:].split(":", 1) ] name = tokens[0] pos = SeqPos(line, lineno) if name in self....
As a Python code composer, you craft elegant and concise scripts.
def append (self, cmd, delay=0.000, attrs=None): """Adds a new command with a relative time delay to this sequence.""" self.lines.append( SeqCmd(cmd, delay, attrs) )
Implement a Python 3 function for adding a new command to this sequence.
You are a Python code generator, capable of creating scripts from specifications.
Prints a text representation of this sequence to the given stream.
Given the following Python 3 function, write the documentation def printText (self, stream=None): if stream is None: stream = sys.stdout stream.write('# seqid : %u\n' % self.seqid ) stream.write('# version : %u\n' % self.version ) stream.write('# crc32 : 0x%04x\n' % self...
As a Python code translator, you convert algorithms and pseudocode into Python.
def read (self, filename=None): """Reads a command sequence from the given filename (defaults to self.pathname). """ if filename is None: filename = self.pathname stream = open(filename, 'rb') magic = struct.unpack('>H', stream.read(2))[0] stream.close() if magic == Seq.Magic: ...
Write a Python 3 function that can read a command sequence from the given filename.
As a Python code analyst, you investigate and solve complex coding mysteries
Reads a binary command sequence from the given file.
How would you explain what the following Python 3 function does def readBinary (self, filename=None): if filename is None: filename = self.pathname stream = open(filename, 'rb') magic = struct.unpack('>H', stream.read(2))[0] self.crc32 = struct.unpack('>I', stream.read(4))[0] s...
You are a Python code generator, capable of creating scripts from specifications.
def readText (self, filename=None): """Reads a text command sequence from the given filename (defaults to self.pathname). """ if filename is None: filename = self.pathname self.header = { } inBody = False with open(filename, 'rt') as stream: for (lineno, line) in enumerate...
Can you write a function in Python 3 where it reads a text command sequence from the given file.
You are a Python code generator, capable of creating scripts from specifications.
Returns True if this Sequence is valid False otherwise.
Explain what the following Python 3 code does def validate (self): if not os.path.isfile(self.pathname): self.message.append('Filename "%s" does not exist.') else: try: with open(self.pathname, 'r') as stream: pass except IOError: self.messages.append('Could not open ...
As a python code expert, you are capable of creating scripts from specifications.
def writeBinary (self, filename=None): """Writes a binary representation of this sequence to the given filename (defaults to self.binpath). """ if filename is None: filename = self.binpath with open(filename, 'wb') as output: # Magic Number output.write( struct.pack('>H', Seq.Magi...
How would you implement a function in Python 3 that writes a binary representation of this sequence to the given filename.
As a Python code translator, you convert algorithms and pseudocode into Python.
def writeText (self, filename=None): """Writes a text representation of this sequence to the given filename (defaults to self.txtpath). """ if filename is None: filename = self.txtpath with open(filename, 'wt') as output: self.printText(output)
Write a Python 3 function that can write a text representation of this sequence to the given filename.
You are a Python code analyst, evaluating scripts for potential improvements.
def decode (cls, bytes, cmddict): """Decodes a sequence command from an array of bytes, according to the given command dictionary, and returns a new SeqCmd. """ attrs = SeqCmdAttrs.decode(bytes[0:1]) delay = SeqDelay .decode(bytes[1:4]) cmd = cmddict .decode(bytes[4:] ) return cls(cmd...
Create a Python 3 function for decoding a sequence command from an array of bytes according to the given command dictionary and returns a new SeqCmd.
As a Python code translator, you convert algorithms and pseudocode into Python.
Encodes this SeqCmd to binary and returns a bytearray.
Can you generate a brief explanation for the following Python 3 code def encode (self): return self.attrs.encode() + self.delay.encode() + self.cmd.encode()
You are a Python code architect, reviewing and designing scalable and efficient code
def parse (cls, line, lineno, log, cmddict): """Parses the sequence command from a line of text, according to the given command dictionary, and returns a new SeqCmd. """ delay = SeqDelay .parse(line, lineno, log, cmddict) attrs = SeqCmdAttrs.parse(line, lineno, log, cmddict) comment = SeqC...
Create a Python 3 function to parse the sequence command from a line of text according to the given command dictionary and returns a new SeqCmd.
As a Python code analyst, you investigate and solve complex coding mysteries
Decodes sequence command attributes from an array of bytes and returns a new SeqCmdAttrs object.
Make a summary of the following Python 3 code def decode (cls, bytes, cmddict=None): byte = struct.unpack('B', bytes)[0] self = cls() defval = self.default for bit, name, value0, value1, default in SeqCmdAttrs.Table: mask = 1 << bit bitset = mask & byte defset = mask & defval ...
As a Python code analyst, you investigate and solve complex coding mysteries
Encodes this SeqCmdAttrs to binary and returns a bytearray.
How would you explain what the following Python 3 function does def encode (self): byte = self.default for bit, name, value0, value1, default in SeqCmdAttrs.Table: if name in self.attrs: value = self.attrs[name] byte = setBit(byte, bit, value == value1) return struct.pack('B', byte)
You are a Python code analyst, evaluating scripts for potential improvements.
def parse (cls, line, lineno, log, cmddict=None): """Parses a SeqCmdAttrs from a line of text and returns it or None. Warning and error messages are logged via the SeqMsgLog log. """ start = line.find('{') stop = line.find('}') pos = SeqPos(line, lineno, start + 1, stop) result = cls(N...
Implement a Python 3 function for parsing a SeqCmdAttrs from a line of text and returns it or None.
You are a Python code generator, capable of creating scripts from specifications.
def decode (cls, bytes, cmddict=None): """Decodes a sequence delay from an array of bytes, according to the given command dictionary, and returns a new SeqDelay. """ delay_s = struct.unpack('>H', bytes[0:2])[0] delay_ms = struct.unpack('B' , bytes[2:3])[0] return cls(delay_s + (delay_ms / 255.0...
Create a Python 3 function to decode a sequence delay from an array of bytes according to the given command dictionary and returns a new SeqDelay.
As a python code expert, you are capable of creating scripts from specifications.
Encodes this SeqDelay to a binary bytearray.
Can you tell what is the following Python 3 function doing def encode (self): delay_s = int( math.floor(self.delay) ) delay_ms = int( (self.delay - delay_s) * 255.0 ) return struct.pack('>H', delay_s) + struct.pack('B', delay_ms)
You are a Python code generator, capable of creating scripts from specifications.
def parse (cls, line, lineno, log, cmddict=None): """Parses the SeqDelay from a line of text. Warning and error messages are logged via the SeqMsgLog log. """ delay = -1 token = line.split()[0] start = line.find(token) pos = SeqPos(line, lineno, start + 1, start + len(token)) try: ...
Implement a Python 3 function for parsing the SeqDelay from a line of text.
You are a Python code generator, capable of creating scripts from specifications.
Parses the SeqMetaCmd from a line of text.
Can you generate a brief explanation for the following Python 3 code def parse (cls, line, lineno, log, cmddict=None): start = line.find('%') pos = SeqPos(line, lineno, start + 1, len(line)) result = None if start >= 0: result = cls(line[start:], pos) return result
As a Python code analyst, you investigate and solve complex coding mysteries
Logs an error message pertaining to the given SeqPos.
Can you generate the documentation for the following Python 3 function def error (self, msg, pos=None): self.log(msg, 'error: ' + self.location(pos))
You are a Python code analyst, evaluating scripts for potential improvements.
Formats the location of the given SeqPos as a string
How would you explain what the following Python 3 function does def location (self, pos): result = '' if self.filename: result += self.filename + ':' if pos: result += str(pos) return result
You are a Python code analyst, evaluating scripts for potential improvements.
Logs a message with an optional prefix.
Can you generate the documentation for the following Python 3 function def log (self, msg, prefix=None): if prefix: if not prefix.strip().endswith(':'): prefix += ': ' msg = prefix + msg self.messages.append(msg)
As a Python code composer, you craft elegant and concise scripts.
Logs a warning message pertaining to the given SeqAtom.
Explain what the following Python 3 code does def warning (self, msg, pos=None): self.log(msg, 'warning: ' + self.location(pos))
As a Python code composer, you craft elegant and concise scripts.
def expandConfigPaths (config, prefix=None, datetime=None, pathvars=None, parameter_key='', *keys): """Updates all relative configuration paths in dictionary config, which contain a key in keys, by prepending prefix. If keys is omitted, it defaults to 'directory', 'file', 'filename', 'path', 'pathname'...
Create a Python 3 function for expanding all relative configuration paths in dictionary config by prepending prefix.
As a Python code analyst, you investigate and solve complex coding mysteries
def replaceVariables(path, datetime=None, pathvars=None): """Return absolute path with path variables replaced as applicable""" if datetime is None: datetime = time.gmtime() # if path variables are not given, set as empty list if pathvars is None: pathvars = [ ] # create an init p...
How would you code a function in Python 3 to return absolute path with path variables replaced as applicable
You are a Python code generator, capable of creating scripts from specifications.
Flattens the dictionary d by merging keys in order such that later keys take precedence over earlier keys.
Can you generate the documentation for the following Python 3 function def flatten (d, *keys): flat = { } for k in keys: flat = merge(flat, d.pop(k, { })) return flat
You are a Python code analyst, evaluating scripts for potential improvements.
Loads either the given YAML configuration file or YAML data.
Make a summary of the following Python 3 code def loadYAML (filename=None, data=None): config = None try: if filename: data = open(filename, 'rt') config = yaml.load(data) if type(data) is file: data.close() except IOError, e: msg = 'Could not read ...
As a Python code composer, you craft elegant and concise scripts.
Internal method. Used by __getattr__ and __getitem__.
How would you explain what the following Python 3 function does def _getattr_ (self, name): value = self._config.get(name) if type(value) is dict: value = AitConfig(self._filename, config=value) return value
As a Python code analyst, you investigate and solve complex coding mysteries
def _datapaths(self): """Returns a simple key-value map for easy access to data paths""" paths = { } try: data = self._config['data'] for k in data: paths[k] = data[k]['path'] except KeyError as e: raise AitConfigMissing(e.message) ...
Implement a function in Python 3 to return a simple key - value map for easy access to data paths
You are a Python code analyst, evaluating scripts for potential improvements.
def reload (self, filename=None, data=None): """Reloads the a AIT configuration. The AIT configuration is automatically loaded when the AIT package is first imported. To replace the configuration, call reload() (defaults to the current config.filename) or reload(new_filename). ...
How would you code a function in Python 3 to reload the AIT configuration.
As a Python code composer, you craft elegant and concise scripts.
Returns the attribute value of AitConfig. name or default if name does not exist.
Make a summary of the following Python 3 code def get (self, name, default=None): if name in self: return self[name] config = self parts = name.split('.') heads = parts[:-1] tail = parts[-1] for part in heads: if part in config and type(confi...
As a python code expert, you are capable of creating scripts from specifications.
Adds path variables to the pathvars map property
Can you tell what is the following Python 3 function doing def addPathVariables(self, pathvars): if type(pathvars) is dict: self._pathvars = merge(self._pathvars, pathvars)
As a Python code composer, you craft elegant and concise scripts.
Returns the PrimitiveType for the given name or None if no such PrimitiveType exists.
How would you explain what the following Python 3 function does def getPDT(typename): if typename not in PrimitiveTypeMap and typename.startswith("S"): PrimitiveTypeMap[typename] = PrimitiveType(typename) return PrimitiveTypeMap.get(typename, None)
As a Python code analyst, you investigate and solve complex coding mysteries
def get(typename): """get(typename) -> PrimitiveType or ComplexType Returns the PrimitiveType or ComplexType for typename or None. """ dt = getPDT(typename) or getCDT(typename) if dt is None: pdt, nelems = ArrayType.parse(typename) if pdt and nelems: dt = ArrayType(pdt,...
Can you create a Python 3 function that gets - Returns the PrimitiveType or ComplexType for typename or None if no primitive type exists for typename or None if no complex type exists for typename.
As a Python code analyst, you investigate and solve complex coding mysteries
def decode(self, bytes, raw=False): """decode(bytearray, raw=False) -> value Decodes the given bytearray according to this PrimitiveType definition. NOTE: The parameter ``raw`` is present to adhere to the ``decode()`` inteface, but has no effect for PrimitiveType defini...
Write a Python 3 script for decoding the given bytearray according to this PrimitiveType definition.
You are a Python code generator, capable of creating scripts from specifications.
Validate the given value according to this PrimitiveType Taxonomy definition.
Given the following Python 3 function, write the documentation def validate(self, value, messages=None, prefix=None): valid = False def log(msg): if messages is not None: if prefix is not None: tok = msg.split() msg = prefix + ' ' + to...
As a Python code analyst, you investigate and solve complex coding mysteries
Raise TypeError or IndexError if index is out of range for the number of elements in this array respectively.
Given the following Python 3 function, write the documentation def _assertIndex(self, index): if type(index) is not int: raise TypeError('list indices must be integers') if index < 0 or index >= self.nelems: raise IndexError('list index out of range')
As a Python code composer, you craft elegant and concise scripts.
decode returns the value1... valueN
Make a summary of the following Python 3 code def decode(self, bytes, index=None, raw=False): if index is None: index = slice(0, self.nelems) if type(index) is slice: step = 1 if index.step is None else index.step indices = xrange(index.start, index.stop, step) ...
As a Python code composer, you craft elegant and concise scripts.
def decodeElem(self, bytes, index, raw=False): """Decodes a single element at array[index] from a sequence bytes that contain data for the entire array. """ self._assertIndex(index) start = index * self.type.nbytes stop = start + self.type.nbytes if stop > len(b...
Write a Python 3 function that can decode a single element at array [ index ] from a sequence bytes that contains data for the entire array.
As a Python code analyst, you investigate and solve complex coding mysteries
Encodes the given values to a sequence of bytes according to thisArray s underlying element type.
Here you have a function in Python 3, explain what it does def encode(self, *args): if len(args) != self.nelems: msg = 'ArrayType %s encode() requires %d values, but received %d.' raise ValueError(msg % (self.name, self.nelems, len(args))) return bytearray().join(self.type.encod...
You are a Python code generator, capable of creating scripts from specifications.
def parse (name): """parse(name) -> [typename | None, nelems | None] Parses an ArrayType name to return the element type name and number of elements, e.g.: >>> ArrayType.parse('MSB_U16[32]') ['MSB_U16', 32] If typename cannot be determined, None is returned. ...
Create a Python 3 function to parse an array name to return the element type name and number of elements e. g. MSB_U16 [ 32 ]
You are a Python code generator, capable of creating scripts from specifications.
PrimitiveType base for the ComplexType
Here you have a function in Python 3, explain what it does def cmddict(self): if self._cmddict is None: self._cmddict = cmd.getDefaultDict() return self._cmddict
As a python code expert, you are capable of creating scripts from specifications.
Encodes the given value according to this PrimitiveType definition.
Given the following Python 3 function, write the documentation def encode(self, value): opcode = self.cmddict[value].opcode return super(CmdType, self).encode(opcode)
As a Python code translator, you convert algorithms and pseudocode into Python.
Decode the given bytearray and returns the corresponding command version.
Explain what the following Python 3 code does def decode(self, bytes, raw=False): opcode = super(CmdType, self).decode(bytes) result = None if raw: result = opcode elif opcode in self.cmddict.opcodes: result = self.cmddict.opcodes[opcode] else: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def evrs(self): """Getter EVRs dictionary""" if self._evrs is None: import ait.core.evr as evr self._evrs = evr.getDefaultDict() return self._evrs
Implement a function in Python 3 to get the EVRs dictionary
You are a Python code analyst, evaluating scripts for potential improvements.
Encodes the given value to a bytearray according to this Complex Type definition.
Here you have a function in Python 3, explain what it does def encode(self, value): e = self.evrs.get(value, None) if not e: log.error(str(value) + " not found as EVR. Cannot encode.") return None else: return super(EVRType, self).encode(e.code)
As a Python code analyst, you investigate and solve complex coding mysteries
decode returns the value of the given bytearray according to the corresponding EVR Definition s EVR code.
How would you explain what the following Python 3 function does def decode(self, bytes, raw=False): code = super(EVRType, self).decode(bytes) result = None if raw: result = code elif code in self.evrs.codes: result = self.evrs.codes[code] else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Decode the given bytearray and returns the number of nanos.
Make a summary of the following Python 3 code def decode(self, bytes, raw=False): result = super(Time8Type, self).decode(bytes) if not raw: result /= 256.0 return result
You are a Python code architect, reviewing and designing scalable and efficient code
Encodes the given value to a bytearray according to thisComplexType definition.
Can you tell what is the following Python 3 function doing def encode(self, value): if type(value) is not datetime.datetime: raise TypeError('encode() argument must be a Python datetime') return super(Time32Type, self).encode( dmc.toGPSSeconds(value) )
You are a Python code generator, capable of creating scripts from specifications.
Decode the given bytearray containing the elapsed time in seconds since the GPS epoch and returns the corresponding value Python : class : datetime.
Can you tell what is the following Python 3 function doing def decode(self, bytes, raw=False): sec = super(Time32Type, self).decode(bytes) return sec if raw else dmc.toLocalTime(sec)
You are a Python code generator, capable of creating scripts from specifications.
Encodes the given value to a bytearray according to thisInternationalType definition.
Explain what the following Python 3 code does def encode(self, value): if type(value) is not datetime.datetime: raise TypeError('encode() argument must be a Python datetime') coarse = Time32Type().encode(value) fine = Time8Type() .encode(value.microsecond / 1e6) return co...
You are a Python code analyst, evaluating scripts for potential improvements.
def decode(self, bytes, raw=False): """decode(bytearray, raw=False) -> value Decodes the given bytearray containing the elapsed time in seconds plus 1/256 subseconds since the GPS epoch returns the corresponding Python :class:`datetime`. If the optional parameter ``raw`` is ``T...
How would you implement a function in Python 3 that decodes the given bytearray containing the elapsed time in seconds plus 1 / 256 subseconds since the GPS epoch returns the corresponding Python datetime.
As a Python code analyst, you investigate and solve complex coding mysteries
Load and process the YAML file
Can you generate the documentation for the following Python 3 function def load(self, ymlfile=None): if ymlfile is not None: self.ymlfile = ymlfile try: # If yaml should be 'cleaned' of document references if self._clean: self.data = self.process(self...
As a Python code translator, you convert algorithms and pseudocode into Python.
def process(self, ymlfile): """Cleans out all document tags from the YAML file to make it JSON-friendly to work with the JSON Schema. """ output = "" try: # Need a list of line numbers where the documents resides # Used for finding/displaying errors ...
How would you code a function in Python 3 to clean out all document tags from the YAML file to make it JSON - friendly.
You are a Python code generator, capable of creating scripts from specifications.
def load(self, schemafile=None): """Load and process the schema file""" if schemafile is not None: self._schemafile = schemafile try: self.data = json.load(open(self._schemafile)) except (IOError, ValueError), e: msg = "Could not load schema file '" +...
How would you implement a function in Python 3 that loads and process the schema file
You are a Python code analyst, evaluating scripts for potential improvements.
def pretty(self, start, end, e, messages=None): """Pretties up the output error message so it is readable and designates where the error came from""" log.debug("Displaying document from lines '%i' to '%i'", start, end) errorlist = [] if len(e.context) > 0: errorlist...
Write a Python 3 script for printing out a pretty representation of the error.
You are a Python code generator, capable of creating scripts from specifications.
Perform validation with processed YAML and Schema
Can you tell what is the following Python 3 function doing def schema_val(self, messages=None): "Perform validation with processed YAML and Schema" self._ymlproc = YAMLProcessor(self._ymlfile) self._schemaproc = SchemaProcessor(self._schemafile) valid = True log.debug("BEGIN: Sc...
You are a Python code analyst, evaluating scripts for potential improvements.
Validates the contents of the Command Dictionary and returns a dictionary of the contents for each of the fields .
How would you explain what the following Python 3 function does def content_val(self, ymldata=None, messages=None): self._ymlproc = YAMLProcessor(self._ymlfile, False) # Turn off the YAML Processor log.debug("BEGIN: Content-based validation of Command dictionary") if ymldata is not Non...
You are a Python code generator, capable of creating scripts from specifications.
Validates the Telemetry Dictionary definitions
Explain what the following Python 3 code does def validate(self, ymldata=None, messages=None): schema_val = self.schema_val(messages) if len(messages) == 0: content_val = self.content_val(ymldata, messages) return schema_val and content_val
As a python code expert, you are capable of creating scripts from specifications.
Validates the contents of the Telemetry Dictionary to ensure that each of the fields in the Telemetry Dictionary meets specific criteria regarding the expected types byte ranges etc.
Here you have a function in Python 3, explain what it does def content_val(self, ymldata=None, messages=None): # Turn off the YAML Processor log.debug("BEGIN: Content-based validation of Telemetry dictionary") if ymldata is not None: tlmdict = ymldata else: tlmdi...
You are a Python code architect, reviewing and designing scalable and efficient code
Performs the uniqueness check against the value list of the attribute in the rule objects
Can you generate a brief explanation for the following Python 3 code def check(self, defn): val = getattr(defn, self.attr) if val is not None and val in self.val_list: self.messages.append(self.msg % str(val)) # TODO self.messages.append("TBD location message") self.v...
As a python code expert, you are capable of creating scripts from specifications.
Performs isinstance check for the definitions data type.
Can you generate the documentation for the following Python 3 function def check(self, defn): allowedTypes = dtype.PrimitiveType, dtype.ArrayType if not isinstance(defn.type, allowedTypes): self.messages.append(self.msg % str(defn.name)) # self.messages.append("TBD location messa...
You are a Python code generator, capable of creating scripts from specifications.
Checks if the number of bytes defined in the object definition matches the number of bytes defined in the object definition.
Given the following Python 3 function, write the documentation def check(self, defn, msg=None): if isinstance(defn.type, dtype.PrimitiveType): # Check the nbytes designated in the YAML match the PDT nbytes = defn.type.nbytes defnbytes = defn.slice().stop - defn.slice().start ...
You are a Python code architect, reviewing and designing scalable and efficient code
def check(self, defn, msg=None): """Uses the definitions slice() method to determine its start/stop range. """ # Check enum does not contain boolean keys if (defn.slice().start != self.prevstop): self.messages.append(self.msg % str(defn.name)) # TODO self....
Can you write a function in Python 3 where it checks if the given definition is valid.
As a python code expert, you are capable of creating scripts from specifications.
Waits for a given condition to be True.
Can you tell what is the following Python 3 function doing def wait (cond, msg=None, _timeout=10, _raiseException=True): status = False delay = 0.25 elapsed = 0 if msg is None and type(cond) is str: msg = cond if type(cond) is bool: if cond: log.warn('Boolean passed ...
As a python code expert, you are capable of creating scripts from specifications.
def send (self, command, *args, **kwargs): """Creates, validates, and sends the given command as a UDP packet to the destination (host, port) specified when this CmdAPI was created. Returns True if the command was created, valid, and sent, False otherwise. """ st...
Can you create a Python 3 function that creates validates and sends the given command as a UDP packet to the destination host and port specified when thisCmdAPI was created. Returns True if the command was created valid and sent False otherwise.
As a python code expert, you are capable of creating scripts from specifications.
Removes and returns the first item from this GeventDeque.
How would you explain what the following Python 3 function does def _pop(self, block=True, timeout=None, left=False): item = None timer = None deque = self._deque empty = IndexError('pop from an empty deque') if block is False: if len(self._deque) > 0: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Add item to the right side of the GeventDeque.
Can you tell what is the following Python 3 function doing def append(self, item): self._deque.append(item) self.notEmpty.set()
You are a Python code generator, capable of creating scripts from specifications.
Add item to the left side of the GeventDeque.
Explain what the following Python 3 code does def appendleft(self, item): self._deque.appendleft(item) self.notEmpty.set()
You are a Python code generator, capable of creating scripts from specifications.
Extend the right side of this GeventDeque by appending the elements from the iterable argument.
Can you tell what is the following Python 3 function doing def extend(self, iterable): self._deque.extend(iterable) if len(self._deque) > 0: self.notEmpty.set()
As a Python code composer, you craft elegant and concise scripts.
Extend the left side of this GeventDeque by appending elements from the iterable argument.
How would you explain what the following Python 3 function does def extendleft(self, iterable): self._deque.extendleft(iterable) if len(self._deque) > 0: self.notEmpty.set()
You are a Python code generator, capable of creating scripts from specifications.
Remove and return an item from the right side of the GeventDeque.
Can you tell what is the following Python 3 function doing def popleft(self, block=True, timeout=None): return self._pop(block, timeout, left=True)
As a Python code translator, you convert algorithms and pseudocode into Python.
Send a confirm prompt to the GUI
Explain what the following Python 3 code does def confirm(self, msg, _timeout=-1): ''' Send a confirm prompt to the GUI Arguments: msg (string): The message to display to the user. _timeout (int): The optional amount of time for which the...
As a Python code analyst, you investigate and solve complex coding mysteries
def msgBox(self, promptType, _timeout=-1, **options): ''' Send a user prompt request to the GUI Arguments: promptType (string): The prompt type to send to the GUI. Currently the only type supported is 'confirm'. _timeout (int): Th...
Implement a function in Python 3 to send a user prompt request to the GUI.
You are a Python code analyst, evaluating scripts for potential improvements.
Subscribes all streams to all plugins and inputs.
Here you have a function in Python 3, explain what it does def _subscribe_all(self): for stream in (self.inbound_streams + self.outbound_streams): for input_ in stream.inputs: if not type(input_) is int and input_ is not None: self._subscribe(stream, input_) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def addLocalHandlers (logger): """Adds logging handlers to logger to log to the following local resources: 1. The terminal 2. localhost:514 (i.e. syslogd) 3. localhost:2514 (i.e. the AIT GUI syslog-like handler) """ termlog = logging.StreamHandler() termlog.setFormatter(...
Write a Python 3 function for adding logging handlers to the logger to log to the local system.
As a Python code analyst, you investigate and solve complex coding mysteries
def addRemoteHandlers (logger): """Adds logging handlers to logger to remotely log to: ait.config.logging.hostname:514 (i.e. syslogd) If not set or hostname cannot be resolved, this method has no effect. """ try: hostname = ait.config.logging.hostname # Do not "remote" lo...
How would you code a function in Python 3 to add logging handlers to logger to remotely log to a specific host.
You are a Python code generator, capable of creating scripts from specifications.