Search is not available for this dataset
text
stringlengths
75
104k
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 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 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 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 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 _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 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 init_app(self, app): """Flask application initialization.""" state = _InvenioCSLRESTState(app) app.extensions['invenio-csl-rest'] = state return state
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 resumeProducing(self): """ Resume producing """ self._paused = False result = self._produce() if result: return result
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 _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 _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 _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 _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 _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 _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 _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_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 _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 _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 _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 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 _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 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 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 strip_token(self, text, start, end): """{{ a }} -> a""" text = text.replace(start, '', 1) text = text.replace(end, '', 1) return text
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 add_data(self, data): """ Add POST data. Args: data (dict): key => value dictionary """ if not self._data: self._data = {} self._data.update(data)
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 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 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 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 _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 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_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 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): """ 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 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_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_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 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 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 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 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()
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
def init_async(self, loop): """Initialize self.""" super(PooledAIODatabase, self).init_async(loop) self._waiters = collections.deque()
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
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 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 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_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 _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 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 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 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_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 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 _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 _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 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 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 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 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 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 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 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 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_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 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 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_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 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_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_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 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 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_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_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_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 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_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_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_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 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 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 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 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 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_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 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_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_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 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 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_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 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 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 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 cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()