Search is not available for this dataset
text stringlengths 75 104k |
|---|
def p_navigation_step_2(self, p):
'''navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR'''
p[0] = NavigationStepNode(key_letter=p[2],
rel_id=p[4],
phrase=p[6]) |
def p_implicit_invocation(self, p):
'''implicit_invocation : namespace DOUBLECOLON identifier LPAREN parameter_list RPAREN'''
p[0] = ImplicitInvocationNode(namespace=p[1],
action_name=p[3],
parameter_list=p[5]) |
def p_operation_invocation_1(self, p):
'''instance_invocation : structure DOT identifier LPAREN parameter_list RPAREN'''
p[0] = InstanceInvocationNode(handle=p[1],
action_name=p[3],
parameter_list=p[5]) |
def p_arithmetic_expression(self, p):
'''
expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIV expression
| expression MOD expression
'''
p[0] ... |
def p_boolean_expression(self, p):
'''
expression : expression LE expression
| expression LESSTHAN expression
| expression DOUBLEEQUAL expression
| expression NOTEQUAL expression
| expression GE expressio... |
def wrap(cls, message_parts):
"""Wraps exceptions in the context with :exc:`MalformedMessage`."""
try:
yield
except BaseException as exception:
__, __, tb = sys.exc_info()
reraise(cls, cls(exception, message_parts), tb) |
async def api_crime(request):
"""
Gets the crime nearby to a given postcode.
:param request: The aiohttp request.
:return: A json representation of the crimes near the postcode.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
try:
coroutine = get_postcode_rand... |
async def api_neighbourhood(request):
"""
Gets police data about a neighbourhood.
:param request: The aiohttp request.
:return: The police data for that post code.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
try:
postcode = (await get_postcode_random()) if... |
def create_queue(self, name, strict=True, auto_delete=False, auto_delete_timeout=0):
"""Create message content and properties to create queue with QMFv2
:param name: Name of queue to create
:type name: str
:param strict: Whether command should fail when unrecognized properties are provi... |
def delete_queue(self, name):
"""Create message content and properties to delete queue with QMFv2
:param name: Name of queue to delete
:type name: str
:returns: Tuple containing content and method properties
"""
content = {"_object_id": {"_object_name": self.object_name... |
def list_queues(self):
"""Create message content and properties to list all queues with QMFv2
:returns: Tuple containing content and query properties
"""
content = {"_what": "OBJECT",
"_schema_id": {"_class_name": "queue"}}
logger.debug("Message content -> {0}... |
def list_exchanges(self):
"""Create message content and properties to list all exchanges with QMFv2
:returns: Tuple containing content and query properties
"""
content = {"_what": "OBJECT",
"_schema_id": {"_class_name": "exchange"}}
logger.debug("Message conte... |
def purge_queue(self, name):
"""Create message content and properties to purge queue with QMFv2
:param name: Name of queue to purge
:type name: str
:returns: Tuple containing content and method properties
"""
content = {"_object_id": {"_object_name": "org.apache.qpid.br... |
def _create_msg(self, to, subject, msgHtml, msgPlain, attachments=None):
'''
attachments should be a list of paths
'''
sender = self.sender
if attachments and isinstance(attachments, str):
attachments = [attachments]
else:
attachments = list(attach... |
def set_remote_exception(self, remote_exc_info):
"""Raises an exception as a :exc:`RemoteException`."""
exc_type, exc_str, filename, lineno = remote_exc_info[:4]
exc_type = RemoteException.compose(exc_type)
exc = exc_type(exc_str, filename, lineno, self.worker_info)
if len(remote... |
def read(self):
"""
Returns the text from an image at a given url.
"""
# Only download the image if it has changed
if self.connection.has_changed():
image_path = self.connection.download_image()
image = Image.open(image_path)
self.text_cache =... |
def text_visible(self):
"""
Returns true or false based on if the OCR process has read
actual words. This is needed to prevent non-words from being
added to the queue since the ocr process can sometimes return
values that are not meaningfull.
"""
# Split the inpu... |
def get_most_recent_bike() -> Optional['Bike']:
"""
Gets the most recently cached bike from the database.
:return: The bike that was cached most recently.
"""
try:
return Bike.select().order_by(Bike.cached_date.desc()).get()
except pw.DoesNotExist:
... |
def main():
'''
Parse command line options and launch the interpreter
'''
parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]",
version=xtuml.version.complete_string,
formatter=optparse.TitledHelp... |
def main():
'''
Parse argv for options and arguments, and start schema generation.
'''
parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path...]",
version=xtuml.version.complete_string,
formatter=optpa... |
def get_token(client_id, client_secret, client_access_token, page=None):
"""
See: http://nodotcom.org/python-facebook-tutorial.html
"""
payload = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
}
if client_access_token:
... |
def get_page_api(client_access_token, page_id):
"""
You can also skip the above if you get a page token:
http://stackoverflow.com/questions/8231877
and make that long-lived token as in Step 3
"""
graph = GraphAPI(client_access_token)
# Get page token to post as the page. You can skip
# t... |
def serialize_value(value, ty):
'''
Serialize a value from an xtuml metamodel instance.
'''
ty = ty.upper()
null_value = {
'BOOLEAN' : False,
'INTEGER' : 0,
'REAL' : 0.0,
'STRING' : '',
'UNIQUE_ID' : 0
}
transfer_fn = {
'B... |
def serialize_instance(instance):
'''
Serialize an *instance* from a metamodel.
'''
attr_count = 0
metaclass = xtuml.get_metaclass(instance)
s = 'INSERT INTO %s VALUES (' % metaclass.kind
for name, ty in metaclass.attributes:
value = getattr(instance, name)
s += ... |
def serialize_instances(metamodel):
'''
Serialize all instances in a *metamodel*.
'''
s = ''
for inst in metamodel.instances:
s += serialize_instance(inst)
return s |
def serialize_association(ass):
'''
Serialize an xtuml metamodel association.
'''
s1 = '%s %s (%s)' % (ass.source_link.cardinality,
ass.source_link.to_metaclass.kind,
', '.join(ass.source_keys))
if ass.target_link.phrase:
s1 += " PHRASE '%s'... |
def serialize_class(Cls):
'''
Serialize an xtUML metamodel class.
'''
metaclass = xtuml.get_metaclass(Cls)
attributes = ['%s %s' % (name, ty.upper()) for name, ty in metaclass.attributes]
s = 'CREATE TABLE %s (\n ' % metaclass.kind
s += ',\n '.join(attributes)
s += '\n);\n'
... |
def serialize_schema(metamodel):
'''
Serialize all class and association definitions in a *metamodel*.
'''
s = ''
for kind in sorted(metamodel.metaclasses.keys()):
s += serialize_class(metamodel.metaclasses[kind].clazz)
for ass in sorted(metamodel.associations, key=lambda x: x.rel_i... |
def serialize_database(metamodel):
'''
Serialize all instances, class definitions, association definitions, and
unique identifiers in a *metamodel*.
'''
schema = serialize_schema(metamodel)
instances = serialize_instances(metamodel)
identifiers = serialize_unique_identifiers(metamodel)
... |
def serialize(resource):
'''
Serialize some xtuml *resource*, e.g. an instance or a complete metamodel.
'''
if isinstance(resource, xtuml.MetaModel):
return serialize_database(resource)
elif isinstance(resource, type) and issubclass(resource, xtuml.Class):
return serialize_class(res... |
def persist_instances(metamodel, path, mode='w'):
'''
Persist all instances in a *metamodel* by serializing them and saving to a
*path* on disk.
'''
with open(path, mode) as f:
for inst in metamodel.instances:
s = serialize_instance(inst)
f.write(s) |
def persist_schema(metamodel, path, mode='w'):
'''
Persist all class and association definitions in a *metamodel* by
serializing them and saving to a *path* on disk.
'''
with open(path, mode) as f:
for kind in sorted(metamodel.metaclasses.keys()):
s = serialize_class(metamodel.m... |
def persist_unique_identifiers(metamodel, path, mode='w'):
'''
Persist all unique identifiers in a *metamodel* by serializing them and
saving to a *path* on disk.
'''
with open(path, mode) as f:
for metaclass in metamodel.metaclasses.values():
for index_name, attribute_names in m... |
def persist_database(metamodel, path, mode='w'):
'''
Persist all instances, class definitions and association definitions in a
*metamodel* by serializing them and saving to a *path* on disk.
'''
with open(path, mode) as f:
for kind in sorted(metamodel.metaclasses.keys()):
metacla... |
def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() |
def load(filename):
"""Load variable from Pickle file
Args:
path (str): path of the file to load
Returns:
variable read from path
"""
fileObj = open(filename, 'rb')
variable = pickle.load(fileObj)
fileObj.close()
return variable |
def main():
"""Function for command line execution"""
parser = ArgumentParser(description="search files using n-grams")
parser.add_argument('--path', dest='path', help="where to search", nargs=1, action="store", default=getcwd())
parser.add_argument('--update', dest='update', help="update the index", a... |
def search(self, query, verbose=0):
"""Searches files satisfying query
It first decompose the query in ngrams, then score each document containing
at least one ngram with the number. The ten document having the most ngrams
in common with the query are selected.
Args:
... |
def partition(condition, collection) -> Tuple[List, List]:
"""Partitions a list into two based on a condition."""
succeed, fail = [], []
for x in collection:
if condition(x):
succeed.append(x)
else:
fail.append(x)
return succeed, fail |
async def cli(location_strings: Tuple[str], random_postcodes_count: int, *,
bikes: bool = False, crime: bool = False,
nearby: bool = False, as_json: bool = False):
"""
Runs the CLI app.
Tries to execute as many steps as possible to give the user
the best understanding of the ... |
async def fetch_neighbourhood(lat: float, long: float) -> Optional[dict]:
"""
Gets the neighbourhood from the fetch that is associated with the given postcode.
:return: A neighbourhood object parsed from the fetch.
:raise ApiError: When there was an error connecting to the API.
"""
lookup_url =... |
async def fetch_crime(lat: float, long: float) -> List[Dict]:
"""
Gets crime for a given lat and long.
:raise ApiError: When there was an error connecting to the API.
todo cache
"""
crime_lookup = f"https://data.police.uk/api/crimes-street/all-crime?lat={lat}&lng={long}"
async with ClientSe... |
def run(locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path,
verbose):
"""
Runs the program. Takes a list of postcodes or coordinates and
returns various information about them. If using the cli, make
sure to update the bikes database with t... |
def bidi(request):
"""Adds to the context BiDi related variables
LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl')
LANGUAGE_START -- Start of language layout ('right' for rtl, 'left'
for 'ltr')
LANGUAGE_END -- End of language layout ('left' for rtl, 'right'
... |
def _is_null(instance, name):
'''
Determine if an attribute of an *instance* with a specific *name*
is null.
'''
if name in instance.__dict__:
value = instance.__dict__[name]
else:
value = getattr(instance, name)
if value:
return False
elif value is None:
... |
def apply_query_operators(iterable, ops):
'''
Apply a series of query operators to a sequence of instances, e.g.
where_eq(), order_by() or filter functions.
'''
for op in ops:
if isinstance(op, WhereEqual):
iterable = op(iterable)
elif isinstance(op, OrderBy)... |
def navigate_subtype(supertype, rel_id):
'''
Perform a navigation from *supertype* to its subtype across *rel_id*. The
navigated association must be modeled as a subtype-supertype association.
The return value will an instance or None.
'''
if not supertype:
return
if isinst... |
def sort_reflexive(set_of_instances, rel_id, phrase):
'''
Sort a *set of instances* in the order they appear across a conditional and
reflexive association. The first instance in the resulting ordered set is
**not** associated to an instance across the given *phrase*.
'''
if not isinstance(set_o... |
def _find_link(inst1, inst2, rel_id, phrase):
'''
Find links that correspond to the given arguments.
'''
metaclass1 = get_metaclass(inst1)
metaclass2 = get_metaclass(inst2)
if isinstance(rel_id, int):
rel_id = 'R%d' % rel_id
for ass in metaclass1.metamodel.associations:
... |
def relate(from_instance, to_instance, rel_id, phrase=''):
'''
Relate *from_instance* to *to_instance* across *rel_id*. For reflexive
association, a *phrase* indicating the direction must also be provided.
The two instances are related to each other by copying the identifying
attributes from t... |
def unrelate(from_instance, to_instance, rel_id, phrase=''):
'''
Unrelate *from_instance* from *to_instance* across *rel_id*. For reflexive
associations, a *phrase* indicating the direction must also be provided.
The two instances are unrelated from each other by reseting the identifying
attrib... |
def get_metaclass(class_or_instance):
'''
Get the metaclass for a *class_or_instance*.
'''
if isinstance(class_or_instance, Class):
return class_or_instance.__metaclass__
elif issubclass(class_or_instance, Class):
return class_or_instance.__metaclass__
raise MetaExcepti... |
def delete(instance, disconnect=True):
'''
Delete an *instance* from its metaclass instance pool and optionally
*disconnect* it from any links it might be connected to.
'''
if not isinstance(instance, Class):
raise DeleteException("the provided argument is not an xtuml instance")
... |
def formalize(self):
'''
Formalize the association and expose referential attributes
on instances.
'''
source_class = self.source_link.to_metaclass
target_class = self.target_link.to_metaclass
source_class.referential_attributes |= set(self.source_keys)
... |
def cardinality(self):
'''
Obtain the cardinality string.
Example: '1C' for a conditional link with a single instance [0..1]
'MC' for a link with any number of instances [0..*]
'M' for a more than one instance [1..*]
'M' for a link wi... |
def connect(self, instance, another_instance, check=True):
'''
Connect an *instance* to *another_instance*.
Optionally, disable any cardinality *check* that would prevent the two
instances from being connected.
'''
if instance not in self:
self[instan... |
def disconnect(self, instance, another_instance):
'''
Disconnect an *instance* from *another_instance*.
'''
if instance not in self:
return False
if another_instance not in self[instance]:
return False
self[instance].remove(another_insta... |
def compute_lookup_key(self, from_instance):
'''
Compute the lookup key for an instance, i.e. a foreign key that
can be used to identify an instance at the end of the link.
'''
kwargs = dict()
for attr, other_attr in self.key_map.items():
if _is_null(from_inst... |
def compute_index_key(self, to_instance):
'''
Compute the index key that can be used to identify an instance
on the link.
'''
kwargs = dict()
for attr in self.key_map.values():
if _is_null(to_instance, attr):
return None
... |
def attribute_type(self, attribute_name):
'''
Obtain the type of an attribute.
'''
attribute_name = attribute_name.upper()
for name, ty in self.attributes:
if name.upper() == attribute_name:
return ty |
def add_link(self, metaclass, rel_id, phrase, conditional, many):
'''
Add a new link from *self* to *metaclass*.
'''
link = Link(self, rel_id, metaclass, phrase, conditional, many)
key = (metaclass.kind.upper(), rel_id, phrase)
self.links[key] = link
return link |
def append_attribute(self, name, type_name):
'''
Append an attribute with a given *name* and *type name* at the end of
the list of attributes.
'''
attr = (name, type_name)
self.attributes.append(attr) |
def insert_attribute(self, index, name, type_name):
'''
Insert an attribute with a given *name* and *type name* at some *index*
in the list of attributes.
'''
attr = (name, type_name)
self.attributes.insert(index, attr) |
def delete_attribute(self, name):
'''
Delete an attribute with a given *name* from the list of attributes.
'''
for idx, attr in enumerate(self.attributes):
attr_name, _ = attr
if attr_name == name:
del self.attributes[idx]
return |
def default_value(self, type_name):
'''
Obtain the default value for some *type name*.
'''
uname = type_name.upper()
if uname == 'BOOLEAN':
return False
elif uname == 'INTEGER':
return 0
elif uname == 'REAL':
... |
def new(self, *args, **kwargs):
'''
Create and return a new instance.
'''
inst = self.clazz()
self.storage.append(inst)
# set all attributes with an initial default value
referential_attributes = dict()
for name, ty in self.attributes:
... |
def clone(self, instance):
'''
Create a shallow clone of an *instance*.
**Note:** the clone and the original instance **does not** have to be
part of the same metaclass.
'''
args = list()
for name, _ in get_metaclass(instance).attributes:
val... |
def delete(self, instance, disconnect=True):
'''
Delete an *instance* from the instance pool and optionally *disconnect*
it from any links it might be connected to. If the *instance* is not
part of the metaclass, a *MetaException* is thrown.
'''
if instance in self.storag... |
def select_one(self, *args):
'''
Select a single instance from the instance pool. Query operators such as
where_eq(), order_by() or filter functions may be passed as optional
arguments.
'''
s = apply_query_operators(self.storage, args)
return next(iter(s), None) |
def select_many(self, *args):
'''
Select several instances from the instance pool. Query operators such as
where_eq(), order_by() or filter functions may be passed as optional
arguments.
'''
s = apply_query_operators(self.storage, args)
if isinstance(s, QuerySet):... |
def navigate(self, inst, kind, rel_id, phrase=''):
'''
Navigate across a link with some *rel_id* and *phrase* that yields
instances of some *kind*.
'''
key = (kind.upper(), rel_id, phrase)
if key in self.links:
link = self.links[key]
return link.na... |
def instances(self):
'''
Obtain a sequence of all instances in the metamodel.
'''
for metaclass in self.metaclasses.values():
for inst in metaclass.storage:
yield inst |
def define_class(self, kind, attributes, doc=''):
'''
Define a new class in the metamodel, and return its metaclass.
'''
ukind = kind.upper()
if ukind in self.metaclasses:
raise MetaModelException('A class with the name %s is already defined' % kind)
metaclas... |
def find_metaclass(self, kind):
'''
Find a metaclass of some *kind* in the metamodel.
'''
ukind = kind.upper()
if ukind in self.metaclasses:
return self.metaclasses[ukind]
else:
raise UnknownClassException(kind) |
def new(self, kind, *args, **kwargs):
'''
Create and return a new instance in the metamodel of some *kind*.
Optionally, initial attribute values may be assigned to the new instance
by passing them as positional or keyword arguments. Positional arguments
are assigned in t... |
def clone(self, instance):
'''
Create a shallow clone of an *instance*.
**Note:** the clone and the original instance **does not** have to be
part of the same metaclass.
'''
metaclass = get_metaclass(instance)
metaclass = self.find_metaclass(metaclass.ki... |
def define_association(self, rel_id, source_kind, source_keys, source_many,
source_conditional, source_phrase, target_kind,
target_keys, target_many, target_conditional,
target_phrase):
'''
Define and return an associatio... |
def define_unique_identifier(self, kind, name, *named_attributes):
'''
Define a unique identifier for some *kind* of class based on its
*named attributes*.
'''
if not named_attributes:
return
if isinstance(name, int):
name = 'I%d' % name
... |
def select_many(self, kind, *args):
'''
Query the metamodel for a set of instances of some *kind*. Query
operators such as where_eq(), order_by() or filter functions may be
passed as optional arguments.
Usage example:
>>> m = xtuml.load_metamodel('db.sql... |
def select_one(self, kind, *args):
'''
Query the metamodel for a single instance of some *kind*. Query
operators such as where_eq(), order_by() or filter functions may be
passed as optional arguments.
Usage example:
>>> m = xtuml.load_metamodel('db.sql')... |
async def api_twitter(request):
"""
Gets the twitter feed from a given handle.
:return: The feed in json format.
"""
handle = request.match_info.get('handle', None)
if handle is None:
raise web.HTTPNotFound(body="Not found.")
try:
posts = await fetch_twitter(handle)
exce... |
def send(socket, header, payload, topics=(), flags=0):
"""Sends header, payload, and topics through a ZeroMQ socket.
:param socket: a zmq socket.
:param header: a list of byte strings which represent a message header.
:param payload: the serialized byte string of a payload.
:param topics: a chain o... |
def recv(socket, flags=0, capture=(lambda msgs: None)):
"""Receives header, payload, and topics through a ZeroMQ socket.
:param socket: a zmq socket.
:param flags: zmq flags to receive messages.
:param capture: a function to capture received messages.
"""
msgs = eintr_retry_zmq(socket.recv_mul... |
def dead_code():
"""
This also finds code you are working on today!
"""
with safe_cd(SRC):
if IS_TRAVIS:
command = "{0} vulture {1}".format(PYTHON, PROJECT_NAME).strip().split()
else:
command = "{0} vulture {1}".format(PIPENV, PROJECT_NAME).strip().split()
... |
def parse_emails(values):
'''
Take a string or list of strings and try to extract all the emails
'''
emails = []
if isinstance(values, str):
values = [values]
# now we know we have a list of strings
for value in values:
matches = re_emails.findall(value)
emails.extend... |
def rpc(f=None, **kwargs):
"""Marks a method as RPC."""
if f is not None:
if isinstance(f, six.string_types):
if 'name' in kwargs:
raise ValueError('name option duplicated')
kwargs['name'] = f
else:
return rpc(**kwargs)(f)
return functools.... |
def rpc_spec_table(app):
"""Collects methods which are speced as RPC."""
table = {}
for attr, value in inspect.getmembers(app):
rpc_spec = get_rpc_spec(value, default=None)
if rpc_spec is None:
continue
table[rpc_spec.name] = (value, rpc_spec)
return table |
async def normalize_postcode_middleware(request, handler):
"""
If there is a postcode in the url it validates and normalizes it.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
if postcode is None or postcode == "random":
return await handler(request)
elif not is_... |
def make_repr(obj, params=None, keywords=None, data=None, name=None,
reprs=None):
"""Generates a string of object initialization code style. It is useful
for custom __repr__ methods::
class Example(object):
def __init__(self, param, keyword=None):
self.param = p... |
def eintr_retry(exc_type, f, *args, **kwargs):
"""Calls a function. If an error of the given exception type with
interrupted system call (EINTR) occurs calls the function again.
"""
while True:
try:
return f(*args, **kwargs)
except exc_type as exc:
if exc.errno !... |
def eintr_retry_zmq(f, *args, **kwargs):
"""The specialization of :func:`eintr_retry` by :exc:`zmq.ZMQError`."""
return eintr_retry(zmq.ZMQError, f, *args, **kwargs) |
def next(self):
'''
Progress to the next identifier, and return the current one.
'''
val = self._current
self._current = self.readfunc()
return val |
def enter(self, node):
'''
Tries to invoke a method matching the pattern *enter_<type name>*, where
<type name> is the name of the type of the *node*.
'''
name = 'enter_' + node.__class__.__name__
fn = getattr(self, name, self.default_enter)
fn(node) |
def leave(self, node):
'''
Tries to invoke a method matching the pattern *leave_<type name>*, where
<type name> is the name of the type of the *node*.
'''
name = 'leave_' + node.__class__.__name__
fn = getattr(self, name, self.default_leave)
fn(node) |
def accept(self, node, **kwargs):
'''
Invoke the visitors before and after decending down the tree.
The walker will also try to invoke a method matching the pattern
*accept_<type name>*, where <type name> is the name of the accepted
*node*.
'''
if node is None:
... |
def default_accept(self, node, **kwargs):
'''
The default accept behaviour is to decend into the iterable member
*node.children* (if available).
'''
if not hasattr(node, 'children'):
return
for child in node.children:
self.accept(child, **... |
def render(self, node):
'''
Try to invoke a method matching the pattern *render_<type name>*, where
<type name> is the name of the rendering *node*.
'''
name = 'render_' + type(node).__name__
fn = getattr(self, name, self.default_render)
return fn(node) |
def accept_S_SYS(self, inst):
'''
A System Model contains top-level packages
'''
for child in many(inst).EP_PKG[1401]():
self.accept(child) |
def accept_C_C(self, inst):
'''
A Component contains packageable elements
'''
for child in many(inst).PE_PE[8003]():
self.accept(child) |
def accept_EP_PKG(self, inst):
'''
A Package contains packageable elements
'''
for child in many(inst).PE_PE[8000]():
self.accept(child) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.