INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Stop streaming
def stop(self): """ Stop streaming """ if self._protocol: self._protocol.factory.continueTrying = 0 self._protocol.transport.loseConnection() if self._reactor and self._reactor.running: self._reactor.stop()
Called when a connection is made and used to send out headers
def connectionMade(self): """ Called when a connection is made, and used to send out headers """ headers = [ "GET %s HTTP/1.1" % ("/room/%s/live.json" % self.factory.get_stream().get_room_id()) ] connection_headers = self.factory.get_stream().get_connection().get_headers() ...
Callback issued by twisted when new line arrives.
def lineReceived(self, line): """ Callback issued by twisted when new line arrives. Args: line (str): Incoming line """ while self._in_header: if line: self._headers.append(line) else: http, status, message = self._head...
Process data.
def rawDataReceived(self, data): """ Process data. Args: data (str): Incoming data """ if self._len_expected is not None: data, extra = data[:self._len_expected], data[self._len_expected:] self._len_expected -= len(data) else: extr...
: return: ( func methods )
def get_func(self, path): """ :return: (func, methods) """ for url_match, func_pair in self._urls_regex_map.items(): m = url_match.match(path) if m is not None: return func_pair.func, func_pair.methods, m.groupdict() return None, None, None
/ <int: id > - > r ( ?P<id > \ d + )
def _replace_type_to_regex(cls, match): """ /<int:id> -> r'(?P<id>\d+)' """ groupdict = match.groupdict() _type = groupdict.get('type') type_regex = cls.TYPE_REGEX_MAP.get(_type, '[^/]+') name = groupdict.get('name') return r'(?P<{name}>{type_regex})'.format( ...
Get a dictionary of CSL styles.
def styles(self): """Get a dictionary of CSL styles.""" styles = get_all_styles() whitelist = self.app.config.get('CSL_STYLES_WHITELIST') if whitelist: return {k: v for k, v in styles.items() if k in whitelist} return styles
Flask application initialization.
def init_app(self, app): """Flask application initialization.""" state = _InvenioCSLRESTState(app) app.extensions['invenio-csl-rest'] = state return state
Start producing.
def startProducing(self, consumer): """ Start producing. Args: consumer: Consumer """ self._consumer = consumer self._current_deferred = defer.Deferred() self._sent = 0 self._paused = False if not hasattr(self, "_chunk_headers"): ...
Resume producing
def resumeProducing(self): """ Resume producing """ self._paused = False result = self._produce() if result: return result
Stop producing
def stopProducing(self): """ Stop producing """ self._finish(True) if self._deferred and self._sent < self.length: self._deferred.errback(Exception("Consumer asked to stop production of request body (%d sent out of %d)" % (self._sent, self.length)))
Cleanup code after asked to stop producing.
def _finish(self, forced=False): """ Cleanup code after asked to stop producing. Kwargs: forced (bool): If True, we were forced to stop """ if hasattr(self, "_current_file_handle") and self._current_file_handle: self._current_file_handle.close() ...
Send a block of bytes to the consumer.
def _send_to_consumer(self, block): """ Send a block of bytes to the consumer. Args: block (str): Block of bytes """ self._consumer.write(block) self._sent += len(block) if self._callback: self._callback(self._sent, self.length)
Returns total length for this request.
def _length(self): """ Returns total length for this request. Returns: int. Length """ self._build_chunk_headers() length = 0 if self._data: for field in self._data: length += len(self._chunk_headers[field]) lengt...
Build headers for each field.
def _build_chunk_headers(self): """ Build headers for each field. """ if hasattr(self, "_chunk_headers") and self._chunk_headers: return self._chunk_headers = {} for field in self._files: self._chunk_headers[field] = self._headers(field, True) for field i...
Returns the header of the encoding of this parameter. Args: name ( str ): Field name Kwargs: is_file ( bool ): If true this is a file field Returns: array. Headers
def _headers(self, name, is_file=False): """ Returns the header of the encoding of this parameter. Args: name (str): Field name Kwargs: is_file (bool): If true, this is a file field Returns: array. Headers """ ...
Returns a random string to use as the boundary for a message. Returns: string. Boundary
def _boundary(self): """ Returns a random string to use as the boundary for a message. Returns: string. Boundary """ boundary = None try: import uuid boundary = uuid.uuid4().hex except ImportError: import random, sh...
Returns file type for given file field. Args: field ( str ): File field
def _file_type(self, field): """ Returns file type for given file field. Args: field (str): File field Returns: string. File type """ type = mimetypes.guess_type(self._files[field])[0] return type.encode("utf-8") if isinstance(type, unico...
Returns the file size for given file field.
def _file_size(self, field): """ Returns the file size for given file field. Args: field (str): File field Returns: int. File size """ size = 0 try: handle = open(self._files[field], "r") size = os.fstat(handle.fileno()).s...
Generate a path value of type result_type.
def _filename(draw, result_type=None): """Generate a path value of type result_type. result_type can either be bytes or text_type """ # Various ASCII chars have a special meaning for the operating system, # so make them more common ascii_char = characters(min_codepoint=0x01, max_codepoint=0x7f...
Given an ASCII str returns a path of the given type.
def _str_to_path(s, result_type): """Given an ASCII str, returns a path of the given type.""" assert isinstance(s, str) if isinstance(s, bytes) and result_type is text_type: return s.decode('ascii') elif isinstance(s, text_type) and result_type is bytes: return s.encode('ascii') ret...
Generates a root component for a path.
def _path_root(draw, result_type): """Generates a root component for a path.""" # Based on https://en.wikipedia.org/wiki/Path_(computing) def tp(s=''): return _str_to_path(s, result_type) if os.name != 'nt': return tp(os.sep) sep = sampled_from([os.sep, os.altsep or os.sep]).map(...
A strategy which generates filesystem path values.
def fspaths(draw, allow_pathlike=None): """A strategy which generates filesystem path values. The generated values include everything which the builtin :func:`python:open` function accepts i.e. which won't lead to :exc:`ValueError` or :exc:`TypeError` being raised. Note that the range of the retur...
exec compiled code
def _exec(self, globals_dict=None): """exec compiled code""" globals_dict = globals_dict or {} globals_dict.setdefault('__builtins__', {}) exec(self._code, globals_dict) return globals_dict
replace all blocks in extends with current blocks
def handle_extends(self, text): """replace all blocks in extends with current blocks""" match = self.re_extends.match(text) if match: extra_text = self.re_extends.sub('', text, count=1) blocks = self.get_blocks(extra_text) path = os.path.join(self.base_dir, ma...
flush all buffered string into code
def flush_buffer(self): """flush all buffered string into code""" self.code_builder.add_line('{0}.extend([{1}])', self.result_var, ','.join(self.buffered)) self.buffered = []
{{ a }} - > a
def strip_token(self, text, start, end): """{{ a }} -> a""" text = text.replace(start, '', 1) text = text.replace(end, '', 1) return text
Called by the thread it runs the process.
def run(self): """ Called by the thread, it runs the process. NEVER call this method directly. Instead call start() to start the thread. Before finishing the thread using this thread, call join() """ queue = Queue() process = UploadProcess(self._connection_settings, sel...
Add POST data.
def add_data(self, data): """ Add POST data. Args: data (dict): key => value dictionary """ if not self._data: self._data = {} self._data.update(data)
Called by the process it runs it.
def run(self): """ Called by the process, it runs it. NEVER call this method directly. Instead call start() to start the separate process. If you don't want to use a second process, then call fetch() directly on this istance. To stop, call terminate() """ producer_defe...
Given some error text it will log the text if self. log_errors is True
def log_error(self, text: str) -> None: ''' Given some error text it will log the text if self.log_errors is True :param text: Error text to log ''' if self.log_errors: with self._log_fp.open('a+') as log_file: log_file.write(f'{text}\n')
Processes the texts using TweeboParse and returns them in CoNLL format.
def parse_conll(self, texts: List[str], retry_count: int = 0) -> List[str]: ''' Processes the texts using TweeboParse and returns them in CoNLL format. :param texts: The List of Strings to be processed by TweeboParse. :param retry_count: The number of times it has retried for. Default ...
Set entity data
def set_data(self, data={}, datetime_fields=[]): """ Set entity data Args: data (dict): Entity data datetime_fields (array): Fields that should be parsed as datetimes """ if datetime_fields: for field in datetime_fields: if field in da...
Parses a datetime string from YYYY/ MM/ DD HH: MM: SS + HHMM format
def _parse_datetime(self, value): """ Parses a datetime string from "YYYY/MM/DD HH:MM:SS +HHMM" format Args: value (str): String Returns: datetime. Datetime """ offset = 0 pattern = r"\s+([+-]{1}\d+)\Z" matches = re.search(pattern, value)...
validates XML text
def validate_xml_text(text): """validates XML text""" bad_chars = __INVALID_XML_CHARS & set(text) if bad_chars: for offset,c in enumerate(text): if c in bad_chars: raise RuntimeError('invalid XML character: ' + repr(c) + ' at offset ' + str(offset))
validates XML name
def validate_xml_name(name): """validates XML name""" if len(name) == 0: raise RuntimeError('empty XML name') if __INVALID_NAME_CHARS & set(name): raise RuntimeError('XML name contains invalid character') if name[0] in __INVALID_NAME_START_CHARS: raise RuntimeError('XML name st...
Update acceleration. Accounts for the importance and priority ( order ) of multiple behaviors.
def update(self, time): """ Update acceleration. Accounts for the importance and priority (order) of multiple behaviors. """ # .... I feel this stuff could be done a lot better. total_acceleration = Vector.null() max_jerk = self.max_acceleration for behavior in ...
Calculate what the desired change in velocity is. delta_velocity = acceleration * delta_time Time will be dealt with by the sprite.
def update (self): """ Calculate what the desired change in velocity is. delta_velocity = acceleration * delta_time Time will be dealt with by the sprite. """ delta_velocity = Vector.null() target_position = self.target.get_position() sprite_position = self.sprite.get_po...
Prepare the actors the world and the messaging system to begin playing the game. This method is guaranteed to be called exactly once upon entering the game stage.
def on_enter_stage(self): """ Prepare the actors, the world, and the messaging system to begin playing the game. This method is guaranteed to be called exactly once upon entering the game stage. """ with self.world._unlock_temporarily(): sel...
Sequentially update the actors the world and the messaging system. The theater terminates once all of the actors indicate that they are done.
def on_update_stage(self, dt): """ Sequentially update the actors, the world, and the messaging system. The theater terminates once all of the actors indicate that they are done. """ for actor in self.actors: actor.on_update_game(dt) self.forum.on_update_g...
Give the actors the world and the messaging system a chance to react to the end of the game.
def on_exit_stage(self): """ Give the actors, the world, and the messaging system a chance to react to the end of the game. """ # 1. Let the forum react to the end of the game. Local forums don't # react to this, but remote forums take the opportunity to stop ...
Return a list of all the tokens that are referenced ( i. e. contained in ) this message. Tokens that haven t been assigned an id yet are searched recursively for tokens. So this method may return fewer results after the message is sent. This information is used by the game engine to catch mistakes like forgetting to ad...
def tokens_referenced(self): """ Return a list of all the tokens that are referenced (i.e. contained in) this message. Tokens that haven't been assigned an id yet are searched recursively for tokens. So this method may return fewer results after the message is sent. This in...
Enable/ Disable handler.
def wrap_handler(self, handler, context_switcher): """Enable/Disable handler.""" context_switcher.add_context_in(lambda: LOGGER.addHandler(self.handler)) context_switcher.add_context_out(lambda: LOGGER.removeHandler(self.handler))
Template variables.
def render_vars(self): """Template variables.""" return { 'records': [ { 'message': record.getMessage(), 'time': dt.datetime.fromtimestamp(record.created).strftime('%H:%M:%S'), } for record in self.handler.records ...
Use when application is starting.
def init_async(self, loop=None): """Use when application is starting.""" self._loop = loop or asyncio.get_event_loop() self._async_lock = asyncio.Lock(loop=loop) # FIX: SQLITE in memory database if not self.database == ':memory:': self._state = ConnectionLocal()
Catch a connection asyncrounosly.
async def async_connect(self): """Catch a connection asyncrounosly.""" if self._async_lock is None: raise Exception('Error, database not properly initialized before async connection') async with self._async_lock: self.connect(True) return self._state.conn
Initialize self.
def init_async(self, loop): """Initialize self.""" super(PooledAIODatabase, self).init_async(loop) self._waiters = collections.deque()
Asyncronously wait for a connection from the pool.
async def async_connect(self): """Asyncronously wait for a connection from the pool.""" if self._waiters is None: raise Exception('Error, database not properly initialized before async connection') if self._waiters or self.max_connections and (len(self._in_use) >= self.max_connectio...
Release waiters.
def _close(self, conn): """Release waiters.""" super(PooledAIODatabase, self)._close(conn) for waiter in self._waiters: if not waiter.done(): logger.debug('Release a waiter') waiter.set_result(True) break
Listen for an id from the server.
def receive_id_from_server(self): """ Listen for an id from the server. At the beginning of a game, each client receives an IdFactory from the server. This factory are used to give id numbers that are guaranteed to be unique to tokens that created locally. This method checks...
Respond when the server indicates that the client is out of sync.
def execute_sync(self, message): """ Respond when the server indicates that the client is out of sync. The server can request a sync when this client sends a message that fails the check() on the server. If the reason for the failure isn't very serious, then the server can de...
Manage the response when the server rejects a message.
def execute_undo(self, message): """ Manage the response when the server rejects a message. An undo is when required this client sends a message that the server refuses to pass on to the other clients playing the game. When this happens, the client must undo the changes that ...
Relay messages from the forum on the server to the client represented by this actor.
def _relay_message(self, message): """ Relay messages from the forum on the server to the client represented by this actor. """ info("relaying message: {message}") if not message.was_sent_by(self._id_factory): self.pipe.send(message) self.pipe.de...
Create a new DataItem.
def generate(request): """ Create a new DataItem. """ models.DataItem.create( content=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20)) ) return muffin.HTTPFound('/')
Raise an ApiUsageError if the given object is not a token that is currently participating in the game. To be participating in the game the given token must have an id number and be associated with the world.
def require_active_token(object): """ Raise an ApiUsageError if the given object is not a token that is currently participating in the game. To be participating in the game, the given token must have an id number and be associated with the world. """ require_token(object) token = object ...
Iterate through each member of the class being created and add a safety check to every method that isn t marked as read - only.
def add_safety_checks(meta, members): """ Iterate through each member of the class being created and add a safety check to every method that isn't marked as read-only. """ for member_name, member_value in members.items(): members[member_name] = meta.add_safety_check(...
If the given member is a method that is public ( i. e. doesn t start with an underscore ) and hasn t been marked as read - only replace it with a version that will check to make sure the world is locked. This ensures that methods that alter the token are only called from update methods or messages.
def add_safety_check(member_name, member_value): """ If the given member is a method that is public (i.e. doesn't start with an underscore) and hasn't been marked as read-only, replace it with a version that will check to make sure the world is locked. This ensures that metho...
Register the given callback to be called whenever the method with the given name is called. You can easily take advantage of this feature in token extensions by using the
def watch_method(self, method_name, callback): """ Register the given callback to be called whenever the method with the given name is called. You can easily take advantage of this feature in token extensions by using the @watch_token decorator. """ # Make sure a toke...
Clear all the internal data the token needed while it was part of the world.
def _remove_from_world(self): """ Clear all the internal data the token needed while it was part of the world. Note that this method doesn't actually remove the token from the world. That's what World._remove_token() does. This method is just responsible for setting...
Allow tokens to modify the world for the duration of a with - block.
def _unlock_temporarily(self): """ Allow tokens to modify the world for the duration of a with-block. It's important that tokens only modify the world at appropriate times, otherwise the changes they make may not be communicated across the network to other clients. To help ca...
Converts XML tree to event generator
def scan(xml): """Converts XML tree to event generator""" if xml.tag is et.Comment: yield {'type': COMMENT, 'text': xml.text} return if xml.tag is et.PI: if xml.text: yield {'type': PI, 'target': xml.target, 'text': xml.text} else: yield {'type': PI,...
Converts events stream into lXML tree
def unscan(events, nsmap=None): """Converts events stream into lXML tree""" root = None last_closed_elt = None stack = [] for obj in events: if obj['type'] == ENTER: elt = _obj2elt(obj, nsmap=nsmap) if stack: stack[-1].append(elt) elif ro...
Parses file content into events stream
def parse(filename): """Parses file content into events stream""" for event, elt in et.iterparse(filename, events= ('start', 'end', 'comment', 'pi'), huge_tree=True): if event == 'start': obj = _elt2obj(elt) obj['type'] = ENTER yield obj if elt.text: ...
selects sub - tree events
def subtree(events): """selects sub-tree events""" stack = 0 for obj in events: if obj['type'] == ENTER: stack += 1 elif obj['type'] == EXIT: if stack == 0: break stack -= 1 yield obj
merges each run of successive text events into one text event
def merge_text(events): """merges each run of successive text events into one text event""" text = [] for obj in events: if obj['type'] == TEXT: text.append(obj['text']) else: if text: yield {'type': TEXT, 'text': ''.join(text)} text.cl...
locates ENTER peer for each EXIT object. Convenient when selectively filtering out XML markup
def with_peer(events): """locates ENTER peer for each EXIT object. Convenient when selectively filtering out XML markup""" stack = [] for obj in events: if obj['type'] == ENTER: stack.append(obj) yield obj, None elif obj['type'] == EXIT: yield obj, st...
This method was ported from the work done by GM Arts on top of the algorithm by Claus Tondering which was based in part on the algorithm of Ouding ( 1940 ) as quoted in Explanatory Supplement to the Astronomical Almanac P. Kenneth Seidelmann editor.
def easter(year): """ This method was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, editor. More about th...
construct BusinessDate instance from datetime. date instance raise ValueError exception if not possible
def from_date(datetime_date): """ construct BusinessDate instance from datetime.date instance, raise ValueError exception if not possible :param datetime.date datetime_date: calendar day :return bool: """ return BusinessDate.from_ymd(datetime_date.year, datetime_...
construction from the following string patterns %Y - %m - %d %d. %m. %Y %m/ %d/ %Y %Y%m%d
def from_string(date_str): """ construction from the following string patterns '%Y-%m-%d' '%d.%m.%Y' '%m/%d/%Y' '%Y%m%d' :param str date_str: :return BusinessDate: """ if date_str.count('-'): str_format = '%Y-%m-%d' eli...
construct datetime. date instance represented calendar date of BusinessDate instance
def to_date(self): """ construct datetime.date instance represented calendar date of BusinessDate instance :return datetime.date: """ y, m, d = self.to_ymd() return date(y, m, d)
checks whether the provided date is a date: param BusinessDate int or float in_date:: return bool:
def is_businessdate(in_date): """ checks whether the provided date is a date :param BusinessDate, int or float in_date: :return bool: """ # Note: if the data range has been created from pace_xl, then all the dates are bank dates # and here it remains to check the ...
: param list holiday_obj: datetime. date list defining business holidays: return: bool
def is_business_day(self, holiday_obj=None): """ :param list holiday_obj : datetime.date list defining business holidays :return: bool method to check if a date falls neither on weekend nor is holiday """ y, m, d = BusinessDate.to_ymd(self) if weekday(y, m, d) > ...
addition of a period object
def add_period(self, p, holiday_obj=None): """ addition of a period object :param BusinessDate d: :param p: :type p: BusinessPeriod or str :param list holiday_obj: :return bankdate: """ if isinstance(p, (list, tuple)): return [Busines...
addition of a number of months
def add_months(self, month_int): """ addition of a number of months :param BusinessDate d: :param int month_int: :return bankdate: """ month_int += self.month while month_int > 12: self = BusinessDate.add_years(self, 1) month_int ...
private method for the addition of business days used in the addition of a BusinessPeriod only
def add_business_days(self, days_int, holiday_obj=None): """ private method for the addition of business days, used in the addition of a BusinessPeriod only :param BusinessDate d: :param int days_int: :param list holiday_obj: :return: BusinessDate """ re...
difference expressed as a tuple of years months days ( see also the python lib dateutils. relativedelta )
def diff(self, end_date): """ difference expressed as a tuple of years, months, days (see also the python lib dateutils.relativedelta) :param BusinessDate start_date: :param BusinessDate end_date: :return (int, int, int): """ if end_date < self: ...
implements 30/ 360 Day Count Convention ( 4. 16 ( f ) 2006 ISDA Definitions )
def get_30_360(self, end): """ implements 30/360 Day Count Convention (4.16(f) 2006 ISDA Definitions) """ start_day = min(self.day, 30) end_day = 30 if (start_day == 30 and end.day == 31) else end.day return (360 * (end.year - self.year) + 30 * (end.month - self.month...
implements Act/ Act day count convention ( 4. 16 ( b ) 2006 ISDA Definitions )
def get_act_act(self, end): """ implements Act/Act day count convention (4.16(b) 2006 ISDA Definitions) """ # split end-self in year portions # if the period does not lie within a year split the days in the period as following: # restdays of start year / ye...
implements the 30E/ 360 Day Count Convention ( 4. 16 ( g ) 2006 ISDA Definitons )
def get_30E_360(self, end): """ implements the 30E/360 Day Count Convention (4.16(g) 2006 ISDA Definitons) """ y1, m1, d1 = self.to_ymd() # adjust to date immediately following the the last day y2, m2, d2 = end.add_days(0).to_ymd() d1 = min(d1, 30) d2 = ...
implements the 30E/ 360 ( ISDA ) Day Count Convention ( 4. 16 ( h ) 2006 ISDA Definitions ): param end:: return:
def get_30E_360_ISDA(self, end): """ implements the 30E/360 (ISDA) Day Count Convention (4.16(h) 2006 ISDA Definitions) :param end: :return: """ y1, m1, d1 = self.to_ymd() # ajdust to date immediately following the last day y2, m2, d2 = end.add_days(0).to_...
adjusts to Business Day Convention Preceding ( 4. 12 ( a ) ( iii ) 2006 ISDA Definitions ).
def adjust_previous(self, holidays_obj=None): """ adjusts to Business Day Convention "Preceding" (4.12(a) (iii) 2006 ISDA Definitions). """ while not BusinessDate.is_business_day(self, holidays_obj): self = BusinessDate.add_days(self, -1) return self
adjusts to Business Day Convention Following ( 4. 12 ( a ) ( i ) 2006 ISDA Definitions ).
def adjust_follow(self, holidays_obj=None): """ adjusts to Business Day Convention "Following" (4.12(a) (i) 2006 ISDA Definitions). """ while not BusinessDate.is_business_day(self, holidays_obj): self = BusinessDate.add_days(self, 1) return self
adjusts to Business Day Convention Modified [ Following ] ( 4. 12 ( a ) ( ii ) 2006 ISDA Definitions ).
def adjust_mod_follow(self, holidays_obj=None): """ adjusts to Business Day Convention "Modified [Following]" (4.12(a) (ii) 2006 ISDA Definitions). """ month = self.month new = BusinessDate.adjust_follow(self, holidays_obj) if month != new.month: new = Busines...
ajusts to Business Day Convention Modified Preceding ( not in 2006 ISDA Definitons ).
def adjust_mod_previous(self, holidays_obj=None): """ ajusts to Business Day Convention "Modified Preceding" (not in 2006 ISDA Definitons). """ month = self.month new = BusinessDate.adjust_previous(self, holidays_obj) if month != new.month: new = BusinessDate....
: param in_period: object to be checked: type in_period: object str timedelta: return: True if cast works: rtype: Boolean
def is_businessperiod(cls, in_period): """ :param in_period: object to be checked :type in_period: object, str, timedelta :return: True if cast works :rtype: Boolean checks is argument con becasted to BusinessPeriod """ try: # to be removed i...
Parses as much as possible until it encounters a matching closing quote. By default matches any_token but can be provided with a more specific parser if required. Returns a string
def quoted(parser=any_token): """Parses as much as possible until it encounters a matching closing quote. By default matches any_token, but can be provided with a more specific parser if required. Returns a string """ quote_char = quote() value, _ = many_until(parser, partial(one_of, quote_...
returns number of days for the given year and month
def days_in_month(year, month): """ returns number of days for the given year and month :param int year: calendar year :param int month: calendar month :return int: """ eom = _days_per_month[month - 1] if is_leap_year(year) and month == 2: eom += 1 return eom
return True if ( year month day ) can be represented in Excel - notation ( number of days since 30. 12. 1899 ) for calendar days otherwise False
def is_valid_ymd(year, month, day): """ return True if (year,month, day) can be represented in Excel-notation (number of days since 30.12.1899) for calendar days, otherwise False :param int year: calendar year :param int month: calendar month :param int day: calendar day :return bool: "...
converts date in Microsoft Excel representation style and returns ( year month day ) tuple
def from_excel_to_ymd(excel_int): """ converts date in Microsoft Excel representation style and returns `(year, month, day)` tuple :param int excel_int: date as int (days since 1899-12-31) :return tuple(int, int, int): """ int_date = int(floor(excel_int)) int_date -= 1 if excel_int > 60 e...
converts date as ( year month day ) tuple into Microsoft Excel representation style
def from_ymd_to_excel(year, month, day): """ converts date as `(year, month, day)` tuple into Microsoft Excel representation style :param tuple(int, int, int): int tuple `year, month, day` :return int: """ if not is_valid_ymd(year, month, day): raise ValueError("Invalid date {0}.{1}.{2}...
adds number of years to a date: param BaseDateFloat d: date to add years to: param int years_int: number of years to add: return BaseDate: resulting date
def add_years(d, years_int): """ adds number of years to a date :param BaseDateFloat d: date to add years to :param int years_int: number of years to add :return BaseDate: resulting date """ y, m, d = BaseDate.to_ymd(d) if not is_leap_year(years_int) and ...
addition of a number of days
def add_days(d, days_int): """ addition of a number of days :param BaseDateDatetimeDate d: :param int days_int: :return BaseDatetimeDate: """ n = date(d.year, d.month, d.day) + timedelta(days_int) return BaseDateDatetimeDate(n.year, n.month, n.day)
addition of a number of years
def add_years(d, years_int): """ addition of a number of years :param BaseDateDatetimeDate d: :param int years_int: :return BaseDatetimeDate: """ y, m, d = BaseDateDatetimeDate.to_ymd(d) y += years_int if not is_leap_year(y) and m == 2: ...
calculate difference between given dates in days
def diff_in_days(start, end): """ calculate difference between given dates in days :param BaseDateDatetimeDate start: state date :param BaseDateDatetimeDate end: end date :return float: difference between end date and start date in days """ diff = date(end.year, ...
addition of a number of days
def add_days(date_obj, days_int): """ addition of a number of days :param BaseDateTuple d: :param int days_int: :return BaseDatetimeDate: """ n = from_ymd_to_excel(*date_obj.date) + days_int return BaseDateTuple(*from_excel_to_ymd(n))
addition of a number of years
def add_years(date_obj, years_int): """ addition of a number of years :param BaseDateTuple d: :param int years_int: :return BaseDatetimeDate: """ y, m, d = BaseDateTuple.to_ymd(date_obj) y += years_int if not is_leap_year(y) and m == 2: ...
calculate difference between given dates in days
def diff_in_days(start, end): """ calculate difference between given dates in days :param BaseDateTuple start: state date :param BaseDateTuple end: end date :return float: difference between end date and start date in days """ diff = from_ymd_to_excel(*end.date)...
Initialize the application.
def setup(self, app): # noqa """Initialize the application.""" super().setup(app) # Setup Database self.database.initialize(connect(self.cfg.connection, **self.cfg.connection_params)) # Fix SQLite in-memory database if self.database.database == ':memory:': ...
Register connection s middleware and prepare self database.
def startup(self, app): """Register connection's middleware and prepare self database.""" self.database.init_async(app.loop) if not self.cfg.connection_manual: app.middlewares.insert(0, self._middleware)
Close all connections.
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()