_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q276700
|
ElementTool.normal_left_dclick
|
test
|
def normal_left_dclick(self, event):
""" Handles the left mouse button being double-clicked when the tool
is in the 'normal' state.
If the event occurred on this tool's component (or any contained
component of that component), the method opens a Traits UI view on the
object referenced by the 'element' trait of the component that was
double-clicked, setting the tool as the active tool for the duration
of the view.
"""
x = event.x
y = event.y
# First determine what component or components we are going to hittest
# on. If our component is a container, then we add its non-container
# components to the list of candidates.
# candidates = []
component = self.component
# if isinstance(component, Container):
# candidates = get_nested_components(self.component)
# else:
# # We don't support clicking on unrecognized components
# return
#
# # Hittest against all the candidate and take the first one
# item = None
#
|
python
|
{
"resource": ""
}
|
q276701
|
CanvasMapping._diagram_canvas_changed
|
test
|
def _diagram_canvas_changed(self, new):
""" Handles the diagram canvas being set """
logger.debug("Diagram canvas changed!")
canvas = self.diagram_canvas
for tool in self.tools:
|
python
|
{
"resource": ""
}
|
q276702
|
CanvasMapping.clear_canvas
|
test
|
def clear_canvas(self):
""" Removes all components from the canvas """
logger.debug("Clearing the diagram canvas!")
old_canvas = self.diagram_canvas
# logger.debug("Canvas components: %s" % canvas.components)
# for component in canvas.components:
# canvas.remove(component)
# logger.debug("Canvas components: %s" % canvas.components)
# for component in canvas.components:
#
|
python
|
{
"resource": ""
}
|
q276703
|
Mapping._domain_model_changed_for_diagram
|
test
|
def _domain_model_changed_for_diagram(self, obj, name, old, new):
""" Handles the domain model changing """
if old is not None:
|
python
|
{
"resource": ""
}
|
q276704
|
Mapping.map_model
|
test
|
def map_model(self, new):
""" Maps a domain model to the diagram """
logger.debug("Mapping the domain model!")
dot = Dot()
self.diagram.clear_canvas()
for node_mapping in self.nodes:
ct = node_mapping.containment_trait
logger.debug("Mapping elements contained by the '%s' trait" % ct)
if hasattr(new, ct):
elements = getattr(new, ct)
logger.debug("%d element(s) found" % len(elements))
for element in elements:
pydot_node = Node(str(id(element)))
dot_attrs = node_mapping.dot_node
if dot_attrs is not None:
self._style_node(pydot_node, dot_attrs)
dot.add_node(pydot_node)
new.on_trait_change(self.map_element, ct+"_items")
logger.debug("Retrieving xdot data and forming pydot graph!")
xdot = graph_from_dot_data(dot.create(self.program, "xdot"))
parser = XDotParser()
for node in xdot.get_node_list():
diagram_node = parser.parse_node(node)
logger.debug(
"Parsed node [%s] and received diagram node [%s]" %
(node, diagram_node)
)
if diagram_node is not None:
for node_mapping in self.nodes: # FIXME: slow
ct = node_mapping.containment_trait
for element in getattr(new, ct):
if str(id(element)) == diagram_node.dot_node.get_name():
logger.debug(
"Referencing element [%s] from diagram node [%s]" %
|
python
|
{
"resource": ""
}
|
q276705
|
Mapping.unmap_model
|
test
|
def unmap_model(self, old):
""" Removes listeners from a domain model """
for node_mapping in self.nodes:
ct = node_mapping.containment_trait
if hasattr(old, ct):
old_elements = getattr(old, ct)
|
python
|
{
"resource": ""
}
|
q276706
|
Mapping.map_element
|
test
|
def map_element(self, obj, name, event):
""" Handles mapping elements to diagram components """
canvas = self.diagram.diagram_canvas
parser = XDotParser()
for element in event.added:
logger.debug("Mapping new element [%s] to diagram node" % element)
for node_mapping in self.nodes:
ct = name[:-6] #strip '_items'
if node_mapping.containment_trait == ct:
dot_attrs = node_mapping.dot_node
dot = Dot()
graph_node = Node(str(id(element)))
self._style_node(graph_node, dot_attrs)
dot.add_node(graph_node)
xdot = graph_from_dot_data(dot.create(self.program,"xdot"))
diagram_nodes = parser.parse_nodes(xdot)#.get_node_list())
for dn in diagram_nodes:
if dn is not None:
|
python
|
{
"resource": ""
}
|
q276707
|
Mapping._style_node
|
test
|
def _style_node(self, pydot_node, dot_attrs):
""" Styles a node """
pydot_node.set_shape(dot_attrs.shape)
pydot_node.set_fixedsize(str(dot_attrs.fixed_size))
pydot_node.set_width(str(dot_attrs.width))
pydot_node.set_height(str(dot_attrs.height))
pydot_node.set_color(rgba2hex(dot_attrs.color_))
pydot_node.set_fillcolor(
|
python
|
{
"resource": ""
}
|
q276708
|
XdotAttrParser.parse_xdot_data
|
test
|
def parse_xdot_data(self, data):
""" Parses xdot data and returns the associated components. """
parser = self.parser
# if pyparsing_version >= "1.2":
#
|
python
|
{
"resource": ""
}
|
q276709
|
XdotAttrParser.proc_font
|
test
|
def proc_font(self, tokens):
""" Sets the font. """
|
python
|
{
"resource": ""
}
|
q276710
|
XdotAttrParser._proc_ellipse
|
test
|
def _proc_ellipse(self, tokens, filled):
""" Returns the components of an ellipse. """
component = Ellipse(pen=self.pen,
x_origin=tokens["x0"],
y_origin=tokens["y0"],
|
python
|
{
"resource": ""
}
|
q276711
|
XdotAttrParser._proc_polygon
|
test
|
def _proc_polygon(self, tokens, filled):
""" Returns the components of a polygon. """
pts = [(p["x"], p["y"]) for p in tokens["points"]]
|
python
|
{
"resource": ""
}
|
q276712
|
XdotAttrParser.proc_polyline
|
test
|
def proc_polyline(self, tokens):
""" Returns the components of a polyline. """
pts = [(p["x"], p["y"]) for p in tokens["points"]]
|
python
|
{
"resource": ""
}
|
q276713
|
XdotAttrParser.proc_text
|
test
|
def proc_text(self, tokens):
""" Returns text components. """
component = Text(pen=self.pen,
text_x=tokens["x"],
text_y=tokens["y"],
|
python
|
{
"resource": ""
}
|
q276714
|
XdotAttrParser.proc_image
|
test
|
def proc_image(self, tokens):
""" Returns the components of an image. """
|
python
|
{
"resource": ""
}
|
q276715
|
render_grid_file
|
test
|
def render_grid_file(context, f):
"""Allow direct use of GridOut GridFS file wrappers as endpoint responses."""
f.seek(0) # Ensure we are reading from the beginning.
response = context.response # Frequently accessed, so made local. Useless optimization on Pypy.
if __debug__: # We add some useful diagnostic information in development, omitting from production due to sec.
response.headers['Grid-ID'] = str(f._id) # The GridFS file ID.
log.debug("Serving GridFS file.", extra=dict(
identifier = str(f._id),
filename = f.filename,
length = f.length,
mimetype = f.content_type
))
|
python
|
{
"resource": ""
}
|
q276716
|
DotFileIResourceAdapter.save
|
test
|
def save(self, obj):
""" Save to file.
"""
fd = None
try:
fd = open(self.dot_file.absolute_path, "wb")
obj.save_dot(fd)
finally:
if
|
python
|
{
"resource": ""
}
|
q276717
|
DotFileIResourceAdapter.load
|
test
|
def load(self):
""" Load the file.
"""
fd = None
try:
obj = parse_dot_file( self.dot_file.absolute_path )
finally:
|
python
|
{
"resource": ""
}
|
q276718
|
Ellipse.is_in
|
test
|
def is_in(self, point_x, point_y):
""" Test if the point is within this ellipse """
x = self.x_origin
|
python
|
{
"resource": ""
}
|
q276719
|
Ellipse._draw_bounds
|
test
|
def _draw_bounds(self, gc):
""" Draws the component bounds for testing purposes """
dx, dy = self.bounds
|
python
|
{
"resource": ""
}
|
q276720
|
NewDotGraphAction.perform
|
test
|
def perform(self, event):
""" Perform the action.
"""
wizard = NewDotGraphWizard(parent=self.window.control,
window=self.window, title="New Graph")
|
python
|
{
"resource": ""
}
|
q276721
|
SQLAlchemyConnection.start
|
test
|
def start(self, context):
"""Construct the SQLAlchemy engine and session factory."""
if __debug__:
log.info("Connecting SQLAlchemy database layer.", extra=dict(
uri = redact_uri(self.uri),
config = self.config,
alias = self.alias,
))
# Construct the engine.
engine = self.engine = create_engine(self.uri, **self.config)
# Construct the session factory.
|
python
|
{
"resource": ""
}
|
q276722
|
GraphViewModel._parse_dot_code_fired
|
test
|
def _parse_dot_code_fired(self):
""" Parses the dot_code string and replaces the existing model.
"""
parser = GodotDataParser()
|
python
|
{
"resource": ""
}
|
q276723
|
GraphViewModel.new_model
|
test
|
def new_model(self, info):
""" Handles the new Graph action. """
if info.initialized:
retval = confirm(parent = info.ui.control,
|
python
|
{
"resource": ""
}
|
q276724
|
GraphViewModel.open_file
|
test
|
def open_file(self, info):
""" Handles the open action. """
if not info.initialized: return # Escape.
# retval = self.edit_traits(parent=info.ui.control, view="file_view")
dlg = FileDialog( action = "open",
wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|"
"*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|"
"All Files (*.*)|*.*|")
if dlg.open() == OK:
parser = GodotDataParser()
|
python
|
{
"resource": ""
}
|
q276725
|
GraphViewModel.save
|
test
|
def save(self, info):
""" Handles saving the current model to the last file.
"""
save_file = self.save_file
if not isfile(save_file):
self.save_as(info)
else:
fd = None
try:
fd = open(save_file, "wb")
|
python
|
{
"resource": ""
}
|
q276726
|
GraphViewModel.save_as
|
test
|
def save_as(self, info):
""" Handles saving the current model to file.
"""
if not info.initialized:
return
# retval = self.edit_traits(parent=info.ui.control, view="file_view")
dlg = FileDialog( action = "save as",
wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|" \
"*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|" \
"All Files (*.*)|*.*|")
if dlg.open() == OK:
fd = None
try:
fd = open(dlg.path, "wb")
dot_code = str(self.model)
fd.write(dot_code)
self.save_file = dlg.path
|
python
|
{
"resource": ""
}
|
q276727
|
GraphViewModel.configure_graph
|
test
|
def configure_graph(self, info):
""" Handles display of the graph dot traits.
"""
if info.initialized:
|
python
|
{
"resource": ""
}
|
q276728
|
GraphViewModel.configure_nodes
|
test
|
def configure_nodes(self, info):
""" Handles display of the nodes editor.
"""
if info.initialized:
|
python
|
{
"resource": ""
}
|
q276729
|
GraphViewModel.configure_edges
|
test
|
def configure_edges(self, info):
""" Handles display of the edges editor.
"""
if info.initialized:
|
python
|
{
"resource": ""
}
|
q276730
|
GraphViewModel.about_godot
|
test
|
def about_godot(self, info):
""" Handles displaying a view about Godot.
"""
if info.initialized:
|
python
|
{
"resource": ""
}
|
q276731
|
GraphViewModel.add_node
|
test
|
def add_node(self, info):
""" Handles adding a Node to the graph.
"""
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
if graph is None:
return
IDs = [v.ID for v in graph.nodes]
|
python
|
{
"resource": ""
}
|
q276732
|
GraphViewModel.add_edge
|
test
|
def add_edge(self, info):
""" Handles adding an Edge to the graph.
"""
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
if graph is None:
return
n_nodes = len(graph.nodes)
IDs = [v.ID for v in graph.nodes]
if n_nodes == 0:
tail_node = Node(ID=make_unique_name("node", IDs))
head_name = make_unique_name("node", IDs + [tail_node.ID])
head_node = Node(ID=head_name)
elif n_nodes == 1:
tail_node = graph.nodes[0]
|
python
|
{
"resource": ""
}
|
q276733
|
GraphViewModel.add_subgraph
|
test
|
def add_subgraph(self, info):
""" Handles adding a Subgraph to the main graph.
"""
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
if graph is not None:
subgraph = Subgraph()#root=graph, parent=graph)
|
python
|
{
"resource": ""
}
|
q276734
|
GraphViewModel.add_cluster
|
test
|
def add_cluster(self, info):
""" Handles adding a Cluster to the main graph. """
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
if graph is not None:
cluster = Cluster()#root=graph, parent=graph)
|
python
|
{
"resource": ""
}
|
q276735
|
GraphViewModel._request_graph
|
test
|
def _request_graph(self, parent=None):
""" Displays a dialog for graph selection if more than one exists.
Returns None if the dialog is canceled.
"""
if (len(self.all_graphs) > 1) and (self.select_graph):
retval = self.edit_traits(parent = parent,
view = "all_graphs_view")
|
python
|
{
"resource": ""
}
|
q276736
|
GraphViewModel.godot_options
|
test
|
def godot_options(self, info):
""" Handles display of the options menu. """
if info.initialized:
self.edit_traits( parent = info.ui.control,
|
python
|
{
"resource": ""
}
|
q276737
|
GraphViewModel.configure_dot_code
|
test
|
def configure_dot_code(self, info):
""" Handles display of the dot code in a text editor.
"""
if not info.initialized:
|
python
|
{
"resource": ""
}
|
q276738
|
GraphViewModel.on_exit
|
test
|
def on_exit(self, info):
""" Handles the user attempting to exit Godot.
"""
if self.prompt_on_exit:# and (not is_ok):
retval = confirm(parent = info.ui.control,
message = "Exit Godot?",
title = "Confirm exit",
|
python
|
{
"resource": ""
}
|
q276739
|
move_to_origin
|
test
|
def move_to_origin(components):
""" Components are positioned relative to their container. Use this
method to position the bottom-left corner of the components at
the origin.
"""
for component in components:
if isinstance(component, Ellipse):
component.x_origin = component.e_width
component.y_origin = component.e_height
elif isinstance(component, (Polygon, BSpline)):
min_x = min( [t[0] for t in component.points] )
min_y = min( [t[1] for t in component.points] )
component.points = [
|
python
|
{
"resource": ""
}
|
q276740
|
Serializable.save_to_file_like
|
test
|
def save_to_file_like(self, flo, format=None, **kwargs):
""" Save the object to a given file like object in the given format.
"""
format = self.format if format is None else format
|
python
|
{
"resource": ""
}
|
q276741
|
Serializable.load_from_file_like
|
test
|
def load_from_file_like(cls, flo, format=None):
""" Load the object to a given file like object with the given
protocol.
"""
|
python
|
{
"resource": ""
}
|
q276742
|
Serializable.save_to_file
|
test
|
def save_to_file(self, filename, format=None, **kwargs):
""" Save the object to file given by filename.
"""
if format is None:
|
python
|
{
"resource": ""
}
|
q276743
|
Serializable.load_from_file
|
test
|
def load_from_file(cls, filename, format=None):
""" Return an instance of the class that is saved in the file with the
given filename in the specified format.
"""
if format is None:
# try to derive protocol from file extension
|
python
|
{
"resource": ""
}
|
q276744
|
Alias
|
test
|
def Alias(name, **metadata):
""" Syntactically concise alias trait but creates a pair of lambda
functions for every alias you declare.
class MyClass(HasTraits):
|
python
|
{
"resource": ""
}
|
q276745
|
parse
|
test
|
def parse(filename, encoding=None):
"""
!DEMO!
Simple file parsing generator
Args:
filename: absolute or relative path to file on disk
encoding: encoding string that is passed to open function
|
python
|
{
"resource": ""
}
|
q276746
|
MarkovChain.startwords
|
test
|
def startwords(self):
"""
!DEMO!
Cached list of keys that can be used to generate sentence.
"""
if self._start_words is not None:
return self._start_words
else:
self._start_words = list(filter(
|
python
|
{
"resource": ""
}
|
q276747
|
MarkovGenerator.add_chain
|
test
|
def add_chain(self, name, order):
"""
Add chain to current shelve file
Args:
name: chain name
order: markov chain order
"""
if name not in self.chains:
|
python
|
{
"resource": ""
}
|
q276748
|
MarkovGenerator.remove_chain
|
test
|
def remove_chain(self, name):
"""
Remove chain from current shelve file
Args:
name: chain name
"""
if name in self.chains:
|
python
|
{
"resource": ""
}
|
q276749
|
MarkovGenerator.build_chain
|
test
|
def build_chain(self, source, chain):
"""
Build markov chain from source on top of existin chain
Args:
source: iterable which will be used to build chain
chain: MarkovChain in currently loaded shelve file that
will be extended by source
"""
for group in WalkByGroup(source, chain.order+1):
pre = group[:-1]
res = group[-1]
if pre not in chain.content:
|
python
|
{
"resource": ""
}
|
q276750
|
MarkovGenerator.generate_sentence
|
test
|
def generate_sentence(self, chain):
"""
!DEMO!
Demo function that shows how to generate a simple sentence starting with
uppercase letter without lenght limit.
Args:
chain: MarkovChain that will be used to generate sentence
"""
def weighted_choice(choices):
total_weight = sum(weight for val, weight in choices)
|
python
|
{
"resource": ""
}
|
q276751
|
BaseGraph.create
|
test
|
def create(self, prog=None, format=None):
""" Creates and returns a representation of the graph using the
Graphviz layout program given by 'prog', according to the given
format.
Writes the graph to a temporary dot file and processes it with
the program given by 'prog' (which defaults to 'dot'), reading
the output and returning it as a string if the operation is
successful. On failure None is returned.
"""
prog = self.program if prog is None else prog
format = self.format if format is None else format
# Make a temporary file ...
tmp_fd, tmp_name = tempfile.mkstemp()
os.close( tmp_fd )
# ... and save the graph to it.
dot_fd = file( tmp_name, "w+b" )
self.save_dot( dot_fd )
dot_fd.close()
# Get the temporary file directory name.
tmp_dir = os.path.dirname( tmp_name )
# TODO: Shape image files (See PyDot). Important.
# Process the file using the layout
|
python
|
{
"resource": ""
}
|
q276752
|
BaseGraph.add_node
|
test
|
def add_node(self, node_or_ID, **kwds):
""" Adds a node to the graph.
"""
if not isinstance(node_or_ID, Node):
nodeID = str( node_or_ID )
if nodeID in self.nodes:
node = self.nodes[ self.nodes.index(nodeID) ]
else:
if self.default_node is not None:
node = self.default_node.clone_traits(copy="deep")
node.ID = nodeID
else:
|
python
|
{
"resource": ""
}
|
q276753
|
BaseGraph.delete_node
|
test
|
def delete_node(self, node_or_ID):
""" Removes a node from the graph.
"""
if isinstance(node_or_ID, Node):
# name = node_or_ID.ID
node = node_or_ID
else:
# name = node_or_ID
node = self.get_node(node_or_ID)
if node is None:
raise ValueError("Node %s does not exists" % node_or_ID)
# try:
# del self.nodes[name]
# except:
|
python
|
{
"resource": ""
}
|
q276754
|
BaseGraph.get_node
|
test
|
def get_node(self, ID):
""" Returns the node with the given ID or None.
|
python
|
{
"resource": ""
}
|
q276755
|
BaseGraph.delete_edge
|
test
|
def delete_edge(self, tail_node_or_ID, head_node_or_ID):
""" Removes an edge from the graph. Returns the deleted edge or None.
"""
if isinstance(tail_node_or_ID, Node):
tail_node = tail_node_or_ID
else:
tail_node = self.get_node(tail_node_or_ID)
if isinstance(head_node_or_ID, Node):
head_node = head_node_or_ID
else:
head_node = self.get_node(head_node_or_ID)
if (tail_node is None) or (head_node is None):
|
python
|
{
"resource": ""
}
|
q276756
|
BaseGraph.add_edge
|
test
|
def add_edge(self, tail_node_or_ID, head_node_or_ID, **kwds):
""" Adds an edge to the graph.
"""
tail_node = self.add_node(tail_node_or_ID)
head_node = self.add_node(head_node_or_ID)
# Only top level graphs are directed and/or strict.
if "directed" in self.trait_names():
directed = self.directed
else:
directed = False
if self.default_edge is not None:
edge = self.default_edge.clone_traits(copy="deep")
edge.tail_node = tail_node
edge.head_node = head_node
edge.conn = "->" if directed else "--"
|
python
|
{
"resource": ""
}
|
q276757
|
BaseGraph.add_subgraph
|
test
|
def add_subgraph(self, subgraph_or_ID):
""" Adds a subgraph to the graph.
"""
if not isinstance(subgraph_or_ID, (godot.subgraph.Subgraph,
godot.cluster.Cluster)):
subgraphID = str( subgraph_or_ID )
if subgraph_or_ID.startswith("cluster"):
subgraph = godot.cluster.Cluster(ID=subgraphID)
else:
subgraph = godot.subgraph.Subgraph(ID=subgraphID)
else:
subgraph = subgraph_or_ID
subgraph.default_node = self.default_node
|
python
|
{
"resource": ""
}
|
q276758
|
BaseGraph._program_changed
|
test
|
def _program_changed(self, new):
""" Handles the Graphviz layout program selection changing.
"""
progs = self.progs
if not progs.has_key(prog):
logger.warning( 'GraphViz\'s executable "%s" not found' % prog )
if not os.path.exists( progs[prog] ) or not \
|
python
|
{
"resource": ""
}
|
q276759
|
BaseGraph._set_node_lists
|
test
|
def _set_node_lists(self, new):
""" Maintains each edge's list of available nodes.
"""
|
python
|
{
"resource": ""
}
|
q276760
|
parse_dot_file
|
test
|
def parse_dot_file(filename):
""" Parses a DOT file and returns a Godot graph.
"""
parser = GodotDataParser()
graph
|
python
|
{
"resource": ""
}
|
q276761
|
GodotDataParser.parse_dot_file
|
test
|
def parse_dot_file(self, file_or_filename):
""" Returns a graph given a file or a filename.
"""
if isinstance(file_or_filename, basestring):
file = None
try:
file = open(file_or_filename, "rb")
data = file.read()
except:
print "Could not open %s." % file_or_filename
return
|
python
|
{
"resource": ""
}
|
q276762
|
GodotDataParser.build_top_graph
|
test
|
def build_top_graph(self,tokens):
""" Build a Godot graph instance from parsed data.
"""
# Get basic graph information.
strict = tokens[0] == 'strict'
graphtype = tokens[1]
directed = graphtype == 'digraph'
graphname = tokens[2]
|
python
|
{
"resource": ""
}
|
q276763
|
GodotDataParser.build_graph
|
test
|
def build_graph(self, graph, tokens):
""" Builds a Godot graph.
"""
subgraph = None
for element in tokens:
cmd = element[0]
if cmd == ADD_NODE:
cmd, nodename, opts = element
graph.add_node(nodename, **opts)
elif cmd == ADD_EDGE:
cmd, src, dest, opts = element
srcport = destport = ""
if isinstance(src,tuple):
srcport = src[1]
src = src[0]
if isinstance(dest,tuple):
destport = dest[1]
dest = dest[0]
graph.add_edge(src, dest, tailport=srcport, headport=destport,
**opts)
elif cmd in [ADD_GRAPH_TO_NODE_EDGE,
ADD_GRAPH_TO_GRAPH_EDGE,
ADD_NODE_TO_GRAPH_EDGE]:
cmd, src, dest, opts = element
srcport = destport = ""
if isinstance(src,tuple):
srcport = src[1]
if isinstance(dest,tuple):
destport = dest[1]
if not (cmd == ADD_NODE_TO_GRAPH_EDGE):
if cmd == ADD_GRAPH_TO_NODE_EDGE:
src = subgraph
|
python
|
{
"resource": ""
}
|
q276764
|
get_time_units_and_multiplier
|
test
|
def get_time_units_and_multiplier(seconds):
"""
Given a duration in seconds, determines the best units and multiplier to
use to display the time. Return value is a 2-tuple of units and multiplier.
"""
|
python
|
{
"resource": ""
}
|
q276765
|
format_duration
|
test
|
def format_duration(seconds):
"""Formats a number of seconds using the best units."""
|
python
|
{
"resource": ""
}
|
q276766
|
TreeEditor.on_path
|
test
|
def on_path(self, new):
""" Handle the file path changing.
"""
self.name
|
python
|
{
"resource": ""
}
|
q276767
|
TreeEditor.create_ui
|
test
|
def create_ui(self, parent):
""" Creates the toolkit-specific control that represents the
editor. 'parent' is the toolkit-specific control that is
the editor's parent.
"""
self.graph = self.editor_input.load()
view = View(Item(name="graph", editor=graph_tree_editor,
|
python
|
{
"resource": ""
}
|
q276768
|
nsplit
|
test
|
def nsplit(seq, n=2):
""" Split a sequence into pieces of length n
If the length of the sequence isn't a multiple of n, the rest is discarded.
Note that nsplit will split strings into individual characters.
Examples:
>>> nsplit("aabbcc")
[("a", "a"), ("b", "b"), ("c", "c")]
>>> nsplit("aabbcc",n=3)
[("a", "a", "b"), ("b",
|
python
|
{
"resource": ""
}
|
q276769
|
windows
|
test
|
def windows(iterable, length=2, overlap=0, padding=True):
""" Code snippet from Python Cookbook, 2nd Edition by David Ascher,
Alex Martelli and Anna Ravenscroft; O'Reilly 2005
Problem: You have an iterable s and need to make another iterable whose
items are sublists (i.e., sliding windows), each of the same given length,
over s' items, with successive windows overlapping by a specified amount.
"""
it = iter(iterable)
|
python
|
{
"resource": ""
}
|
q276770
|
main
|
test
|
def main():
""" Runs Godot.
"""
application = GodotApplication( id="godot",
plugins=[CorePlugin(),
PuddlePlugin(),
WorkbenchPlugin(),
|
python
|
{
"resource": ""
}
|
q276771
|
BaseGraphTreeNode.get_children
|
test
|
def get_children ( self, object ):
""" Gets the object's children.
"""
children = []
children.extend( object.subgraphs )
children.extend( object.clusters )
|
python
|
{
"resource": ""
}
|
q276772
|
BaseGraphTreeNode.append_child
|
test
|
def append_child ( self, object, child ):
""" Appends a child to the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.append( child )
elif isinstance( child, Cluster ):
object.clusters.append( child )
|
python
|
{
"resource": ""
}
|
q276773
|
BaseGraphTreeNode.insert_child
|
test
|
def insert_child ( self, object, index, child ):
""" Inserts a child into the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.insert( index, child )
elif isinstance( child, Cluster ):
object.clusters.insert( index, child )
|
python
|
{
"resource": ""
}
|
q276774
|
BaseGraphTreeNode.delete_child
|
test
|
def delete_child ( self, object, index ):
""" Deletes a child at a specified index from the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.pop(index)
elif isinstance( child, Cluster ):
object.clusters.pop( index )
|
python
|
{
"resource": ""
}
|
q276775
|
BaseGraphTreeNode.when_children_replaced
|
test
|
def when_children_replaced ( self, object, listener, remove ):
""" Sets up or removes a listener for children being replaced on a
specified object.
"""
object.on_trait_change( listener, "subgraphs", remove = remove,
dispatch = "fast_ui" )
object.on_trait_change( listener, "clusters", remove = remove,
dispatch = "fast_ui" )
|
python
|
{
"resource": ""
}
|
q276776
|
BaseGraphTreeNode.when_children_changed
|
test
|
def when_children_changed ( self, object, listener, remove ):
""" Sets up or removes a listener for children being changed on a
specified object.
"""
object.on_trait_change( listener, "subgraphs_items",
remove = remove, dispatch = "fast_ui" )
|
python
|
{
"resource": ""
}
|
q276777
|
GraphNode.get_label
|
test
|
def get_label ( self, object ):
""" Gets the label to display for a specified object.
"""
label = self.label
if label[:1] == '=':
return label[1:]
label = xgetattr( object, label, '' )
|
python
|
{
"resource": ""
}
|
q276778
|
GraphNode.set_label
|
test
|
def set_label ( self, object, label ):
""" Sets the label for a specified object.
"""
label_name
|
python
|
{
"resource": ""
}
|
q276779
|
GraphNode.when_label_changed
|
test
|
def when_label_changed ( self, object, listener, remove ):
""" Sets up or removes a listener for the label being changed on a
specified object.
"""
label = self.label
if label[:1] !=
|
python
|
{
"resource": ""
}
|
q276780
|
SimpleGraphEditor.init
|
test
|
def init ( self, parent ):
""" Finishes initialising the editor by creating the underlying toolkit
widget.
"""
self._graph = graph = Graph()
|
python
|
{
"resource": ""
}
|
q276781
|
SimpleGraphEditor.update_editor
|
test
|
def update_editor ( self ):
""" Updates the editor when the object trait changes externally to the
editor.
"""
object = self.value
# Graph the new object...
canvas = self.factory.canvas
if canvas is not None:
|
python
|
{
"resource": ""
}
|
q276782
|
SimpleGraphEditor._add_listeners
|
test
|
def _add_listeners ( self ):
""" Adds the event listeners for a specified object.
"""
object = self.value
canvas = self.factory.canvas
if canvas is not None:
for name in canvas.node_children:
object.on_trait_change(self._nodes_replaced, name)
object.on_trait_change(self._nodes_changed, name + "_items")
for name
|
python
|
{
"resource": ""
}
|
q276783
|
SimpleGraphEditor._nodes_replaced
|
test
|
def _nodes_replaced(self, object, name, old, new):
""" Handles a list of nodes being set.
"""
|
python
|
{
"resource": ""
}
|
q276784
|
SimpleGraphEditor._nodes_changed
|
test
|
def _nodes_changed(self, object, name, undefined, event):
""" Handles addition and removal of nodes.
"""
|
python
|
{
"resource": ""
}
|
q276785
|
SimpleGraphEditor._add_nodes
|
test
|
def _add_nodes(self, features):
""" Adds a node to the graph for each item in 'features' using
the GraphNodes from the editor factory.
"""
graph = self._graph
if graph is not None:
|
python
|
{
"resource": ""
}
|
q276786
|
SimpleGraphEditor._edges_replaced
|
test
|
def _edges_replaced(self, object, name, old, new):
""" Handles a list of edges being set.
"""
|
python
|
{
"resource": ""
}
|
q276787
|
SimpleGraphEditor._edges_changed
|
test
|
def _edges_changed(self, object, name, undefined, event):
""" Handles addition and removal of edges.
"""
|
python
|
{
"resource": ""
}
|
q276788
|
SimpleGraphEditor._add_edges
|
test
|
def _add_edges(self, features):
""" Adds an edge to the graph for each item in 'features' using
the GraphEdges from the editor factory.
"""
graph = self._graph
if graph is not None:
for feature in features:
for graph_edge in self.factory.edges:
if feature.__class__ in graph_edge.edge_for:
tail_feature = getattr(feature, graph_edge.tail_name)
|
python
|
{
"resource": ""
}
|
q276789
|
Edge._parse_xdot_directive
|
test
|
def _parse_xdot_directive(self, name, new):
""" Handles parsing Xdot drawing directives.
"""
parser = XdotAttrParser()
components = parser.parse_xdot_data(new)
# The absolute coordinate of the drawing container wrt graph origin.
x1 = min( [c.x for c in components] )
y1 = min( [c.y for c in components] )
print "X1/Y1:", name, x1, y1
# Components are positioned relative to their container. This
# function positions the bottom-left corner of the components at
# their origin rather than relative to the graph.
# move_to_origin( components )
for c in components:
if isinstance(c, Ellipse):
component.x_origin -= x1
component.y_origin -= y1
# c.position = [ c.x - x1, c.y - y1 ]
elif isinstance(c, (Polygon, BSpline)):
print "Points:", c.points
|
python
|
{
"resource": ""
}
|
q276790
|
Edge._on_drawing
|
test
|
def _on_drawing(self, object, name, old, new):
""" Handles the containers of drawing components being set.
"""
attrs = [ "drawing", "arrowhead_drawing" ]
others = [getattr(self, a) for a in attrs \
if (a != name) and (getattr(self, a) is not None)]
x, y = self.component.position
print "POS:", x, y, self.component.position
abs_x = [d.x + x for d in others]
abs_y = [d.y + y for d in others]
print "ABS:", abs_x, abs_y
# Assume that he new drawing is positioned relative to graph origin.
x1 = min( abs_x + [new.x] )
y1 = min( abs_y + [new.y] )
print "DRAW:", new.position
new.position = [ new.x - x1, new.y - y1 ]
print "DRAW:", new.position
# for i, b in enumerate( others ):
# self.drawing.position = [100, 100]
# self.drawing.request_redraw()
# print "OTHER:", b.position, abs_x[i] - x1
# b.position = [ abs_x[i] - x1, abs_y[i] - y1 ]
# b.x = 50
# b.y = 50
#
|
python
|
{
"resource": ""
}
|
q276791
|
node_factory
|
test
|
def node_factory(**row_factory_kw):
""" Give new nodes a unique ID. """
if "__table_editor__" in row_factory_kw:
graph = row_factory_kw["__table_editor__"].object
ID = make_unique_name("n", [node.ID for node in graph.nodes])
|
python
|
{
"resource": ""
}
|
q276792
|
edge_factory
|
test
|
def edge_factory(**row_factory_kw):
""" Give new edges a unique ID. """
if "__table_editor__" in row_factory_kw:
table_editor = row_factory_kw["__table_editor__"]
graph = table_editor.object
ID = make_unique_name("node", [node.ID for node in graph.nodes])
n_nodes = len(graph.nodes)
IDs = [v.ID for v in graph.nodes]
if n_nodes == 0:
tail_node = godot.Node(ID=make_unique_name("n", IDs))
head_node = godot.Node(ID=make_unique_name("n", IDs))
elif n_nodes == 1:
|
python
|
{
"resource": ""
}
|
q276793
|
MongoEngineConnection.prepare
|
test
|
def prepare(self, context):
"""Attach this connection's default database to the context using our alias."""
|
python
|
{
"resource": ""
}
|
q276794
|
Node.parse_xdot_drawing_directive
|
test
|
def parse_xdot_drawing_directive(self, new):
""" Parses the drawing directive, updating the node components.
"""
components = XdotAttrParser().parse_xdot_data(new)
max_x = max( [c.bounds[0] for c in components] + [1] )
max_y = max( [c.bounds[1] for c in components] + [1] )
|
python
|
{
"resource": ""
}
|
q276795
|
Node.parse_xdot_label_directive
|
test
|
def parse_xdot_label_directive(self, new):
""" Parses the label drawing directive, updating the label
components.
"""
components = XdotAttrParser().parse_xdot_data(new)
pos_x = min( [c.x for c in components] )
pos_y = min( [c.y for c in components] )
move_to_origin(components)
|
python
|
{
"resource": ""
}
|
q276796
|
Node._drawing_changed
|
test
|
def _drawing_changed(self, old, new):
""" Handles the container of drawing components changing.
"""
if old is not None:
self.component.remove( old )
if new is not None:
# new.bgcolor="pink"
self.component.add( new )
|
python
|
{
"resource": ""
}
|
q276797
|
Node._on_position_change
|
test
|
def _on_position_change(self, new):
""" Handles the poition of the component changing.
"""
|
python
|
{
"resource": ""
}
|
q276798
|
Node._pos_changed
|
test
|
def _pos_changed(self, new):
""" Handles the Graphviz position attribute changing.
"""
w, h = self.component.bounds
|
python
|
{
"resource": ""
}
|
q276799
|
ContextMenuTool.normal_right_down
|
test
|
def normal_right_down(self, event):
""" Handles the right mouse button being clicked when the tool is in
the 'normal' state.
If the event occurred on this tool's component (or any contained
component of that component), the method opens a context menu with
menu items from any tool of the parent component that implements
MenuItemTool interface i.e. has a get_item() method.
"""
x = event.x
y = event.y
# First determine what component or components we are going to hittest
# on. If our component is a container, then we add
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.