code stringlengths 1 18.2k |
|---|
+= """{version_field} """.format(version_field=AsciiArmor._get_version_field()) # add message comment if specified if message_comment: ascii_armor_block += """{comment_field} """.format(comment_field=AsciiArmor._get_comment_field(message_comment)) # blank line separator ascii_armor_block += '\n' if pubkey: # add encryp... |
def _remove_trailing_spaces(text: str) -> str: """ Remove trailing spaces and tabs :param text: Text to clean up :return: """ clean_text = str() for line in text.splitlines(True): # remove trailing spaces (0x20) and tabs (0x09) clean_text += line.rstrip("\x09\x20") return clean_text |
def _dash_escape_text(text: str) -> str: """ Add dash '-' (0x2D) and space ' ' (0x20) as prefix on each line :param text: Text to dash-escape :return: """ dash_escaped_text = str() for line in text.splitlines(True): # add dash '-' (0x2D) and space ' ' (0x20) as prefix dash_escaped_text += DASH_ESCAPE_PREFIX + line retu... |
def _parse_dash_escaped_line(dash_escaped_line: str) -> str: """ Parse a dash-escaped text line :param dash_escaped_line: Dash escaped text line :return: """ text = str() regex_dash_escape_prefix = compile('^' + DASH_ESCAPE_PREFIX) # if prefixed by a dash escape prefix... if regex_dash_escape_prefix.match(dash_escaped_... |
def _get_signature_block(message: str, signing_key: SigningKey, close_block: bool = True, comment: Optional[str] = None) -> str: """ Return a signature block :param message: Message (not encrypted!) to sign :param signing_key: The libnacl SigningKey instance of the keypair :param close_block: Optional flag to close the... |
def parse(ascii_armor_message: str, signing_key: Optional[SigningKey] = None, sender_pubkeys: Optional[List[str]] = None) -> dict: """ Return a dict with parsed content (decrypted message, signature validation) :: { 'message': { 'fields': {}, 'content': str, }, 'signatures': [ {'pubkey': str, 'valid': bool, fields: {}}... |
ascii_armor_message = ascii_armor_message.strip(" \t\n\r") # init vars parsed_result = { 'message': { 'fields': {}, 'content': '', }, 'signatures': [] } # type: Dict[str, Any] cursor_status = 0 message = '' signatures_index = 0 # parse each line... for line in ascii_armor_message.splitlines(True): # if begin message he... |
is present, the message is encrypted... if 'Version' in parsed_result['message']['fields']: # If keypair instance to decrypt not given... if signing_key is None: # SigningKey keypair is mandatory to decrypt the message... raise PARSER_MISSING_SIGNING_KEY_EXCEPTION # decrypt message with secret key from keypair message ... |
are on a signature fields zone... if cursor_status == ON_SIGNATURE_FIELDS: # parse field m = regex_fields.match(line.strip()) if m: # capture field sig_field_name = m.groups()[0] sig_field_value = m.groups()[1] parsed_result['signatures'][signatures_index]['fields'][sig_field_name] = sig_field_value continue # if blank... |
def _decrypt(ascii_armor_message: str, signing_key: SigningKey) -> str: """ Decrypt a message from ascii armor format :param ascii_armor_message: Utf-8 message :param signing_key: SigningKey instance created from credentials :return: """ data = signing_key.decrypt_seal(base64.b64decode(ascii_armor_message)) return data... |
def render(request, template_name, context=None, content_type=None, status=None, using=None, logs=None): """ Wrapper around Django render method. Can take one or a list of logs and logs the response. No overhead if no logs are passed. """ if logs: obj_logger = ObjectLogger() if not isinstance(logs, list): logs = [logs,... |
def getEntitiesByRegexp(data = None, listRegexp = None, verbosity=1, logFolder="./logs"): ''' Method to obtain entities by Regexp. :param data: text where the entities will be looked for. :param listRegexp: list of selected regular expressions to be looked for. If None was provided, all the available will be chosen ins... |
def scanFolderForRegexp(folder = None, listRegexp = None, recursive = False, verbosity=1, logFolder= "./logs"): ''' [Optionally] recursive method to scan the files in a given folder. :param folder: the folder to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :param recursive: when True, it per... |
onlyfiles: filePath = join(folder,f) logger.debug("Looking for regular expressions in: " + filePath) with open(filePath, "r") as tempF: # reading data foundExpr = getEntitiesByRegexp(data = tempF.read(), listRegexp = listRegexp) logger.debug("Updating the " + str(len(foundExpr)) + " results found on: " + filePath) resu... |
def scanResource(uri = None, listRegexp = None, verbosity=1, logFolder= "./logs"): ''' [Optionally] recursive method to scan the files in a given folder. :param uri: the URI to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :return: a dictionary where the key is the name of the file. ''' i3vis... |
def entify_main(args): ''' Main function. This function is created in this way so as to let other applications make use of the full configuration capabilities of the application. ''' # Recovering the logger # Calling the logger when being imported i3visiotools.logger.setupLogger(loggerName="entify", verbosity=args.verb... |
= args.input_folder, listRegexp= listRegexp, recursive = args.recursive, verbosity=args.verbose, logFolder= args.logfolder) else: results = scanResource(uri = args.web, listRegexp= listRegexp, verbosity=args.verbose, logFolder= args.logfolder) logger.info("Printing the results:\n" + general.dictToJson(results)) if args... |
def grouper_df(df, chunksize): """Evenly divide pd.DataFrame into n rows piece, no filled value if sub dataframe's size smaller than n. :param df: ``pandas.DataFrame`` instance. :param chunksize: number of rows of each small DataFrame. **中文文档** 将 ``pandas.DataFrame`` 分拆成等大小的小DataFrame。 """ data = list() counter = 0 for... |
def to_index_row_dict(df, index_col=None, use_ordered_dict=True): """Transform data frame to list of dict. :param index_col: None or str, the column that used as index. :param use_ordered_dict: if True, row dict is has same order as df.columns. **中文文档** 将dataframe以指定列为key, 转化成以行为视角的dict结构, 提升按行index访问 的速度。若无指定列, 则使用ind... |
def to_dict_list(df, use_ordered_dict=True): """Transform each row to dict, and put them into a list. **中文文档** 将 ``pandas.DataFrame`` 转换成一个字典的列表。列表的长度与行数相同, 其中 每一个字典相当于表中的一行, 相当于一个 ``pandas.Series`` 对象。 """ if use_ordered_dict: dict = OrderedDict columns = df.columns data = list() for tp in itertuple(df): data.append(d... |
def to_dict_list_generic_type(df, int_col=None, binary_col=None): """Transform each row to dict, and put them into a list. And automatically convert ``np.int64`` to ``int``, ``pandas.tslib.Timestamp`` to ``datetime.datetime``, ``np.nan`` to ``None``. :param df: ``pandas.DataFrame`` instance. :param int_col: integer typ... |
not None: for col in binary_col: df[col] = df[col].apply(b64_encode) data = json.loads(df.to_json(orient="records", date_format="iso")) if int_col is not None: for row in data: for col in int_col: try: row[col] = int(row[col]) except: pass if binary_col is not None: for row in data: for col in binary_col: try: row[col]... |
def add_connection_args(parser: FileAwareParser, strong_config_file: bool=True) -> FileAwareParser: """ Add the database connection arguments to the supplied parser :param parser: parser to add arguments to :param strong_config_file: If True, force --conf to be processed. This is strictly a test for programming errors,... |
parser.add_argument("--onttable", metavar="ONTOLOGY TABLE NAME", help="Ontology table name (default: {})".format(DEFAULT_ONTOLOGY_TABLE), default=DEFAULT_ONTOLOGY_TABLE) return parser |
def process_parsed_args(opts: Namespace, error_fun: Optional[Callable], connect: bool=True) -> Namespace: """ Set the defaults for the crc and ontology schemas :param opts: parsed arguments :param error_fun: Function to call if error :param connect: actually connect. (For debugging) :return: namespace with additional e... |
harness if opts.onttable: i2b2tablenames.ontology_table = opts.onttable return opts |
def build_dir_tree(self, files): """ Convert a flat file dict into the tree format used for storage """ def helper(split_files): this_dir = {'files' : {}, 'dirs' : {}} dirs = defaultdict(list) for fle in split_files: index = fle[0]; fileinfo = fle[1] if len(index) == 1: fileinfo['path'] = index[0] # store only the file... |
def flatten_dir_tree(self, tree): """ Convert a file tree back into a flat dict """ result = {} def helper(tree, leading_path = ''): dirs = tree['dirs']; files = tree['files'] for name, file_info in files.iteritems(): file_info['path'] = leading_path + '/' + name result[file_info['path']] = file_info for name, contents... |
def read_dir_tree(self, file_hash): """ Recursively read the directory structure beginning at hash """ json_d = self.read_index_object(file_hash, 'tree') node = {'files' : json_d['files'], 'dirs' : {}} for name, hsh in json_d['dirs'].iteritems(): node['dirs'][name] = self.read_dir_tree(hsh) return node |
def write_dir_tree(self, tree): """ Recur through dir tree data structure and write it as a set of objects """ dirs = tree['dirs']; files = tree['files'] child_dirs = {name : self.write_dir_tree(contents) for name, contents in dirs.iteritems()} return self.write_index_object('tree', {'files' : files, 'dirs': child_dirs... |
def have_active_commit(self): """ Checks if there is an active commit owned by the specified user """ commit_state = sfs.file_or_default(sfs.cpjoin(self.base_path, 'active_commit'), None) if commit_state != None: return True return False |
def amend_commit( self, append_to_msg: typing.Optional[str] = None, new_message: typing.Optional[str] = None, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, ): """ Amends last commit Args: append_to_msg: string to append to previous message new_message: new commit message files_to_add: optio... |
def from_text_code(cls, email, result_text_code): """ Alternative method to create an instance of VerifiedEmail object from a text code. :param str email: Email address. :param str result_text_code: A result of verification represented by text (e.g. valid, unknown). :return: An instance of object. """ result_code = cls... |
def compile(self, source_code, post_treatment=''.join, source='<string>', target='exec'): """Return ready-to-exec object code of compilation. Use python built-in compile function. Use exec(1) on returned object for execute it.""" self.last_python_code = super().compile(source_code, post_treatment) return PyCompiler.exe... |
def example_exc_handler(tries_remaining, exception, delay): """Example exception handler; prints a warning to stderr. tries_remaining: The number of tries remaining. exception: The exception instance which was raised. """ print >> sys.stderr, "Caught '%s', %d tries remaining, sleeping for %s seconds" % ( exception, tri... |
def set_env_var(key: str, value: str): """ Sets environment variable on AV Args: key: variable name value: variable value """ elib_run.run(f'appveyor SetVariable -Name {key} -Value {value}') AV.info('Env', f'set "{key}" -> "{value}"') |
def init(scope): """ Initialize the xqt system with the PyQt4 wrapper for the Qt system. :param scope | <dict> """ # update globals scope['py2q'] = py2q scope['q2py'] = q2py # define wrapper compatibility symbols QtCore.THREADSAFE_NONE = None # define the importable symbols scope['QtCore'] = QtCore scope['QtGui'] = laz... |
def validate_internal_deps(self): """Freak out if there are missing local references.""" for node in self.node: if ('target_obj' not in self.node[node] and node not in self.crossrefs): raise error.BrokenGraph('Missing target: %s referenced from %s' ' but not defined there.' % (node, self.name)) |
def crossrefs(self): """Returns a set of non-local targets referenced by this build file.""" # TODO: memoize this? crefs = set() for node in self.node: if node.repo != self.target.repo or node.path != self.target.path: crefs.add(node) return crefs |
def crossref_paths(self): """Just like crossrefs, but all the targets are munged to :all.""" return set( [address.new(repo=x.repo, path=x.path) for x in self.crossrefs]) |
def local_targets(self): """Iterator over the targets defined in this build file.""" for node in self.node: if (node.repo, node.path) == (self.target.repo, self.target.path): yield node |
def _parse(self, stream): """Parse a JSON BUILD file. Args: builddata: dictionary of buildfile data reponame: name of the repo that it came from path: directory path within the repo """ builddata = json.load(stream) log.debug('This is a JSON build file.') if 'targets' not in builddata: log.warn('Warning: No targets def... |
self.target.repo and not d_target.path: d_target.path = self.target.path if d_target not in self.nodes(): self.add_node(d_target) log.debug('New dep: %s -> %s', target, d_target) self.add_edge(target, d_target) |
def check(self, *exc_classes): """Check if any of exception classes caused the failure/s. :param exc_classes: exception types/exception type names to search for. If any of the contained failures were caused by an exception of a given type, the corresponding argument that matched is returned. If not then ``None`` is ret... |
def from_exc_info(cls, exc_info=None, retain_exc_info=True, cause=None, find_cause=True): """Creates a failure object from a ``sys.exc_info()`` tuple.""" if exc_info is None: exc_info = sys.exc_info() if not any(exc_info): raise NoActiveException("No exception currently" " being handled") # This should always be the (t... |
really an exception... raise TypeError("Invalid exception type '%s' (not an" " exception)" % (exc_type_name)) exception_str = utils.exception_message(exc_val) if hasattr(exc_val, '__traceback_str__'): traceback_str = exc_val.__traceback_str__ else: if exc_tb is not None: traceback_str = '\n'.join( traceback.format_exce... |
def from_exception(cls, exception, retain_exc_info=True, cause=None, find_cause=True): """Creates a failure object from a exception instance.""" exc_info = ( type(exception), exception, getattr(exception, '__traceback__', None) ) return cls.from_exc_info(exc_info=exc_info, retain_exc_info=retain_exc_info, cause=cause, ... |
def validate(cls, data): """Validate input data matches expected failure ``dict`` format.""" try: jsonschema.validate( data, cls.SCHEMA, # See: https://github.com/Julian/jsonschema/issues/148 types={'array': (list, tuple)}) except jsonschema.ValidationError as e: raise InvalidFormat("Failure data not of the" " expected... |
sub_cause is not None: causes.append(sub_cause) |
def matches(self, other): """Checks if another object is equivalent to this object. :returns: checks if another object is equivalent to this object :rtype: boolean """ if not isinstance(other, Failure): return False if self.exc_info is None or other.exc_info is None: return self._matches(other) else: return self == oth... |
def reraise_if_any(failures, cause_cls_finder=None): """Re-raise exceptions if argument is not empty. If argument is empty list/tuple/iterator, this method returns None. If argument is converted into a list with a single ``Failure`` object in it, that failure is reraised. Else, a :class:`~.WrappedFailure` exception is ... |
def reraise(self, cause_cls_finder=None): """Re-raise captured exception (possibly trying to recreate).""" if self._exc_info: six.reraise(*self._exc_info) else: # Attempt to regenerate the full chain (and then raise # from the root); without a traceback, oh well... root = None parent = None for cause in itertools.chain... |
None: parent.__cause__ = exc parent = exc six.reraise(type(root), root, tb=None) |
def check(self, *exc_classes): """Check if any of ``exc_classes`` caused the failure. Arguments of this method can be exception types or type names (strings **fully qualified**). If captured exception is an instance of exception of given type, the corresponding argument is returned, otherwise ``None`` is returned. """ ... |
def pformat(self, traceback=False): """Pretty formats the failure object into a string.""" buf = six.StringIO() if not self._exc_type_names: buf.write('Failure: %s' % (self._exception_str)) else: buf.write('Failure: %s: %s' % (self._exc_type_names[0], self._exception_str)) if traceback: if self._traceback_str is not No... |
def iter_causes(self): """Iterate over all causes.""" curr = self._cause while curr is not None: yield curr curr = curr._cause |
def _extract_cause(cls, exc_val): """Helper routine to extract nested cause (if any).""" # See: https://www.python.org/dev/peps/pep-3134/ for why/what # these are... # # '__cause__' attribute for explicitly chained exceptions # '__context__' attribute for implicitly chained exceptions # '__traceback__' attribute for th... |
def from_dict(cls, data): """Converts this from a dictionary to a object.""" data = dict(data) cause = data.get('cause') if cause is not None: data['cause'] = cls.from_dict(cause) return cls(**data) |
def to_dict(self, include_args=True, include_kwargs=True): """Converts this object to a dictionary. :param include_args: boolean indicating whether to include the exception args in the output. :param include_kwargs: boolean indicating whether to include the exception kwargs in the output. """ data = { 'exception_str': ... |
def copy(self, deep=False): """Copies this object (shallow or deep). :param deep: boolean indicating whether to do a deep copy (or a shallow copy). """ cause = self._cause if cause is not None: cause = cause.copy(deep=deep) exc_info = utils.copy_exc_info(self.exc_info, deep=deep) exc_args = self.exception_args exc_kwar... |
def explain_feature(featurename): '''print the location of single feature and its version if the feature is located inside a git repository, this will also print the git-rev and modified files ''' import os import featuremonkey import importlib import subprocess def guess_version(feature_module): if hasattr(feature_mod... |
print('Error: unable to import feature "%s"' % featurename) print('Location: %s' % os.path.dirname(feature_module.__file__)) print() if is_subfeature: print('Version: see parent feature') print() else: print('Version: %s' % str(guess_version(feature_module))) print() print('git: %s' % git_rev(feature_module)) print() p... |
def explain_features(): '''print the location of each feature and its version if the feature is located inside a git repository, this will also print the git-rev and modified files ''' from ape import tasks import featuremonkey import os featurenames = featuremonkey.get_features_from_equation_file(os.environ['PRODUCT_E... |
def git_day(): """Constructs a version string of the form: day[.<commit-number-in-day>][+<branch-name-if-not-master>] Master is understood to be always buildable and thus untagged versions are treated as patch levels. Branches not master are treated as PEP-440 "local version identifiers". """ vec = ['env', 'TZ=UTC', 'g... |
def git_version(): """Constructs a version string of the form: <tag>[.<distance-from-tag>[+<branch-name-if-not-master>]] Master is understood to be always buildable and thus untagged versions are treated as patch levels. Branches not master are treated as PEP-440 "local version identifiers". """ tag = cmd('git', 'descr... |
def imprint(self, path=None): """Write the determined version, if any, to ``self.version_file`` or the path passed as an argument. """ if self.version is not None: with open(path or self.version_file, 'w') as h: h.write(self.version + '\n') else: raise ValueError('Can not write null version to file.') return self |
def from_file(self, path=None): """Look for a version in ``self.version_file``, or in the specified path if supplied. """ if self._version is None: self._version = file_version(path or self.version_file) return self |
def from_git(self, path=None, prefer_daily=False): """Use Git to determine the package version. This routine uses the __file__ value of the caller to determine which Git repository root to use. """ if self._version is None: frame = caller(1) path = frame.f_globals.get('__file__') or '.' providers = ([git_day, git_versi... |
def from_pkg(self): """Use pkg_resources to determine the installed package version. """ if self._version is None: frame = caller(1) pkg = frame.f_globals.get('__package__') if pkg is not None: self._version = pkg_version(pkg) return self |
def __load_dump(self, message): """ Calls the hook method to modify the loaded peer description before giving it to the directory :param message: The received Herald message :return: The updated peer description """ dump = message.content if self._hook is not None: # Call the hook try: updated_dump = self._hook(message... |
def herald_message(self, herald_svc, message): """ Handles a message received by Herald :param herald_svc: Herald service :param message: Received message """ subject = message.subject if subject == SUBJECT_DISCOVERY_STEP_1: # Step 1: Register the remote peer and reply with our dump try: # Delayed registration notifica... |
notify listeners notification.notify() except ValueError: self._logger.error("Error registering a peer using the " "description it sent") elif subject == SUBJECT_DISCOVERY_STEP_3: # Step 3: notify local listeners about the remote peer try: self.__delayed_notifs.pop(message.sender).notify() except KeyError: # Unknown pe... |
def api_url(self): """Returns the api_url or None. """ if not self._api_url: error_msg = ( f"Email is enabled but API_URL is not set. " f"See settings.{self.api_url_attr}" ) try: self._api_url = getattr(settings, self.api_url_attr) except AttributeError: raise EmailNotEnabledError(error_msg, code="api_url_attribute_err... |
def api_key(self): """Returns the api_key or None. """ if not self._api_key: error_msg = ( f"Email is enabled but API_KEY is not set. " f"See settings.{self.api_key_attr}" ) try: self._api_key = getattr(settings, self.api_key_attr) except AttributeError: raise EmailNotEnabledError(error_msg, code="api_key_attribute_err... |
def subscribe(self, user, verbose=None): """Returns a response after attempting to subscribe a member to the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") if not user.email: raise UserEmailError(f"User {user}'s email address is not defined.") response = requests.post( f"{... |
def unsubscribe(self, user, verbose=None): """Returns a response after attempting to unsubscribe a member from the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") response = requests.put( f"{self.api_url}/{self.address}/members/{user.email}", auth=("api", self.api_key), dat... |
def create(self, verbose=None): """Returns a response after attempting to create the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") response = requests.post( self.api_url, auth=("api", self.api_key), data={ "address": self.address, "name": self.name, "description": self.di... |
def delete(self): """Returns a response after attempting to delete the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") return requests.delete( f"{self.api_url}/{self.address}", auth=("api", self.api_key) ) |
def delete_member(self, user): """Returns a response after attempting to remove a member from the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") return requests.delete( f"{self.api_url}/{self.address}/members/{user.email}", auth=("api", self.api_key), ) |
def fbpe_key(code): """ input: 'S0102-67202009000300001' output: 'S0102-6720(09)000300001' """ begin = code[0:10] year = code[12:14] end = code[14:] return '%s(%s)%s' % (begin, year, end) |
def join_accesses(unique_id, accesses, from_date, until_date, dayly_granularity): """ Esse metodo recebe 1 ou mais chaves para um documento em específico para que os acessos sejam recuperados no Ratchet e consolidados em um unico id. Esse processo é necessário pois os acessos de um documento podem ser registrados para ... |
dt >= from_date[:7] or not dt <= until_date[:7]: continue joined_data.setdefault(dt, {}) joined_data[dt].setdefault(atype, 0) joined_data[dt][atype] += data[year][month]['total'] return joined_data def joining_dayly(joined_data, atype, data): if 'total' in data: del(data['total']) for year, months in data.items(): del(... |
def str2date(self, datestr): """Parse date from string. If no template matches this string, raise Error. Please go https://github.com/MacHu-GWU/rolex-project/issues submit your date string. I 'll update templates asap. This method is faster than :meth:`dateutil.parser.parse`. :param datestr: a string represent a date :... |
def _str2datetime(self, datetimestr): """Parse datetime from string. If no template matches this string, raise Error. Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates asap. This method is faster than :meth:`dateutil.parser.parse`. :param datetimestr: a stri... |
def parse_date(self, value): """A lazy method to parse anything to date. If input data type is: - string: parse date from it - integer: use from ordinal - datetime: use date part - date: just return it """ if value is None: raise Exception("Unable to parse date from %r" % value) elif isinstance(value, string_types): re... |
def parse_datetime(self, value): """A lazy method to parse anything to datetime. If input data type is: - string: parse datetime from it - integer: use from ordinal - date: use date part and set hour, minute, second to zero - datetime: just return it """ if value is None: raise Exception("Unable to parse datetime from ... |
def to_utctimestamp(self, dt): """Calculate number of seconds from UTC 1970-01-01 00:00:00. When: - dt doesn't have tzinfo: assume it's a utc time - dt has tzinfo: use tzinfo WARNING, if your datetime object doens't have ``tzinfo``, make sure it's a UTC time, but **NOT a LOCAL TIME**. **中文文档** 计算时间戳 若: - 不带tzinfo: 则默认为... |
def from_utctimestamp(self, timestamp): """Create a **UTC datetime** object that number of seconds after UTC 1970-01-01 00:00:00. If you want local time, use :meth:`Rolex.from_timestamp` Because python doesn't support negative timestamp to datetime so we have to implement my own method. **中文文档** 返回一个在UTC 1970-01-01 00:... |
def _freq_parser(self, freq): """Parse timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() valid_keywords = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m",... |
timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) |
def weekday_series(self, start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, ... |
def rnd_date(self, start=date(1970, 1, 1), end=date.today()): """Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date obje... |
def rnd_date_array(self, size, start=date(1970, 1, 1), end=date.today()): """Array or Matrix of random date generator. """ if isinstance(start, string_types): start = self.str2date(start) if isinstance(end, string_types): end = self.str2date(end) if start > end: raise ValueError("start time has to be earlier than end t... |
def _rnd_datetime(self, start, end): """Internal random datetime generator. """ return self.from_utctimestamp( random.randint( int(self.to_utctimestamp(start)), int(self.to_utctimestamp(end)), ) ) |
def rnd_datetime(self, start=datetime(1970, 1, 1), end=datetime.now()): """Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :... |
def rnd_datetime_array(self, size, start=datetime(1970, 1, 1), end=datetime.now()): """Array or Matrix of random datetime generator. """ if isinstance(start, string_types): start = self.str2datetime(start) if isinstance(end, str): end = self.str2datetime(end) if start > end: raise ValueError("start time has to be earli... |
def add_seconds(self, datetimestr, n): """Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) return a_datetime + timedelta(seconds=n) |
def add_minutes(self, datetimestr, n): """Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) return a_datetime + timedelta(seconds=60 * n) |
def add_hours(self, datetimestr, n): """Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) return a_datetime + timedelta(seconds=3600 * n) |
def add_weeks(self, datetimestr, n, return_date=False): """Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N周之后的时间。 """ a_datetime = self.parse_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.