code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
try:
sess = self.sessions[session]
if sess is not self:
sess.close()
except KeyError:
return StatusCode.error_invalid_object | def close(self, session) | Closes the specified session, event, or find list.
Corresponds to viClose function of the VISA library.
:param session: Unique logical identifier to a session, event, or find list.
:return: return value of the library call.
:rtype: VISAStatus | 7.690719 | 8.526262 | 0.902004 |
# For each session type, ask for the list of connected resources and
# merge them into a single list.
resources = sum([st.list_resources()
for key, st in sessions.Session.iter_valid_session_classes()], [])
resources = rname.filter(resources, query)
... | def list_resources(self, session, query='?*::INSTR') | Returns a tuple of all connected devices matching query.
:param query: regular expression used to match devices. | 11.555687 | 12.76494 | 0.905268 |
# from the session handle, dispatch to the read method of the session object.
try:
ret = self.sessions[session].read(count)
except KeyError:
return 0, StatusCode.error_invalid_object
if ret[1] < 0:
raise errors.VisaIOError(ret[1])
r... | def read(self, session, count) | Reads data from device or interface synchronously.
Corresponds to viRead function of the VISA library.
:param session: Unique logical identifier to a session.
:param count: Number of bytes to be read.
:return: data read, return value of the library call.
:rtype: bytes, VISAStat... | 6.630195 | 6.301667 | 1.052133 |
# from the session handle, dispatch to the write method of the session object.
try:
ret = self.sessions[session].write(data)
except KeyError:
return 0, StatusCode.error_invalid_object
if ret[1] < 0:
raise errors.VisaIOError(ret[1])
... | def write(self, session, data) | Writes data to device or interface synchronously.
Corresponds to viWrite function of the VISA library.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:type data: str
:return: Number of bytes actually transferred, return value of the lib... | 7.08723 | 6.345276 | 1.11693 |
try:
sess = self.sessions[session]
except KeyError:
return None, StatusCode.error_invalid_object
return sess.get_attribute(attribute) | def get_attribute(self, session, attribute) | Retrieves the state of an attribute.
Corresponds to viGetAttribute function of the VISA library.
:param session: Unique logical identifier to a session, event, or find list.
:param attribute: Resource attribute for which the state query is made (see Attributes.*)
:return: The state of ... | 7.070233 | 7.845831 | 0.901145 |
try:
sess = self.sessions[session]
except KeyError:
return StatusCode.error_invalid_object
return sess.set_attribute(attribute, attribute_state) | def set_attribute(self, session, attribute, attribute_state) | Sets the state of an attribute.
Corresponds to viSetAttribute function of the VISA library.
:param session: Unique logical identifier to a session.
:param attribute: Attribute for which the state is to be modified. (Attributes.*)
:param attribute_state: The state of the attribute to be... | 5.197118 | 5.411626 | 0.960362 |
try:
sess = self.sessions[session]
except KeyError:
return StatusCode.error_invalid_object
return sess.lock(lock_type, timeout, requested_key) | def lock(self, session, lock_type, timeout, requested_key=None) | Establishes an access mode to the specified resources.
Corresponds to viLock function of the VISA library.
:param session: Unique logical identifier to a session.
:param lock_type: Specifies the type of lock requested, either Constants.EXCLUSIVE_LOCK or Constants.SHARED_LOCK.
:param ti... | 5.186496 | 4.533571 | 1.14402 |
try:
sess = self.sessions[session]
except KeyError:
return StatusCode.error_invalid_object
return sess.unlock() | def unlock(self, session) | Relinquishes a lock for the specified resource.
Corresponds to viUnlock function of the VISA library.
:param session: Unique logical identifier to a session.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode` | 8.41961 | 7.020416 | 1.199304 |
def is_usbraw(dev):
if custom_match and not custom_match(dev):
return False
return bool(find_interfaces(dev, bInterfaceClass=0xFF,
bInterfaceSubClass=0xFF))
return find_devices(vendor, product, serial_number, is_usbraw, **kwargs) | def find_raw_devices(vendor=None, product=None, serial_number=None,
custom_match=None, **kwargs) | Find connected USB RAW devices. See usbutil.find_devices for more info. | 4.404818 | 3.542359 | 1.24347 |
begin, end, size = 0, 0, len(data)
bytes_sent = 0
raw_write = super(USBRawDevice, self).write
while not end > size:
begin = end
end = begin + self.RECV_CHUNK
bytes_sent += raw_write(data[begin:end])
return bytes_sent | def write(self, data) | Send raw bytes to the instrument.
:param data: bytes to be sent to the instrument
:type data: bytes | 5.214676 | 4.921571 | 1.059555 |
raw_read = super(USBRawDevice, self).read
received = bytearray()
while not len(received) >= size:
resp = raw_read(self.RECV_CHUNK)
received.extend(resp)
return bytes(received) | def read(self, size) | Read raw bytes from the instrument.
:param size: amount of bytes to be sent to the instrument
:type size: integer
:return: received bytes
:return type: bytes | 7.208115 | 7.890317 | 0.913539 |
for i in range(31):
try:
if gpib.listener(BOARD, i) and gpib.ask(BOARD, 1) != i:
yield i
except gpib.GpibError as e:
logger.debug("GPIB error in _find_listeners(): %s", repr(e)) | def _find_listeners() | Find GPIB listeners. | 6.559713 | 5.311107 | 1.235093 |
kwargs = kwargs or {}
attrs = {}
if isinstance(vendor, str):
attrs['manufacturer'] = vendor
elif vendor is not None:
kwargs['idVendor'] = vendor
if isinstance(product, str):
attrs['product'] = product
elif product is not None:
kwargs['idProduct'] = product
... | def find_devices(vendor=None, product=None, serial_number=None,
custom_match=None, **kwargs) | Find connected USB devices matching certain keywords.
Wildcards can be used for vendor, product and serial_number.
:param vendor: name or id of the vendor (manufacturer)
:param product: name or id of the product
:param serial_number: serial number.
:param custom_match: callable returning True or F... | 2.332002 | 2.20306 | 1.058528 |
interfaces = []
try:
for cfg in device:
try:
interfaces.extend(usb_find_desc(cfg, find_all=True, **kwargs))
except:
pass
except:
pass
return interfaces | def find_interfaces(device, **kwargs) | :param device:
:return: | 5.465585 | 5.277004 | 1.035736 |
def _usb_reader():
try:
return self.interface.read(count)
except usb.USBError as exc:
if exc.errno in (errno.ETIMEDOUT, -errno.ETIMEDOUT):
raise USBTimeoutException()
raise
supress_end_en,... | def read(self, count) | Reads data from device or interface synchronously.
Corresponds to viRead function of the VISA library.
:param count: Number of bytes to be read.
:return: data read, return value of the library call.
:rtype: (bytes, VISAStatus) | 4.353695 | 4.287093 | 1.015535 |
send_end, _ = self.get_attribute(constants.VI_ATTR_SEND_END_EN)
count = self.interface.write(data)
return count, StatusCode.success | def write(self, data) | Writes data to device or interface synchronously.
Corresponds to viWrite function of the VISA library.
:param data: data to be written.
:type data: bytes
:return: Number of bytes actually transferred, return value of the library call.
:rtype: (int, VISAStatus) | 13.922159 | 7.963339 | 1.748282 |
if hasattr(get_model(parent_obj), "_tx_reference_resolver"):
return get_model(parent_obj)._tx_reference_resolver. \
has_unresolved_crossrefs(parent_obj, attr_name)
else:
return False | def needs_to_be_resolved(parent_obj, attr_name) | This function determines, if a reference (CrossReference) needs to be
resolved or not (while creating the model, while resolving references).
Args:
parent_obj: the object containing the attribute to be resolved.
attr_name: the attribute identification object.
Returns:
True if the a... | 5.054601 | 5.380177 | 0.939486 |
if isinstance(obj, obj_cls):
return True
if hasattr(obj_cls, "_tx_fqn") and hasattr(obj, "_tx_fqn"):
if obj_cls._tx_fqn == obj._tx_fqn:
return True
if hasattr(obj_cls, "_tx_inh_by"):
for cls in obj_cls._tx_inh_by:
if (textx_isinstance(obj, cls)):
... | def textx_isinstance(obj, obj_cls) | This function determines, if a textx object is an instance of a
textx class.
Args:
obj: the object to be analyzed
obj_cls: the class to be checked
Returns:
True if obj is an instance of obj_cls. | 2.229684 | 2.526858 | 0.882394 |
from textx.scoping import Postponed
if lst is None:
lst = []
if not obj:
return lst
if obj in lst:
return lst
lst.append(obj)
if type(obj) is Postponed:
return lst
ret = get_referenced_object(None, obj, dot_separated_name)
if type(ret) is list:
... | def get_list_of_concatenated_objects(obj, dot_separated_name,
lst=None) | get a list of the objects consisting of
- obj
- obj+"."+dot_separated_name
- (obj+"."+dot_separated_name)+"."+dot_separated_name (called recursively)
Note: lists are expanded
Args:
obj: the starting point
dot_separated_name: "the search path" (applied recursively)
lst: the i... | 2.211682 | 2.353304 | 0.93982 |
the_model = get_model(model_obj)
line, col = the_model._tx_parser.pos_to_linecol(
model_obj._tx_position)
return {"line": line, "col": col, "filename": the_model._tx_filename} | def get_location(model_obj) | Args:
model_obj: the model object of interest
Returns:
the line, col and filename of the model element.
The filename may be None.
This function may be used to fill exceptions | 4.81981 | 4.271876 | 1.128266 |
from textx.scoping import Postponed
assert prev_obj or not type(obj) is list
names = dot_separated_name.split(".")
match = re.match(r'parent\((\w+)\)', names[0])
if match:
next_obj = obj
desired_parent_typename = match.group(1)
next_obj = get_recursive_parent_with_typena... | def get_referenced_object(prev_obj, obj, dot_separated_name,
desired_type=None) | get objects based on a path
Args:
prev_obj: the object containing obj (req. if obj is a list)
obj: the current object
dot_separated_name: the attribute name "a.b.c.d" starting from obj
Note: the attribute "parent(TYPE)" is a shortcut to jump to the
parent of type "TYPE... | 2.799629 | 2.75335 | 1.016808 |
res = get_referenced_object(prev_obj, obj, dot_separated_name,
desired_type)
if res is None:
return []
elif type(res) is list:
return res
else:
return [res] | def get_referenced_object_as_list(
prev_obj, obj, dot_separated_name, desired_type=None) | Same as get_referenced_object, but always returns a list.
Args:
prev_obj: see get_referenced_object
obj: see get_referenced_object
dot_separated_name: see get_referenced_object
desired_type: see get_referenced_object
Returns:
same as get_referenced_object, but always re... | 2.149594 | 2.582005 | 0.832529 |
if hasattr(root, '_tx_model_repository'):
src = list(
root._tx_model_repository.local_models.filename_to_model.values())
if root not in src:
src.append(root)
else:
src = [root]
a = []
for m in src:
print("analyzing {}".format(m._tx_filename))... | def get_unique_named_object_in_all_models(root, name) | retrieves a unique named object (no fully qualified name)
Args:
root: start of search (if root is a model all known models are searched
as well)
name: name of object
Returns:
the object (if not unique, raises an error) | 4.45648 | 4.775742 | 0.933149 |
a = get_children(lambda x: hasattr(x, 'name') and x.name == name, root)
assert len(a) == 1
return a[0] | def get_unique_named_object(root, name) | retrieves a unique named object (no fully qualified name)
Args:
root: start of search
name: name of object
Returns:
the object (if not unique, raises an error) | 3.450893 | 5.016219 | 0.687947 |
assert class_name == get_unique_named_object(root, name).__class__.__name__ | def check_unique_named_object_has_class(root, name, class_name) | checks the type (type name) of an unique named object (no fully qualified
name)
Args:
root: start of search
name: name of object
class_name: the name of the type to be checked
Returns:
nothing (if not unique, raises an error) | 4.852103 | 7.333293 | 0.661654 |
if (hasattr(model, "_tx_model_repository")):
models = list(
model._tx_model_repository.all_models.filename_to_model.values())
if model not in models:
models.append(model)
else:
models = [model]
return models | def get_all_models_including_attached_models(model) | get a list of all models stored within a model
(including the owning model).
Args:
model: the owning model
Returns:
a list of all models | 4.245044 | 5.025095 | 0.844769 |
if (model):
self.update_model_in_repo_based_on_filename(model)
filenames = glob.glob(filename_pattern, **glob_args)
if len(filenames) == 0:
raise IOError(
errno.ENOENT, os.strerror(errno.ENOENT), filename_pattern)
loaded_models = []
... | def load_models_using_filepattern(
self, filename_pattern, model, glob_args, is_main_model=False,
encoding='utf-8', add_to_local_models=True) | add a new model to all relevant objects
Args:
filename_pattern: models to be loaded
model: model holding the loaded models in its _tx_model_repository
field (may be None).
glob_args: arguments passed to the glob.glob function.
Returns:
... | 2.709522 | 2.653336 | 1.021176 |
if (model):
self.update_model_in_repo_based_on_filename(model)
for the_path in search_path:
full_filename = join(the_path, filename)
# print(full_filename)
if exists(full_filename):
the_metamodel = \
MetaModelPr... | def load_model_using_search_path(
self, filename, model, search_path, is_main_model=False,
encoding='utf8', add_to_local_models=True) | add a new model to all relevant objects
Args:
filename: models to be loaded
model: model holding the loaded models in its _tx_model_repository
field (may be None).
search_path: list of search directories.
Returns:
the loaded model | 3.157475 | 3.229188 | 0.977792 |
if not self.local_models.has_model(filename):
if self.all_models.has_model(filename):
new_model = self.all_models.filename_to_model[filename]
else:
# print("LOADING {}".format(filename))
# all models loaded here get their referenc... | def load_model(
self, the_metamodel, filename, is_main_model, encoding='utf-8',
add_to_local_models=True) | load a single model
Args:
the_metamodel: the metamodel used to load the model
filename: the model to be loaded (if not cached)
Returns:
the loaded/cached model | 2.978675 | 3.058554 | 0.973883 |
if model._tx_filename is None:
for fn in self.all_models.filename_to_model:
if self.all_models.filename_to_model[fn] == model:
return fn
i = 0
while self.all_models.has_model("anonymous{}".format(i)):
i += 1
... | def update_model_in_repo_based_on_filename(self, model) | Adds a model to the repo (not initially visible)
Args:
model: the model to be added. If the model
has no filename, a name is invented
Returns: the filename of the model added to the repo | 2.763983 | 2.597703 | 1.064011 |
# print("PRE-CALLBACK{}".format(filename))
filename = other_model._tx_filename
assert (filename)
other_model._tx_model_repository = \
GlobalModelRepository(self.all_models)
self.all_models.filename_to_model[filename] = other_model | def pre_ref_resolution_callback(self, other_model) | (internal: used to store a model after parsing into the repository)
Args:
other_model: the parsed model
Returns:
nothing | 9.863062 | 10.083471 | 0.978142 |
debug = ctx.obj['debug']
check_model(meta_model_file, model_file, debug, ignore_case) | def check(ctx, meta_model_file, model_file, ignore_case) | Check validity of meta-model and optionally model. | 3.562787 | 3.512614 | 1.014283 |
debug = ctx.obj['debug']
meta_model, model = check_model(meta_model_file,
model_file, debug, ignore_case)
if output_format == 'plantuml':
pu_file = "{}.pu".format(meta_model_file)
click.echo("Generating '{}' file for meta-model.".format(pu_file))
... | def visualize(ctx, meta_model_file, model_file, ignore_case, output_format) | Generate .dot file(s) from meta-model and optionally model. | 2.262424 | 2.221408 | 1.018464 |
# Register direct sub-commands
global textx
for subcommand in pkg_resources.iter_entry_points(group='textx_commands'):
textx.command()(subcommand.load())
# Register sub-command groups
for subgroup in pkg_resources.iter_entry_points(
group='textx_command_groups'):
su... | def register_textx_subcommands() | Find and use all textx sub-commands registered through extension points.
Extension points for CLI extension are:
- `textx_commands` - for registering top-level commands.
- `textx_command_groups` - for registering command groups. | 3.355973 | 3.160208 | 1.061947 |
type_builtins = {
'integer': SimpleType(None, 'integer'),
'string': SimpleType(None, 'string')
}
entity_mm = metamodel_from_file(join(this_folder, 'entity.tx'),
classes=[SimpleType],
builtins=type_builtins)
... | def get_entity_mm() | Builds and returns a meta-model for Entity language. | 5.339702 | 4.590118 | 1.163304 |
dot_str = HEADER
# Render states
first = True
for state in model.states:
dot_str += '{}[label="{{{}{}|{}}}"]\n'.format(
id(state), r"-\> " if first else "", state.name,
"\\n".join(action.name for action in state.actions))
first = False
# Render tra... | def sm_to_dot(model) | Transforms given state machine model to dot str. | 4.063614 | 3.903861 | 1.040922 |
langs = list(pkg_resources.iter_entry_points(group=LANG_EP,
name=language_name))
if not langs:
raise TextXError('Language "{}" is not registered.'
.format(language_name))
if len(langs) > 1:
# Multiple languages... | def get_language(language_name) | Returns a callable that instantiates meta-model for the given language. | 3.129678 | 3.035028 | 1.031186 |
p = obj
while hasattr(p, 'parent'):
p = p.parent
return p | def get_model(obj) | Finds model root element for the given object. | 4.666942 | 3.876984 | 1.203756 |
if type(typ) is not text:
typ = typ.__name__
while hasattr(obj, 'parent'):
obj = obj.parent
if obj.__class__.__name__ == typ:
return obj | def get_parent_of_type(typ, obj) | Finds first object up the parent chain of the given type.
If no parent of the given type exists None is returned.
Args:
typ(str or python class): The type of the model object we are
looking for.
obj (model object): Python model object which is the start of the
search pro... | 3.615697 | 3.968397 | 0.911123 |
collected = []
def follow(elem):
if elem in collected:
return
# Use meta-model to search for all contained child elements.
cls = elem.__class__
if hasattr(cls, '_tx_attrs') and decider(elem):
collected.append(elem)
if hasattr(cls, '_tx_at... | def get_children(decider, root) | Returns a list of all model elements of type 'typ' starting from model
element 'root'. The search process will follow containment links only.
Non-containing references shall not be followed.
Args:
decider(obj): a callable returning True if the object is of interest.
root (model object): Pyt... | 3.635074 | 3.497431 | 1.039355 |
if type(typ) is not text:
typ = typ.__name__
return get_children(lambda x: x.__class__.__name__ == typ, root) | def get_children_of_type(typ, root) | Returns a list of all model elements of type 'typ' starting from model
element 'root'. The search process will follow containment links only.
Non-containing references shall not be followed.
Args:
typ(str or python class): The type of the model object we are
looking for.
root (m... | 4.741664 | 5.595148 | 0.84746 |
class TextXModelParser(Parser):
def __init__(self, *args, **kwargs):
super(TextXModelParser, self).__init__(*args, **kwargs)
# By default first rule is starting rule
# and must be followed by the EOF
self.parser_model = Sequence(
... | def get_model_parser(top_rule, comments_model, **kwargs) | Creates model parser for the given language. | 3.772685 | 3.749537 | 1.006174 |
if get_model(obj) != self.model:
return get_model(obj). \
_tx_reference_resolver.has_unresolved_crossrefs(obj)
else:
for crossref_obj, attr, crossref in self.parser._crossrefs:
if crossref_obj is obj:
if (not attr_name)... | def has_unresolved_crossrefs(self, obj, attr_name=None) | Args:
obj: has this object unresolved crossrefs in its fields
(non recursively)
Returns:
True (has unresolved crossrefs) or False (else) | 5.166722 | 5.255897 | 0.983033 |
metamodel = self.parser.metamodel
current_crossrefs = self.parser._crossrefs
# print("DEBUG: Current crossrefs #: {}".
# format(len(current_crossrefs)))
new_crossrefs = []
self.delayed_crossrefs = []
resolved_crossref_count = 0
# ----------... | def resolve_one_step(self) | Resolves model references. | 3.746536 | 3.712319 | 1.009217 |
import textx.scoping
if not global_model_repo:
global_model_repo = textx.scoping.GlobalModelRepository()
for filename_pattern in self.filename_pattern_list:
global_model_repo.load_models_using_filepattern(
filename_pattern, model=None, glob_args=s... | def load_models_in_model_repo(self, global_model_repo=None,
encoding='utf-8') | load all registered models (called explicitly from
the user and not as an automatic activity).
Normally this is done automatically while
reference resolution of one loaded model.
However, if you wish to load all models
you can call this and get a model repository.
The m... | 3.816426 | 4.028203 | 0.947427 |
return {
'ID': text,
'BOOL': bool,
'INT': int,
'FLOAT': float,
'STRICTFLOAT': float,
'STRING': text,
'NUMBER': float,
'BASETYPE': text,
}.get(textx_type_name, textx_type_name) | def python_type(textx_type_name) | Return Python type from the name of base textx type. | 3.524363 | 3.094882 | 1.138772 |
if type(language_def) is not text:
raise TextXError("textX accepts only unicode strings.")
if metamodel.debug:
metamodel.dprint("*** PARSING LANGUAGE DEFINITION ***")
# Check the cache for already conctructed textX parser
if metamodel.debug in textX_parsers:
parser = text... | def language_from_str(language_def, metamodel) | Constructs parser and initializes metamodel from language description
given in textX language.
Args:
language_def (str): A language description in textX.
metamodel (TextXMetaModel): A metamodel to initialize.
Returns:
Parser for the new language. | 5.789937 | 5.530797 | 1.046854 |
if self.grammar_parser.debug:
self.grammar_parser.dprint("RESOLVING MODEL PARSER: second_pass")
self._resolve_rule_refs(self.grammar_parser, model_parser)
self._determine_rule_types(model_parser.metamodel)
self._resolve_cls_refs(self.grammar_parser, model_parser)
... | def second_textx_model(self, model_parser) | Cross reference resolving for parser model. | 5.44359 | 4.852181 | 1.121885 |
def _resolve_rule(rule):
if not isinstance(rule, RuleCrossRef) and rule in resolved_rules:
return rule
resolved_rules.add(rule)
if grammar_parser.debug:
grammar_parser.dprint("Resolving rule: {}".format(rule))
... | def _resolve_rule_refs(self, grammar_parser, model_parser) | Resolves parser ParsingExpression crossrefs. | 3.722717 | 3.654948 | 1.018542 |
def _determine_rule_type(cls):
if cls in resolved_classes:
return
resolved_classes.add(cls)
# If there are attributes collected than this is a common
# rule
if len(cls._tx_attrs) > 0:
if cls._tx_... | def _determine_rule_types(self, metamodel) | Determine textX rule/metaclass types | 3.490058 | 3.465317 | 1.00714 |
def r(s):
if s.root:
if s in visited or s.rule_name in ALL_TYPE_NAMES or \
(hasattr(s, '_tx_class') and
s._tx_class._tx_type is not RULE_MATCH):
return s.rule_name
visited.add(s)
if isinstance(s, Match):
r... | def match_abstract_str(cls) | For a given abstract or match rule meta-class returns a nice string
representation for the body. | 3.270157 | 3.176786 | 1.029392 |
with codecs.open(file_name, 'w', encoding="utf-8") as f:
model_export_to_file(f, model, repo) | def model_export(model, file_name, repo=None) | Args:
model: the model to be exported (may be None if repo is not None)
file_name: the output file name
repo: the model repo (alternative to model input) to be exported
Returns:
Nothing | 3.268608 | 3.892439 | 0.839733 |
if not model and not repo:
raise Exception("specity either a model or a repo")
if model and repo:
raise Exception("specity either a model or a repo")
processed_set = set()
f.write(HEADER)
def _export(obj):
if obj is None or obj in processed_set or type(obj) \
... | def model_export_to_file(f, model=None, repo=None) | Args:
f: the file object to be used as output.
model: the model to be exported (alternative to repo)
repo: the repo to be exported (alternative to model)
Returns:
Nothing | 2.90891 | 2.93332 | 0.991678 |
if not metamodel:
metamodel = TextXMetaModel(**kwargs)
language_from_str(lang_desc, metamodel)
return metamodel | def metamodel_from_str(lang_desc, metamodel=None, **kwargs) | Creates a new metamodel from the textX description given as a string.
Args:
lang_desc(str): A textX language description.
metamodel(TextXMetaModel): A metamodel that should be used.
other params: See TextXMetaModel. | 4.789968 | 4.782658 | 1.001529 |
with codecs.open(file_name, 'r', 'utf-8') as f:
lang_desc = f.read()
metamodel = metamodel_from_str(lang_desc=lang_desc,
file_name=file_name,
**kwargs)
return metamodel | def metamodel_from_file(file_name, **kwargs) | Creates new metamodel from the given file.
Args:
file_name(str): The name of the file with textX language description.
other params: See metamodel_from_str. | 2.794861 | 2.901251 | 0.96333 |
if namespace_name not in self.namespaces:
self.namespaces[namespace_name] = {}
# BASETYPE namespace is imported in each namespace
# as the first namespace to be searched.
self._imported_namespaces[namespace_name] = \
[self.namespaces['__b... | def _enter_namespace(self, namespace_name) | A namespace is usually an absolute file name of the grammar.
A special namespace '__base__' is used for BASETYPE namespace. | 5.753483 | 3.934246 | 1.462411 |
# Import can't be used if meta-model is loaded from string
assert self.root_path is not None, \
'"import" statement can not be used if meta-model is ' \
'loaded from string.'
# Find the absolute file name of the import based on the relative
# import_nam... | def _new_import(self, import_name) | Starts a new import.
Args:
import_name(str): A relative import in the dot syntax
(e.g. "first.second.expressions") | 4.363936 | 4.221105 | 1.033837 |
class TextXMetaClass(type):
def __repr__(cls):
return '<textx:{} class at {}>'.format(cls._tx_fqn,
id(cls))
@add_metaclass(TextXMetaClass)
class TextXClass(object):
def __repr... | def _new_class(self, name, peg_rule, position, position_end=None,
inherits=None, root=False, rule_type=RULE_MATCH) | Creates a new class with the given name in the current namespace.
Args:
name(str): The name of the class.
peg_rule(ParserExpression): An arpeggio peg rule used to match
this class.
position(int): A position in the input where class is defined.
root... | 3.534596 | 3.576303 | 0.988338 |
cls._tx_metamodel = self
# Attribute information (MetaAttr instances) keyed by name.
cls._tx_attrs = OrderedDict()
# A list of inheriting classes
cls._tx_inh_by = inherits if inherits else []
cls._tx_position = position
cls._tx_position_end = \
... | def _init_class(self, cls, peg_rule, position, position_end=None,
inherits=None, root=False, rule_type=RULE_MATCH) | Setup meta-class special attributes, namespaces etc. This is called
both for textX created classes as well as user classes. | 5.552593 | 5.252812 | 1.05707 |
ns = self._namespace_stack[-1]
if ns in ['__base__', None]:
return cls.__name__
else:
return ns + '.' + cls.__name__ | def _cls_fqn(self, cls) | Returns fully qualified name for the class based on current namespace
and the class name. | 4.694866 | 3.957639 | 1.186279 |
for attr in obj.__class__._tx_attrs.values():
if user:
# Mangle name to prvent name clashing
attr_name = "_txa_%s" % attr.name
else:
attr_name = attr.name
if attr.mult in [MULT_ZEROORMORE, MULT_ONEORMORE]:
... | def _init_obj_attrs(self, obj, user=False) | Initialize obj attributes.
Args:
obj(object): A python object to set attributes to.
user(bool): If this object is a user object mangle attribute names. | 6.239015 | 6.099601 | 1.022856 |
attr = MetaAttr(name, cls, mult, cont, ref, bool_assignment,
position)
clazz._tx_attrs[name] = attr
return attr | def _new_cls_attr(self, clazz, name, cls=None, mult=MULT_ONE, cont=True,
ref=False, bool_assignment=False, position=0) | Creates new meta attribute of this class. | 4.242287 | 4.212953 | 1.006963 |
return self.type_convertors.get(_type, lambda x: x)(value) | def convert(self, value, _type) | Convert instances of textx types and match rules to python types. | 5.872494 | 4.785534 | 1.227134 |
if type(model_str) is not text:
raise TextXError("textX accepts only unicode strings.")
model = self._parser_blueprint.clone().get_model_from_str(
model_str, debug=debug,
pre_ref_resolution_callback=pre_ref_resolution_callback)
for p in self._model_... | def model_from_str(self, model_str, debug=None,
pre_ref_resolution_callback=None) | Instantiates model from the given string.
:param pre_ref_resolution_callback: called before references are
resolved. This can be useful to manage models distributed
across files (scoping) | 5.028049 | 5.34668 | 0.940406 |
model = None
callback = pre_ref_resolution_callback
if hasattr(self, "_tx_model_repository"):
# metamodel has a global repo
if not callback:
def _pre_ref_resolution_callback(other_model):
from textx.scoping import GlobalModelR... | def internal_model_from_file(
self, file_name, encoding='utf-8', debug=None,
pre_ref_resolution_callback=None, is_main_model=True) | Instantiates model from the given file.
:param pre_ref_resolution_callback: called before references are
resolved. This can be useful to manage models distributed
across files (scoping) | 3.62466 | 3.793835 | 0.955408 |
self.obj_processors = obj_processors
self.type_convertors.update(obj_processors) | def register_obj_processors(self, obj_processors) | Object processors are callables that will be called after
each successful model object construction.
Those callables receive model object as its parameter.
Registration of new object processors will replace previous.
Args:
obj_processors(dict): A dictionary where key=class n... | 4.986892 | 7.263087 | 0.686608 |
self.print_menu()
while True:
try:
event = input()
if event == 'q':
return
event = int(event)
event = self.model.events[event-1]
except Exception:
print('Invalid input')
... | def interpret(self) | Main interpreter loop. | 4.264306 | 3.941917 | 1.081785 |
if font_name in STANDARD_FONT_NAMES:
return font_name, True
elif font_name in _registered_fonts:
return font_name, _registered_fonts[font_name]
NOT_FOUND = (None, False)
try:
# Try first to register the font if it exists as ttf,
# based on ReportLab font search.
... | def find_font(font_name) | Return the font and a Boolean indicating if the match is exact. | 3.372664 | 3.290298 | 1.025033 |
"Convert an SVG file to an RLG Drawing object."
# unzip .svgz file into .svg
unzipped = False
if isinstance(path, str) and os.path.splitext(path)[1].lower() == ".svgz":
with gzip.open(path, 'rb') as f_in, open(path[:-1], 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
path =... | def svg2rlg(path, **kwargs) | Convert an SVG file to an RLG Drawing object. | 2.942146 | 2.808868 | 1.047449 |
from reportlab.pdfgen.canvas import Canvas
from reportlab.graphics import shapes
original_renderPath = shapes._renderPath
def patchedRenderPath(path, drawFuncs, **kwargs):
# Patched method to transfer fillRule from Path to PDFPathObject
# Get back from bound method to instance
... | def monkeypatch_reportlab() | https://bitbucket.org/rptlab/reportlab/issues/95/
ReportLab always use 'Even-Odd' filling mode for paths, this patch forces
RL to honor the path fill rule mode (possibly 'Non-Zero Winding') instead. | 3.57176 | 3.397208 | 1.051381 |
attrs = line.split(';')
attrs = [a.strip() for a in attrs]
attrs = filter(lambda a:len(a)>0, attrs)
new_attrs = {}
for a in attrs:
k, v = a.split(':')
k, v = [s.strip() for s in (k, v)]
new_attrs[k] = v
return new_attrs | def parseMultiAttributes(self, line) | Try parsing compound attribute string.
Return a dictionary with single attributes in 'line'. | 2.303242 | 2.227003 | 1.034234 |
# This needs also to lookup values like "url(#SomeName)"...
if self.css_rules is not None and not svgNode.attrib.get('__rules_applied', False):
if isinstance(svgNode, NodeTracker):
svgNode.apply_rules(self.css_rules)
else:
ElementWrapper... | def findAttr(self, svgNode, name) | Search an attribute with some name in some node or above.
First the node is searched, then its style attribute, then
the search continues in the node's parent node. If no such
attribute is found, '' is returned. | 4.269323 | 4.164133 | 1.025261 |
"Return a dictionary of all attributes of svgNode or those inherited by it."
dict = {}
if node_name(svgNode.getparent()) == 'g':
dict.update(self.getAllAttributes(svgNode.getparent()))
style = svgNode.attrib.get("style")
if style:
d = self.parseMultiAtt... | def getAllAttributes(self, svgNode) | Return a dictionary of all attributes of svgNode or those inherited by it. | 3.767672 | 3.086727 | 1.220604 |
line = svgAttr.strip()
ops = line[:]
brackets = []
indices = []
for i, lin in enumerate(line):
if lin in "()":
brackets.append(i)
for i in range(0, len(brackets), 2):
bi, bj = brackets[i], brackets[i+1]
sublin... | def convertTransform(self, svgAttr) | Parse transform attribute string.
E.g. "scale(2) translate(10,20)"
-> [("scale", 2), ("translate", (10,20))] | 2.850268 | 2.771946 | 1.028255 |
"Convert length to points."
text = svgAttr
if not text:
return 0.0
if ' ' in text.replace(',', ' ').strip():
logger.debug("Only getting first value of %s" % text)
text = text.replace(',', ' ').split()[0]
if text.endswith('%'):
log... | def convertLength(self, svgAttr, percentOf=100, em_base=12) | Convert length to points. | 4.186055 | 4.008618 | 1.044264 |
return [self.convertLength(a) for a in self.split_attr_list(svgAttr)] | def convertLengthList(self, svgAttr) | Convert a list of lengths. | 6.776554 | 5.870009 | 1.154437 |
"Convert string to a RL color object."
# fix it: most likely all "web colors" are allowed
predefined = "aqua black blue fuchsia gray green lime maroon navy "
predefined = predefined + "olive orange purple red silver teal white yellow "
predefined = predefined + "lawngreen indian... | def convertColor(self, svgAttr) | Convert string to a RL color object. | 3.844406 | 3.638626 | 1.056554 |
def get_path_from_node(node):
for child in node.getchildren():
if node_name(child) == 'path':
group = self.shape_converter.convertShape('path', NodeTracker(child))
return group.contents[-1]
else:
ret... | def get_clippath(self, node) | Return the clipping Path object referenced by the node 'clip-path'
attribute, if any. | 3.725276 | 3.507956 | 1.061951 |
xlink_href = node.attrib.get('{http://www.w3.org/1999/xlink}href')
if not xlink_href:
return None
# First handle any raster embedded image data
match = re.match(r"^data:image/(jpeg|png);base64", xlink_href)
if match:
img_format = match.groups()[0... | def xlink_href_target(self, node, group=None) | Return either:
- a tuple (renderer, node) when the the xlink:href attribute targets
a vector file or node
- the path to an image file for any raster image targets
- None if any problem occurs | 3.591318 | 3.476697 | 1.032968 |
if text is None:
return
if preserve_space:
text = text.replace('\r\n', ' ').replace('\n', ' ').replace('\t', ' ')
else:
text = text.replace('\r\n', '').replace('\n', '').replace('\t', ' ')
text = text.strip()
while (' ' in tex... | def clean_text(self, text, preserve_space) | Text cleaning as per https://www.w3.org/TR/SVG/text.html#WhiteSpace | 2.01261 | 1.91178 | 1.052741 |
tr = self.attrConverter.convertTransform(transform)
for op, values in tr:
if op == "scale":
if not isinstance(values, tuple):
values = (values, values)
group.scale(*values)
elif op == "translate":
if is... | def applyTransformOnGroup(self, transform, group) | Apply an SVG transformation to a RL Group shape.
The transformation is the value of an SVG transform attribute
like transform="scale(1, -1) translate(10, 30)".
rotate(<angle> [<cx> <cy>]) is equivalent to:
translate(<cx> <cy>) rotate(<angle>) translate(-<cx> -<cy>) | 2.564492 | 2.326692 | 1.102205 |
# RLG-specific: all RLG shapes
"Apply style attributes of a sequence of nodes to an RL shape."
# tuple format: (svgAttr, rlgAttr, converter, default)
mappingN = (
("fill", "fillColor", "convertColor", "black"),
("fill-opacity", "fillOpacity", "convertOp... | def applyStyleOnShape(self, shape, node, only_explicit=False) | Apply styles from an SVG element to an RLG shape.
If only_explicit is True, only attributes really present are applied. | 3.025716 | 2.894875 | 1.045197 |
floats = [float(seq) for seq in re.findall(r'(-?\d*\.?\d*(?:e[+-]\d+)?)', value) if seq]
res = []
for i in range(0, len(floats), min_num):
if i > 0 and op in {'m', 'M'}:
op = 'l' if op == 'm' else 'L'
res.extend([op, floats[i:i + min_num]])
return res | def split_floats(op, min_num, value) | Split `value`, a list of numbers as a string, to a list of float numbers.
Also optionally insert a `l` or `L` operation depending on the operation
and the length of values.
Example: with op='m' and value='10,20 30,40,' the returned value will be
['m', [10.0, 20.0], 'l', [30.0, 40.0]] | 3.151099 | 2.864521 | 1.100044 |
# operator codes mapped to the minimum number of expected arguments
ops = {
'A': 7, 'a': 7,
'Q': 4, 'q': 4, 'T': 2, 't': 2, 'S': 4, 's': 4,
'M': 2, 'L': 2, 'm': 2, 'l': 2, 'H': 1, 'V': 1,
'h': 1, 'v': 1, 'C': 6, 'c': 6, 'Z': 0, 'z': 0,
}
op_keys = ops.keys()
# ... | def normalise_svg_path(attr) | Normalise SVG path.
This basically introduces operator codes for multi-argument
parameters. Also, it fixes sequences of consecutive M or m
operators to MLLL... and mlll... operators. It adds an empty
list as argument for Z and z only in order to make the resul-
ting list easier to iterate over.
... | 3.50549 | 3.254278 | 1.077194 |
c0 = q0
c1 = (q0[0] + 2. / 3 * (q1[0] - q0[0]), q0[1] + 2. / 3 * (q1[1] - q0[1]))
c2 = (c1[0] + 1. / 3 * (q2[0] - q0[0]), c1[1] + 1. / 3 * (q2[1] - q0[1]))
c3 = q2
return c0, c1, c2, c3 | def convert_quadratic_to_cubic_path(q0, q1, q2) | Convert a quadratic Bezier curve through q0, q1, q2 to a cubic one. | 1.657401 | 1.548058 | 1.070632 |
'''
See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5
note that we reduce phi to zero outside this routine
'''
rx = fabs(rx)
ry = fabs(ry)
# step 1
if phi:
phi_rad = radians(phi)
sin_phi = sin(phi_rad)
cos_phi = cos(phi_rad)
tx = 0.5... | def end_point_to_center_parameters(x1, y1, x2, y2, fA, fS, rx, ry, phi=0) | See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5
note that we reduce phi to zero outside this routine | 2.33642 | 2.128386 | 1.097743 |
context = {}
socket = SocketIOChannelProxy(request.environ["socketio"])
client_start(request, socket, context)
try:
if socket.on_connect():
events.on_connect.send(request, socket, context)
while True:
messages = socket.recv()
if not messages and n... | def socketio(request) | Socket.IO handler - maintains the lifecycle of a Socket.IO
request, sending the each of the events. Also handles
adding/removing request/socket pairs to the CLIENTS dict
which is used for sending on_finish events when the server
stops. | 4.072297 | 4.014699 | 1.014347 |
CLIENTS[socket.session.session_id] = (request, socket, context) | def client_start(request, socket, context) | Adds the client triple to CLIENTS. | 8.743094 | 5.890088 | 1.484374 |
# Send the unsubscribe event prior to actually unsubscribing, so
# that the finish event can still match channels if applicable.
for channel in socket.channels:
events.on_unsubscribe.send(request, socket, context, channel)
events.on_finish.send(request, socket, context)
# Actually unsub... | def client_end(request, socket, context) | Handles cleanup when a session ends for the given client triple.
Sends unsubscribe and finish events, actually unsubscribes from
any channels subscribed to, and removes the client triple from
CLIENTS. | 8.346941 | 5.590846 | 1.492966 |
for request, socket, context in CLIENTS.values()[:]:
client_end(request, socket, context) | def client_end_all() | Performs cleanup on all clients - called by runserver_socketio
when the server is shut down or reloaded. | 12.547835 | 12.608103 | 0.99522 |
if channel in self.channels:
return False
CHANNELS[channel].append(self.socket.session.session_id)
self.channels.append(channel)
return True | def subscribe(self, channel) | Add the channel to this socket's channels, and to the list of
subscribed session IDs for the channel. Return False if
already subscribed, otherwise True. | 4.541121 | 3.221674 | 1.409553 |
try:
CHANNELS[channel].remove(self.socket.session.session_id)
self.channels.remove(channel)
except ValueError:
return False
return True | def unsubscribe(self, channel) | Remove the channel from this socket's channels, and from the
list of subscribed session IDs for the channel. Return False
if not subscribed, otherwise True. | 5.347292 | 3.669023 | 1.457416 |
if channel is None:
channels = self.channels
else:
channels = [channel]
for channel in channels:
for subscriber in CHANNELS[channel]:
if subscriber != self.socket.session.session_id:
session = self.socket.handler.se... | def broadcast_channel(self, message, channel=None) | Send the given message to all subscribers for the channel
given. If no channel is given, send to the subscribers for
all the channels that this socket is subscribed to. | 4.408431 | 3.968517 | 1.110851 |
self.send(message)
self.broadcast_channel(message, channel) | def send_and_broadcast_channel(self, message, channel=None) | Shortcut for a socket to broadcast to all sockets subscribed
to a channel, and itself. | 4.337634 | 3.550968 | 1.221536 |
room = get_object_or_404(ChatRoom, id=message["room"])
if message["action"] == "start":
name = strip_tags(message["name"])
user, created = room.users.get_or_create(name=name)
if not created:
socket.send({"action": "in-use"})
else:
context["user"] = us... | def message(request, socket, context, message) | Event handler for a room receiving a message. First validates a
joining user's name and sends them the list of users. | 2.62002 | 2.577493 | 1.0165 |
try:
user = context["user"]
except KeyError:
return
left = {"action": "leave", "name": user.name, "id": user.id}
socket.broadcast_channel(left)
user.delete() | def finish(request, socket, context) | Event handler for a socket session ending in a room. Broadcast
the user leaving and delete them from the DB. | 5.575529 | 4.306678 | 1.294624 |
try:
socket = CLIENTS[session_id][1]
except KeyError:
raise NoSocket("There is no socket with the session ID: " + session_id)
socket.send(message) | def send(session_id, message) | Send a message to the socket for the given session ID. | 4.745225 | 4.351968 | 1.090363 |
try:
socket = CLIENTS.values()[0][1]
except IndexError:
raise NoSocket("There are no clients.")
socket.send_and_broadcast(message) | def broadcast(message) | Find the first socket and use it to broadcast to all sockets
including the socket itself. | 8.688118 | 7.309945 | 1.188534 |
try:
socket = CLIENTS[CHANNELS.get(channel, [])[0]][1]
except (IndexError, KeyError):
raise NoSocket("There are no clients on the channel: " + channel)
socket.send_and_broadcast_channel(message, channel) | def broadcast_channel(message, channel) | Find the first socket for the given channel, and use it to
broadcast to the channel, including the socket itself. | 6.889958 | 5.495297 | 1.253792 |
from django_socketio.settings import MESSAGE_LOG_FORMAT
if MESSAGE_LOG_FORMAT is None:
return None
now = datetime.now().replace(microsecond=0)
args = dict(request.META, TYPE=message_type, MESSAGE=message, TIME=now)
return (MESSAGE_LOG_FORMAT % args) + "\n" | def format_log(request, message_type, message) | Formats a log message similar to gevent's pywsgi request logging. | 4.270058 | 4.138197 | 1.031864 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.