code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
length = contiguous_unittest_frames = 0 while tb: length += 1 if _is_unittest_frame(tb): contiguous_unittest_frames += 1 else: contiguous_unittest_frames = 0 tb = tb.tb_next return length - contiguous_unittest_frames
def _count_relevant_tb_levels(tb)
Return the number of frames in ``tb`` before all that's left is unittest frames. Unlike its namesake in unittest, this doesn't bail out as soon as it hits a unittest frame, which means we don't bail out as soon as somebody uses the mock library, which defines ``__unittest``.
3.51
2.841269
1.235364
def unwrapping_raw_input(*args, **kwargs): wrapped_stdout = sys.stdout sys.stdout = wrapped_stdout.stream ret = orig_raw_input(*args, **kwargs) sys.stdout = wrapped_stdout return ret try: orig_raw_input = raw_input except NameError: or...
def cmdloop(self, *args, **kwargs)
Call pdb's cmdloop, making readline work. Patch raw_input so it sees the original stdin and stdout, lest readline refuse to work. The C implementation of raw_input uses readline functionality only if both stdin and stdout are from a terminal AND are FILE*s (not PyObject*s): http://bugs.python.org/...
5.023343
4.779643
1.050987
# There's no stream attr if capture plugin is enabled: out = sys.stdout.stream if hasattr(sys.stdout, 'stream') else None # Python 2.5 can't put an explicit kwarg and **kwargs in the same function # call. kwargs['stdout'] = out debugger = pdb.Pdb(*args, **kwargs) # Ordinarily (and in ...
def set_trace(*args, **kwargs)
Call pdb.set_trace, making sure it receives the unwrapped stdout. This is so we don't keep drawing progress bars over debugger output.
9.213527
8.782737
1.04905
# The calls to begin/finalize end up like this: a call to begin() on # instance A of the plugin, then a paired begin/finalize for each test # on instance B, then a final call to finalize() on instance A. # TODO: Do only if isatty. self._stderr.append(sys.stderr) ...
def begin(self)
Make some monkeypatches to dodge progress bar. Wrap stderr and stdout to keep other users of them from smearing the progress bar. Wrap some pdb routines to stop showing the bar while in the debugger.
7.752008
7.079202
1.09504
sys.stderr = self._stderr.pop() sys.stdout = self._stdout.pop() pdb.set_trace = self._set_trace.pop() pdb.Pdb.cmdloop = self._cmdloop.pop()
def finalize(self, result)
Put monkeypatches back as we found them.
4.647466
4.035626
1.151609
super(ProgressivePlugin, self).configure(options, conf) if (getattr(options, 'verbosity', 0) > 1 and getattr(options, 'enable_plugin_id', False)): # TODO: Can we forcibly disable the ID plugin? print ('Using --with-id and --verbosity=2 or higher with ' ...
def configure(self, options, conf)
Turn style-forcing on if bar-forcing is on. It'd be messy to position the bar but still have the rest of the terminal capabilities emit ''.
9.844605
10.07618
0.977018
# TODO: Play nicely with absurdly narrow terminals. (OS X's won't even # go small enough to hurt us.) # Figure out graph: GRAPH_WIDTH = 14 # min() is in case we somehow get the total test count wrong. It's tricky. num_filled = int(round(min(1.0, float(number) / ...
def update(self, test_path, number)
Draw an updated progress bar. At the moment, the graph takes a fixed width, and the test identifier takes the rest of the row, truncated from the left to fit. test_path -- the selector of the test being run number -- how many tests have been run so far, including this one
6.768436
6.311737
1.072357
with self._at_last_line(): self.stream.write(self._term.clear_eol) self.stream.flush()
def erase(self)
White out the progress bar.
9.194702
7.602623
1.209412
class ShyProgressBar(object): def __enter__(self): # My terminal has no status line, so we make one manually. bar._is_dodging += 1 # Increment before calling erase(), which # calls dodging(...
def dodging(bar)
Return a context manager which erases the bar, lets you output things, and then redraws the bar. It's reentrant.
11.204298
10.872288
1.030537
return ProgressiveResult(self._cwd, self._totalTests, self.stream, config=self.config)
def _makeResult(self)
Return a Result that doesn't print dots. Nose's ResultProxy will wrap it, and other plugins can still print stuff---but without smashing into our progress bar, care of ProgressivePlugin's stderr/out wrapping.
18.502417
10.187163
1.816248
"Run the given test case or test suite...quietly." # These parts of Nose's pluggability are baked into # nose.core.TextTestRunner. Reproduce them: wrapper = self.config.plugins.prepareTest(test) if wrapper is not None: test = wrapper wrapped = self.config.plug...
def run(self, test)
Run the given test case or test suite...quietly.
8.294556
7.595123
1.09209
# Don't bind third item to a local var; that can create # circular refs which are expensive to collect. See the # sys.exc_info() docs. exception_type, exception_value = err[:2] # TODO: In Python 3, the traceback is attached to the exception # instance through the...
def _printTraceback(self, test, err)
Print a nicely formatted traceback. :arg err: exc_info()-style traceback triple :arg test: the test that precipitated this call
7.930811
7.733935
1.025456
if is_failure or self._options.show_advisories: with self.bar.dodging(): self.stream.writeln( '\n' + (self._term.bold if is_failure else '') + '%s: %s' % (kind, nose_selector(test)) + ...
def _printHeadline(self, kind, test, is_failure=True)
Output a 1-line error summary to the stream if appropriate. The line contains the kind of error and the pathname of the test. :arg kind: The (string) type of incident the precipitated this call :arg test: The test that precipitated this call
7.267722
8.534365
0.851583
# We duplicate the errorclass handling from super rather than calling # it and monkeying around with showAll flags to keep it from printing # anything. is_error_class = False for cls, (storage, label, is_failure) in self.errorClasses.items(): if isclass(error...
def _recordAndPrintHeadline(self, test, error_class, artifact)
Record that an error-like thing occurred, and print a summary. Store ``artifact`` with the record. Return whether the test result is any sort of failure.
5.548741
5.115549
1.084682
self._recordAndPrintHeadline(test, SkipTest, reason) # Python 2.7 users get a little bonus: the reason the test was skipped. if isinstance(reason, Exception): reason = getattr(reason, 'message', None) or getattr( reason, 'args')[0] if reason and self....
def addSkip(self, test, reason)
Catch skipped tests in Python 2.7 and above. Though ``addSkip()`` is deprecated in the nose plugin API, it is very much not deprecated as a Python 2.7 ``TestResult`` method. In Python 2.7, this will get called instead of ``addError()`` for skips. :arg reason: Text describing why the te...
11.983175
12.064828
0.993232
def renderResultType(type, number, is_failure): # I'd rather hope for the best with plurals than totally punt on # being Englishlike: ret = '%s %s%s' % (number, type, 's' if number != 1 else '') if is_failure and number: ret =...
def printSummary(self, start, stop)
As a final summary, print number of tests, broken down by result.
7.853034
7.764206
1.011441
address = test_address(test) if address: file, module, rest = address if module: if rest: try: return '%s:%s%s' % (module, rest, test.test.arg or '') except AttributeError: return '%s:%s' % (module, rest) ...
def nose_selector(test)
Return the string you can pass to nose to run `test`, including argument values if the test was made by a test generator. Return "Unknown test" if it can't construct a decent path.
5.383987
4.19032
1.284863
# TODO: Canonicalize the path to remove /kitsune/../kitsune nonsense. path = abspath(path) if cwd and path.startswith(cwd): path = path[len(cwd) + 1:] # Make path relative. Remove leading slash. return path
def human_path(path, cwd)
Return the most human-readable representation of the given path. If an absolute path is given that's within the current directory, convert it to a relative path to shorten it. Otherwise, return the absolute path.
6.810225
6.815382
0.999243
if confidence > self.confidence: self.best = what self.confidence = confidence return self
def know(self, what, confidence)
Know something with the given confidence, and return self for chaining. If confidence is higher than that of what we already know, replace what we already know with what you're telling us.
4.093337
4.354264
0.940076
from .ds9_region_parser import ds9_shape_defs from .ds9_attr_parser import ds9_shape_in_comment_defs if shape_name in ds9_shape_defs: shape_def = ds9_shape_defs[shape_name] else: shape_def = ds9_shape_in_comment_defs[shape_name] initial_arg_types = shape_def.args_list arg_...
def _generate_arg_types(coordlist_length, shape_name)
Find coordinate types based on shape name and coordlist length This function returns a list of coordinate types based on which coordinates can be repeated for a given type of shap Parameters ---------- coordlist_length : int The number of coordinates or arguments used to define the shape. ...
3.149195
2.870618
1.097044
arg_types = _generate_arg_types(len(shape.coord_list), shape.name) new_coordlist = [] is_even_distance = True coord_list_iter = iter(zip(shape.coord_list, arg_types)) new_wcs = WCS(header) pixel_scales = proj_plane_pixel_scales(new_wcs) for coordinate, coordinate_type in coord_list_i...
def convert_to_imagecoord(shape, header)
Convert the coordlist of `shape` to image coordinates Parameters ---------- shape : `pyregion.parser_helper.Shape` The `Shape` to convert coordinates header : `~astropy.io.fits.Header` Specifies what WCS transformations to use. Returns ------- new_coordlist : list ...
3.737169
3.586996
1.041866
env_username = os.environ.get('JOTTACLOUD_USERNAME') env_password = os.environ.get('JOTTACLOUD_PASSWORD') netrc_auth = None try: netrc_file = netrc.netrc() netrc_auth = netrc_file.authenticators('jottacloud.com') except IOError: # .netrc file doesn't exist pass ...
def get_auth_info()
Get authentication details to jottacloud. Will first check environment variables, then the .netrc file.
2.883981
2.490314
1.158079
fileobject.seek(0) md5 = hashlib.md5() for data in iter(lambda: fileobject.read(size), b''): if not data: break if isinstance(data, six.text_type): data = data.encode('utf-8') # md5 needs a byte string md5.update(data) fileobject.seek(0) # rewind read head re...
def calculate_md5(fileobject, size=2**16)
Utility function to calculate md5 hashes while being light on memory usage. By reading the fileobject piece by piece, we are able to process content that is larger than available memory
2.508145
2.765708
0.906872
'Return datetime.datetime or None if the file isnt deleted' _d = self.folder.attrib.get('deleted', None) if _d is None: return None return dateutil.parser.parse(str(_d))
def deleted(self)
Return datetime.datetime or None if the file isnt deleted
8.182484
5.080433
1.610588
'Update state of folder from Jottacloud server' log.info("syncing %r" % self.path) self.folder = self.jfs.get(self.path) self.synced = True
def sync(self)
Update state of folder from Jottacloud server
14.452022
5.992658
2.411621
'Create a new subfolder and return the new JFSFolder' #url = '%s?mkDir=true' % posixpath.join(self.path, foldername) url = posixpath.join(self.path, foldername) params = {'mkDir':'true'} r = self.jfs.post(url, params) self.sync() return r
def mkdir(self, foldername)
Create a new subfolder and return the new JFSFolder
5.310843
3.873533
1.371059
'Delete this folder and return a deleted JFSFolder' #url = '%s?dlDir=true' % self.path params = {'dlDir':'true'} r = self.jfs.post(self.path, params) self.sync() return r
def delete(self)
Delete this folder and return a deleted JFSFolder
11.336357
6.516661
1.739596
'Deletes without possibility to restore' url = 'https://www.jottacloud.com/rest/webrest/%s/action/delete' % self.jfs.username data = {'paths[]': self.path.replace(JFS_ROOT, ''), 'web': 'true', 'ts': int(time.time()), 'authToken': 0} r = sel...
def hard_delete(self)
Deletes without possibility to restore
10.999739
9.228509
1.19193
"Move folder to a new name, possibly a whole new path" # POST https://www.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/Ny%20mappe?mvDir=/**USERNAME**/Jotta/Sync/testFolder #url = '%s?mvDir=/%s%s' % (self.path, self.jfs.username, newpath) params = {'mvDir':'/%s%s' % (self.jfs.username, newp...
def rename(self, newpath)
Move folder to a new name, possibly a whole new path
8.226263
6.933471
1.186457
'Upload a file to current folder and return the new JFSFile' close_on_done = False if isinstance(fileobj_or_path, six.string_types): filename = filename or os.path.basename(fileobj_or_path) fileobj_or_path = open(fileobj_or_path, 'rb') close_on_done = True ...
def up(self, fileobj_or_path, filename=None, upload_callback=None)
Upload a file to current folder and return the new JFSFile
2.876084
2.51894
1.141783
return JFSIncompleteFile(fileobject, jfs, parentpath) elif str(fileobject.latestRevision.state) == ProtoFile.STATE_CORRUPT: return JFSCorruptFile(fileobject, jfs, parentpath) else: raise NotImplementedError('No JFS*File support for state %r. Please file a bug!' % file...
def factory(fileobject, jfs, parentpath): # fileobject from lxml.objectify 'Class method to get the correct file class instatiated' if hasattr(fileobject, 'currentRevision'): # a normal file return JFSFile(fileobject, jfs, parentpath) elif str(fileobject.latestRevision.state) == Prot...
Class method to get the correct file class instatiated
2.724284
2.511749
1.084616
'return datetime.datetime' return dateutil.parser.parse(str(self.f.latestRevision.created))
def created(self)
return datetime.datetime
20.765596
20.850588
0.995924
'return datetime.datetime' return dateutil.parser.parse(str(self.f.latestRevision.modified))
def modified(self)
return datetime.datetime
21.778734
20.992998
1.037428
'return datetime.datetime' return dateutil.parser.parse(str(self.f.latestRevision.updated))
def updated(self)
return datetime.datetime
20.938269
19.699409
1.062888
'Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object' if not hasattr(data, 'read'): data = six.BytesIO(data)#StringIO(data) #Check that we actually know from what byte to resume. #If self.size === -1, it means we never got th...
def resume(self, data)
Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object
7.226277
6.295442
1.147859
if hasattr(self.f.latestRevision, 'size'): return int(self.f.latestRevision.size) return None
def size(self)
Bytes uploaded of the file so far. Note that we only have the file size if the file was requested directly, not if it's part of a folder listing.
8.180284
7.790932
1.049975
'Returns a generator to iterate over the file contents' #return self.jfs.stream(url='%s?mode=bin' % self.path, chunk_size=chunk_size) return self.jfs.stream(url=self.path, params={'mode':'bin'}, chunk_size=chunk_size)
def stream(self, chunk_size=64*1024)
Returns a generator to iterate over the file contents
5.552247
4.80995
1.154325
'Get a part of the file, from start byte to end byte (integers)' #return self.jfs.raw('%s?mode=bin' % self.path, return self.jfs.raw(url=self.path, params={'mode':'bin'}, # note that we deduct 1 from end because # in http Range requests, th...
def readpartial(self, start, end)
Get a part of the file, from start byte to end byte (integers)
9.006138
7.000343
1.286528
'Put, possibly replace, file contents with (new) data' if not hasattr(data, 'read'): data = six.BytesIO(data)#StringIO(data) self.jfs.up(self.path, data)
def write(self, data)
Put, possibly replace, file contents with (new) data
13.504256
7.423738
1.819064
'Restore the file' # # # As of 2016-06-15, Jottacloud.com has changed their restore api # To restore, this is what's done # # HTTP POST to https://www.jottacloud.com/web/restore/trash/list # Data: # hash:undefined # files:@0025d37be...
def restore(self)
Restore the file
11.146353
11.116839
1.002655
'Delete this file and return the new, deleted JFSFile' #url = '%s?dl=true' % self.path r = self.jfs.post(url=self.path, params={'dl':'true'}) return r
def delete(self)
Delete this file and return the new, deleted JFSFile
12.748876
6.745567
1.889963
'''Get a thumbnail as string or None if the file isnt an image size would be one of JFSFile.BIGTHUMB, .MEDIUMTHUMB, .SMALLTHUMB or .XLTHUMB''' if not self.is_image(): return None if not size in (self.BIGTHUMB, self.MEDIUMTHUMB, self.SMALLTHUMB, self.XLTHUMB): rai...
def thumb(self, size=BIGTHUMB)
Get a thumbnail as string or None if the file isnt an image size would be one of JFSFile.BIGTHUMB, .MEDIUMTHUMB, .SMALLTHUMB or .XLTHUMB
4.326509
2.463922
1.755944
'return datetime.datetime' return dateutil.parser.parse(str(self.f.currentRevision.created))
def created(self)
return datetime.datetime
21.653913
22.258432
0.972841
'return datetime.datetime' return dateutil.parser.parse(str(self.f.currentRevision.modified))
def modified(self)
return datetime.datetime
22.079351
21.774794
1.013987
'return datetime.datetime' return dateutil.parser.parse(str(self.f.currentRevision.updated))
def updated(self)
return datetime.datetime
21.852745
21.275023
1.027155
if isinstance(path, object) and hasattr(path, 'name'): log.debug("passed an object, use .'name' as path value") # passed an object, use .'name' as path value path = '/%s' % path.name c = self._jfs.get('%s%s' % (self.path, path or '/')) return c
def contents(self, path=None)
Get _all_ metadata for this device. Call this method if you have the lite/abbreviated device info from e.g. <user/>.
6.395064
6.560982
0.974711
if isinstance(mountPoint, six.string_types): # shortcut: pass a mountpoint name mountPoint = self.mountPoints[mountPoint] try: return [JFSFile(f, self, parentpath='%s/%s' % (self.path, mountPoint.name)) for f in self.contents(mountPoint).files.iterchildren()]...
def files(self, mountPoint)
Get an iterator of JFSFile() from the given mountPoint. "mountPoint" may be either an actual mountPoint element from JFSDevice.mountPoints{} or its .name.
5.942029
4.737686
1.254205
if isinstance(mountPoint, six.string_types): # shortcut: pass a mountpoint name mountPoint = self.mountPoints[mountPoint] try: return [JFSFolder(f, self, parentpath='%s/%s' % (self.path, mountPoint.name)) for f in self.contents(mountPoint).folders.iterchildre...
def folders(self, mountPoint)
Get an iterator of JFSFolder() from the given mountPoint. "mountPoint" may be either an actual mountPoint element from JFSDevice.mountPoints{} or its .name.
6.287182
4.953875
1.269144
url = posixpath.join(self.path, name) r = self._jfs.post(url, extra_headers={'content-type': 'application/x-www-form-urlencoded'}) return r
def new_mountpoint(self, name)
Create a new mountpoint
5.042586
5.03554
1.001399
'iterate over shared files and get their public URI' for f in self.sharing.files.iterchildren(): yield (f.attrib['name'], f.attrib['uuid'], 'https://www.jottacloud.com/p/%s/%s' % (self.jfs.username, f.publicURI.text))
def sharedFiles(self)
iterate over shared files and get their public URI
15.041496
10.923863
1.376939
'iterate over found files' for _f in self.searchresult.files.iterchildren(): yield ProtoFile.factory(_f, jfs=self.jfs, parentpath=unicode(_f.abspath))
def files(self)
iterate over found files
21.34132
17.272892
1.235538
'Make a GET request for url, with or without caching' if not url.startswith('http'): # relative url url = self.rootpath + url log.debug("getting url: %r, extra_headers=%r, params=%r", url, extra_headers, params) if extra_headers is None: extra_headers={} r...
def request(self, url, extra_headers=None, params=None)
Make a GET request for url, with or without caching
4.594726
3.900795
1.177895
'Make a GET request for url and return whatever content we get' r = self.request(url, extra_headers=extra_headers, params=params) # uncomment to dump raw xml # with open('/tmp/%s.xml' % time.time(), 'wb') as f: # f.write(r.content) if not r.ok: o = lxml.o...
def raw(self, url, extra_headers=None, params=None)
Make a GET request for url and return whatever content we get
4.743889
3.867418
1.22663
'Make a GET request for url and return the response content as a generic lxml.objectify object' url = self.escapeUrl(url) content = six.BytesIO(self.raw(url, params=params)) # We need to make sure that the xml fits in available memory before we parse # with lxml.objectify.fromst...
def get(self, url, params=None)
Make a GET request for url and return the response content as a generic lxml.objectify object
5.120353
4.367559
1.17236
'Take a url or some xml response from JottaCloud and wrap it up with the corresponding JFS* class' if isinstance(url_or_requests_response, requests.models.Response): # this is a raw xml response that we need to parse url = url_or_requests_response.url o = lxml.objecti...
def getObject(self, url_or_requests_response, params=None)
Take a url or some xml response from JottaCloud and wrap it up with the corresponding JFS* class
3.060956
2.579173
1.186798
'Iterator to get remote content by chunk_size (bytes)' r = self.request(url, params=params) for chunk in r.iter_content(chunk_size): yield chunk
def stream(self, url, params=None, chunk_size=64*1024)
Iterator to get remote content by chunk_size (bytes)
6.898928
3.525294
1.956979
'HTTP Post files[] or content (unicode string) to url' if not url.startswith('http'): # relative url url = self.rootpath + url log.debug('posting content (len %s) to url %s', len(content) if content is not None else '?', url) headers = self.session.headers.copy()...
def post(self, url, content='', files=None, params=None, extra_headers={}, upload_callback=None)
HTTP Post files[] or content (unicode string) to url
4.034722
3.420814
1.179462
"Upload a fileobject to path, HTTP POST-ing to up.jottacloud.com, using the JottaCloud API" url = path.replace('www.jottacloud.com', 'up.jottacloud.com') # Calculate file length fileobject.seek(0,2) contentlen = fileobject.tell() # Rewind read head to correct of...
def up(self, path, fileobject, upload_callback=None, resume_offset=None)
Upload a fileobject to path, HTTP POST-ing to up.jottacloud.com, using the JottaCloud API
4.407964
3.839821
1.147961
# at least android client also includes a "cid" with is derived from the unique device id # and encrypted with a public key in the apk. The field appears to be optional url = posixpath.join(self.rootpath, name) r = self.post(url, {'type': type}) return r
def new_device(self, name, type)
Create a new (backup) device on jottacloud. Types can be one of ['workstation', 'imac', 'laptop', 'macbook', 'ipad', 'android', 'iphone', 'windows_phone']
18.305149
19.321972
0.947375
'return generator of configured devices' return self.fs is not None and [JFSDevice(d, self, parentpath=self.rootpath) for d in self.fs.devices.iterchildren()] or [x for x in []]
def devices(self)
return generator of configured devices
15.430749
12.657845
1.219066
rp = RegionParser() ss = rp.parse(region_string) sss1 = rp.convert_attr(ss) sss2 = _check_wcs(sss1) shape_list, comment_list = rp.filter_shape2(sss2) return ShapeList(shape_list, comment_list=comment_list)
def parse(region_string)
Parse DS9 region string into a ShapeList. Parameters ---------- region_string : str Region string Returns ------- shapes : `ShapeList` List of `~pyregion.Shape`
7.570678
6.974538
1.085474
with _builtin_open(fname) as fh: region_string = fh.read() return parse(region_string)
def open(fname)
Open, read and parse DS9 region file. Parameters ---------- fname : str Filename Returns ------- shapes : `ShapeList` List of `~pyregion.Shape`
7.297069
9.994432
0.730113
rp = RegionParser() ss = rp.parse(s) sss1 = rp.convert_attr(ss) sss2 = _check_wcs(sss1) shape_list = rp.filter_shape(sss2) return ShapeList(shape_list)
def read_region(s)
Read region. Parameters ---------- s : str Region string Returns ------- shapes : `ShapeList` List of `~pyregion.Shape`
8.32997
7.474534
1.114447
rp = RegionParser() ss = rp.parse(s) sss1 = rp.convert_attr(ss) sss2 = _check_wcs(sss1) sss3 = rp.sky_to_image(sss2, header) shape_list = rp.filter_shape(sss3) return ShapeList(shape_list)
def read_region_as_imagecoord(s, header)
Read region as image coordinates. Parameters ---------- s : str Region string header : `~astropy.io.fits.Header` FITS header Returns ------- shapes : `~pyregion.ShapeList` List of `~pyregion.Shape`
6.643401
6.131523
1.083483
from pyregion.region_to_filter import as_region_filter data = hdu.data region_filter = as_region_filter(region, origin=origin) mask = region_filter.mask(data) return mask
def get_mask(region, hdu, origin=1)
Get mask. Parameters ---------- region : `~pyregion.ShapeList` List of `~pyregion.Shape` hdu : `~astropy.io.fits.ImageHDU` FITS image HDU origin : float TODO: document me Returns ------- mask : `~numpy.array` Boolean mask Examples -------- >...
4.657498
6.675756
0.697674
comment_list = self._comment_list if comment_list is None: comment_list = cycle([None]) r = RegionParser.sky_to_image(zip(self, comment_list), header) shape_list, comment_list = zip(*list(r)) return ShapeList(shape_list...
def as_imagecoord(self, header)
New shape list in image coordinates. Parameters ---------- header : `~astropy.io.fits.Header` FITS header Returns ------- shape_list : `ShapeList` New shape list, with coordinates of the each shape converted to the image coordinate us...
7.866209
6.455006
1.218621
from .mpl_helper import as_mpl_artists patches, txts = as_mpl_artists(self, properties_func, text_offset, origin=origin) return patches, txts
def get_mpl_patches_texts(self, properties_func=None, text_offset=5.0, origin=1)
Often, the regions files implicitly assume the lower-left corner of the image as a coordinate (1,1). However, the python convetion is that the array index starts from 0. By default (``origin=1``), coordinates of the returned mpl artists have coordinate shifted by (1, 1). If you do not wa...
4.421347
4.539225
0.974031
from .region_to_filter import as_region_filter if header is None: if not self.check_imagecoord(): raise RuntimeError("the region has non-image coordinate. header is required.") reg_in_imagecoord = self else: reg_in_imagecoord = self....
def get_filter(self, header=None, origin=1)
Get filter. Often, the regions files implicitly assume the lower-left corner of the image as a coordinate (1,1). However, the python convetion is that the array index starts from 0. By default (``origin=1``), coordinates of the returned mpl artists have coordinate shifted by (1, ...
4.800113
5.094519
0.942211
if hdu and header is None: header = hdu.header if hdu and shape is None: shape = hdu.data.shape region_filter = self.get_filter(header=header) mask = region_filter.mask(shape) return mask
def get_mask(self, hdu=None, header=None, shape=None)
Create a 2-d mask. Parameters ---------- hdu : `astropy.io.fits.ImageHDU` FITS image HDU header : `~astropy.io.fits.Header` FITS header shape : tuple Image shape Returns ------- mask : `numpy.array` Boolean...
2.895534
3.77973
0.766069
if len(self) < 1: print("WARNING: The region list is empty. The region file " "'{:s}' will be empty.".format(outfile)) try: outf = _builtin_open(outfile, 'w') outf.close() return except IOError as e: ...
def write(self, outfile)
Write this shape list to a region file. Parameters ---------- outfile : str File name
2.865815
2.829421
1.012863
if not current_app: log.warn(u"Got a request to check for {feature} but we're outside the request context. Returning False".format(feature=feature)) return False try: return current_app.config[FEATURE_FLAGS_CONFIG][feature] except (AttributeError, KeyError): raise NoFeatureFlagFound()
def AppConfigFlagHandler(feature=None)
This is the default handler. It checks for feature flags in the current app's configuration. For example, to have 'unfinished_feature' hidden in production but active in development: config.py class ProductionConfig(Config): FEATURE_FLAGS = { 'unfinished_feature' : False, } class Development...
6.165239
5.478366
1.125379
if current_app: feature_flagger = current_app.extensions.get(EXTENSION_NAME) if feature_flagger: return feature_flagger.check(feature) else: raise AssertionError("Oops. This application doesn't have the Flask-FeatureFlag extention installed.") else: log.warn(u"Got a request to check...
def is_active(feature)
Check if a feature is active
5.75793
5.593916
1.02932
def _is_active_feature(func): @wraps(func) def wrapped(*args, **kwargs): if not is_active(feature): url = redirect_to if redirect: url = url_for(redirect) if url: log.debug(u'Feature {feature} is off, redirecting to {url}'.format(feature=feature, url=url)...
def is_active_feature(feature, redirect_to=None, redirect=None)
Decorator for Flask views. If a feature is off, it can either return a 404 or redirect to a URL if you'd rather.
2.261881
2.01096
1.124777
app.config.setdefault(FEATURE_FLAGS_CONFIG, {}) app.config.setdefault(RAISE_ERROR_ON_MISSING_FEATURES, False) if hasattr(app, "add_template_test"): # flask 0.10 and higher has a proper hook app.add_template_test(self.check, name=self.JINJA_TEST_NAME) else: app.jinja_env.tests[se...
def init_app(self, app)
Add ourselves into the app config and setup, and add a jinja function test
3.525453
3.402788
1.036048
found = False for handler in self.handlers: try: if handler(feature): return True except StopCheckingFeatureFlags: return False except NoFeatureFlagFound: pass else: found = True if not found: message = u"No feature flag defined ...
def check(self, feature)
Loop through all our feature flag checkers and return true if any of them are true. The order of handlers matters - we will immediately return True if any handler returns true. If you want to a handler to return False and stop the chain, raise the StopCheckingFeatureFlags exception.
4.659742
3.732969
1.248267
local_attr = [], {} for kv in attr_list: keyword = kv[0] if len(kv) == 1: local_attr[0].append(keyword) continue elif len(kv) == 2: value = kv[1] elif len(kv) > 2: value = kv[1:] if keyword == 'tag': local_...
def get_attr(attr_list, global_attrs)
Parameters ---------- attr_list : list A list of (keyword, value) tuple pairs global_attrs : tuple(list, dict) Global attributes which update the local attributes
2.283107
2.402114
0.950457
for func in self._caches: cache = {} for key in self._caches[func].keys(): log.debug("cache key %s for func %s", key, func) if path in key[0]: log.debug("del cache key %s", key) del self._caches[func][key]
def yank_path(self, path)
Clear cache of results from a specific path
4.020822
3.63208
1.10703
"A wrapper of JFS.getObject(), with some tweaks that make sense in a file system." if is_blacklisted(path): raise JottaFuseError('Blacklisted file, refusing to retrieve it') return self.client.getObject(path)
def _getpath(self, path)
A wrapper of JFS.getObject(), with some tweaks that make sense in a file system.
25.201962
7.918639
3.182613
"Run after a read or write operation has finished. This is where we upload on writes" #print "release! inpath:", path in self.__newfiles.keys() # if the path exists in self.__newfiles.keys(), we have a new version to upload try: f = self.__newfiles[path] # make a local shortc...
def release(self, path, fh)
Run after a read or write operation has finished. This is where we upload on writes
10.867908
7.589095
1.432043
"Return a statvfs(3) structure, for stat and df and friends" # from fuse.py source code: # # class c_statvfs(Structure): # _fields_ = [ # ('f_bsize', c_ulong), # preferred size of file blocks, in bytes # ('f_frsize', c_ulong), # fundamental size of file blcoks, in...
def statfs(self, path)
Return a statvfs(3) structure, for stat and df and friends
3.194266
2.943704
1.085118
log.info("***SYMLINK* %s (link) -> %s (existing)", linkname, existing_file) sourcepath = os.path.abspath(existing_file) if not os.path.exists(sourcepath): # broken symlink raise OSError(errno.ENOENT, '') try: with open(sourcepath) as sourcefile: ...
def symlink(self, linkname, existing_file)
Called to create a symlink `target -> source` (e.g. ln -s existing_file linkname). In jottafuse, we upload the _contents_ of source. This is a handy shortcut for streaming uploads directly from disk, without reading the file into memory first
4.398332
4.129224
1.065171
"Download existing path, truncate and reupload" try: f = self._getpath(path) except JFS.JFSError: raise OSError(errno.ENOENT, '') if isinstance(f, (JFS.JFSFile, JFS.JFSFolder)) and f.is_deleted(): raise OSError(errno.ENOENT) data = StringIO(f.r...
def truncate(self, path, length, fh=None)
Download existing path, truncate and reupload
5.841814
5.134722
1.137708
'Convert bytestring from command line to unicode, using default file system encoding' if six.PY3: return bytestring unicode_string = bytestring.decode(sys.getfilesystemencoding()) return unicode_string
def commandline_text(bytestring)
Convert bytestring from command line to unicode, using default file system encoding
5.931304
3.575096
1.659062
for shape, comment in shape_list: if isinstance(shape, Shape) and \ (shape.coord_format not in image_like_coordformats): new_coords = convert_to_imagecoord(shape, header) l1n = copy.copy(shape) l1n.coord_list = new_coor...
def sky_to_image(shape_list, header)
Converts a `ShapeList` into shapes with coordinates in image coordinates Parameters ---------- shape_list : `pyregion.ShapeList` The ShapeList to convert header : `~astropy.io.fits.Header` Specifies what WCS transformations to use. Yields -------...
3.062598
3.022346
1.013318
'Called when a file (or directory) is modified. ' super(ArchiveEventHandler, self).on_modified(event) src_path = event.src_path if event.is_directory: if not platform.is_darwin(): log.info("event is a directory, safe to ignore") return ...
def on_modified(self, event, dry_run=False, remove_uploaded=True)
Called when a file (or directory) is modified.
8.718749
8.633512
1.009873
'Called when a file (or directory) is created. ' super(ArchiveEventHandler, self).on_created(event) log.info("created: %s", event)
def on_created(self, event, dry_run=False, remove_uploaded=True)
Called when a file (or directory) is created.
7.605909
6.395388
1.18928
'Code to upload' # are we getting a symbolic link? if os.path.islink(src_path): sourcefile = os.path.normpath(os.path.join(self.topdir, os.readlink(src_path))) if not os.path.exists(sourcefile): # broken symlink log.error("broken sy...
def _new(self, src_path, dry_run=False, remove_uploaded=False)
Code to upload
2.567373
2.521152
1.018333
y_axis_rot = _calculate_rotation_angle(reg_coordinate_frame, header) return angle - y_axis_rot
def _estimate_angle(angle, reg_coordinate_frame, header)
Transform an angle into a different frame Parameters ---------- angle : float, int The number of degrees, measured from the Y axis in origin's frame reg_coordinate_frame : str Coordinate frame in which ``angle`` is defined header : `~astropy.io.fits.Header` instance Header...
4.596137
5.750442
0.799267
new_wcs = WCS(header) region_frame = SkyCoord( '0d 0d', frame=reg_coordinate_frame, obstime='J2000') region_frame = SkyCoord( '0d 0d', frame=reg_coordinate_frame, obstime='J2000', equinox=region_frame.equinox) origin = SkyCoord.from_pixel( ...
def _calculate_rotation_angle(reg_coordinate_frame, header)
Calculates the rotation angle from the region to the header's frame This attempts to be compatible with the implementation used by SAOImage DS9. In particular, this measures the rotation of the north axis as measured at the center of the image, and therefore requires a `~astropy.io.fits.Header` object ...
2.515988
2.51569
1.000119
log.debug('Create SyncFile from %s', repr(f)) log.debug('Got encoded filename %r, joining with dirpath %r', _encode_filename_to_filesystem(f), dirpath) return SyncFile(localpath=os.path.join(dirpath, _encode_filename_to_filesystem(f)), jottapath=posixpath.join(_decode_filename_to_unic...
def sf(f, dirpath, jottapath)
Create and return a SyncFile tuple from filename. localpath will be a byte string with utf8 code points jottapath will be a unicode string
4.881586
4.142564
1.178397
log.debug("get_jottapath %r %r %r", localtopdir, dirpath, jottamountpoint) normpath = posixpath.normpath(posixpath.join(jottamountpoint, posixpath.basename(localtopdir), posixpath.relpath(dirpath, localtopdir))) return _decode_filename_to_unicode(normpath)
def get_jottapath(localtopdir, dirpath, jottamountpoint)
Translate localtopdir to jottapath. Returns unicode string
3.303136
3.157577
1.046098
log.debug("is_file %r", jottapath) try: jf = JFS.getObject(jottapath) except JFSNotFoundError: return False return isinstance(jf, JFSFile)
def is_file(jottapath, JFS)
Check if a file exists on jottacloud
3.649627
3.855658
0.946564
log.debug("filelist %r", jottapath) try: jf = JFS.getObject(jottapath) except JFSNotFoundError: return set() # folder does not exist, so pretend it is an empty folder if not isinstance(jf, JFSFolder): return False return set([f.name for f in jf.files() if not f.is_delete...
def filelist(jottapath, JFS)
Get a set() of files from a jottapath (a folder)
4.349383
4.024195
1.080808
logging.debug("folderlist %r", jottapath) try: jf = JFS.getObject(jottapath) except JFSNotFoundError: return set() # folder does not exist, so pretend it is an empty folder if not isinstance(jf, JFSFolder): return False return set([f.name for f in jf.folders() if not f.i...
def folderlist(jottapath, JFS)
Get a set() of folders from a jottapath (a folder)
4.27432
3.976429
1.074914
def excluded(unicodepath, fname): fpath = os.path.join(unicodepath, _decode_filename_to_unicode(fname)) # skip FIFOs, block devices, character devices and the like, see bug#129 mode = os.stat(fpath).st_mode if not (stat.S_ISREG(mode) or stat.S_ISLNK(mode) or ...
def compare(localtopdir, jottamountpoint, JFS, followlinks=False, exclude_patterns=None)
Make a tree of local files and folders and compare it with what's currently on JottaCloud. For each folder, yields: dirpath, # byte string, full path onlylocal, # set(), files that only exist locally, i.e. newly added files that don't exist online, onlyremote, # set(), files that only exist...
3.342094
3.042057
1.09863
'''Get bytestring filename and return unicode. First, try to decode from default file system encoding If that fails, use ``chardet`` module to guess encoding. As a last resort, try to decode as utf-8. If the argument already is unicode, return as is''' log.debug('_decode_filename_to_unicode(%s...
def _decode_filename_to_unicode(f)
Get bytestring filename and return unicode. First, try to decode from default file system encoding If that fails, use ``chardet`` module to guess encoding. As a last resort, try to decode as utf-8. If the argument already is unicode, return as is
3.395042
2.394148
1.418058
'''Get a unicode filename and return bytestring, encoded to file system default. If the argument already is a bytestring, return as is''' log.debug('_encode_filename_to_filesystem(%s)', repr(f)) if isinstance(f, str): return f try: return f.encode(sys.getfilesystemencoding()) ex...
def _encode_filename_to_filesystem(f)
Get a unicode filename and return bytestring, encoded to file system default. If the argument already is a bytestring, return as is
4.942691
2.370736
2.084876
with open(localfile) as lf: _new = JFS.up(jottapath, lf) return _new
def new(localfile, jottapath, JFS)
Upload a new file from local disk (doesn't exist on JottaCloud). Returns JottaFile object
6.971396
10.507373
0.663477
with open(localfile) as lf: _complete = jottafile.resume(lf) return _complete
def resume(localfile, jottafile, JFS)
Continue uploading a new file from local file (already exists on JottaCloud
8.011063
7.979871
1.003909
jf = JFS.getObject(jottapath) lf_hash = getxattrhash(localfile) # try to read previous hash, stored in xattr if lf_hash is None: # no valid hash found in xattr, with open(localfile) as lf: lf_hash = calculate_md5(lf) # (re)calculate it if type(jf) == JFSIncompleteF...
def replace_if_changed(localfile, jottapath, JFS)
Compare md5 hash to determine if contents have changed. Upload a file from local disk and replace file on JottaCloud if the md5s differ, or continue uploading if the file is incompletely uploaded. Returns the JottaFile object
5.861917
5.536133
1.058847