INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Works like a apispec plugin May return a path as string and mutate operations dict. | def path_helper(self, path=None, operations=None, **kwargs):
"""
Works like a apispec plugin
May return a path as string and mutate operations dict.
:param str path: Path to the resource
:param dict operations: A `dict` mapping HTTP methods to operation object. See
... |
May mutate operations.: param str path: Path to the resource: param dict operations: A dict mapping HTTP methods to operation object. See: param list methods: A list of methods registered for this path | def operation_helper(
self, path=None, operations=None, methods=None, func=None, **kwargs
):
"""May mutate operations.
:param str path: Path to the resource
:param dict operations: A `dict` mapping HTTP methods to operation object. See
:param list methods: A list of methods r... |
Generic HTTP JSON response method | def response(code, **kwargs):
"""
Generic HTTP JSON response method
:param code: HTTP code (int)
:param kwargs: Data structure for response (dict)
:return: HTTP Json response
"""
_ret_json = jsonify(kwargs)
resp = make_response(_ret_json, code)
... |
Auto generates pretty label_columns from list of columns | def _gen_labels_columns(self, list_columns):
"""
Auto generates pretty label_columns from list of columns
"""
for col in list_columns:
if not self.label_columns.get(col):
self.label_columns[col] = self._prettify_column(col) |
Prepares dict with labels to be JSON serializable | def _label_columns_json(self, cols=None):
"""
Prepares dict with labels to be JSON serializable
"""
ret = {}
cols = cols or []
d = {k: v for (k, v) in self.label_columns.items() if k in cols}
for key, value in d.items():
ret[key] = as_unicode(_(val... |
Init Titles if not defined | def _init_titles(self):
"""
Init Titles if not defined
"""
super(ModelRestApi, self)._init_titles()
class_name = self.datamodel.model_name
if not self.list_title:
self.list_title = "List " + self._prettify_name(class_name)
if not self.add_title:
... |
Init Properties | def _init_properties(self):
"""
Init Properties
"""
super(ModelRestApi, self)._init_properties()
# Reset init props
self.description_columns = self.description_columns or {}
self.list_exclude_columns = self.list_exclude_columns or []
self.show_exclude_... |
Endpoint that renders a response for CRUD REST meta data --- get: parameters: - $ref: #/ components/ parameters/ get_info_schema responses: 200: description: Item from Model content: application/ json: schema: type: object properties: add_columns: type: object edit_columns: type: object filters: type: object permission... | def info(self, **kwargs):
""" Endpoint that renders a response for CRUD REST meta data
---
get:
parameters:
- $ref: '#/components/parameters/get_info_schema'
responses:
200:
description: Item from Model
content:
... |
Get item from Model --- get: parameters: - in: path schema: type: integer name: pk - $ref: #/ components/ parameters/ get_item_schema responses: 200: description: Item from Model content: application/ json: schema: type: object properties: label_columns: type: object show_columns: type: array items: type: string descri... | def get(self, pk, **kwargs):
"""Get item from Model
---
get:
parameters:
- in: path
schema:
type: integer
name: pk
- $ref: '#/components/parameters/get_item_schema'
responses:
200:
description... |
Get list of items from Model --- get: parameters: - $ref: #/ components/ parameters/ get_list_schema responses: 200: description: Items from Model content: application/ json: schema: type: object properties: label_columns: type: object list_columns: type: array items: type: string description_columns: type: object list... | def get_list(self, **kwargs):
"""Get list of items from Model
---
get:
parameters:
- $ref: '#/components/parameters/get_list_schema'
responses:
200:
description: Items from Model
content:
application/json:
... |
POST item to Model --- post: requestBody: description: Model schema required: true content: application/ json: schema: $ref: #/ components/ schemas/ {{ self. __class__. __name__ }}. post responses: 201: description: Item inserted content: application/ json: schema: type: object properties: id: type: string result: $ref... | def post(self):
"""POST item to Model
---
post:
requestBody:
description: Model schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
... |
POST item to Model --- put: parameters: - in: path schema: type: integer name: pk requestBody: description: Model schema required: true content: application/ json: schema: $ref: #/ components/ schemas/ {{ self. __class__. __name__ }}. put responses: 200: description: Item changed content: application/ json: schema: typ... | def put(self, pk):
"""POST item to Model
---
put:
parameters:
- in: path
schema:
type: integer
name: pk
requestBody:
description: Model schema
required: true
content:
application... |
Delete item from Model --- delete: parameters: - in: path schema: type: integer name: pk responses: 200: description: Item deleted content: application/ json: schema: type: object properties: message: type: string 404: $ref: #/ components/ responses/ 404 422: $ref: #/ components/ responses/ 422 500: $ref: #/ components... | def delete(self, pk):
"""Delete item from Model
---
delete:
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Item deleted
content:
applica... |
Helper function to handle rison page arguments sets defaults and impose FAB_API_MAX_PAGE_SIZE | def _handle_page_args(self, rison_args):
"""
Helper function to handle rison page
arguments, sets defaults and impose
FAB_API_MAX_PAGE_SIZE
:param rison_args:
:return: (tuple) page, page_size
"""
page = rison_args.get(API_PAGE_INDEX_RIS_KEY, 0... |
Help function to handle rison order arguments | def _handle_order_args(self, rison_args):
"""
Help function to handle rison order
arguments
:param rison_args:
:return:
"""
order_column = rison_args.get(API_ORDER_COLUMN_RIS_KEY, "")
order_direction = rison_args.get(API_ORDER_DIRECTION_RIS_KEY, "... |
Prepares dict with col descriptions to be JSON serializable | def _description_columns_json(self, cols=None):
"""
Prepares dict with col descriptions to be JSON serializable
"""
ret = {}
cols = cols or []
d = {k: v for (k, v) in self.description_columns.items() if k in cols}
for key, value in d.items():
ret[k... |
Return a dict with field details ready to serve as a response | def _get_field_info(self, field, filter_rel_field, page=None, page_size=None):
"""
Return a dict with field details
ready to serve as a response
:param field: marshmallow field
:return: dict with field details
"""
ret = dict()
ret["name"] = field.... |
Returns a dict with fields detail from a marshmallow schema | def _get_fields_info(self, cols, model_schema, filter_rel_fields, **kwargs):
"""
Returns a dict with fields detail
from a marshmallow schema
:param cols: list of columns to show info for
:param model_schema: Marshmallow model schema
:param filter_rel_fields: expe... |
Return a list of values for a related field | def _get_list_related_field(
self, field, filter_rel_field, page=None, page_size=None
):
"""
Return a list of values for a related field
:param field: Marshmallow field
:param filter_rel_field: Filters for the related field
:param page: The page index
:pa... |
Merge a model with a python data structure This is useful to turn PUT method into a PATCH also: param model_item: SQLA Model: param data: python data structure: return: python data structure | def _merge_update_item(self, model_item, data):
"""
Merge a model with a python data structure
This is useful to turn PUT method into a PATCH also
:param model_item: SQLA Model
:param data: python data structure
:return: python data structure
"""
d... |
Creates a WTForm field for many to one related fields will use a Select box based on a query. Will only work with SQLAlchemy interface. | def _convert_many_to_one(self, col_name, label, description,
lst_validators, filter_rel_fields,
form_props):
"""
Creates a WTForm field for many to one related fields,
will use a Select box based on a query. Will only
... |
Converts a model to a form given | def create_form(self, label_columns=None, inc_columns=None,
description_columns=None, validators_columns=None,
extra_fields=None, filter_rel_fields=None):
"""
Converts a model to a form given
:param label_columns:
A dictionary with... |
Returns the object for the key Override it for efficiency. | def get(self, pk):
"""
Returns the object for the key
Override it for efficiency.
"""
for item in self.store.get(self.query_class):
# coverts pk value to correct type
pk = item.properties[item.pk].col_type(pk)
if getattr(item, item.pk) ... |
SQLAlchemy query like method | def query(self, model_cls):
"""
SQLAlchemy query like method
"""
self._filters_cmd = list()
self.query_filters = list()
self._order_by_cmd = None
self._offset = 0
self._limit = 0
self.query_class = model_cls._name
return self |
SQLA like all method will populate all rows and apply all filters and orders to it. | def all(self):
"""
SQLA like 'all' method, will populate all rows and apply all
filters and orders to it.
"""
items = list()
if not self._filters_cmd:
items = self.store.get(self.query_class)
else:
for item in self.store.get(self.qu... |
Arguments are passed like: _oc_<VIEW_NAME > = <COL_NAME > &_od_<VIEW_NAME > = asc | desc | def link_order_filter(self, column, modelview_name):
"""
Arguments are passed like:
_oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
"""
new_args = request.view_args.copy()
args = request.args.copy()
if ("_oc_" + modelview_name) in args:
... |
Arguments are passed like: page_<VIEW_NAME > = <PAGE_NUMBER > | def link_page_filter(self, page, modelview_name):
"""
Arguments are passed like: page_<VIEW_NAME>=<PAGE_NUMBER>
"""
new_args = request.view_args.copy()
args = request.args.copy()
args["page_" + modelview_name] = page
return url_for(
request.endpoin... |
Arguments are passed like: psize_<VIEW_NAME > = <PAGE_NUMBER > | def link_page_size_filter(self, page_size, modelview_name):
"""
Arguments are passed like: psize_<VIEW_NAME>=<PAGE_NUMBER>
"""
new_args = request.view_args.copy()
args = request.args.copy()
args["psize_" + modelview_name] = page_size
return url_for(
re... |
Resets a user s password | def reset_password(app, appbuilder, username, password):
"""
Resets a user's password
"""
_appbuilder = import_application(app, appbuilder)
user = _appbuilder.sm.find_user(username=username)
if not user:
click.echo("User {0} not found.".format(username))
else:
_appbuilder... |
Creates an admin user | def create_admin(app, appbuilder, username, firstname, lastname, email, password):
"""
Creates an admin user
"""
auth_type = {
c.AUTH_DB: "Database Authentications",
c.AUTH_OID: "OpenID Authentication",
c.AUTH_LDAP: "LDAP Authentication",
c.AUTH_REMOTE_USER: "WebServe... |
Create a user | def create_user(app, appbuilder, role, username, firstname, lastname, email, password):
"""
Create a user
"""
_appbuilder = import_application(app, appbuilder)
role_object = _appbuilder.sm.find_role(role)
user = _appbuilder.sm.add_user(
username, firstname, lastname, email, role_obje... |
Runs Flask dev web server. | def run(app, appbuilder, host, port, debug):
"""
Runs Flask dev web server.
"""
_appbuilder = import_application(app, appbuilder)
_appbuilder.get_app.run(host=host, port=port, debug=debug) |
Create all your database objects ( SQLAlchemy specific ). | def create_db(app, appbuilder):
"""
Create all your database objects (SQLAlchemy specific).
"""
from flask_appbuilder.models.sqla import Base
_appbuilder = import_application(app, appbuilder)
engine = _appbuilder.get_session.get_bind(mapper=None, clause=None)
Base.metadata.create_all(en... |
Flask - AppBuilder package version | def version(app, appbuilder):
"""
Flask-AppBuilder package version
"""
_appbuilder = import_application(app, appbuilder)
click.echo(
click.style(
"F.A.B Version: {0}.".format(_appbuilder.version), bg="blue", fg="white"
)
) |
Cleanup unused permissions from views and roles. | def security_cleanup(app, appbuilder):
"""
Cleanup unused permissions from views and roles.
"""
_appbuilder = import_application(app, appbuilder)
_appbuilder.security_cleanup()
click.echo(click.style("Finished security cleanup", fg="green")) |
List all registered views | def list_views(app, appbuilder):
"""
List all registered views
"""
_appbuilder = import_application(app, appbuilder)
echo_header("List of registered views")
for view in _appbuilder.baseviews:
click.echo(
"View:{0} | Route:{1} | Perms:{2}".format(
view.__cl... |
List all users on the database | def list_users(app, appbuilder):
"""
List all users on the database
"""
_appbuilder = import_application(app, appbuilder)
echo_header("List of users")
for user in _appbuilder.sm.get_all_users():
click.echo(
"username:{0} | email:{1} | role:{2}".format(
use... |
Copies flask - appbuilder static files to your projects static folder | def collect_static(static_folder):
"""
Copies flask-appbuilder static files to your projects static folder
"""
appbuilder_static_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "static/appbuilder"
)
app_static_path = os.path.join(os.getcwd(), static_folder)
if no... |
Function to use on Group by Charts. accepts a list and returns the average of the list s items | def aggregate_avg(items, col):
"""
Function to use on Group by Charts.
accepts a list and returns the average of the list's items
"""
try:
return aggregate_sum(items, col) / aggregate_count(items, col)
except Exception:
log.warning(c.LOGMSG_WAR_DBI_AVG_ZERODIV)
re... |
Will return a dict with Google JSON structure for charts | def to_json(self, data, labels=None):
"""
Will return a dict with Google JSON structure for charts
The Google structure::
{
cols: [{id:<COL_NAME>, label:<LABEL FOR COL>, type: <COL TYPE>}, ...]
rows: [{c: [{v: <COL VALUE}, ...], .... |
Create Flask blueprint. You will generally not use it | def create_blueprint(self, appbuilder, endpoint=None, static_folder=None):
"""
Create Flask blueprint. You will generally not use it
:param appbuilder:
the AppBuilder object
:param endpoint:
endpoint override for this blueprint,
w... |
Use this method on your own endpoints will pass the extra_args to the templates. | def render_template(self, template, **kwargs):
"""
Use this method on your own endpoints, will pass the extra_args
to the templates.
:param template: The template relative path
:param kwargs: arguments to be passed to the template
"""
kwargs["base... |
Call it on your own endpoint s to update the back history navigation. If you bypass it the next submit or back will go over it. | def update_redirect(self):
"""
Call it on your own endpoint's to update the back history navigation.
If you bypass it, the next submit or back will go over it.
"""
page_history = Stack(session.get("page_history", []))
page_history.push(request.url)
session... |
Returns the previous url. | def get_redirect(self):
"""
Returns the previous url.
"""
index_url = self.appbuilder.get_url_for_index
page_history = Stack(session.get("page_history", []))
if page_history.pop() is None:
return index_url
session["page_history"] = page_history.to... |
Prepares dict with labels to be JSON serializable | def _label_columns_json(self):
"""
Prepares dict with labels to be JSON serializable
"""
ret = {}
for key, value in list(self.label_columns.items()):
ret[key] = as_unicode(value.encode("UTF-8"))
return ret |
Init forms for Add and Edit | def _init_forms(self):
"""
Init forms for Add and Edit
"""
super(BaseCRUDView, self)._init_forms()
conv = GeneralModelConverter(self.datamodel)
if not self.add_form:
self.add_form = conv.create_form(
self.label_columns,
self... |
Init Properties | def _init_properties(self):
"""
Init Properties
"""
super(BaseCRUDView, self)._init_properties()
# Reset init props
self.related_views = self.related_views or []
self._related_views = self._related_views or []
self.description_columns = self.descriptio... |
: return: Returns a dict with related_views key with a list of Model View widgets | def _get_related_views_widgets(
self, item, orders=None, pages=None, page_sizes=None, widgets=None, **args
):
"""
:return:
Returns a dict with 'related_views' key with a list of
Model View widgets
"""
widgets = widgets or {}
widgets... |
get joined base filter and current active filter for query | def _get_list_widget(
self,
filters,
actions=None,
order_column="",
order_direction="",
page=None,
page_size=None,
widgets=None,
**args
):
""" get joined base filter and current active filter for query """
widgets = widgets or ... |
list function logic override to implement different logic returns list and search widget | def _list(self):
"""
list function logic, override to implement different logic
returns list and search widget
"""
if get_order_args().get(self.__class__.__name__):
order_column, order_direction = get_order_args().get(
self.__class__.__name__
... |
show function logic override to implement different logic returns show and related list widget | def _show(self, pk):
"""
show function logic, override to implement different logic
returns show and related list widget
"""
pages = get_page_args()
page_sizes = get_page_size_args()
orders = get_order_args()
item = self.datamodel.get(pk, self._ba... |
Add function logic override to implement different logic returns add widget or None | def _add(self):
"""
Add function logic, override to implement different logic
returns add widget or None
"""
is_valid_form = True
get_filter_args(self._filters)
exclude_cols = self._filters.get_relation_cols()
form = self.add_form.refresh()
... |
Edit function logic override to implement different logic returns Edit widget and related list or None | def _edit(self, pk):
"""
Edit function logic, override to implement different logic
returns Edit widget and related list or None
"""
is_valid_form = True
pages = get_page_args()
page_sizes = get_page_size_args()
orders = get_order_args()
ge... |
Delete function logic override to implement different logic deletes the record with primary_key = pk | def _delete(self, pk):
"""
Delete function logic, override to implement different logic
deletes the record with primary_key = pk
:param pk:
record primary key to delete
"""
item = self.datamodel.get(pk, self._base_filters)
if not item:... |
fill the form with the suppressed cols generated from exclude_cols | def _fill_form_exclude_cols(self, exclude_cols, form):
"""
fill the form with the suppressed cols, generated from exclude_cols
"""
for filter_key in exclude_cols:
filter_value = self._filters.get_filter_value(filter_key)
rel_obj = self.datamodel.get_related_ob... |
Download a file from the current connection to the local filesystem. | def get(self, remote, local=None, preserve_mode=True):
"""
Download a file from the current connection to the local filesystem.
:param str remote:
Remote file to download.
May be absolute, or relative to the remote working directory.
.. note::
... |
Upload a file from the local filesystem to the current connection. | def put(self, local, remote=None, preserve_mode=True):
"""
Upload a file from the local filesystem to the current connection.
:param local:
Local path of file to upload, or a file-like object.
**If a string is given**, it should be a path to a local (regular)
... |
Load SSH config file ( s ) from disk. | def load_ssh_config(self):
"""
Load SSH config file(s) from disk.
Also (beforehand) ensures that Invoke-level config re: runtime SSH
config file paths, is accounted for.
.. versionadded:: 2.0
"""
# Update the runtime SSH config path (assumes enough regular confi... |
Trigger loading of configured SSH config file paths. | def _load_ssh_files(self):
"""
Trigger loading of configured SSH config file paths.
Expects that ``base_ssh_config`` has already been set to an
`~paramiko.config.SSHConfig` object.
:returns: ``None``.
"""
# TODO: does this want to more closely ape the behavior o... |
Attempt to open and parse an SSH config file at path. | def _load_ssh_file(self, path):
"""
Attempt to open and parse an SSH config file at ``path``.
Does nothing if ``path`` is not a path to a valid file.
:returns: ``None``.
"""
if os.path.isfile(path):
old_rules = len(self.base_ssh_config._config)
w... |
Default configuration values and behavior toggles. | def global_defaults():
"""
Default configuration values and behavior toggles.
Fabric only extends this method in order to make minor adjustments and
additions to Invoke's `~invoke.config.Config.global_defaults`; see its
documentation for the base values, such as the config subtr... |
Read chunk_size from reader writing result to writer. | def read_and_write(self, reader, writer, chunk_size):
"""
Read ``chunk_size`` from ``reader``, writing result to ``writer``.
Returns ``None`` if successful, or ``True`` if the read was empty.
.. versionadded:: 2.0
"""
data = reader.recv(chunk_size)
if len(data) ... |
Return the local executing username or None if one can t be found. | def get_local_user():
"""
Return the local executing username, or ``None`` if one can't be found.
.. versionadded:: 2.0
"""
# TODO: I don't understand why these lines were added outside the
# try/except, since presumably it means the attempt at catching ImportError
# wouldn't work. However,... |
Parameterize a Call with its Context set to a per - host Config. | def parameterize(self, call, host):
"""
Parameterize a Call with its Context set to a per-host Config.
"""
debug("Parameterizing {!r} for host {!r}".format(call, host))
# Generate a custom ConnectionCall that knows how to yield a Connection
# in its make_context(), specif... |
Run command truly locally and over SSH via localhost | def mixed_use_of_local_and_run(self):
"""
Run command truly locally, and over SSH via localhost
"""
cxn = Connection("localhost")
result = cxn.local("echo foo", hide=True)
assert result.stdout == "foo\n"
assert not cxn.is_connected # meh way of proving it didn't ... |
Initiate an SSH connection to the host/ port this object is bound to. | def open(self):
"""
Initiate an SSH connection to the host/port this object is bound to.
This may include activating the configured gateway connection, if one
is set.
Also saves a handle to the now-set Transport object for easier access.
Various connect-time settings (... |
Obtain a socket - like object from gateway. | def open_gateway(self):
"""
Obtain a socket-like object from `gateway`.
:returns:
A ``direct-tcpip`` `paramiko.channel.Channel`, if `gateway` was a
`.Connection`; or a `~paramiko.proxy.ProxyCommand`, if `gateway`
was a string.
.. versionadded:: 2.0
... |
Terminate the network connection to the remote end if open. | def close(self):
"""
Terminate the network connection to the remote end, if open.
If no connection is open, this method does nothing.
.. versionadded:: 2.0
"""
if self.is_connected:
self.client.close()
if self.forward_agent and self._agent_handle... |
Execute a shell command on the remote end of this connection. | def run(self, command, **kwargs):
"""
Execute a shell command on the remote end of this connection.
This method wraps an SSH-capable implementation of
`invoke.runners.Runner.run`; see its documentation for details.
.. warning::
There are a few spots where Fabric dep... |
Execute a shell command via sudo on the remote end. | def sudo(self, command, **kwargs):
"""
Execute a shell command, via ``sudo``, on the remote end.
This method is identical to `invoke.context.Context.sudo` in every way,
except in that -- like `run` -- it honors per-host/per-connection
configuration overrides in addition to the g... |
Execute a shell command on the local system. | def local(self, *args, **kwargs):
"""
Execute a shell command on the local system.
This method is effectively a wrapper of `invoke.run`; see its docs for
details and call signature.
.. versionadded:: 2.0
"""
# Superclass run() uses runners.local, so we can liter... |
Return a ~paramiko. sftp_client. SFTPClient object. | def sftp(self):
"""
Return a `~paramiko.sftp_client.SFTPClient` object.
If called more than one time, memoizes the first result; thus, any
given `.Connection` instance will only ever have a single SFTP client,
and state (such as that managed by
`~paramiko.sftp_client.SFT... |
Open a tunnel connecting local_port to the server s environment. | def forward_local(
self,
local_port,
remote_port=None,
remote_host="localhost",
local_host="localhost",
):
"""
Open a tunnel connecting ``local_port`` to the server's environment.
For example, say you want to connect to a remote PostgreSQL database
... |
Open a tunnel connecting remote_port to the local environment. | def forward_remote(
self,
remote_port,
local_port=None,
remote_host="127.0.0.1",
local_host="localhost",
):
"""
Open a tunnel connecting ``remote_port`` to the local environment.
For example, say you're running a daemon in development mode on your
... |
Given a list ( l ) will removing duplicates from the list preserving the original order of the list. Assumes that the list entrie are hashable. | def dedup_list(l):
"""Given a list (l) will removing duplicates from the list,
preserving the original order of the list. Assumes that
the list entrie are hashable."""
dedup = set()
return [ x for x in l if not (x in dedup or dedup.add(x))] |
Parses sentence s using CNF grammar g. | def _parse(s, g):
"""Parses sentence 's' using CNF grammar 'g'."""
# The CYK table. Indexed with a 2-tuple: (start pos, end pos)
table = defaultdict(set)
# Top-level structure is similar to the CYK table. Each cell is a dict from
# rule name to the best (lightest) tree for that rule.
trees = def... |
Returns a non - terminal unit rule from g or None if there is none. | def get_any_nt_unit_rule(g):
"""Returns a non-terminal unit rule from 'g', or None if there is none."""
for rule in g.rules:
if len(rule.rhs) == 1 and isinstance(rule.rhs[0], NT):
return rule
return None |
Removes rule from g without changing the langugage produced by g. | def _remove_unit_rule(g, rule):
"""Removes 'rule' from 'g' without changing the langugage produced by 'g'."""
new_rules = [x for x in g.rules if x != rule]
refs = [x for x in g.rules if x.lhs == rule.rhs[0]]
new_rules += [build_unit_skiprule(rule, ref) for ref in refs]
return Grammar(new_rules) |
Splits a rule whose len ( rhs ) > 2 into shorter rules. | def _split(rule):
"""Splits a rule whose len(rhs) > 2 into shorter rules."""
rule_str = str(rule.lhs) + '__' + '_'.join(str(x) for x in rule.rhs)
rule_name = '__SP_%s' % (rule_str) + '_%d'
yield Rule(rule.lhs, [rule.rhs[0], NT(rule_name % 1)], weight=rule.weight, alias=rule.alias)
for i in xrange(1,... |
Applies the TERM rule on g ( see top comment ). | def _term(g):
"""Applies the TERM rule on 'g' (see top comment)."""
all_t = {x for rule in g.rules for x in rule.rhs if isinstance(x, T)}
t_rules = {t: Rule(NT('__T_%s' % str(t)), [t], weight=0, alias='Term') for t in all_t}
new_rules = []
for rule in g.rules:
if len(rule.rhs) > 1 and any(is... |
Applies the BIN rule to g ( see top comment ). | def _bin(g):
"""Applies the BIN rule to 'g' (see top comment)."""
new_rules = []
for rule in g.rules:
if len(rule.rhs) > 2:
new_rules += _split(rule)
else:
new_rules.append(rule)
return Grammar(new_rules) |
Applies the UNIT rule to g ( see top comment ). | def _unit(g):
"""Applies the UNIT rule to 'g' (see top comment)."""
nt_unit_rule = get_any_nt_unit_rule(g)
while nt_unit_rule:
g = _remove_unit_rule(g, nt_unit_rule)
nt_unit_rule = get_any_nt_unit_rule(g)
return g |
Reverts a parse tree ( RuleNode ) to its original non - CNF form ( Node ). | def revert_cnf(node):
"""Reverts a parse tree (RuleNode) to its original non-CNF form (Node)."""
if isinstance(node, T):
return node
# Reverts TERM rule.
if node.rule.lhs.name.startswith('__T_'):
return node.children[0]
else:
children = []
for child in map(revert_cnf,... |
Converts a lark rule ( lhs rhs callback options ) to a Rule. | def _to_rule(self, lark_rule):
"""Converts a lark rule, (lhs, rhs, callback, options), to a Rule."""
assert isinstance(lark_rule.origin, NT)
assert all(isinstance(x, Symbol) for x in lark_rule.expansion)
return Rule(
lark_rule.origin, lark_rule.expansion,
weight=l... |
Parses input which is a list of tokens. | def parse(self, tokenized): # pylint: disable=invalid-name
"""Parses input, which is a list of tokens."""
table, trees = _parse(tokenized, self.grammar)
# Check if the parse succeeded.
if all(r.lhs != self.start for r in table[(0, len(tokenized) - 1)]):
raise ParseError('Par... |
Converts a RuleNode parse tree to a lark Tree. | def _to_tree(self, rule_node):
"""Converts a RuleNode parse tree to a lark Tree."""
orig_rule = self.orig_rules[rule_node.rule.alias]
children = []
for child in rule_node.children:
if isinstance(child, RuleNode):
children.append(self._to_tree(child))
... |
Creates a colorful image that represents the tree ( data + children without meta ) | def pydot__tree_to_png(tree, filename, rankdir="LR"):
"""Creates a colorful image that represents the tree (data+children, without meta)
Possible values for `rankdir` are "TB", "LR", "BT", "RL", corresponding to
directed graphs drawn from top to bottom, from left to right, from bottom to
top, and from ... |
Expand ( inline ) children at the given indices | def expand_kids_by_index(self, *indices):
"Expand (inline) children at the given indices"
for i in sorted(indices, reverse=True): # reverse so that changing tail won't affect indices
kid = self.children[i]
self.children[i:i+1] = kid.children |
See Interpreter | def visit_children_decor(func):
"See Interpreter"
@wraps(func)
def inner(cls, tree):
values = cls.visit_children(tree)
return func(cls, values)
return inner |
A convenience decorator factory for modifying the behavior of user - supplied visitor methods | def v_args(inline=False, meta=False, tree=False):
"A convenience decorator factory, for modifying the behavior of user-supplied visitor methods"
if [tree, meta, inline].count(True) > 1:
raise ValueError("Visitor functions can either accept tree, or meta, or be inlined. These cannot be combined.")
de... |
Given a parser instance and a dictionary mapping some label with some malformed syntax examples it ll return the label for the example that bests matches the current error. | def match_examples(self, parse_fn, examples):
""" Given a parser instance and a dictionary mapping some label with
some malformed syntax examples, it'll return the label for the
example that bests matches the current error.
"""
assert self.state is not None, "Not supporte... |
Consume a token and calculate the new line & column. | def feed(self, token, test_newline=True):
"""Consume a token and calculate the new line & column.
As an optional optimization, set test_newline=False is token doesn't contain a newline.
"""
if test_newline:
newlines = token.count(self.newline_char)
if newlines:
... |
Create an instance of Lark with the grammar given by its filename | def open(cls, grammar_filename, rel_to=None, **options):
"""Create an instance of Lark with the grammar given by its filename
If rel_to is provided, the function will find the grammar filename in relation to it.
Example:
>>> Lark.open("grammar_file.lark", rel_to=__file__, parser="... |
Only lex ( and postlex ) the text without parsing it. Only relevant when lexer = standard | def lex(self, text):
"Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
if not hasattr(self, 'lexer'):
self.lexer = self._build_lexer()
stream = self.lexer.lex(text)
if self.options.postlex:
return self.options.postlex.proce... |
Calculate FOLLOW sets. | def calculate_sets(rules):
"""Calculate FOLLOW sets.
Adapted from: http://lara.epfl.ch/w/cc09:algorithm_for_first_and_follow_sets"""
symbols = {sym for rule in rules for sym in rule.expansion} | {rule.origin for rule in rules}
# foreach grammar rule X ::= Y(1) ... Y(k)
# if k=0 or {Y(1),...,Y(k)} ... |
Returns all init_ptrs accessible by rule ( recursive ) | def expand_rule(self, rule):
"Returns all init_ptrs accessible by rule (recursive)"
init_ptrs = set()
def _expand_rule(rule):
assert not rule.is_term, rule
for r in self.rules_by_origin[rule]:
init_ptr = RulePtr(r, 0)
init_ptrs.add(init_pt... |
Returns all rules and terminals of grammar prepended with a namespace prefix except for those which are aliased. | def import_from_grammar_into_namespace(grammar, namespace, aliases):
"""Returns all rules and terminals of grammar, prepended
with a 'namespace' prefix, except for those which are aliased.
"""
imported_terms = dict(grammar.term_defs)
imported_rules = {n:(n,deepcopy(t),o) for n,t,o in grammar.rule_d... |
Parse grammar_text verify and create Grammar object. Display nice messages on error. | def load_grammar(self, grammar_text, grammar_name='<?>'):
"Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
try:
tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
except UnexpectedCharacters as e:
context =... |
The core Earley Predictor and Completer. | def predict_and_complete(self, i, to_scan, columns, transitives):
"""The core Earley Predictor and Completer.
At each stage of the input, we handling any completed items (things
that matched on the last cycle) and use those to predict what should
come next in the input stream. The compl... |
Conditionally disabled/ enables form fields based on the current section in the radio group | def applyStyleRules(self):
"""
Conditionally disabled/enables form fields based on the current
section in the radio group
"""
for button, widget in zip(self.radioButtons, self.widgets):
if isinstance(widget, CheckBox):
widget.hideInput()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.