_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q10000
_get_usage
train
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 identi...
python
{ "resource": "" }
q10001
_remove_duplicates
train
def _remove_duplicates(objects): """Remove duplicate objects. Inspired by http://www.peterbe.com/plog/uniqifiers-benchmark """ seen = {} result = [] for item in objects: marker = id(item) if marker in seen: continue seen[marker] = 1 result.append(ite...
python
{ "resource": "" }
q10002
summarize
train
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. """ count = {} total_size = {} for o in objects: ...
python
{ "resource": "" }
q10003
get_diff
train
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 ro...
python
{ "resource": "" }
q10004
print_
train
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' """ localrows = [] for row in r...
python
{ "resource": "" }
q10005
_print_table
train
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 """ border = "=" # vertical delimiter vdelim = " |...
python
{ "resource": "" }
q10006
_repr
train
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 t...
python
{ "resource": "" }
q10007
_traverse
train
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 """ function(summary, *args) for row in summary: ...
python
{ "resource": "" }
q10008
_subtract
train
def _subtract(summary, o): """Remove object o from the summary by subtracting it's size.""" 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.a...
python
{ "resource": "" }
q10009
Polynomial.get_degree
train
def get_degree(self, poly=None): '''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 a...
python
{ "resource": "" }
q10010
Polynomial.scale
train
def scale(self, scalar): '''Multiply a polynomial with a scalar''' return self.__class__([self.coefficients[i] * scalar for i in _range(len(self))])
python
{ "resource": "" }
q10011
LineProfiler.wrap_function
train
def wrap_function(self, func): """ Wrap a function to profile it. """ def f(*args, **kwds): self.enable_by_count() try: result = func(*args, **kwds) finally: self.disable_by_count() return result return f
python
{ "resource": "" }
q10012
LineProfiler.runctx
train
def runctx(self, cmd, globals, locals): """ Profile a single executable statement in the given namespaces. """ self.enable_by_count() try: exec(cmd, globals, locals) finally: self.disable_by_count() return self
python
{ "resource": "" }
q10013
LineProfiler.runcall
train
def runcall(self, func, *args, **kw): """ Profile a single function call. """ # XXX where is this used ? can be removed ? self.enable_by_count() try: return func(*args, **kw) finally: self.disable_by_count()
python
{ "resource": "" }
q10014
LineProfiler.disable_by_count
train
def disable_by_count(self): """ Disable the profiler if the number of disable requests matches the number of enable requests. """ if self.enable_count > 0: self.enable_count -= 1 if self.enable_count == 0: self.disable()
python
{ "resource": "" }
q10015
parse_makefile_aliases
train
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. ''' # -- Parsing the Makefile using ConfigParser # Addi...
python
{ "resource": "" }
q10016
KThread.start
train
def start(self): """Start the thread.""" self.__run_backup = self.run self.run = self.__run # Force the Thread to install our trace. threading.Thread.start(self)
python
{ "resource": "" }
q10017
KThread.__run
train
def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup
python
{ "resource": "" }
q10018
MProfiler.codepoint_included
train
def codepoint_included(self, codepoint): """Check if codepoint matches any of the defined codepoints.""" 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...
python
{ "resource": "" }
q10019
MProfiler.profile
train
def profile(self, frame, event, arg): #PYCHOK arg requ. to match signature """Profiling method used to profile matching codepoints and events.""" if (self.events == None) or (event in self.events): frame_info = inspect.getframeinfo(frame) cp = (frame_info[0], frame_info[2], frame...
python
{ "resource": "" }
q10020
runprofile
train
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 ''' if noprofiler == True: print('ERROR: profiler and/or pstats library missing ...
python
{ "resource": "" }
q10021
parseprofile
train
def parseprofile(profilelog, out): ''' 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 t...
python
{ "resource": "" }
q10022
browseprofile
train
def browseprofile(profilelog): ''' 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." ...
python
{ "resource": "" }
q10023
browseprofilegui
train
def browseprofilegui(profilelog): ''' 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 pr...
python
{ "resource": "" }
q10024
GF2int._to_binpoly
train
def _to_binpoly(x): '''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...
python
{ "resource": "" }
q10025
loads
train
def loads( source ): """Load json structure from meliae from source Supports only the required structures to support loading meliae memory dumps """ source = source.strip() assert source.startswith( '{' ) assert source.endswith( '}' ) source = source[1:-1] result = {} for match ...
python
{ "resource": "" }
q10026
RSCoder._list_lstrip
train
def _list_lstrip(self, L, val=0): '''Left strip the specified value''' for i in _range(len(L)): if L[i] != val: return L[i:]
python
{ "resource": "" }
q10027
RSCoder._chien_search_fast
train
def _chien_search_fast(self, sigma): '''Real chien search, we reuse the previous polynomial evaluation and just multiply by a constant polynomial. This should be faster, but it seems it's just the same speed as the other bruteforce version. However, it should easily be parallelizable.''' # TODO: doesn't...
python
{ "resource": "" }
q10028
_ProcessMemoryInfoPS.update
train
def update(self): """ Get virtual and resident size of current process via 'ps'. This should work for MacOS X, Solaris, Linux. Returns true if it was successful. """ try: p = Popen(['/bin/ps', '-p%s' % self.pid, '-o', 'rss,vsz'], stdout=P...
python
{ "resource": "" }
q10029
_ProcessMemoryInfoProc.update
train
def update(self): """ Get virtual size of current process by reading the process' stat file. This should work for Linux. """ try: stat = open('/proc/self/stat') status = open('/proc/self/status') except IOError: # pragma: no cover retur...
python
{ "resource": "" }
q10030
DataView.SetColumns
train
def SetColumns( self, columns, sortOrder=None ): """Set columns to a set of values other than the originals and recreates column controls""" self.columns = columns self.sortOrder = [(x.defaultOrder,x) for x in self.columns if x.sortDefault] self.CreateColumns()
python
{ "resource": "" }
q10031
DataView.OnNodeActivated
train
def OnNodeActivated(self, event): """We have double-clicked for hit enter on a node refocus squaremap to this node""" try: node = self.sorted[event.GetIndex()] except IndexError, err: log.warn(_('Invalid index in node activated: %(index)s'), index=eve...
python
{ "resource": "" }
q10032
DataView.OnNodeSelected
train
def OnNodeSelected(self, event): """We have selected a node with the list control, tell the world""" try: node = self.sorted[event.GetIndex()] except IndexError, err: log.warn(_('Invalid index in node selected: %(index)s'), index=event.GetIndex()) ...
python
{ "resource": "" }
q10033
DataView.SetIndicated
train
def SetIndicated(self, node): """Set this node to indicated status""" self.indicated_node = node self.indicated = self.NodeToIndex(node) self.Refresh(False) return self.indicated
python
{ "resource": "" }
q10034
DataView.SetSelected
train
def SetSelected(self, node): """Set our selected node""" self.selected_node = node index = self.NodeToIndex(node) if index != -1: self.Focus(index) self.Select(index, True) return index
python
{ "resource": "" }
q10035
DataView.OnReorder
train
def OnReorder(self, event): """Given a request to reorder, tell us to reorder""" column = self.columns[event.GetColumn()] return self.ReorderByColumn( column )
python
{ "resource": "" }
q10036
DataView.ReorderByColumn
train
def ReorderByColumn( self, column ): """Reorder the set of records by column""" # TODO: store current selection and re-select after sorting... single_column = self.SetNewOrder( column ) self.reorder( single_column = True ) self.Refresh()
python
{ "resource": "" }
q10037
DataView.reorder
train
def reorder(self, single_column=False): """Force a reorder of the displayed items""" if single_column: columns = self.sortOrder[:1] else: columns = self.sortOrder for ascending,column in columns[::-1]: # Python 2.2+ guarantees stable sort, so sort by e...
python
{ "resource": "" }
q10038
DataView.integrateRecords
train
def integrateRecords(self, functions): """Integrate records from the loader""" self.SetItemCount(len(functions)) self.sorted = functions[:] self.reorder() self.Refresh()
python
{ "resource": "" }
q10039
DataView.OnGetItemText
train
def OnGetItemText(self, item, col): """Retrieve text for the item and column respectively""" # TODO: need to format for rjust and the like... try: column = self.columns[col] value = column.get(self.sorted[item]) except IndexError, err: return None ...
python
{ "resource": "" }
q10040
encode
train
def encode(input, output_filename): """Encodes the input data with reed-solomon error correction in 223 byte blocks, and outputs each block along with 32 parity bytes to a new file by the given filename. input is a file-like object The outputted image will be in png format, and will be 255 by x pi...
python
{ "resource": "" }
q10041
redirect
train
def redirect(url, code=303): """ Aborts execution and causes a 303 redirect """ scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/' location = urljoin(request.url, urljoin(scriptname, url)) raise HTTPResponse("", status=code, header=dict(Location=location))
python
{ "resource": "" }
q10042
parse_date
train
def parse_date(ims): """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """ try: ts = email.utils.parsedate_tz(ims) return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone except (TypeError, ValueError, IndexError): return None
python
{ "resource": "" }
q10043
run
train
def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080, interval=1, reloader=False, **kargs): """ Runs bottle as a web server. """ app = app if app else default_app() quiet = bool(kargs.get('quiet', False)) # Instantiate server, if it is a class instead of an instance if isinsta...
python
{ "resource": "" }
q10044
template
train
def template(tpl, template_adapter=SimpleTemplate, **kwargs): ''' Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. ''' if tpl not in TEMPLATES or DEBUG: settings = kwargs.get('template_settings',{}) lookup = kwargs....
python
{ "resource": "" }
q10045
Route.group_re
train
def group_re(self): ''' Return a regexp pattern with named groups ''' out = '' for token, data in self.tokens(): if token == 'TXT': out += re.escape(data) elif token == 'VAR': out += '(?P<%s>%s)' % (data[1], data[0]) elif token == 'ANON': out += '(?:%s)' %...
python
{ "resource": "" }
q10046
Route.format_str
train
def format_str(self): ''' Return a format string with named fields. ''' if self.static: return self.route.replace('%','%%') out, i = '', 0 for token, value in self.tokens(): if token == 'TXT': out += value.replace('%','%%') elif token == 'ANON': out +=...
python
{ "resource": "" }
q10047
Route.is_dynamic
train
def is_dynamic(self): ''' Return true if the route contains dynamic parts ''' if not self._static: for token, value in self.tokens(): if token != 'TXT': return True self._static = True return False
python
{ "resource": "" }
q10048
Router.build
train
def build(self, route_name, **args): ''' Builds an URL out of a named route and some parameters.''' try: return self.named[route_name] % args except KeyError: raise RouteBuildError("No route found with name '%s'." % route_name)
python
{ "resource": "" }
q10049
Bottle.add_filter
train
def add_filter(self, ftype, func): ''' Register a new output filter. Whenever bottle hits a handler output matching `ftype`, `func` is applyed to it. ''' if not isinstance(ftype, type): raise TypeError("Expected type object, got %s" % type(ftype)) self.castfilter = [(t, f...
python
{ "resource": "" }
q10050
Request.bind
train
def bind(self, environ, app=None): """ Bind a new WSGI enviroment and clear out all previously computed attributes. This is done automatically for the global `bottle.request` instance on every request. """ if isinstance(environ, Request): # Recycl...
python
{ "resource": "" }
q10051
Request.path_shift
train
def path_shift(self, count=1): ''' Shift some levels of PATH_INFO into SCRIPT_NAME and return the moved part. count defaults to 1''' #/a/b/ /c/d --> 'a','b' 'c','d' if count == 0: return '' pathlist = self.path.strip('/').split('/') scriptlist = self.environ.get('S...
python
{ "resource": "" }
q10052
Request.POST
train
def POST(self): """ The HTTP POST body parsed into a MultiDict. This supports urlencoded and multipart POST requests. Multipart is commonly used for file uploads and may result in some of the values beeing cgi.FieldStorage objects instead of strings. Multiple va...
python
{ "resource": "" }
q10053
Request.params
train
def params(self): """ A combined MultiDict with POST and GET parameters. """ if self._GETPOST is None: self._GETPOST = MultiDict(self.GET) self._GETPOST.update(dict(self.POST)) return self._GETPOST
python
{ "resource": "" }
q10054
Response.copy
train
def copy(self): ''' Returns a copy of self ''' copy = Response(self.app) copy.status = self.status copy.headers = self.headers.copy() copy.content_type = self.content_type return copy
python
{ "resource": "" }
q10055
magic_mprun
train
def magic_mprun(self, parameter_s=''): """ Execute a statement under the line-by-line memory profiler from the memory_profiler module. Usage: %mprun -f func1 -f func2 <statement> The given statement (which doesn't require quote marks) is run via the LineProfiler. Profiling is enabled for the...
python
{ "resource": "" }
q10056
profile
train
def profile(func, stream=None): """ Decorator that will run the function and print a line-by-line profile """ def wrapper(*args, **kwargs): prof = LineProfiler() val = prof(func)(*args, **kwargs) show_results(prof, stream=stream) return val return wrapper
python
{ "resource": "" }
q10057
TimeStamper.timestamp
train
def timestamp(self, name="<block>"): """Returns a context manager for timestamping a block of code.""" # Make a fake function func = lambda x: x func.__module__ = "" func.__name__ = name self.add_function(func) timestamps = [] self.functions[func].append(t...
python
{ "resource": "" }
q10058
TimeStamper.wrap_function
train
def wrap_function(self, func): """ Wrap a function to timestamp it. """ def f(*args, **kwds): # Start time timestamps = [_get_memory(os.getpid(), timestamps=True)] self.functions[func].append(timestamps) try: result = func(*args, **...
python
{ "resource": "" }
q10059
LineProfiler.run
train
def run(self, cmd): """ Profile a single executable statement in the main namespace. """ # TODO: can this be removed ? import __main__ main_dict = __main__.__dict__ return self.runctx(cmd, main_dict, main_dict)
python
{ "resource": "" }
q10060
PStatsLoader.get_root
train
def get_root( self, key ): """Retrieve a given declared root by root-type-key""" if key not in self.roots: function = getattr( self, 'load_%s'%(key,) )() self.roots[key] = function return self.roots[key]
python
{ "resource": "" }
q10061
PStatsLoader.get_rows
train
def get_rows( self, key ): """Get the set of rows for the type-key""" if key not in self.roots: self.get_root( key ) if key == 'location': return self.location_rows else: return self.rows
python
{ "resource": "" }
q10062
PStatsLoader.load
train
def load( self, stats ): """Build a squaremap-compatible model from a pstats class""" rows = self.rows for func, raw in stats.iteritems(): try: rows[func] = row = PStatRow( func,raw ) except ValueError, err: log.info( 'Null row: %s', func )...
python
{ "resource": "" }
q10063
PStatsLoader._load_location
train
def _load_location( self ): """Build a squaremap-compatible model for location-based hierarchy""" directories = {} files = {} root = PStatLocation( '/', 'PYTHONPATH' ) self.location_rows = self.rows.copy() for child in self.rows.values(): current = directories...
python
{ "resource": "" }
q10064
PStatLocation.filter_children
train
def filter_children( self ): """Filter our children into regular and local children sets""" real_children = [] for child in self.children: if child.name == '<module>': self.local_children.append( child ) else: real_children.append( child ) ...
python
{ "resource": "" }
q10065
split_box
train
def split_box( fraction, x,y, w,h ): """Return set of two boxes where first is the fraction given""" if w >= h: new_w = int(w*fraction) if new_w: return (x,y,new_w,h),(x+new_w,y,w-new_w,h) else: return None,None else: new_h = int(h*fraction) if...
python
{ "resource": "" }
q10066
HotMapNavigator.findNode
train
def findNode(class_, hot_map, targetNode, parentNode=None): ''' Find the target node in the hot_map. ''' for index, (rect, node, children) in enumerate(hot_map): if node == targetNode: return parentNode, hot_map, index result = class_.findNode(children, targetNode...
python
{ "resource": "" }
q10067
HotMapNavigator.firstChild
train
def firstChild(hot_map, index): ''' Return the first child of the node indicated by index. ''' children = hot_map[index][2] if children: return children[0][1] else: return hot_map[index][1]
python
{ "resource": "" }
q10068
HotMapNavigator.nextChild
train
def nextChild(hotmap, index): ''' Return the next sibling of the node indicated by index. ''' nextChildIndex = min(index + 1, len(hotmap) - 1) return hotmap[nextChildIndex][1]
python
{ "resource": "" }
q10069
SquareMap.OnMouse
train
def OnMouse( self, event ): """Handle mouse-move event by selecting a given element""" node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition()) self.SetHighlight( node, event.GetPosition() )
python
{ "resource": "" }
q10070
SquareMap.OnClickRelease
train
def OnClickRelease( self, event ): """Release over a given square in the map""" node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition()) self.SetSelected( node, event.GetPosition() )
python
{ "resource": "" }
q10071
SquareMap.OnDoubleClick
train
def OnDoubleClick(self, event): """Double click on a given square in the map""" node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition()) if node: wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) )
python
{ "resource": "" }
q10072
SquareMap.SetSelected
train
def SetSelected( self, node, point=None, propagate=True ): """Set the given node selected in the square-map""" if node == self.selectedNode: return self.selectedNode = node self.UpdateDrawing() if node: wx.PostEvent( self, SquareSelectionEvent( node=node, ...
python
{ "resource": "" }
q10073
SquareMap.SetHighlight
train
def SetHighlight( self, node, point=None, propagate=True ): """Set the currently-highlighted node""" if node == self.highlightedNode: return self.highlightedNode = node # TODO: restrict refresh to the squares for previous node and new node... self.UpdateDrawing() ...
python
{ "resource": "" }
q10074
SquareMap.Draw
train
def Draw(self, dc): ''' Draw the tree map on the device context. ''' self.hot_map = [] dc.BeginDrawing() brush = wx.Brush( self.BackgroundColour ) dc.SetBackground( brush ) dc.Clear() if self.model: self.max_depth_seen = 0 font = self.Font...
python
{ "resource": "" }
q10075
SquareMap.FontForLabels
train
def FontForLabels(self, dc): ''' Return the default GUI font, scaled for printing if necessary. ''' font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) scale = dc.GetPPI()[0] / wx.ScreenDC().GetPPI()[0] font.SetPointSize(scale*font.GetPointSize()) return font
python
{ "resource": "" }
q10076
SquareMap.BrushForNode
train
def BrushForNode( self, node, depth=0 ): """Create brush to use to display the given node""" if node == self.selectedNode: color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT) elif node == self.highlightedNode: color = wx.Colour( red=0, green=255, blue=0 ) ...
python
{ "resource": "" }
q10077
SquareMap.PenForNode
train
def PenForNode( self, node, depth=0 ): """Determine the pen to use to display the given node""" if node == self.selectedNode: return self.SELECTED_PEN return self.DEFAULT_PEN
python
{ "resource": "" }
q10078
SquareMap.TextForegroundForNode
train
def TextForegroundForNode(self, node, depth=0): """Determine the text foreground color to use to display the label of the given node""" if node == self.selectedNode: fg_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT) else: fg_color = self.adapt...
python
{ "resource": "" }
q10079
SquareMap.DrawBox
train
def DrawBox( self, dc, node, x,y,w,h, hot_map, depth=0 ): """Draw a model-node's box and all children nodes""" log.debug( 'Draw: %s to (%s,%s,%s,%s) depth %s', node, x,y,w,h, depth, ) if self.max_depth and depth > self.max_depth: return self.max_depth_seen...
python
{ "resource": "" }
q10080
SquareMap.DrawIconAndLabel
train
def DrawIconAndLabel(self, dc, node, x, y, w, h, depth): ''' Draw the icon, if any, and the label, if any, of the node. ''' if w-2 < self._em_size_//2 or h-2 < self._em_size_ //2: return dc.SetClippingRegion(x+1, y+1, w-2, h-2) # Don't draw outside the box try: ic...
python
{ "resource": "" }
q10081
DefaultAdapter.overall
train
def overall( self, node ): """Calculate overall size of the node including children and empty space""" return sum( [self.value(value,node) for value in self.children(node)] )
python
{ "resource": "" }
q10082
DefaultAdapter.children_sum
train
def children_sum( self, children,node ): """Calculate children's total sum""" return sum( [self.value(value,node) for value in children] )
python
{ "resource": "" }
q10083
DefaultAdapter.empty
train
def empty( self, node ): """Calculate empty space as a fraction of total space""" overall = self.overall( node ) if overall: return (overall - self.children_sum( self.children(node), node))/float(overall) return 0
python
{ "resource": "" }
q10084
format_sizeof
train
def format_sizeof(num, suffix='bytes'): '''Readable size format, courtesy of Sridhar Ratnakumar''' for unit in ['','K','M','G','T','P','E','Z']: if abs(num) < 1000.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1000.0 return "%.1f%s%s" % (num, 'Y', suffix)
python
{ "resource": "" }
q10085
tqdm.close
train
def close(self): """ Call this method to force print the last progress bar update based on the latest n value """ if self.leave: if self.last_print_n < self.n: cur_t = time.time() self.sp.print_status(format_meter(self.n, self.total, cur_t-self...
python
{ "resource": "" }
q10086
tonativefunc
train
def tonativefunc(enc='utf-8'): ''' Returns a function that turns everything into 'native' strings using enc ''' if sys.version_info >= (3,0,0): return lambda x: x.decode(enc) if isinstance(x, bytes) else str(x) return lambda x: x.encode(enc) if isinstance(x, unicode) else str(x)
python
{ "resource": "" }
q10087
Bottle.mount
train
def mount(self, app, script_path): ''' Mount a Bottle application to a specific URL prefix ''' if not isinstance(app, Bottle): raise TypeError('Only Bottle instances are supported for now.') script_path = '/'.join(filter(None, script_path.split('/'))) path_depth = script_path...
python
{ "resource": "" }
q10088
Request.GET
train
def GET(self): """ The QUERY_STRING parsed into a MultiDict. Keys and values are strings. Multiple values per key are possible. See MultiDict for details. """ if self._GET is None: data = parse_qs(self.query_string, keep_blank_values=True) self._G...
python
{ "resource": "" }
q10089
Request.COOKIES
train
def COOKIES(self): """ Cookie information parsed into a dictionary. Secure cookies are NOT decoded automatically. See Request.get_cookie() for details. """ if self._COOKIES is None: raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE','')) self....
python
{ "resource": "" }
q10090
Response.set_cookie
train
def set_cookie(self, key, value, **kargs): """ Add a new cookie with various options. If the cookie value is not a string, a secure cookie is created. Possible options are: expires, path, comment, domain, max_age, secure, version, httponly See http://de.wikipedia.org/wi...
python
{ "resource": "" }
q10091
tamper_file_at
train
def tamper_file_at(path, pos=0, replace_str=None): """ Tamper a file at the given position and using the given string """ if not replace_str: replace_str = "\x00" try: with open(path, "r+b") as fh: if pos < 0: # if negative, we calculate the position backward from the end of file...
python
{ "resource": "" }
q10092
tamper_file
train
def tamper_file(filepath, mode='e', proba=0.03, block_proba=None, blocksize=65535, burst_length=None, header=None): """ Randomly tamper a file's content """ if header and header > 0: blocksize = header tamper_count = 0 # total number of characters tampered in the file total_size = 0 # total buf...
python
{ "resource": "" }
q10093
tamper_dir
train
def tamper_dir(inputpath, *args, **kwargs): """ Randomly tamper the files content in a directory tree, recursively """ silent = kwargs.get('silent', False) if 'silent' in kwargs: del kwargs['silent'] filescount = 0 for _ in tqdm(recwalk(inputpath), desc='Precomputing', disable=silent): file...
python
{ "resource": "" }
q10094
TrackedObject._save_trace
train
def _save_trace(self): """ Save current stack trace as formatted string. """ stack_trace = stack() try: self.trace = [] for frm in stack_trace[5:]: # eliminate our own overhead self.trace.insert(0, frm[1:]) finally: del ...
python
{ "resource": "" }
q10095
TrackedObject.track_size
train
def track_size(self, ts, sizer): """ Store timestamp and current size for later evaluation. The 'sizer' is a stateful sizing facility that excludes other tracked objects. """ obj = self.ref() self.snapshots.append( (ts, sizer.asized(obj, detail=self._r...
python
{ "resource": "" }
q10096
PeriodicThread.run
train
def run(self): """ Loop until a stop signal is set. """ self.stop = False while not self.stop: self.tracker.create_snapshot() sleep(self.interval)
python
{ "resource": "" }
q10097
Snapshot.label
train
def label(self): """Return timestamped label for this snapshot, or a raw timestamp.""" if not self.desc: return "%.3fs" % self.timestamp return "%s (%.3fs)" % (self.desc, self.timestamp)
python
{ "resource": "" }
q10098
ClassTracker._tracker
train
def _tracker(self, _observer_, _self_, *args, **kwds): """ Injected constructor for tracked classes. Call the actual constructor of the object and track the object. Attach to the object before calling the constructor to track the object with the parameters of the most specialized...
python
{ "resource": "" }
q10099
ClassTracker._inject_constructor
train
def _inject_constructor(self, cls, func, name, resolution_level, keep, trace): """ Modifying Methods in Place - after the recipe 15.7 in the Python Cookbook by Ken Seehof. The original constructors may be restored later. """ try: co...
python
{ "resource": "" }