INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Finaliza la seleccion.
Marca como seleccionados todos los objetos que se encuentran
dentro del recuadro de seleccion. | def _finish_selecting(self, event):
"""Finaliza la seleccion.
Marca como seleccionados todos los objetos que se encuentran
dentro del recuadro de seleccion."""
self._selecting = False
canvas = self._canvas
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
... |
Create a callback to manage mousewheel events
orient: string (posible values: ('x', 'y'))
widget: widget that implement tk xview and yview methods | def make_onmousewheel_cb(widget, orient, factor = 1):
"""Create a callback to manage mousewheel events
orient: string (posible values: ('x', 'y'))
widget: widget that implement tk xview and yview methods
"""
_os = platform.system()
view_command = getattr(widget, ... |
- json list of key, value pairs:
Example: [["A", "Option 1 Label"], ["B", "Option 2 Label"]]
- space separated string with a list of options:
Example: "Option1 Opt2 Opt3"
will be converted to a key, value pair of the following form:
(("Option1", "Option1), ("Opt2"... | def __obj2choices(self, values):
"""
- json list of key, value pairs:
Example: [["A", "Option 1 Label"], ["B", "Option 2 Label"]]
- space separated string with a list of options:
Example: "Option1 Opt2 Opt3"
will be converted to a key, value pair of the follow... |
choices: iterable of key, value pairs | def __choices2tkvalues(self, choices):
"""choices: iterable of key, value pairs"""
values = []
for k, v in choices:
values.append(v)
return values |
Generate coords for a matrix of rects | def matrix_coords(rows, cols, rowh, colw, ox=0, oy=0):
"Generate coords for a matrix of rects"
for i, f, c in rowmajor(rows, cols):
x = ox + c * colw
y = oy + f * rowh
x1 = x + colw
y1 = y + rowh
yield (i, x, y, x1, y1) |
Marks the specified month day with a visual marker
(typically by making the number bold).
If only day is specified and the calendar month and year
are changed, the marked day remain marked.
You can be more specific setting month and year parameters. | def mark_day(self, day, month=None, year=None):
"""Marks the specified month day with a visual marker
(typically by making the number bold).
If only day is specified and the calendar month and year
are changed, the marked day remain marked.
You can be more specific setting month ... |
Draws calendar. | def _draw_calendar(self, canvas, redraw=False):
"""Draws calendar."""
options = self.__options
# Update labels:
name = self._cal.formatmonthname(self._date.year, self._date.month, 0,
withyear=False)
self._lmonth.configure(text=name.title()... |
Return a dictionary that represents the Tcl array | def get(self):
'''Return a dictionary that represents the Tcl array'''
value = {}
for (elementname, elementvar) in self._elementvars.items():
value[elementname] = elementvar.get()
return value |
Update inplace widgets position when doing vertical scroll | def yview(self, *args):
"""Update inplace widgets position when doing vertical scroll"""
self.after_idle(self.__updateWnds)
ttk.Treeview.yview(self, *args) |
Update inplace widgets position when doing horizontal scroll | def xview(self, *args):
"""Update inplace widgets position when doing horizontal scroll"""
self.after_idle(self.__updateWnds)
ttk.Treeview.xview(self, *args) |
Checks if the focus has changed | def __check_focus(self, event):
"""Checks if the focus has changed"""
#print('Event:', event.type, event.x, event.y)
changed = False
if not self._curfocus:
changed = True
elif self._curfocus != self.focus():
self.__clear_inplace_widgets()
chang... |
Called when focus item has changed | def __focus(self, item):
"""Called when focus item has changed"""
cols = self.__get_display_columns()
for col in cols:
self.__event_info =(col,item)
self.event_generate('<<TreeviewInplaceEdit>>')
if col in self._inplace_widgets:
w = self._inpla... |
Remove all inplace edit widgets. | def __clear_inplace_widgets(self):
"""Remove all inplace edit widgets."""
cols = self.__get_display_columns()
#print('Clear:', cols)
for c in cols:
if c in self._inplace_widgets:
widget = self._inplace_widgets[c]
widget.place_forget()
... |
Run parent install, and then save the install dir in the script. | def run(self):
"""Run parent install, and then save the install dir in the script."""
install.run(self)
#
# Remove old pygubu.py from scripts path if exists
spath = os.path.join(self.install_scripts, 'pygubu')
for ext in ('.py', '.pyw'):
filename = spath + ex... |
Populate a frame with a list of all editable properties | def _create_properties(self):
"""Populate a frame with a list of all editable properties"""
self._rcbag = {} # bag for row/column prop editors
self._fgrid = f = ttk.Labelframe(self._sframe.innerframe,
text=_('Grid options:'), padding=5)
f.grid(st... |
Populate a frame with a list of all editable properties | def _create_properties(self):
"""Populate a frame with a list of all editable properties"""
self._frame = f = ttk.Labelframe(self._sframe.innerframe,
text=_('Widget properties'))
f.grid(sticky='nswe')
label_tpl = "{0}:"
row = 0
co... |
Hide all properties from property editor. | def hide_all(self):
"""Hide all properties from property editor."""
self.current = None
for _v, (label, widget) in self._propbag.items():
label.grid_remove()
widget.grid_remove() |
Creates dict with properties marked as readonly | def _get_init_args(self):
"""Creates dict with properties marked as readonly"""
args = {}
for rop in self.ro_properties:
if rop in self.properties:
args[rop] = self.properties[rop]
return args |
Calculate menu widht and height. | def _calculate_menu_wh(self):
""" Calculate menu widht and height."""
w = iw = 50
h = ih = 0
# menu.index returns None if there are no choices
index = self._menu.index(tk.END)
index = index if index is not None else 0
count = index + 1
# First calculate u... |
Returns True if mouse is over a resizer | def _over_resizer(self, x, y):
"Returns True if mouse is over a resizer"
over_resizer = False
c = self.canvas
ids = c.find_overlapping(x, y, x, y)
if ids:
o = ids[0]
tags = c.gettags(o)
if 'resizer' in tags:
over_resizer = True... |
Resizes preview that is currently dragged | def resize_preview(self, dw, dh):
"Resizes preview that is currently dragged"
# identify preview
if self._objects_moving:
id_ = self._objects_moving[0]
tags = self.canvas.gettags(id_)
for tag in tags:
if tag.startswith('preview_'):
... |
Move previews after a resize event | def move_previews(self):
"Move previews after a resize event"
# calculate new positions
min_y = self._calc_preview_ypos()
for idx, (key, p) in enumerate(self.previews.items()):
new_dy = min_y[idx] - p.y
self.previews[key].move_by(0, new_dy)
self._update_c... |
Calculates the previews positions on canvas | def _calc_preview_ypos(self):
"Calculates the previews positions on canvas"
y = 10
min_y = [y]
for k, p in self.previews.items():
y += p.height() + self.padding
min_y.append(y)
return min_y |
Returns the next coordinates for a preview | def _get_slot(self):
"Returns the next coordinates for a preview"
x = y = 10
for k, p in self.previews.items():
y += p.height() + self.padding
return x, y |
Call this before closing tk root | def clear_cache(cls):
"""Call this before closing tk root"""
#Prevent tkinter errors on python 2 ??
for key in cls._cached:
cls._cached[key] = None
cls._cached = {} |
Register a image file using key | def register(cls, key, filename):
"""Register a image file using key"""
if key in cls._stock:
logger.info('Warning, replacing resource ' + str(key))
cls._stock[key] = {'type': 'custom', 'filename': filename}
logger.info('%s registered as %s' % (filename, key)) |
Register a image data using key | def register_from_data(cls, key, format, data):
"""Register a image data using key"""
if key in cls._stock:
logger.info('Warning, replacing resource ' + str(key))
cls._stock[key] = {'type': 'data', 'data': data, 'format': format }
logger.info('%s registered as %s' % ('data',... |
Register an already created image using key | def register_created(cls, key, image):
"""Register an already created image using key"""
if key in cls._stock:
logger.info('Warning, replacing resource ' + str(key))
cls._stock[key] = {'type': 'created', 'image': image}
logger.info('%s registered as %s' % ('data', key)) |
List files from dir_path and register images with
filename as key (without extension)
Additionaly a prefix for the key can be provided,
so the resulting key will be prefix + filename | def register_from_dir(cls, dir_path, prefix=''):
"""List files from dir_path and register images with
filename as key (without extension)
Additionaly a prefix for the key can be provided,
so the resulting key will be prefix + filename
"""
for filename in os.listdir(d... |
Load image from file or return the cached instance. | def _load_image(cls, rkey):
"""Load image from file or return the cached instance."""
v = cls._stock[rkey]
img = None
itype = v['type']
if itype in ('stock', 'data'):
img = tk.PhotoImage(format=v['format'], data=v['data'])
elif itype == 'created':
... |
Get image previously registered with key rkey.
If key not exist, raise StockImageException | def get(cls, rkey):
"""Get image previously registered with key rkey.
If key not exist, raise StockImageException
"""
if rkey in cls._cached:
logger.info('Resource %s is in cache.' % rkey)
return cls._cached[rkey]
if rkey in cls._stock:
img = ... |
Sets treeview columns and other params | def config_treeview(self):
"""Sets treeview columns and other params"""
tree = self.treeview
tree.bind('<Double-1>', self.on_treeview_double_click)
tree.bind('<<TreeviewSelect>>', self.on_treeview_select, add='+') |
Returns the top level parent for treeitem. | def get_toplevel_parent(self, treeitem):
"""Returns the top level parent for treeitem."""
tv = self.treeview
toplevel_items = tv.get_children()
item = treeitem
while not (item in toplevel_items):
item = tv.parent(item)
return item |
Create a preview of the selected treeview item | def draw_widget(self, item):
"""Create a preview of the selected treeview item"""
if item:
self.filter_remove(remember=True)
selected_id = self.treedata[item]['id']
item = self.get_toplevel_parent(item)
widget_id = self.treedata[item]['id']
wcl... |
Removes selected items from treeview | def on_treeview_delete_selection(self, event=None):
"""Removes selected items from treeview"""
tv = self.treeview
selection = tv.selection()
# Need to remove filter
self.filter_remove(remember=True)
toplevel_items = tv.get_children()
parents_to_redraw = set()
... |
Traverses treeview and generates a ElementTree object | def tree_to_xml(self):
"""Traverses treeview and generates a ElementTree object"""
# Need to remove filter or hidden items will not be saved.
self.filter_remove(remember=True)
tree = self.treeview
root = ET.Element('interface')
items = tree.get_children()
for it... |
Converts a treeview item and children to xml nodes | def tree_node_to_xml(self, parent, item):
"""Converts a treeview item and children to xml nodes"""
tree = self.treeview
data = self.treedata[item]
node = data.to_xml_node()
children = tree.get_children(item)
for child in children:
cnode = ET.Element('child')... |
Insert a item on the treeview and fills columns from data | def _insert_item(self, root, data, from_file=False):
"""Insert a item on the treeview and fills columns from data"""
tree = self.treeview
treelabel = data.get_id()
row = col = ''
if root != '' and 'layout' in data:
row = data.get_layout_property('row')
co... |
Copies selected items to clipboard. | def copy_to_clipboard(self):
"""
Copies selected items to clipboard.
"""
tree = self.treeview
# get the selected item:
selection = tree.selection()
if selection:
self.filter_remove(remember=True)
root = ET.Element('selection')
f... |
Adds a new item to the treeview. | def add_widget(self, wclass):
"""Adds a new item to the treeview."""
tree = self.treeview
# get the selected item:
selected_item = ''
tsel = tree.selection()
if tsel:
selected_item = tsel[0]
# Need to remove filter if set
self.filter_remove... |
Load file into treeview | def load_file(self, filename):
"""Load file into treeview"""
self.counter.clear()
# python2 issues
try:
etree = ET.parse(filename)
except ET.ParseError:
parser = ET.XMLParser(encoding='UTF-8')
etree = ET.parse(filename, parser)
eroot =... |
Reads xml nodes and populates tree item | def populate_tree(self, master, parent, element,from_file=False):
"""Reads xml nodes and populates tree item"""
data = WidgetDescr(None, None)
data.from_xml_node(element)
cname = data.get_class()
uniqueid = self.get_unique_id(cname, data.get_id())
data.set_property('id',... |
Updates tree colums when itemdata is changed. | def update_event(self, hint, obj):
"""Updates tree colums when itemdata is changed."""
tree = self.treeview
data = obj
item = self.get_item_by_data(obj)
if item:
if data.get_id() != tree.item(item, 'text'):
tree.item(item, text=data.get_id())
... |
Filters treeview | def filter_by(self, string):
"""Filters treeview"""
self._reatach()
if string == '':
self.filter_remove()
return
self._expand_all()
self.treeview.selection_set('')
children = self.treeview.get_children('')
for item in children:
... |
Reinsert the hidden items. | def _reatach(self):
"""Reinsert the hidden items."""
for item, p, idx in self._detached:
# The item may have been deleted.
if self.treeview.exists(item) and self.treeview.exists(p):
self.treeview.move(item, p, idx)
self._detached = [] |
Hide items from treeview that do not match the search string. | def _detach(self, item):
"""Hide items from treeview that do not match the search string."""
to_detach = []
children_det = []
children_match = False
match_found = False
value = self.filtervar.get()
txt = self.treeview.item(item, 'text').lower()
if value i... |
Creates all gui widgets | def _create_ui(self):
"""Creates all gui widgets"""
self.preview = None
self.about_dialog = None
self.preferences = None
self.builder = pygubu.Builder(translator)
self.currentfile = None
self.is_changed = False
uifile = os.path.join(FILE_PATH, "ui/pygubu... |
Load xml into treeview | def load_file(self, filename):
"""Load xml into treeview"""
self.tree_editor.load_file(filename)
self.project_name.configure(text=filename)
self.currentfile = filename
self.is_changed = False |
Lower the IR into an IR form that can be represented in Gremlin queries.
Args:
ir_blocks: list of IR blocks to lower into Gremlin-compatible form
query_metadata_table: QueryMetadataTable object containing all metadata collected during
query processing, including locati... | def lower_ir(ir_blocks, query_metadata_table, type_equivalence_hints=None):
"""Lower the IR into an IR form that can be represented in Gremlin queries.
Args:
ir_blocks: list of IR blocks to lower into Gremlin-compatible form
query_metadata_table: QueryMetadataTable object containing all metadat... |
Rewrite CoerceType blocks to explicitly state which types are allowed in the coercion. | def lower_coerce_type_block_type_data(ir_blocks, type_equivalence_hints):
"""Rewrite CoerceType blocks to explicitly state which types are allowed in the coercion."""
allowed_key_type_spec = (GraphQLInterfaceType, GraphQLObjectType)
allowed_value_type_spec = GraphQLUnionType
# Validate that the type_eq... |
Lower CoerceType blocks into Filter blocks with a type-check predicate. | def lower_coerce_type_blocks(ir_blocks):
"""Lower CoerceType blocks into Filter blocks with a type-check predicate."""
new_ir_blocks = []
for block in ir_blocks:
new_block = block
if isinstance(block, CoerceType):
predicate = BinaryComposition(
u'contains', Liter... |
In optional contexts, add a check for null that allows non-existent optional data through.
Optional traversals in Gremlin represent missing optional data by setting the current vertex
to null until the exit from the optional scope. Therefore, filtering and type coercions
(which should have been lowered int... | def rewrite_filters_in_optional_blocks(ir_blocks):
"""In optional contexts, add a check for null that allows non-existent optional data through.
Optional traversals in Gremlin represent missing optional data by setting the current vertex
to null until the exit from the optional scope. Therefore, filtering ... |
Convert Filter/Traverse blocks and LocalField expressions within @fold to Gremlin objects. | def _convert_folded_blocks(folded_ir_blocks):
"""Convert Filter/Traverse blocks and LocalField expressions within @fold to Gremlin objects."""
new_folded_ir_blocks = []
def folded_context_visitor(expression):
"""Transform LocalField objects into their Gremlin-specific counterpart."""
if not... |
Lower standard folded output fields into GremlinFoldedContextField objects. | def lower_folded_outputs(ir_blocks):
"""Lower standard folded output fields into GremlinFoldedContextField objects."""
folds, remaining_ir_blocks = extract_folds_from_ir_blocks(ir_blocks)
if not remaining_ir_blocks:
raise AssertionError(u'Expected at least one non-folded block to remain: {} {} '
... |
Validate that the GremlinFoldedContextField is correctly representable. | def validate(self):
"""Validate that the GremlinFoldedContextField is correctly representable."""
if not isinstance(self.fold_scope_location, FoldScopeLocation):
raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format(
type(self.fold_scope_locatio... |
Return a unicode object with the Gremlin representation of this expression. | def to_gremlin(self):
"""Return a unicode object with the Gremlin representation of this expression."""
self.validate()
edge_direction, edge_name = self.fold_scope_location.get_first_folded_edge()
validate_safe_string(edge_name)
inverse_direction_table = {
'out': 'in... |
Create a GremlinFoldedTraverse block as a copy of the given Traverse block. | def from_traverse(cls, traverse_block):
"""Create a GremlinFoldedTraverse block as a copy of the given Traverse block."""
if isinstance(traverse_block, Traverse):
return cls(traverse_block.direction, traverse_block.edge_name)
else:
raise AssertionError(u'Tried to initiali... |
Return a unicode object with the Gremlin representation of this block. | def to_gremlin(self):
"""Return a unicode object with the Gremlin representation of this block."""
self.validate()
template_data = {
'direction': self.direction,
'edge_name': self.edge_name,
'inverse_direction': 'in' if self.direction == 'out' else 'out'
... |
Filter union types with no edges from the type equivalence hints dict. | def _get_referenced_type_equivalences(graphql_types, type_equivalence_hints):
"""Filter union types with no edges from the type equivalence hints dict."""
referenced_types = set()
for graphql_type in graphql_types.values():
if isinstance(graphql_type, (GraphQLObjectType, GraphQLInterfaceType)):
... |
Return a dictionary describing the field type overrides in subclasses. | def _get_inherited_field_types(class_to_field_type_overrides, schema_graph):
"""Return a dictionary describing the field type overrides in subclasses."""
inherited_field_type_overrides = dict()
for superclass_name, field_type_overrides in class_to_field_type_overrides.items():
for subclass_name in s... |
Assert that the fields we want to override are not defined in superclasses. | def _validate_overriden_fields_are_not_defined_in_superclasses(class_to_field_type_overrides,
schema_graph):
"""Assert that the fields we want to override are not defined in superclasses."""
for class_name, field_type_overrides in six.iteritems(clas... |
Return the best GraphQL type representation for an OrientDB property descriptor. | def _property_descriptor_to_graphql_type(property_obj):
"""Return the best GraphQL type representation for an OrientDB property descriptor."""
property_type = property_obj.type_id
scalar_types = {
PROPERTY_TYPE_BOOLEAN_ID: GraphQLBoolean,
PROPERTY_TYPE_DATE_ID: GraphQLDate,
PROPERTY_... |
Construct a unique union type name based on the type names being unioned. | def _get_union_type_name(type_names_to_union):
"""Construct a unique union type name based on the type names being unioned."""
if not type_names_to_union:
raise AssertionError(u'Expected a non-empty list of type names to union, received: '
u'{}'.format(type_names_to_union))
... |
Return a dict from field name to GraphQL field type, for the specified graph class. | def _get_fields_for_class(schema_graph, graphql_types, field_type_overrides, hidden_classes,
cls_name):
"""Return a dict from field name to GraphQL field type, for the specified graph class."""
properties = schema_graph.get_element_by_class_name(cls_name).properties
# Add leaf Gra... |
Return a function that specifies the fields present on the given type. | def _create_field_specification(schema_graph, graphql_types, field_type_overrides,
hidden_classes, cls_name):
"""Return a function that specifies the fields present on the given type."""
def field_maker_func():
"""Create and return the fields for the given GraphQL type.""... |
Return a function that specifies the interfaces implemented by the given type. | def _create_interface_specification(schema_graph, graphql_types, hidden_classes, cls_name):
"""Return a function that specifies the interfaces implemented by the given type."""
def interface_spec():
"""Return a list of GraphQL interface types implemented by the type named 'cls_name'."""
abstract... |
Return a function that gives the types in the union type rooted at base_name. | def _create_union_types_specification(schema_graph, graphql_types, hidden_classes, base_name):
"""Return a function that gives the types in the union type rooted at base_name."""
# When edges point to vertices of type base_name, and base_name is both non-abstract and
# has subclasses, we need to represent t... |
Return a GraphQL schema object corresponding to the schema of the given schema graph.
Args:
schema_graph: SchemaGraph
class_to_field_type_overrides: dict, class name -> {field name -> field type},
(string -> {string -> GraphQLType}). Used to override the
... | def get_graphql_schema_from_schema_graph(schema_graph, class_to_field_type_overrides,
hidden_classes):
"""Return a GraphQL schema object corresponding to the schema of the given schema graph.
Args:
schema_graph: SchemaGraph
class_to_field_type_overrides:... |
Extract locations from TernaryConditionals and rewrite their Filter blocks as necessary. | def workaround_lowering_pass(ir_blocks, query_metadata_table):
"""Extract locations from TernaryConditionals and rewrite their Filter blocks as necessary."""
new_ir_blocks = []
for block in ir_blocks:
if isinstance(block, Filter):
new_block = _process_filter_block(query_metadata_table, ... |
Rewrite the provided Filter block if necessary. | def _process_filter_block(query_metadata_table, block):
"""Rewrite the provided Filter block if necessary."""
# For a given Filter block with BinaryComposition predicate expression X,
# let L be the set of all Locations referenced in any TernaryConditional
# predicate expression enclosed in X.
# For... |
For a given location, create a BinaryComposition that always evaluates to 'true'. | def _create_tautological_expression_for_location(query_metadata_table, location):
"""For a given location, create a BinaryComposition that always evaluates to 'true'."""
location_type = query_metadata_table.get_location_info(location).type
location_exists = BinaryComposition(
u'!=', ContextField(lo... |
Assert that the collection has exactly one element, then return that element. | def get_only_element_from_collection(one_element_collection):
"""Assert that the collection has exactly one element, then return that element."""
if len(one_element_collection) != 1:
raise AssertionError(u'Expected a collection with exactly one element, but got: {}'
.format(... |
Return the normalized field name for the given AST node. | def get_ast_field_name(ast):
"""Return the normalized field name for the given AST node."""
replacements = {
# We always rewrite the following field names into their proper underlying counterparts.
TYPENAME_META_FIELD_NAME: '@class'
}
base_field_name = ast.name.value
normalized_name ... |
Return the type of the field in the given type, accounting for field name normalization. | def get_field_type_from_schema(schema_type, field_name):
"""Return the type of the field in the given type, accounting for field name normalization."""
if field_name == '@class':
return GraphQLString
else:
if field_name not in schema_type.fields:
raise AssertionError(u'Field {} p... |
Return the type of the vertex within the specified vertex field name of the given type. | def get_vertex_field_type(current_schema_type, vertex_field_name):
"""Return the type of the vertex within the specified vertex field name of the given type."""
# According to the schema, the vertex field itself is of type GraphQLList, and this is
# what get_field_type_from_schema returns. We care about wha... |
Get the edge direction and name from a non-root vertex field name. | def get_edge_direction_and_name(vertex_field_name):
"""Get the edge direction and name from a non-root vertex field name."""
edge_direction = None
edge_name = None
if vertex_field_name.startswith(OUTBOUND_EDGE_FIELD_PREFIX):
edge_direction = OUTBOUND_EDGE_DIRECTION
edge_name = vertex_fie... |
Return True if the argument is a vertex field type, and False otherwise. | def is_vertex_field_type(graphql_type):
"""Return True if the argument is a vertex field type, and False otherwise."""
# This will need to change if we ever support complex embedded types or edge field types.
underlying_type = strip_non_null_from_type(graphql_type)
return isinstance(underlying_type, (Gr... |
Ensure the value is a string, and return it as unicode. | def ensure_unicode_string(value):
"""Ensure the value is a string, and return it as unicode."""
if not isinstance(value, six.string_types):
raise TypeError(u'Expected string value, got: {}'.format(value))
return six.text_type(value) |
Return dict of name -> object pairs from a list of objects with unique names.
Args:
object_list: list of objects, each X of which has a unique name accessible as X.name.value
Returns:
dict, { X.name.value: X for x in object_list }
If the list is empty or None, returns an empty dict. | def get_uniquely_named_objects_by_name(object_list):
"""Return dict of name -> object pairs from a list of objects with unique names.
Args:
object_list: list of objects, each X of which has a unique name accessible as X.name.value
Returns:
dict, { X.name.value: X for x in object_list }
... |
Ensure the provided string does not have illegal characters. | def validate_safe_string(value):
"""Ensure the provided string does not have illegal characters."""
# The following strings are explicitly allowed, despite having otherwise-illegal chars.
legal_strings_with_special_chars = frozenset({'@rid', '@class', '@this', '%'})
if not isinstance(value, six.string_... |
Ensure the provided edge direction is either "in" or "out". | def validate_edge_direction(edge_direction):
"""Ensure the provided edge direction is either "in" or "out"."""
if not isinstance(edge_direction, six.string_types):
raise TypeError(u'Expected string edge_direction, got: {} {}'.format(
type(edge_direction), edge_direction))
if... |
Validate that a Location object is safe for marking, and not at a field. | def validate_marked_location(location):
"""Validate that a Location object is safe for marking, and not at a field."""
if not isinstance(location, (Location, FoldScopeLocation)):
raise TypeError(u'Expected Location or FoldScopeLocation location, got: {} {}'.format(
type(location).__name__, l... |
Invert a dict. A dict is invertible if values are unique and hashable. | def invert_dict(invertible_dict):
"""Invert a dict. A dict is invertible if values are unique and hashable."""
inverted = {}
for k, v in six.iteritems(invertible_dict):
if not isinstance(v, Hashable):
raise TypeError(u'Expected an invertible dict, but value at key {} has type {}'.format(... |
Read package file as text to get name and version | def read_file(filename):
"""Read package file as text to get name and version"""
# intentionally *not* adding an encoding option to open
# see here:
# https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.joi... |
Only define version in one place | def find_version():
"""Only define version in one place"""
version_file = read_file('__init__.py')
version_match = re.search(r'^__version__ = ["\']([^"\']*)["\']',
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to ... |
Only define name in one place | def find_name():
"""Only define name in one place"""
name_file = read_file('__init__.py')
name_match = re.search(r'^__package_name__ = ["\']([^"\']*)["\']',
name_file, re.M)
if name_match:
return name_match.group(1)
raise RuntimeError('Unable to find name string.') |
Lower CoerceType blocks into Filter blocks within Recurse steps. | def workaround_type_coercions_in_recursions(match_query):
"""Lower CoerceType blocks into Filter blocks within Recurse steps."""
# This step is required to work around an OrientDB bug that causes queries with both
# "while:" and "class:" in the same query location to fail to parse correctly.
#
# Thi... |
Read a GraphQL query from standard input, and output it pretty-printed to standard output. | def main():
"""Read a GraphQL query from standard input, and output it pretty-printed to standard output."""
query = ' '.join(sys.stdin.readlines())
sys.stdout.write(pretty_print_graphql(query)) |
Sanitize and represent a string argument in Gremlin. | def _safe_gremlin_string(value):
"""Sanitize and represent a string argument in Gremlin."""
if not isinstance(value, six.string_types):
if isinstance(value, bytes): # should only happen in py3
value = value.decode('utf-8')
else:
raise GraphQLInvalidArgumentError(u'Attemp... |
Represent the list of "inner_type" objects in Gremlin form. | def _safe_gremlin_list(inner_type, argument_value):
"""Represent the list of "inner_type" objects in Gremlin form."""
if not isinstance(argument_value, list):
raise GraphQLInvalidArgumentError(u'Attempting to represent a non-list as a list: '
u'{}'.format(argume... |
Return a Gremlin string representing the given argument value. | def _safe_gremlin_argument(expected_type, argument_value):
"""Return a Gremlin string representing the given argument value."""
if GraphQLString.is_same_type(expected_type):
return _safe_gremlin_string(argument_value)
elif GraphQLID.is_same_type(expected_type):
# IDs can be strings or number... |
Insert the arguments into the compiled Gremlin query to form a complete query.
The GraphQL compiler attempts to use single-quoted string literals ('abc') in Gremlin output.
Double-quoted strings allow inline interpolation with the $ symbol, see here for details:
http://www.groovy-lang.org/syntax.html#all-s... | def insert_arguments_into_gremlin_query(compilation_result, arguments):
"""Insert the arguments into the compiled Gremlin query to form a complete query.
The GraphQL compiler attempts to use single-quoted string literals ('abc') in Gremlin output.
Double-quoted strings allow inline interpolation with the $... |
Get the location name from a location that is expected to point to a vertex. | def _get_vertex_location_name(location):
"""Get the location name from a location that is expected to point to a vertex."""
mark_name, field_name = location.get_location_name()
if field_name is not None:
raise AssertionError(u'Location unexpectedly pointed to a field: {}'.format(location))
retu... |
Transform the very first MATCH step into a MATCH query string. | def _first_step_to_match(match_step):
"""Transform the very first MATCH step into a MATCH query string."""
parts = []
if match_step.root_block is not None:
if not isinstance(match_step.root_block, QueryRoot):
raise AssertionError(u'Expected None or QueryRoot root block, received: '
... |
Transform any subsequent (non-first) MATCH step into a MATCH query string. | def _subsequent_step_to_match(match_step):
"""Transform any subsequent (non-first) MATCH step into a MATCH query string."""
if not isinstance(match_step.root_block, (Traverse, Recurse)):
raise AssertionError(u'Expected Traverse root block, received: '
u'{} {}'.format(match_s... |
Emit MATCH query code for an entire MATCH traversal sequence. | def _represent_match_traversal(match_traversal):
"""Emit MATCH query code for an entire MATCH traversal sequence."""
output = []
output.append(_first_step_to_match(match_traversal[0]))
for step in match_traversal[1:]:
output.append(_subsequent_step_to_match(step))
return u''.join(output) |
Emit a LET clause corresponding to the IR blocks for a @fold scope. | def _represent_fold(fold_location, fold_ir_blocks):
"""Emit a LET clause corresponding to the IR blocks for a @fold scope."""
start_let_template = u'$%(mark_name)s = %(base_location)s'
traverse_edge_template = u'.%(direction)s("%(edge_name)s")'
base_template = start_let_template + traverse_edge_template... |
Transform a ConstructResult block into a MATCH query string. | def _construct_output_to_match(output_block):
"""Transform a ConstructResult block into a MATCH query string."""
output_block.validate()
selections = (
u'%s AS `%s`' % (output_block.fields[key].to_match(), key)
for key in sorted(output_block.fields.keys()) # Sort keys for deterministic out... |
Transform a Filter block into a MATCH query string. | def _construct_where_to_match(where_block):
"""Transform a Filter block into a MATCH query string."""
if where_block.predicate == TrueLiteral:
raise AssertionError(u'Received WHERE block with TrueLiteral predicate: {}'
.format(where_block))
return u'WHERE ' + where_block... |
Return a MATCH query string from a list of IR blocks. | def emit_code_from_single_match_query(match_query):
"""Return a MATCH query string from a list of IR blocks."""
query_data = deque([u'MATCH '])
if not match_query.match_traversals:
raise AssertionError(u'Unexpected falsy value for match_query.match_traversals received: '
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.