partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
LiveStreamProcess.stop
Stop streaming
pyfire/stream.py
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()
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()
[ "Stop", "streaming" ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L316-L324
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_protocol", ":", "self", ".", "_protocol", ".", "factory", ".", "continueTrying", "=", "0", "self", ".", "_protocol", ".", "transport", ".", "loseConnection", "(", ")", "if", "self", ".", "_reactor", "and", "self", ".", "_reactor", ".", "running", ":", "self", ".", "_reactor", ".", "stop", "(", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
LiveStreamProtocol.connectionMade
Called when a connection is made, and used to send out headers
pyfire/stream.py
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() for header in connection_headers: headers.append("%s: %s" % (header, connection_headers[header])) headers.append("Host: streaming.campfirenow.com") self.transport.write("\r\n".join(headers) + "\r\n\r\n") self.factory.get_stream().set_protocol(self)
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() for header in connection_headers: headers.append("%s: %s" % (header, connection_headers[header])) headers.append("Host: streaming.campfirenow.com") self.transport.write("\r\n".join(headers) + "\r\n\r\n") self.factory.get_stream().set_protocol(self)
[ "Called", "when", "a", "connection", "is", "made", "and", "used", "to", "send", "out", "headers" ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L350-L364
[ "def", "connectionMade", "(", "self", ")", ":", "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", "(", ")", "for", "header", "in", "connection_headers", ":", "headers", ".", "append", "(", "\"%s: %s\"", "%", "(", "header", ",", "connection_headers", "[", "header", "]", ")", ")", "headers", ".", "append", "(", "\"Host: streaming.campfirenow.com\"", ")", "self", ".", "transport", ".", "write", "(", "\"\\r\\n\"", ".", "join", "(", "headers", ")", "+", "\"\\r\\n\\r\\n\"", ")", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "set_protocol", "(", "self", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
LiveStreamProtocol.lineReceived
Callback issued by twisted when new line arrives. Args: line (str): Incoming line
pyfire/stream.py
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._headers[0].split(" ", 2) status = int(status) if status == 200: self.factory.get_stream().connected() else: self.factory.continueTrying = 0 self.transport.loseConnection() self.factory.get_stream().disconnected(RuntimeError(status, message)) return self._in_header = False break else: try: self._len_expected = int(line, 16) self.setRawMode() except: pass
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._headers[0].split(" ", 2) status = int(status) if status == 200: self.factory.get_stream().connected() else: self.factory.continueTrying = 0 self.transport.loseConnection() self.factory.get_stream().disconnected(RuntimeError(status, message)) return self._in_header = False break else: try: self._len_expected = int(line, 16) self.setRawMode() except: pass
[ "Callback", "issued", "by", "twisted", "when", "new", "line", "arrives", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L366-L393
[ "def", "lineReceived", "(", "self", ",", "line", ")", ":", "while", "self", ".", "_in_header", ":", "if", "line", ":", "self", ".", "_headers", ".", "append", "(", "line", ")", "else", ":", "http", ",", "status", ",", "message", "=", "self", ".", "_headers", "[", "0", "]", ".", "split", "(", "\" \"", ",", "2", ")", "status", "=", "int", "(", "status", ")", "if", "status", "==", "200", ":", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "connected", "(", ")", "else", ":", "self", ".", "factory", ".", "continueTrying", "=", "0", "self", ".", "transport", ".", "loseConnection", "(", ")", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "disconnected", "(", "RuntimeError", "(", "status", ",", "message", ")", ")", "return", "self", ".", "_in_header", "=", "False", "break", "else", ":", "try", ":", "self", ".", "_len_expected", "=", "int", "(", "line", ",", "16", ")", "self", ".", "setRawMode", "(", ")", "except", ":", "pass" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
LiveStreamProtocol.rawDataReceived
Process data. Args: data (str): Incoming data
pyfire/stream.py
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: extra = "" self._buffer += data if self._len_expected == 0: data = self._buffer.strip() if data: lines = data.split("\r") for line in lines: try: message = self.factory.get_stream().get_connection().parse(line) if message: self.factory.get_stream().received([message]) except ValueError: pass self._buffer = "" self._len_expected = None self.setLineMode(extra)
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: extra = "" self._buffer += data if self._len_expected == 0: data = self._buffer.strip() if data: lines = data.split("\r") for line in lines: try: message = self.factory.get_stream().get_connection().parse(line) if message: self.factory.get_stream().received([message]) except ValueError: pass self._buffer = "" self._len_expected = None self.setLineMode(extra)
[ "Process", "data", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/stream.py#L395-L422
[ "def", "rawDataReceived", "(", "self", ",", "data", ")", ":", "if", "self", ".", "_len_expected", "is", "not", "None", ":", "data", ",", "extra", "=", "data", "[", ":", "self", ".", "_len_expected", "]", ",", "data", "[", "self", ".", "_len_expected", ":", "]", "self", ".", "_len_expected", "-=", "len", "(", "data", ")", "else", ":", "extra", "=", "\"\"", "self", ".", "_buffer", "+=", "data", "if", "self", ".", "_len_expected", "==", "0", ":", "data", "=", "self", ".", "_buffer", ".", "strip", "(", ")", "if", "data", ":", "lines", "=", "data", ".", "split", "(", "\"\\r\"", ")", "for", "line", "in", "lines", ":", "try", ":", "message", "=", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "get_connection", "(", ")", ".", "parse", "(", "line", ")", "if", "message", ":", "self", ".", "factory", ".", "get_stream", "(", ")", ".", "received", "(", "[", "message", "]", ")", "except", "ValueError", ":", "pass", "self", ".", "_buffer", "=", "\"\"", "self", ".", "_len_expected", "=", "None", "self", ".", "setLineMode", "(", "extra", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
Router.get_func
:return: (func, methods)
bustard/router.py
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
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
[ ":", "return", ":", "(", "func", "methods", ")" ]
mozillazg/bustard
python
https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/router.py#L24-L32
[ "def", "get_func", "(", "self", ",", "path", ")", ":", "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" ]
bd7b47f3ba5440cf6ea026c8b633060fedeb80b7
valid
URLBuilder._replace_type_to_regex
/<int:id> -> r'(?P<id>\d+)'
bustard/router.py
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( name=name, type_regex=type_regex )
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( name=name, type_regex=type_regex )
[ "/", "<int", ":", "id", ">", "-", ">", "r", "(", "?P<id", ">", "\\", "d", "+", ")" ]
mozillazg/bustard
python
https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/router.py#L94-L102
[ "def", "_replace_type_to_regex", "(", "cls", ",", "match", ")", ":", "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", "(", "name", "=", "name", ",", "type_regex", "=", "type_regex", ")" ]
bd7b47f3ba5440cf6ea026c8b633060fedeb80b7
valid
_InvenioCSLRESTState.styles
Get a dictionary of CSL styles.
invenio_csl_rest/ext.py
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
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
[ "Get", "a", "dictionary", "of", "CSL", "styles", "." ]
inveniosoftware/invenio-csl-rest
python
https://github.com/inveniosoftware/invenio-csl-rest/blob/a474a5b4caa9e6ae841a007fa52b30ad7e957560/invenio_csl_rest/ext.py#L43-L49
[ "def", "styles", "(", "self", ")", ":", "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" ]
a474a5b4caa9e6ae841a007fa52b30ad7e957560
valid
InvenioCSLREST.init_app
Flask application initialization.
invenio_csl_rest/ext.py
def init_app(self, app): """Flask application initialization.""" state = _InvenioCSLRESTState(app) app.extensions['invenio-csl-rest'] = state return state
def init_app(self, app): """Flask application initialization.""" state = _InvenioCSLRESTState(app) app.extensions['invenio-csl-rest'] = state return state
[ "Flask", "application", "initialization", "." ]
inveniosoftware/invenio-csl-rest
python
https://github.com/inveniosoftware/invenio-csl-rest/blob/a474a5b4caa9e6ae841a007fa52b30ad7e957560/invenio_csl_rest/ext.py#L72-L76
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "state", "=", "_InvenioCSLRESTState", "(", "app", ")", "app", ".", "extensions", "[", "'invenio-csl-rest'", "]", "=", "state", "return", "state" ]
a474a5b4caa9e6ae841a007fa52b30ad7e957560
valid
MultiPartProducer.startProducing
Start producing. Args: consumer: Consumer
pyfire/twistedx/producer.py
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"): self._build_chunk_headers() if self._data: block = "" for field in self._data: block += self._chunk_headers[field] block += self._data[field] block += "\r\n" self._send_to_consumer(block) if self._files: self._files_iterator = self._files.iterkeys() self._files_sent = 0 self._files_length = len(self._files) self._current_file_path = None self._current_file_handle = None self._current_file_length = None self._current_file_sent = 0 result = self._produce() if result: return result else: return defer.succeed(None) return self._current_deferred
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"): self._build_chunk_headers() if self._data: block = "" for field in self._data: block += self._chunk_headers[field] block += self._data[field] block += "\r\n" self._send_to_consumer(block) if self._files: self._files_iterator = self._files.iterkeys() self._files_sent = 0 self._files_length = len(self._files) self._current_file_path = None self._current_file_handle = None self._current_file_length = None self._current_file_sent = 0 result = self._produce() if result: return result else: return defer.succeed(None) return self._current_deferred
[ "Start", "producing", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L42-L80
[ "def", "startProducing", "(", "self", ",", "consumer", ")", ":", "self", ".", "_consumer", "=", "consumer", "self", ".", "_current_deferred", "=", "defer", ".", "Deferred", "(", ")", "self", ".", "_sent", "=", "0", "self", ".", "_paused", "=", "False", "if", "not", "hasattr", "(", "self", ",", "\"_chunk_headers\"", ")", ":", "self", ".", "_build_chunk_headers", "(", ")", "if", "self", ".", "_data", ":", "block", "=", "\"\"", "for", "field", "in", "self", ".", "_data", ":", "block", "+=", "self", ".", "_chunk_headers", "[", "field", "]", "block", "+=", "self", ".", "_data", "[", "field", "]", "block", "+=", "\"\\r\\n\"", "self", ".", "_send_to_consumer", "(", "block", ")", "if", "self", ".", "_files", ":", "self", ".", "_files_iterator", "=", "self", ".", "_files", ".", "iterkeys", "(", ")", "self", ".", "_files_sent", "=", "0", "self", ".", "_files_length", "=", "len", "(", "self", ".", "_files", ")", "self", ".", "_current_file_path", "=", "None", "self", ".", "_current_file_handle", "=", "None", "self", ".", "_current_file_length", "=", "None", "self", ".", "_current_file_sent", "=", "0", "result", "=", "self", ".", "_produce", "(", ")", "if", "result", ":", "return", "result", "else", ":", "return", "defer", ".", "succeed", "(", "None", ")", "return", "self", ".", "_current_deferred" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer.resumeProducing
Resume producing
pyfire/twistedx/producer.py
def resumeProducing(self): """ Resume producing """ self._paused = False result = self._produce() if result: return result
def resumeProducing(self): """ Resume producing """ self._paused = False result = self._produce() if result: return result
[ "Resume", "producing" ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L82-L87
[ "def", "resumeProducing", "(", "self", ")", ":", "self", ".", "_paused", "=", "False", "result", "=", "self", ".", "_produce", "(", ")", "if", "result", ":", "return", "result" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer.stopProducing
Stop producing
pyfire/twistedx/producer.py
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)))
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)))
[ "Stop", "producing" ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L93-L97
[ "def", "stopProducing", "(", "self", ")", ":", "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", ")", ")", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer._finish
Cleanup code after asked to stop producing. Kwargs: forced (bool): If True, we were forced to stop
pyfire/twistedx/producer.py
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() if self._current_deferred: self._current_deferred.callback(self._sent) self._current_deferred = None if not forced and self._deferred: self._deferred.callback(self._sent)
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() if self._current_deferred: self._current_deferred.callback(self._sent) self._current_deferred = None if not forced and self._deferred: self._deferred.callback(self._sent)
[ "Cleanup", "code", "after", "asked", "to", "stop", "producing", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L135-L149
[ "def", "_finish", "(", "self", ",", "forced", "=", "False", ")", ":", "if", "hasattr", "(", "self", ",", "\"_current_file_handle\"", ")", "and", "self", ".", "_current_file_handle", ":", "self", ".", "_current_file_handle", ".", "close", "(", ")", "if", "self", ".", "_current_deferred", ":", "self", ".", "_current_deferred", ".", "callback", "(", "self", ".", "_sent", ")", "self", ".", "_current_deferred", "=", "None", "if", "not", "forced", "and", "self", ".", "_deferred", ":", "self", ".", "_deferred", ".", "callback", "(", "self", ".", "_sent", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer._send_to_consumer
Send a block of bytes to the consumer. Args: block (str): Block of bytes
pyfire/twistedx/producer.py
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)
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)
[ "Send", "a", "block", "of", "bytes", "to", "the", "consumer", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L151-L160
[ "def", "_send_to_consumer", "(", "self", ",", "block", ")", ":", "self", ".", "_consumer", ".", "write", "(", "block", ")", "self", ".", "_sent", "+=", "len", "(", "block", ")", "if", "self", ".", "_callback", ":", "self", ".", "_callback", "(", "self", ".", "_sent", ",", "self", ".", "length", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer._length
Returns total length for this request. Returns: int. Length
pyfire/twistedx/producer.py
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]) length += len(self._data[field]) length += 2 if self._files: for field in self._files: length += len(self._chunk_headers[field]) length += self._file_size(field) length += 2 length += len(self.boundary) length += 6 return length
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]) length += len(self._data[field]) length += 2 if self._files: for field in self._files: length += len(self._chunk_headers[field]) length += self._file_size(field) length += 2 length += len(self.boundary) length += 6 return length
[ "Returns", "total", "length", "for", "this", "request", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L162-L187
[ "def", "_length", "(", "self", ")", ":", "self", ".", "_build_chunk_headers", "(", ")", "length", "=", "0", "if", "self", ".", "_data", ":", "for", "field", "in", "self", ".", "_data", ":", "length", "+=", "len", "(", "self", ".", "_chunk_headers", "[", "field", "]", ")", "length", "+=", "len", "(", "self", ".", "_data", "[", "field", "]", ")", "length", "+=", "2", "if", "self", ".", "_files", ":", "for", "field", "in", "self", ".", "_files", ":", "length", "+=", "len", "(", "self", ".", "_chunk_headers", "[", "field", "]", ")", "length", "+=", "self", ".", "_file_size", "(", "field", ")", "length", "+=", "2", "length", "+=", "len", "(", "self", ".", "boundary", ")", "length", "+=", "6", "return", "length" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer._build_chunk_headers
Build headers for each field.
pyfire/twistedx/producer.py
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 in self._data: self._chunk_headers[field] = self._headers(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 in self._data: self._chunk_headers[field] = self._headers(field)
[ "Build", "headers", "for", "each", "field", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L189-L198
[ "def", "_build_chunk_headers", "(", "self", ")", ":", "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", "in", "self", ".", "_data", ":", "self", ".", "_chunk_headers", "[", "field", "]", "=", "self", ".", "_headers", "(", "field", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer._headers
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
pyfire/twistedx/producer.py
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 """ value = self._files[name] if is_file else self._data[name] _boundary = self.boundary.encode("utf-8") if isinstance(self.boundary, unicode) else urllib.quote_plus(self.boundary) headers = ["--%s" % _boundary] if is_file: disposition = 'form-data; name="%s"; filename="%s"' % (name, os.path.basename(value)) else: disposition = 'form-data; name="%s"' % name headers.append("Content-Disposition: %s" % disposition) if is_file: file_type = self._file_type(name) else: file_type = "text/plain; charset=utf-8" headers.append("Content-Type: %s" % file_type) if is_file: headers.append("Content-Length: %i" % self._file_size(name)) else: headers.append("Content-Length: %i" % len(value)) headers.append("") headers.append("") return "\r\n".join(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 """ value = self._files[name] if is_file else self._data[name] _boundary = self.boundary.encode("utf-8") if isinstance(self.boundary, unicode) else urllib.quote_plus(self.boundary) headers = ["--%s" % _boundary] if is_file: disposition = 'form-data; name="%s"; filename="%s"' % (name, os.path.basename(value)) else: disposition = 'form-data; name="%s"' % name headers.append("Content-Disposition: %s" % disposition) if is_file: file_type = self._file_type(name) else: file_type = "text/plain; charset=utf-8" headers.append("Content-Type: %s" % file_type) if is_file: headers.append("Content-Length: %i" % self._file_size(name)) else: headers.append("Content-Length: %i" % len(value)) headers.append("") headers.append("") return "\r\n".join(headers)
[ "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" ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L200-L239
[ "def", "_headers", "(", "self", ",", "name", ",", "is_file", "=", "False", ")", ":", "value", "=", "self", ".", "_files", "[", "name", "]", "if", "is_file", "else", "self", ".", "_data", "[", "name", "]", "_boundary", "=", "self", ".", "boundary", ".", "encode", "(", "\"utf-8\"", ")", "if", "isinstance", "(", "self", ".", "boundary", ",", "unicode", ")", "else", "urllib", ".", "quote_plus", "(", "self", ".", "boundary", ")", "headers", "=", "[", "\"--%s\"", "%", "_boundary", "]", "if", "is_file", ":", "disposition", "=", "'form-data; name=\"%s\"; filename=\"%s\"'", "%", "(", "name", ",", "os", ".", "path", ".", "basename", "(", "value", ")", ")", "else", ":", "disposition", "=", "'form-data; name=\"%s\"'", "%", "name", "headers", ".", "append", "(", "\"Content-Disposition: %s\"", "%", "disposition", ")", "if", "is_file", ":", "file_type", "=", "self", ".", "_file_type", "(", "name", ")", "else", ":", "file_type", "=", "\"text/plain; charset=utf-8\"", "headers", ".", "append", "(", "\"Content-Type: %s\"", "%", "file_type", ")", "if", "is_file", ":", "headers", ".", "append", "(", "\"Content-Length: %i\"", "%", "self", ".", "_file_size", "(", "name", ")", ")", "else", ":", "headers", ".", "append", "(", "\"Content-Length: %i\"", "%", "len", "(", "value", ")", ")", "headers", ".", "append", "(", "\"\"", ")", "headers", ".", "append", "(", "\"\"", ")", "return", "\"\\r\\n\"", ".", "join", "(", "headers", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer._boundary
Returns a random string to use as the boundary for a message. Returns: string. Boundary
pyfire/twistedx/producer.py
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, sha bits = random.getrandbits(160) boundary = sha.new(str(bits)).hexdigest() return 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, sha bits = random.getrandbits(160) boundary = sha.new(str(bits)).hexdigest() return boundary
[ "Returns", "a", "random", "string", "to", "use", "as", "the", "boundary", "for", "a", "message", ".", "Returns", ":", "string", ".", "Boundary" ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L241-L255
[ "def", "_boundary", "(", "self", ")", ":", "boundary", "=", "None", "try", ":", "import", "uuid", "boundary", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", "except", "ImportError", ":", "import", "random", ",", "sha", "bits", "=", "random", ".", "getrandbits", "(", "160", ")", "boundary", "=", "sha", ".", "new", "(", "str", "(", "bits", ")", ")", ".", "hexdigest", "(", ")", "return", "boundary" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer._file_type
Returns file type for given file field. Args: field (str): File field Returns: string. File type
pyfire/twistedx/producer.py
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, unicode) else str(type)
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, unicode) else str(type)
[ "Returns", "file", "type", "for", "given", "file", "field", ".", "Args", ":", "field", "(", "str", ")", ":", "File", "field" ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L257-L267
[ "def", "_file_type", "(", "self", ",", "field", ")", ":", "type", "=", "mimetypes", ".", "guess_type", "(", "self", ".", "_files", "[", "field", "]", ")", "[", "0", "]", "return", "type", ".", "encode", "(", "\"utf-8\"", ")", "if", "isinstance", "(", "type", ",", "unicode", ")", "else", "str", "(", "type", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
MultiPartProducer._file_size
Returns the file size for given file field. Args: field (str): File field Returns: int. File size
pyfire/twistedx/producer.py
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()).st_size handle.close() except: size = 0 self._file_lengths[field] = size return self._file_lengths[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()).st_size handle.close() except: size = 0 self._file_lengths[field] = size return self._file_lengths[field]
[ "Returns", "the", "file", "size", "for", "given", "file", "field", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L269-L286
[ "def", "_file_size", "(", "self", ",", "field", ")", ":", "size", "=", "0", "try", ":", "handle", "=", "open", "(", "self", ".", "_files", "[", "field", "]", ",", "\"r\"", ")", "size", "=", "os", ".", "fstat", "(", "handle", ".", "fileno", "(", ")", ")", ".", "st_size", "handle", ".", "close", "(", ")", "except", ":", "size", "=", "0", "self", ".", "_file_lengths", "[", "field", "]", "=", "size", "return", "self", ".", "_file_lengths", "[", "field", "]" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
_filename
Generate a path value of type result_type. result_type can either be bytes or text_type
hypothesis_fspaths.py
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) if os.name == 'nt': # pragma: no cover # Windows paths can contain all surrogates and even surrogate pairs # if two paths are concatenated. This makes it more likely for them to # be generated. surrogate = characters( min_codepoint=0xD800, max_codepoint=0xDFFF) uni_char = characters(min_codepoint=0x1) text_strategy = text( alphabet=one_of(uni_char, surrogate, ascii_char)) def text_to_bytes(path): fs_enc = sys.getfilesystemencoding() try: return path.encode(fs_enc, 'surrogatepass') except UnicodeEncodeError: return path.encode(fs_enc, 'replace') bytes_strategy = text_strategy.map(text_to_bytes) else: latin_char = characters(min_codepoint=0x01, max_codepoint=0xff) bytes_strategy = text(alphabet=one_of(latin_char, ascii_char)).map( lambda t: t.encode('latin-1')) unix_path_text = bytes_strategy.map( lambda b: b.decode( sys.getfilesystemencoding(), 'surrogateescape' if PY3 else 'ignore')) # Two surrogates generated through surrogateescape can generate # a valid utf-8 sequence when encoded and result in a different # code point when decoded again. Can happen when two paths get # concatenated. Shuffling makes it possible to generate such a case. text_strategy = permutations(draw(unix_path_text)).map(u"".join) if result_type is None: return draw(one_of(bytes_strategy, text_strategy)) elif result_type is bytes: return draw(bytes_strategy) else: return draw(text_strategy)
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) if os.name == 'nt': # pragma: no cover # Windows paths can contain all surrogates and even surrogate pairs # if two paths are concatenated. This makes it more likely for them to # be generated. surrogate = characters( min_codepoint=0xD800, max_codepoint=0xDFFF) uni_char = characters(min_codepoint=0x1) text_strategy = text( alphabet=one_of(uni_char, surrogate, ascii_char)) def text_to_bytes(path): fs_enc = sys.getfilesystemencoding() try: return path.encode(fs_enc, 'surrogatepass') except UnicodeEncodeError: return path.encode(fs_enc, 'replace') bytes_strategy = text_strategy.map(text_to_bytes) else: latin_char = characters(min_codepoint=0x01, max_codepoint=0xff) bytes_strategy = text(alphabet=one_of(latin_char, ascii_char)).map( lambda t: t.encode('latin-1')) unix_path_text = bytes_strategy.map( lambda b: b.decode( sys.getfilesystemencoding(), 'surrogateescape' if PY3 else 'ignore')) # Two surrogates generated through surrogateescape can generate # a valid utf-8 sequence when encoded and result in a different # code point when decoded again. Can happen when two paths get # concatenated. Shuffling makes it possible to generate such a case. text_strategy = permutations(draw(unix_path_text)).map(u"".join) if result_type is None: return draw(one_of(bytes_strategy, text_strategy)) elif result_type is bytes: return draw(bytes_strategy) else: return draw(text_strategy)
[ "Generate", "a", "path", "value", "of", "type", "result_type", "." ]
lazka/hypothesis-fspaths
python
https://github.com/lazka/hypothesis-fspaths/blob/19edb40a91ae4055bccf125a1e0b1796fa2e6a5c/hypothesis_fspaths.py#L53-L101
[ "def", "_filename", "(", "draw", ",", "result_type", "=", "None", ")", ":", "# 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", ")", "if", "os", ".", "name", "==", "'nt'", ":", "# pragma: no cover", "# Windows paths can contain all surrogates and even surrogate pairs", "# if two paths are concatenated. This makes it more likely for them to", "# be generated.", "surrogate", "=", "characters", "(", "min_codepoint", "=", "0xD800", ",", "max_codepoint", "=", "0xDFFF", ")", "uni_char", "=", "characters", "(", "min_codepoint", "=", "0x1", ")", "text_strategy", "=", "text", "(", "alphabet", "=", "one_of", "(", "uni_char", ",", "surrogate", ",", "ascii_char", ")", ")", "def", "text_to_bytes", "(", "path", ")", ":", "fs_enc", "=", "sys", ".", "getfilesystemencoding", "(", ")", "try", ":", "return", "path", ".", "encode", "(", "fs_enc", ",", "'surrogatepass'", ")", "except", "UnicodeEncodeError", ":", "return", "path", ".", "encode", "(", "fs_enc", ",", "'replace'", ")", "bytes_strategy", "=", "text_strategy", ".", "map", "(", "text_to_bytes", ")", "else", ":", "latin_char", "=", "characters", "(", "min_codepoint", "=", "0x01", ",", "max_codepoint", "=", "0xff", ")", "bytes_strategy", "=", "text", "(", "alphabet", "=", "one_of", "(", "latin_char", ",", "ascii_char", ")", ")", ".", "map", "(", "lambda", "t", ":", "t", ".", "encode", "(", "'latin-1'", ")", ")", "unix_path_text", "=", "bytes_strategy", ".", "map", "(", "lambda", "b", ":", "b", ".", "decode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ",", "'surrogateescape'", "if", "PY3", "else", "'ignore'", ")", ")", "# Two surrogates generated through surrogateescape can generate", "# a valid utf-8 sequence when encoded and result in a different", "# code point when decoded again. Can happen when two paths get", "# concatenated. Shuffling makes it possible to generate such a case.", "text_strategy", "=", "permutations", "(", "draw", "(", "unix_path_text", ")", ")", ".", "map", "(", "u\"\"", ".", "join", ")", "if", "result_type", "is", "None", ":", "return", "draw", "(", "one_of", "(", "bytes_strategy", ",", "text_strategy", ")", ")", "elif", "result_type", "is", "bytes", ":", "return", "draw", "(", "bytes_strategy", ")", "else", ":", "return", "draw", "(", "text_strategy", ")" ]
19edb40a91ae4055bccf125a1e0b1796fa2e6a5c
valid
_str_to_path
Given an ASCII str, returns a path of the given type.
hypothesis_fspaths.py
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') return s
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') return s
[ "Given", "an", "ASCII", "str", "returns", "a", "path", "of", "the", "given", "type", "." ]
lazka/hypothesis-fspaths
python
https://github.com/lazka/hypothesis-fspaths/blob/19edb40a91ae4055bccf125a1e0b1796fa2e6a5c/hypothesis_fspaths.py#L104-L112
[ "def", "_str_to_path", "(", "s", ",", "result_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'", ")", "return", "s" ]
19edb40a91ae4055bccf125a1e0b1796fa2e6a5c
valid
_path_root
Generates a root component for a path.
hypothesis_fspaths.py
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(tp) name = _filename(result_type) char = characters(min_codepoint=ord("A"), max_codepoint=ord("z")).map( lambda c: tp(str(c))) relative = sep # [drive_letter]:\ drive = builds(lambda *x: tp().join(x), char, just(tp(':')), sep) # \\?\[drive_spec]:\ extended = builds( lambda *x: tp().join(x), sep, sep, just(tp('?')), sep, drive) network = one_of([ # \\[server]\[sharename]\ builds(lambda *x: tp().join(x), sep, sep, name, sep, name, sep), # \\?\[server]\[sharename]\ builds(lambda *x: tp().join(x), sep, sep, just(tp('?')), sep, name, sep, name, sep), # \\?\UNC\[server]\[sharename]\ builds(lambda *x: tp().join(x), sep, sep, just(tp('?')), sep, just(tp('UNC')), sep, name, sep, name, sep), # \\.\[physical_device]\ builds(lambda *x: tp().join(x), sep, sep, just(tp('.')), sep, name, sep), ]) final = one_of(relative, drive, extended, network) return draw(final)
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(tp) name = _filename(result_type) char = characters(min_codepoint=ord("A"), max_codepoint=ord("z")).map( lambda c: tp(str(c))) relative = sep # [drive_letter]:\ drive = builds(lambda *x: tp().join(x), char, just(tp(':')), sep) # \\?\[drive_spec]:\ extended = builds( lambda *x: tp().join(x), sep, sep, just(tp('?')), sep, drive) network = one_of([ # \\[server]\[sharename]\ builds(lambda *x: tp().join(x), sep, sep, name, sep, name, sep), # \\?\[server]\[sharename]\ builds(lambda *x: tp().join(x), sep, sep, just(tp('?')), sep, name, sep, name, sep), # \\?\UNC\[server]\[sharename]\ builds(lambda *x: tp().join(x), sep, sep, just(tp('?')), sep, just(tp('UNC')), sep, name, sep, name, sep), # \\.\[physical_device]\ builds(lambda *x: tp().join(x), sep, sep, just(tp('.')), sep, name, sep), ]) final = one_of(relative, drive, extended, network) return draw(final)
[ "Generates", "a", "root", "component", "for", "a", "path", "." ]
lazka/hypothesis-fspaths
python
https://github.com/lazka/hypothesis-fspaths/blob/19edb40a91ae4055bccf125a1e0b1796fa2e6a5c/hypothesis_fspaths.py#L116-L156
[ "def", "_path_root", "(", "draw", ",", "result_type", ")", ":", "# 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", "(", "tp", ")", "name", "=", "_filename", "(", "result_type", ")", "char", "=", "characters", "(", "min_codepoint", "=", "ord", "(", "\"A\"", ")", ",", "max_codepoint", "=", "ord", "(", "\"z\"", ")", ")", ".", "map", "(", "lambda", "c", ":", "tp", "(", "str", "(", "c", ")", ")", ")", "relative", "=", "sep", "# [drive_letter]:\\", "drive", "=", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "char", ",", "just", "(", "tp", "(", "':'", ")", ")", ",", "sep", ")", "# \\\\?\\[drive_spec]:\\", "extended", "=", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "just", "(", "tp", "(", "'?'", ")", ")", ",", "sep", ",", "drive", ")", "network", "=", "one_of", "(", "[", "# \\\\[server]\\[sharename]\\", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "name", ",", "sep", ",", "name", ",", "sep", ")", ",", "# \\\\?\\[server]\\[sharename]\\", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "just", "(", "tp", "(", "'?'", ")", ")", ",", "sep", ",", "name", ",", "sep", ",", "name", ",", "sep", ")", ",", "# \\\\?\\UNC\\[server]\\[sharename]\\", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "just", "(", "tp", "(", "'?'", ")", ")", ",", "sep", ",", "just", "(", "tp", "(", "'UNC'", ")", ")", ",", "sep", ",", "name", ",", "sep", ",", "name", ",", "sep", ")", ",", "# \\\\.\\[physical_device]\\", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "sep", ",", "sep", ",", "just", "(", "tp", "(", "'.'", ")", ")", ",", "sep", ",", "name", ",", "sep", ")", ",", "]", ")", "final", "=", "one_of", "(", "relative", ",", "drive", ",", "extended", ",", "network", ")", "return", "draw", "(", "final", ")" ]
19edb40a91ae4055bccf125a1e0b1796fa2e6a5c
valid
fspaths
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 returned values depends on the operating system, the Python version, and the filesystem encoding as returned by :func:`sys.getfilesystemencoding`. :param allow_pathlike: If :obj:`python:None` makes the strategy include objects implementing the :class:`python:os.PathLike` interface when Python >= 3.6 is used. If :obj:`python:False` no pathlike objects will be generated. If :obj:`python:True` pathlike will be generated (Python >= 3.6 required) :type allow_pathlike: :obj:`python:bool` or :obj:`python:None` .. versionadded:: 3.15
hypothesis_fspaths.py
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 returned values depends on the operating system, the Python version, and the filesystem encoding as returned by :func:`sys.getfilesystemencoding`. :param allow_pathlike: If :obj:`python:None` makes the strategy include objects implementing the :class:`python:os.PathLike` interface when Python >= 3.6 is used. If :obj:`python:False` no pathlike objects will be generated. If :obj:`python:True` pathlike will be generated (Python >= 3.6 required) :type allow_pathlike: :obj:`python:bool` or :obj:`python:None` .. versionadded:: 3.15 """ has_pathlike = hasattr(os, 'PathLike') if allow_pathlike is None: allow_pathlike = has_pathlike if allow_pathlike and not has_pathlike: raise InvalidArgument( 'allow_pathlike: os.PathLike not supported, use None instead ' 'to enable it only when available') result_type = draw(sampled_from([bytes, text_type])) def tp(s=''): return _str_to_path(s, result_type) special_component = sampled_from([tp(os.curdir), tp(os.pardir)]) normal_component = _filename(result_type) path_component = one_of(normal_component, special_component) extension = normal_component.map(lambda f: tp(os.extsep) + f) root = _path_root(result_type) def optional(st): return one_of(st, just(result_type())) sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp) path_part = builds(lambda s, l: s.join(l), sep, lists(path_component)) main_strategy = builds(lambda *x: tp().join(x), optional(root), path_part, optional(extension)) if allow_pathlike and hasattr(os, 'fspath'): pathlike_strategy = main_strategy.map(lambda p: _PathLike(p)) main_strategy = one_of(main_strategy, pathlike_strategy) return draw(main_strategy)
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 returned values depends on the operating system, the Python version, and the filesystem encoding as returned by :func:`sys.getfilesystemencoding`. :param allow_pathlike: If :obj:`python:None` makes the strategy include objects implementing the :class:`python:os.PathLike` interface when Python >= 3.6 is used. If :obj:`python:False` no pathlike objects will be generated. If :obj:`python:True` pathlike will be generated (Python >= 3.6 required) :type allow_pathlike: :obj:`python:bool` or :obj:`python:None` .. versionadded:: 3.15 """ has_pathlike = hasattr(os, 'PathLike') if allow_pathlike is None: allow_pathlike = has_pathlike if allow_pathlike and not has_pathlike: raise InvalidArgument( 'allow_pathlike: os.PathLike not supported, use None instead ' 'to enable it only when available') result_type = draw(sampled_from([bytes, text_type])) def tp(s=''): return _str_to_path(s, result_type) special_component = sampled_from([tp(os.curdir), tp(os.pardir)]) normal_component = _filename(result_type) path_component = one_of(normal_component, special_component) extension = normal_component.map(lambda f: tp(os.extsep) + f) root = _path_root(result_type) def optional(st): return one_of(st, just(result_type())) sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp) path_part = builds(lambda s, l: s.join(l), sep, lists(path_component)) main_strategy = builds(lambda *x: tp().join(x), optional(root), path_part, optional(extension)) if allow_pathlike and hasattr(os, 'fspath'): pathlike_strategy = main_strategy.map(lambda p: _PathLike(p)) main_strategy = one_of(main_strategy, pathlike_strategy) return draw(main_strategy)
[ "A", "strategy", "which", "generates", "filesystem", "path", "values", "." ]
lazka/hypothesis-fspaths
python
https://github.com/lazka/hypothesis-fspaths/blob/19edb40a91ae4055bccf125a1e0b1796fa2e6a5c/hypothesis_fspaths.py#L161-L215
[ "def", "fspaths", "(", "draw", ",", "allow_pathlike", "=", "None", ")", ":", "has_pathlike", "=", "hasattr", "(", "os", ",", "'PathLike'", ")", "if", "allow_pathlike", "is", "None", ":", "allow_pathlike", "=", "has_pathlike", "if", "allow_pathlike", "and", "not", "has_pathlike", ":", "raise", "InvalidArgument", "(", "'allow_pathlike: os.PathLike not supported, use None instead '", "'to enable it only when available'", ")", "result_type", "=", "draw", "(", "sampled_from", "(", "[", "bytes", ",", "text_type", "]", ")", ")", "def", "tp", "(", "s", "=", "''", ")", ":", "return", "_str_to_path", "(", "s", ",", "result_type", ")", "special_component", "=", "sampled_from", "(", "[", "tp", "(", "os", ".", "curdir", ")", ",", "tp", "(", "os", ".", "pardir", ")", "]", ")", "normal_component", "=", "_filename", "(", "result_type", ")", "path_component", "=", "one_of", "(", "normal_component", ",", "special_component", ")", "extension", "=", "normal_component", ".", "map", "(", "lambda", "f", ":", "tp", "(", "os", ".", "extsep", ")", "+", "f", ")", "root", "=", "_path_root", "(", "result_type", ")", "def", "optional", "(", "st", ")", ":", "return", "one_of", "(", "st", ",", "just", "(", "result_type", "(", ")", ")", ")", "sep", "=", "sampled_from", "(", "[", "os", ".", "sep", ",", "os", ".", "altsep", "or", "os", ".", "sep", "]", ")", ".", "map", "(", "tp", ")", "path_part", "=", "builds", "(", "lambda", "s", ",", "l", ":", "s", ".", "join", "(", "l", ")", ",", "sep", ",", "lists", "(", "path_component", ")", ")", "main_strategy", "=", "builds", "(", "lambda", "*", "x", ":", "tp", "(", ")", ".", "join", "(", "x", ")", ",", "optional", "(", "root", ")", ",", "path_part", ",", "optional", "(", "extension", ")", ")", "if", "allow_pathlike", "and", "hasattr", "(", "os", ",", "'fspath'", ")", ":", "pathlike_strategy", "=", "main_strategy", ".", "map", "(", "lambda", "p", ":", "_PathLike", "(", "p", ")", ")", "main_strategy", "=", "one_of", "(", "main_strategy", ",", "pathlike_strategy", ")", "return", "draw", "(", "main_strategy", ")" ]
19edb40a91ae4055bccf125a1e0b1796fa2e6a5c
valid
CodeBuilder._exec
exec compiled code
bustard/template.py
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
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
[ "exec", "compiled", "code" ]
mozillazg/bustard
python
https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/template.py#L54-L59
[ "def", "_exec", "(", "self", ",", "globals_dict", "=", "None", ")", ":", "globals_dict", "=", "globals_dict", "or", "{", "}", "globals_dict", ".", "setdefault", "(", "'__builtins__'", ",", "{", "}", ")", "exec", "(", "self", ".", "_code", ",", "globals_dict", ")", "return", "globals_dict" ]
bd7b47f3ba5440cf6ea026c8b633060fedeb80b7
valid
Template.handle_extends
replace all blocks in extends with current blocks
bustard/template.py
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, match.group('path')) with open(path, encoding='utf-8') as fp: return self.replace_blocks_in_extends(fp.read(), blocks) else: return None
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, match.group('path')) with open(path, encoding='utf-8') as fp: return self.replace_blocks_in_extends(fp.read(), blocks) else: return None
[ "replace", "all", "blocks", "in", "extends", "with", "current", "blocks" ]
mozillazg/bustard
python
https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/template.py#L267-L277
[ "def", "handle_extends", "(", "self", ",", "text", ")", ":", "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", ",", "match", ".", "group", "(", "'path'", ")", ")", "with", "open", "(", "path", ",", "encoding", "=", "'utf-8'", ")", "as", "fp", ":", "return", "self", ".", "replace_blocks_in_extends", "(", "fp", ".", "read", "(", ")", ",", "blocks", ")", "else", ":", "return", "None" ]
bd7b47f3ba5440cf6ea026c8b633060fedeb80b7
valid
Template.flush_buffer
flush all buffered string into code
bustard/template.py
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 = []
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 = []
[ "flush", "all", "buffered", "string", "into", "code" ]
mozillazg/bustard
python
https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/template.py#L306-L310
[ "def", "flush_buffer", "(", "self", ")", ":", "self", ".", "code_builder", ".", "add_line", "(", "'{0}.extend([{1}])'", ",", "self", ".", "result_var", ",", "','", ".", "join", "(", "self", ".", "buffered", ")", ")", "self", ".", "buffered", "=", "[", "]" ]
bd7b47f3ba5440cf6ea026c8b633060fedeb80b7
valid
Template.strip_token
{{ a }} -> a
bustard/template.py
def strip_token(self, text, start, end): """{{ a }} -> a""" text = text.replace(start, '', 1) text = text.replace(end, '', 1) return text
def strip_token(self, text, start, end): """{{ a }} -> a""" text = text.replace(start, '', 1) text = text.replace(end, '', 1) return text
[ "{{", "a", "}}", "-", ">", "a" ]
mozillazg/bustard
python
https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/template.py#L312-L316
[ "def", "strip_token", "(", "self", ",", "text", ",", "start", ",", "end", ")", ":", "text", "=", "text", ".", "replace", "(", "start", ",", "''", ",", "1", ")", "text", "=", "text", ".", "replace", "(", "end", ",", "''", ",", "1", ")", "return", "text" ]
bd7b47f3ba5440cf6ea026c8b633060fedeb80b7
valid
Upload.run
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()
pyfire/upload.py
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, self._room, queue, self._files) if self._data: process.add_data(self._data) process.start() if not process.is_alive(): return self._uploading = True done = False while not self._abort and not done: if not process.is_alive(): self._abort = True break messages = None try: data = queue.get() if not data: done = True if self._finished_callback: self._finished_callback() elif isinstance(data, tuple): sent, total = data if self._progress_callback: self._progress_callback(sent, total) else: self._abort = True if self._error_callback: self._error_callback(data, self._room) except Empty: time.sleep(0.5) self._uploading = False if self._abort and not process.is_alive() and self._error_callback: self._error_callback(Exception("Upload process was killed"), self._room) queue.close() if process.is_alive(): queue.close() process.terminate() process.join()
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, self._room, queue, self._files) if self._data: process.add_data(self._data) process.start() if not process.is_alive(): return self._uploading = True done = False while not self._abort and not done: if not process.is_alive(): self._abort = True break messages = None try: data = queue.get() if not data: done = True if self._finished_callback: self._finished_callback() elif isinstance(data, tuple): sent, total = data if self._progress_callback: self._progress_callback(sent, total) else: self._abort = True if self._error_callback: self._error_callback(data, self._room) except Empty: time.sleep(0.5) self._uploading = False if self._abort and not process.is_alive() and self._error_callback: self._error_callback(Exception("Upload process was killed"), self._room) queue.close() if process.is_alive(): queue.close() process.terminate() process.join()
[ "Called", "by", "the", "thread", "it", "runs", "the", "process", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/upload.py#L60-L110
[ "def", "run", "(", "self", ")", ":", "queue", "=", "Queue", "(", ")", "process", "=", "UploadProcess", "(", "self", ".", "_connection_settings", ",", "self", ".", "_room", ",", "queue", ",", "self", ".", "_files", ")", "if", "self", ".", "_data", ":", "process", ".", "add_data", "(", "self", ".", "_data", ")", "process", ".", "start", "(", ")", "if", "not", "process", ".", "is_alive", "(", ")", ":", "return", "self", ".", "_uploading", "=", "True", "done", "=", "False", "while", "not", "self", ".", "_abort", "and", "not", "done", ":", "if", "not", "process", ".", "is_alive", "(", ")", ":", "self", ".", "_abort", "=", "True", "break", "messages", "=", "None", "try", ":", "data", "=", "queue", ".", "get", "(", ")", "if", "not", "data", ":", "done", "=", "True", "if", "self", ".", "_finished_callback", ":", "self", ".", "_finished_callback", "(", ")", "elif", "isinstance", "(", "data", ",", "tuple", ")", ":", "sent", ",", "total", "=", "data", "if", "self", ".", "_progress_callback", ":", "self", ".", "_progress_callback", "(", "sent", ",", "total", ")", "else", ":", "self", ".", "_abort", "=", "True", "if", "self", ".", "_error_callback", ":", "self", ".", "_error_callback", "(", "data", ",", "self", ".", "_room", ")", "except", "Empty", ":", "time", ".", "sleep", "(", "0.5", ")", "self", ".", "_uploading", "=", "False", "if", "self", ".", "_abort", "and", "not", "process", ".", "is_alive", "(", ")", "and", "self", ".", "_error_callback", ":", "self", ".", "_error_callback", "(", "Exception", "(", "\"Upload process was killed\"", ")", ",", "self", ".", "_room", ")", "queue", ".", "close", "(", ")", "if", "process", ".", "is_alive", "(", ")", ":", "queue", ".", "close", "(", ")", "process", ".", "terminate", "(", ")", "process", ".", "join", "(", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
UploadProcess.add_data
Add POST data. Args: data (dict): key => value dictionary
pyfire/upload.py
def add_data(self, data): """ Add POST data. Args: data (dict): key => value dictionary """ if not self._data: self._data = {} self._data.update(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)
[ "Add", "POST", "data", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/upload.py#L134-L142
[ "def", "add_data", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "_data", ":", "self", ".", "_data", "=", "{", "}", "self", ".", "_data", ".", "update", "(", "data", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
UploadProcess.run
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()
pyfire/upload.py
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_deferred = defer.Deferred() producer_deferred.addCallback(self._request_finished) producer_deferred.addErrback(self._request_error) receiver_deferred = defer.Deferred() receiver_deferred.addCallback(self._response_finished) receiver_deferred.addErrback(self._response_error) self._producer = producer.MultiPartProducer( self._files, self._data, callback = self._request_progress, deferred = producer_deferred ) self._receiver = receiver.StringReceiver(receiver_deferred) headers = { 'Content-Type': "multipart/form-data; boundary=%s" % self._producer.boundary } self._reactor, request = self._connection.build_twisted_request( "POST", "room/%s/uploads" % self._room.id, extra_headers = headers, body_producer = self._producer ) request.addCallback(self._response) request.addErrback(self._shutdown) self._reactor.run()
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_deferred = defer.Deferred() producer_deferred.addCallback(self._request_finished) producer_deferred.addErrback(self._request_error) receiver_deferred = defer.Deferred() receiver_deferred.addCallback(self._response_finished) receiver_deferred.addErrback(self._response_error) self._producer = producer.MultiPartProducer( self._files, self._data, callback = self._request_progress, deferred = producer_deferred ) self._receiver = receiver.StringReceiver(receiver_deferred) headers = { 'Content-Type': "multipart/form-data; boundary=%s" % self._producer.boundary } self._reactor, request = self._connection.build_twisted_request( "POST", "room/%s/uploads" % self._room.id, extra_headers = headers, body_producer = self._producer ) request.addCallback(self._response) request.addErrback(self._shutdown) self._reactor.run()
[ "Called", "by", "the", "process", "it", "runs", "it", "." ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/upload.py#L144-L183
[ "def", "run", "(", "self", ")", ":", "producer_deferred", "=", "defer", ".", "Deferred", "(", ")", "producer_deferred", ".", "addCallback", "(", "self", ".", "_request_finished", ")", "producer_deferred", ".", "addErrback", "(", "self", ".", "_request_error", ")", "receiver_deferred", "=", "defer", ".", "Deferred", "(", ")", "receiver_deferred", ".", "addCallback", "(", "self", ".", "_response_finished", ")", "receiver_deferred", ".", "addErrback", "(", "self", ".", "_response_error", ")", "self", ".", "_producer", "=", "producer", ".", "MultiPartProducer", "(", "self", ".", "_files", ",", "self", ".", "_data", ",", "callback", "=", "self", ".", "_request_progress", ",", "deferred", "=", "producer_deferred", ")", "self", ".", "_receiver", "=", "receiver", ".", "StringReceiver", "(", "receiver_deferred", ")", "headers", "=", "{", "'Content-Type'", ":", "\"multipart/form-data; boundary=%s\"", "%", "self", ".", "_producer", ".", "boundary", "}", "self", ".", "_reactor", ",", "request", "=", "self", ".", "_connection", ".", "build_twisted_request", "(", "\"POST\"", ",", "\"room/%s/uploads\"", "%", "self", ".", "_room", ".", "id", ",", "extra_headers", "=", "headers", ",", "body_producer", "=", "self", ".", "_producer", ")", "request", ".", "addCallback", "(", "self", ".", "_response", ")", "request", ".", "addErrback", "(", "self", ".", "_shutdown", ")", "self", ".", "_reactor", ".", "run", "(", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
API.log_error
Given some error text it will log the text if self.log_errors is True :param text: Error text to log
tweebo_parser/api.py
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')
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')
[ "Given", "some", "error", "text", "it", "will", "log", "the", "text", "if", "self", ".", "log_errors", "is", "True" ]
apmoore1/tweebo_parser_python_api
python
https://github.com/apmoore1/tweebo_parser_python_api/blob/224be2570b8b2508d29771f5e5abe06e1889fd89/tweebo_parser/api.py#L47-L55
[ "def", "log_error", "(", "self", ",", "text", ":", "str", ")", "->", "None", ":", "if", "self", ".", "log_errors", ":", "with", "self", ".", "_log_fp", ".", "open", "(", "'a+'", ")", "as", "log_file", ":", "log_file", ".", "write", "(", "f'{text}\\n'", ")" ]
224be2570b8b2508d29771f5e5abe06e1889fd89
valid
API.parse_conll
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 0 does not require setting, main purpose is for recursion. :return: A list of CoNLL formated strings. :raises ServerError: Caused when the server is not running. :raises :py:class:`requests.exceptions.HTTPError`: Caused when the input texts is not formated correctly e.g. When you give it a String not a list of Strings. :raises :py:class:`json.JSONDecodeError`: Caused if after self.retries attempts to parse the data it cannot decode the data. :Example:
tweebo_parser/api.py
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 0 does not require setting, main purpose is for recursion. :return: A list of CoNLL formated strings. :raises ServerError: Caused when the server is not running. :raises :py:class:`requests.exceptions.HTTPError`: Caused when the input texts is not formated correctly e.g. When you give it a String not a list of Strings. :raises :py:class:`json.JSONDecodeError`: Caused if after self.retries attempts to parse the data it cannot decode the data. :Example: ''' post_data = {'texts': texts, 'output_type': 'conll'} try: response = requests.post(f'http://{self.hostname}:{self.port}', json=post_data, headers={'Connection': 'close'}) response.raise_for_status() except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as server_error: raise ServerError(server_error, self.hostname, self.port) except requests.exceptions.HTTPError as http_error: raise http_error else: try: return response.json() except json.JSONDecodeError as json_exception: if retry_count == self.retries: self.log_error(response.text) raise Exception('Json Decoding error cannot parse this ' f':\n{response.text}') return self.parse_conll(texts, retry_count + 1)
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 0 does not require setting, main purpose is for recursion. :return: A list of CoNLL formated strings. :raises ServerError: Caused when the server is not running. :raises :py:class:`requests.exceptions.HTTPError`: Caused when the input texts is not formated correctly e.g. When you give it a String not a list of Strings. :raises :py:class:`json.JSONDecodeError`: Caused if after self.retries attempts to parse the data it cannot decode the data. :Example: ''' post_data = {'texts': texts, 'output_type': 'conll'} try: response = requests.post(f'http://{self.hostname}:{self.port}', json=post_data, headers={'Connection': 'close'}) response.raise_for_status() except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as server_error: raise ServerError(server_error, self.hostname, self.port) except requests.exceptions.HTTPError as http_error: raise http_error else: try: return response.json() except json.JSONDecodeError as json_exception: if retry_count == self.retries: self.log_error(response.text) raise Exception('Json Decoding error cannot parse this ' f':\n{response.text}') return self.parse_conll(texts, retry_count + 1)
[ "Processes", "the", "texts", "using", "TweeboParse", "and", "returns", "them", "in", "CoNLL", "format", "." ]
apmoore1/tweebo_parser_python_api
python
https://github.com/apmoore1/tweebo_parser_python_api/blob/224be2570b8b2508d29771f5e5abe06e1889fd89/tweebo_parser/api.py#L57-L95
[ "def", "parse_conll", "(", "self", ",", "texts", ":", "List", "[", "str", "]", ",", "retry_count", ":", "int", "=", "0", ")", "->", "List", "[", "str", "]", ":", "post_data", "=", "{", "'texts'", ":", "texts", ",", "'output_type'", ":", "'conll'", "}", "try", ":", "response", "=", "requests", ".", "post", "(", "f'http://{self.hostname}:{self.port}'", ",", "json", "=", "post_data", ",", "headers", "=", "{", "'Connection'", ":", "'close'", "}", ")", "response", ".", "raise_for_status", "(", ")", "except", "(", "requests", ".", "exceptions", ".", "ConnectionError", ",", "requests", ".", "exceptions", ".", "Timeout", ")", "as", "server_error", ":", "raise", "ServerError", "(", "server_error", ",", "self", ".", "hostname", ",", "self", ".", "port", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "http_error", ":", "raise", "http_error", "else", ":", "try", ":", "return", "response", ".", "json", "(", ")", "except", "json", ".", "JSONDecodeError", "as", "json_exception", ":", "if", "retry_count", "==", "self", ".", "retries", ":", "self", ".", "log_error", "(", "response", ".", "text", ")", "raise", "Exception", "(", "'Json Decoding error cannot parse this '", "f':\\n{response.text}'", ")", "return", "self", ".", "parse_conll", "(", "texts", ",", "retry_count", "+", "1", ")" ]
224be2570b8b2508d29771f5e5abe06e1889fd89
valid
CampfireEntity.set_data
Set entity data Args: data (dict): Entity data datetime_fields (array): Fields that should be parsed as datetimes
pyfire/entity.py
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 data: data[field] = self._parse_datetime(data[field]) super(CampfireEntity, self).set_data(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 data: data[field] = self._parse_datetime(data[field]) super(CampfireEntity, self).set_data(data)
[ "Set", "entity", "data" ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/entity.py#L90-L102
[ "def", "set_data", "(", "self", ",", "data", "=", "{", "}", ",", "datetime_fields", "=", "[", "]", ")", ":", "if", "datetime_fields", ":", "for", "field", "in", "datetime_fields", ":", "if", "field", "in", "data", ":", "data", "[", "field", "]", "=", "self", ".", "_parse_datetime", "(", "data", "[", "field", "]", ")", "super", "(", "CampfireEntity", ",", "self", ")", ".", "set_data", "(", "data", ")" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
CampfireEntity._parse_datetime
Parses a datetime string from "YYYY/MM/DD HH:MM:SS +HHMM" format Args: value (str): String Returns: datetime. Datetime
pyfire/entity.py
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) if matches: value = re.sub(pattern, '', value) offset = datetime.timedelta(hours=int(matches.group(1))/100) return datetime.datetime.strptime(value, "%Y/%m/%d %H:%M:%S") - offset
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) if matches: value = re.sub(pattern, '', value) offset = datetime.timedelta(hours=int(matches.group(1))/100) return datetime.datetime.strptime(value, "%Y/%m/%d %H:%M:%S") - offset
[ "Parses", "a", "datetime", "string", "from", "YYYY", "/", "MM", "/", "DD", "HH", ":", "MM", ":", "SS", "+", "HHMM", "format" ]
mariano/pyfire
python
https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/entity.py#L104-L119
[ "def", "_parse_datetime", "(", "self", ",", "value", ")", ":", "offset", "=", "0", "pattern", "=", "r\"\\s+([+-]{1}\\d+)\\Z\"", "matches", "=", "re", ".", "search", "(", "pattern", ",", "value", ")", "if", "matches", ":", "value", "=", "re", ".", "sub", "(", "pattern", ",", "''", ",", "value", ")", "offset", "=", "datetime", ".", "timedelta", "(", "hours", "=", "int", "(", "matches", ".", "group", "(", "1", ")", ")", "/", "100", ")", "return", "datetime", ".", "datetime", ".", "strptime", "(", "value", ",", "\"%Y/%m/%d %H:%M:%S\"", ")", "-", "offset" ]
42e3490c138abc8e10f2e9f8f8f3b40240a80412
valid
validate_xml_text
validates XML text
lxmlx/validate.py
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))
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", "text" ]
innodatalabs/lxmlx
python
https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/validate.py#L54-L60
[ "def", "validate_xml_text", "(", "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", ")", ")" ]
d0514f62127e51378be4e0c8cea2622c9786f99f
valid
validate_xml_name
validates XML name
lxmlx/validate.py
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 starts with invalid character')
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 starts with invalid character')
[ "validates", "XML", "name" ]
innodatalabs/lxmlx
python
https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/validate.py#L91-L100
[ "def", "validate_xml_name", "(", "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 starts with invalid character'", ")" ]
d0514f62127e51378be4e0c8cea2622c9786f99f
valid
Vehicle.update
Update acceleration. Accounts for the importance and priority (order) of multiple behaviors.
kxg/misc/sprites.py
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 self.behaviors: acceleration, importance = behavior.update() weighted_acceleration = acceleration * importance """ if max_jerk >= weighted_acceleration.magnitude: max_jerk -= weighted_acceleration.magnitude total_acceleration += weighted_acceleration elif max_jerk > 0 and max_jerk < weighted_acceleration.magnitude: total_acceleration += weighted_acceleration.normal * max_jerk break else: break """ total_acceleration += weighted_acceleration self.acceleration = total_acceleration # Update position and velocity. Sprite.update(self, time) # Update facing direction. if self.velocity.magnitude > 0.0: self.facing = self.velocity.normal
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 self.behaviors: acceleration, importance = behavior.update() weighted_acceleration = acceleration * importance """ if max_jerk >= weighted_acceleration.magnitude: max_jerk -= weighted_acceleration.magnitude total_acceleration += weighted_acceleration elif max_jerk > 0 and max_jerk < weighted_acceleration.magnitude: total_acceleration += weighted_acceleration.normal * max_jerk break else: break """ total_acceleration += weighted_acceleration self.acceleration = total_acceleration # Update position and velocity. Sprite.update(self, time) # Update facing direction. if self.velocity.magnitude > 0.0: self.facing = self.velocity.normal
[ "Update", "acceleration", ".", "Accounts", "for", "the", "importance", "and", "priority", "(", "order", ")", "of", "multiple", "behaviors", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/misc/sprites.py#L113-L143
[ "def", "update", "(", "self", ",", "time", ")", ":", "# .... I feel this stuff could be done a lot better.", "total_acceleration", "=", "Vector", ".", "null", "(", ")", "max_jerk", "=", "self", ".", "max_acceleration", "for", "behavior", "in", "self", ".", "behaviors", ":", "acceleration", ",", "importance", "=", "behavior", ".", "update", "(", ")", "weighted_acceleration", "=", "acceleration", "*", "importance", "\"\"\" \n if max_jerk >= weighted_acceleration.magnitude:\n max_jerk -= weighted_acceleration.magnitude\n total_acceleration += weighted_acceleration\n elif max_jerk > 0 and max_jerk < weighted_acceleration.magnitude:\n total_acceleration += weighted_acceleration.normal * max_jerk\n break\n else:\n break \"\"\"", "total_acceleration", "+=", "weighted_acceleration", "self", ".", "acceleration", "=", "total_acceleration", "# Update position and velocity.", "Sprite", ".", "update", "(", "self", ",", "time", ")", "# Update facing direction.", "if", "self", ".", "velocity", ".", "magnitude", ">", "0.0", ":", "self", ".", "facing", "=", "self", ".", "velocity", ".", "normal" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
Flee.update
Calculate what the desired change in velocity is. delta_velocity = acceleration * delta_time Time will be dealt with by the sprite.
kxg/misc/sprites.py
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_position() desired_direction = target_position - sprite_position if 0.0 == self.los or desired_direction.magnitude <= self.los: try: desired_normal = desired_direction.normal except NullVectorError: desired_normal = Vector.null() desired_velocity = desired_normal * self.sprite.get_max_speed() delta_velocity = desired_velocity - self.sprite.get_velocity() self.last_delta_velocity = delta_velocity return delta_velocity, self.power
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_position() desired_direction = target_position - sprite_position if 0.0 == self.los or desired_direction.magnitude <= self.los: try: desired_normal = desired_direction.normal except NullVectorError: desired_normal = Vector.null() desired_velocity = desired_normal * self.sprite.get_max_speed() delta_velocity = desired_velocity - self.sprite.get_velocity() self.last_delta_velocity = delta_velocity return delta_velocity, self.power
[ "Calculate", "what", "the", "desired", "change", "in", "velocity", "is", ".", "delta_velocity", "=", "acceleration", "*", "delta_time", "Time", "will", "be", "dealt", "with", "by", "the", "sprite", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/misc/sprites.py#L223-L242
[ "def", "update", "(", "self", ")", ":", "delta_velocity", "=", "Vector", ".", "null", "(", ")", "target_position", "=", "self", ".", "target", ".", "get_position", "(", ")", "sprite_position", "=", "self", ".", "sprite", ".", "get_position", "(", ")", "desired_direction", "=", "target_position", "-", "sprite_position", "if", "0.0", "==", "self", ".", "los", "or", "desired_direction", ".", "magnitude", "<=", "self", ".", "los", ":", "try", ":", "desired_normal", "=", "desired_direction", ".", "normal", "except", "NullVectorError", ":", "desired_normal", "=", "Vector", ".", "null", "(", ")", "desired_velocity", "=", "desired_normal", "*", "self", ".", "sprite", ".", "get_max_speed", "(", ")", "delta_velocity", "=", "desired_velocity", "-", "self", ".", "sprite", ".", "get_velocity", "(", ")", "self", ".", "last_delta_velocity", "=", "delta_velocity", "return", "delta_velocity", ",", "self", ".", "power" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
GameStage.on_enter_stage
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.
kxg/theater.py
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(): self.forum.connect_everyone(self.world, self.actors) # 1. Setup the forum. self.forum.on_start_game() # 2. Setup the world. with self.world._unlock_temporarily(): self.world.on_start_game() # 3. Setup the actors. Because this is done after the forum and the # world have been setup, this signals to the actors that they can # send messages and query the game world as usual. num_players = len(self.actors) - 1 for actor in self.actors: actor.on_setup_gui(self.gui) for actor in self.actors: actor.on_start_game(num_players)
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(): self.forum.connect_everyone(self.world, self.actors) # 1. Setup the forum. self.forum.on_start_game() # 2. Setup the world. with self.world._unlock_temporarily(): self.world.on_start_game() # 3. Setup the actors. Because this is done after the forum and the # world have been setup, this signals to the actors that they can # send messages and query the game world as usual. num_players = len(self.actors) - 1 for actor in self.actors: actor.on_setup_gui(self.gui) for actor in self.actors: actor.on_start_game(num_players)
[ "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", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/theater.py#L169-L199
[ "def", "on_enter_stage", "(", "self", ")", ":", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "self", ".", "forum", ".", "connect_everyone", "(", "self", ".", "world", ",", "self", ".", "actors", ")", "# 1. Setup the forum.", "self", ".", "forum", ".", "on_start_game", "(", ")", "# 2. Setup the world.", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "self", ".", "world", ".", "on_start_game", "(", ")", "# 3. Setup the actors. Because this is done after the forum and the ", "# world have been setup, this signals to the actors that they can ", "# send messages and query the game world as usual.", "num_players", "=", "len", "(", "self", ".", "actors", ")", "-", "1", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "on_setup_gui", "(", "self", ".", "gui", ")", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "on_start_game", "(", "num_players", ")" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
GameStage.on_update_stage
Sequentially update the actors, the world, and the messaging system. The theater terminates once all of the actors indicate that they are done.
kxg/theater.py
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_game() with self.world._unlock_temporarily(): self.world.on_update_game(dt) if self.world.has_game_ended(): self.exit_stage()
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_game() with self.world._unlock_temporarily(): self.world.on_update_game(dt) if self.world.has_game_ended(): self.exit_stage()
[ "Sequentially", "update", "the", "actors", "the", "world", "and", "the", "messaging", "system", ".", "The", "theater", "terminates", "once", "all", "of", "the", "actors", "indicate", "that", "they", "are", "done", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/theater.py#L201-L216
[ "def", "on_update_stage", "(", "self", ",", "dt", ")", ":", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "on_update_game", "(", "dt", ")", "self", ".", "forum", ".", "on_update_game", "(", ")", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "self", ".", "world", ".", "on_update_game", "(", "dt", ")", "if", "self", ".", "world", ".", "has_game_ended", "(", ")", ":", "self", ".", "exit_stage", "(", ")" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
GameStage.on_exit_stage
Give the actors, the world, and the messaging system a chance to react to the end of the game.
kxg/theater.py
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 # trying to extract tokens from messages. self.forum.on_finish_game() # 2. Let the actors react to the end of the game. for actor in self.actors: actor.on_finish_game() # 3. Let the world react to the end of the game. with self.world._unlock_temporarily(): self.world.on_finish_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 # trying to extract tokens from messages. self.forum.on_finish_game() # 2. Let the actors react to the end of the game. for actor in self.actors: actor.on_finish_game() # 3. Let the world react to the end of the game. with self.world._unlock_temporarily(): self.world.on_finish_game()
[ "Give", "the", "actors", "the", "world", "and", "the", "messaging", "system", "a", "chance", "to", "react", "to", "the", "end", "of", "the", "game", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/theater.py#L218-L238
[ "def", "on_exit_stage", "(", "self", ")", ":", "# 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 ", "# trying to extract tokens from messages.", "self", ".", "forum", ".", "on_finish_game", "(", ")", "# 2. Let the actors react to the end of the game.", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "on_finish_game", "(", ")", "# 3. Let the world react to the end of the game.", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "self", ".", "world", ".", "on_finish_game", "(", ")" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
Message.tokens_referenced
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 add a token to the world or keeping a stale reference to a token after its been removed.
kxg/messages.py
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 information is used by the game engine to catch mistakes like forgetting to add a token to the world or keeping a stale reference to a token after its been removed. """ tokens = set() # Use the pickle machinery to find all the tokens contained at any # level of this message. When an object is being pickled, the Pickler # calls its persistent_id() method for each object it encounters. We # hijack this method to add every Token we encounter to a list. # This definitely feels like a hacky abuse of the pickle machinery, but # that notwithstanding this should be quite robust and quite fast. def persistent_id(obj): from .tokens import Token if isinstance(obj, Token): tokens.add(obj) # Recursively descend into tokens that haven't been assigned an # id yet, but not into tokens that have. return obj.id from pickle import Pickler from io import BytesIO # Use BytesIO to basically ignore the serialized data stream, since we # only care about visiting all the objects that would be pickled. pickler = Pickler(BytesIO()) pickler.persistent_id = persistent_id pickler.dump(self) return tokens
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 information is used by the game engine to catch mistakes like forgetting to add a token to the world or keeping a stale reference to a token after its been removed. """ tokens = set() # Use the pickle machinery to find all the tokens contained at any # level of this message. When an object is being pickled, the Pickler # calls its persistent_id() method for each object it encounters. We # hijack this method to add every Token we encounter to a list. # This definitely feels like a hacky abuse of the pickle machinery, but # that notwithstanding this should be quite robust and quite fast. def persistent_id(obj): from .tokens import Token if isinstance(obj, Token): tokens.add(obj) # Recursively descend into tokens that haven't been assigned an # id yet, but not into tokens that have. return obj.id from pickle import Pickler from io import BytesIO # Use BytesIO to basically ignore the serialized data stream, since we # only care about visiting all the objects that would be pickled. pickler = Pickler(BytesIO()) pickler.persistent_id = persistent_id pickler.dump(self) return tokens
[ "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", "add", "a", "token", "to", "the", "world", "or", "keeping", "a", "stale", "reference", "to", "a", "token", "after", "its", "been", "removed", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/messages.py#L52-L92
[ "def", "tokens_referenced", "(", "self", ")", ":", "tokens", "=", "set", "(", ")", "# Use the pickle machinery to find all the tokens contained at any ", "# level of this message. When an object is being pickled, the Pickler ", "# calls its persistent_id() method for each object it encounters. We ", "# hijack this method to add every Token we encounter to a list.", "# This definitely feels like a hacky abuse of the pickle machinery, but ", "# that notwithstanding this should be quite robust and quite fast.", "def", "persistent_id", "(", "obj", ")", ":", "from", ".", "tokens", "import", "Token", "if", "isinstance", "(", "obj", ",", "Token", ")", ":", "tokens", ".", "add", "(", "obj", ")", "# Recursively descend into tokens that haven't been assigned an ", "# id yet, but not into tokens that have.", "return", "obj", ".", "id", "from", "pickle", "import", "Pickler", "from", "io", "import", "BytesIO", "# Use BytesIO to basically ignore the serialized data stream, since we ", "# only care about visiting all the objects that would be pickled.", "pickler", "=", "Pickler", "(", "BytesIO", "(", ")", ")", "pickler", ".", "persistent_id", "=", "persistent_id", "pickler", ".", "dump", "(", "self", ")", "return", "tokens" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
DebugPanel.wrap_handler
Enable/Disable handler.
muffin_peewee/debugtoolbar.py
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))
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))
[ "Enable", "/", "Disable", "handler", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/debugtoolbar.py#L44-L47
[ "def", "wrap_handler", "(", "self", ",", "handler", ",", "context_switcher", ")", ":", "context_switcher", ".", "add_context_in", "(", "lambda", ":", "LOGGER", ".", "addHandler", "(", "self", ".", "handler", ")", ")", "context_switcher", ".", "add_context_out", "(", "lambda", ":", "LOGGER", ".", "removeHandler", "(", "self", ".", "handler", ")", ")" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
DebugPanel.render_vars
Template variables.
muffin_peewee/debugtoolbar.py
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 ] }
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 ] }
[ "Template", "variables", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/debugtoolbar.py#L59-L68
[ "def", "render_vars", "(", "self", ")", ":", "return", "{", "'records'", ":", "[", "{", "'message'", ":", "record", ".", "getMessage", "(", ")", ",", "'time'", ":", "dt", ".", "datetime", ".", "fromtimestamp", "(", "record", ".", "created", ")", ".", "strftime", "(", "'%H:%M:%S'", ")", ",", "}", "for", "record", "in", "self", ".", "handler", ".", "records", "]", "}" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
AIODatabase.init_async
Use when application is starting.
muffin_peewee/mpeewee.py
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()
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()
[ "Use", "when", "application", "is", "starting", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L89-L96
[ "def", "init_async", "(", "self", ",", "loop", "=", "None", ")", ":", "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", "(", ")" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
AIODatabase.async_connect
Catch a connection asyncrounosly.
muffin_peewee/mpeewee.py
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
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
[ "Catch", "a", "connection", "asyncrounosly", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L98-L106
[ "async", "def", "async_connect", "(", "self", ")", ":", "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" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
PooledAIODatabase.init_async
Initialize self.
muffin_peewee/mpeewee.py
def init_async(self, loop): """Initialize self.""" super(PooledAIODatabase, self).init_async(loop) self._waiters = collections.deque()
def init_async(self, loop): """Initialize self.""" super(PooledAIODatabase, self).init_async(loop) self._waiters = collections.deque()
[ "Initialize", "self", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L123-L126
[ "def", "init_async", "(", "self", ",", "loop", ")", ":", "super", "(", "PooledAIODatabase", ",", "self", ")", ".", "init_async", "(", "loop", ")", "self", ".", "_waiters", "=", "collections", ".", "deque", "(", ")" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
PooledAIODatabase.async_connect
Asyncronously wait for a connection from the pool.
muffin_peewee/mpeewee.py
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_connections): waiter = asyncio.Future(loop=self._loop) self._waiters.append(waiter) try: logger.debug('Wait for connection.') await waiter finally: self._waiters.remove(waiter) self.connect() return self._state.conn
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_connections): waiter = asyncio.Future(loop=self._loop) self._waiters.append(waiter) try: logger.debug('Wait for connection.') await waiter finally: self._waiters.remove(waiter) self.connect() return self._state.conn
[ "Asyncronously", "wait", "for", "a", "connection", "from", "the", "pool", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L128-L144
[ "async", "def", "async_connect", "(", "self", ")", ":", "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_connections", ")", ":", "waiter", "=", "asyncio", ".", "Future", "(", "loop", "=", "self", ".", "_loop", ")", "self", ".", "_waiters", ".", "append", "(", "waiter", ")", "try", ":", "logger", ".", "debug", "(", "'Wait for connection.'", ")", "await", "waiter", "finally", ":", "self", ".", "_waiters", ".", "remove", "(", "waiter", ")", "self", ".", "connect", "(", ")", "return", "self", ".", "_state", ".", "conn" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
PooledAIODatabase._close
Release waiters.
muffin_peewee/mpeewee.py
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
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
[ "Release", "waiters", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L146-L153
[ "def", "_close", "(", "self", ",", "conn", ")", ":", "super", "(", "PooledAIODatabase", ",", "self", ")", ".", "_close", "(", "conn", ")", "for", "waiter", "in", "self", ".", "_waiters", ":", "if", "not", "waiter", ".", "done", "(", ")", ":", "logger", ".", "debug", "(", "'Release a waiter'", ")", "waiter", ".", "set_result", "(", "True", ")", "break" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
ClientForum.receive_id_from_server
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 to see if such a factory has been received. If it hasn't, this method does not block and immediately returns False. If it has, this method returns True after saving the factory internally. At this point it is safe to enter the GameStage.
kxg/multiplayer.py
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 to see if such a factory has been received. If it hasn't, this method does not block and immediately returns False. If it has, this method returns True after saving the factory internally. At this point it is safe to enter the GameStage. """ for message in self.pipe.receive(): if isinstance(message, IdFactory): self.actor_id_factory = message return True return False
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 to see if such a factory has been received. If it hasn't, this method does not block and immediately returns False. If it has, this method returns True after saving the factory internally. At this point it is safe to enter the GameStage. """ for message in self.pipe.receive(): if isinstance(message, IdFactory): self.actor_id_factory = message return True return False
[ "Listen", "for", "an", "id", "from", "the", "server", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L18-L34
[ "def", "receive_id_from_server", "(", "self", ")", ":", "for", "message", "in", "self", ".", "pipe", ".", "receive", "(", ")", ":", "if", "isinstance", "(", "message", ",", "IdFactory", ")", ":", "self", ".", "actor_id_factory", "=", "message", "return", "True", "return", "False" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
ClientForum.execute_sync
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 decide to send it as usual in the interest of a smooth gameplay experience. When this happens, the server sends out an extra response providing the clients with the information they need to resync themselves.
kxg/multiplayer.py
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 decide to send it as usual in the interest of a smooth gameplay experience. When this happens, the server sends out an extra response providing the clients with the information they need to resync themselves. """ info("synchronizing message: {message}") # Synchronize the world. with self.world._unlock_temporarily(): message._sync(self.world) self.world._react_to_sync_response(message) # Synchronize the tokens. for actor in self.actors: actor._react_to_sync_response(message)
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 decide to send it as usual in the interest of a smooth gameplay experience. When this happens, the server sends out an extra response providing the clients with the information they need to resync themselves. """ info("synchronizing message: {message}") # Synchronize the world. with self.world._unlock_temporarily(): message._sync(self.world) self.world._react_to_sync_response(message) # Synchronize the tokens. for actor in self.actors: actor._react_to_sync_response(message)
[ "Respond", "when", "the", "server", "indicates", "that", "the", "client", "is", "out", "of", "sync", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L65-L87
[ "def", "execute_sync", "(", "self", ",", "message", ")", ":", "info", "(", "\"synchronizing message: {message}\"", ")", "# Synchronize the world.", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "message", ".", "_sync", "(", "self", ".", "world", ")", "self", ".", "world", ".", "_react_to_sync_response", "(", "message", ")", "# Synchronize the tokens.", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "_react_to_sync_response", "(", "message", ")" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
ClientForum.execute_undo
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 the message made to the world before being sent or crash. Note that unlike sync requests, undo requests are only reported to the client that sent the offending message.
kxg/multiplayer.py
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 the message made to the world before being sent or crash. Note that unlike sync requests, undo requests are only reported to the client that sent the offending message. """ info("undoing message: {message}") # Roll back changes that the original message made to the world. with self.world._unlock_temporarily(): message._undo(self.world) self.world._react_to_undo_response(message) # Give the actors a chance to react to the error. For example, a # GUI actor might inform the user that there are connectivity # issues and that their last action was countermanded. for actor in self.actors: actor._react_to_undo_response(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 the message made to the world before being sent or crash. Note that unlike sync requests, undo requests are only reported to the client that sent the offending message. """ info("undoing message: {message}") # Roll back changes that the original message made to the world. with self.world._unlock_temporarily(): message._undo(self.world) self.world._react_to_undo_response(message) # Give the actors a chance to react to the error. For example, a # GUI actor might inform the user that there are connectivity # issues and that their last action was countermanded. for actor in self.actors: actor._react_to_undo_response(message)
[ "Manage", "the", "response", "when", "the", "server", "rejects", "a", "message", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L89-L113
[ "def", "execute_undo", "(", "self", ",", "message", ")", ":", "info", "(", "\"undoing message: {message}\"", ")", "# Roll back changes that the original message made to the world.", "with", "self", ".", "world", ".", "_unlock_temporarily", "(", ")", ":", "message", ".", "_undo", "(", "self", ".", "world", ")", "self", ".", "world", ".", "_react_to_undo_response", "(", "message", ")", "# Give the actors a chance to react to the error. For example, a ", "# GUI actor might inform the user that there are connectivity ", "# issues and that their last action was countermanded.", "for", "actor", "in", "self", ".", "actors", ":", "actor", ".", "_react_to_undo_response", "(", "message", ")" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
ServerActor._relay_message
Relay messages from the forum on the server to the client represented by this actor.
kxg/multiplayer.py
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.deliver()
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.deliver()
[ "Relay", "messages", "from", "the", "forum", "on", "the", "server", "to", "the", "client", "represented", "by", "this", "actor", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L274-L283
[ "def", "_relay_message", "(", "self", ",", "message", ")", ":", "info", "(", "\"relaying message: {message}\"", ")", "if", "not", "message", ".", "was_sent_by", "(", "self", ".", "_id_factory", ")", ":", "self", ".", "pipe", ".", "send", "(", "message", ")", "self", ".", "pipe", ".", "deliver", "(", ")" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
generate
Create a new DataItem.
example/views.py
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('/')
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('/')
[ "Create", "a", "new", "DataItem", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/example/views.py#L22-L27
[ "def", "generate", "(", "request", ")", ":", "models", ".", "DataItem", ".", "create", "(", "content", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "for", "_", "in", "range", "(", "20", ")", ")", ")", "return", "muffin", ".", "HTTPFound", "(", "'/'", ")" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
require_active_token
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.
kxg/tokens.py
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 if not token.has_id: raise ApiUsageError("""\ token {token} should have an id, but doesn't. This error usually means that a token was added to the world without being assigned an id number. To correct this, make sure that you're using a message (i.e. CreateToken) to create all of your tokens.""") if not token.has_world: raise ApiUsageError("""\ token {token} (id={token.id}) not in world. You can get this error if you try to remove the same token from the world twice. This might happen is you don't get rid of every reference to a token after it's removed the first time, then later on you try to remove the stale reference.""")
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 if not token.has_id: raise ApiUsageError("""\ token {token} should have an id, but doesn't. This error usually means that a token was added to the world without being assigned an id number. To correct this, make sure that you're using a message (i.e. CreateToken) to create all of your tokens.""") if not token.has_world: raise ApiUsageError("""\ token {token} (id={token.id}) not in world. You can get this error if you try to remove the same token from the world twice. This might happen is you don't get rid of every reference to a token after it's removed the first time, then later on you try to remove the stale reference.""")
[ "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", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L564-L589
[ "def", "require_active_token", "(", "object", ")", ":", "require_token", "(", "object", ")", "token", "=", "object", "if", "not", "token", ".", "has_id", ":", "raise", "ApiUsageError", "(", "\"\"\"\\\n token {token} should have an id, but doesn't.\n\n This error usually means that a token was added to the world \n without being assigned an id number. To correct this, make \n sure that you're using a message (i.e. CreateToken) to create \n all of your tokens.\"\"\"", ")", "if", "not", "token", ".", "has_world", ":", "raise", "ApiUsageError", "(", "\"\"\"\\\n token {token} (id={token.id}) not in world.\n\n You can get this error if you try to remove the same token from \n the world twice. This might happen is you don't get rid of \n every reference to a token after it's removed the first time, \n then later on you try to remove the stale reference.\"\"\"", ")" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
TokenSafetyChecks.add_safety_checks
Iterate through each member of the class being created and add a safety check to every method that isn't marked as read-only.
kxg/tokens.py
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( member_name, member_value)
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( member_name, member_value)
[ "Iterate", "through", "each", "member", "of", "the", "class", "being", "created", "and", "add", "a", "safety", "check", "to", "every", "method", "that", "isn", "t", "marked", "as", "read", "-", "only", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L59-L66
[ "def", "add_safety_checks", "(", "meta", ",", "members", ")", ":", "for", "member_name", ",", "member_value", "in", "members", ".", "items", "(", ")", ":", "members", "[", "member_name", "]", "=", "meta", ".", "add_safety_check", "(", "member_name", ",", "member_value", ")" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
TokenSafetyChecks.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.
kxg/tokens.py
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 methods that alter the token are only called from update methods or messages. """ import functools from types import FunctionType # Bail if the given member is read-only, private, or not a method. is_method = isinstance(member_value, FunctionType) is_read_only = hasattr(member_value, '_kxg_read_only') is_private = member_name.startswith('_') if not is_method or is_read_only or is_private: return member_value def safety_checked_method(self, *args, **kwargs): """ Make sure that the token the world is locked before a non-read-only method is called. """ # Because these checks are pretty magical, I want to be really # careful to avoid raising any exceptions other than the check # itself (which comes with a very clear error message). Here, that # means using getattr() to make sure the world attribute actually # exists. For example, there's nothing wrong with the following # code, but it does call a safety-checked method before the world # attribute is defined: # # class MyToken(kxg.Token): # def __init__(self): # self.init_helper() # super().__init__() world = getattr(self, 'world', None) if world and world.is_locked(): nonlocal member_name raise ApiUsageError("""\ attempted unsafe invocation of {self.__class__.__name__}.{member_name}(). This error brings attention to situations that might cause synchronization issues in multiplayer games. The {member_name}() method is not marked as read-only, but it was invoked from outside the context of a message. This means that if {member_name}() makes any changes to the world, those changes will not be propagated. If {member_name}() is actually read-only, label it with the @kxg.read_only decorator.""") # After making that check, call the method as usual. return member_value(self, *args, **kwargs) # Preserve any "forum observer" decorations that have been placed on # the method and restore the method's original name and module strings, # to make inspection and debugging a little easier. functools.update_wrapper( safety_checked_method, member_value, assigned=functools.WRAPPER_ASSIGNMENTS + ( '_kxg_subscribe_to_message', '_kxg_subscribe_to_sync_response', '_kxg_subscribe_to_undo_response', ) ) return safety_checked_method
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 methods that alter the token are only called from update methods or messages. """ import functools from types import FunctionType # Bail if the given member is read-only, private, or not a method. is_method = isinstance(member_value, FunctionType) is_read_only = hasattr(member_value, '_kxg_read_only') is_private = member_name.startswith('_') if not is_method or is_read_only or is_private: return member_value def safety_checked_method(self, *args, **kwargs): """ Make sure that the token the world is locked before a non-read-only method is called. """ # Because these checks are pretty magical, I want to be really # careful to avoid raising any exceptions other than the check # itself (which comes with a very clear error message). Here, that # means using getattr() to make sure the world attribute actually # exists. For example, there's nothing wrong with the following # code, but it does call a safety-checked method before the world # attribute is defined: # # class MyToken(kxg.Token): # def __init__(self): # self.init_helper() # super().__init__() world = getattr(self, 'world', None) if world and world.is_locked(): nonlocal member_name raise ApiUsageError("""\ attempted unsafe invocation of {self.__class__.__name__}.{member_name}(). This error brings attention to situations that might cause synchronization issues in multiplayer games. The {member_name}() method is not marked as read-only, but it was invoked from outside the context of a message. This means that if {member_name}() makes any changes to the world, those changes will not be propagated. If {member_name}() is actually read-only, label it with the @kxg.read_only decorator.""") # After making that check, call the method as usual. return member_value(self, *args, **kwargs) # Preserve any "forum observer" decorations that have been placed on # the method and restore the method's original name and module strings, # to make inspection and debugging a little easier. functools.update_wrapper( safety_checked_method, member_value, assigned=functools.WRAPPER_ASSIGNMENTS + ( '_kxg_subscribe_to_message', '_kxg_subscribe_to_sync_response', '_kxg_subscribe_to_undo_response', ) ) return safety_checked_method
[ "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", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L69-L139
[ "def", "add_safety_check", "(", "member_name", ",", "member_value", ")", ":", "import", "functools", "from", "types", "import", "FunctionType", "# Bail if the given member is read-only, private, or not a method.", "is_method", "=", "isinstance", "(", "member_value", ",", "FunctionType", ")", "is_read_only", "=", "hasattr", "(", "member_value", ",", "'_kxg_read_only'", ")", "is_private", "=", "member_name", ".", "startswith", "(", "'_'", ")", "if", "not", "is_method", "or", "is_read_only", "or", "is_private", ":", "return", "member_value", "def", "safety_checked_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Make sure that the token the world is locked before a non-read-only \n method is called.\n \"\"\"", "# Because these checks are pretty magical, I want to be really ", "# careful to avoid raising any exceptions other than the check ", "# itself (which comes with a very clear error message). Here, that ", "# means using getattr() to make sure the world attribute actually ", "# exists. For example, there's nothing wrong with the following ", "# code, but it does call a safety-checked method before the world ", "# attribute is defined:", "#", "# class MyToken(kxg.Token):", "# def __init__(self):", "# self.init_helper()", "# super().__init__()", "world", "=", "getattr", "(", "self", ",", "'world'", ",", "None", ")", "if", "world", "and", "world", ".", "is_locked", "(", ")", ":", "nonlocal", "member_name", "raise", "ApiUsageError", "(", "\"\"\"\\\n attempted unsafe invocation of \n {self.__class__.__name__}.{member_name}().\n\n This error brings attention to situations that might \n cause synchronization issues in multiplayer games. The \n {member_name}() method is not marked as read-only, but \n it was invoked from outside the context of a message. \n This means that if {member_name}() makes any changes to \n the world, those changes will not be propagated. If \n {member_name}() is actually read-only, label it with \n the @kxg.read_only decorator.\"\"\"", ")", "# After making that check, call the method as usual.", "return", "member_value", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Preserve any \"forum observer\" decorations that have been placed on ", "# the method and restore the method's original name and module strings, ", "# to make inspection and debugging a little easier.", "functools", ".", "update_wrapper", "(", "safety_checked_method", ",", "member_value", ",", "assigned", "=", "functools", ".", "WRAPPER_ASSIGNMENTS", "+", "(", "'_kxg_subscribe_to_message'", ",", "'_kxg_subscribe_to_sync_response'", ",", "'_kxg_subscribe_to_undo_response'", ",", ")", ")", "return", "safety_checked_method" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
Token.watch_method
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.
kxg/tokens.py
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 token method with the given name exists, and complain if # nothing is found. try: method = getattr(self, method_name) except AttributeError: raise ApiUsageError("""\ {self.__class__.__name__} has no such method {method_name}() to watch. This error usually means that you used the @watch_token decorator on a method of a token extension class that didn't match the name of any method in the corresponding token class. Check for typos.""") # Wrap the method in a WatchedMethod object, if that hasn't already # been done. This object manages a list of callback method and takes # responsibility for calling them after the method itself has been # called. if not isinstance(method, Token.WatchedMethod): setattr(self, method_name, Token.WatchedMethod(method)) method = getattr(self, method_name) # Add the given callback to the watched method. method.add_watcher(callback)
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 token method with the given name exists, and complain if # nothing is found. try: method = getattr(self, method_name) except AttributeError: raise ApiUsageError("""\ {self.__class__.__name__} has no such method {method_name}() to watch. This error usually means that you used the @watch_token decorator on a method of a token extension class that didn't match the name of any method in the corresponding token class. Check for typos.""") # Wrap the method in a WatchedMethod object, if that hasn't already # been done. This object manages a list of callback method and takes # responsibility for calling them after the method itself has been # called. if not isinstance(method, Token.WatchedMethod): setattr(self, method_name, Token.WatchedMethod(method)) method = getattr(self, method_name) # Add the given callback to the watched method. method.add_watcher(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" ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L246-L279
[ "def", "watch_method", "(", "self", ",", "method_name", ",", "callback", ")", ":", "# Make sure a token method with the given name exists, and complain if ", "# nothing is found.", "try", ":", "method", "=", "getattr", "(", "self", ",", "method_name", ")", "except", "AttributeError", ":", "raise", "ApiUsageError", "(", "\"\"\"\\\n {self.__class__.__name__} has no such method \n {method_name}() to watch.\n\n This error usually means that you used the @watch_token \n decorator on a method of a token extension class that \n didn't match the name of any method in the corresponding \n token class. Check for typos.\"\"\"", ")", "# Wrap the method in a WatchedMethod object, if that hasn't already ", "# been done. This object manages a list of callback method and takes ", "# responsibility for calling them after the method itself has been ", "# called.", "if", "not", "isinstance", "(", "method", ",", "Token", ".", "WatchedMethod", ")", ":", "setattr", "(", "self", ",", "method_name", ",", "Token", ".", "WatchedMethod", "(", "method", ")", ")", "method", "=", "getattr", "(", "self", ",", "method_name", ")", "# Add the given callback to the watched method.", "method", ".", "add_watcher", "(", "callback", ")" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
Token._remove_from_world
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 the internal state of the token being removed.
kxg/tokens.py
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 the internal state of the token being removed. """ self.on_remove_from_world() self._extensions = {} self._disable_forum_observation() self._world = None self._id = None
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 the internal state of the token being removed. """ self.on_remove_from_world() self._extensions = {} self._disable_forum_observation() self._world = None self._id = None
[ "Clear", "all", "the", "internal", "data", "the", "token", "needed", "while", "it", "was", "part", "of", "the", "world", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L383-L396
[ "def", "_remove_from_world", "(", "self", ")", ":", "self", ".", "on_remove_from_world", "(", ")", "self", ".", "_extensions", "=", "{", "}", "self", ".", "_disable_forum_observation", "(", ")", "self", ".", "_world", "=", "None", "self", ".", "_id", "=", "None" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
World._unlock_temporarily
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 catch and prevent these kinds of errors, the game engine keeps the world locked most of the time and only briefly unlocks it (using this method) when tokens are allowed to make changes. When the world is locked, token methods that aren't marked as being read-only can't be called. When the world is unlocked, any token method can be called. These checks can be disabled by running python with optimization enabled. You should never call this method manually from within your own game. This method is intended to be used by the game engine, which was carefully designed to allow the world to be modified only when safe. Calling this method yourself disables an important safety check.
kxg/tokens.py
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 catch and prevent these kinds of errors, the game engine keeps the world locked most of the time and only briefly unlocks it (using this method) when tokens are allowed to make changes. When the world is locked, token methods that aren't marked as being read-only can't be called. When the world is unlocked, any token method can be called. These checks can be disabled by running python with optimization enabled. You should never call this method manually from within your own game. This method is intended to be used by the game engine, which was carefully designed to allow the world to be modified only when safe. Calling this method yourself disables an important safety check. """ if not self._is_locked: yield else: try: self._is_locked = False yield finally: self._is_locked = True
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 catch and prevent these kinds of errors, the game engine keeps the world locked most of the time and only briefly unlocks it (using this method) when tokens are allowed to make changes. When the world is locked, token methods that aren't marked as being read-only can't be called. When the world is unlocked, any token method can be called. These checks can be disabled by running python with optimization enabled. You should never call this method manually from within your own game. This method is intended to be used by the game engine, which was carefully designed to allow the world to be modified only when safe. Calling this method yourself disables an important safety check. """ if not self._is_locked: yield else: try: self._is_locked = False yield finally: self._is_locked = True
[ "Allow", "tokens", "to", "modify", "the", "world", "for", "the", "duration", "of", "a", "with", "-", "block", "." ]
kxgames/kxg
python
https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/tokens.py#L488-L514
[ "def", "_unlock_temporarily", "(", "self", ")", ":", "if", "not", "self", ".", "_is_locked", ":", "yield", "else", ":", "try", ":", "self", ".", "_is_locked", "=", "False", "yield", "finally", ":", "self", ".", "_is_locked", "=", "True" ]
a68c01dc4aa1abf6b3780ba2c65a7828282566aa
valid
scan
Converts XML tree to event generator
lxmlx/event.py
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, 'target': xml.target} return obj = _elt2obj(xml) obj['type'] = ENTER yield obj assert type(xml.tag) is str, xml if xml.text: yield {'type': TEXT, 'text': xml.text} for c in xml: for x in scan(c): yield x if c.tail: yield {'type': TEXT, 'text': c.tail} yield {'type': EXIT}
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, 'target': xml.target} return obj = _elt2obj(xml) obj['type'] = ENTER yield obj assert type(xml.tag) is str, xml if xml.text: yield {'type': TEXT, 'text': xml.text} for c in xml: for x in scan(c): yield x if c.tail: yield {'type': TEXT, 'text': c.tail} yield {'type': EXIT}
[ "Converts", "XML", "tree", "to", "event", "generator" ]
innodatalabs/lxmlx
python
https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L32-L59
[ "def", "scan", "(", "xml", ")", ":", "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", ",", "'target'", ":", "xml", ".", "target", "}", "return", "obj", "=", "_elt2obj", "(", "xml", ")", "obj", "[", "'type'", "]", "=", "ENTER", "yield", "obj", "assert", "type", "(", "xml", ".", "tag", ")", "is", "str", ",", "xml", "if", "xml", ".", "text", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "xml", ".", "text", "}", "for", "c", "in", "xml", ":", "for", "x", "in", "scan", "(", "c", ")", ":", "yield", "x", "if", "c", ".", "tail", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "c", ".", "tail", "}", "yield", "{", "'type'", ":", "EXIT", "}" ]
d0514f62127e51378be4e0c8cea2622c9786f99f
valid
unscan
Converts events stream into lXML tree
lxmlx/event.py
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 root is not None: raise RuntimeError('Event stream tried to create second XML tree') else: root = elt stack.append(elt) last_closed_elt = None elif obj['type'] == EXIT: last_closed_elt = stack.pop() elif obj['type'] == COMMENT: elt = et.Comment(obj['text']) stack[-1].append(elt) elif obj['type'] == PI: elt = et.PI(obj['target']) if obj.get('text'): elt.text = obj['text'] stack[-1].append(elt) elif obj['type'] == TEXT: text = obj['text'] if text: if last_closed_elt is None: stack[-1].text = (stack[-1].text or '') + text else: last_closed_elt.tail = (last_closed_elt.tail or '') + text else: assert False, obj if root is None: raise RuntimeError('Empty XML event stream') return root
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 root is not None: raise RuntimeError('Event stream tried to create second XML tree') else: root = elt stack.append(elt) last_closed_elt = None elif obj['type'] == EXIT: last_closed_elt = stack.pop() elif obj['type'] == COMMENT: elt = et.Comment(obj['text']) stack[-1].append(elt) elif obj['type'] == PI: elt = et.PI(obj['target']) if obj.get('text'): elt.text = obj['text'] stack[-1].append(elt) elif obj['type'] == TEXT: text = obj['text'] if text: if last_closed_elt is None: stack[-1].text = (stack[-1].text or '') + text else: last_closed_elt.tail = (last_closed_elt.tail or '') + text else: assert False, obj if root is None: raise RuntimeError('Empty XML event stream') return root
[ "Converts", "events", "stream", "into", "lXML", "tree" ]
innodatalabs/lxmlx
python
https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L61-L106
[ "def", "unscan", "(", "events", ",", "nsmap", "=", "None", ")", ":", "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", "root", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'Event stream tried to create second XML tree'", ")", "else", ":", "root", "=", "elt", "stack", ".", "append", "(", "elt", ")", "last_closed_elt", "=", "None", "elif", "obj", "[", "'type'", "]", "==", "EXIT", ":", "last_closed_elt", "=", "stack", ".", "pop", "(", ")", "elif", "obj", "[", "'type'", "]", "==", "COMMENT", ":", "elt", "=", "et", ".", "Comment", "(", "obj", "[", "'text'", "]", ")", "stack", "[", "-", "1", "]", ".", "append", "(", "elt", ")", "elif", "obj", "[", "'type'", "]", "==", "PI", ":", "elt", "=", "et", ".", "PI", "(", "obj", "[", "'target'", "]", ")", "if", "obj", ".", "get", "(", "'text'", ")", ":", "elt", ".", "text", "=", "obj", "[", "'text'", "]", "stack", "[", "-", "1", "]", ".", "append", "(", "elt", ")", "elif", "obj", "[", "'type'", "]", "==", "TEXT", ":", "text", "=", "obj", "[", "'text'", "]", "if", "text", ":", "if", "last_closed_elt", "is", "None", ":", "stack", "[", "-", "1", "]", ".", "text", "=", "(", "stack", "[", "-", "1", "]", ".", "text", "or", "''", ")", "+", "text", "else", ":", "last_closed_elt", ".", "tail", "=", "(", "last_closed_elt", ".", "tail", "or", "''", ")", "+", "text", "else", ":", "assert", "False", ",", "obj", "if", "root", "is", "None", ":", "raise", "RuntimeError", "(", "'Empty XML event stream'", ")", "return", "root" ]
d0514f62127e51378be4e0c8cea2622c9786f99f
valid
parse
Parses file content into events stream
lxmlx/event.py
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: yield {'type': TEXT, 'text': elt.text} elif event == 'end': yield {'type': EXIT} if elt.tail: yield {'type': TEXT, 'text': elt.tail} elt.clear() elif event == 'comment': yield {'type': COMMENT, 'text': elt.text} elif event == 'pi': yield {'type': PI, 'text': elt.text} else: assert False, (event, elt)
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: yield {'type': TEXT, 'text': elt.text} elif event == 'end': yield {'type': EXIT} if elt.tail: yield {'type': TEXT, 'text': elt.tail} elt.clear() elif event == 'comment': yield {'type': COMMENT, 'text': elt.text} elif event == 'pi': yield {'type': PI, 'text': elt.text} else: assert False, (event, elt)
[ "Parses", "file", "content", "into", "events", "stream" ]
innodatalabs/lxmlx
python
https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L109-L128
[ "def", "parse", "(", "filename", ")", ":", "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", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "elt", ".", "text", "}", "elif", "event", "==", "'end'", ":", "yield", "{", "'type'", ":", "EXIT", "}", "if", "elt", ".", "tail", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "elt", ".", "tail", "}", "elt", ".", "clear", "(", ")", "elif", "event", "==", "'comment'", ":", "yield", "{", "'type'", ":", "COMMENT", ",", "'text'", ":", "elt", ".", "text", "}", "elif", "event", "==", "'pi'", ":", "yield", "{", "'type'", ":", "PI", ",", "'text'", ":", "elt", ".", "text", "}", "else", ":", "assert", "False", ",", "(", "event", ",", "elt", ")" ]
d0514f62127e51378be4e0c8cea2622c9786f99f
valid
subtree
selects sub-tree events
lxmlx/event.py
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
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
[ "selects", "sub", "-", "tree", "events" ]
innodatalabs/lxmlx
python
https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L130-L140
[ "def", "subtree", "(", "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" ]
d0514f62127e51378be4e0c8cea2622c9786f99f
valid
merge_text
merges each run of successive text events into one text event
lxmlx/event.py
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.clear() yield obj if text: yield {'type': TEXT, 'text': ''.join(text)}
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.clear() yield obj if text: yield {'type': TEXT, 'text': ''.join(text)}
[ "merges", "each", "run", "of", "successive", "text", "events", "into", "one", "text", "event" ]
innodatalabs/lxmlx
python
https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L143-L155
[ "def", "merge_text", "(", "events", ")", ":", "text", "=", "[", "]", "for", "obj", "in", "events", ":", "if", "obj", "[", "'type'", "]", "==", "TEXT", ":", "text", ".", "append", "(", "obj", "[", "'text'", "]", ")", "else", ":", "if", "text", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "''", ".", "join", "(", "text", ")", "}", "text", ".", "clear", "(", ")", "yield", "obj", "if", "text", ":", "yield", "{", "'type'", ":", "TEXT", ",", "'text'", ":", "''", ".", "join", "(", "text", ")", "}" ]
d0514f62127e51378be4e0c8cea2622c9786f99f
valid
with_peer
locates ENTER peer for each EXIT object. Convenient when selectively filtering out XML markup
lxmlx/event.py
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, stack.pop() else: yield obj, None
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, stack.pop() else: yield obj, None
[ "locates", "ENTER", "peer", "for", "each", "EXIT", "object", ".", "Convenient", "when", "selectively", "filtering", "out", "XML", "markup" ]
innodatalabs/lxmlx
python
https://github.com/innodatalabs/lxmlx/blob/d0514f62127e51378be4e0c8cea2622c9786f99f/lxmlx/event.py#L158-L170
[ "def", "with_peer", "(", "events", ")", ":", "stack", "=", "[", "]", "for", "obj", "in", "events", ":", "if", "obj", "[", "'type'", "]", "==", "ENTER", ":", "stack", ".", "append", "(", "obj", ")", "yield", "obj", ",", "None", "elif", "obj", "[", "'type'", "]", "==", "EXIT", ":", "yield", "obj", ",", "stack", ".", "pop", "(", ")", "else", ":", "yield", "obj", ",", "None" ]
d0514f62127e51378be4e0c8cea2622c9786f99f
valid
easter
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 the algorithm may be found at: http://users.chariot.net.au/~gmarts/eastalg.htm and http://www.tondering.dk/claus/calendar.html
businessdate/businessdate.py
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 the algorithm may be found at: http://users.chariot.net.au/~gmarts/eastalg.htm and http://www.tondering.dk/claus/calendar.html """ # g - Golden year - 1 # c - Century # h - (23 - Epact) mod 30 # i - Number of days from March 21 to Paschal Full Moon # j - Weekday for PFM (0=Sunday, etc) # p - Number of days from March 21 to Sunday on or before PFM # (-6 to 28 methods 1 & 3, to 56 for method 2) # e - Extra days to add for method 2 (converting Julian # date to Gregorian date) y = year g = y % 19 e = 0 c = y // 100 h = (c - c // 4 - (8 * c + 13) // 25 + 19 * g + 15) % 30 i = h - (h // 28) * (1 - (h // 28) * (29 // (h + 1)) * ((21 - g) // 11)) j = (y + y // 4 + i + 2 - c + c // 4) % 7 # p can be from -6 to 56 corresponding to dates 22 March to 23 May # (later dates apply to method 2, although 23 May never actually occurs) p = i - j + e d = 1 + (p + 27 + (p + 6) // 40) % 31 m = 3 + (p + 26) // 30 return BusinessDate.from_ymd(int(y), int(m), int(d))
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 the algorithm may be found at: http://users.chariot.net.au/~gmarts/eastalg.htm and http://www.tondering.dk/claus/calendar.html """ # g - Golden year - 1 # c - Century # h - (23 - Epact) mod 30 # i - Number of days from March 21 to Paschal Full Moon # j - Weekday for PFM (0=Sunday, etc) # p - Number of days from March 21 to Sunday on or before PFM # (-6 to 28 methods 1 & 3, to 56 for method 2) # e - Extra days to add for method 2 (converting Julian # date to Gregorian date) y = year g = y % 19 e = 0 c = y // 100 h = (c - c // 4 - (8 * c + 13) // 25 + 19 * g + 15) % 30 i = h - (h // 28) * (1 - (h // 28) * (29 // (h + 1)) * ((21 - g) // 11)) j = (y + y // 4 + i + 2 - c + c // 4) % 7 # p can be from -6 to 56 corresponding to dates 22 March to 23 May # (later dates apply to method 2, although 23 May never actually occurs) p = i - j + e d = 1 + (p + 27 + (p + 6) // 40) % 31 m = 3 + (p + 26) // 30 return BusinessDate.from_ymd(int(y), int(m), int(d))
[ "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", "." ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L1080-L1121
[ "def", "easter", "(", "year", ")", ":", "# g - Golden year - 1", "# c - Century", "# h - (23 - Epact) mod 30", "# i - Number of days from March 21 to Paschal Full Moon", "# j - Weekday for PFM (0=Sunday, etc)", "# p - Number of days from March 21 to Sunday on or before PFM", "# (-6 to 28 methods 1 & 3, to 56 for method 2)", "# e - Extra days to add for method 2 (converting Julian", "# date to Gregorian date)", "y", "=", "year", "g", "=", "y", "%", "19", "e", "=", "0", "c", "=", "y", "//", "100", "h", "=", "(", "c", "-", "c", "//", "4", "-", "(", "8", "*", "c", "+", "13", ")", "//", "25", "+", "19", "*", "g", "+", "15", ")", "%", "30", "i", "=", "h", "-", "(", "h", "//", "28", ")", "*", "(", "1", "-", "(", "h", "//", "28", ")", "*", "(", "29", "//", "(", "h", "+", "1", ")", ")", "*", "(", "(", "21", "-", "g", ")", "//", "11", ")", ")", "j", "=", "(", "y", "+", "y", "//", "4", "+", "i", "+", "2", "-", "c", "+", "c", "//", "4", ")", "%", "7", "# p can be from -6 to 56 corresponding to dates 22 March to 23 May", "# (later dates apply to method 2, although 23 May never actually occurs)", "p", "=", "i", "-", "j", "+", "e", "d", "=", "1", "+", "(", "p", "+", "27", "+", "(", "p", "+", "6", ")", "//", "40", ")", "%", "31", "m", "=", "3", "+", "(", "p", "+", "26", ")", "//", "30", "return", "BusinessDate", ".", "from_ymd", "(", "int", "(", "y", ")", ",", "int", "(", "m", ")", ",", "int", "(", "d", ")", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.from_date
construct BusinessDate instance from datetime.date instance, raise ValueError exception if not possible :param datetime.date datetime_date: calendar day :return bool:
businessdate/businessdate.py
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_date.month, datetime_date.day)
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_date.month, datetime_date.day)
[ "construct", "BusinessDate", "instance", "from", "datetime", ".", "date", "instance", "raise", "ValueError", "exception", "if", "not", "possible" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L189-L197
[ "def", "from_date", "(", "datetime_date", ")", ":", "return", "BusinessDate", ".", "from_ymd", "(", "datetime_date", ".", "year", ",", "datetime_date", ".", "month", ",", "datetime_date", ".", "day", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.from_string
construction from the following string patterns '%Y-%m-%d' '%d.%m.%Y' '%m/%d/%Y' '%Y%m%d' :param str date_str: :return BusinessDate:
businessdate/businessdate.py
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' elif date_str.count('.'): str_format = '%d.%m.%Y' elif date_str.count('/'): str_format = '%m/%d/%Y' elif len(date_str) == 8: str_format = '%Y%m%d' elif len(date_str) == 4: year = ord(date_str[0]) * 256 + ord(date_str[1]) month = ord(date_str[2]) day = ord(date_str[3]) return BusinessDate.from_ymd(year, month, day) else: msg = "the date string " + date_str + " has not the right format" raise ValueError(msg) d = datetime.strptime(date_str, str_format) return BusinessDate.from_ymd(d.year, d.month, d.day)
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' elif date_str.count('.'): str_format = '%d.%m.%Y' elif date_str.count('/'): str_format = '%m/%d/%Y' elif len(date_str) == 8: str_format = '%Y%m%d' elif len(date_str) == 4: year = ord(date_str[0]) * 256 + ord(date_str[1]) month = ord(date_str[2]) day = ord(date_str[3]) return BusinessDate.from_ymd(year, month, day) else: msg = "the date string " + date_str + " has not the right format" raise ValueError(msg) d = datetime.strptime(date_str, str_format) return BusinessDate.from_ymd(d.year, d.month, d.day)
[ "construction", "from", "the", "following", "string", "patterns", "%Y", "-", "%m", "-", "%d", "%d", ".", "%m", ".", "%Y", "%m", "/", "%d", "/", "%Y", "%Y%m%d" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L205-L235
[ "def", "from_string", "(", "date_str", ")", ":", "if", "date_str", ".", "count", "(", "'-'", ")", ":", "str_format", "=", "'%Y-%m-%d'", "elif", "date_str", ".", "count", "(", "'.'", ")", ":", "str_format", "=", "'%d.%m.%Y'", "elif", "date_str", ".", "count", "(", "'/'", ")", ":", "str_format", "=", "'%m/%d/%Y'", "elif", "len", "(", "date_str", ")", "==", "8", ":", "str_format", "=", "'%Y%m%d'", "elif", "len", "(", "date_str", ")", "==", "4", ":", "year", "=", "ord", "(", "date_str", "[", "0", "]", ")", "*", "256", "+", "ord", "(", "date_str", "[", "1", "]", ")", "month", "=", "ord", "(", "date_str", "[", "2", "]", ")", "day", "=", "ord", "(", "date_str", "[", "3", "]", ")", "return", "BusinessDate", ".", "from_ymd", "(", "year", ",", "month", ",", "day", ")", "else", ":", "msg", "=", "\"the date string \"", "+", "date_str", "+", "\" has not the right format\"", "raise", "ValueError", "(", "msg", ")", "d", "=", "datetime", ".", "strptime", "(", "date_str", ",", "str_format", ")", "return", "BusinessDate", ".", "from_ymd", "(", "d", ".", "year", ",", "d", ".", "month", ",", "d", ".", "day", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.to_date
construct datetime.date instance represented calendar date of BusinessDate instance :return datetime.date:
businessdate/businessdate.py
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)
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)
[ "construct", "datetime", ".", "date", "instance", "represented", "calendar", "date", "of", "BusinessDate", "instance" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L260-L267
[ "def", "to_date", "(", "self", ")", ":", "y", ",", "m", ",", "d", "=", "self", ".", "to_ymd", "(", ")", "return", "date", "(", "y", ",", "m", ",", "d", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.is_businessdate
checks whether the provided date is a date :param BusinessDate, int or float in_date: :return bool:
businessdate/businessdate.py
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 validity. # !!! However, if the data has been read from json string via json.load() function # it does not recognize that this numbers are bankdates, just considers them as integers # therefore, additional check is useful here, first to convert the date if it is integer to BusinessDate, # then check the validity. # (as the parameter to this method should always be a BusinessDate) if not isinstance(in_date, BaseDate): try: # to be removed in_date = BusinessDate(in_date) except: return False y, m, d, = in_date.to_ymd() return is_valid_ymd(y, m, d)
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 validity. # !!! However, if the data has been read from json string via json.load() function # it does not recognize that this numbers are bankdates, just considers them as integers # therefore, additional check is useful here, first to convert the date if it is integer to BusinessDate, # then check the validity. # (as the parameter to this method should always be a BusinessDate) if not isinstance(in_date, BaseDate): try: # to be removed in_date = BusinessDate(in_date) except: return False y, m, d, = in_date.to_ymd() return is_valid_ymd(y, m, d)
[ "checks", "whether", "the", "provided", "date", "is", "a", "date", ":", "param", "BusinessDate", "int", "or", "float", "in_date", ":", ":", "return", "bool", ":" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L319-L338
[ "def", "is_businessdate", "(", "in_date", ")", ":", "# 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 validity.", "# !!! However, if the data has been read from json string via json.load() function", "# it does not recognize that this numbers are bankdates, just considers them as integers", "# therefore, additional check is useful here, first to convert the date if it is integer to BusinessDate,", "# then check the validity.", "# (as the parameter to this method should always be a BusinessDate)", "if", "not", "isinstance", "(", "in_date", ",", "BaseDate", ")", ":", "try", ":", "# to be removed", "in_date", "=", "BusinessDate", "(", "in_date", ")", "except", ":", "return", "False", "y", ",", "m", ",", "d", ",", "=", "in_date", ".", "to_ymd", "(", ")", "return", "is_valid_ymd", "(", "y", ",", "m", ",", "d", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.is_business_day
: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
businessdate/businessdate.py
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) > FRIDAY: return False holiday_list = holiday_obj if holiday_obj is not None else DEFAULT_HOLIDAYS if self in holiday_list: return False elif date(y, m, d) in holiday_list: return False return True
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) > FRIDAY: return False holiday_list = holiday_obj if holiday_obj is not None else DEFAULT_HOLIDAYS if self in holiday_list: return False elif date(y, m, d) in holiday_list: return False return True
[ ":", "param", "list", "holiday_obj", ":", "datetime", ".", "date", "list", "defining", "business", "holidays", ":", "return", ":", "bool" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L350-L365
[ "def", "is_business_day", "(", "self", ",", "holiday_obj", "=", "None", ")", ":", "y", ",", "m", ",", "d", "=", "BusinessDate", ".", "to_ymd", "(", "self", ")", "if", "weekday", "(", "y", ",", "m", ",", "d", ")", ">", "FRIDAY", ":", "return", "False", "holiday_list", "=", "holiday_obj", "if", "holiday_obj", "is", "not", "None", "else", "DEFAULT_HOLIDAYS", "if", "self", "in", "holiday_list", ":", "return", "False", "elif", "date", "(", "y", ",", "m", ",", "d", ")", "in", "holiday_list", ":", "return", "False", "return", "True" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.add_period
addition of a period object :param BusinessDate d: :param p: :type p: BusinessPeriod or str :param list holiday_obj: :return bankdate:
businessdate/businessdate.py
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 [BusinessDate.add_period(self, pd) for pd in p] elif isinstance(p, str): period = BusinessPeriod(p) else: period = p res = self res = BusinessDate.add_months(res, period.months) res = BusinessDate.add_years(res, period.years) res = BusinessDate.add_days(res, period.days) if period.businessdays: if holiday_obj: res = BusinessDate.add_business_days(res, period.businessdays, holiday_obj) else: res = BusinessDate.add_business_days(res, period.businessdays, period.holiday) return res
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 [BusinessDate.add_period(self, pd) for pd in p] elif isinstance(p, str): period = BusinessPeriod(p) else: period = p res = self res = BusinessDate.add_months(res, period.months) res = BusinessDate.add_years(res, period.years) res = BusinessDate.add_days(res, period.days) if period.businessdays: if holiday_obj: res = BusinessDate.add_business_days(res, period.businessdays, holiday_obj) else: res = BusinessDate.add_business_days(res, period.businessdays, period.holiday) return res
[ "addition", "of", "a", "period", "object" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L381-L410
[ "def", "add_period", "(", "self", ",", "p", ",", "holiday_obj", "=", "None", ")", ":", "if", "isinstance", "(", "p", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "BusinessDate", ".", "add_period", "(", "self", ",", "pd", ")", "for", "pd", "in", "p", "]", "elif", "isinstance", "(", "p", ",", "str", ")", ":", "period", "=", "BusinessPeriod", "(", "p", ")", "else", ":", "period", "=", "p", "res", "=", "self", "res", "=", "BusinessDate", ".", "add_months", "(", "res", ",", "period", ".", "months", ")", "res", "=", "BusinessDate", ".", "add_years", "(", "res", ",", "period", ".", "years", ")", "res", "=", "BusinessDate", ".", "add_days", "(", "res", ",", "period", ".", "days", ")", "if", "period", ".", "businessdays", ":", "if", "holiday_obj", ":", "res", "=", "BusinessDate", ".", "add_business_days", "(", "res", ",", "period", ".", "businessdays", ",", "holiday_obj", ")", "else", ":", "res", "=", "BusinessDate", ".", "add_business_days", "(", "res", ",", "period", ".", "businessdays", ",", "period", ".", "holiday", ")", "return", "res" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.add_months
addition of a number of months :param BusinessDate d: :param int month_int: :return bankdate:
businessdate/businessdate.py
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 -= 12 while month_int < 1: self = BusinessDate.add_years(self, -1) month_int += 12 l = monthrange(self.year, month_int)[1] return BusinessDate.from_ymd(self.year, month_int, min(l, self.day))
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 -= 12 while month_int < 1: self = BusinessDate.add_years(self, -1) month_int += 12 l = monthrange(self.year, month_int)[1] return BusinessDate.from_ymd(self.year, month_int, min(l, self.day))
[ "addition", "of", "a", "number", "of", "months" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L412-L429
[ "def", "add_months", "(", "self", ",", "month_int", ")", ":", "month_int", "+=", "self", ".", "month", "while", "month_int", ">", "12", ":", "self", "=", "BusinessDate", ".", "add_years", "(", "self", ",", "1", ")", "month_int", "-=", "12", "while", "month_int", "<", "1", ":", "self", "=", "BusinessDate", ".", "add_years", "(", "self", ",", "-", "1", ")", "month_int", "+=", "12", "l", "=", "monthrange", "(", "self", ".", "year", ",", "month_int", ")", "[", "1", "]", "return", "BusinessDate", ".", "from_ymd", "(", "self", ".", "year", ",", "month_int", ",", "min", "(", "l", ",", "self", ".", "day", ")", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.add_business_days
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
businessdate/businessdate.py
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 """ res = self if days_int >= 0: count = 0 while count < days_int: res = BusinessDate.add_days(res, 1) if BusinessDate.is_business_day(res, holiday_obj): count += 1 else: count = 0 while count > days_int: res = BusinessDate.add_days(res, -1) if BusinessDate.is_business_day(res, holiday_obj): count -= 1 return res
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 """ res = self if days_int >= 0: count = 0 while count < days_int: res = BusinessDate.add_days(res, 1) if BusinessDate.is_business_day(res, holiday_obj): count += 1 else: count = 0 while count > days_int: res = BusinessDate.add_days(res, -1) if BusinessDate.is_business_day(res, holiday_obj): count -= 1 return res
[ "private", "method", "for", "the", "addition", "of", "business", "days", "used", "in", "the", "addition", "of", "a", "BusinessPeriod", "only" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L431-L455
[ "def", "add_business_days", "(", "self", ",", "days_int", ",", "holiday_obj", "=", "None", ")", ":", "res", "=", "self", "if", "days_int", ">=", "0", ":", "count", "=", "0", "while", "count", "<", "days_int", ":", "res", "=", "BusinessDate", ".", "add_days", "(", "res", ",", "1", ")", "if", "BusinessDate", ".", "is_business_day", "(", "res", ",", "holiday_obj", ")", ":", "count", "+=", "1", "else", ":", "count", "=", "0", "while", "count", ">", "days_int", ":", "res", "=", "BusinessDate", ".", "add_days", "(", "res", ",", "-", "1", ")", "if", "BusinessDate", ".", "is_business_day", "(", "res", ",", "holiday_obj", ")", ":", "count", "-=", "1", "return", "res" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.diff
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):
businessdate/businessdate.py
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: y, m, d = BusinessDate.diff(end_date, self) return -y, -m, -d y = end_date.year - self.year m = end_date.month - self.month while m < 0: y -= 1 m += 12 while m > 12: y += 1 m -= 12 s = BusinessDate.add_years(BusinessDate.add_months(self, m), y) d = BusinessDate.diff_in_days(s, end_date) if d < 0: m -= 1 if m < 0: y -= 1 m += 12 s = BusinessDate.add_years(BusinessDate.add_months(self, m), y) d = BusinessDate.diff_in_days(s, end_date) return -int(y), -int(m), -int(d)
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: y, m, d = BusinessDate.diff(end_date, self) return -y, -m, -d y = end_date.year - self.year m = end_date.month - self.month while m < 0: y -= 1 m += 12 while m > 12: y += 1 m -= 12 s = BusinessDate.add_years(BusinessDate.add_months(self, m), y) d = BusinessDate.diff_in_days(s, end_date) if d < 0: m -= 1 if m < 0: y -= 1 m += 12 s = BusinessDate.add_years(BusinessDate.add_months(self, m), y) d = BusinessDate.diff_in_days(s, end_date) return -int(y), -int(m), -int(d)
[ "difference", "expressed", "as", "a", "tuple", "of", "years", "months", "days", "(", "see", "also", "the", "python", "lib", "dateutils", ".", "relativedelta", ")" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L457-L492
[ "def", "diff", "(", "self", ",", "end_date", ")", ":", "if", "end_date", "<", "self", ":", "y", ",", "m", ",", "d", "=", "BusinessDate", ".", "diff", "(", "end_date", ",", "self", ")", "return", "-", "y", ",", "-", "m", ",", "-", "d", "y", "=", "end_date", ".", "year", "-", "self", ".", "year", "m", "=", "end_date", ".", "month", "-", "self", ".", "month", "while", "m", "<", "0", ":", "y", "-=", "1", "m", "+=", "12", "while", "m", ">", "12", ":", "y", "+=", "1", "m", "-=", "12", "s", "=", "BusinessDate", ".", "add_years", "(", "BusinessDate", ".", "add_months", "(", "self", ",", "m", ")", ",", "y", ")", "d", "=", "BusinessDate", ".", "diff_in_days", "(", "s", ",", "end_date", ")", "if", "d", "<", "0", ":", "m", "-=", "1", "if", "m", "<", "0", ":", "y", "-=", "1", "m", "+=", "12", "s", "=", "BusinessDate", ".", "add_years", "(", "BusinessDate", ".", "add_months", "(", "self", ",", "m", ")", ",", "y", ")", "d", "=", "BusinessDate", ".", "diff_in_days", "(", "s", ",", "end_date", ")", "return", "-", "int", "(", "y", ")", ",", "-", "int", "(", "m", ")", ",", "-", "int", "(", "d", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.get_30_360
implements 30/360 Day Count Convention (4.16(f) 2006 ISDA Definitions)
businessdate/businessdate.py
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) + (end_day - start_day)) / 360.0
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) + (end_day - start_day)) / 360.0
[ "implements", "30", "/", "360", "Day", "Count", "Convention", "(", "4", ".", "16", "(", "f", ")", "2006", "ISDA", "Definitions", ")" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L505-L511
[ "def", "get_30_360", "(", "self", ",", "end", ")", ":", "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", ")", "+", "(", "end_day", "-", "start_day", ")", ")", "/", "360.0" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.get_act_act
implements Act/Act day count convention (4.16(b) 2006 ISDA Definitions)
businessdate/businessdate.py
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 / years in between / days in the end year # REMARK: following the affore mentioned ISDA Definition the first day of the period is included whereas the # last day will be excluded # What remains to check now is only whether the start and end year are leap or non-leap years. The quotients # can be easily calculated and for the years in between they are always one (365/365 = 1; 366/366 = 1) if end.year - self.year == 0: if BusinessDate.is_leap_year(self.year): return BusinessDate.diff_in_days(self, end) / 366.0 # leap year: 366 days else: # return BusinessDate.diff_in_days(self, end) / 366.0 return BusinessDate.diff_in_days(self, end) / 365.0 # non-leap year: 365 days else: rest_year1 = BusinessDate.diff_in_days(self, BusinessDate( date(self.year, 12, 31))) + 1 # since the first day counts rest_year2 = abs(BusinessDate.diff_in_days(end, BusinessDate( date(end.year, 1, 1)))) # here the last day is automatically not counted years_in_between = end.year - self.year - 1 return years_in_between + rest_year1 / (366.0 if is_leap_year(self.year) else 365.0) + rest_year2 / ( 366.0 if is_leap_year(end.year) else 365.0)
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 / years in between / days in the end year # REMARK: following the affore mentioned ISDA Definition the first day of the period is included whereas the # last day will be excluded # What remains to check now is only whether the start and end year are leap or non-leap years. The quotients # can be easily calculated and for the years in between they are always one (365/365 = 1; 366/366 = 1) if end.year - self.year == 0: if BusinessDate.is_leap_year(self.year): return BusinessDate.diff_in_days(self, end) / 366.0 # leap year: 366 days else: # return BusinessDate.diff_in_days(self, end) / 366.0 return BusinessDate.diff_in_days(self, end) / 365.0 # non-leap year: 365 days else: rest_year1 = BusinessDate.diff_in_days(self, BusinessDate( date(self.year, 12, 31))) + 1 # since the first day counts rest_year2 = abs(BusinessDate.diff_in_days(end, BusinessDate( date(end.year, 1, 1)))) # here the last day is automatically not counted years_in_between = end.year - self.year - 1 return years_in_between + rest_year1 / (366.0 if is_leap_year(self.year) else 365.0) + rest_year2 / ( 366.0 if is_leap_year(end.year) else 365.0)
[ "implements", "Act", "/", "Act", "day", "count", "convention", "(", "4", ".", "16", "(", "b", ")", "2006", "ISDA", "Definitions", ")" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L531-L560
[ "def", "get_act_act", "(", "self", ",", "end", ")", ":", "# 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 / years in between / days in the end year", "# REMARK: following the affore mentioned ISDA Definition the first day of the period is included whereas the", "# last day will be excluded", "# What remains to check now is only whether the start and end year are leap or non-leap years. The quotients", "# can be easily calculated and for the years in between they are always one (365/365 = 1; 366/366 = 1)", "if", "end", ".", "year", "-", "self", ".", "year", "==", "0", ":", "if", "BusinessDate", ".", "is_leap_year", "(", "self", ".", "year", ")", ":", "return", "BusinessDate", ".", "diff_in_days", "(", "self", ",", "end", ")", "/", "366.0", "# leap year: 366 days", "else", ":", "# return BusinessDate.diff_in_days(self, end) / 366.0", "return", "BusinessDate", ".", "diff_in_days", "(", "self", ",", "end", ")", "/", "365.0", "# non-leap year: 365 days", "else", ":", "rest_year1", "=", "BusinessDate", ".", "diff_in_days", "(", "self", ",", "BusinessDate", "(", "date", "(", "self", ".", "year", ",", "12", ",", "31", ")", ")", ")", "+", "1", "# since the first day counts", "rest_year2", "=", "abs", "(", "BusinessDate", ".", "diff_in_days", "(", "end", ",", "BusinessDate", "(", "date", "(", "end", ".", "year", ",", "1", ",", "1", ")", ")", ")", ")", "# here the last day is automatically not counted", "years_in_between", "=", "end", ".", "year", "-", "self", ".", "year", "-", "1", "return", "years_in_between", "+", "rest_year1", "/", "(", "366.0", "if", "is_leap_year", "(", "self", ".", "year", ")", "else", "365.0", ")", "+", "rest_year2", "/", "(", "366.0", "if", "is_leap_year", "(", "end", ".", "year", ")", "else", "365.0", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.get_30E_360
implements the 30E/360 Day Count Convention (4.16(g) 2006 ISDA Definitons)
businessdate/businessdate.py
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 = min(d2, 30) return (360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)) / 360.0
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 = min(d2, 30) return (360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)) / 360.0
[ "implements", "the", "30E", "/", "360", "Day", "Count", "Convention", "(", "4", ".", "16", "(", "g", ")", "2006", "ISDA", "Definitons", ")" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L575-L587
[ "def", "get_30E_360", "(", "self", ",", "end", ")", ":", "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", "=", "min", "(", "d2", ",", "30", ")", "return", "(", "360", "*", "(", "y2", "-", "y1", ")", "+", "30", "*", "(", "m2", "-", "m1", ")", "+", "(", "d2", "-", "d1", ")", ")", "/", "360.0" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.get_30E_360_ISDA
implements the 30E/360 (ISDA) Day Count Convention (4.16(h) 2006 ISDA Definitions) :param end: :return:
businessdate/businessdate.py
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_ymd() if (m1 == 2 and d1 >= 28) or d1 == 31: d1 = 30 if (m2 == 2 and d2 >= 28) or d2 == 31: d2 = 30 return (360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)) / 360.0
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_ymd() if (m1 == 2 and d1 >= 28) or d1 == 31: d1 = 30 if (m2 == 2 and d2 >= 28) or d2 == 31: d2 = 30 return (360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)) / 360.0
[ "implements", "the", "30E", "/", "360", "(", "ISDA", ")", "Day", "Count", "Convention", "(", "4", ".", "16", "(", "h", ")", "2006", "ISDA", "Definitions", ")", ":", "param", "end", ":", ":", "return", ":" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L589-L604
[ "def", "get_30E_360_ISDA", "(", "self", ",", "end", ")", ":", "y1", ",", "m1", ",", "d1", "=", "self", ".", "to_ymd", "(", ")", "# ajdust to date immediately following the last day", "y2", ",", "m2", ",", "d2", "=", "end", ".", "add_days", "(", "0", ")", ".", "to_ymd", "(", ")", "if", "(", "m1", "==", "2", "and", "d1", ">=", "28", ")", "or", "d1", "==", "31", ":", "d1", "=", "30", "if", "(", "m2", "==", "2", "and", "d2", ">=", "28", ")", "or", "d2", "==", "31", ":", "d2", "=", "30", "return", "(", "360", "*", "(", "y2", "-", "y1", ")", "+", "30", "*", "(", "m2", "-", "m1", ")", "+", "(", "d2", "-", "d1", ")", ")", "/", "360.0" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.adjust_previous
adjusts to Business Day Convention "Preceding" (4.12(a) (iii) 2006 ISDA Definitions).
businessdate/businessdate.py
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
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", "Preceding", "(", "4", ".", "12", "(", "a", ")", "(", "iii", ")", "2006", "ISDA", "Definitions", ")", "." ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L608-L614
[ "def", "adjust_previous", "(", "self", ",", "holidays_obj", "=", "None", ")", ":", "while", "not", "BusinessDate", ".", "is_business_day", "(", "self", ",", "holidays_obj", ")", ":", "self", "=", "BusinessDate", ".", "add_days", "(", "self", ",", "-", "1", ")", "return", "self" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.adjust_follow
adjusts to Business Day Convention "Following" (4.12(a) (i) 2006 ISDA Definitions).
businessdate/businessdate.py
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
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", "Following", "(", "4", ".", "12", "(", "a", ")", "(", "i", ")", "2006", "ISDA", "Definitions", ")", "." ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L616-L622
[ "def", "adjust_follow", "(", "self", ",", "holidays_obj", "=", "None", ")", ":", "while", "not", "BusinessDate", ".", "is_business_day", "(", "self", ",", "holidays_obj", ")", ":", "self", "=", "BusinessDate", ".", "add_days", "(", "self", ",", "1", ")", "return", "self" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.adjust_mod_follow
adjusts to Business Day Convention "Modified [Following]" (4.12(a) (ii) 2006 ISDA Definitions).
businessdate/businessdate.py
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 = BusinessDate.adjust_previous(self, holidays_obj) self = new return self
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 = BusinessDate.adjust_previous(self, holidays_obj) self = new return self
[ "adjusts", "to", "Business", "Day", "Convention", "Modified", "[", "Following", "]", "(", "4", ".", "12", "(", "a", ")", "(", "ii", ")", "2006", "ISDA", "Definitions", ")", "." ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L624-L633
[ "def", "adjust_mod_follow", "(", "self", ",", "holidays_obj", "=", "None", ")", ":", "month", "=", "self", ".", "month", "new", "=", "BusinessDate", ".", "adjust_follow", "(", "self", ",", "holidays_obj", ")", "if", "month", "!=", "new", ".", "month", ":", "new", "=", "BusinessDate", ".", "adjust_previous", "(", "self", ",", "holidays_obj", ")", "self", "=", "new", "return", "self" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessDate.adjust_mod_previous
ajusts to Business Day Convention "Modified Preceding" (not in 2006 ISDA Definitons).
businessdate/businessdate.py
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.adjust_follow(self, holidays_obj) self = new return self
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.adjust_follow(self, holidays_obj) self = new return self
[ "ajusts", "to", "Business", "Day", "Convention", "Modified", "Preceding", "(", "not", "in", "2006", "ISDA", "Definitons", ")", "." ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L635-L644
[ "def", "adjust_mod_previous", "(", "self", ",", "holidays_obj", "=", "None", ")", ":", "month", "=", "self", ".", "month", "new", "=", "BusinessDate", ".", "adjust_previous", "(", "self", ",", "holidays_obj", ")", "if", "month", "!=", "new", ".", "month", ":", "new", "=", "BusinessDate", ".", "adjust_follow", "(", "self", ",", "holidays_obj", ")", "self", "=", "new", "return", "self" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BusinessPeriod.is_businessperiod
: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
businessdate/businessdate.py
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 if str(in_period).upper() == '0D': return True else: p = BusinessPeriod(str(in_period)) return not (p.days == 0 and p.months == 0 and p.years == 0 and p.businessdays == 0) except: return False
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 if str(in_period).upper() == '0D': return True else: p = BusinessPeriod(str(in_period)) return not (p.days == 0 and p.months == 0 and p.years == 0 and p.businessdays == 0) except: return False
[ ":", "param", "in_period", ":", "object", "to", "be", "checked", ":", "type", "in_period", ":", "object", "str", "timedelta", ":", "return", ":", "True", "if", "cast", "works", ":", "rtype", ":", "Boolean" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L761-L777
[ "def", "is_businessperiod", "(", "cls", ",", "in_period", ")", ":", "try", ":", "# to be removed", "if", "str", "(", "in_period", ")", ".", "upper", "(", ")", "==", "'0D'", ":", "return", "True", "else", ":", "p", "=", "BusinessPeriod", "(", "str", "(", "in_period", ")", ")", "return", "not", "(", "p", ".", "days", "==", "0", "and", "p", ".", "months", "==", "0", "and", "p", ".", "years", "==", "0", "and", "p", ".", "businessdays", "==", "0", ")", "except", ":", "return", "False" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
quoted
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
picoparse/text.py
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_char)) return build_string(value)
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_char)) return build_string(value)
[ "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" ]
brehaut/picoparse
python
https://github.com/brehaut/picoparse/blob/5e07c8e687a021bba58a5a2a76696c7a7ff35a1c/picoparse/text.py#L64-L72
[ "def", "quoted", "(", "parser", "=", "any_token", ")", ":", "quote_char", "=", "quote", "(", ")", "value", ",", "_", "=", "many_until", "(", "parser", ",", "partial", "(", "one_of", ",", "quote_char", ")", ")", "return", "build_string", "(", "value", ")" ]
5e07c8e687a021bba58a5a2a76696c7a7ff35a1c
valid
days_in_month
returns number of days for the given year and month :param int year: calendar year :param int month: calendar month :return int:
businessdate/basedate.py
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
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
[ "returns", "number", "of", "days", "for", "the", "given", "year", "and", "month" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L54-L67
[ "def", "days_in_month", "(", "year", ",", "month", ")", ":", "eom", "=", "_days_per_month", "[", "month", "-", "1", "]", "if", "is_leap_year", "(", "year", ")", "and", "month", "==", "2", ":", "eom", "+=", "1", "return", "eom" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
is_valid_ymd
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:
businessdate/basedate.py
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: """ return 1 <= month <= 12 and 1 <= day <= days_in_month(year, month) and year >= 1899
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: """ return 1 <= month <= 12 and 1 <= day <= days_in_month(year, month) and year >= 1899
[ "return", "True", "if", "(", "year", "month", "day", ")", "can", "be", "represented", "in", "Excel", "-", "notation", "(", "number", "of", "days", "since", "30", ".", "12", ".", "1899", ")", "for", "calendar", "days", "otherwise", "False" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L70-L81
[ "def", "is_valid_ymd", "(", "year", ",", "month", ",", "day", ")", ":", "return", "1", "<=", "month", "<=", "12", "and", "1", "<=", "day", "<=", "days_in_month", "(", "year", ",", "month", ")", "and", "year", ">=", "1899" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
from_excel_to_ymd
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):
businessdate/basedate.py
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 else 0 # jan dingerkus: There are two errors in excels own date <> int conversion. # The first is that there exists the 00.01.1900 and the second that there never happend to be a 29.2.1900 since it # was no leap year. So there is the int 60 <> 29.2.1900 which has to be jumped over. year = (int_date - 1) // 365 rest_days = int_date - 365 * year - (year + 3) // 4 + (year + 99) // 100 - (year + 299) // 400 year += 1900 while rest_days <= 0: year -= 1 rest_days += days_in_year(year) month = 1 if is_leap_year(year) and rest_days == 60: month = 2 day = 29 else: if is_leap_year(year) and rest_days > 60: rest_days -= 1 while rest_days > _cum_month_days[month]: month += 1 day = rest_days - _cum_month_days[month - 1] return year, month, day
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 else 0 # jan dingerkus: There are two errors in excels own date <> int conversion. # The first is that there exists the 00.01.1900 and the second that there never happend to be a 29.2.1900 since it # was no leap year. So there is the int 60 <> 29.2.1900 which has to be jumped over. year = (int_date - 1) // 365 rest_days = int_date - 365 * year - (year + 3) // 4 + (year + 99) // 100 - (year + 299) // 400 year += 1900 while rest_days <= 0: year -= 1 rest_days += days_in_year(year) month = 1 if is_leap_year(year) and rest_days == 60: month = 2 day = 29 else: if is_leap_year(year) and rest_days > 60: rest_days -= 1 while rest_days > _cum_month_days[month]: month += 1 day = rest_days - _cum_month_days[month - 1] return year, month, day
[ "converts", "date", "in", "Microsoft", "Excel", "representation", "style", "and", "returns", "(", "year", "month", "day", ")", "tuple" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L84-L118
[ "def", "from_excel_to_ymd", "(", "excel_int", ")", ":", "int_date", "=", "int", "(", "floor", "(", "excel_int", ")", ")", "int_date", "-=", "1", "if", "excel_int", ">", "60", "else", "0", "# jan dingerkus: There are two errors in excels own date <> int conversion.", "# The first is that there exists the 00.01.1900 and the second that there never happend to be a 29.2.1900 since it", "# was no leap year. So there is the int 60 <> 29.2.1900 which has to be jumped over.", "year", "=", "(", "int_date", "-", "1", ")", "//", "365", "rest_days", "=", "int_date", "-", "365", "*", "year", "-", "(", "year", "+", "3", ")", "//", "4", "+", "(", "year", "+", "99", ")", "//", "100", "-", "(", "year", "+", "299", ")", "//", "400", "year", "+=", "1900", "while", "rest_days", "<=", "0", ":", "year", "-=", "1", "rest_days", "+=", "days_in_year", "(", "year", ")", "month", "=", "1", "if", "is_leap_year", "(", "year", ")", "and", "rest_days", "==", "60", ":", "month", "=", "2", "day", "=", "29", "else", ":", "if", "is_leap_year", "(", "year", ")", "and", "rest_days", ">", "60", ":", "rest_days", "-=", "1", "while", "rest_days", ">", "_cum_month_days", "[", "month", "]", ":", "month", "+=", "1", "day", "=", "rest_days", "-", "_cum_month_days", "[", "month", "-", "1", "]", "return", "year", ",", "month", ",", "day" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
from_ymd_to_excel
converts date as `(year, month, day)` tuple into Microsoft Excel representation style :param tuple(int, int, int): int tuple `year, month, day` :return int:
businessdate/basedate.py
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}".format(year, month, day)) days = _cum_month_days[month - 1] + day days += 1 if (is_leap_year(year) and month > 2) else 0 years_distance = year - 1900 days += years_distance * 365 + \ (years_distance + 3) // 4 - (years_distance + 99) // 100 + (years_distance + 299) // 400 # count days since 30.12.1899 (excluding 30.12.1899) (workaround for excel bug) days += 1 if (year, month, day) > (1900, 2, 28) else 0 return days
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}".format(year, month, day)) days = _cum_month_days[month - 1] + day days += 1 if (is_leap_year(year) and month > 2) else 0 years_distance = year - 1900 days += years_distance * 365 + \ (years_distance + 3) // 4 - (years_distance + 99) // 100 + (years_distance + 299) // 400 # count days since 30.12.1899 (excluding 30.12.1899) (workaround for excel bug) days += 1 if (year, month, day) > (1900, 2, 28) else 0 return days
[ "converts", "date", "as", "(", "year", "month", "day", ")", "tuple", "into", "Microsoft", "Excel", "representation", "style" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L121-L140
[ "def", "from_ymd_to_excel", "(", "year", ",", "month", ",", "day", ")", ":", "if", "not", "is_valid_ymd", "(", "year", ",", "month", ",", "day", ")", ":", "raise", "ValueError", "(", "\"Invalid date {0}.{1}.{2}\"", ".", "format", "(", "year", ",", "month", ",", "day", ")", ")", "days", "=", "_cum_month_days", "[", "month", "-", "1", "]", "+", "day", "days", "+=", "1", "if", "(", "is_leap_year", "(", "year", ")", "and", "month", ">", "2", ")", "else", "0", "years_distance", "=", "year", "-", "1900", "days", "+=", "years_distance", "*", "365", "+", "(", "years_distance", "+", "3", ")", "//", "4", "-", "(", "years_distance", "+", "99", ")", "//", "100", "+", "(", "years_distance", "+", "299", ")", "//", "400", "# count days since 30.12.1899 (excluding 30.12.1899) (workaround for excel bug)", "days", "+=", "1", "if", "(", "year", ",", "month", ",", "day", ")", ">", "(", "1900", ",", "2", ",", "28", ")", "else", "0", "return", "days" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BaseDateFloat.add_years
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
businessdate/basedate.py
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 m == 2: d = min(28, d) return BaseDateFloat.from_ymd(y + years_int, m, d)
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 m == 2: d = min(28, d) return BaseDateFloat.from_ymd(y + years_int, m, d)
[ "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" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L204-L215
[ "def", "add_years", "(", "d", ",", "years_int", ")", ":", "y", ",", "m", ",", "d", "=", "BaseDate", ".", "to_ymd", "(", "d", ")", "if", "not", "is_leap_year", "(", "years_int", ")", "and", "m", "==", "2", ":", "d", "=", "min", "(", "28", ",", "d", ")", "return", "BaseDateFloat", ".", "from_ymd", "(", "y", "+", "years_int", ",", "m", ",", "d", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BaseDateDatetimeDate.add_days
addition of a number of days :param BaseDateDatetimeDate d: :param int days_int: :return BaseDatetimeDate:
businessdate/basedate.py
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)
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", "days" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L274-L283
[ "def", "add_days", "(", "d", ",", "days_int", ")", ":", "n", "=", "date", "(", "d", ".", "year", ",", "d", ".", "month", ",", "d", ".", "day", ")", "+", "timedelta", "(", "days_int", ")", "return", "BaseDateDatetimeDate", "(", "n", ".", "year", ",", "n", ".", "month", ",", "n", ".", "day", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BaseDateDatetimeDate.add_years
addition of a number of years :param BaseDateDatetimeDate d: :param int years_int: :return BaseDatetimeDate:
businessdate/basedate.py
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: d = min(28, d) return BaseDateDatetimeDate.from_ymd(y, m, d)
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: d = min(28, d) return BaseDateDatetimeDate.from_ymd(y, m, d)
[ "addition", "of", "a", "number", "of", "years" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L286-L298
[ "def", "add_years", "(", "d", ",", "years_int", ")", ":", "y", ",", "m", ",", "d", "=", "BaseDateDatetimeDate", ".", "to_ymd", "(", "d", ")", "y", "+=", "years_int", "if", "not", "is_leap_year", "(", "y", ")", "and", "m", "==", "2", ":", "d", "=", "min", "(", "28", ",", "d", ")", "return", "BaseDateDatetimeDate", ".", "from_ymd", "(", "y", ",", "m", ",", "d", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BaseDateDatetimeDate.diff_in_days
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
businessdate/basedate.py
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, end.month, end.day) - date(start.year, start.month, start.day) return float(diff.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, end.month, end.day) - date(start.year, start.month, start.day) return float(diff.days)
[ "calculate", "difference", "between", "given", "dates", "in", "days" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L301-L310
[ "def", "diff_in_days", "(", "start", ",", "end", ")", ":", "diff", "=", "date", "(", "end", ".", "year", ",", "end", ".", "month", ",", "end", ".", "day", ")", "-", "date", "(", "start", ".", "year", ",", "start", ".", "month", ",", "start", ".", "day", ")", "return", "float", "(", "diff", ".", "days", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BaseDateTuple.add_days
addition of a number of days :param BaseDateTuple d: :param int days_int: :return BaseDatetimeDate:
businessdate/basedate.py
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))
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", "days" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L380-L390
[ "def", "add_days", "(", "date_obj", ",", "days_int", ")", ":", "n", "=", "from_ymd_to_excel", "(", "*", "date_obj", ".", "date", ")", "+", "days_int", "return", "BaseDateTuple", "(", "*", "from_excel_to_ymd", "(", "n", ")", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BaseDateTuple.add_years
addition of a number of years :param BaseDateTuple d: :param int years_int: :return BaseDatetimeDate:
businessdate/basedate.py
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: d = min(28, d) return BaseDateTuple.from_ymd(y, m, d)
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: d = min(28, d) return BaseDateTuple.from_ymd(y, m, d)
[ "addition", "of", "a", "number", "of", "years" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L393-L405
[ "def", "add_years", "(", "date_obj", ",", "years_int", ")", ":", "y", ",", "m", ",", "d", "=", "BaseDateTuple", ".", "to_ymd", "(", "date_obj", ")", "y", "+=", "years_int", "if", "not", "is_leap_year", "(", "y", ")", "and", "m", "==", "2", ":", "d", "=", "min", "(", "28", ",", "d", ")", "return", "BaseDateTuple", ".", "from_ymd", "(", "y", ",", "m", ",", "d", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
BaseDateTuple.diff_in_days
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
businessdate/basedate.py
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)-from_ymd_to_excel(*start.date) return float(diff)
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)-from_ymd_to_excel(*start.date) return float(diff)
[ "calculate", "difference", "between", "given", "dates", "in", "days" ]
pbrisk/businessdate
python
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/basedate.py#L408-L418
[ "def", "diff_in_days", "(", "start", ",", "end", ")", ":", "diff", "=", "from_ymd_to_excel", "(", "*", "end", ".", "date", ")", "-", "from_ymd_to_excel", "(", "*", "start", ".", "date", ")", "return", "float", "(", "diff", ")" ]
79a0c5a4e557cbacca82a430403b18413404a9bc
valid
Plugin.setup
Initialize the application.
muffin_peewee/plugin.py
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:': self.cfg.connection_manual = True if not self.cfg.migrations_enabled: return # Setup migration engine self.router = Router(self.database, migrate_dir=self.cfg.migrations_path) # Register migration commands def pw_migrate(name: str=None, fake: bool=False): """Run application's migrations. :param name: Choose a migration' name :param fake: Run as fake. Update migration history and don't touch the database """ self.router.run(name, fake=fake) self.app.manage.command(pw_migrate) def pw_rollback(name: str=None): """Rollback a migration. :param name: Migration name (actually it always should be a last one) """ if not name: name = self.router.done[-1] self.router.rollback(name) self.app.manage.command(pw_rollback) def pw_create(name: str='auto', auto: bool=False): """Create a migration. :param name: Set name of migration [auto] :param auto: Track changes and setup migrations automatically """ if auto: auto = list(self.models.values()) self.router.create(name, auto) self.app.manage.command(pw_create) def pw_list(): """List migrations.""" self.router.logger.info('Migrations are done:') self.router.logger.info('\n'.join(self.router.done)) self.router.logger.info('') self.router.logger.info('Migrations are undone:') self.router.logger.info('\n'.join(self.router.diff)) self.app.manage.command(pw_list) @self.app.manage.command def pw_merge(): """Merge migrations into one.""" self.router.merge() self.app.manage.command(pw_merge)
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:': self.cfg.connection_manual = True if not self.cfg.migrations_enabled: return # Setup migration engine self.router = Router(self.database, migrate_dir=self.cfg.migrations_path) # Register migration commands def pw_migrate(name: str=None, fake: bool=False): """Run application's migrations. :param name: Choose a migration' name :param fake: Run as fake. Update migration history and don't touch the database """ self.router.run(name, fake=fake) self.app.manage.command(pw_migrate) def pw_rollback(name: str=None): """Rollback a migration. :param name: Migration name (actually it always should be a last one) """ if not name: name = self.router.done[-1] self.router.rollback(name) self.app.manage.command(pw_rollback) def pw_create(name: str='auto', auto: bool=False): """Create a migration. :param name: Set name of migration [auto] :param auto: Track changes and setup migrations automatically """ if auto: auto = list(self.models.values()) self.router.create(name, auto) self.app.manage.command(pw_create) def pw_list(): """List migrations.""" self.router.logger.info('Migrations are done:') self.router.logger.info('\n'.join(self.router.done)) self.router.logger.info('') self.router.logger.info('Migrations are undone:') self.router.logger.info('\n'.join(self.router.diff)) self.app.manage.command(pw_list) @self.app.manage.command def pw_merge(): """Merge migrations into one.""" self.router.merge() self.app.manage.command(pw_merge)
[ "Initialize", "the", "application", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/plugin.py#L43-L109
[ "def", "setup", "(", "self", ",", "app", ")", ":", "# noqa", "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:'", ":", "self", ".", "cfg", ".", "connection_manual", "=", "True", "if", "not", "self", ".", "cfg", ".", "migrations_enabled", ":", "return", "# Setup migration engine", "self", ".", "router", "=", "Router", "(", "self", ".", "database", ",", "migrate_dir", "=", "self", ".", "cfg", ".", "migrations_path", ")", "# Register migration commands", "def", "pw_migrate", "(", "name", ":", "str", "=", "None", ",", "fake", ":", "bool", "=", "False", ")", ":", "\"\"\"Run application's migrations.\n\n :param name: Choose a migration' name\n :param fake: Run as fake. Update migration history and don't touch the database\n \"\"\"", "self", ".", "router", ".", "run", "(", "name", ",", "fake", "=", "fake", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_migrate", ")", "def", "pw_rollback", "(", "name", ":", "str", "=", "None", ")", ":", "\"\"\"Rollback a migration.\n\n :param name: Migration name (actually it always should be a last one)\n \"\"\"", "if", "not", "name", ":", "name", "=", "self", ".", "router", ".", "done", "[", "-", "1", "]", "self", ".", "router", ".", "rollback", "(", "name", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_rollback", ")", "def", "pw_create", "(", "name", ":", "str", "=", "'auto'", ",", "auto", ":", "bool", "=", "False", ")", ":", "\"\"\"Create a migration.\n\n :param name: Set name of migration [auto]\n :param auto: Track changes and setup migrations automatically\n \"\"\"", "if", "auto", ":", "auto", "=", "list", "(", "self", ".", "models", ".", "values", "(", ")", ")", "self", ".", "router", ".", "create", "(", "name", ",", "auto", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_create", ")", "def", "pw_list", "(", ")", ":", "\"\"\"List migrations.\"\"\"", "self", ".", "router", ".", "logger", ".", "info", "(", "'Migrations are done:'", ")", "self", ".", "router", ".", "logger", ".", "info", "(", "'\\n'", ".", "join", "(", "self", ".", "router", ".", "done", ")", ")", "self", ".", "router", ".", "logger", ".", "info", "(", "''", ")", "self", ".", "router", ".", "logger", ".", "info", "(", "'Migrations are undone:'", ")", "self", ".", "router", ".", "logger", ".", "info", "(", "'\\n'", ".", "join", "(", "self", ".", "router", ".", "diff", ")", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_list", ")", "@", "self", ".", "app", ".", "manage", ".", "command", "def", "pw_merge", "(", ")", ":", "\"\"\"Merge migrations into one.\"\"\"", "self", ".", "router", ".", "merge", "(", ")", "self", ".", "app", ".", "manage", ".", "command", "(", "pw_merge", ")" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
Plugin.startup
Register connection's middleware and prepare self database.
muffin_peewee/plugin.py
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)
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)
[ "Register", "connection", "s", "middleware", "and", "prepare", "self", "database", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/plugin.py#L111-L115
[ "def", "startup", "(", "self", ",", "app", ")", ":", "self", ".", "database", ".", "init_async", "(", "app", ".", "loop", ")", "if", "not", "self", ".", "cfg", ".", "connection_manual", ":", "app", ".", "middlewares", ".", "insert", "(", "0", ",", "self", ".", "_middleware", ")" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e
valid
Plugin.cleanup
Close all connections.
muffin_peewee/plugin.py
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()
[ "Close", "all", "connections", "." ]
klen/muffin-peewee
python
https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/plugin.py#L117-L120
[ "def", "cleanup", "(", "self", ",", "app", ")", ":", "if", "hasattr", "(", "self", ".", "database", ".", "obj", ",", "'close_all'", ")", ":", "self", ".", "database", ".", "close_all", "(", ")" ]
8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e