code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if len(img.shape) < 3: raise ValueError('Input volume must be atleast 3D!') elif len(img.shape) == 3: for dim_size in img.shape: if dim_size < 1: raise ValueError('Atleast one slice must exist in each dimension') elif len(img.shape) == 4: if img.shap...
def check_image_is_3d(img)
Ensures the image loaded is 3d and nothing else.
2.598395
2.527144
1.028194
if len(img.shape) < 4: raise ValueError('Input volume must be 4D!') elif len(img.shape) == 4: for dim_size in img.shape[:3]: if dim_size < 1: raise ValueError('Atleast one slice must exist in each dimension') if img.shape[3] < min_num_volumes: ...
def check_image_is_4d(img, min_num_volumes=2)
Ensures the image loaded is 3d and nothing else.
3.013456
2.947473
1.022387
if bkground_thresh is None: return img if isinstance(bkground_thresh, str): try: thresh_perc = float(bkground_thresh.replace('%', '')) except: raise ValueError( 'percentile specified could not be parsed correctly ' ' - must b...
def threshold_image(img, bkground_thresh, bkground_value=0.0)
Thresholds a given image at a value or percentile. Replacement value can be specified too. Parameters ----------- image_in : ndarray Input image bkground_thresh : float a threshold value to identify the background bkground_value : float a value to fill the background...
2.97429
3.038219
0.978958
min_value = image_in.min() max_value = image_in.max() # making a copy to ensure no side-effects image = image_in.copy() if exclude_outliers_below: perctl = float(exclude_outliers_below) image[image < np.percentile(image, perctl)] = min_value if exclude_outliers_above: ...
def scale_0to1(image_in, exclude_outliers_below=False, exclude_outliers_above=False)
Scale the two images to [0, 1] based on min/max from both. Parameters ----------- image_in : ndarray Input image exclude_outliers_{below,above} : float Lower/upper limit, a value between 0 and 100. Returns ------- scaled_image : ndarray clipped and/or scaled image
2.04868
2.144185
0.955459
if matrix.shape[0] <= matrix.shape[1]: raise ValueError('Number of voxels is less than the number of time points!! ' 'Are you sure data is reshaped correctly?') min_ = matrix.min(axis=1) range_ = matrix.ptp(axis=1) # ptp : peak to peak, max-min min_tile = np.tile(mi...
def row_wise_rescale(matrix)
Row-wise rescale of a given matrix. For fMRI data (num_voxels x num_time_points), this would translate to voxel-wise normalization over time. Parameters ---------- matrix : ndarray Input rectangular matrix, typically a carpet of size num_voxels x num_4th_dim, 4th_dim could be time points or g...
3.344033
3.075398
1.08735
beg_coords, end_coords = crop_coords(seg, padding) img = crop_3dimage(img, beg_coords, end_coords) seg = crop_3dimage(seg, beg_coords, end_coords) return img, seg
def crop_to_seg_extents(img, seg, padding)
Crop the image (usually MRI) to fit within the bounding box of a segmentation (or set of seg)
2.948132
2.931913
1.005532
beg_coords1, end_coords1 = crop_coords(img1, padding) beg_coords2, end_coords2 = crop_coords(img2, padding) beg_coords = np.fmin(beg_coords1, beg_coords2) end_coords = np.fmax(end_coords1, end_coords2) img1 = crop_3dimage(img1, beg_coords, end_coords) img2 = crop_3dimage(img2, beg_coords...
def crop_to_extents(img1, img2, padding)
Crop the images to ensure both fit within the bounding box
1.86249
1.892794
0.983989
"Crops an image or slice to its extents" if padding < 1: return img beg_coords, end_coords = crop_coords(img, padding) if len(img.shape) == 3: img = crop_3dimage(img, beg_coords, end_coords) elif len(img.shape) == 2: img = crop_2dimage(img, beg_coords, end_coords) else...
def crop_image(img, padding=5)
Crops an image or slice to its extents
3.129235
2.608932
1.199431
coords = np.nonzero(img) empty_axis_exists = np.any([len(arr) == 0 for arr in coords]) if empty_axis_exists: end_coords = img.shape beg_coords = np.zeros((1, img.ndim)).astype(int).flatten() else: min_coords = np.array([arr.min() for arr in coords]) max_coords = np....
def crop_coords(img, padding)
Find coordinates describing extent of non-zero portion of image, padded
2.726295
2.655164
1.02679
cropped_img = img[ beg_coords[0]:end_coords[0], beg_coords[1]:end_coords[1], beg_coords[2]:end_coords[2] ] return cropped_img
def crop_3dimage(img, beg_coords, end_coords)
Crops a 3d image to the bounding box specified.
1.860089
1.815863
1.024355
cropped_img = img[ beg_coords[0]:end_coords[0], beg_coords[1]:end_coords[1], ] return cropped_img
def crop_2dimage(img, beg_coords, end_coords)
Crops a 3d image to the bounding box specified.
2.318954
2.345152
0.988829
slices = list() for view in range(len(img.shape)): dim_size = img.shape[view] non_empty_slices = np.array( [sl for sl in range(dim_size) if np.count_nonzero(get_axis(img, view, sl)) > 0]) num_non_empty = len(non_empty_slices) # trying to 5% slices at the tails ...
def pick_slices(img, num_slices_per_view)
Picks the slices to display in each dimension, skipping any empty slices (without any segmentation at all).
3.359794
3.318401
1.012474
min_value = max(slice1.min(), slice2.min()) max_value = max(slice1.max(), slice2.max()) slice1 = (slice1 - min_value) / max_value slice2 = (slice2 - min_value) / max_value return slice1, slice2
def scale_images_0to1(slice1, slice2)
Scale the two images to [0, 1] based on min/max from both.
1.853145
1.700884
1.089519
if isinstance(sampler, str): sampler = sampler.lower() if sampler not in ['linear', ]: raise ValueError('Sampling strategy: {} not implemented.'.format(sampler)) out_sampler = sampler out_sampling_method = 'linear' elif isinstance(sampler, Iterable): if ...
def verify_sampler(sampler, image, image_shape, view_set, num_slices)
verifies the sampler requested is valid.
3.476925
3.424381
1.015344
fields = [field for field in USER._meta.fields if field.name == 'username'] try: length = fields[0].max_length except IndexError: length = 30 return length
def get_username_max_len()
Returns username maximum length as supported by Django. :rtype: int
3.605618
4.090487
0.881464
for option, value in config.items(): env_name = 'SCRAPEKIT_%s' % option.upper() value = os.environ.get(env_name, value) config[option] = value return config
def _get_env(self, config)
Read environment variables based on the settings defined in the defaults. These are expected to be upper-case versions of the actual setting names, prefixed by ``SCRAPEKIT_``.
3.371451
2.466142
1.367095
config_file = SafeConfigParser() config_file.read([os.path.expanduser('~/.scrapekit.ini')]) if config_file.has_section('scrapekit'): config.update(dict(config_file.items('scrapekit'))) if config_file.has_section(self.scraper.name): config.update(dict(conf...
def _get_file(self, config)
Read a per-user .ini file, which is expected to have either a ``[scraperkit]`` or a ``[$SCRAPER_NAME]`` section.
2.513786
2.186288
1.149796
self.queue = Queue(maxsize=self.num_threads * 10) for i in range(self.num_threads): t = Thread(target=self._consume) t.daemon = True t.start()
def _spawn(self)
Initialize the queue and the threads.
2.656547
2.105783
1.261549
while True: try: task, args, kwargs = self.queue.get(True) task(*args, **kwargs) finally: self.queue.task_done()
def _consume(self)
Main loop for each thread, handles picking a task off the queue, processing it and notifying the queue that it is done.
3.049891
2.395388
1.273235
if self.num_threads == 0: return task(*args, **kwargs) if self.queue is None: self._spawn() self.queue.put((task, args, kwargs))
def put(self, task, args, kwargs)
Add a new item to the queue. An item is a task and the arguments needed to call it. Do not call this directly, use Task.queue/Task.run instead.
3.071006
3.597406
0.853672
self.scraper.task_manager.put(self, args, kwargs) return self
def queue(self, *args, **kwargs)
Schedule a task for execution. The task call (and its arguments) will be placed on the queue and processed asynchronously.
12.826544
14.259461
0.899511
if self._source is not None: return self._source.run(*args, **kwargs) else: self.queue(*args, **kwargs) return self.wait()
def run(self, *args, **kwargs)
Queue a first item to execute, then wait for the queue to be empty before returning. This should be the default way of starting any scraper.
3.905469
3.296688
1.184665
other_task._source = self self._listeners.append(ChainListener(other_task)) return other_task
def chain(self, other_task)
Add a chain listener to the execution of this task. Whenever an item has been processed by the task, the registered listener task will be queued to be executed with the output of this task. Can also be written as:: pipeline = task1 > task2
7.902329
10.032165
0.787699
other_task._source = self self._listeners.append(PipeListener(other_task)) return other_task
def pipe(self, other_task)
Add a pipe listener to the execution of this task. The output of this task is required to be an iterable. Each item in the iterable will be queued as the sole argument to an execution of the listener task. Can also be written as:: pipeline = task1 | task2
7.115967
9.452774
0.752791
if not self._client_auth: self._client_auth = E.Element('merchantAuthentication') E.SubElement(self._client_auth, 'name').text = self.config.login_id E.SubElement(self._client_auth, 'transactionKey').text = self.config.transaction_key return self._client_auth
def client_auth(self)
Generate an XML element with client auth data populated.
2.922446
2.361001
1.2378
request = E.Element(method) request.set('xmlns', 'AnetApi/xml/v1/schema/AnetApiSchema.xsd') request.append(self.client_auth) return request
def _base_request(self, method)
Factory method for generating the base XML requests.
5.595049
4.840638
1.15585
try: request = urllib2.Request(self.config.environment, E.tostring(call)) request.add_header('Content-Type', 'text/xml') response = urllib2.urlopen(request).read() response = E.fromstring(response) response_json = parse_response(response) ...
def _make_call(self, call)
Make a call to the Authorize.net server with the XML.
4.150375
3.600529
1.152712
tokens = token.split_contents() tokens_num = len(tokens) if tokens_num == 1 or (tokens_num == 3 and tokens[1] == 'for'): flow_name = None if tokens_num == 3: flow_name = tokens[2] return cls(flow_name) else: raise template.TemplateSyntaxError( ...
def tag_builder(parser, token, cls, flow_type)
Helper function handling flow form tags.
3.289593
3.228094
1.019051
if len(args_dec): # simple decoration w/o parameters return signup_view(signin_view(redirect_signedin(*args_dec, **kwargs_dec))) signin = signin_view(**kwargs_dec) signup = signup_view(**kwargs_dec) return lambda *args, **kwargs: signup(signin(redirect_signedin(*args, **kwargs)))
def sitegate_view(*args_dec, **kwargs_dec)
Decorator to mark views used both for signup & sign in.
5.169162
4.613978
1.120327
assert len(binary) == 16 if not py3 and isinstance(binary, str): binary = [ord(b) for b in binary] symbols = _symbols return ''.join([ symbols[(binary[0] & 224) >> 5], symbols[binary[0] & 31], symbols[(binary[1] & 248) >> 3], symbols[((binary[1] & 7) << 2) ...
def encode_ulid_base32(binary)
Encode 16 binary bytes into a 26-character long base32 string. :param binary: Bytestring or list of bytes :return: ASCII string of 26 characters :rtype: str
1.243768
1.253366
0.992342
if len(encoded) != 26: raise InvalidULID('base32 ulid is %d characters long, expected 26' % len(encoded)) if not all(c in _symbols for c in encoded): raise InvalidULID('invalid characters in base32 ulid') b = [ord(c) for c in encoded] if b[0] < 48 or b[0] > 55: # See http...
def decode_ulid_base32(encoded)
Decode a 26-character long base32 string into the original 16 bytes. :param encoded: 26-character long string :return: 16 bytes
1.910083
1.907628
1.001287
ts_bytes = ulid_to_binary(ulid)[:6] ts_bytes = b'\0\0' + ts_bytes assert len(ts_bytes) == 8 return (struct.unpack(b'!Q', ts_bytes)[0] / 1000.)
def get_ulid_timestamp(ulid)
Get the time from an ULID as an UNIX timestamp. :param ulid: An ULID (either as UUID, base32 ULID or binary) :return: UNIX timestamp :rtype: float
3.650856
4.019618
0.90826
global _last_entropy, _last_timestamp if timestamp is None: timestamp = time.time() elif isinstance(timestamp, datetime.datetime): timestamp = calendar.timegm(timestamp.utctimetuple()) ts = int(timestamp * 1000.0) ts_bytes = _to_binary( (ts >> shift) & 0xFF for shift in...
def generate_binary_ulid(timestamp=None, monotonic=False)
Generate the bytes for an ULID. :param timestamp: An optional timestamp override. If `None`, the current time is used. :type timestamp: int|float|datetime.datetime|None :param monotonic: Attempt to ensure ULIDs are monotonically increasing. Monotonic behavior is ...
2.918951
2.908147
1.003715
return uuid.UUID(bytes=generate_binary_ulid(timestamp, monotonic=monotonic))
def generate_ulid_as_uuid(timestamp=None, monotonic=False)
Generate an ULID, but expressed as an UUID. :param timestamp: An optional timestamp override. If `None`, the current time is used. :type timestamp: int|float|datetime.datetime|None :param monotonic: Attempt to ensure ULIDs are monotonically increasing. Monotonic ...
5.382968
8.047824
0.668872
if isinstance(ulid, uuid.UUID): return ulid.bytes if isinstance(ulid, (text_type, bytes)) and len(ulid) == 26: return decode_ulid_base32(ulid) if isinstance(ulid, (bytes, bytearray)) and len(ulid) == 16: return ulid raise InvalidULID('can not convert ulid %r to binary' % uli...
def ulid_to_binary(ulid)
Convert an ULID to its binary representation. :param ulid: An ULID (either as UUID, base32 ULID or binary) :return: Bytestring of length 16 :rtype: bytes
2.417028
2.274434
1.062695
cache_path = os.path.join(scraper.config.data_path, 'cache') cache_policy = scraper.config.cache_policy cache_policy = cache_policy.lower().strip() session = ScraperSession() session.scraper = scraper session.cache_policy = cache_policy adapter = CacheControlAdapter( FileCache(...
def make_session(scraper)
Instantiate a session with the desired configuration parameters, including the cache policy.
3.365277
3.367969
0.9992
try: from lxml import html return html.fromstring(self.content) except ImportError as ie: raise DependencyException(ie)
def html(self)
Create an ``lxml``-based HTML DOM from the response. The tree will not have a root, so all queries need to be relative (i.e. start with a dot).
6.302608
4.487431
1.404503
try: from lxml import etree return etree.fromstring(self.content) except ImportError as ie: raise DependencyException(ie)
def xml(self)
Create an ``lxml``-based XML DOM from the response. The tree will not have a root, so all queries need to be relative (i.e. start with a dot).
5.311664
4.254432
1.248501
try: return super(ScraperResponse, self).json(**kwargs) except ValueError as ve: raise ParseException(ve)
def json(self, **kwargs)
Create JSON object out of the response.
7.619275
5.752654
1.32448
url_verify = url(r'^verify_email/(?P<code>\S+)/$', verify_email, name='verify_email') if VERSION >= (1, 9): return [url_verify] from django.conf.urls import patterns return patterns('', url_verify)
def get_sitegate_urls()
Returns sitegate urlpatterns, that can be attached to urlpatterns of a project: # Example from urls.py. from sitegate.toolbox import get_sitegate_urls urlpatterns = patterns('', ... url(r'^login/$', 'apps.views.login', name='login'), ... ) + get...
5.116643
5.366429
0.953454
if text is None: return None if hasattr(text, 'xpath'): text = text.xpath('string()') text = re.sub('\s+', ' ', text) return text.strip()
def collapse_whitespace(text)
Collapse all consecutive whitespace, newlines and tabs in a string into single whitespaces, and strip the outer whitespace. This will also accept an ``lxml`` element and extract all text.
3.136534
2.713411
1.155938
#Regex for matching the entire body of the type and getting top-level modifiers. self._RX_TYPE = r"\n\s*type(?P<modifiers>,\s+(public|private))?(\s*::)?\s+(?P<name>[A-Za-z0-9_]+)" + \ r"(?P<contents>.+?)end\s*type(\s+(?P=name))?" self.RE_TYPE = re.compile(self._R...
def setup_regex(self)
Sets up the patterns and compiled regex objects for parsing types.
3.479491
3.382604
1.028643
#Types don't have their signatures updated in any way that affects #the intellisense other than a name change. tmatch = self.RE_SIG.match(statement) result = (None, None, None) if tmatch is not None: name = tmatch.group("name") #We also need to ...
def parse_signature(self, statement, element, module=None)
Parses the specified line as a new version of the signature for 'element'. :arg statement: the string that has the new signature. :arg element: the code element whose signature will be changed. :arg module: for real-time module update, the module who the new element will be child to.
6.550976
6.766571
0.968138
if element.incomplete: #We need to check for the end_token so we can close up the incomplete #status for the instance. if element.end_token in statement: element.incomplete = False return #This method deals with updating the *...
def parse_line(self, statement, element, mode)
As part of real-time update, parses the statement and adjusts the attributes of the specified CustomType instance to reflect the changes. :arg statement: the lines of code that was added/removed/changed on the element after it had alread been parsed. The lines together form a single ...
13.234158
12.517324
1.057267
if mode == "delete": self._rt_members_delete(element, statement) elif mode == "insert": self._rt_members_add(element, statement)
def _rt_parse_members(self, statement, element, mode)
As part of parse_line() check for type members in the statement.
3.237766
3.157113
1.025547
members = self.vparser.parse(statement, None) for member in members: single = members[member] single.parent = element element.members[member] = single
def _rt_members_add(self, element, statement)
Finds all the member declarations in 'statement' and adds the corresponding instances to element.members.
6.547246
5.791847
1.130425
removals = self.vparser.parse(statement, None) for member in removals: if member in element.members: del element.members[member]
def _rt_members_delete(self, element, statement)
Finds all the member declarations in 'statement' and removes the corresponding instances from element.members.
5.696902
5.039579
1.130432
matches = self.RE_TYPE.finditer(module.contents) result = {} for match in matches: name = match.group("name") modifiers = match.group("modifiers") if modifiers is not None: cleanmods = re.split("[\s,]+", modifiers.strip()) ...
def parse(self, module)
Extracts all the types from the specified module body.
5.249003
4.964455
1.057317
#First, we need to see if the types children are private. if self.RE_PRIV.search(contents): modifiers.append("private contents") #Next, we need to parse out all the members of the type and their docstrings members = self.vparser.parse(contents, None) ...
def _process_type(self, name, modifiers, contents, module, match)
Processes a regex match of a type's contents.
6.464789
6.280759
1.029301
#We need to look in the parent module docstrings for this types decorating tags. key = "{}.{}".format(module.name, t.name) if key in module.predocs: t.docstring = self.docparser.to_doc(module.predocs[key][0], t.name) t.docstart, t.docend = (module.predocs...
def update_docs(self, t, module)
Updates the documentation for the specified type using the module predocs.
6.992765
6.15679
1.135781
#We only want to look at text after the contains statement match = self.RE_CONTAINS.search(contents) #It is possible for the type to not have any executables if match is not None: exectext = match.group("remainder") self._process_execs_contents(exectext,...
def _process_execs(self, contents, modulename, atype, mode="insert")
Extracts all the executable methods that belong to the type.
6.725373
6.069401
1.108079
if self.session is None: return False panel_url = u'http://myanimelist.net/panel.php' panel = self.session.get(panel_url) if 'Logout' in panel.content: return True return False
def logged_in(self)
Checks the logged-in status of the current session. Expensive (requests a page), so use sparingly! Best practice is to try a request and catch an UnauthorizedError. :rtype: bool :return: Whether or not the current session is logged-in.
5.39497
4.988263
1.081533
# POSTS a login to mal. mal_headers = { 'Host': 'myanimelist.net', } mal_payload = { 'username': self.username, 'password': self.password, 'cookie': 1, 'sublogin': 'Login' } self.session.headers.update(mal_headers) r = self.session.post(u'http://myanimelist...
def login(self)
Logs into MAL and sets cookies appropriately. :rtype: :class:`.Session` :return: The current session.
3.909663
3.901864
1.001999
def wrapper(*args, **kwargs): global _debug_indent _debug_indent += 1 result = func(*args, **kwargs) _debug_indent -= 1 return result return wrapper
def increase_indent(func)
Decorator for makin
2.146812
2.49082
0.86189
if debug_function and enable_notice: frm = inspect.stack()[1] mod = inspect.getmodule(frm[0]) if not (mod.__name__ in ignored_modules): i = ' ' * _debug_indent debug_function(NOTICE, i + 'dbg: ' + message % args)
def dbg(message, *args)
Looks at the stack, to see if a debug message should be printed.
6.877422
6.851239
1.003822
if level == NOTICE: col = Fore.GREEN elif level == WARNING: col = Fore.RED else: col = Fore.YELLOW if not is_py3: str_out = str_out.encode(encoding, 'replace') print((col + str_out + Fore.RESET))
def print_to_stdout(level, str_out)
The default debug function
3.278698
3.34184
0.981106
result = 0 for e in entry: if isinstance(e, str): sliced = e.strip(",").split(",") result += 0 if len(sliced) == 1 and sliced[0] == "" else len(sliced) return result
def count_dimensions(entry)
Counts the number of dimensions from a nested list of dimension assignments that may include function calls.
3.548641
3.510847
1.010765
result = {} for member in self.RE_MEMBERS.finditer(string): mems = self._process_member(member, parent, string) #The regex match could contain multiple members that were defined #on the same line in the code file. for onemem in mems: ...
def parse(self, string, parent)
Parses all the value code elements from the specified string.
7.129593
6.993501
1.01946
#The modifiers regex is very greedy so we have some cleaning up to do #to extract the mods. modifiers = member.group("modifiers") dimension = None if modifiers is not None: #Unfortunately, the dimension can also be specified as a modifier and ...
def _process_member(self, member, parent, string)
Extracts all the member info from the regex match; returns a ValueElements.
6.952453
6.63851
1.047291
import pyparsing nester = pyparsing.nestedExpr('(', ')') try: parsed = nester.parseString("(" + re.sub("=(>?)", " =\\1 ", defstring) + ")").asList()[0] except pyparsing.ParseException as err: from fortpy import msg repl = (parent.name, refline...
def _separate_multiple_def(self, defstring, parent, refstring, refline)
Separates the text after '::' in a variable definition to extract all the variables, their dimensions and default values.
3.717377
3.699444
1.004848
if isinstance(entry, tuple) or isinstance(entry, list): sets = [] i = 0 while i < len(entry): if isinstance(entry[i], str) and i+1 < len(entry) and isinstance(entry[i+1], list): sets.append((entry[i], entry[i+1])) ...
def _collapse_default(self, entry)
Collapses the list structure in entry to a single string representing the default value assigned to a variable or its dimensions.
2.052565
2.019382
1.016432
result = [] for entry in ready: if isinstance(entry, list): #This variable declaration has a default value specified, which is in the #second slot of the list. default = self._collapse_default(entry[1]) #For hard-coded ...
def _clean_multiple_def(self, ready)
Cleans the list of variable definitions extracted from the definition text to get hold of the dimensions and default values.
4.55465
4.226509
1.077639
if dimstring is None: suffix = modifiers.split("dimension")[1] start = modifiers.index("dimension") + len("dimension") else: suffix = dimstring start = 0 #We use a stack to monitor how many parenthesis we have traversed in the str...
def _get_dim_modifier(self, modifiers, dimstring=None)
Extracts the dimension information from the string of modifiers extracted by the regex. :arg modifiers: the list of modifiers identified by the regex.
5.311894
5.344197
0.993956
assert isinstance(starting_char, str), 'char_range: Wrong argument/s type' assert isinstance(ending_char, str), 'char_range: Wrong argument/s type' for char in range(ord(starting_char), ord(ending_char) + 1): yield chr(char)
def char_range(starting_char, ending_char)
Create a range generator for chars
2.412605
2.357252
1.023482
import re regex = r'(\w-\w)' pat = re.compile(regex) found = pat.findall(charset) result = '' if found: for element in found: for char in char_range(element[0], element[-1]): result += char return result return charset
def parse_charset(charset)
Finds out whether there are intervals to expand and creates the charset
4.267303
3.823896
1.115957
width = max( map(lambda x: x.size()[0], self.sections.itervalues())) height = sum( map(lambda x: x.size()[1], self.sections.itervalues())) return width, height
def size(self)
Return the viewable size of the Table as @tuple (x,y)
3.777209
3.289801
1.148157
if not self.ftr: return self.ftr width = self.size()[0] return re.sub( "%time", "%s\n" % time.strftime("%H:%M:%S"), self.ftr).rjust(width)
def get_ftr(self)
Process footer and return the processed string
7.188936
5.586972
1.286732
if arg == "": lines = [("The fortpy unit testing analysis shell makes it easy to analyze the results " "of multiple test cases, make plots of trends and tabulate values for use in " "other applications. This documentation will provide an overview ...
def do_help(self, arg)
Sets up the header for the help command that explains the background on how to use the script generally. Help for each command then stands alone in the context of this documentation. Although we could have documented this on the wiki, it is better served when shipped with the shell.
10.850044
10.359928
1.047309
for string in lines: for line in [string[i:i+80] for i in range(0, len(string), 80)]: msg.info(line) msg.blank()
def _fixed_width_info(self, lines)
Prints the specified string as information with fixed width of 80 chars.
3.957386
3.096043
1.278208
#This is where we update the arguments to new dictionary versions when the code #is updated with new features etc. so that the older, serialized sessions don't #break. if (self.active not in self._version_check or self.group not in self._version_check[self.active]):...
def curargs(self)
Returns the dictionary of arguments for plotting/tabulating of the active unit test and analysis group.
3.103587
3.031309
1.023844
if ">>" in args: append = True usable, filename = args.split(">>") elif ">" in args: append = False usable, filename = args.split(">") else: append = filename = None usable = args if filename is not None: ...
def _redirect_split(self, args)
Determines whether the specified shell args have a redirect specification for the output. Returns a tuple of (usable args, filename, append).
3.927608
2.579883
1.522398
if filename is None: if printfun is None: print(value) else: printfun(value) else: if append: mode = 'a' else: mode = 'w' from os import path fullpath = path....
def _redirect_output(self, value, filename=None, append=None, printfun=None)
Outputs the specified value to the console or a file depending on the redirect behavior specified. :arg value: the string text to print or save. :arg filename: the name of the file to save the text to. :arg append: when true, the text is appended to the file if it exists.
2.244685
2.695452
0.832767
if case in self.live and target in self.live[case]: lines = [] data = self.live[case][target] skeys = list(sorted(data.keys())) for key in skeys: props = ", ".join(sorted(data[key].keys())) lines.append("'{}': {}".format(ke...
def _print_dict_files(self, case, target)
Prints the file names and available properties in the specified test case's 'target' dictionary. :arg case: the identifier of the test case to print contents for. :arg target: one of ['inputs', 'outputs', 'percent']
3.880678
4.088973
0.949059
if text == "": return list(self.live.keys()) else: return [c for c in self.live if c.startswith(text)]
def _complete_cases(self, text, line, istart, iend)
Returns the completion list of possible test cases for the active unit test.
4.881258
4.28791
1.138377
usable, filename, append = self._redirect_split(arg) if usable != "": self.curargs[argid] = cast(usable) if argid in self.curargs: result = "{}: '{}'".format(argid.upper(), self.curargs[argid]) self._redirect_output(result, filename, append, msg.info)
def _set_arg_generic(self, argid, arg, cast=str)
Sets the value of the argument with the specified id using the argument passed in from the shell session.
7.332812
7.065947
1.037768
if arg == "list": msg.info("TEST CASE FILTERS") for f in self.curargs["tfilter"]: if f == "*": msg.info(" * (default, matches all)") else: msg.info(" " + f) elif arg not in self.curargs["tfilter"]:...
def do_filter(self, arg)
Sets the filter for the test cases to include in the plot/table by name. Only those test cases that include this text are included in plots, tables etc.
4.839573
4.402494
1.09928
if arg in self.curargs["tfilter"]: if arg == "*": msg.warn("The default filter cannot be removed.") else: self.curargs["tfilter"].remove(arg) self.do_filter("list")
def do_rmfilter(self, arg)
Removes the test case filter that limits which results are included in plots/tables.
7.327178
7.367723
0.994497
if "/" in var: filt, rest = var.split("/") if "|" in rest: varname, prop = rest.split("|") return prop != "" elif rest == "timing": return True else: return False else: re...
def _validate_var(self, var)
Validates the *form* only of the specified variable.
6.468016
5.990221
1.079763
if not self._validate_var(arg): msg.err("Variable {} is not a valid file name and property combination.".format(arg)) else: self.curargs["independent"] = arg
def do_indep(self, arg)
Sets the name and attribute of the independent variable for plotting/tabulating functions.
15.042042
11.42558
1.316523
vals = args.split() twin = None if len(vals) > 1: if len(vals) == 2: var, plot = vals elif len(vals) == 3: var, plot, twin = vals else: var = vals[0] plot = None if not self._validate_var(va...
def do_dep(self, args)
Adds the name and attribute of a dependent variable to the list for plotting/tabulating functions.
3.215792
2.944826
1.092014
for arg in args.split(): if arg in self.curargs["dependents"]: self.curargs["dependents"].remove(arg) if arg in self.curargs["plottypes"]: del self.curargs["plottypes"][arg] if arg in self.curargs["twinplots"]: del self...
def do_rmdep(self, args)
Removes dependent variables currently set for plotting/tabulating etc.
1.972015
1.803819
1.093244
result = [] skeys = list(sorted(self.curargs[argkey].keys())) for key in skeys: result.append("'{}' => {}".format(key, self.curargs[argkey][key])) self._redirect_output('\n'.join(result), filename, append, msg.info)
def _print_map_dict(self, argkey, filename, append)
Prints a dictionary that has variable => value mappings.
4.966951
4.779994
1.039112
usable, filename, append = self._redirect_split(arg) sargs = usable.split() if len(sargs) == 1 and sargs[0] == "list": self._print_map_dict("functions", filename, append) elif len(sargs) >= 2: defvars = self._postfix_varlist("postfix " + arg) ...
def do_postfix(self, arg)
Sets the function to apply to the values of a specific variable before plotting or tabulating values.
6.71827
6.566422
1.023125
els = line.split() result = {} if len(els) >= 2: defvars = [v for v in els if "=" in v] varlist = [] for dvar in defvars: gvar, lvar = dvar.split("=") if lvar != "": result[lvar] = gvar retur...
def _postfix_varlist(self, line)
Returns a dictionary of the global variable names (keys) and their local name for the lambda function.
4.598638
3.726719
1.233964
altered = False if arg in self.curargs["functions"]: del self.curargs["functions"][arg] altered = True elif arg == "*": for varname in list(self.curargs["functions"].keys()): del self.curargs["functions"][varname] altered =...
def do_rmpostfix(self, arg)
Removes a postfix function from a variable. See 'postfix'.
4.185728
3.651859
1.146191
if arg in self.curargs["fits"]: del self.curargs["fits"][arg] #We also need to remove the variable entry if it exists. if "timing" in arg: fitvar = "{}|fit".format(arg) else: fitvar = "{}.fit".format(arg) if fitvar in self.cura...
def do_rmfit(self, arg)
Removes a fit function from a variable. See 'fit'.
4.884845
4.759224
1.026395
cargs = self.curargs[option] result = cargs.copy() for varname in cargs: if prop in cargs[varname]: name = cargs[varname][prop] for key, val in list(defdict.items()): if val == name: cargs[varname][p...
def _get_matplot_dict(self, option, prop, defdict)
Returns a copy of the settings dictionary for the specified option in curargs with update values where the value is replaced by the key from the relevant default dictionary. :arg option: the key in self.curargs to update. :arg defdict: the default dictionary whose keys should be used ...
4.191068
3.467191
1.208779
#Since the filename is being passed directly from the argument, check its validity. if filename == "": filename = None if "x" not in self.curargs["labels"]: #Set a default x-label since we know what variable is being plotted. self.curargs["labels"]["...
def _plot_generic(self, filename=None)
Plots the current state of the shell, saving the value to the specified file if specified.
8.390941
8.31751
1.008828
usable, filename, append = self._redirect_split(arg) self.curargs["xscale"] = None self.curargs["yscale"] = None self._plot_generic(filename)
def do_plot(self, arg)
Plots the current state of the shell's independent vs. dependent variables on the same set of axes. Give filename to save to as argument or leave blank to show.
12.950629
14.533093
0.891113
if len(self.active) > 15: ids = self.active.split(".") if len(ids) > 2: module, executable, compiler = ids else: module, executable = ids compiler = "g" self.prompt = "({}*.{}*.{}:{})".format(module[0:6], ex...
def _set_def_prompt(self)
Sets the default prompt to match the currently active unit test.
5.438011
4.83756
1.124123
if arg in self.tests: self.active = arg #Create a default argument set and analysis group for the current plotting if arg not in self.args: self.args[arg] = {"default": dict(self._template_args)} self.group = "default" else...
def do_set(self, arg)
Sets the specified 'module.executable' to be the active test result to interact with.
9.147303
8.591297
1.064717
#We need to save the full paths to the staging directories for the tests that are loaded #so far; then when the session is restored, we can reparse the results. from os import path import json fullpath = path.expanduser(arg) data = { "tests": [path.a...
def do_save(self, arg)
Saves the session variables to a file so that the same analysis can be continued later.
7.560524
6.751685
1.119798
from os import path import json fullpath = path.expanduser(arg) if path.isfile(fullpath): with open(fullpath) as f: data = json.load(f) #Now, reparse the staging directories that were present in the saved session. for stagepat...
def do_load(self, arg)
Loads a saved session variables, settings and test results to the shell.
6.147498
5.243524
1.172398
from os import path fullpath = path.abspath(path.expanduser(arg)) if path.isdir(fullpath): if fullpath[-1] == "/": end = -2 else: end = -1 case = fullpath.split("/")[end] self.tests[case] = Analysis(fullpath...
def do_parse(self, arg, fullparse=False)
Parse the test results from the specified directory and load them under the name of 'module.executable ' that they were created with. E.g. parse classes.polya/
4.144856
4.078513
1.016266
#We just get the full path of the currently active test and hit reparse. full = arg == "full" from os import path fullpath = path.abspath(self.tests[self.active].stagedir) self.tests[self.active] = Analysis(fullpath, full)
def do_reparse(self, arg)
Reparses the currently active unit test to get the latest test results loaded to the console.
12.391942
10.805714
1.146795
from copy import deepcopy vals = arg.split() if len(vals) == 0 or vals[0] not in ["list", "duplicate", "add", "switch", "remove"]: self.help_group() return if vals[0] == "add": if vals[1] not in self.args[self.active]: self.ar...
def do_group(self, arg)
Creates a new analysis group with unique settings for plotting/tabulating etc. or switches the active group to the specified name.
2.13548
2.042596
1.045473
a = self.tests[self.active] args = self.curargs #We need to generate a fit for the data if there are any fits specified. if len(args["fits"]) > 0: for fit in list(args["fits"].keys()): a.fit(args["independent"], fit, args["fits"][fit], args["threshold...
def _make_fits(self)
Generates the data fits for any variables set for fitting in the shell.
8.958906
7.385436
1.21305
usable, filename, append = self._redirect_split(arg) a = self.tests[self.active] args = self.curargs self._make_fits() result = a.table(args["independent"], args["dependents"], args["threshold"], args["headings"], args["functions"]) if re...
def do_table(self, arg)
Prints the set of values for the independent vs. dependent variables in the active unit test and analysis group as a table.
13.464048
11.436912
1.177245
usable, filename, append = self._redirect_split(arg) a = self.tests[self.active] args = self.curargs splitargs = usable.split() if len(splitargs) > 0: tfilter = splitargs[0] else: tfilter = "*" outfiles = None if len(split...
def do_failures(self, arg)
Prints a list of test cases that failed for the current unit test and analysis group settings. To only check failure on specific output files, set the list of files to check as arguments.
6.725181
6.451085
1.042488
#We use their default editor (if it has been set); otherwise we can't do much of #anything and issue a warning. from os import getenv, path, system testcase, output = arg.split() target = path.join(self.tests[self.active].stagedir, "tests", testcase, ...
def do_examine(self, arg)
Opens a unit test case's .out.compare file to examine the verbose comparison report across values.
10.559701
8.70763
1.212695