text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def last(self, limit=1, **kwargs): """ Returns the last `limit` records inserted in the model's table in the replica database. Rows are sorted by ``created_at``. """
return self.collection_instance( self.db_adapter( db_name=kwargs.get('db'), role=kwargs.get('role', 'replica') ).select( where='created_at IS NOT NULL', order='created_at DESC', limit=limit ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by(self, values={}, **kwargs): """ Returns a single record matching the criteria in ``values`` found in the model's table in the replica database. :param values: Criteria to find the record. :type values: dict :returns: an instance of the model. """
try: return self( **self.select( where=values, limit=1, **kwargs ).to_dict(orient='records')[0] ) except IndexError: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replica_lag(self, **kwargs): """ Returns the current replication lag in seconds between the master and replica databases. :returns: float """
if not self._use_replica(): return 0 try: kwargs['stack'] = self.stack_mark(inspect.stack()) sql = "select EXTRACT(EPOCH FROM NOW() - pg_last_xact_replay_timestamp()) AS replication_lag" return self.collection_instance( self.db_adapter().raw_query( sql=sql, **kwargs ) ).squeeze() except: return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_schema(self): """ Returns the table schema. :returns: dict """
if self.__dict__.get('_table_schema') is None: self._table_schema = None table_schema = {} for row in self.query_schema(): name, default, dtype = self.db().lexicon.column_info(row) if isinstance(default, str): json_matches = re.findall(r"^\'(.*)\'::jsonb$", default) if len(json_matches) > 0: default = json.loads(json_matches[0]) if name == self.primary_key: default = None table_schema[name] = {'default': default, 'type': dtype} if len(table_schema): self._table_schema = table_schema return self._table_schema
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_vertex_buffer(self, fd, material, length): """ Load vertex data from file. Can be overriden to reduce data copy :param fd: file object :param material: The material these vertices belong to :param length: Byte length of the vertex data """
material.vertices = struct.unpack('{}f'.format(length // 4), fd.read(length))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_vertex_buffers(self): """Load each vertex buffer into each material"""
fd = gzip.open(cache_name(self.file_name), 'rb') for buff in self.meta.vertex_buffers: mat = self.wavefront.materials.get(buff['material']) if not mat: mat = Material(name=buff['material'], is_default=True) self.wavefront.materials[mat.name] = mat mat.vertex_format = buff['vertex_format'] self.load_vertex_buffer(fd, mat, buff['byte_length']) fd.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_mtllibs(self): """Load mtl files"""
for mtllib in self.meta.mtllibs: try: materials = self.material_parser_cls( os.path.join(self.path, mtllib), encoding=self.encoding, strict=self.strict).materials except IOError: raise IOError("Failed to load mtl file:".format(os.path.join(self.path, mtllib))) for name, material in materials.items(): self.wavefront.materials[name] = material
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_vertex_buffer(self, material, vertex_format, byte_offset, byte_length): """Add a vertex buffer"""
self._vertex_buffers.append({ "material": material, "vertex_format": vertex_format, "byte_offset": byte_offset, "byte_length": byte_length, })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, path): """Save the metadata as json"""
with open(path, 'w') as fd: fd.write(json.dumps( { "created_at": self._created_at, "version": self._version, "mtllibs": self._mtllibs, "vertex_buffers": self._vertex_buffers, }, indent=2, ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_material(self, new_material): """Determine whether we already have a material of this name."""
for material in self.materials: if material.name == new_material.name: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_material(self, material): """Add a material to the mesh, IF it's not already present."""
if self.has_material(material): return self.materials.append(material)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auto_consume(func): """Decorator for auto consuming lines when leaving the function"""
def inner(*args, **kwargs): func(*args, **kwargs) args[0].consume_line() return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_line_generator(self): """ Creates a generator function yielding lines in the file Should only yield non-empty lines """
if self.file_name.endswith(".gz"): if sys.version_info.major == 3: gz = gzip.open(self.file_name, mode='rt', encoding=self.encoding) else: gz = gzip.open(self.file_name, mode='rt') for line in gz.readlines(): yield line gz.close() else: if sys.version_info.major == 3: # Python 3 native `open` is much faster file = open(self.file_name, mode='r', encoding=self.encoding) else: # Python 2 needs the codecs package to deal with encoding file = codecs.open(self.file_name, mode='r', encoding=self.encoding) for line in file: yield line file.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_line(self): """Read the next line from the line generator and split it"""
self.line = next(self.lines) # Will raise StopIteration when there are no more lines self.values = self.line.split()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self): """ Parse all the lines in the obj file Determines what type of line we are and dispatch appropriately. """
try: # Continues until `next_line()` raises StopIteration # This can trigger here or in parse functions in the subclass while True: # Only advance the parser if the previous line was consumed. # Parse functions reading multiple lines can end up reading one line too far, # so they return without consuming the line and we pick it up here if not self.line: self.next_line() if self.line[0] == '#' or len(self.values) < 2: self.consume_line() continue self.dispatcher.get(self.values[0], self.parse_fallback)() except StopIteration: pass if self.auto_post_parse: self.post_parse()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_fallback(self): """Fallback method when parser doesn't know the statement"""
if self.strict: raise PywavefrontException("Unimplemented OBJ format statement '%s' on line '%s'" % (self.values[0], self.line.rstrip())) else: logger.warning("Unimplemented OBJ format statement '%s' on line '%s'" % (self.values[0], self.line.rstrip()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(instance): """Generic draw function"""
# Draw Wavefront instance if isinstance(instance, Wavefront): draw_materials(instance.materials) # Draw single material elif isinstance(instance, Material): draw_material(instance) # Draw dict of materials elif isinstance(instance, dict): draw_materials(instance) else: raise ValueError("Cannot figure out how to draw: {}".format(instance))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_material(material, face=GL_FRONT_AND_BACK): """Draw a single material"""
if material.gl_floats is None: material.gl_floats = (GLfloat * len(material.vertices))(*material.vertices) material.triangle_count = len(material.vertices) / material.vertex_size vertex_format = VERTEX_FORMATS.get(material.vertex_format) if not vertex_format: raise ValueError("Vertex format {} not supported by pyglet".format(material.vertex_format)) glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) # Fall back to ambient texture if no diffuse texture = material.texture or material.texture_ambient if texture and material.has_uvs: bind_texture(texture) else: glDisable(GL_TEXTURE_2D) glMaterialfv(face, GL_DIFFUSE, gl_light(material.diffuse)) glMaterialfv(face, GL_AMBIENT, gl_light(material.ambient)) glMaterialfv(face, GL_SPECULAR, gl_light(material.specular)) glMaterialfv(face, GL_EMISSION, gl_light(material.emissive)) glMaterialf(face, GL_SHININESS, min(128.0, material.shininess)) glEnable(GL_LIGHT0) if material.has_normals: glEnable(GL_LIGHTING) else: glDisable(GL_LIGHTING) glInterleavedArrays(vertex_format, 0, material.gl_floats) glDrawArrays(GL_TRIANGLES, 0, int(material.triangle_count)) glPopAttrib() glPopClientAttrib()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_texture(texture): """Draw a single texture"""
if not getattr(texture, 'image', None): texture.image = load_image(texture.path) glEnable(texture.image.target) glBindTexture(texture.image.target, texture.image.id) gl.glTexParameterf(texture.image.target, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameterf(texture.image.target, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_image(name): """Load an image"""
image = pyglet.image.load(name).texture verify_dimensions(image) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad_light(self, values): """Accept an array of up to 4 values, and return an array of 4 values. If the input array is less than length 4, pad it with zeroes until it is length 4. Also ensure each value is a float"""
while len(values) < 4: values.append(0.) return list(map(float, values))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_cache(self): """Loads the file using cached data"""
self.cache_loaded = self.cache_loader_cls( self.file_name, self.wavefront, strict=self.strict, create_materials=self.create_materials, encoding=self.encoding, parse=self.parse, ).parse()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_parse(self): """Called after parsing is done"""
if self.cache and not self.cache_loaded: self.cache_writer_cls(self.file_name, self.wavefront).write()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume_normals(self): """Consumes all consecutive texture coordinate lines"""
# The first iteration processes the current/first vn statement. # The loop continues until there are no more vn-statements or StopIteration is raised by generator while True: yield ( float(self.values[1]), float(self.values[2]), float(self.values[3]), ) try: self.next_line() except StopIteration: break if not self.values: break if self.values[0] != "vn": break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume_texture_coordinates(self): """Consume all consecutive texture coordinates"""
# The first iteration processes the current/first vt statement. # The loop continues until there are no more vt-statements or StopIteration is raised by generator while True: yield ( float(self.values[1]), float(self.values[2]), ) try: self.next_line() except StopIteration: break if not self.values: break if self.values[0] != "vt": break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_error(code, context="client"): """ check if the error code is set. If so, a Python log message is generated and an error is raised. """
if code: error = error_text(code, context) logger.error(error) raise Snap7Exception(error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error_text(error, context="client"): """Returns a textual explanation of a given error number :param error: an error integer :param context: server, client or partner :returns: the error string """
assert context in ("client", "server", "partner") logger.debug("error text for %s" % hex(error)) len_ = 1024 text_type = c_char * len_ text = text_type() library = load_library() if context == "client": library.Cli_ErrorText(error, text, len_) elif context == "server": library.Srv_ErrorText(error, text, len_) elif context == "partner": library.Par_ErrorText(error, text, len_) return text.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def event_text(self, event): """Returns a textual explanation of a given event object :param event: an PSrvEvent struct object :returns: the error string """
logger.debug("error text for %s" % hex(event.EvtCode)) len_ = 1024 text_type = ctypes.c_char * len_ text = text_type() error = self.library.Srv_EventText(ctypes.byref(event), ctypes.byref(text), len_) check_error(error) if six.PY2: return text.value else: return text.value.decode('ascii')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self): """ create the server. """
logger.info("creating server") self.library.Srv_Create.restype = snap7.snap7types.S7Object self.pointer = snap7.snap7types.S7Object(self.library.Srv_Create())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_area(self, area_code, index, userdata): """Shares a memory area with the server. That memory block will be visible by the clients. """
size = ctypes.sizeof(userdata) logger.info("registering area %s, index %s, size %s" % (area_code, index, size)) size = ctypes.sizeof(userdata) return self.library.Srv_RegisterArea(self.pointer, area_code, index, ctypes.byref(userdata), size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_events_callback(self, call_back): """Sets the user callback that the Server object has to call when an event is created. """
logger.info("setting event callback") callback_wrap = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(snap7.snap7types.SrvEvent), ctypes.c_int) def wrapper(usrptr, pevent, size): """ Wraps python function into a ctypes function :param usrptr: not used :param pevent: pointer to snap7 event struct :param size: :returns: should return an int """ logger.info("callback event: " + self.event_text(pevent.contents)) call_back(pevent.contents) return 0 self._callback = callback_wrap(wrapper) usrPtr = ctypes.c_void_p() return self.library.Srv_SetEventsCallback(self.pointer, self._callback, usrPtr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_read_events_callback(self, call_back): """ Sets the user callback that the Server object has to call when a Read event is created. :param call_back: a callback function that accepts a pevent argument. """
logger.info("setting read event callback") callback_wrapper = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(snap7.snap7types.SrvEvent), ctypes.c_int) def wrapper(usrptr, pevent, size): """ Wraps python function into a ctypes function :param usrptr: not used :param pevent: pointer to snap7 event struct :param size: :returns: should return an int """ logger.info("callback event: " + self.event_text(pevent.contents)) call_back(pevent.contents) return 0 self._read_callback = callback_wrapper(wrapper) return self.library.Srv_SetReadEventsCallback(self.pointer, self._read_callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_log_callback(self): """Sets a callback that logs the events """
logger.debug("setting up event logger") def log_callback(event): logger.info("callback event: " + self.event_text(event)) self.set_events_callback(log_callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, tcpport=102): """ start the server. """
if tcpport != 102: logger.info("setting server TCP port to %s" % tcpport) self.set_param(snap7.snap7types.LocalPort, tcpport) logger.info("starting server on 0.0.0.0:%s" % tcpport) return self.library.Srv_Start(self.pointer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy(self): """ destroy the server. """
logger.info("destroying server") if self.library: self.library.Srv_Destroy(ctypes.byref(self.pointer))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_status(self): """Reads the server status, the Virtual CPU status and the number of the clients connected. :returns: server status, cpu status, client count """
logger.debug("get server status") server_status = ctypes.c_int() cpu_status = ctypes.c_int() clients_count = ctypes.c_int() error = self.library.Srv_GetStatus(self.pointer, ctypes.byref(server_status), ctypes.byref(cpu_status), ctypes.byref(clients_count)) check_error(error) logger.debug("status server %s cpu %s clients %s" % (server_status.value, cpu_status.value, clients_count.value)) return snap7.snap7types.server_statuses[server_status.value], \ snap7.snap7types.cpu_statuses[cpu_status.value], \ clients_count.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unlock_area(self, code, index): """Unlocks a previously locked shared memory area. """
logger.debug("unlocking area code %s index %s" % (code, index)) return self.library.Srv_UnlockArea(self.pointer, code, index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lock_area(self, code, index): """Locks a shared memory area. """
logger.debug("locking area code %s index %s" % (code, index)) return self.library.Srv_LockArea(self.pointer, code, index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_to(self, ip, tcpport=102): """ start server on a specific interface. """
if tcpport != 102: logger.info("setting server TCP port to %s" % tcpport) self.set_param(snap7.snap7types.LocalPort, tcpport) assert re.match(ipv4, ip), '%s is invalid ipv4' % ip logger.info("starting server to %s:102" % ip) return self.library.Srv_Start(self.pointer, ip)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_mask(self, kind, mask): """Writes the specified filter mask. """
logger.debug("setting mask kind %s to %s" % (kind, mask)) return self.library.Srv_SetMask(self.pointer, kind, mask)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_cpu_status(self, status): """Sets the Virtual CPU status. """
assert status in snap7.snap7types.cpu_statuses, 'unknown cpu state %s' % status logger.debug("setting cpu status to %s" % status) return self.library.Srv_SetCpuStatus(self.pointer, status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_param(self, number): """Reads an internal Server object parameter. """
logger.debug("retreiving param number %s" % number) value = ctypes.c_int() code = self.library.Srv_GetParam(self.pointer, number, ctypes.byref(value)) check_error(code) return value.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mask(self, kind): """Reads the specified filter mask. """
logger.debug("retrieving mask kind %s" % kind) mask = snap7.snap7types.longword() code = self.library.Srv_GetMask(self.pointer, kind, ctypes.byref(mask)) check_error(code) return mask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error_wrap(func): """Parses a s7 error code returned the decorated function."""
def f(*args, **kw): code = func(*args, **kw) check_error(code, context="client") return f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self): """ create a SNAP7 client. """
logger.info("creating snap7 client") self.library.Cli_Create.restype = c_void_p self.pointer = S7Object(self.library.Cli_Create())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy(self): """ destroy a client. """
logger.info("destroying snap7 client") if self.library: return self.library.Cli_Destroy(byref(self.pointer))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cpu_state(self): """ Retrieves CPU state from client """
state = c_int(0) self.library.Cli_GetPlcStatus(self.pointer,byref(state)) try: status_string = cpu_statuses[state.value] except KeyError: status_string = None if not status_string: raise Snap7Exception("The cpu state (%s) is invalid" % state.value) logger.debug("CPU state is %s" % status_string) return status_string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cpu_info(self): """ Retrieves CPU info from client """
info = snap7.snap7types.S7CpuInfo() result = self.library.Cli_GetCpuInfo(self.pointer, byref(info)) check_error(result, context="client") return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, address, rack, slot, tcpport=102): """ Connect to a S7 server. :param address: IP address of server :param rack: rack on server :param slot: slot on server. """
logger.info("connecting to %s:%s rack %s slot %s" % (address, tcpport, rack, slot)) self.set_param(snap7.snap7types.RemotePort, tcpport) return self.library.Cli_ConnectTo( self.pointer, c_char_p(six.b(address)), c_int(rack), c_int(slot))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(self, block_num): """ Uploads a block body from AG :param data: bytearray """
logger.debug("db_upload block_num: %s" % (block_num)) block_type = snap7.snap7types.block_types['DB'] _buffer = buffer_type() size = c_int(sizeof(_buffer)) result = self.library.Cli_Upload(self.pointer, block_type, block_num, byref(_buffer), byref(size)) check_error(result, context="client") logger.info('received %s bytes' % size) return bytearray(_buffer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_get(self, db_number): """Uploads a DB from AG. """
logger.debug("db_get db_number: %s" % db_number) _buffer = buffer_type() result = self.library.Cli_DBGet( self.pointer, db_number, byref(_buffer), byref(c_int(buffer_size))) check_error(result, context="client") return bytearray(_buffer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_area(self, area, dbnumber, start, size): """This is the main function to read data from a PLC. With it you can read DB, Inputs, Outputs, Merkers, Timers and Counters. :param dbnumber: The DB number, only used when area= S7AreaDB :param start: offset to start writing :param size: number of units to read """
assert area in snap7.snap7types.areas.values() wordlen = snap7.snap7types.S7WLByte type_ = snap7.snap7types.wordlen_to_ctypes[wordlen] logger.debug("reading area: %s dbnumber: %s start: %s: amount %s: " "wordlen: %s" % (area, dbnumber, start, size, wordlen)) data = (type_ * size)() result = self.library.Cli_ReadArea(self.pointer, area, dbnumber, start, size, wordlen, byref(data)) check_error(result, context="client") return bytearray(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_multi_vars(self, items): """This function read multiple variables from the PLC. :param items: list of S7DataItem objects :returns: a tuple with the return code and a list of data items """
result = self.library.Cli_ReadMultiVars(self.pointer, byref(items), c_int32(len(items))) check_error(result, context="client") return result, items
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_blocks(self): """Returns the AG blocks amount divided by type. :returns: a snap7.types.BlocksList object. """
logger.debug("listing blocks") blocksList = BlocksList() result = self.library.Cli_ListBlocks(self.pointer, byref(blocksList)) check_error(result, context="client") logger.debug("blocks: %s" % blocksList) return blocksList
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_blocks_of_type(self, blocktype, size): """This function returns the AG list of a specified block type."""
blocktype = snap7.snap7types.block_types.get(blocktype) if not blocktype: raise Snap7Exception("The blocktype parameter was invalid") logger.debug("listing blocks of type: %s size: %s" % (blocktype, size)) if (size == 0): return 0 data = (c_uint16 * size)() count = c_int(size) result = self.library.Cli_ListBlocksOfType( self.pointer, blocktype, byref(data), byref(count)) logger.debug("number of items found: %s" % count) check_error(result, context="client") return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_block_info(self, blocktype, db_number): """Returns the block information for the specified block."""
blocktype = snap7.snap7types.block_types.get(blocktype) if not blocktype: raise Snap7Exception("The blocktype parameter was invalid") logger.debug("retrieving block info for block %s of type %s" % (db_number, blocktype)) data = TS7BlockInfo() result = self.library.Cli_GetAgBlockInfo( self.pointer, blocktype, db_number, byref(data)) check_error(result, context="client") return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_session_password(self, password): """Send the password to the PLC to meet its security level."""
assert len(password) <= 8, 'maximum password length is 8' return self.library.Cli_SetSessionPassword(self.pointer, c_char_p(six.b(password)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_connection_type(self, connection_type): """ Sets the connection resource type, i.e the way in which the Clients connects to a PLC. :param connection_type: 1 for PG, 2 for OP, 3 to 10 for S7 Basic """
result = self.library.Cli_SetConnectionType(self.pointer, c_uint16(connection_type)) if result != 0: raise Snap7Exception("The parameter was invalid")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_connected(self): """ Returns the connection status :returns: a boolean that indicates if connected. """
connected = c_int32() result = self.library.Cli_GetConnected(self.pointer, byref(connected)) check_error(result, context="client") return bool(connected)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_ab_write(self, start, data): """ This is the asynchronous counterpart of Cli_ABWrite. """
wordlen = snap7.snap7types.S7WLByte type_ = snap7.snap7types.wordlen_to_ctypes[wordlen] size = len(data) cdata = (type_ * size).from_buffer_copy(data) logger.debug("ab write: start: %s: size: %s: " % (start, size)) return self.library.Cli_AsABWrite( self.pointer, start, size, byref(cdata))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_db_get(self, db_number): """ This is the asynchronous counterpart of Cli_DBGet. """
logger.debug("db_get db_number: %s" % db_number) _buffer = buffer_type() result = self.library.Cli_AsDBGet(self.pointer, db_number, byref(_buffer), byref(c_int(buffer_size))) check_error(result, context="client") return bytearray(_buffer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_param(self, number): """Reads an internal Client object parameter. """
logger.debug("retreiving param number %s" % number) type_ = param_types[number] value = type_() code = self.library.Cli_GetParam(self.pointer, c_int(number), byref(value)) check_error(code) return value.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_pdu_length(self): """ Returns info about the PDU length. """
logger.info("getting PDU length") requested_ = c_uint16() negotiated_ = c_uint16() code = self.library.Cli_GetPduLength(self.pointer, byref(requested_), byref(negotiated_)) check_error(code) return negotiated_.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_plc_datetime(self): """ Get date and time from PLC. :return: date and time as datetime """
type_ = c_int32 buffer = (type_ * 9)() result = self.library.Cli_GetPlcDateTime(self.pointer, byref(buffer)) check_error(result, context="client") return datetime( year = buffer[5] + 1900, month = buffer[4] + 1, day = buffer[3], hour = buffer[2], minute = buffer[1], second = buffer[0] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_plc_datetime(self, dt): """ Set date and time in PLC :param dt: date and time as datetime """
type_ = c_int32 buffer = (type_ * 9)() buffer[0] = dt.second buffer[1] = dt.minute buffer[2] = dt.hour buffer[3] = dt.day buffer[4] = dt.month - 1 buffer[5] = dt.year - 1900 return self.library.Cli_SetPlcDateTime(self.pointer, byref(buffer))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_db1(): """ Here we read out DB1, all data we is put in the all_data variable and is a bytearray with the raw plc data """
all_data = client.db_get(1) for i in range(400): # items in db row_size = 130 # size of item index = i * row_size offset = index + row_size # end of row in db util.print_row(all_data[index:offset])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_db_row(db, start, size): """ Here you see and example of readying out a part of a DB Args: db (int): The db to use start (int): The index of where to start in db data size (int): The size of the db data to read """
type_ = snap7.snap7types.wordlen_to_ctypes[snap7.snap7types.S7WLByte] data = client.db_read(db, start, type_, size) # print_row(data[:60]) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_db_row(db, start, size, _bytearray): """ Here we replace a piece of data in a db block with new data Args: db (int): The db to use start(int): The start within the db size(int): The size of the data in bytes _butearray (enumerable): The data to put in the db """
client.db_write(db, start, size, _bytearray)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_row(x, row): """ We use db 1, use offset 4, we replace row x. To find the correct start_index we mulitpy by row_size by x and we put the byte array representation of row in the PLC """
row_size = 126 set_db_row(1, 4 + x * row_size, row_size, row._bytearray)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_bool(_bytearray, byte_index, bool_index): """ Get the boolean value from location in bytearray """
index_value = 1 << bool_index byte_value = _bytearray[byte_index] current_value = byte_value & index_value return current_value == index_value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_bool(_bytearray, byte_index, bool_index, value): """ Set boolean value on location in bytearray """
assert value in [0, 1, True, False] current_value = get_bool(_bytearray, byte_index, bool_index) index_value = 1 << bool_index # check if bool already has correct value if current_value == value: return if value: # make sure index_v is IN current byte _bytearray[byte_index] += index_value else: # make sure index_v is NOT in current byte _bytearray[byte_index] -= index_value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_int(bytearray_, byte_index, _int): """ Set value in bytearray to int """
# make sure were dealing with an int _int = int(_int) _bytes = struct.unpack('2B', struct.pack('>h', _int)) bytearray_[byte_index:byte_index + 2] = _bytes return bytearray_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_int(bytearray_, byte_index): """ Get int value from bytearray. int are represented in two bytes """
data = bytearray_[byte_index:byte_index + 2] data[1] = data[1] & 0xff data[0] = data[0] & 0xff packed = struct.pack('2B', *data) value = struct.unpack('>h', packed)[0] return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_real(_bytearray, byte_index, real): """ Set Real value make 4 byte data from real """
real = float(real) real = struct.pack('>f', real) _bytes = struct.unpack('4B', real) for i, b in enumerate(_bytes): _bytearray[byte_index + i] = b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_real(_bytearray, byte_index): """ Get real value. create float from 4 bytes """
x = _bytearray[byte_index:byte_index + 4] real = struct.unpack('>f', struct.pack('4B', *x))[0] return real
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_string(_bytearray, byte_index, value, max_size): """ Set string value :params value: string data :params max_size: max possible string size """
if six.PY2: assert isinstance(value, (str, unicode)) else: assert isinstance(value, str) size = len(value) # FAIL HARD WHEN trying to write too much data into PLC if size > max_size: raise ValueError('size %s > max_size %s %s' % (size, max_size, value)) # set len count on first position _bytearray[byte_index + 1] = len(value) i = 0 # fill array which chr integers for i, c in enumerate(value): _bytearray[byte_index + 2 + i] = ord(c) # fill the rest with empty space for r in range(i + 1, _bytearray[byte_index]): _bytearray[byte_index + 2 + r] = ord(' ')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_string(_bytearray, byte_index, max_size): """ parse string from bytearray """
size = _bytearray[byte_index + 1] if max_size < size: logger.error("the string is to big for the size encountered in specification") logger.error("WRONG SIZED STRING ENCOUNTERED") size = max_size data = map(chr, _bytearray[byte_index + 2:byte_index + 2 + size]) return "".join(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_specification(db_specification): """ Create a db specification derived from a dataview of a db in which the byte layout is specified """
parsed_db_specification = OrderedDict() for line in db_specification.split('\n'): if line and not line.startswith('#'): row = line.split('#')[0] # remove trailing comment index, var_name, _type = row.split() parsed_db_specification[var_name] = (index, _type) return parsed_db_specification
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_bytearray(self): """ return bytearray from self or DB parent """
if isinstance(self._bytearray, DB): return self._bytearray._bytearray return self._bytearray
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export(self): """ export dictionary with values """
data = {} for key in self._specification: data[key] = self[key] return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, client): """ Write current data to db in plc """
assert(isinstance(self._bytearray, DB)) assert(self.row_size >= 0) db_nr = self._bytearray.db_number offset = self.db_offset data = self.get_bytearray()[offset:offset+self.row_size] db_offset = self.db_offset # indicate start of write only area of row! if self.row_offset: data = data[self.row_offset:] db_offset += self.row_offset client.db_write(db_nr, db_offset, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, client): """ read current data of db row from plc """
assert(isinstance(self._bytearray, DB)) assert(self.row_size >= 0) db_nr = self._bytearray.db_number _bytearray = client.db_read(db_nr, self.db_offset, self.row_size) data = self.get_bytearray() # replace data in bytearray for i, b in enumerate(_bytearray): data[i + self.db_offset] = b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self): """ disconnect a client. """
logger.info("disconnecting snap7 client") result = self.library.Cli_Disconnect(self.pointer) check_error(result, context="client") return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_as_b_send_completion(self): """ Checks if the current asynchronous send job was completed and terminates immediately. """
op_result = ctypes.c_int32() result = self.library.Par_CheckAsBSendCompletion(self.pointer, ctypes.byref(op_result)) return_values = { 0: "job complete", 1: "job in progress", -2: "invalid handled supplied", } if result == -2: raise Snap7Exception("The Client parameter was invalid") return return_values[result], op_result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, active=False): """ Creates a Partner and returns its handle, which is the reference that you have to use every time you refer to that Partner. :param active: 0 :returns: a pointer to the partner object """
self.library.Par_Create.restype = snap7.snap7types.S7Object self.pointer = snap7.snap7types.S7Object(self.library.Par_Create(int(active)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy(self): """ Destroy a Partner of given handle. Before destruction the Partner is stopped, all clients disconnected and all shared memory blocks released. """
if self.library: return self.library.Par_Destroy(ctypes.byref(self.pointer))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_last_error(self): """ Returns the last job result. """
error = ctypes.c_int32() result = self.library.Par_GetLastError(self.pointer, ctypes.byref(error)) check_error(result, "partner") return error
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_param(self, number): """ Reads an internal Partner object parameter. """
logger.debug("retreiving param number %s" % number) type_ = snap7.snap7types.param_types[number] value = type_() code = self.library.Par_GetParam(self.pointer, ctypes.c_int(number), ctypes.byref(value)) check_error(code) return value.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_stats(self): """ Returns some statistics. :returns: a tuple containing bytes send, received, send errors, recv errors """
sent = ctypes.c_uint32() recv = ctypes.c_uint32() send_errors = ctypes.c_uint32() recv_errors = ctypes.c_uint32() result = self.library.Par_GetStats(self.pointer, ctypes.byref(sent), ctypes.byref(recv), ctypes.byref(send_errors), ctypes.byref(recv_errors)) check_error(result, "partner") return sent, recv, send_errors, recv_errors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_status(self): """ Returns the Partner status. """
status = ctypes.c_int32() result = self.library.Par_GetStatus(self.pointer, ctypes.byref(status)) check_error(result, "partner") return status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_times(self): """ Returns the last send and recv jobs execution time in milliseconds. """
send_time = ctypes.c_int32() recv_time = ctypes.c_int32() result = self.library.Par_GetTimes(self.pointer, ctypes.byref(send_time), ctypes.byref(recv_time)) check_error(result, "partner") return send_time, recv_time
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_to(self, local_ip, remote_ip, local_tsap, remote_tsap): """ Starts the Partner and binds it to the specified IP address and the IsoTCP port. :param local_ip: PC host IPV4 Address. "0.0.0.0" is the default adapter :param remote_ip: PLC IPV4 Address :param local_tsap: Local TSAP :param remote_tsap: PLC TSAP """
assert re.match(ipv4, local_ip), '%s is invalid ipv4' % local_ip assert re.match(ipv4, remote_ip), '%s is invalid ipv4' % remote_ip logger.info("starting partnering from %s to %s" % (local_ip, remote_ip)) return self.library.Par_StartTo(self.pointer, local_ip, remote_ip, ctypes.c_uint16(local_tsap), ctypes.c_uint16(remote_tsap))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_socket(_socket, session, timeout=1): """Helper function for testing non-blocking mode. This function blocks the calling thread for <timeout> seconds - to be used only for testing purposes. Also available at `ssh2.utils.wait_socket` """
directions = session.block_directions() if directions == 0: return 0 readfds = [_socket] \ if (directions & LIBSSH2_SESSION_BLOCK_INBOUND) else () writefds = [_socket] \ if (directions & LIBSSH2_SESSION_BLOCK_OUTBOUND) else () return select(readfds, writefds, (), timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_slices_to_layers(graphs, interslice_weight=1, slice_attr='slice', vertex_id_attr='id', edge_type_attr='type', weight_attr='weight'): """ Convert time slices to layer graphs. Each graph is considered to represent a time slice. This function simply connects all the consecutive slices (i.e. the slice graph) with an ``interslice_weight``. The further conversion is then delegated to :func:`slices_to_layers`, which also provides further details. See Also -------- :func:`find_partition_temporal` :func:`slices_to_layers` """
G_slices = _ig.Graph.Tree(len(graphs), 1, mode=_ig.TREE_UNDIRECTED) G_slices.es[weight_attr] = interslice_weight G_slices.vs[slice_attr] = graphs return slices_to_layers(G_slices, slice_attr, vertex_id_attr, edge_type_attr, weight_attr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FromPartition(cls, partition, **kwargs): """ Create a new partition from an existing partition. Parameters partition The :class:`~VertexPartition.MutableVertexPartition` to replicate. **kwargs Any remaining keyword arguments will be passed on to the constructor of the new partition. Notes ----- This may for example come in handy when determining the quality of a partition using a different method. Suppose that we already have a partition ``p`` and that we want to determine the Significance of that partition. We can then simply use """
new_partition = cls(partition.graph, partition.membership, **kwargs) return new_partition
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregate_partition(self, membership_partition=None): """ Aggregate the graph according to the current partition and provide a default partition for it. The aggregated graph can then be found as a parameter of the partition ``partition.graph``. Notes ----- This function contrasts to the function ``cluster_graph`` in igraph itself, which also provides the aggregate graph, but we may require setting the appropriate ``resolution_parameter``, ``weights`` and ``node_sizes``. In particular, this function also ensures that the quality defined on the aggregate partition is identical to the quality defined on the original partition. Examples -------- True """
partition_agg = self._FromCPartition(_c_leiden._MutableVertexPartition_aggregate_partition(self._partition)) if (not membership_partition is None): membership = partition_agg.membership for v in self.graph.vs: membership[self.membership[v.index]] = membership_partition.membership[v.index] partition_agg.set_membership(membership) return partition_agg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_node(self,v,new_comm): """ Move node ``v`` to community ``new_comm``. Parameters v Node to move. new_comm Community to move to. Examples -------- """
_c_leiden._MutableVertexPartition_move_node(self._partition, v, new_comm) # Make sure this move is also reflected in the membership vector of the python object self._membership[v] = new_comm self._modularity_dirty = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_coarse_partition(self, partition, coarse_node=None): """ Update current partition according to coarser partition. Parameters partition : :class:`~VertexPartition.MutableVertexPartition` The coarser partition used to update the current partition. coarse_node : list of int The coarser node which represent the current node in the partition. Notes ----- This function is to be used to determine the correct partition for an aggregated graph. In particular, suppose we move nodes and then get an aggregate graph. Now we also move nodes in the aggregate partition Now we improved the quality function of ``aggregate_partition``, but this is not yet reflected in the original ``partition``. We can thus call so that ``partition`` now reflects the changes made to ``aggregate_partition``. The ``coarse_node`` can be used it the ``aggregate_partition`` is not defined based on the membership of this partition. In particular the membership of this partition is defined as follows: If ``coarse_node`` is :obj:`None` it is assumed the coarse node was defined based on the membership of the current partition, so that This can be useful when the aggregate partition is defined on a more refined partition. """
# Read the coarser partition _c_leiden._MutableVertexPartition_from_coarse_partition(self._partition, partition.membership, coarse_node) self._update_internal_membership()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup_tmpdir(dirname): """Removes the given temporary directory if it exists."""
if dirname is not None and os.path.exists(dirname): shutil.rmtree(dirname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dir_unless_exists(*args): """Creates a directory unless it exists already."""
path = os.path.join(*args) if not os.path.isdir(path): os.makedirs(path)