code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
Returns
"--option_name argument"
'''
self.AssertInitialization('Choice')
if self._widget.GetValue() == self._DEFAULT_VALUE:
return None
return ' '.join(
[self._action.option_strings[0] if self._action.option_strings else '', # get the verbose copy if available
self.... | def GetValue(self) | Returns
"--option_name argument" | 14.533859 | 9.664623 | 1.503821 |
'''
General options are key/value style pairs (conceptually).
Thus the name of the option, as well as the argument to it
are returned
e.g.
>>> myscript --outfile myfile.txt
returns
"--Option Value"
'''
self.AssertInitialization('Optional')
value = self._widget.GetValue()
... | def GetValue(self) | General options are key/value style pairs (conceptually).
Thus the name of the option, as well as the argument to it
are returned
e.g.
>>> myscript --outfile myfile.txt
returns
"--Option Value" | 22.897085 | 4.659902 | 4.913641 |
'''
Flag options have no param associated with them.
Thus we only need the name of the option.
e.g
>>> Python -v myscript
returns
Options name for argument (-v)
'''
if not self._widget.GetValue() or len(self._widget.GetValue()) <= 0:
return None
else:
return s... | def GetValue(self) | Flag options have no param associated with them.
Thus we only need the name of the option.
e.g
>>> Python -v myscript
returns
Options name for argument (-v) | 16.285006 | 2.916289 | 5.584153 |
'''
Custom wrapper calculator to account for the
increased size of the _msg widget after being
inlined with the wx.CheckBox
'''
if self._msg is None:
return
help_msg = self._msg
width, height = size
content_area = int((width / 3) * .70)
wiggle_room = range(int(content_area... | def Update(self, size) | Custom wrapper calculator to account for the
increased size of the _msg widget after being
inlined with the wx.CheckBox | 7.625965 | 3.849396 | 1.981081 |
'''
NOTE: Added on plane. Cannot remember exact implementation
of counter objects. I believe that they count sequentail
pairings of options
e.g.
-vvvvv
But I'm not sure. That's what I'm going with for now.
Returns
str(action.options_string[0]) * DropDown Value
'''
dropdo... | def GetValue(self) | NOTE: Added on plane. Cannot remember exact implementation
of counter objects. I believe that they count sequentail
pairings of options
e.g.
-vvvvv
But I'm not sure. That's what I'm going with for now.
Returns
str(action.options_string[0]) * DropDown Value | 20.438246 | 2.483563 | 8.229404 |
''' Returns the full path to the language file '''
filename = language.lower() + '.json'
lang_file_path = os.path.join(_DEFAULT_DIR, filename)
if not os.path.exists(lang_file_path):
raise IOError('Could not find {} language file'.format(language))
return lang_file_path | def get_path(language) | Returns the full path to the language file | 3.107879 | 3.01955 | 1.029252 |
''' Open and return the supplied json file '''
global _DICTIONARY
try:
json_file = filename + '.json'
with open(os.path.join(_DEFAULT_DIR, json_file), 'rb') as f:
_DICTIONARY = json.load(f)
except IOError:
raise IOError('Language file not found. Make sure that your ',
'transl... | def load(filename) | Open and return the supplied json file | 6.502768 | 5.897144 | 1.102698 |
try:
s = repr(obj)
if not clip or len(s) <= clip:
return s
else:
return s[:clip-4]+'..'+s[-2:]
except:
return 'N/A' | def safe_repr(obj, clip=None) | Convert object to string representation, yielding the same result a `repr`
but catches all exceptions and returns 'N/A' instead of raising the
exception. Strings may be truncated by providing `clip`.
>>> safe_repr(42)
'42'
>>> safe_repr('Clipped text', clip=8)
'Clip..xt'
>>> safe_repr([1,2,... | 3.181073 | 3.390547 | 0.938218 |
s = str(obj)
s = s.replace('\n', '|')
if len(s) > max:
if left:
return '...'+s[len(s)-max+3:]
else:
return s[:(max-3)]+'...'
else:
return s | def trunc(obj, max, left=0) | Convert `obj` to string, eliminate newlines and truncate the string to `max`
characters. If there are more characters in the string add ``...`` to the
string. With `left=True`, the string can be truncated at the beginning.
@note: Does not catch exceptions when converting `obj` to string with `str`.
>>... | 2.634687 | 3.30712 | 0.796671 |
degree = 0
pattern = "%4d %s"
while i > base:
pattern = "%7.2f %s"
i = i / float(base)
degree += 1
scales = ['B', 'KB', 'MB', 'GB', 'TB', 'EB']
return pattern % (i, scales[degree]) | def pp(i, base=1024) | Pretty-print the integer `i` as a human-readable size representation. | 4.483768 | 4.041377 | 1.109465 |
if t is None:
return ''
h, m, s = int(t / 3600), int(t / 60 % 60), t % 60
return "%02d:%02d:%05.2f" % (h, m, s) | def pp_timestamp(t) | Get a friendly timestamp represented as a string. | 2.063226 | 2.0084 | 1.027299 |
if not stream: # pragma: no cover
stream = sys.stdout
self.metadata.sort(key=lambda x: -x.size)
stream.write('%-10s %8s %-12s %-46s\n' % ('id', 'size', 'type', 'representation'))
for g in self.metadata:
stream.write('0x%08x %8d %-12s %-46s\n' % (g.id, g.s... | def print_stats(self, stream=None) | Log annotated garbage objects to console or file.
:param stream: open file, uses sys.stdout if not given | 4.630793 | 4.394371 | 1.053801 |
result = set(self.file_dict)
# Ignore profiling code. __file__ does not always provide consistent
# results with f_code.co_filename (ex: easy_install with zipped egg),
# so inspect current frame instead.
# XXX: assumes all of pprofile code resides in a single file.
... | def getFilenameSet(self) | Returns a set of profiled file names.
Note: "file name" is used loosely here. See python documentation for
co_filename, linecache module and PEP302. It may not be a valid
filesystem path. | 14.280603 | 11.004395 | 1.297718 |
print >> out, 'version: 1'
if commandline is not None:
print >> out, 'cmd:', commandline
print >> out, 'creator: pprofile'
print >> out, 'event: usphit :us/hit'
print >> out, 'events: hits us usphit'
file_dict = self.file_dict
if relative_path... | def callgrind(self, out, filename=None, commandline=None, relative_path=False) | Dump statistics in callgrind format.
Contains:
- per-line hit count, time and time-per-hit
- call associations (call tree)
Note: hit count is not inclusive, in that it is not the sum of all
hits inside that call.
Time unit: microsecond (1e-6 second).
out (file... | 3.838192 | 3.644176 | 1.05324 |
file_dict = self.file_dict
total_time = self.total_time
if commandline is not None:
print >> out, 'Command line:', commandline
print >> out, 'Total duration: %gs' % total_time
if not total_time:
return
def percent(value, scale):
... | def annotate(self, out, filename=None, commandline=None, relative_path=False) | Dump annotated source code with current profiling statistics to "out"
file.
Time unit: second.
out (file-ish opened for writing)
Destination of annotated sources.
filename (str, list of str)
If provided, dump stats for given source file(s) only.
By def... | 2.517225 | 2.467353 | 1.020213 |
if self.enabled_start:
sys.settrace(None)
self._disable()
else:
warn('Duplicate "disable" call') | def disable(self, threads=True) | Disable profiling. | 14.797567 | 11.98873 | 1.23429 |
import __main__
dict = __main__.__dict__
return self.runctx(cmd, dict, dict) | def run(self, cmd) | Similar to profile.Profile.run . | 7.293167 | 5.836564 | 1.249565 |
if not self.nostdout:
self.stdout.write(data+end)
if self.file is not None:
self.file.write(data+end)
if flush:
self.flush() | def write(self, data, end="\n", flush=True) | Output data to stdout and/or file | 3.180451 | 2.884949 | 1.102429 |
if not self.nostdout:
self.stdout.flush()
if self.file is not None:
self.file.flush() | def flush(self) | Force commit changes to the file and stdout | 4.553813 | 3.310708 | 1.37548 |
if normalized:
return nlevenshtein(seq1, seq2, method=1)
if seq1 == seq2:
return 0
len1, len2 = len(seq1), len(seq2)
if max_dist >= 0 and abs(len1 - len2) > max_dist:
return -1
if len1 == 0:
return len2
if len2 == 0:
return len1
if len1 < len2:
len1, len2 = len2, len1
seq1, seq2 = seq2, seq1... | def levenshtein(seq1, seq2, normalized=False, max_dist=-1) | Compute the absolute Levenshtein distance between the two sequences
`seq1` and `seq2`.
The Levenshtein distance is the minimum number of edit operations necessary
for transforming one sequence into the other. The edit operations allowed are:
* deletion: ABC -> BC, AC, AB
* insertion: ABC -> ABCD, EABC... | 2.044313 | 2.034002 | 1.00507 |
if seq1 == seq2:
return 0.0
len1, len2 = len(seq1), len(seq2)
if len1 == 0 or len2 == 0:
return 1.0
if len1 < len2: # minimize the arrays size
len1, len2 = len2, len1
seq1, seq2 = seq2, seq1
if method == 1:
return levenshtein(seq1, seq2) / float(len1)
if method != 2:
raise ValueError("expected e... | def nlevenshtein(seq1, seq2, method=1) | Compute the normalized Levenshtein distance between `seq1` and `seq2`.
Two normalization methods are provided. For both of them, the normalized
distance will be a float between 0 and 1, where 0 means equal and 1
completely different. The computation obeys the following patterns:
0.0 if se... | 2.461288 | 2.372701 | 1.037336 |
return [
parent for parent in
getattr( node, 'parents', [] )
if getattr(parent, 'tree', self.TREE) == self.TREE
] | def parents(self, node) | Determine all parents of node in our tree | 7.428721 | 6.967319 | 1.066224 |
if not node.directory:
# TODO: any cases other than built-ins?
return None
if node.filename == '~':
# TODO: look up C/Cython/whatever source???
return None
return os.path.join(node.directory, node.filename) | def filename( self, node ) | Extension to squaremap api to provide "what file is this" information | 9.9554 | 9.540918 | 1.043443 |
oid = id(obj)
try:
server.id2ref[oid] = obj
except TypeError:
server.id2obj[oid] = obj
return str(oid) | def get_ref(obj) | Get string reference to object. Stores a weak reference in a dictionary
using the object's id as the key. If the object cannot be weakly
referenced (e.g. dictionaries, frame objects), store a strong references
in a classic dictionary.
Returns the object's id as a string. | 6.012498 | 5.581436 | 1.077232 |
oid = int(ref)
return server.id2ref.get(oid) or server.id2obj[oid] | def get_obj(ref) | Get object from string reference. | 10.113517 | 10.252493 | 0.986445 |
pmi = ProcessMemoryInfo()
threads = get_current_threads()
return dict(info=pmi, threads=threads) | def process() | Get process overview. | 9.725007 | 9.354098 | 1.039652 |
stats = server.stats
if stats and stats.snapshots:
stats.annotate()
timeseries = []
for cls in stats.tracked_classes:
series = []
for snapshot in stats.snapshots:
series.append(snapshot.classes.get(cls, {}).get('sum', 0))
timeserie... | def tracker_index() | Get tracker overview. | 2.991062 | 2.942561 | 1.016483 |
stats = server.stats
if not stats:
bottle.redirect('/tracker')
stats.annotate()
return dict(stats=stats, clsname=clsname) | def tracker_class(clsname) | Get class instance details. | 9.136868 | 9.063865 | 1.008054 |
graph = _compute_garbage_graphs()[int(index)]
graph.reduce_to_cycles()
objects = graph.metadata
objects.sort(key=lambda x: -x.size)
return dict(objects=objects, index=index) | def garbage_cycle(index) | Get reference cycle details. | 9.648057 | 9.59478 | 1.005553 |
try:
rendered = graph.rendered_file
except AttributeError:
try:
graph.render(os.path.join(server.tmpdir, filename), format='png')
rendered = filename
except OSError:
rendered = None
graph.rendered_file = rendered
return rendered | def _get_graph(graph, filename) | Retrieve or render a graph. | 4.859572 | 4.493921 | 1.081366 |
graph = _compute_garbage_graphs()[int(index)]
reduce_graph = bottle.request.GET.get('reduce', '')
if reduce_graph:
graph = graph.reduce_to_cycles()
if not graph:
return None
filename = 'garbage%so%s.png' % (index, reduce_graph)
rendered_file = _get_graph(graph, filename)
... | def garbage_graph(index) | Get graph representation of reference cycle. | 5.932586 | 5.917387 | 1.002569 |
if tracker and not stats:
server.stats = tracker.stats
else:
server.stats = stats
try:
server.tmpdir = mkdtemp(prefix='pympler')
server.server = PymplerServer(host=host, port=port, **kwargs)
bottle.debug(debug)
bottle.run(server=server.server)
finally... | def start_profiler(host='localhost', port=8090, tracker=None, stats=None,
debug=False, **kwargs) | Start the web server to show profiling data. The function suspends the
Python application (the current thread) until the web server is stopped.
The only way to stop the server is to signal the running thread, e.g. press
Ctrl+C in the console. If this isn't feasible for your application use
`start_in_ba... | 3.714391 | 4.425922 | 0.839236 |
k = _winreg.OpenKey(
_winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
)
try:
# should check that it's valid? How?
return _winreg.QueryValueEx( k, name )[0]
finally:
_winreg.CloseKey( k ) | def _winreg_getShellFolder( name ) | Get a shell folder by string name from the registry | 2.572256 | 2.595421 | 0.991075 |
if shell:
# on Win32 and have Win32all extensions, best-case
return shell_getShellFolder(shellcon.CSIDL_APPDATA)
if _winreg:
# on Win32, but no Win32 shell com available, this uses
# a direct registry access, likely to fail on Win98/Me
return _winreg_getShellFolder( ... | def appdatadirectory( ) | Attempt to retrieve the current user's app-data directory
This is the location where application-specific
files should be stored. On *nix systems, this will
be the ${HOME}/.config directory. On Win32 systems, it will be
the "Application Data" directory. Note that for
Win32 systems it is normal t... | 10.594279 | 10.29398 | 1.029172 |
gc.collect()
# Do not initialize local variables before calling gc.get_objects or those
# will be included in the list. Furthermore, ignore frame objects to
# prevent reference cycles.
tmp = gc.get_objects()
tmp = [o for o in tmp if not isframe(o)]
res = []
for o in tmp:
#... | def get_objects(remove_dups=True, include_frames=False) | Return a list of all known objects excluding frame objects.
If (outer) frame objects shall be included, pass `include_frames=True`. In
order to prevent building reference cycles, the current frame object (of
the caller of get_objects) is ignored. This will not prevent creating
reference cycles if the ... | 5.258598 | 5.23266 | 1.004957 |
res = 0
for o in objects:
try:
res += _getsizeof(o)
except AttributeError:
print("IGNORING: type=%s; o=%s" % (str(type(o)), str(o)))
return res | def get_size(objects) | Compute the total size of all elements in objects. | 4.562701 | 3.936879 | 1.158964 |
res = {'+': [], '-': []}
def partition(objects):
res = {}
for o in objects:
t = type(o)
if type(o) not in res:
res[t] = []
res[t].append(o)
return res
def get_not_included(foo, bar):
res = []
... | def get_diff(left, right) | Get the difference of both lists.
The result will be a dict with this form {'+': [], '-': []}.
Items listed in '+' exist only in the right list,
items listed in '-' exist only in the left list. | 3.366611 | 3.19982 | 1.052125 |
raise ValueError("minimum must be smaller than maximum")
if Type is not None:
res = [o for o in objects if isinstance(o, Type)]
if min > -1:
res = [o for o in res if _getsizeof(o) < min]
if max > -1:
res = [o for o in res if _getsizeof(o) > max]
return res | def filter(objects, Type=None, min=-1, max=-1): #PYCHOK muppy filter
res = []
if min > max | Filter objects.
The filter can be by type, minimum size, and/or maximum size.
Keyword arguments:
Type -- object type to filter by
min -- minimum object size
max -- maximum object size | 2.481866 | 2.605587 | 0.952517 |
res = gc.get_referents(object)
level -= 1
if level > 0:
for o in res:
res.extend(get_referents(o, level))
res = _remove_duplicates(res)
return res | def get_referents(object, level=1) | Get all referents of an object up to a certain level.
The referents will not be returned in a specific order and
will not contain duplicate objects. Duplicate objects will be removed.
Keyword arguments:
level -- level of indirection to which referents considered.
This function is recursive. | 2.990699 | 3.611742 | 0.828049 |
# The usage of a function is calculated by creating one summary of all
# objects before the function is invoked and afterwards. These summaries
# are compared and the diff is returned.
# This function works in a 2-steps process. Before the actual function is
# invoked an empty dummy function is... | def _get_usage(function, *args) | Test if more memory is used after the function has been called.
The function will be invoked twice and only the second measurement will be
considered. Thus, memory used in initialisation (e.g. loading modules)
will not be included in the result. The goal is to identify memory leaks
caused by functions ... | 5.386458 | 5.386723 | 0.999951 |
seen = {}
result = []
for item in objects:
marker = id(item)
if marker in seen:
continue
seen[marker] = 1
result.append(item)
return result | def _remove_duplicates(objects) | Remove duplicate objects.
Inspired by http://www.peterbe.com/plog/uniqifiers-benchmark | 2.065442 | 2.040937 | 1.012006 |
boolean_actions = (
_StoreConstAction, _StoreFalseAction,
_StoreTrueAction
)
return [action
for action in actions
if action.option_strings
and not action.choices
and not isinstance(action, _CountAction)
and not isinstance(action, _... | def get_optionals_without_choices(self, actions) | All actions which are:
(a) Optional, but without required choices
(b) Not of a "boolean" type (storeTrue, etc..)
(c) Of type _AppendAction
e.g. anything which has an argument style like:
>>> -f myfilename.txt | 5.063588 | 4.249176 | 1.191664 |
return [action
for action in actions
if isinstance(action, _StoreTrueAction)
or isinstance(action, _StoreFalseAction)
or isinstance(action, _StoreConstAction)] | def get_flag_style_optionals(self, actions) | Gets all instances of "flag" type options.
i.e. options which either store a const, or
store boolean style options (e.g. StoreTrue).
Types:
_StoreTrueAction
_StoreFalseAction
_StoreConst | 4.553603 | 3.109981 | 1.46419 |
'''
Resizes a bitmap to a height of 89 pixels (the
size of the top panel), while keeping aspect ratio
in tact
'''
image = wx.ImageFromBitmap(_bitmap)
_width, _height = image.GetSize()
if _height < target_height:
return wx.StaticBitmap(parent, -1, wx.BitmapFromImage(image))
ratio = float(_width) / ... | def resize_bitmap(parent, _bitmap, target_height) | Resizes a bitmap to a height of 89 pixels (the
size of the top panel), while keeping aspect ratio
in tact | 3.427727 | 1.918418 | 1.786747 |
for seq2 in seqs:
dist = levenshtein(seq1, seq2, max_dist=max_dist)
if dist != -1:
yield dist, seq2 | def ilevenshtein(seq1, seqs, max_dist=-1) | Compute the Levenshtein distance between the sequence `seq1` and the series
of sequences `seqs`.
`seq1`: the reference sequence
`seqs`: a series of sequences (can be a generator)
`max_dist`: if provided and > 0, only the sequences which distance from
the reference sequence is lower or equal to this value wil... | 2.065551 | 2.552453 | 0.809241 |
for seq2 in seqs:
dist = fast_comp(seq1, seq2, transpositions)
if dist != -1:
yield dist, seq2 | def ifast_comp(seq1, seqs, transpositions=False) | Return an iterator over all the sequences in `seqs` which distance from
`seq1` is lower or equal to 2. The sequences which distance from the
reference sequence is higher than that are dropped.
`seq1`: the reference sequence.
`seqs`: a series of sequences (can be a generator)
`transpositions` has the same sens... | 3.070273 | 3.725477 | 0.824129 |
count = {}
total_size = {}
for o in objects:
otype = _repr(o)
if otype in count:
count[otype] += 1
total_size[otype] += _getsizeof(o)
else:
count[otype] = 1
total_size[otype] = _getsizeof(o)
rows = []
for otype in count:
... | def summarize(objects) | Summarize an objects list.
Return a list of lists, whereas each row consists of::
[str(type), number of objects of this type, total size of these objects].
No guarantee regarding the order is given. | 2.180146 | 1.914801 | 1.138576 |
res = []
for row_r in right:
found = False
for row_l in left:
if row_r[0] == row_l[0]:
res.append([row_r[0], row_r[1] - row_l[1], row_r[2] - row_l[2]])
found = True
if not found:
res.append(row_r)
for row_l in left:
... | def get_diff(left, right) | Get the difference of two summaries.
Subtracts the values of the right summary from the values of the left
summary.
If similar rows appear on both sides, the are included in the summary with
0 for number of elements and total size.
If the number of elements of a row of the diff is 0, but the total ... | 1.565744 | 1.599548 | 0.978867 |
localrows = []
for row in rows:
localrows.append(list(row))
# input validation
sortby = ['type', '#', 'size']
if sort not in sortby:
raise ValueError("invalid sort, should be one of" + str(sortby))
orders = ['ascending', 'descending']
if order not in orders:
rais... | def print_(rows, limit=15, sort='size', order='descending') | Print the rows as a summary.
Keyword arguments:
limit -- the maximum number of elements to be listed
sort -- sort elements by 'size', 'type', or '#'
order -- sort 'ascending' or 'descending' | 2.316462 | 2.40894 | 0.96161 |
border = "="
# vertical delimiter
vdelim = " | "
# padding nr. of spaces are left around the longest element in the
# column
padding = 1
# may be left,center,right
justify = 'right'
justify = {'left' : str.ljust,
'center' : str.center,
'right' : ... | def _print_table(rows, header=True) | Print a list of lists as a pretty table.
Keyword arguments:
header -- if True the first row is treated as a table header
inspired by http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 | 4.585232 | 4.495304 | 1.020005 |
res = ""
t = type(o)
if (verbosity == 0) or (t not in representations):
res = str(t)
else:
verbosity -= 1
if len(representations[t]) < verbosity:
verbosity = len(representations[t]) - 1
res = representations[t][verbosity](o)
res = address.sub('', re... | def _repr(o, verbosity=1) | Get meaning object representation.
This function should be used when the simple str(o) output would result in
too general data. E.g. "<type 'instance'" is less meaningful than
"instance: Foo".
Keyword arguments:
verbosity -- if True the first row is treated as a table header | 3.737111 | 4.392529 | 0.850788 |
function(summary, *args)
for row in summary:
function(row, *args)
for item in row:
function(item, *args) | def _traverse(summary, function, *args) | Traverse all objects of a summary and call function with each as a
parameter.
Using this function, the following objects will be traversed:
- the summary
- each row
- each item of a row | 3.253129 | 3.169893 | 1.026258 |
found = False
row = [_repr(o), 1, _getsizeof(o)]
for r in summary:
if r[0] == row[0]:
(r[1], r[2]) = (r[1] - row[1], r[2] - row[2])
found = True
if not found:
summary.append([row[0], -row[1], -row[2]])
return summary | def _subtract(summary, o) | Remove object o from the summary by subtracting it's size. | 2.982005 | 2.69104 | 1.108124 |
#http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted/1401565#1401565
# Check structure only for images (not supported for other types currently)
if filepath.lower().endswith(tuple(img_filter)):
try:
#try:
... | def check_structure(filepath) | Returns False if the file is okay, None if file format is unsupported by PIL/PILLOW, or returns an error string if the file is corrupt. | 8.13451 | 7.35152 | 1.106507 |
'''Generate several hashes (md5 and sha1) in a single sweep of the file. Using two hashes lowers the probability of collision and false negative (file modified but the hash is the same). Supports big files by streaming blocks by blocks to the hasher automatically. Blocksize can be any multiple of 128.'''
# Init... | def generate_hashes(filepath, blocksize=65536) | Generate several hashes (md5 and sha1) in a single sweep of the file. Using two hashes lowers the probability of collision and false negative (file modified but the hash is the same). Supports big files by streaming blocks by blocks to the hasher automatically. Blocksize can be any multiple of 128. | 4.117771 | 1.786439 | 2.305016 |
'''Returns the degree of the polynomial'''
if not poly:
return self.degree
#return len(self.coefficients) - 1
elif poly and hasattr("coefficients", poly):
return len(poly.coefficients) - 1
else:
while poly and poly[-1] == 0:
... | def get_degree(self, poly=None) | Returns the degree of the polynomial | 3.955689 | 3.98949 | 0.991528 |
'''Compute the multiplication between two polynomials only at the specified coefficient (this is a lot cheaper than doing the full polynomial multiplication and then extract only the required coefficient)'''
if k > (self.degree + other.degree) or k > self.degree: return 0 # optimization: if the required... | def mul_at(self, other, k) | Compute the multiplication between two polynomials only at the specified coefficient (this is a lot cheaper than doing the full polynomial multiplication and then extract only the required coefficient) | 6.697862 | 4.242807 | 1.578639 |
'''Multiply a polynomial with a scalar'''
return self.__class__([self.coefficients[i] * scalar for i in _range(len(self))]) | def scale(self, scalar) | Multiply a polynomial with a scalar | 6.642437 | 5.605564 | 1.184972 |
'''Fast polynomial division by using Extended Synthetic Division (aka Horner's method). Also works with non-monic polynomials.
A nearly exact same code is explained greatly here: http://research.swtch.com/field and you can also check the Wikipedia article and the Khan Academy video.'''
# Note: f... | def _fastdivmod(dividend, divisor) | Fast polynomial division by using Extended Synthetic Division (aka Horner's method). Also works with non-monic polynomials.
A nearly exact same code is explained greatly here: http://research.swtch.com/field and you can also check the Wikipedia article and the Khan Academy video. | 10.32494 | 6.73611 | 1.532775 |
'''Fast polynomial division by using Extended Synthetic Division and optimized for GF(2^p) computations (so it is not generic, must be used with GF2int).
Transposed from the reedsolomon library: https://github.com/tomerfiliba/reedsolomon
BEWARE: it works only for monic divisor polynomial! (which... | def _gffastdivmod(dividend, divisor) | Fast polynomial division by using Extended Synthetic Division and optimized for GF(2^p) computations (so it is not generic, must be used with GF2int).
Transposed from the reedsolomon library: https://github.com/tomerfiliba/reedsolomon
BEWARE: it works only for monic divisor polynomial! (which is always ... | 13.376098 | 8.355291 | 1.600913 |
'''Evaluate this polynomial at value x, returning the result (which is the sum of all evaluations at each term).'''
# Holds the sum over each term in the polynomial
#c = 0
# Holds the current power of x. This is multiplied by x after each term
# in the polynomial is added up. In... | def evaluate(self, x) | Evaluate this polynomial at value x, returning the result (which is the sum of all evaluations at each term). | 5.75845 | 4.342017 | 1.326215 |
'''Simple way of evaluating a polynomial at value x, but here we return both the full array (evaluated at each polynomial position) and the sum'''
x_gf = self.coefficients[0].__class__(x)
arr = [self.coefficients[-i]*x_gf**(i-1) for i in _range(len(self), 0, -1)]
# if x == 1: arr = sum(s... | def evaluate_array(self, x) | Simple way of evaluating a polynomial at value x, but here we return both the full array (evaluated at each polynomial position) and the sum | 8.648911 | 4.261912 | 2.02935 |
'''Compute the formal derivative of the polynomial: sum(i*coeff[i] x^(i-1))'''
#res = [0] * (len(self)-1) # pre-allocate the list, it will be one item shorter because the constant coefficient (x^0) will be removed
#for i in _range(2, len(self)+1): # start at 2 to skip the first coeff which is us... | def derive(self) | Compute the formal derivative of the polynomial: sum(i*coeff[i] x^(i-1)) | 6.202035 | 5.095854 | 1.217075 |
'''Generalized feature scaling (useful for variable error correction rate calculation)'''
return a + float(x - xmin) * (b - a) / (xmax - xmin) | def feature_scaling(x, xmin, xmax, a=0, b=1) | Generalized feature scaling (useful for variable error correction rate calculation) | 12.083534 | 3.587722 | 3.368024 |
'''From an ecc entry position (a list with starting and ending positions), extract the metadata fields (filename, filesize, ecc for both), and the starting/ending positions of the ecc stream (containing variably encoded blocks of hash and ecc per blocks of the original file's header)'''
# Read the the beginning... | def entry_fields(file, entry_pos, field_delim="\xFF") | From an ecc entry position (a list with starting and ending positions), extract the metadata fields (filename, filesize, ecc for both), and the starting/ending positions of the ecc stream (containing variably encoded blocks of hash and ecc per blocks of the original file's header) | 7.884447 | 6.129708 | 1.286268 |
'''From an entry with its parameters (filename, filesize), assemble a list of each block from the original file along with the relative hash and ecc for easy processing later.'''
# Cut the header and the ecc entry into blocks, and then assemble them so that we can easily process block by block
eccfile.seek(... | def stream_entry_assemble(hasher, file, eccfile, entry_fields, max_block_size, header_size, resilience_rates, constantmode=False) | From an entry with its parameters (filename, filesize), assemble a list of each block from the original file along with the relative hash and ecc for easy processing later. | 6.503183 | 5.485446 | 1.185534 |
'''Generate a stream of hash/ecc blocks, of variable encoding rate and size, given a file.'''
curpos = file.tell() # init the reading cursor at the beginning of the file
# Find the total size to know when to stop
#size = os.fstat(file.fileno()).st_size # old way of doing it, doesn't work with StringIO o... | def stream_compute_ecc_hash(ecc_manager, hasher, file, max_block_size, header_size, resilience_rates) | Generate a stream of hash/ecc blocks, of variable encoding rate and size, given a file. | 5.367333 | 4.861855 | 1.103968 |
'''Generate a concatenated string of ecc stream of hash/ecc blocks, of constant encoding rate, given a string.
NOTE: resilience_rate here is constant, you need to supply only one rate, between 0.0 and 1.0. The encoding rate will then be constant, like in header_ecc.py.'''
fpfile = StringIO(string)
ecc_s... | def compute_ecc_hash_from_string(string, ecc_manager, hasher, max_block_size, resilience_rate) | Generate a concatenated string of ecc stream of hash/ecc blocks, of constant encoding rate, given a string.
NOTE: resilience_rate here is constant, you need to supply only one rate, between 0.0 and 1.0. The encoding rate will then be constant, like in header_ecc.py. | 13.277224 | 4.778378 | 2.778605 |
# convert strings to StringIO object so that we can trick our ecc reading functions that normally works only on files
fpfile = StringIO(field)
fpfile_ecc = StringIO(ecc)
fpentry_p = {"ecc_field_pos": [0, len(field)]} # create a fake entry_pos so that the ecc reading function works correctly
# P... | def ecc_correct_intra_stream(ecc_manager_intra, ecc_params_intra, hasher_intra, resilience_rate_intra, field, ecc, enable_erasures=False, erasures_char="\x00", only_erasures=False, max_block_size=65535) | Correct an intra-field with its corresponding intra-ecc if necessary | 5.402874 | 5.321995 | 1.015197 |
ret = []
if timeout is not None:
max_iter = timeout / interval
elif isinstance(proc, int):
# external process and no timeout
max_iter = 1
else:
# for a Python function wait until it finishes
max_iter = float('inf')
if str(proc).endswith('.py'):
... | def memory_usage(proc=-1, interval=.1, timeout=None, run_in_place=False) | Return the memory usage of a process or piece of code
Parameters
----------
proc : {int, string, tuple}, optional
The process to monitor. Can be given by a PID, by a string
containing a filename or by a tuple. The tuple should contain
three values (f, args, kw) specifies to run the ... | 2.647977 | 2.597213 | 1.019546 |
if os.path.isfile(script_name):
return script_name
path = os.getenv('PATH', os.defpath).split(os.pathsep)
for dir in path:
if dir == '':
continue
fn = os.path.join(dir, script_name)
if os.path.isfile(fn):
return fn
print >> sys.stderr, 'Could... | def _find_script(script_name) | Find the script.
If the input is not a file, then $PATH will be searched. | 2.070714 | 2.013021 | 1.02866 |
opts, stmt = self.parse_options(line, 'r:t:i', posix=False, strict=False)
repeat = int(getattr(opts, 'r', 1))
if repeat < 1:
repeat == 1
timeout = int(getattr(opts, 't', 0))
if timeout <= 0:
timeout = None
run_in_place = hasattr(opts, 'i')
mem_usage = memory_usage((_fun... | def magic_memit(self, line='') | Measure memory usage of a Python statement
Usage, in line mode:
%memit [-ir<R>t<T>] statement
Options:
-r<R>: repeat the loop iteration <R> times and take the best result.
Default: 1
-i: run the code in the current environment, without forking a new process.
This is required on some Mac... | 5.410284 | 4.685875 | 1.154594 |
try:
# func_code does not exist in Python3
code = func.__code__
except AttributeError:
import warnings
warnings.warn("Could not extract a code object for the object %r"
% (func,))
return
if code not in... | def add_function(self, func) | Record line profiling information for the given Python function. | 4.448222 | 4.438947 | 1.002089 |
def f(*args, **kwds):
self.enable_by_count()
try:
result = func(*args, **kwds)
finally:
self.disable_by_count()
return result
return f | def wrap_function(self, func) | Wrap a function to profile it. | 3.322263 | 2.690369 | 1.234873 |
self.enable_by_count()
try:
exec(cmd, globals, locals)
finally:
self.disable_by_count()
return self | def runctx(self, cmd, globals, locals) | Profile a single executable statement in the given namespaces. | 4.211448 | 3.779657 | 1.114241 |
# XXX where is this used ? can be removed ?
self.enable_by_count()
try:
return func(*args, **kw)
finally:
self.disable_by_count() | def runcall(self, func, *args, **kw) | Profile a single function call. | 5.765461 | 4.86354 | 1.185445 |
if self.enable_count > 0:
self.enable_count -= 1
if self.enable_count == 0:
self.disable() | def disable_by_count(self) | Disable the profiler if the number of disable requests matches the
number of enable requests. | 2.83458 | 2.723504 | 1.040784 |
if event in ('line', 'return') and frame.f_code in self.code_map:
lineno = frame.f_lineno
if event == 'return':
lineno += 1
entry = self.code_map[frame.f_code].setdefault(lineno, [])
entry.append(_get_memory(os.getpid()... | def trace_memory_usage(self, frame, event, arg) | Callback for sys.settrace | 3.401297 | 3.347415 | 1.016097 |
'''
Parse a makefile to find commands and substitute variables. Expects a
makefile with only aliases and a line return between each command.
Returns a dict, with a list of commands for each alias.
'''
# -- Parsing the Makefile using ConfigParser
# Adding a fake section to make the Makefile... | def parse_makefile_aliases(filepath) | Parse a makefile to find commands and substitute variables. Expects a
makefile with only aliases and a line return between each command.
Returns a dict, with a list of commands for each alias. | 4.982643 | 4.274975 | 1.165537 |
self.__run_backup = self.run
self.run = self.__run # Force the Thread to install our trace.
threading.Thread.start(self) | def start(self) | Start the thread. | 15.389828 | 9.939478 | 1.548354 |
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup | def __run(self) | Hacked run function, which installs the trace. | 8.685531 | 6.280484 | 1.38294 |
if self.codepoints == None:
return True
for cp in self.codepoints:
mismatch = False
for i in range(len(cp)):
if (cp[i] is not None) and (cp[i] != codepoint[i]):
mismatch = True
break
if not m... | def codepoint_included(self, codepoint) | Check if codepoint matches any of the defined codepoints. | 2.559132 | 2.286082 | 1.11944 |
frame_info = inspect.getframeinfo(frame)
cp = (frame_info[0], frame_info[2], frame_info[1])
if self.codepoint_included(cp):
objects = muppy.get_objects()
size = muppy.get_size(objects)
if cp not in self.memories:
sel... | def profile(self, frame, event, arg): #PYCHOK arg requ. to match signature
if (self.events == None) or (event in self.events) | Profiling method used to profile matching codepoints and events. | 2.524901 | 2.262804 | 1.115828 |
'''
Run the functions profiler and save the result
If timeout is greater than 0, the profile will automatically stops after timeout seconds
'''
if noprofiler == True:
print('ERROR: profiler and/or pstats library missing ! Please install it (probably package named python-profile) before r... | def runprofile(mainfunction, output, timeout = 0, calibrate=False) | Run the functions profiler and save the result
If timeout is greater than 0, the profile will automatically stops after timeout seconds | 8.13504 | 7.385619 | 1.10147 |
'''
Calibrate the profiler (necessary to have non negative and more exact values)
'''
pr = profile.Profile()
calib = []
crepeat = 10
for i in range(crepeat):
calib.append(pr.calibrate(10000))
final = sum(calib) / crepeat
profile.Profile.bias = final # Apply computed bias ... | def calibrateprofile() | Calibrate the profiler (necessary to have non negative and more exact values) | 12.050161 | 6.990694 | 1.723743 |
'''
Parse a profile log and print the result on screen
'''
file = open(out, 'w') # opening the output file
print('Opening the profile in %s...' % profilelog)
p = pstats.Stats(profilelog, stream=file) # parsing the profile with pstats, and output everything to the file
print('Generating the ... | def parseprofile(profilelog, out) | Parse a profile log and print the result on screen | 3.743983 | 3.534414 | 1.059294 |
'''
Browse interactively a profile log in console
'''
print('Starting the pstats profile browser...\n')
try:
browser = ProfileBrowser(profilelog)
print >> browser.stream, "Welcome to the profile statistics browser. Type help to get started."
browser.cmdloop()
... | def browseprofile(profilelog) | Browse interactively a profile log in console | 8.26009 | 6.356647 | 1.299441 |
'''
Browse interactively a profile log in GUI using RunSnakeRun and SquareMap
'''
from runsnakerun import runsnake # runsnakerun needs wxPython lib, if it's not available then we can pass if we don't want a GUI. RunSnakeRun is only used for GUI visualisation, not for profiling (and you can still use pst... | def browseprofilegui(profilelog) | Browse interactively a profile log in GUI using RunSnakeRun and SquareMap | 16.810747 | 9.450219 | 1.778874 |
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
''' Returns a list of primes < n '''
sieve = [True] * (n/2)
for i in _range(3,int(n**0.5)+1,2):
if sieve[i/2]:
sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1)
return [2]... | def rwh_primes1(n) | Returns a list of primes < n | 1.797484 | 1.781829 | 1.008786 |
'''Convert a Galois Field's number into a nice polynomial'''
if x <= 0: return "0"
b = 1 # init to 2^0 = 1
c = [] # stores the degrees of each term of the polynomials
i = 0 # counter for b = 2^i
while x > 0:
b = (1 << i) # generate a number power of 2: 2^0, 2^... | def _to_binpoly(x) | Convert a Galois Field's number into a nice polynomial | 5.590637 | 4.971738 | 1.124484 |
'''A slow multiply method. This method gives the same results as the
other __mul__ method but without needing precomputed tables,
thus it can be used to generate those tables.
If prim is set to 0 and carryless=False, the function produces the result of a standard multiplication of integ... | def multiply(a, b, prim=0x11b, field_charac_full=256, carryless=True) | A slow multiply method. This method gives the same results as the
other __mul__ method but without needing precomputed tables,
thus it can be used to generate those tables.
If prim is set to 0 and carryless=False, the function produces the result of a standard multiplication of integers (outsid... | 10.548196 | 3.252624 | 3.242981 |
'''Another equivalent (but even slower) way to compute multiplication in Galois Fields without using a precomputed look-up table.
This is the form you will most often see in academic literature, by using the standard carry-less multiplication + modular reduction using an irreducible prime polynomial.'''... | def multiply_slow(x, y, prim=0x11b) | Another equivalent (but even slower) way to compute multiplication in Galois Fields without using a precomputed look-up table.
This is the form you will most often see in academic literature, by using the standard carry-less multiplication + modular reduction using an irreducible prime polynomial. | 6.108754 | 4.21417 | 1.449575 |
source = source.strip()
assert source.startswith( '{' )
assert source.endswith( '}' )
source = source[1:-1]
result = {}
for match in attr.finditer( source ):
key = match.group('key')
if match.group( 'list' ) is not None:
value = [
int(x)
... | def loads( source ) | Load json structure from meliae from source
Supports only the required structures to support loading meliae memory dumps | 2.967895 | 3.029755 | 0.979583 |
'''Encode a given string or list of values (between 0 and gf2_charac)
with reed-solomon encoding. Returns a list of values (or a string if return_string is true)
with the k message bytes and n-k parity bytes at the end.
If a message is < k bytes long, it is assumed to be padded ... | def encode(self, message, poly=False, k=None, return_string=True) | Encode a given string or list of values (between 0 and gf2_charac)
with reed-solomon encoding. Returns a list of values (or a string if return_string is true)
with the k message bytes and n-k parity bytes at the end.
If a message is < k bytes long, it is assumed to be padded at the fron... | 9.8721 | 5.759612 | 1.714022 |
'''Verifies the codeword is valid by testing that the codeword (message+ecc) as a polynomial code divides g
returns True/False
'''
n = self.n
if not k: k = self.k
#h = self.h[k]
g = self.g[k]
# If we were given a string, convert to a list (important to su... | def check(self, r, k=None) | Verifies the codeword is valid by testing that the codeword (message+ecc) as a polynomial code divides g
returns True/False | 10.54581 | 6.485884 | 1.625963 |
'''Fast check if there's any error in a message+ecc. Can be used before decoding, in addition to hashes to detect if the message was tampered, or after decoding to check that the message was fully recovered.
returns True/False
'''
n = self.n
if not k: k = self.k
#h = self... | def check_fast(self, r, k=None) | Fast check if there's any error in a message+ecc. Can be used before decoding, in addition to hashes to detect if the message was tampered, or after decoding to check that the message was fully recovered.
returns True/False | 7.988797 | 4.375891 | 1.825639 |
'''Left strip the specified value'''
for i in _range(len(L)):
if L[i] != val:
return L[i:] | def _list_lstrip(self, L, val=0) | Left strip the specified value | 5.340398 | 5.366714 | 0.995096 |
'''Left pad with the specified value to obtain a list of the specified width (length)'''
length = max(0, width - len(L))
return [fillchar]*length + L | def _list_rjust(self, L, width, fillchar=0) | Left pad with the specified value to obtain a list of the specified width (length) | 8.58801 | 3.808771 | 2.254798 |
'''Given the received codeword r in the form of a Polynomial object,
computes the syndromes and returns the syndrome polynomial.
Mathematically, it's essentially equivalent to a Fourrier Transform (Chien search being the inverse).
'''
n = self.n
if not k: k = self.k
... | def _syndromes(self, r, k=None) | Given the received codeword r in the form of a Polynomial object,
computes the syndromes and returns the syndrome polynomial.
Mathematically, it's essentially equivalent to a Fourrier Transform (Chien search being the inverse). | 18.088335 | 10.96209 | 1.650081 |
'''Compute the erasures locator polynomial from the erasures positions (the positions must be relative to the x coefficient, eg: "hello worldxxxxxxxxx" is tampered to "h_ll_ worldxxxxxxxxx" with xxxxxxxxx being the ecc of length n-k=9, here the string positions are [1, 4], but the coefficients are reversed sinc... | def _find_erasures_locator(self, erasures_pos) | Compute the erasures locator polynomial from the erasures positions (the positions must be relative to the x coefficient, eg: "hello worldxxxxxxxxx" is tampered to "h_ll_ worldxxxxxxxxx" with xxxxxxxxx being the ecc of length n-k=9, here the string positions are [1, 4], but the coefficients are reversed since the ecc c... | 12.124003 | 5.456416 | 2.221972 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.