_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q264600 | Room.get_users | validation | def get_users(self, sort=True):
""" Get list of users in the room.
Kwargs:
sort (bool): If True, sort rooms by name
Returns:
array. List of users
| python | {
"resource": ""
} |
q264601 | Room.set_name | validation | def set_name(self, name):
""" Set the room name.
Args:
name (str): Name
Returns:
bool. Success
"""
| python | {
"resource": ""
} |
q264602 | Room.set_topic | validation | def set_topic(self, topic):
""" Set the room topic.
Args:
topic (str): Topic
Returns:
bool. Success
"""
if not topic:
topic = ''
| python | {
"resource": ""
} |
q264603 | Room.speak | validation | def speak(self, message):
""" Post a message.
Args:
message (:class:`Message` or string): Message
Returns:
bool. Success
"""
campfire = self.get_campfire()
if not isinstance(message, Message):
message = Message(campfire, message)
result = self._connection.post(
| python | {
"resource": ""
} |
q264604 | Config.get_xdg_dirs | validation | def get_xdg_dirs(self):
# type: () -> List[str]
"""
Returns a list of paths specified by the XDG_CONFIG_DIRS environment
variable or the appropriate default.
The list is sorted by precedence, with the most important item coming
*last* (required by the existing config_resolver logic).
| python | {
"resource": ""
} |
q264605 | Config.get_xdg_home | validation | def get_xdg_home(self):
# type: () -> str
"""
Returns the value specified in the XDG_CONFIG_HOME environment variable
or the appropriate default.
"""
config_home = getenv('XDG_CONFIG_HOME', '')
if config_home:
self._log.debug('XDG_CONFIG_HOME is set to %r', config_home)
| python | {
"resource": ""
} |
q264606 | Config._effective_filename | validation | def _effective_filename(self):
# type: () -> str
"""
Returns the filename which is effectively used by the application. If
overridden by an environment variable, it will return that filename.
"""
# same logic for the configuration filename. First, check if we were
# initialized with a filename...
config_filename = ''
if self.filename:
config_filename = self.filename
# ... next, take the value from the environment
env_filename = getenv(self.env_filename_name)
if env_filename:
| python | {
"resource": ""
} |
q264607 | Config.check_file | validation | def check_file(self, filename):
# type: (str) -> bool
"""
Check if ``filename`` can be read. Will return boolean which is True if
the file can be read, False otherwise.
"""
if not exists(filename):
return False
# Check if the file is version-compatible with this instance.
new_config = ConfigResolverBase()
new_config.read(filename)
if self.version and not new_config.has_option('meta', 'version'):
# self.version is set, so we MUST have a version in the file!
raise NoVersionError(
"The config option 'meta.version' is missing in {}. The "
"application expects version {}!".format(filename,
self.version))
elif not self.version and new_config.has_option('meta', 'version'):
# Automatically "lock-in" a version number if one is found.
# This prevents loading a chain of config files with incompatible
| python | {
"resource": ""
} |
q264608 | Config.load | validation | def load(self, reload=False, require_load=False):
# type: (bool, bool) -> None
"""
Searches for an appropriate config file. If found, loads the file into
the current instance. This method can also be used to reload a
configuration. Note that you may want to set ``reload`` to ``True`` to
clear the configuration before loading in that case. Without doing
that, values will remain available even if they have been removed from
the config files.
:param reload: if set to ``True``, the existing values are cleared
before reloading.
:param require_load: If set to ``True`` this will raise a
:py:exc:`IOError` if no config file has been found
to load.
"""
if reload: # pragma: no cover
self.config = None
# only load the config if necessary (or explicitly requested)
if self.config: # pragma: no cover
self._log.debug('Returning cached config instance. Use '
'``reload=True`` to avoid caching!')
return
path = self._effective_path()
config_filename = self._effective_filename()
# Next, use the resolved path to find the filenames. Keep track of
# which files we loaded in order to inform the user.
self._active_path = [join(_, config_filename) for _ in path]
for dirname in path:
conf_name = join(dirname, config_filename)
readable = self.check_file(conf_name)
if readable:
action = 'Updating' if self._loaded_files else 'Loading initial'
self._log.info('%s config from %s', action, conf_name)
self.read(conf_name)
if conf_name == expanduser("~/.%s/%s/%s" % (
self.group_name, self.app_name, self.filename)):
self._log.warning(
"DEPRECATION WARNING: The file "
| python | {
"resource": ""
} |
q264609 | StylesResource.get | validation | def get(self, q=None, page=None):
"""Get styles."""
# Check cache to exit early if needed
etag = generate_etag(current_ext.content_version.encode('utf8'))
self.check_etag(etag, weak=True)
| python | {
"resource": ""
} |
q264610 | Connection.create_from_settings | validation | def create_from_settings(settings):
""" Create a connection with given settings.
Args:
settings (dict): A dictionary of settings
Returns:
:class:`Connection`. The connection
"""
return Connection(
settings["url"],
| python | {
"resource": ""
} |
q264611 | Connection.delete | validation | def delete(self, url=None, post_data={}, parse_data=False, key=None, parameters=None):
""" Issue a PUT request.
Kwargs:
url (str): Destination URL
post_data (dict): Dictionary of parameter and values
parse_data (bool): If true, parse response data
key (string): If parse_data==True, look for this key when parsing data
parameters (dict): Additional GET parameters to append to the URL
Returns:
dict. Response (a dict with keys: success, data, info, body)
| python | {
"resource": ""
} |
q264612 | Connection.post | validation | def post(self, url=None, post_data={}, parse_data=False, key=None, parameters=None, listener=None):
""" Issue a POST request.
Kwargs:
url (str): Destination URL
post_data (dict): Dictionary of parameter and values
parse_data (bool): If true, parse response data
key (string): If parse_data==True, look for this key when parsing data
parameters (dict): Additional GET parameters to append to the URL
listener (func): callback called when uploading a file
Returns:
dict. Response (a | python | {
"resource": ""
} |
q264613 | Connection.get | validation | def get(self, url=None, parse_data=True, key=None, parameters=None):
""" Issue a GET request.
Kwargs:
url (str): Destination URL
parse_data (bool): If true, parse response data
key (string): If parse_data==True, look for this key when parsing data
| python | {
"resource": ""
} |
q264614 | Connection.get_headers | validation | def get_headers(self):
""" Get headers.
Returns:
tuple: Headers
"""
headers = {
"User-Agent": "kFlame 1.0"
| python | {
"resource": ""
} |
q264615 | Connection._get_password_url | validation | def _get_password_url(self):
""" Get URL used for authentication
Returns:
string: URL
"""
password_url = None
if self._settings["user"] or self._settings["authorization"]: | python | {
"resource": ""
} |
q264616 | Connection.parse | validation | def parse(self, text, key=None):
""" Parses a response.
Args:
text (str): Text to parse
Kwargs:
key (str): Key to look for, if any
Returns:
Parsed value
Raises:
ValueError
"""
try:
data = json.loads(text)
except ValueError as e:
raise ValueError("%s: Value: [%s]" % (e, text))
| python | {
"resource": ""
} |
q264617 | Connection.build_twisted_request | validation | def build_twisted_request(self, method, url, extra_headers={}, body_producer=None, full_url=False):
""" Build a request for twisted
Args:
method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None
url (str): Destination URL (full, or relative)
Kwargs:
extra_headers (dict): Headers (override default connection headers, if any)
body_producer (:class:`twisted.web.iweb.IBodyProducer`): Object producing request body
full_url (bool): If False, URL is relative
Returns:
tuple. Tuple with two elements: reactor, and request
"""
| python | {
"resource": ""
} |
q264618 | Connection._fetch | validation | def _fetch(self, method, url=None, post_data=None, parse_data=True, key=None, parameters=None, listener=None, full_return=False):
""" Issue a request.
Args:
method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None
Kwargs:
url (str): Destination URL
post_data (str): A string of what to POST
parse_data (bool): If true, parse response data
key (string): If parse_data==True, look for this key when parsing data
parameters (dict): Additional GET parameters to append to the URL
listener (func): callback called when uploading a file
full_return (bool): If set to True, get a full response (with success, data, info, body)
Returns:
dict. Response. If full_return==True, a dict with keys: success, data, info, body, otherwise the parsed data
Raises:
AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError
"""
headers = self.get_headers()
headers["Content-Type"] = "application/json"
handlers = []
debuglevel = int(self._settings["debug"])
handlers.append(urllib2.HTTPHandler(debuglevel=debuglevel))
if hasattr(httplib, "HTTPS"):
handlers.append(urllib2.HTTPSHandler(debuglevel=debuglevel))
handlers.append(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
password_url = self._get_password_url()
| python | {
"resource": ""
} |
q264619 | Connection._url | validation | def _url(self, url=None, parameters=None):
""" Build destination URL.
Kwargs:
url (str): Destination URL
parameters (dict): Additional GET parameters to append to the URL
| python | {
"resource": ""
} |
q264620 | Message.is_text | validation | def is_text(self):
""" Tells if this message is a text message.
Returns:
bool. Success
| python | {
"resource": ""
} |
q264621 | Campfire.get_rooms | validation | def get_rooms(self, sort=True):
""" Get rooms list.
Kwargs:
sort (bool): If True, sort rooms by name
Returns:
array. List of rooms (each room is a dict)
"""
| python | {
"resource": ""
} |
q264622 | Campfire.get_room_by_name | validation | def get_room_by_name(self, name):
""" Get a room by name.
Returns:
:class:`Room`. Room
Raises:
RoomNotFoundException
"""
rooms = self.get_rooms()
for room in rooms or []:
| python | {
"resource": ""
} |
q264623 | Campfire.get_room | validation | def get_room(self, id):
""" Get room.
Returns:
:class:`Room`. Room
| python | {
"resource": ""
} |
q264624 | Campfire.get_user | validation | def get_user(self, id = None):
""" Get user.
Returns:
:class:`User`. User
"""
if not id:
id = self._user.id
if id not in self._users:
| python | {
"resource": ""
} |
q264625 | Campfire.search | validation | def search(self, terms):
""" Search transcripts.
Args:
terms (str): Terms for search
Returns:
array. Messages
"""
messages | python | {
"resource": ""
} |
q264626 | Stream.attach | validation | def attach(self, observer):
""" Attach an observer.
Args:
observer (func): A function to be called when new messages arrive
Returns:
:class:`Stream`. Current instance to allow chaining
| python | {
"resource": ""
} |
q264627 | Stream.incoming | validation | def incoming(self, messages):
""" Called when incoming messages arrive.
Args:
messages (tuple): Messages (each message is a dict)
"""
if self._observers:
campfire = self._room.get_campfire()
| python | {
"resource": ""
} |
q264628 | StreamProcess.fetch | validation | def fetch(self):
""" Fetch new messages. """
try:
if not self._last_message_id:
messages = self._connection.get("room/%s/recent" % self._room_id, key="messages", parameters={
"limit": 1
})
self._last_message_id = messages[-1]["id"]
messages = | python | {
"resource": ""
} |
q264629 | StreamProcess.received | validation | def received(self, messages):
""" Called when new messages arrive.
Args:
messages (tuple): Messages
"""
if messages:
if self._queue:
| python | {
"resource": ""
} |
q264630 | LiveStreamProtocol.connectionMade | validation | 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:
| python | {
"resource": ""
} |
q264631 | LiveStreamProtocol.lineReceived | validation | 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:
| python | {
"resource": ""
} |
q264632 | LiveStreamProtocol.rawDataReceived | validation | 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:
| python | {
"resource": ""
} |
q264633 | _InvenioCSLRESTState.styles | validation | def styles(self):
"""Get a dictionary of CSL styles."""
styles = get_all_styles()
whitelist = self.app.config.get('CSL_STYLES_WHITELIST')
if whitelist:
| python | {
"resource": ""
} |
q264634 | MultiPartProducer.startProducing | validation | 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:
| python | {
"resource": ""
} |
q264635 | MultiPartProducer._finish | validation | 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:
| python | {
"resource": ""
} |
q264636 | MultiPartProducer._send_to_consumer | validation | def _send_to_consumer(self, block):
""" Send a block of bytes to the consumer.
Args:
block (str): Block of bytes
"""
| python | {
"resource": ""
} |
q264637 | MultiPartProducer._length | validation | 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:
| python | {
"resource": ""
} |
q264638 | MultiPartProducer._build_chunk_headers | validation | 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:
| python | {
"resource": ""
} |
q264639 | MultiPartProducer._file_size | validation | 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], | python | {
"resource": ""
} |
q264640 | _filename | validation | 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(
| python | {
"resource": ""
} |
q264641 | _str_to_path | validation | 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 | python | {
"resource": ""
} |
q264642 | _path_root | validation | 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),
| python | {
"resource": ""
} |
q264643 | fspaths | validation | 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)
| python | {
"resource": ""
} |
q264644 | CodeBuilder._exec | validation | def _exec(self, globals_dict=None):
"""exec compiled code"""
globals_dict = globals_dict or {}
| python | {
"resource": ""
} |
q264645 | Template.handle_extends | validation | 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'))
| python | {
"resource": ""
} |
q264646 | Template.flush_buffer | validation | def flush_buffer(self):
"""flush all buffered string into code"""
self.code_builder.add_line('{0}.extend([{1}])',
| python | {
"resource": ""
} |
q264647 | UploadProcess.add_data | validation | def add_data(self, data):
""" Add POST data.
Args:
data (dict): key => value dictionary
"""
| python | {
"resource": ""
} |
q264648 | API.log_error | validation | 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:
| python | {
"resource": ""
} |
q264649 | API.parse_conll | validation | 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,
| python | {
"resource": ""
} |
q264650 | CampfireEntity.set_data | validation | 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:
| python | {
"resource": ""
} |
q264651 | validate_xml_text | validation | 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:
| python | {
"resource": ""
} |
q264652 | validate_xml_name | validation | 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')
| python | {
"resource": ""
} |
q264653 | GameStage.on_enter_stage | validation | 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 | python | {
"resource": ""
} |
q264654 | GameStage.on_update_stage | validation | 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:
| python | {
"resource": ""
} |
q264655 | GameStage.on_exit_stage | validation | 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 | python | {
"resource": ""
} |
q264656 | DebugPanel.render_vars | validation | def render_vars(self):
"""Template variables."""
return {
'records': [
{
'message': record.getMessage(),
| python | {
"resource": ""
} |
q264657 | AIODatabase.init_async | validation | 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)
| python | {
"resource": ""
} |
q264658 | AIODatabase.async_connect | validation | 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')
| python | {
"resource": ""
} |
q264659 | PooledAIODatabase.init_async | validation | def init_async(self, loop):
"""Initialize self."""
super(PooledAIODatabase, | python | {
"resource": ""
} |
q264660 | PooledAIODatabase.async_connect | validation | 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)
| python | {
"resource": ""
} |
q264661 | PooledAIODatabase._close | validation | def _close(self, conn):
"""Release waiters."""
super(PooledAIODatabase, self)._close(conn)
for waiter in | python | {
"resource": ""
} |
q264662 | ClientForum.receive_id_from_server | validation | 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 | python | {
"resource": ""
} |
q264663 | ClientForum.execute_sync | validation | 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}")
| python | {
"resource": ""
} |
q264664 | ClientForum.execute_undo | validation | 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(): | python | {
"resource": ""
} |
q264665 | ServerActor._relay_message | validation | 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 | python | {
"resource": ""
} |
q264666 | generate | validation | def generate(request):
""" Create a new DataItem. """
models.DataItem.create(
| python | {
"resource": ""
} |
q264667 | require_active_token | validation | 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
| python | {
"resource": ""
} |
q264668 | TokenSafetyChecks.add_safety_checks | validation | 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.
"""
| python | {
"resource": ""
} |
q264669 | Token.watch_method | validation | 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.""") | python | {
"resource": ""
} |
q264670 | Token._remove_from_world | validation | 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.
| python | {
"resource": ""
} |
q264671 | World._unlock_temporarily | validation | 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.
| python | {
"resource": ""
} |
q264672 | scan | validation | 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}
| python | {
"resource": ""
} |
q264673 | unscan | validation | 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)
| python | {
"resource": ""
} |
q264674 | parse | validation | 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:
| python | {
"resource": ""
} |
q264675 | subtree | validation | def subtree(events):
"""selects sub-tree events"""
stack = 0
for obj in events:
if obj['type'] == ENTER:
stack += 1
elif obj['type'] == EXIT:
| python | {
"resource": ""
} |
q264676 | merge_text | validation | 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: | python | {
"resource": ""
} |
q264677 | with_peer | validation | 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)
| python | {
"resource": ""
} |
q264678 | BusinessDate.from_date | validation | 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
| python | {
"resource": ""
} |
q264679 | BusinessDate.to_date | validation | def to_date(self):
"""
construct datetime.date instance represented calendar date of BusinessDate instance
:return datetime.date:
| python | {
"resource": ""
} |
q264680 | BusinessDate.add_period | validation | 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 | python | {
"resource": ""
} |
q264681 | BusinessDate.add_months | validation | 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 | python | {
"resource": ""
} |
q264682 | BusinessDate.add_business_days | validation | 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)
| python | {
"resource": ""
} |
q264683 | quoted | validation | 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 | python | {
"resource": ""
} |
q264684 | days_in_month | validation | 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:
| python | {
"resource": ""
} |
q264685 | Plugin.setup | validation | 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):
| python | {
"resource": ""
} |
q264686 | Plugin.startup | validation | def startup(self, app):
"""Register connection's middleware and prepare self database."""
self.database.init_async(app.loop)
if | python | {
"resource": ""
} |
q264687 | Plugin.cleanup | validation | def cleanup(self, app):
"""Close all connections."""
if | python | {
"resource": ""
} |
q264688 | Plugin.register | validation | def register(self, model):
"""Register a model in self."""
self.models[model._meta.table_name] = model
| python | {
"resource": ""
} |
q264689 | Plugin.manage | validation | async def manage(self):
"""Manage a database connection."""
cm = _ContextManager(self.database)
if isinstance(self.database.obj, AIODatabase): | python | {
"resource": ""
} |
q264690 | migrate | validation | def migrate(migrator, database, **kwargs):
""" Write your migrations here.
> Model = migrator.orm['name']
> migrator.sql(sql)
> migrator.create_table(Model)
> migrator.drop_table(Model, cascade=True)
> migrator.add_columns(Model, **fields)
> migrator.change_columns(Model, **fields)
> migrator.drop_columns(Model, *field_names, cascade=True)
> migrator.rename_column(Model, old_field_name, new_field_name)
> migrator.rename_table(Model, new_table_name)
> migrator.add_index(Model, *col_names, unique=False)
> migrator.drop_index(Model, index_name)
> migrator.add_not_null(Model, | python | {
"resource": ""
} |
q264691 | chain | validation | def chain(*args):
"""Runs a series of parsers in sequence passing the result of each parser to the next.
The result of the last parser is returned.
"""
def chain_block(*args, **kwargs):
| python | {
"resource": ""
} |
q264692 | one_of | validation | def one_of(these):
"""Returns the current token if is found in the collection provided.
Fails otherwise.
"""
ch = peek()
try:
if (ch is EndOfFile) or (ch not in these):
| python | {
"resource": ""
} |
q264693 | not_one_of | validation | def not_one_of(these):
"""Returns the current token if it is not found in the collection provided.
The negative of one_of.
"""
ch = peek()
desc = "not_one_of" + repr(these)
try:
if (ch is EndOfFile) or (ch in these):
| python | {
"resource": ""
} |
q264694 | satisfies | validation | def satisfies(guard):
"""Returns the current token if it satisfies the guard function provided.
Fails otherwise.
This is the a generalisation of one_of.
"""
i = peek() | python | {
"resource": ""
} |
q264695 | not_followed_by | validation | def not_followed_by(parser):
"""Succeeds if the given parser cannot consume input"""
@tri
def not_followed_by_block():
| python | {
"resource": ""
} |
q264696 | many | validation | def many(parser):
"""Applies the parser to input zero or more times.
Returns a list of parser results.
"""
results = []
terminate = object()
while local_ps.value:
| python | {
"resource": ""
} |
q264697 | many_until | validation | def many_until(these, term):
"""Consumes as many of these as it can until it term is encountered.
Returns a tuple of the list of these results and the term result
"""
results = []
while True:
stop, result = choice(_tag(True, term),
| python | {
"resource": ""
} |
q264698 | many_until1 | validation | def many_until1(these, term):
"""Like many_until but must consume at least one of these.
"""
first = [these()]
these_results, term_result | python | {
"resource": ""
} |
q264699 | sep1 | validation | def sep1(parser, separator):
"""Like sep but must consume at least one of parser.
"""
first = [parser()]
def inner(): | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.