code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# ignore this and the caller frame
ignore.append(inspect.currentframe()) #PYCHOK change ignore
self.o1 = self._get_objects(ignore)
diff = muppy.get_diff(self.o0, self.o1)
self.o0 = self.o1
# manual cleanup, see comment above
del ignore[:] #PYCHOK change i... | def get_diff(self, ignore=[]) | Get the diff to the last time the state of objects was measured.
keyword arguments
ignore -- list of objects to ignore | 8.846794 | 8.758439 | 1.010088 |
# ignore this and the caller frame
ignore.append(inspect.currentframe()) #PYCHOK change ignore
diff = self.get_diff(ignore)
print("Added objects:")
summary.print_(summary.summarize(diff['+']))
print("Removed objects:")
summary.print_(summary.summarize(dif... | def print_diff(self, ignore=[]) | Print the diff to the last time the state of objects was measured.
keyword arguments
ignore -- list of objects to ignore | 9.362415 | 9.569201 | 0.978391 |
L = len(seq1)
if L != len(seq2):
raise ValueError("expected two strings of the same length")
if L == 0:
return 0.0 if normalized else 0 # equal
dist = sum(c1 != c2 for c1, c2 in zip(seq1, seq2))
if normalized:
return dist / float(L)
return dist | def hamming(seq1, seq2, normalized=False) | Compute the Hamming distance between the two sequences `seq1` and `seq2`.
The Hamming distance is the number of differing items in two ordered
sequences of the same length. If the sequences submitted do not have the
same length, an error will be raised.
If `normalized` evaluates to `False`, the return value will ... | 2.519575 | 2.572893 | 0.979277 |
set1, set2 = set(seq1), set(seq2)
return 1 - len(set1 & set2) / float(len(set1 | set2)) | def jaccard(seq1, seq2) | Compute the Jaccard distance between the two sequences `seq1` and `seq2`.
They should contain hashable items.
The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. | 2.21085 | 2.415358 | 0.91533 |
set1, set2 = set(seq1), set(seq2)
return 1 - (2 * len(set1 & set2) / float(len(set1) + len(set2))) | def sorensen(seq1, seq2) | Compute the Sorensen distance between the two sequences `seq1` and `seq2`.
They should contain hashable items.
The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. | 2.335656 | 2.475783 | 0.943401 |
L1, L2 = len(seq1), len(seq2)
ms = []
mlen = last = 0
if L1 < L2:
seq1, seq2 = seq2, seq1
L1, L2 = L2, L1
column = array('L', range(L2))
for i in range(L1):
for j in range(L2):
old = column[j]
if seq1[i] == seq2[j]:
if i == 0 or j == 0:
column[j] = 1
else:
column[j] = last + 1
... | def lcsubstrings(seq1, seq2, positions=False) | Find the longest common substring(s) in the sequences `seq1` and `seq2`.
If positions evaluates to `True` only their positions will be returned,
together with their length, in a tuple:
(length, [(start pos in seq1, start pos in seq2)..])
Otherwise, the substrings themselves will be returned, in a set.
Exa... | 2.119659 | 2.101343 | 1.008716 |
if self.color_mapping is None:
self.color_mapping = {}
color = self.color_mapping.get(node.key)
if color is None:
depth = len(self.color_mapping)
red = (depth * 10) % 255
green = 200 - ((depth * 5) % 200)
blue = (depth * 25) % ... | def background_color(self, node, depth) | Create a (unique-ish) background color for each node | 2.375879 | 2.303797 | 1.031288 |
self.percentageView = percent
self.total = total | def SetPercentage(self, percent, total) | Set whether to display percentage values (and total for doing so) | 17.335672 | 10.139933 | 1.709644 |
'''
Run a functions profiler and show it in a GUI visualisation using RunSnakeRun
Note: can also use calibration for more exact results
'''
functionprofiler.runprofile(funcname+'(\''+argv+'\')', profilepath, *args, **kwargs)
print 'Showing profile (windows should open in the background)'; sys.st... | def runprofilerandshow(funcname, profilepath, argv='', *args, **kwargs) | Run a functions profiler and show it in a GUI visualisation using RunSnakeRun
Note: can also use calibration for more exact results | 15.978633 | 5.175519 | 3.087349 |
''' Makes a call graph
Note: be sure to install GraphViz prior to printing the dot graph!
'''
import pycallgraph
@functools.wraps(func)
def wrapper(*args, **kwargs):
pycallgraph.start_trace()
func(*args, **kwargs)
pycallgraph.save_dot('callgraph.log')
pycallgraph.... | def callgraph(func) | Makes a call graph
Note: be sure to install GraphViz prior to printing the dot graph! | 4.387445 | 3.011791 | 1.456756 |
def _long2bytes(n, blocksize=0):
# After much testing, this algorithm was deemed to be the fastest.
s = ''
pack = struct.pack
while n > 0:
### CHANGED FROM '>I' TO '<I'. (DCG)
s = pack('<I', n & 0xffffffffL) + s
### --------------------------
n = n >> 32
... | Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front
of the byte string with binary zeros so that the length is a multiple
of blocksize. | null | null | null | |
def XX(func, a, b, c, d, x, s, ac):
res = 0L
res = res + a + func(b, c, d)
res = res + x
res = res + ac
res = res & 0xffffffffL
res = _rotateLeft(res, s)
res = res & 0xffffffffL
res = res + b
return res & 0xffffffffL | Wrapper for call distribution to functions F, G, H and I.
This replaces functions FF, GG, HH and II from "Appl. Crypto.
Rotation is separate from addition to prevent recomputation
(now summed-up in one function). | null | null | null | |
def init(self):
"Initialize the message-digest and set all fields to zero."
self.length = 0L
self.input = []
# Load magic initialization constants.
self.A = 0x67452301L
self.B = 0xefcdab89L
self.C = 0x98badcfeL
self.D = 0x10325476L | Initialize the message-digest and set all fields to zero. | null | null | null | |
def update(self, inBuf):
leninBuf = long(len(inBuf))
# Compute number of bytes mod 64.
index = (self.count[0] >> 3) & 0x3FL
# Update number of bits.
self.count[0] = self.count[0] + (leninBuf << 3)
if self.count[0] < (leninBuf << 3):
self.... | Add to the current message.
Update the md5 object with the string arg. Repeated calls
are equivalent to a single call with the concatenation of all
the arguments, i.e. m.update(a); m.update(b) is equivalent
to m.update(a+b). | null | null | null | |
def digest(self):
A = self.A
B = self.B
C = self.C
D = self.D
input = [] + self.input
count = [] + self.count
index = (self.count[0] >> 3) & 0x3fL
if index < 56:
padLen = 56 - index
else:
padLen = ... | Terminate the message-digest computation and return digest.
Return the digest of the strings passed to the update()
method so far. This is a 16-byte string which may contain
non-ASCII characters, including null bytes. | null | null | null | |
def hexdigest(self):
d = map(None, self.digest())
d = map(ord, d)
d = map(lambda x:"%02x" % x, d)
d = string.join(d, '')
return d | Terminate and return digest in HEX form.
Like digest() except the digest is returned as a string of
length 32, containing only hexadecimal digits. This may be
used to exchange the value safely in email or other non-
binary environments. | null | null | null | |
# this is the *weighted* size/contribution of the node
try:
return node['contribution']
except KeyError, err:
contribution = int(node.get('totsize',0)/float( len(node.get('parents',())) or 1))
node['contribution'] = contribution
return co... | def value( self, node, parent=None ) | Return value used to compare size of this node | 10.741731 | 10.23534 | 1.049475 |
result = []
if node.get('type'):
result.append( node['type'] )
if node.get('name' ):
result.append( node['name'] )
elif node.get('value') is not None:
result.append( unicode(node['value'])[:32])
if 'module' in node and not node['module... | def label( self, node ) | Return textual description of this node | 3.256465 | 3.146892 | 1.03482 |
if 'index' in node:
index = node['index']()
parents = list(meliaeloader.children( node, index, 'parents' ))
return parents
return [] | def parents( self, node ) | Retrieve/calculate the set of parents for the given node | 16.010464 | 16.121777 | 0.993095 |
parents = self.parents(node)
selected_parent = None
if node['type'] == 'type':
module = ".".join( node['name'].split( '.' )[:-1] )
if module:
for mod in parents:
if mod['type'] == 'module' and mod['name'] == module:
... | def best_parent( self, node, tree_type=None ) | Choose the best parent for a given node | 3.727097 | 3.625214 | 1.028104 |
'''
Decorator for client code's main function.
Serializes argparse data to JSON for use with the Gooey front end
'''
params = locals()
def build(payload):
def run_gooey(self, args=None, namespace=None):
source_path = sys.argv[0]
build_spec = config_generator.create_from_parser(self, source... | def Gooey(f=None,
advanced=True,
language='english',
show_config=True,
program_name=None,
program_description=None,
default_size=(610, 530),
required_cols=2,
optional_cols=2,
dump_build_config=False,
monospace_display=Fa... | Decorator for client code's main function.
Serializes argparse data to JSON for use with the Gooey front end | 3.89424 | 3.248074 | 1.198938 |
'''
:param widget_list: list of dicts containing widget info (name, type, etc..)
:return: ComponentList
Converts the Json widget information into concrete wx Widget types
'''
required_args, optional_args = partition(widget_list, is_required)
checkbox_args, general_args = partition(map(build_widget, opti... | def build_components(widget_list) | :param widget_list: list of dicts containing widget info (name, type, etc..)
:return: ComponentList
Converts the Json widget information into concrete wx Widget types | 6.18144 | 2.889279 | 2.13944 |
ref2key = lambda ref: ref.name.split(':')[0]
base.size += other.size
base.flat += other.flat
if level > 0:
base.name = ref2key(base)
# Add refs from other to base. Any new refs are appended.
base.refs = list(base.refs) # we may need to append items
refs = {}
for ref in base.... | def _merge_asized(base, other, level=0) | Merge **Asized** instances `base` and `other` into `base`. | 4.282745 | 4.113398 | 1.04117 |
size = None
for (timestamp, tsize) in obj.snapshots:
if timestamp == tref:
size = tsize
if size:
_merge_asized(merged, size) | def _merge_objects(tref, merged, obj) | Merge the snapshot size information of multiple tracked objects. The
tracked object `obj` is scanned for size information at time `tref`.
The sizes are merged into **Asized** instance `merged`. | 9.156248 | 5.080401 | 1.802269 |
lines = []
for fname, lineno, func, src, _ in trace:
if src:
for line in src:
lines.append(' '+line.strip()+'\n')
lines.append(' %s:%4d in %s\n' % (fname, lineno, func))
return ''.join(lines) | def _format_trace(trace) | Convert the (stripped) stack-trace to a nice readable format. The stack
trace `trace` is a list of frame records as returned by
**inspect.stack** but without the frame objects.
Returns a string. | 3.545905 | 3.677179 | 0.9643 |
if isinstance(fdump, type('')):
fdump = open(fdump, 'rb')
self.index = pickle.load(fdump)
self.snapshots = pickle.load(fdump)
self.sorted = [] | def load_stats(self, fdump) | Load the data from a dump file.
The argument `fdump` can be either a filename or an open file object
that requires read access. | 3.933928 | 3.559399 | 1.105222 |
if self.tracker:
self.tracker.stop_periodic_snapshots()
if isinstance(fdump, type('')):
fdump = open(fdump, 'wb')
pickle.dump(self.index, fdump, protocol=pickle.HIGHEST_PROTOCOL)
pickle.dump(self.snapshots, fdump, protocol=pickle.HIGHEST_PROTOCOL)
... | def dump_stats(self, fdump, close=True) | Dump the logged data to a file.
The argument `file` can be either a filename or an open file object
that requires write access. `close` controls if the file is closed
before leaving this method (the default behaviour). | 2.928074 | 2.929214 | 0.999611 |
if not self.sorted:
# Identify the snapshot that tracked the largest amount of memory.
tmax = None
maxsize = 0
for snapshot in self.snapshots:
if snapshot.tracked_total > maxsize:
tmax = snapshot.timestamp
f... | def _init_sort(self) | Prepare the data to be sorted.
If not yet sorted, import all tracked objects from the tracked index.
Extend the tracking information by implicit information to make
sorting easier (DSU pattern). | 5.063382 | 4.456531 | 1.136171 |
criteria = ('classname', 'tsize', 'birth', 'death',
'name', 'repr', 'size')
if not set(criteria).issuperset(set(args)):
raise ValueError("Invalid sort criteria")
if not args:
args = criteria
def args_to_tuple(obj):
keys... | def sort_stats(self, *args) | Sort the tracked objects according to the supplied criteria. The
argument is a string identifying the basis of a sort (example: 'size'
or 'classname'). When more than one key is provided, then additional
keys are used as secondary criteria when there is equality in all keys
selected befo... | 4.622328 | 3.413953 | 1.353952 |
if hasattr(snapshot, 'classes'):
return
snapshot.classes = {}
for classname in list(self.index.keys()):
total = 0
active = 0
merged = Asized(0, 0)
for tobj in self.index[classname]:
_merge_objects(snapshot.tim... | def annotate_snapshot(self, snapshot) | Store additional statistical data in snapshot. | 3.773871 | 3.692313 | 1.022089 |
lrefs = list(refs)
lrefs.sort(key=lambda x: x.size)
lrefs.reverse()
for ref in lrefs:
if ref.size > minsize and (ref.size*100.0/total) > minpct:
self.stream.write('%-50s %-14s %3d%% [%d]\n' % (
trunc(prefix+str(ref.name), 50),
... | def _print_refs(self, refs, total, prefix=' ',
level=1, minsize=0, minpct=0.1) | Print individual referents recursively. | 2.794064 | 2.836583 | 0.98501 |
if tobj.death:
self.stream.write('%-32s ( free ) %-35s\n' % (
trunc(tobj.name, 32, left=1), trunc(tobj.repr, 35)))
else:
self.stream.write('%-32s 0x%08x %-35s\n' % (
trunc(tobj.name, 32, left=1),
tobj.id,
... | def print_object(self, tobj) | Print the gathered information of object `tobj` in human-readable format. | 3.710185 | 3.696183 | 1.003788 |
if self.tracker:
self.tracker.stop_periodic_snapshots()
if not self.sorted:
self.sort_stats()
_sorted = self.sorted
if clsname:
_sorted = [to for to in _sorted if clsname in to.classname]
if limit < 1.0:
limit = max(1, ... | def print_stats(self, clsname=None, limit=1.0) | Write tracked objects to stdout. The output can be filtered and
pruned. Only objects are printed whose classname contain the substring
supplied by the `clsname` argument. The output can be pruned by
passing a `limit` value.
:param clsname: Only print objects whose classname contain t... | 4.494156 | 4.550084 | 0.987708 |
# Emit class summaries for each snapshot
classlist = self.tracked_classes
fobj = self.stream
fobj.write('---- SUMMARY '+'-'*66+'\n')
for snapshot in self.snapshots:
self.annotate_snapshot(snapshot)
fobj.write('%-35s %11s %12s %12s %5s\n' % (
... | def print_summary(self) | Print per-class summary for each snapshot. | 4.865249 | 4.568642 | 1.064922 |
lrefs = list(refs)
lrefs.sort(key=lambda x: x.size)
lrefs.reverse()
if level == 1:
fobj.write('<table>\n')
for ref in lrefs:
if ref.size > minsize and (ref.size*100.0/total) > minpct:
data = dict(level=level,
... | def _print_refs(self, fobj, refs, total, level=1, minsize=0, minpct=0.1) | Print individual referents recursively. | 2.538782 | 2.531168 | 1.003008 |
fobj = open(fname, "w")
fobj.write(self.header % (classname, self.style))
fobj.write("<h1>%s</h1>\n" % (classname))
sizes = [tobj.get_max_size() for tobj in self.index[classname]]
total = 0
for s in sizes:
total += s
data = {'cnt': len(self.... | def print_class_details(self, fname, classname) | Print detailed statistics and instances for the class `classname`. All
data will be written to the file `fname`. | 2.753763 | 2.760032 | 0.997729 |
if basepath is None:
basepath = self.basedir
if not basepath:
return filepath
if filepath.startswith(basepath):
rel = filepath[len(basepath):]
if rel and rel[0] == os.sep:
rel = rel[1:]
return rel | def relative_path(self, filepath, basepath=None) | Convert the filepath path to a relative path against basepath. By
default basepath is self.basedir. | 2.467152 | 2.202737 | 1.120039 |
fobj = open(filename, "w")
fobj.write(self.header % (title, self.style))
fobj.write("<h1>%s</h1>\n" % title)
fobj.write("<h2>Memory distribution over time</h2>\n")
fobj.write(self.charts['snapshots'])
fobj.write("<h2>Snapshots statistics</h2>\n")
fobj.w... | def create_title_page(self, filename, title='') | Output the title page. | 3.027782 | 3.033465 | 0.998127 |
try:
from pylab import figure, title, xlabel, ylabel, plot, savefig
except ImportError:
return HtmlStats.nopylab_msg % (classname+" lifetime")
cnt = []
for tobj in self.index[classname]:
cnt.append([tobj.birth, 1])
if tobj.death:
... | def create_lifetime_chart(self, classname, filename='') | Create chart that depicts the lifetime of the instance registered with
`classname`. The output is written to `filename`. | 3.435451 | 3.396087 | 1.011591 |
try:
from pylab import figure, title, xlabel, ylabel, plot, fill, legend, savefig
import matplotlib.mlab as mlab
except ImportError:
return self.nopylab_msg % ("memory allocation")
classlist = self.tracked_classes
times = [snapshot.timestamp... | def create_snapshot_chart(self, filename='') | Create chart that depicts the memory allocation over time apportioned to
the tracked classes. | 4.020032 | 3.776242 | 1.064559 |
try:
from pylab import figure, title, pie, axes, savefig
from pylab import sum as pylab_sum
except ImportError:
return self.nopylab_msg % ("pie_chart")
# Don't bother illustrating a pie without pieces.
if not snapshot.tracked_total:
... | def create_pie_chart(self, snapshot, filename='') | Create a pie chart that depicts the distribution of the allocated memory
for a given `snapshot`. The chart is saved to `filename`. | 4.63129 | 4.520814 | 1.024437 |
# Create a folder to store the charts and additional HTML files.
self.basedir = os.path.dirname(os.path.abspath(fname))
self.filesdir = os.path.splitext(fname)[0] + '_files'
if not os.path.isdir(self.filesdir):
os.mkdir(self.filesdir)
self.filesdir = os.path.... | def create_html(self, fname, title="ClassTracker Statistics") | Create HTML page `fname` and additional files in a directory derived
from `fname`. | 3.733995 | 3.676524 | 1.015632 |
path_cls = type(parent_path)
is_dir = path_cls.is_dir
exists = path_cls.exists
listdir = parent_path._accessor.listdir
return self._select_from(parent_path, is_dir, exists, listdir) | def select_from(self, parent_path) | Iterate over all child paths of `parent_path` matched by this
selector. This can contain parent_path itself. | 4.079235 | 4.15204 | 0.982465 |
# For the purpose of this method, drive and root are considered
# separate parts, i.e.:
# Path('c:/').relative_to('c:') gives Path('/')
# Path('c:/').relative_to('/') raise ValueError
if not other:
raise TypeError("need at least one argument")
... | def relative_to(self, *other) | Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path), raise ValueError. | 3.637555 | 3.3882 | 1.073595 |
pattern = self._flavour.casefold(pattern)
drv, root, pattern_parts = self._flavour.parse_parts((pattern,))
if drv or root:
raise NotImplementedError("Non-relative patterns are unsupported")
selector = _make_selector(tuple(pattern_parts))
for p in selector.sel... | def glob(self, pattern) | Iterate over this subtree and yield all existing files (of any
kind, including directories) matching the given pattern. | 7.513981 | 7.642473 | 0.983187 |
if not isinstance(data, six.binary_type):
raise TypeError(
'data must be %s, not %s' %
(six.binary_type.__class__.__name__, data.__class__.__name__))
with self.open(mode='wb') as f:
return f.write(data) | def write_bytes(self, data) | Open the file in bytes mode, write to it, and close the file. | 2.805686 | 2.498583 | 1.122911 |
if not isinstance(data, six.text_type):
raise TypeError(
'data must be %s, not %s' %
(six.text_type.__class__.__name__, data.__class__.__name__))
with self.open(mode='w', encoding=encoding, errors=errors) as f:
return f.write(data) | def write_text(self, data, encoding=None, errors=None) | Open the file in text mode, write to it, and close the file. | 2.397429 | 2.281594 | 1.050769 |
''' Helper function to convert all paths to relative posix like paths (to ease comparison) '''
return recwalk_result[0], path2unix(os.path.join(os.path.relpath(recwalk_result[0], pardir),recwalk_result[1]), nojoin=True, fromwinpath=fromwinpath) | def relpath_posix(recwalk_result, pardir, fromwinpath=False) | Helper function to convert all paths to relative posix like paths (to ease comparison) | 5.278035 | 3.19172 | 1.653664 |
# Find the path that is the deepest, and count the number of parts
max_rec = max(len(x) if x else 0 for x in d.values())
# Pad other paths with empty parts to fill in, so that all paths will have the same number of parts (necessary to compare correctly, else deeper paths may get precedence over top one... | def sort_dict_of_paths(d) | Sort a dict containing paths parts (ie, paths divided in parts and stored as a list). Top paths will be given precedence over deeper paths. | 7.229216 | 6.344002 | 1.139536 |
''' Sort a dictionary of relative paths and cluster equal paths together at the same time '''
# First, sort the paths in order (this must be a couple: (parent_dir, filename), so that there's no ambiguity because else a file at root will be considered as being after a folder/file since the ordering is done alpha... | def sort_group(d, return_only_first=False) | Sort a dictionary of relative paths and cluster equal paths together at the same time | 7.639977 | 6.803842 | 1.122892 |
self.ignore.append(inspect.currentframe())
return self._get_tree(self.root, self.maxdepth) | def get_tree(self) | Get a tree of referrers of the root object. | 8.487645 | 6.003361 | 1.413815 |
self.ignore.append(inspect.currentframe())
res = _Node(root, self.str_func) #PYCHOK use root parameter
self.already_included.add(id(root)) #PYCHOK use root parameter
if maxdepth == 0:
return res
objects = gc.get_referrers(root) #PYCHOK use root parameter
... | def _get_tree(self, root, maxdepth) | Workhorse of the get_tree implementation.
This is an recursive method which is why we have a wrapper method.
root is the current root object of the tree which should be returned.
Note that root is not of the type _Node.
maxdepth defines how much further down the from the root the tree
... | 4.669261 | 4.554174 | 1.025271 |
if tree is None:
self._print(self.root, '', '')
else:
self._print(tree, '', '') | def print_tree(self, tree=None) | Print referrers tree to console.
keyword arguments
tree -- if not None, the passed tree will be printed. Otherwise it is
based on the rootobject. | 3.880343 | 4.602819 | 0.843036 |
level = prefix.count(self.cross) + prefix.count(self.vline)
len_children = 0
if isinstance(tree , _Node):
len_children = len(tree.children)
# add vertex
prefix += str(tree)
# and as many spaces as the vertex is long
carryon += self.space * le... | def _print(self, tree, prefix, carryon) | Compute and print a new line of the tree.
This is a recursive function.
arguments
tree -- tree to print
prefix -- prefix to the current line to print
carryon -- prefix which is used to carry on the vertical lines | 4.161903 | 4.131924 | 1.007256 |
old_stream = self.stream
self.stream = open(filename, 'w')
try:
super(FileBrowser, self).print_tree(tree=tree)
finally:
self.stream.close()
self.stream = old_stream | def print_tree(self, filename, tree=None) | Print referrers tree to file (in text format).
keyword arguments
tree -- if not None, the passed tree will be printed. | 2.782847 | 2.854657 | 0.974845 |
window = _Tkinter.Tk()
sc = _TreeWidget.ScrolledCanvas(window, bg="white",\
highlightthickness=0, takefocus=1)
sc.frame.pack(expand=1, fill="both")
item = _ReferrerTreeItem(window, self.get_tree(), self)
node = _TreeNode(sc.canvas, ... | def main(self, standalone=False) | Create interactive browser window.
keyword arguments
standalone -- Set to true, if the browser is not attached to other
windows | 6.406559 | 7.469886 | 0.857652 |
'''
Returns
str(option_string * DropDown Value)
e.g.
-vvvvv
'''
dropdown_value = self.widget.GetValue()
if not str(dropdown_value).isdigit():
return ''
arg = str(self.option_string).replace('-', '')
repeated_args = arg * int(dropdown_value)
return '-' + repeated_a... | def getValue(self) | Returns
str(option_string * DropDown Value)
e.g.
-vvvvv | 11.742067 | 3.993992 | 2.939933 |
# in case the total is wrong (n is above the total), then
# we switch to the mode without showing the total prediction
# (since ETA would be wrong anyway)
if total and n > total:
total = None
elapsed_str = format_interval(elapsed)
if elapsed:
if unit_scale:
rat... | def format_meter(n, total, elapsed, ncols=None, prefix='',
unit=None, unit_scale=False, ascii=False) | Return a string-based progress bar given some parameters
Parameters
----------
n : int
Number of finished iterations.
total : int
The expected total number of iterations. If None, only basic progress
statistics are displayed (no ETA).
elapsed : float
Number of sec... | 3.099249 | 3.082521 | 1.005427 |
import cStringIO
stream = cStringIO.StringIO(data)
image = wx.ImageFromStream(stream)
icon = wx.EmptyIcon()
icon.CopyFromBitmap(wx.BitmapFromImage(image))
return icon | def getIcon( data ) | Return the data from the resource as a wxIcon | 2.511637 | 2.293953 | 1.094895 |
logging.basicConfig(level=logging.INFO)
app = RunSnakeRunApp(0)
app.MainLoop() | def main() | Mainloop for the application | 8.660938 | 7.577925 | 1.142917 |
self.CreateMenuBar()
self.SetupToolBar()
self.CreateStatusBar()
self.leftSplitter = wx.SplitterWindow(
self
)
self.rightSplitter = wx.SplitterWindow(
self.leftSplitter
)
self.listControl = listviews.DataView(
se... | def CreateControls(self, config_parser) | Create our sub-controls | 2.604001 | 2.602023 | 1.00076 |
menubar = wx.MenuBar()
menu = wx.Menu()
menu.Append(ID_OPEN, _('&Open Profile'), _('Open a cProfile file'))
menu.Append(ID_OPEN_MEMORY, _('Open &Memory'), _('Open a Meliae memory-dump file'))
menu.AppendSeparator()
menu.Append(ID_EXIT, _('&Close'), _('Close this ... | def CreateMenuBar(self) | Create our menu-bar for triggering operations | 2.782673 | 2.770555 | 1.004374 |
if editor and self.sourceCodeControl is None:
self.sourceCodeControl = wx.py.editwindow.EditWindow(
self.tabs, -1
)
self.sourceCodeControl.SetText(u"")
self.sourceFileShown = None
self.sourceCodeControl.setDisplayLineNumbers(Tr... | def CreateSourceWindow(self, tabs) | Create our source-view window for tabs | 7.881212 | 7.386241 | 1.067013 |
tb = self.CreateToolBar(self.TBFLAGS)
tsize = (24, 24)
tb.ToolBitmapSize = tsize
open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR,
tsize)
tb.AddLabelTool(ID_OPEN, "Open", open_bmp, shortHelp="Open",
... | def SetupToolBar(self) | Create the toolbar for common actions | 3.089846 | 3.075563 | 1.004644 |
new = self.viewTypeTool.GetStringSelection()
if new != self.viewType:
self.viewType = new
self.OnRootView( event ) | def OnViewTypeTool( self, event ) | When the user changes the selection, make that our selection | 5.700421 | 4.450506 | 1.280848 |
self.viewTypeTool.SetItems( getattr( self.loader, 'ROOTS', [] ))
if self.loader and self.viewType in self.loader.ROOTS:
self.viewTypeTool.SetSelection( self.loader.ROOTS.index( self.viewType ))
# configure the menu with the available choices...
def choos... | def ConfigureViewTypeChoices( self, event=None ) | Configure the set of View types in the toolbar (and menus) | 3.357425 | 3.258338 | 1.03041 |
dialog = wx.FileDialog(self, style=wx.OPEN|wx.FD_MULTIPLE)
if dialog.ShowModal() == wx.ID_OK:
paths = dialog.GetPaths()
if self.loader:
# we've already got a displayed data-set, open new window...
frame = MainFrame()
frame.... | def OnOpenFile(self, event) | Request to open a new profile file | 4.283285 | 4.312622 | 0.993197 |
dialog = wx.FileDialog(self, style=wx.OPEN)
if dialog.ShowModal() == wx.ID_OK:
path = dialog.GetPath()
if self.loader:
# we've already got a displayed data-set, open new window...
frame = MainFrame()
frame.Show(True)
... | def OnOpenMemory(self, event) | Request to open a new profile file | 4.416763 | 4.328826 | 1.020314 |
self.directoryView = not self.directoryView
self.packageMenuItem.Check(self.directoryView)
self.packageViewTool.SetValue(self.directoryView)
if self.loader:
self.SetModel(self.loader)
self.RecordHistory() | def SetPackageView(self, directoryView) | Set whether to use directory/package based view | 5.685756 | 5.460964 | 1.041163 |
self.percentageView = percentageView
self.percentageMenuItem.Check(self.percentageView)
self.percentageViewTool.SetValue(self.percentageView)
total = self.adapter.value( self.loader.get_root( self.viewType ) )
for control in self.ProfileListControls:
control.... | def SetPercentageView(self, percentageView) | Set whether to display percentage or absolute values | 6.357919 | 6.301988 | 1.008875 |
node = self.activated_node
parents = []
selected_parent = None
if node:
if hasattr( self.adapter, 'best_parent' ):
selected_parent = self.adapter.best_parent( node )
else:
parents = self.adapter.parents( node )
... | def OnUpView(self, event) | Request to move up the hierarchy to highest-weight parent | 3.997908 | 3.84682 | 1.039276 |
self.historyIndex -= 1
try:
self.RestoreHistory(self.history[self.historyIndex])
except IndexError, err:
self.SetStatusText(_('No further history available')) | def OnBackView(self, event) | Request to move backward in the history | 4.996084 | 4.120319 | 1.212548 |
self.adapter, tree, rows = self.RootNode()
self.squareMap.SetModel(tree, self.adapter)
self.RecordHistory()
self.ConfigureViewTypeChoices() | def OnRootView(self, event) | Reset view to the root of the tree | 29.451385 | 25.93762 | 1.13547 |
self.activated_node = self.selected_node = event.node
self.squareMap.SetModel(event.node, self.adapter)
self.squareMap.SetSelected( event.node )
if editor:
if self.SourceShowFile(event.node):
if hasattr(event.node,'lineno'):
self.s... | def OnNodeActivated(self, event) | Double-click or enter on a node in some control... | 10.10416 | 9.651823 | 1.046865 |
filename = self.adapter.filename( node )
if filename and self.sourceFileShown != filename:
try:
data = open(filename).read()
except Exception, err:
# TODO: load from zips/eggs? What about .pyc issues?
return None
... | def SourceShowFile(self, node) | Show the given file in the source-code view (attempt it anyway) | 8.047971 | 7.734732 | 1.040498 |
self.selected_node = event.node
self.calleeListControl.integrateRecords(self.adapter.children( event.node) )
self.callerListControl.integrateRecords(self.adapter.parents( event.node) ) | def OnSquareSelected(self, event) | Update all views to show selection children/parents | 10.672609 | 8.31685 | 1.283251 |
self.squareMap.square_style = not self.squareMap.square_style
self.squareMap.Refresh()
self.moreSquareViewItem.Check(self.squareMap.square_style) | def OnMoreSquareToggle( self, event ) | Toggle the more-square view (better looking, but more likely to filter records) | 6.790854 | 4.442052 | 1.528765 |
if not self.restoringHistory:
record = self.activated_node
if self.historyIndex < -1:
try:
del self.history[self.historyIndex+1:]
except AttributeError, err:
pass
if (not self.history) or record ... | def RecordHistory(self) | Add the given node to the history-set | 4.966316 | 4.740478 | 1.04764 |
if len(filenames) == 1:
if os.path.basename( filenames[0] ) == 'index.coldshot':
return self.load_coldshot( os.path.dirname( filenames[0]) )
elif os.path.isdir( filenames[0] ):
return self.load_coldshot( filenames[0] )
try:
sel... | def load(self, *filenames) | Load our dataset (iteratively) | 5.232174 | 5.248259 | 0.996935 |
self.loader = loader
self.adapter, tree, rows = self.RootNode()
self.listControl.integrateRecords(rows.values())
self.activated_node = tree
self.squareMap.SetModel(tree, self.adapter)
self.RecordHistory() | def SetModel(self, loader) | Set our overall model (a loader object) and populate sub-controls | 22.483641 | 22.448759 | 1.001554 |
tree = self.loader.get_root( self.viewType )
adapter = self.loader.get_adapter( self.viewType )
rows = self.loader.get_rows( self.viewType )
adapter.SetPercentage(self.percentageView, adapter.value( tree ))
return adapter, tree, rows | def RootNode(self) | Return our current root node and appropriate adapter for it | 8.574542 | 7.368335 | 1.163701 |
if not config_parser.has_section( 'window' ):
config_parser.add_section( 'window' )
if self.IsMaximized():
config_parser.set( 'window', 'maximized', str(True))
else:
config_parser.set( 'window', 'maximized', str(False))
size = self.GetSizeTupl... | def SaveState( self, config_parser ) | Retrieve window state to be restored on the next run... | 1.816602 | 1.683735 | 1.078912 |
if not config_parser:
return
if (
not config_parser.has_section( 'window' ) or (
config_parser.has_option( 'window','maximized' ) and
config_parser.getboolean( 'window', 'maximized' )
)
):
self.Maximize(Tru... | def LoadState( self, config_parser ) | Set our window state from the given config_parser instance | 3.200789 | 3.118769 | 1.026299 |
wx.Image.AddHandler(self.handler)
frame = MainFrame( config_parser = load_config())
frame.Show(True)
self.SetTopWindow(frame)
if profile:
wx.CallAfter(frame.load, *[profile])
elif sys.argv[1:]:
if sys.argv[1] == '-m':
if sy... | def OnInit(self, profile=None, memoryProfile=None) | Initialise the application | 4.056163 | 4.088434 | 0.992107 |
wx.Image.AddHandler(self.handler)
frame = MainFrame( config_parser = load_config())
frame.Show(True)
self.SetTopWindow(frame)
if sys.argv[1:]:
wx.CallAfter( frame.load_memory, sys.argv[1] )
else:
log.warn( 'No memory file specified' )
... | def OnInit(self) | Initialise the application | 5.414983 | 5.349722 | 1.012199 |
replace, insert, delete = "r", "i", "d"
L1, L2 = len(seq1), len(seq2)
if L1 < L2:
L1, L2 = L2, L1
seq1, seq2 = seq2, seq1
ldiff = L1 - L2
if ldiff == 0:
models = (insert+delete, delete+insert, replace+replace)
elif ldiff == 1:
models = (delete+replace, replace+delete)
elif ldiff == 2:
models = (de... | def fast_comp(seq1, seq2, transpositions=False) | Compute the distance between the two sequences `seq1` and `seq2` up to a
maximum of 2 included, and return it. If the edit distance between the two
sequences is higher than that, -1 is returned.
If `transpositions` is `True`, transpositions will be taken into account for
the computation of the distance. This can ... | 2.178198 | 2.184932 | 0.996918 |
'''Checks if a path is an actual file that exists'''
if not os.path.isfile(dirname):
msg = "{0} is not an existing file".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | def is_file(dirname) | Checks if a path is an actual file that exists | 3.219048 | 2.771497 | 1.161483 |
'''Checks if a path is an actual directory that exists'''
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | def is_dir(dirname) | Checks if a path is an actual directory that exists | 2.823757 | 2.505523 | 1.127013 |
'''Checks if a path is an actual directory that exists or a file'''
if not os.path.isdir(dirname) and not os.path.isfile(dirname):
msg = "{0} is not a directory nor a file".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | def is_dir_or_file(dirname) | Checks if a path is an actual directory that exists or a file | 2.978624 | 2.298029 | 1.296165 |
'''Relative path to absolute'''
if (type(relpath) is object or type(relpath) is file):
relpath = relpath.name
return os.path.abspath(os.path.expanduser(relpath)) | def fullpath(relpath) | Relative path to absolute | 4.165759 | 4.44557 | 0.937059 |
'''Recursively walk through a folder. This provides a mean to flatten out the files restitution (necessary to show a progress bar). This is a generator.'''
# If it's only a single file, return this single file
if os.path.isfile(inputpath):
abs_path = fullpath(inputpath)
yield os.path.dirname... | def recwalk(inputpath, sorting=True) | Recursively walk through a folder. This provides a mean to flatten out the files restitution (necessary to show a progress bar). This is a generator. | 6.115767 | 3.541581 | 1.726847 |
'''From a path given in any format, converts to posix path format
fromwinpath=True forces the input path to be recognized as a Windows path (useful on Unix machines to unit test Windows paths)'''
if fromwinpath:
pathparts = list(PureWindowsPath(path).parts)
else:
pathparts = list(PurePat... | def path2unix(path, nojoin=False, fromwinpath=False) | From a path given in any format, converts to posix path format
fromwinpath=True forces the input path to be recognized as a Windows path (useful on Unix machines to unit test Windows paths) | 5.26053 | 1.891411 | 2.781273 |
if os.path.isdir(path):
shutil.rmtree(path)
return True
elif os.path.isfile(path):
os.remove(path)
return True
return False | def remove_if_exist(path): # pragma: no cover
if os.path.exists(path) | Delete a file or a directory recursively if it exists, else no exception is raised | 2.479503 | 2.056221 | 1.205854 |
remove_if_exist(dst)
if os.path.exists(src):
if os.path.isdir(src):
if not only_missing:
shutil.copytree(src, dst, symlinks=False, ignore=None)
else:
for dirpath, filepath in recwalk(src):
srcfile = os.path.join(dirpath, fil... | def copy_any(src, dst, only_missing=False): # pragma: no cover
if not only_missing | Copy a file or a directory tree, deleting the destination before processing | 2.005626 | 1.90099 | 1.055043 |
Input: number of groups G per cluster, list of files F with respective sizes
- Order F by descending size
- Until F is empty:
- Create a cluster X
- A = Pop first item in F
- Put A in X[0] (X[0] is thus the first group in cluster X)
For g in 1..len(G)-1 :
- B = Po... | def group_files_by_size(fileslist, multi): # pragma: no cover
''' Cluster files into the specified number of groups, where each groups total size is as close as possible to each other.
Pseudo-code (O(n^g) time complexity) | Cluster files into the specified number of groups, where each groups total size is as close as possible to each other.
Pseudo-code (O(n^g) time complexity):
Input: number of groups G per cluster, list of files F with respective sizes
- Order F by descending size
- Until F is empty:
- Create a c... | 3.29549 | 1.837374 | 1.793587 |
def group_files_by_size_simple(fileslist, nbgroups): # pragma: no cover
ford = sorted(fileslist.iteritems(), key=lambda x: x[1], reverse=True)
ford = [[x[0]] for x in ford]
return [group for group in grouper(nbgroups, ford)] | Simple and fast files grouping strategy: just order by size, and group files n-by-n, so that files with the closest sizes are grouped together.
In this strategy, there is only one file per subgroup, and thus there will often be remaining space left because there is no filling strategy here, but it's very fast. | null | null | null | |
allitems = fgrouped.iteritems()
elif isinstance(fgrouped, list):
allitems = enumerate(fgrouped)
for fkey, cluster in allitems:
fsizes[fkey] = []
for subcluster in cluster:
tot = 0
if subcluster is not None:
for fname in subcluster:
... | def grouped_count_sizes(fileslist, fgrouped): # pragma: no cover
'''Compute the total size per group and total number of files. Useful to check that everything is OK.'''
fsizes = {}
total_files = 0
allitems = None
if isinstance(fgrouped, dict) | Compute the total size per group and total number of files. Useful to check that everything is OK. | 2.829944 | 2.585479 | 1.094553 |
values = [c.GetValue()
for c in chain(*self.widgets)
if c.GetValue() is not None]
return ' '.join(values) | def GetOptions(self) | returns the collective values from all of the
widgets contained in the panel | 8.69089 | 7.242584 | 1.199971 |
"itertools recipe: Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args) | def chunk(self, iterable, n, fillvalue=None) | itertools recipe: Collect data into fixed-length chunks or blocks | 3.10025 | 2.400752 | 1.291366 |
'''
Positionals have no associated options_string,
so only the supplied arguments are returned.
The order is assumed to be the same as the order
of declaration in the client code
Returns
"argument_value"
'''
self.AssertInitialization('Positional')
if str(self._widget.GetValue(... | def GetValue(self) | Positionals have no associated options_string,
so only the supplied arguments are returned.
The order is assumed to be the same as the order
of declaration in the client code
Returns
"argument_value" | 17.591526 | 3.305499 | 5.321898 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.