code stringlengths 1 18.2k |
|---|
def p_SingleType_any(p): """SingleType : any TypeSuffixStartingWithArray""" p[0] = helper.unwrapTypeSuffix(model.SimpleType( model.SimpleType.ANY), p[2]) |
def p_UnionType(p): """UnionType : "(" UnionMemberType or UnionMemberType UnionMemberTypes ")" """ t = [p[2]] + [p[4]] + p[5] p[0] = model.UnionType(t=t) |
def p_UnionMemberType_anyType(p): """UnionMemberType : any "[" "]" TypeSuffix""" p[0] = helper.unwrapTypeSuffix(model.Array(t=model.SimpleType( type=model.SimpleType.ANY)), p[4]) |
def p_NonAnyType_domString(p): """NonAnyType : DOMString TypeSuffix""" p[0] = helper.unwrapTypeSuffix(model.SimpleType( type=model.SimpleType.DOMSTRING), p[2]) |
def p_NonAnyType_interface(p): """NonAnyType : IDENTIFIER TypeSuffix""" p[0] = helper.unwrapTypeSuffix(model.InterfaceType(name=p[1]), p[2]) |
def p_NonAnyType_object(p): """NonAnyType : object TypeSuffix""" p[0] = helper.unwrapTypeSuffix(model.SimpleType( type=model.SimpleType.OBJECT), p[2]) |
def p_NonAnyType(p): """NonAnyType : Date TypeSuffix""" p[0] = helper.unwrapTypeSuffix(model.SimpleType( type=model.SimpleType.DATE), p[2]) |
def p_ExtendedAttributeNoArgs(p): """ExtendedAttributeNoArgs : IDENTIFIER""" p[0] = model.ExtendedAttribute( value=model.ExtendedAttributeValue(name=p[1])) |
def p_ExtendedAttributeArgList(p): """ExtendedAttributeArgList : IDENTIFIER "(" ArgumentList ")" """ p[0] = model.ExtendedAttribute( value=model.ExtendedAttributeValue(name=p[1], arguments=p[3])) |
def p_ExtendedAttributeIdent(p): """ExtendedAttributeIdent : IDENTIFIER "=" IDENTIFIER""" p[0] = model.ExtendedAttribute( name=p[1], value=model.ExtendedAttributeValue(name=p[3])) |
def p_ExtendedAttributeNamedArgList(p): """ExtendedAttributeNamedArgList : IDENTIFIER "=" IDENTIFIER "(" ArgumentList ")" """ p[0] = model.ExtendedAttribute( name=p[1], value=model.ExtendedAttributeValue(name=p[3], arguments=p[5])) |
def declare_selfvars(self): """ A block to declare self variables """ # # Object desc block # self.str_desc = '' self.__name__ = "pfdicom" self.str_version = '1.6.0' # Directory and filenames self.str_workingDir = '' self.str_inputDir = '' self.str_inputFile = '' self.str_extension = '' self.str_outputFileStem = '' sel... |
self.d_dicom = {} # values directly from dcm ojbect self.d_dicomSimple = {} # formatted dict convert # Convenience vars self.tic_start = None self.dp = None self.log = None self.tic_start = 0.0 self.pp = pprint.PrettyPrinter(indent=4) self.verbosityLevel = 1 |
def env_check(self, *args, **kwargs): """ This method provides a common entry for any checks on the environment (input / output dirs, etc) """ b_status = True str_error = '' if not len(self.str_outputDir): b_status = False str_error = 'output directory not specified.' self.dp.qprint(str_error, comms = 'error') error.wa... |
def tagsInString_process(self, d_DICOM, astr, *args, **kwargs): """ This method substitutes DICOM tags that are '%'-tagged in a string template with the actual tag lookup. For example, an output filename that is specified as the following string: %PatientAge-%PatientID-output.txt will be parsed to 006Y-4412364-ouptut.t... |
noise etc from each tag l_funcTag = [] # a function/tag list l_args = [] # the 'args' of the function func = '' # the function to apply tag = '' # the tag in the funcTag combo chars = '' # the number of resultant chars from func # result to use if '%' in astr: l_tags = astr.split('%')[1:] # Find which tags (mangled) in... |
'md5' in func: str_replace = hashlib.md5(str_replace.encode('utf-8')).hexdigest() l_funcTag = func.split('_')[1:] func = l_funcTag[0] l_args = func.split('|') if len(l_args) > 1: chars = l_args[1] str_replace = str_replace[0:int(chars)] astr = astr.replace('_%s_' % func, '') if 'strmsk' in func: l_funcTag = func.split(... |
astr.replace('%' + tag, str_replace) return { 'status': True, 'b_tagsFound': b_tagsFound, 'str_result': astr } |
def DICOMfile_read(self, *args, **kwargs): """ Read a DICOM file and perform some initial parsing of tags. NB! For thread safety, class member variables should not be assigned since other threads might override/change these variables in mid- flight! """ b_status = False l_tags = [] l_tagsToUse = [] d_tagsInString = {} ... |
on DICOM file: %s" % (threading.currentThread().getName(),str_localFile)) # self.dp.qprint("%s: Loading: %s" % (threading.currentThread().getName(),str_file)) try: # self.dcm = dicom.read_file(str_file) d_DICOM['dcm'] = dicom.read_file(str_file) b_status = True except: self.dp.qprint('In directory: %s' % os.getcwd(), c... |
def filelist_prune(self, at_data, *args, **kwargs): """ Given a list of files, possibly prune list by extension. """ b_status = True l_file = [] str_path = at_data[0] al_file = at_data[1] if len(self.str_extension): al_file = [x for x in al_file if self.str_extension in x] if len(al_file): al_file.sort() l_file = al_fi... |
def ret_dump(self, d_ret, **kwargs): """ JSON print results to console (or caller) """ b_print = True for k, v in kwargs.items(): if k == 'JSONprint': b_print = bool(v) if b_print: print( json.dumps( d_ret, indent = 4, sort_keys = True ) ) |
def run(self, *args, **kwargs): """ The run method is merely a thin shim down to the embedded pftree run method. """ b_status = True d_pftreeRun = {} d_inputAnalysis = {} d_env = self.env_check() b_timerStart = False self.dp.qprint( "\tStarting pfdicom run... (please be patient while running)", level = 1 ) for k, v in ... |
pfdicom run...', level = 1) return d_ret |
def reconnect_to_broker(self): """Connect or reconnect to broker""" #print "CONNECT !" if self.client: self.poller.unregister(self.client) self.client.close() self.client = self.ctx.socket(zmq.DEALER) self.client.linger = 0 self.client.connect(self.broker) self.poller.register(self.client, zmq.POLLIN) if self.verbose: ... |
def send(self, service, request): """Send request to broker """ if not isinstance(request, list): request = [request] # Prefix request with protocol frames # Frame 0: empty (REQ emulation) # Frame 1: "MDPCxy" (six bytes, MDP/Client x.y) # Frame 2: Service name (printable string) request = ['', MDP.C_CLIENT, service] + ... |
def recv(self): """Returns the reply message or None if there was no reply.""" try: items = self.poller.poll(self.timeout) except KeyboardInterrupt: return # interrupted if items: # if we got a reply, process it msg = self.client.recv_multipart() self.close() if self.verbose: logging.info("I: received reply:") dump(msg... |
async def get_identity_document(client: Client, current_block: dict, pubkey: str) -> Identity: """ Get the identity document of the pubkey :param client: Client to connect to the api :param current_block: Current block data :param pubkey: UID/Public key :rtype: Identity """ # Here we request for the path wot/lookup/pub... |
def get_certification_document(current_block: dict, self_cert_document: Identity, from_pubkey: str) -> Certification: """ Create and return a Certification document :param current_block: Current block data :param self_cert_document: Identity document :param from_pubkey: Pubkey of the certifier :rtype: Certification """... |
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # pr... |
we request for the path wot/certify response = await client(bma.wot.certify, certification.signed_raw()) if response.status == 200: print(await response.text()) else: print("Error while publishing certification: {0}".format(await response.text())) # Close client aiohttp session await client.close() |
def sign(self, keys): """ Sign the current document. Warning : current signatures will be replaced with the new ones. """ key = keys[0] signed = self.raw()[-2:] signing = base64.b64encode(key.signature(bytes(signed, 'ascii'))) self.signatures = [signing.decode("ascii")] |
def _dfs_cycle_detect(graph, node, path, visited_nodes): """ search graph for cycle using DFS continuing from node path contains the list of visited nodes currently on the stack visited_nodes is the set of already visited nodes :param graph: :param node: :param path: :param visited_nodes: :return: """ visited_nodes.add... |
def detect_cycle(graph): """ search the given directed graph for cycles returns None if the given graph is cycle free otherwise it returns a path through the graph that contains a cycle :param graph: :return: """ visited_nodes = set() for node in list(graph): if node not in visited_nodes: cycle = _dfs_cycle_detect(grap... |
def topsort(graph): """ For the given graph, returns a list of nodes in topological order In py3 the behaviour of this function differs from py2, the resulting order will change with every execution in py3 while in py2 the order stays the same :param graph: :return: """ count = defaultdict(int) for feature, node in gra... |
def main(): cmd = sys.argv cmd.pop(0) """ parse arguments and make go """ parser = argparse.ArgumentParser() parser.add_argument( '-s', '--src', help='source folder to watch', default='.', dest='src', metavar='folder' ) parser.add_argument( '-d', '--dest', help='source folder to watch', default=None, dest='dest', metav... |
def init_sources(path): """ initializes array of groups and their associated js files """ for f in dir_list(path): if(os.path.splitext(f)[1][1:] == config.source_ext): print "Source file discovered: %s" % (f) script = Script(f) if (script.filename not in config.sources.keys()): config.sources[script.path] = script pars... |
def start_scanner(path): """ watch for file events in the supplied path """ try: observer = Observer() observer.start() stream = Stream(file_modified, path, file_events=True) observer.schedule(stream) print "Watching for changes. Press Ctrl-C to stop." while 1: pass except (KeyboardInterrupt, OSError, IOError): observe... |
def file_modified(event): """ react to file events """ if re.match(config.file_regex,event.name) or (event.name in config.sources.keys()): print "Change detected to: %s" % (event.name) config.stack = [] script = config.sources[event.name] if script.extension == config.source_ext: parse.parse_file(script) else: parse.pa... |
def iter_tuple_from_csv(path, iterator=False, chunksize=None, skiprows=None, nrows=None, **kwargs): """A high performance, low memory usage csv file row iterator function. :param path: csv file path. :param iterator: :param chunksize: :param skiprows: :param nrows: :yield tuple: **中文文档** 对dataframe进行tuple风格的高性能行遍历。 对用p... |
def index_row_dict_from_csv(path, index_col=None, iterator=False, chunksize=None, skiprows=None, nrows=None, use_ordered_dict=True, **kwargs): """Read the csv into a dictionary. The key is it's index, the value is the dictionary form of the row. :param path: csv file path. :param index_col: None or str, the column that... |
pd.read_csv(path, index_col=index_col, **kwargs): for ind, tp in zip(df.index, itertuple(df)): table[ind] = dict(zip(columns, tp)) else: df = pd.read_csv(path, index_col=index_col, **kwargs) for ind, tp in zip(df.index, itertuple(df)): table[ind] = dict(zip(columns, tp)) return table |
def native_path(path): # pragma: no cover """ Always return a native path, that is unicode on Python 3 and bytestring on Python 2. Taken `from Django <http://bit.ly/1r3gogZ>`_. """ if PY2 and not isinstance(path, bytes): return path.encode(fs_encoding) return path |
def select_field(col, field_or_fields, filters=None): """Select single or multiple fields. :params field_or_fields: str or list of str :returns headers: headers :return data: list of row **中文文档** - 在选择单列时, 返回的是 str, list. - 在选择多列时, 返回的是 str list, list of list. 返回单列或多列的数据。 """ fields = _preprocess_field_or_fields(field_... |
def select_distinct_field(col, field_or_fields, filters=None): """Select distinct value or combination of values of single or multiple fields. :params fields: str or list of str. :return data: list of list. **中文文档** 选择多列中出现过的所有可能的排列组合。 """ fields = _preprocess_field_or_fields(field_or_fields) if filters is None: filter... |
def random_sample(col, n=5, filters=None): """Randomly select n document from query result set. If no query specified, then from entire collection. **中文文档** 从collection中随机选择 ``n`` 个样本。 """ pipeline = list() if filters is not None: pipeline.append({"$match": filters}) pipeline.append({"$sample": {"size": n}}) return lis... |
def _before_flush_handler(session, _flush_context, _instances): """Update version ID for all dirty, modified rows""" dialect = get_dialect(session) for row in session.dirty: if isinstance(row, SavageModelMixin) and is_modified(row, dialect): # Update row version_id row.update_version_id() |
def _after_flush_handler(session, _flush_context): """Archive all new/updated/deleted data""" dialect = get_dialect(session) handlers = [ (_versioned_delete, session.deleted), (_versioned_insert, session.new), (_versioned_update, session.dirty), ] for handler, rows in handlers: # TODO: Bulk archive insert statements fo... |
def opticalModel(sim, ver: xarray.DataArray, obsAlt_km: float, zenithang: float): """ ver: Nalt x Nwavelength """ assert isinstance(ver, xarray.DataArray) # %% get system optical transmission T optT = getSystemT(ver.wavelength_nm, sim.bg3fn, sim.windowfn, sim.qefn, obsAlt_km, zenithang) # %% first multiply VER by T, TH... |
def register_text_type(content_type, default_encoding, dumper, loader): """ Register handling for a text-based content type. :param str content_type: content type to register the hooks for :param str default_encoding: encoding to use if none is present in the request :param dumper: called to decode a string into a dict... |
def register_binary_type(content_type, dumper, loader): """ Register handling for a binary content type. :param str content_type: content type to register the hooks for :param dumper: called to decode bytes into a dictionary. Calling convention: ``dumper(obj_dict) -> bytes``. :param loader: called to encode a dictionar... |
def unpack_bytes(self, obj_bytes, encoding=None): """Unpack a byte stream into a dictionary.""" assert self.bytes_to_dict or self.string_to_dict encoding = encoding or self.default_encoding LOGGER.debug('%r decoding %d bytes with encoding of %s', self, len(obj_bytes), encoding) if self.bytes_to_dict: return escape.recu... |
def pack_bytes(self, obj_dict, encoding=None): """Pack a dictionary into a byte stream.""" assert self.dict_to_bytes or self.dict_to_string encoding = encoding or self.default_encoding or 'utf-8' LOGGER.debug('%r encoding dict with encoding %s', self, encoding) if self.dict_to_bytes: return None, self.dict_to_bytes(obj... |
def get_request_body(self): """ Decodes the request body and returns it. :return: the decoded request body as a :class:`dict` instance. :raises: :class:`tornado.web.HTTPError` if the body cannot be decoded (415) or if decoding fails (400) """ if self._request_body is None: content_type_str = self.request.headers.get( '... |
def send_response(self, response_dict): """ Encode a response according to the request. :param dict response_dict: the response to send :raises: :class:`tornado.web.HTTPError` if no acceptable content type exists This method will encode `response_dict` using the most appropriate encoder based on the :mailheader:`Accept... |
%s', handler, charset) encoding, response_bytes = handler.pack_bytes(response_dict, encoding=charset) if encoding: # don't overwrite the value in _content_types copied = datastructures.ContentType(selected.content_type, selected.content_subtype, selected.parameters) copied.parameters['charset'] = encoding selected = co... |
def archive_query_interval(self, _from, to): ''' :param _from: Start of interval (int) (inclusive) :param to: End of interval (int) (exclusive) :raises: IOError ''' with self.session as session: table = self.tables.archive try: results = session.query(table)\ .filter(table.dateTime >= _from)\ .filter(table.dateTime < t... |
def archive_insert_data(self, data_dump): ''' :param data: Archive table data :type data: list[archive] :raises: IOError ''' with self.session as session: try: data = [self.tables.archive(**entry) for entry in data_dump] session.add_all(data) session.commit() except SQLAlchemyError as exc: session.rollback() print_exc(... |
def read_config(): """ Read a config file from ``$HOME/.profrc`` We expect a file of the following form [DEFAULT] Baseurl = https://your-prof-instance Login = username """ filename = path.join(path.expanduser('~'), '.profrc') config = configparser.ConfigParser() config.read(filename) if 'baseurl' not in config['DEFAULT... |
def set_sessid(sessid): """ Save this current sessid in ``$HOME/.profrc`` """ filename = path.join(path.expanduser('~'), '.profrc') config = configparser.ConfigParser() config.read(filename) config.set('DEFAULT', 'Session', sessid) with open(filename, 'w') as configfile: print("write a new sessid") config.write(configf... |
def run_command(command): """ Utility function for run command with subprocess. Return a tuple, with return code and if python >= 2.7 command's output or None if python <= 2.6 """ try: check_ouput = getattr( subprocess, 'check_output', subprocess.check_call) result = check_ouput(command, stderr=subprocess.STDOUT, shell... |
def parse_env(config_schema, env): """Parse the values from a given environment against a given config schema Args: config_schema: A dict which maps the variable name to a Schema object that describes the requested value. env: A dict which represents the value of each variable in the environment. """ try: return { key:... |
def parse(self, key, value): """Parse the environment value for a given key against the schema. Args: key: The name of the environment variable. value: The value to be parsed. """ if value is not None: try: return self._parser(value) except Exception: raise ParsingError("Error parsing {}".format(key)) elif self._defaul... |
def write_json_to_temp_file(data): """Writes JSON data to a temporary file and returns the path to it""" fp = tempfile.NamedTemporaryFile(delete=False) fp.write(json.dumps(data).encode('utf-8')) fp.close() return fp.name |
def mock_lockfile_update(path): """ This is a mock update. In place of this, you might simply shell out to a command like `yarn upgrade`. """ updated_lockfile_contents = { 'package1': '1.2.0' } with open(path, 'w+') as f: f.write(json.dumps(updated_lockfile_contents, indent=4)) return updated_lockfile_contents |
def print_settings_example(): """ You can use settings to get additional information from the user via their dependencies.io configuration file. Settings will be automatically injected as env variables with the "SETTING_" prefix. All settings will be passed as strings. More complex types will be json encoded. You shoul... |
def otsu(fpath): """ Returns value of otsu threshold for an image """ img = imread(fpath, as_grey=True) thresh = skimage.filter.threshold_otsu(img) return thresh |
def move_to(name): """ Path to image folders """ datapath = path.join(path.dirname(path.realpath(__file__)), path.pardir) datapath = path.join(datapath, '../gzoo_data', 'images', name) print path.normpath(datapath) return path.normpath(datapath) |
def labels(): """ Path to labels file """ datapath = path.join(path.dirname(path.realpath(__file__)), path.pardir) datapath = path.join(datapath, '../gzoo_data', 'train_solution.csv') return path.normpath(datapath) |
def Feature_Engineering(DataFrame,train): """ Extracts important features and writes them in usable form Deletes features of little importance :param DataFrame: This is the file name of a csv file we wish to convert into a usable DataFrame. :param train: This is training set corresponding to our csv file. Should be of ... |
DataFrame["Cabin"].apply(lambda x: 0 if type(x) == float else 1) cabins=DataFrame['Cabin'].apply(lambda x: str(x)[0]) cabin_mapping={'A':3,'B':5,'C':5,'D':4,'E':4,'F':3,'G':2,'T':1,'n':10} for k,v in cabin_mapping.items(): cabins[cabins==k]=v DataFrame['Cabin']=cabins del DataFrame['Parch'] del DataFrame['SibSp'] del D... |
def Create_Random_Forest(train): """ Fits Random Forest to training set. :param train: This is the file name of a csv file we wish to have fitted to a Random Forest, does not need to have features already extracted. :returns: Returns sklearn.ensemble.Random_Forest_Classifier fitted to training set. """ trainDF=pd.read_... |
def Produce_Predictions(FileName,train,test): """ Produces predictions for testing set, based off of training set. :param FileName: This is the csv file name we wish to have our predictions exported to. :param train: This is the file name of a csv file that will be the training set. :param test: This is the file name o... |
def _make_json_result(code, message="", results=None): """ An utility method to prepare a JSON result string, usable by the SignalReceiver :param code: A HTTP Code :param message: An associated message """ return code, json.dumps({'code': code, 'message': message, 'results': results}) |
def temp_file_context(raw_dump_path, logger=None): """this contextmanager implements conditionally deleting a pathname at the end of a context if the pathname indicates that it is a temp file by having the word 'TEMPORARY' embedded in it.""" try: yield raw_dump_path finally: if 'TEMPORARY' in raw_dump_path: try: os.unl... |
async def memberships(client: Client, search: str) -> dict: """ GET list of Membership documents for UID/Public key :param client: Client to connect to the api :param search: UID/Public key :return: """ return await client.get(MODULE + '/memberships/%s' % search, schema=MEMBERSHIPS_SCHEMA) |
async def membership(client: Client, membership_signed_raw: str) -> ClientResponse: """ POST a Membership document :param client: Client to connect to the api :param membership_signed_raw: Membership signed raw document :return: """ return await client.post(MODULE + '/membership', {'membership': membership_signed_raw},... |
async def block(client: Client, number: int = 0, block_raw: str = None, signature: str = None) -> Union[dict, ClientResponse]: """ GET/POST a block from/to the blockchain :param client: Client to connect to the api :param number: Block number to get :param block_raw: Block document to post :param signature: Signature o... |
async def blocks(client: Client, count: int, start: int) -> list: """ GET list of blocks from the blockchain :param client: Client to connect to the api :param count: Number of blocks :param start: First block number :return: """ assert type(count) is int assert type(start) is int return await client.get(MODULE + '/blo... |
async def hardship(client: Client, pubkey: str) -> dict: """ GET hardship level for given member's public key for writing next block :param client: Client to connect to the api :param pubkey: Public key of the member :return: """ return await client.get(MODULE + '/hardship/%s' % pubkey, schema=HARDSHIP_SCHEMA) |
def block_uid(value: Union[str, BlockUID, None]) -> BlockUID: """ Convert value to BlockUID instance :param value: Value to convert :return: """ if isinstance(value, BlockUID): return value elif isinstance(value, str): return BlockUID.from_str(value) elif value is None: return BlockUID.empty() else: raise TypeError("Ca... |
def from_str(cls: Type[BlockUIDType], blockid: str) -> BlockUIDType: """ :param blockid: The block id """ data = BlockUID.re_block_uid.match(blockid) if data is None: raise MalformedDocumentError("BlockUID") try: number = int(data.group(1)) except AttributeError: raise MalformedDocumentError("BlockUID") try: sha_hash =... |
def make_heartbeat(port, path, peer_uid, node_uid, app_id): """ Prepares the heart beat UDP packet Format : Little endian * Kind of beat (1 byte) * Herald HTTP server port (2 bytes) * Herald HTTP servlet path length (2 bytes) * Herald HTTP servlet path (variable, UTF-8) * Peer UID length (2 bytes) * Peer UID (variable,... |
packet = struct.pack("<BBH", PACKET_FORMAT_VERSION, PACKET_TYPE_HEARTBEAT, port) for string in (path, peer_uid, node_uid, app_id): # Strings... string_bytes = to_bytes(string) packet += struct.pack("<H", len(string_bytes)) packet += string_bytes return packet |
def make_lastbeat(peer_uid, app_id): """ Prepares the last beat UDP packet (when the peer is going away) Format : Little endian * Kind of beat (1 byte) * Peer UID length (2 bytes) * Peer UID (variable, UTF-8) * Application ID length (2 bytes) * Application ID (variable, UTF-8) :param peer_uid: Peer UID :param app_id: A... |
def start(self): """ Starts listening to the socket :return: True if the socket has been created """ # Create the multicast socket (update the group) self._socket, self._group = create_multicast_socket(self._group, self._port) # Start the listening thread self._stop_event.clear() self._thread = threading.Thread( target... |
def stop(self): """ Stops listening to the socket """ # Stop the loop self._stop_event.set() # Join the thread self._thread.join() self._thread = None # Close the socket close_multicast_socket(self._socket, self._group) |
def _handle_heartbeat(self, sender, data): """ Handles a raw heart beat :param sender: Sender (address, port) tuple :param data: Raw packet data """ # Format of packet parsed, data = self._unpack("<B", data) format = parsed[0] if format == PACKET_FORMAT_VERSION: # Kind of beat parsed, data = self._unpack("<B", data) ki... |
uid, node_uid, app_id, sender[0], port, path) except Exception as ex: _logger.exception("Error handling heart beat: %s", ex) |
def _unpack(self, fmt, data): """ Calls struct.unpack(). Returns a tuple containing the result tuple and the subset of data containing the unread content. :param fmt: The format of data :param data: Data to unpack :return: A tuple (result tuple, unread_data) """ size = struct.calcsize(fmt) read, unread = data[:size], d... |
def _unpack_string(self, data): """ Unpacks the next string from the given data :param data: A datagram, starting at a string size :return: A (string, unread_data) tuple """ # Get the size of the string result, data = self._unpack("<H", data) size = result[0] # Read it string_bytes = data[:size] # Convert it return to_... |
def __read(self): """ Reads packets from the socket """ # Set the socket as non-blocking self._socket.setblocking(0) while not self._stop_event.is_set(): # Watch for content ready = select.select([self._socket], [], [], 1) if ready[0]: # Socket is ready data, sender = self._socket.recvfrom(1024) try: self._handle_heart... |
def get_log_config(component, handlers, level='DEBUG', path='/var/log/vfine/'): """Return a log config for django project.""" config = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s][%(threadName)s]' + '[%(name)s.%(funcName)s():%(lineno)d] %(messag... |
'.error.log', 'maxBytes': 1024 * 1024 * 100, 'backupCount': 5, 'formatter': 'standard', }, 'console': { 'level': level, 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': handlers, 'level': 'INFO', 'propagate': False }, 'django.request': { 'handlers': handlers, 'level':... |
def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove t... |
os.path.exists(self.baseFilename): os.rename(self.baseFilename, dfn) with open(self.baseFilename, 'a'): pass if self.backupCount > 0: # find the oldest log file and delete it # s = glob.glob(self.baseFilename + ".20*") # if len(s) > self.backupCount: # s.sort() # os.remove(s[0]) for s in self.getFilesToDelete(): os.rem... |
bows out before next rollover, so we need to add an hour newRolloverAt = newRolloverAt + 3600 self.rolloverAt = newRolloverAt |
def format(self, record): """Format a message from a record object.""" record = ColoredRecord(record) record.log_color = self.color(self.log_colors, record.levelname) # Set secondary log colors if self.secondary_log_colors: for name, log_colors in self.secondary_log_colors.items(): color = self.color(log_colors, record... |
def get_console_logger(): """ just for kkconst demos """ global __console_logger if __console_logger: return __console_logger logger = logging.getLogger("kkconst") logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(l... |
def _load_referenced_schemes_from_list(the_list, val, a_scheme, a_property): """ takes the referenced files and loads them returns the updated schema :param the_list: :param val: :param a_scheme: :param a_property: :return: """ scheme = copy.copy(a_scheme) new_list = [] if isinstance(the_list, list): for an_item in the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.