code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
regexps = ( # e.g. "+++ b/foo/bar" r'^\+\+\+ b/(.*)', # e.g. "+++ /dev/null" r'^\+\+\+ (.*)', ) for regexp in regexps: r = re.compile(regexp, re.MULTILINE) match = r.search(diff_part) if match is not None: return match.groups()[0] ...
def get_new_filename(diff_part)
Returns the filename for the updated file in a diff part.
3.51419
3.364843
1.044384
old_sha = get_old_sha(diff_part) old_filename = get_old_filename(diff_part) old_contents = get_old_contents(old_sha, old_filename) new_filename = get_new_filename(diff_part) new_contents = get_new_contents(new_filename) return old_contents, new_contents
def get_contents(diff_part)
Returns a tuple of old content and new content.
1.793876
1.687946
1.062757
vault = VaultLib(get_vault_password(password_file)) old_contents, new_contents = get_contents(diff_part) if vault.is_encrypted(old_contents): old_contents = vault.decrypt(old_contents) if vault.is_encrypted(new_contents): new_contents = vault.decrypt(new_contents) return old_con...
def decrypt_diff(diff_part, password_file=None)
Diff part is a string in the format: diff --git a/group_vars/foo b/group_vars/foo index c09080b..0d803bb 100644 --- a/group_vars/foo +++ b/group_vars/foo @@ -1,32 +1,33 @@ $ANSIBLE_VAULT;1.1;AES256 -613166623637303132306264323036623163303230643738666164366235656...
2.438786
2.330087
1.04665
rp = np.atleast_1d(rp) sq2 = np.sqrt(2) bins = np.array([1/sq2,1,sq2,2,2*sq2, 4,4*sq2,8,8*sq2, 16,16*sq2]) rates = np.array([0,0.155,0.155,0.165,0.17,0.065,0.02,0.01,0.012,0.01,0.002,0]) return rates[np.digitize(rp,bins)]
def fressin_occurrence(rp)
Occurrence rates per bin from Fressin+ (2013)
3.027208
2.793272
1.08375
cache = {} if os.path.exists(cachefile): with open(cachefile) as f: for line in f: line = line.split() if len(line) == 2: try: cache[int(line[0])] = float(line[1]) except: ...
def _loadcache(cachefile)
Returns a dictionary resulting from reading a likelihood cachefile
1.783983
1.726592
1.03324
logging.info('Fitting trapezoid models for {}...'.format(self.model)) if msg is None: msg = '{}: '.format(self.model) n = len(self.stars) deps, durs, slopes = (np.zeros(n), np.zeros(n), np.zeros(n)) secs = np.zeros(n, dtype=bool) dsec = np.zeros(n) ...
def fit_trapezoids(self, MAfn=None, msg=None, use_pbar=True, **kwargs)
Fit trapezoid shape to each eclipse in population For each instance in the population, first the correct, physical Mandel-Agol transit shape is simulated, and then this curve is fit with a trapezoid model :param MAfn: :class:`transit_basic.MAInterpolationFunction` object. ...
2.764055
2.769227
0.998132
#TODO: incorporate eccentricity/omega for exact calculation? s = self.stars return ((s['radius_1'] + s['radius_2'])*RSUN / (semimajor(s['P'],s['mass_1'] + s['mass_2'])*AU))
def eclipseprob(self)
Array of eclipse probabilities.
12.691862
12.003167
1.057376
try: name = SHORT_MODELNAMES[self.model] #add index if specific model is indexed if hasattr(self,'index'): name += '-{}'.format(self.index) return name except KeyError: raise KeyError('No short name for model: %s' % ...
def modelshort(self)
Short version of model name Dictionary defined in ``populations.py``:: SHORT_MODELNAMES = {'Planets':'pl', 'EBs':'eb', 'HEBs':'heb', 'BEBs':'beb', 'Blended Planets':'bpl', 'Specific BEB':'sbeb', ...
6.315187
4.910017
1.286184
self.apply_constraint(UpperLimit(self.secondary_depth, thresh, name='secondary depth'))
def constrain_secdepth(self, thresh)
Constrain the observed secondary depth to be less than a given value :param thresh: Maximum allowed fractional depth for diluted secondary eclipse depth
13.16184
15.688092
0.83897
prior = self.prob * self.selectfrac for f in self.priorfactors: prior *= self.priorfactors[f] return prior
def prior(self)
Model prior for particular model. Product of eclipse probability (``self.prob``), the fraction of scenario that is allowed by the various constraints (``self.selectfrac``), and all additional factors in ``self.priorfactors``.
9.161566
3.586035
2.55479
for kw in kwargs: if kw in self.priorfactors: logging.error('%s already in prior factors for %s. use change_prior function instead.' % (kw,self.model)) continue else: self.priorfactors[kw] = kwargs[kw] logging.info...
def add_priorfactor(self,**kwargs)
Adds given values to priorfactors If given keyword exists already, error will be raised to use :func:`EclipsePopulation.change_prior` instead.
3.397038
3.006712
1.129818
for kw in kwargs: if kw in self.priorfactors: self.priorfactors[kw] = kwargs[kw] logging.info('{0} changed to {1} for {2} model'.format(kw,kwargs[kw], self.model))
def change_prior(self, **kwargs)
Changes existing priorfactors. If given keyword isn't already in priorfactors, then will be ignored.
3.919863
3.38765
1.157104
if self.sklearn_kde: #TODO: fix preprocessing pts = np.array([(logd - self.mean_logdepth)/self.std_logdepth, (dur - self.mean_dur)/self.std_dur, (slope - self.mean_slope)/self.std_slope]) return self.kde.score_s...
def _density(self, logd, dur, slope)
Evaluate KDE at given points. Prepares data according to whether sklearn or scipy KDE in use. :param log, dur, slope: Trapezoidal shape parameters.
3.293381
3.032983
1.085855
if not hasattr(self,'kde'): self._make_kde() if cachefile is None: cachefile = self.lhoodcachefile if cachefile is None: cachefile = 'lhoodcache.dat' lhoodcache = _loadcache(cachefile) key = hashcombine(self, trsig) i...
def lhood(self, trsig, recalc=False, cachefile=None)
Returns likelihood of transit signal Returns sum of ``trsig`` MCMC samples evaluated at ``self.kde``. :param trsig: :class:`vespa.TransitSignal` object. :param recalc: (optional) Whether to recalculate likelihood (if calculation is cached). ...
3.531138
3.663095
0.963977
texp = self.cadence s = self.stars.iloc[i] e = s['ecc'] P = s['P'] if secondary: mu1, mu2 = s[['u1_2', 'u2_2']] w = np.mod(np.deg2rad(s['w']) + np.pi, 2*np.pi) mass_central, radius_central = s[['mass_2','radius_2']] mass_b...
def eclipse_new(self, i, secondary=False, npoints=200, width=3, texp=None)
Returns times and fluxes of eclipse i (centered at t=0)
3.184959
3.064017
1.039472
with pd.HDFStore(filename) as store: if '{}/starmodel'.format(path) in store: new._starmodel = None new._starmodel_file = filename new._starmodel_path = '{}/starmodel'.format(path) except: pass try: ...
def load_hdf(cls, filename, path=''): #perhaps this doesn't need to be written? new = StarPopulation.load_hdf(filename, path=path) #setup lazy loading of starmodel if present try
Loads EclipsePopulation from HDF file Also runs :func:`EclipsePopulation._make_kde` if it can. :param filename: HDF file :param path: (optional) Path within HDF file
5.274835
6.305353
0.836565
new = copy.deepcopy(self) N = len(new.stars) inds = np.random.randint(N, size=N) # Resample stars new.stars = new.stars.iloc[inds].reset_index() # Resample constraints if hasattr(new, '_constraints'): for c in new._constraints: ...
def resample(self)
Returns a copy of population with stars resampled (with replacement). Used in bootstrap estimate of FPP uncertainty. TODO: check to make sure constraints properly copied!
3.591156
2.986898
1.202303
cs = [] for pop in self.poplist: cs += [c for c in pop.constraints] return list(set(cs))
def constraints(self)
Unique list of constraints among all populations in set.
6.505494
3.921102
1.659098
if os.path.exists(filename) and overwrite: os.remove(filename) for pop in self.poplist: name = pop.modelshort pop.save_hdf(filename, path='{}/{}'.format(path,name), append=True)
def save_hdf(self, filename, path='', overwrite=False)
Saves PopulationSet to HDF file.
5.04492
4.671677
1.079895
with pd.HDFStore(filename) as store: models = [] types = [] for k in store.keys(): m = re.search('/(\S+)/stars', k) if m: models.append(m.group(1)) types.append(store.get_storer(m.group(0)).attrs...
def load_hdf(cls, filename, path='')
Loads PopulationSet from file
3.934897
3.811695
1.032322
if pop.model in self.modelnames: raise ValueError('%s model already in PopulationSet.' % pop.model) self.modelnames.append(pop.model) self.shortmodelnames.append(pop.modelshort) self.poplist.append(pop)
def add_population(self,pop)
Adds population to PopulationSet
4.151437
3.569116
1.163156
iremove=None for i in range(len(self.poplist)): if self.modelnames[i]==self.poplist[i].model: iremove=i if iremove is not None: self.modelnames.pop(i) self.shortmodelnames.pop(i) self.poplist.pop(i)
def remove_population(self,pop)
Removes population from PopulationSet
3.414071
3.397018
1.00502
d = {} i=0 n = len(self.constraints) for c in self.constraints: #self.colordict[c] = colors[i % 6] d[c] = cm.jet(1.*i/n) i+=1 return d
def colordict(self)
Dictionary holding colors that correspond to constraints.
4.07218
3.429937
1.187246
priorfactors = {} for pop in self.poplist: for f in pop.priorfactors: if f in priorfactors: if pop.priorfactors[f] != priorfactors[f]: raise ValueError('prior factor %s is inconsistent!' % f) else: ...
def priorfactors(self)
Combinartion of priorfactors from all populations
2.860694
2.464988
1.16053
for kw,val in kwargs.items(): if kw=='area': logging.warning('cannot change area in this way--use change_maxrad instead') continue for pop in self.poplist: k = {kw:val} pop.change_prior(**k)
def change_prior(self,**kwargs)
Changes prior factor(s) in all populations
8.710075
7.164235
1.215772
if '{} band transit'.format(band) not in self.constraints: self.constraints.append('{} band transit'.format(band)) for pop in self.poplist: pop.apply_multicolor_transit(band,depth)
def apply_multicolor_transit(self,band,depth)
Applies constraint corresponding to measuring transit in different band This is not implemented yet.
3.893937
3.72842
1.044393
if not isinstance(newrad, Quantity): newrad = newrad * u.arcsec #if 'Rsky' not in self.constraints: # self.constraints.append('Rsky') for pop in self.poplist: if not pop.is_specific: try: pop.maxrad = newrad ...
def set_maxrad(self,newrad)
Sets max allowed radius in populations. Doesn't operate via the :class:`stars.Constraint` protocol; rather just rescales the sky positions for the background objects and recalculates sky area, etc.
4.498497
4.130103
1.089197
raise NotImplementedError if 'bright blend limit' not in self.constraints: self.constraints.append('bright blend limit') for pop in self.poplist: if not hasattr(pop,'dmaglim') or pop.is_specific: continue if dmaglim is None: ...
def apply_dmaglim(self,dmaglim=None)
Applies a constraint that sets the maximum brightness for non-target star :func:`stars.StarPopulation.set_dmaglim` not yet implemented.
3.83956
3.484067
1.102034
if 'RV monitoring' not in self.constraints: self.constraints.append('RV monitoring') for pop in self.poplist: if not hasattr(pop,'dRV'): continue pop.apply_trend_constraint(limit, dt, **kwargs) self.trend_limit = limit self.tre...
def apply_trend_constraint(self, limit, dt, **kwargs)
Applies constraint corresponding to RV trend non-detection to each population See :func:`stars.StarPopulation.apply_trend_constraint`; all arguments passed to that function for each population.
4.712847
3.673836
1.282814
if 'secondary depth' not in self.constraints: self.constraints.append('secondary depth') for pop in self.poplist: if not isinstance(pop, EclipsePopulation_Px2): pop.apply_secthresh(secthresh, **kwargs) self.secthresh = secthresh
def apply_secthresh(self, secthresh, **kwargs)
Applies secondary depth constraint to each population See :func:`EclipsePopulation.apply_secthresh`; all arguments passed to that function for each population.
6.507725
3.959891
1.64341
if 'odd-even' not in self.constraints: self.constraints.append('odd-even') for pop in self.poplist: if isinstance(pop, EclipsePopulation_Px2): pop.constrain_oddeven(diff, **kwargs) self.oddeven_diff = diff
def constrain_oddeven(self, diff, **kwargs)
Constrains the difference b/w primary and secondary to be < diff
5.300292
5.124073
1.034391
if prop not in self.constraints: self.constraints.append(prop) for pop in self.poplist: try: pop.constrain_property(prop,**kwargs) except AttributeError: logging.info('%s model does not have property stars.%s (constraint not ap...
def constrain_property(self,prop,**kwargs)
Constrains property for each population See :func:`vespa.stars.StarPopulation.constrain_property`; all arguments passed to that function for each population.
5.136923
4.544676
1.130317
for pop in self.poplist: pop.replace_constraint(name,**kwargs) if name not in self.constraints: self.constraints.append(name)
def replace_constraint(self,name,**kwargs)
Replaces removed constraint in each population. See :func:`vespa.stars.StarPopulation.replace_constraint`
4.147045
4.310919
0.961986
for name in names: for pop in self.poplist: if name in pop.constraints: pop.remove_constraint(name) else: logging.info('%s model does not have %s constraint' % (pop.model,name)) if name in self.constraints: ...
def remove_constraint(self,*names)
Removes constraint from each population See :func:`vespa.stars.StarPopulation.remove_constraint
3.25995
3.610072
0.903015
if type(cc)==type(''): pass if cc.name not in self.constraints: self.constraints.append(cc.name) for pop in self.poplist: if not pop.is_specific: try: pop.apply_cc(cc, **kwargs) except AttributeError...
def apply_cc(self, cc, **kwargs)
Applies contrast curve constraint to each population See :func:`vespa.stars.StarPopulation.apply_cc`; all arguments passed to that function for each population.
4.900405
4.423647
1.107775
if 'secondary spectrum' not in self.constraints: self.constraints.append('secondary spectrum') for pop in self.poplist: if not pop.is_specific: try: pop.apply_vcc(vcc) except: logging.info('VCC const...
def apply_vcc(self,vcc)
Applies velocity contrast curve constraint to each population See :func:`vespa.stars.StarPopulation.apply_vcc`; all arguments passed to that function for each population.
5.998444
5.373201
1.116363
if galactic: l, b = ra, dec else: try: c = SkyCoord(ra,dec) except UnitsError: c = SkyCoord(ra,dec,unit='deg') l,b = (c.galactic.l.value,c.galactic.b.value) if os.path.isabs(filename): folder = '' if not re.search('\.dat$',filename):...
def get_trilegal(filename,ra,dec,folder='.', galactic=False, filterset='kepler_2mass',area=1,maglim=27,binaries=False, trilegal_version='1.6',sigma_AV=0.1,convert_h5=True)
Runs get_trilegal perl script; optionally saves output into .h5 file Depends on a perl script provided by L. Girardi; calls the web form simulation, downloads the file, and (optionally) converts to HDF format. Uses A_V at infinity from :func:`utils.get_AV_infinity`. .. note:: Would be de...
2.549277
2.489401
1.024052
log = logging.getLogger('client.py') # Set the log format and log level try: debug = self.params["debug"] log.setLevel(logging.DEBUG) except KeyError: log.setLevel(logging.INFO) # Set the log format. stream = logging.StreamHa...
def log_wrapper(self)
Wrapper to set logging parameters for output
2.674009
2.587291
1.033517
try: lo, hi = struct.unpack('<QQ', b32decode(encoded.upper() + '======')) except struct.error: raise ValueError('Cannot decode {!r}'.format(encoded)) return (hi << 64) + lo
def decode_setid(encoded)
Decode setid as uint128
4.881587
4.511592
1.08201
hi, lo = divmod(uint128, 2**64) return b32encode(struct.pack('<QQ', lo, hi))[:-6].lower()
def encode_setid(uint128)
Encode uint128 setid as stripped b32encoded string
4.804523
3.899596
1.232057
if watermark.type() != ImageType.TrueColorMatteType: watermark.type(ImageType.TrueColorMatteType) depth = 255 - int(255 * opacity) watermark.quantumOperator(ChannelType.OpacityChannel, QuOp.MaxQuantumOp, depth)
def _reduce_opacity(self, watermark, opacity)
Returns an image with reduced opacity. Converts image to RGBA if needs. Simple watermark.opacity(65535 - int(65535 * opacity) would not work for images with the Opacity channel (RGBA images). So we have to convert RGB or any other type to RGBA in this case
11.189602
9.496698
1.178262
collections = self.collections for relation in [x for col in collections.values() for x in col.model.relations.values()]: db.session.query(relation)\ .filter(~relation.listing.any())\ .delete(synchronize_session=...
def cleanup_relations(self)
Cleanup listing relations
4.672328
4.214877
1.108532
if not any([discarded, unused_tags]): click.echo(ctx.get_help()) ctx.exit(1) site = create_app().site if discarded: site.cleanup_discarded() if unused_tags: site.cleanup_tags() site.cleanup_relations()
def marvcli_cleanup(ctx, discarded, unused_tags)
Cleanup unused tags and discarded datasets.
4.241529
4.134777
1.025818
from flask_cors import CORS app = create_app(push=False) app.site.load_for_web() CORS(app) class IPDBMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): from ipdb import launch_ipdb_on_exception ...
def marvcli_develop_server(port, public)
Run development webserver. ATTENTION: By default it is only served on localhost. To run it within a container and access it from the outside, you need to forward the port and tell it to listen on all IPs instead of only localhost.
2.462296
2.601628
0.946445
mark_discarded = not any([all_nodes, nodes, tags, comments]) site = create_app().site setids = parse_setids(datasets) if tags or comments: if confirm: msg = ' and '.join(filter(None, ['tags' if tags else None, 'comments' if comments...
def marvcli_discard(datasets, all_nodes, nodes, tags, comments, confirm)
Mark DATASETS to be discarded or discard associated data. Without any options the specified datasets are marked to be discarded via `marv cleanup --discarded`. Use `marv undiscard` to undo this operation. Otherwise, selected data associated with the specified datasets is discarded right away.
3.164593
3.400198
0.930709
create_app() setids = parse_setids(datasets, discarded=True) dataset = Dataset.__table__ stmt = dataset.update()\ .where(dataset.c.setid.in_(setids))\ .values(discarded=False) db.session.execute(stmt) db.session.commit()
def marvcli_undiscard(datasets)
Undiscard DATASETS previously discarded.
4.641405
4.464592
1.039603
data = json.load(file) site = create_app().site site.restore_database(**data)
def marvcli_restore(file)
Restore previously dumped database
10.51256
10.668139
0.985416
if not any([collections, discarded, list_tags, outdated, path, tags]): click.echo(ctx.get_help()) ctx.exit(1) sep = '\x00' if null else '\n' site = create_app().site if '*' in collections: collections = None else: for col in collections: if col not...
def marvcli_query(ctx, list_tags, collections, discarded, outdated, path, tags, null)
Query datasets. Use --collection=* to list all datasets across all collections.
2.967161
3.121361
0.950598
if collections and datasets: ctx.fail('--collection and DATASETS are mutually exclusive') if list_dependent and not selected_nodes: ctx.fail('--list-dependent needs at least one selected --node') if not any([datasets, collections, list_nodes]): click.echo(ctx.get_help()) ...
def marvcli_run(ctx, datasets, deps, excluded_nodes, force, force_dependent, force_deps, keep, keep_going, list_nodes, list_dependent, selected_nodes, update_detail, update_listing, cachesize, collections)
Run nodes for selected datasets. Datasets are specified by a list of set ids, or --collection <name>, use --collection=* to run for all collections. --node in conjunction with --collection=* will pick those collections for which the selected nodes are configured. Set ids may be abbreviated to any ...
2.866817
2.855148
1.004087
if not any([add, remove]) or not datasets: click.echo(ctx.get_help()) ctx.exit(1) app = create_app() setids = parse_setids(datasets) app.site.tag(setids, add, remove)
def marvcli_tag(ctx, add, remove, datasets)
Add or remove tags to datasets
4.627461
4.642457
0.99677
app = create_app() try: db.session.query(User).filter(User.name==user).one() except NoResultFound: click.echo("ERROR: No such user '{}'".format(user), err=True) sys.exit(1) ids = parse_setids(datasets, dbids=True) app.site.comment(user, message, ids)
def marvcli_comment_add(user, message, datasets)
Add comment as user for one or more datasets
4.484996
4.305192
1.041765
app = create_app() ids = parse_setids(datasets, dbids=True) comments = db.session.query(Comment)\ .options(db.joinedload(Comment.dataset))\ .filter(Comment.dataset_id.in_(ids)) for comment in sorted(comments, key=lambda x: (x.dataset._setid, x.id)):...
def marvcli_comment_list(datasets)
Lists comments for datasets. Output: setid comment_id date time author message
3.796648
3.648892
1.040493
app = create_app() db.session.query(Comment)\ .filter(Comment.id.in_(ids))\ .delete(synchronize_session=False) db.session.commit()
def marvcli_comment_rm(ids)
Remove comments. Remove comments by id as given in second column of: marv comment list
2.662788
3.137707
0.848641
if not re.match(r'[0-9a-zA-Z\-_\.@+]+$', username): click.echo('Invalid username: {}'.format(username), err=True) click.echo('Must only contain ASCII letters, numbers, dash, underscore and dot', err=True) sys.exit(1) if password is None: password = click.p...
def marvcli_user_add(ctx, username, password)
Add a user
2.714594
2.782683
0.975531
app = create_app() for name in db.session.query(User.name).order_by(User.name): click.echo(name[0])
def marvcli_user_list()
List existing users
3.958092
3.988631
0.992343
app = create_app() try: app.um.user_pw(username, password) except ValueError as e: ctx.fail(e.args[0])
def marvcli_user_pw(ctx, username, password)
Change password
4.616862
5.136894
0.898765
app = create_app() try: app.um.user_rm(username) except ValueError as e: ctx.fail(e.args[0])
def marvcli_user_rm(ctx, username)
Remove a user
4.681966
4.990627
0.938152
watermark_img = options.get("watermark", settings.THUMBNAIL_WATERMARK) if not watermark_img: raise AttributeError("No THUMBNAIL_WATERMARK defined or set on tag.") watermark_path = find(watermark_img) if not watermark_path: raise RuntimeError("Could not fi...
def watermark(self, image, options)
Wrapper for ``_watermark`` Takes care of all the options handling.
3.209713
3.223455
0.995737
if hasattr(size, "__getitem__"): # a tuple or any iterable already mark_size = size elif isinstance(size, float): mark_size = map(lambda coord: int(coord * size), mark_default_size) else: raise ImproperlyConfigured( "Waterm...
def _get_new_watermark_size(self, size, mark_default_size)
New size can be passed as a pair of valuer (tuple) or a fsloat (persentage case)
4.970164
4.975307
0.998966
return { 'cat': lambda *lists: [x for lst in lists for x in lst], 'comments': lambda: None, 'detail_route': detail_route, 'format': lambda fmt, *args: fmt.format(*args), 'get': partial(getnode, dataset, setdir, store), 'join': lambda sep, *args: sep.join([x for x...
def make_funcs(dataset, setdir, store)
Functions available for listing columns and filters.
4.179399
4.166857
1.00301
return { 'len': len, 'list': lambda *x: filter(None, list(x)), 'max': max, 'min': min, 'rows': partial(summary_rows, rows, ids), 'sum': sum, 'trace': print_trace }
def make_summary_funcs(rows, ids)
Functions available for listing summary fields.
4.73989
4.615698
1.026906
@functools.wraps(func) def cached_func(self): cacheattr = '_{}'.format(func.func_name) try: return getattr(self, cacheattr) except AttributeError: value = func(self) setattr(self, cacheattr, value) return value return property(cach...
def cached_property(func)
Create read-only property that caches its function's value
2.056198
2.171572
0.946871
assert isinstance(name, basestring), name return CreateStream(parent=None, name=name, group=False, header=header)
def create_stream(name, **header)
Create a stream for publishing messages. All keyword arguments will be used to form the header.
10.196761
11.506215
0.886196
assert isinstance(handle, Handle), handle return Pull(handle, enumerate)
def pull(handle, enumerate=False)
Pulls next message for handle. Args: handle: A :class:`.stream.Handle` or GroupHandle. enumerate (bool): boolean to indicate whether a tuple ``(idx, msg)`` should be returned, not unlike Python's enumerate(). Returns: A :class:`Pull` task to be yielded. Marv will send the ...
9.217406
26.301424
0.350453
assert ep.name not in self.endpoints, ep self.endpoints[ep.name] = ep
def add_endpoint(self, ep)
endpoints and groups are all the same (for now)
3.843202
3.677283
1.04512
if "%" not in geometry: # fall back to old parser return xy_geometry_parser(geometry, ratio) # parse with float so geometry strings like "42.11%" are possible return float(geometry.strip("%")) / 100.0
def parse_geometry(geometry, ratio=None)
Enhanced parse_geometry parser with percentage support.
8.896736
8.086331
1.100219
# Set output stream title and pull first message yield marv.set_header(title=cam.topic) msg = yield marv.pull(cam) if msg is None: return # Deserialize raw ros message pytype = get_message_type(cam) rosmsg = pytype() rosmsg.deserialize(msg.data) # Write image to jpeg a...
def image(cam)
Extract first image of input stream to jpg file. Args: cam: Input stream of raw rosbag messages. Returns: File instance for first image of input stream.
4.935503
5.009204
0.985287
# pull first image img = yield marv.pull(image) if img is None: return # create image widget and section containing it widget = {'title': image.title, 'image': {'src': img.relpath}} section = {'title': title, 'widgets': [widget]} yield marv.push(section)
def image_section(image, title)
Create detail section with one image. Args: title (str): Title to be displayed for detail section. image: marv image file. Returns One detail section.
8.071575
8.207781
0.983405
# Set output stream title and pull first message yield marv.set_header(title=cam.topic) # Fetch and process first 20 image messages name_template = '%s-{}.jpg' % cam.topic.replace('/', ':')[1:] while True: idx, msg = yield marv.pull(cam, enumerate=True) if msg is None or idx >=...
def images(cam)
Extract images from input stream to jpg files. Args: cam: Input stream of raw rosbag messages. Returns: File instances for images of input stream.
6.309023
6.331217
0.996494
# pull all images imgs = [] while True: img = yield marv.pull(images) if img is None: break imgs.append({'src': img.relpath}) if not imgs: return # create gallery widget and section containing it widget = {'title': images.title, 'gallery': {'imag...
def gallery_section(images, title)
Create detail section with gallery. Args: title (str): Title to be displayed for detail section. images: stream of marv image files Returns One detail section.
6.011316
5.644763
1.064937
# Pull each image and push its filesize while True: img = yield marv.pull(images) if img is None: break yield marv.push(img.size)
def filesizes(images)
Stat filesize of files. Args: images: stream of marv image files Returns: Stream of filesizes
9.754575
7.664863
1.272635
assert default is None or foreach is None value = foreach if foreach is not None else default value = StreamSpec(value) if isinstance(value, Node) else value foreach = foreach is not None spec = InputSpec(name, value, foreach) def deco(func): .format(spec) specs = func.__dic...
def input(name, default=None, foreach=None)
Decorator to declare input for a node. Plain inputs, that is plain python objects, are directly passed to the node. Whereas streams generated by other nodes are requested and once the handles of all input streams are available the node is instantiated. Args: name (str): Name of the node fu...
4.925253
5.517581
0.892647
def deco(func): .format(schema, header, group) if isinstance(func, Node): raise TypeError('Attempted to convert function into node twice.') assert isgeneratorfunction(func), \ "Node {}:{} needs to be a generator function".format(func.__module__, ...
def node(schema=None, header=None, group=None, version=None)
Turn function into node. Args: schema: capnproto schema describing the output messages format header: This parameter is currently not supported and only for internal usage. group (bool): A boolean indicating whether the default stream of the node is a group, meaning ...
4.638837
4.01957
1.154063
'''Indents a table by column. - rows: A sequence of sequences of items, one sequence per row. - hasHeader: True if the first row consists of the columns' names. - headerChar: Character to be used for the row separator line (if hasHeader==True or separateRo...
def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left', separateRows=False, prefix='', postfix='', wrapfunc=lambda x: x)
Indents a table by column. - rows: A sequence of sequences of items, one sequence per row. - hasHeader: True if the first row consists of the columns' names. - headerChar: Character to be used for the row separator line (if hasHeader==True or separateRows==True). ...
2.852617
2.080254
1.371283
def decorator(func): wf = update_wrapper(Msg(func, message), func) if name: wf.name = name return wf return decorator
def message(message, name=None)
Convenience decorator that applies [`Msg()`](#msg) to a callable. ```python from good import Schema, message @message(u'Need a number') def intify(v): return int(v) ``` :param message: Error message to use instead :type message: unicode :param name: Override schema name as wel...
6.772712
6.850765
0.988607
# Decorator mode if validator is None: def decorator(f): f.name = name return f return decorator # Direct mode validator.name = name return validator
def name(name, validator=None)
Set a name on a validator callable. Useful for user-friendly reporting when using lambdas to populate the [`Invalid.expected`](#invalid) field: ```python from good import Schema, name Schema(lambda x: int(x))('a') #-> Invalid: invalid literal for int(): expected <lambda>(), got Schema(name('i...
4.83638
5.514924
0.876962
def decorator(func): return update_wrapper(Check(func, message, expected), func) return decorator
def truth(message, expected=None)
Convenience decorator that applies [`Check`](#check) to a callable. ```python from good import truth @truth(u'Must be an existing directory') def isDir(v): return os.path.isdir(v) ``` :param message: Validation error message :type message: unicode :param expected: Expected val...
6.679569
7.551487
0.884537
method_name = func() @wraps(func) def factory(): def validator(v): if not isinstance(v, six.string_types): raise Invalid(_(u'Not a string'), get_type_name(six.text_type), get_type_name(type(v))) return getattr(v, method_name)() return validator ...
def stringmethod(func)
Validator factory which call a single method on the string.
4.707743
4.15078
1.134183
assert len(offset) == 5, 'Invalid offset string format, must be "+HHMM"' return timedelta(hours=int(offset[:3]), minutes=int(offset[0] + offset[3:]))
def parse_z(cls, offset)
Parse %z offset into `timedelta`
7.732729
5.632278
1.372931
sec = offset.total_seconds() return '{s}{h:02d}{m:02d}'.format(s='-' if sec<0 else '+', h=abs(int(sec/3600)), m=int((sec%3600)/60))
def format_z(cls, offset)
Format `timedelta` into %z
3.242528
3.060314
1.059541
# Process try: # this block should not raise errors, and if it does -- they should not be wrapped with `Invalid` # localize if self.localize and dt.tzinfo is None: dt = self.localize(dt) # astimezone if self.astz and dt.tzinfo is...
def preprocess(self, dt)
Preprocess the `dt` with `localize()` and `astz()`
6.390237
4.887654
1.307424
# Simplest case: direct parsing if cls.python_supports_z or '%z' not in format: return datetime.strptime(value, format) else: # %z emulation case assert format[-2:] == '%z', 'For performance, %z is only supported at the end of the string' ...
def strptime(cls, value, format)
Parse a datetime string using the provided format. This also emulates `%z` support on Python 2. :param value: Datetime string :type value: str :param format: Format to use for parsing :type format: str :rtype: datetime :raises ValueError: Invalid format ...
6.93736
6.605799
1.050192
type = choice(['int', 'str']) r = lambda: randrange(-1000000000, 1000000000) if type == 'int': return int, (r() if valid else str(r()) for i in itertools.count()) elif type == 'str': return str, (str(r()) if valid else r() for i in itertools.count()) else: raise Asser...
def generate_random_type(valid)
Generate a random type and samples for it. :param valid: Generate valid samples? :type valid: bool :return: type, sample-generator :rtype: type, generator
3.69051
4.279715
0.862326
schema_type = choice(['literal', 'type']) if schema_type == 'literal': type, gen = generate_random_type(valid) value = next(gen) return value, (value if valid else None for i in itertools.count()) elif schema_type == 'type': return generate_random_type(valid) else: ...
def generate_random_schema(valid)
Generate a random plain schema, and a sample generation function. :param valid: Generate valid samples? :type valid: bool :returns: schema, sample-generator :rtype: *, generator
5.409997
5.649618
0.957586
schema = {} generator_items = [] # Generate schema for i in range(0, size): while True: key_schema, key_generator = generate_random_schema(valid) if key_schema not in schema: break value_schema, value_generator = generate_random_schema(v...
def generate_dict_schema(size, valid)
Generate a schema dict of size `size` using library `lib`. In addition, it returns samples generator :param size: Schema size :type size: int :param samples: The number of samples to generate :type samples: int :param valid: Generate valid samples? :type valid: bool :returns
3.34338
3.47152
0.963088
import fnmatch def _ignore_patterns(path, names): ignored_names = [] for pattern in patterns: ignored_names.extend(fnmatch.filter(names, pattern)) return set(ignored_names) return _ignore_patterns
def ignore_patterns(*patterns)
Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns that are used to exclude files
2.087316
2.524925
0.826684
from shutil import copy2, Error, copystat names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() os.makedirs(dst) errors = [] for name in names: if name in ignored_names: continue srcname...
def copytree(src, dst, symlinks=False, ignore=None)
Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is f...
1.185299
1.259881
0.940803
if (os.getenv("VAULT_TOKEN", None) or (os.getenv("VAULT_APPID", None) and os.getenv("VAULT_USERID", None)) or (os.getenv("VAULT_SSLCERT", None) and os.getenv("VAULT_SSLKEY", None)) or (os.getenv("VAULT_ROLEID", None) and os.getenv("VAULT_SECRETID", None))...
def has_envconfig() -> bool
(static) :return: True if enough information is available in the environment to authenticate to Vault
2.765628
2.522674
1.096308
i = None # type: VaultAuth12Factor if os.getenv("VAULT_TOKEN", None): i = VaultAuth12Factor.token(os.getenv("VAULT_TOKEN")) elif os.getenv("VAULT_APPID", None) and os.getenv("VAULT_USERID", None): i = VaultAuth12Factor.app_id(os.getenv("VAULT_APPID"), os.getenv(...
def fromenv() -> 'VaultAuth12Factor'
:return: Load configuration from the environment and return a configured instance
2.126836
2.068356
1.028274
topo = Topoplot(**kwargs) topo.set_locations(locations) topo.set_values(values) topo.create_map() topo.plot_map(axes=axes, offset=offset) if plot_locations: topo.plot_locations(axes=axes, offset=offset) if plot_head: topo.plot_head(axes=axes, offset=offset) return to...
def topoplot(values, locations, axes=None, offset=(0, 0), plot_locations=True, plot_head=True, **kwargs)
Wrapper function for :class:`Topoplot.
2.025585
1.925616
1.051915
t, m, l = np.shape(data) n = (l - p) * t # number of linear relations rows = n if delta is None else n + m * p # Construct matrix x (predictor variables) x = np.zeros((rows, m * p)) for i in range(m): for k in range(1, p + 1): x[:n, ...
def _construct_var_eqns(data, p, delta=None)
Construct VAR equation system (optionally with RLS constraint).
3.776036
3.631446
1.039816
t, m, n = x.shape # covariance matrix of x c0 = acm(x, 0) # LU factorization of covariance matrix c0f = sp.linalg.lu_factor(c0, overwrite_a=False, check_finite=True) q = np.zeros((3, h + 1)) for l in range(1, h + 1): cl = acm(x, l) # calculate tr(cl' * c0^-1 * cl * c...
def _calc_q_statistic(x, h, nt)
Calculate Portmanteau statistics up to a lag of h.
3.65196
3.500296
1.043329
rng = check_random_state(random_state) par, func = parallel_loop(_calc_q_statistic, n_jobs, verbose) q = par(func(rng.permutation(x.T).T, h, nt) for _ in range(n)) return np.array(q)
def _calc_q_h0(n, x, h, nt, n_jobs=1, verbose=0, random_state=None)
Calculate q under the null hypothesis of whiteness.
4.650259
4.544608
1.023247
other = self.__class__(self.p) other.coef = self.coef.copy() other.residuals = self.residuals.copy() other.rescov = self.rescov.copy() return other
def copy(self)
Create a copy of the VAR model.
3.638412
3.410062
1.066964
if len(acms) != self.p + 1: raise ValueError("Number of autocorrelation matrices ({}) does not" " match model order ({}) + 1.".format(len(acms), self.p)) n_channels = acms[0].shape[0] ...
def from_yw(self, acms)
Determine VAR model from autocorrelation matrices by solving the Yule-Walker equations. Parameters ---------- acms : array, shape (n_lags, n_channels, n_channels) acms[l] contains the autocorrelation matrix at lag l. The highest lag must equal the model order. ...
3.664182
3.445862
1.063357
m, n = np.shape(self.coef) p = n // m try: l, t = l except TypeError: t = 1 if noisefunc is None: rng = check_random_state(random_state) noisefunc = lambda: rng.normal(size=(1, m)) n = l + 10 * p y = np....
def simulate(self, l, noisefunc=None, random_state=None)
Simulate vector autoregressive (VAR) model. This function generates data from the VAR model. Parameters ---------- l : int or [int, int] Number of samples to generate. Can be a tuple or list, where l[0] is the number of samples and l[1] is the number of trials. ...
3.210712
3.186973
1.007449
data = atleast_3d(data) t, m, l = data.shape p = int(np.shape(self.coef)[1] / m) y = np.zeros(data.shape) if t > l - p: # which takes less loop iterations for k in range(1, p + 1): bp = self.coef[:, (k - 1)::p] for n in rang...
def predict(self, data)
Predict samples on actual data. The result of this function is used for calculating the residuals. Parameters ---------- data : array, shape (trials, channels, samples) or (channels, samples) Epoched or continuous data set. Returns ------- predicted...
3.802861
3.757265
1.012136
m, mp = self.coef.shape p = mp // m assert(mp == m * p) # TODO: replace with raise? top_block = [] for i in range(p): top_block.append(self.coef[:, i::p]) top_block = np.hstack(top_block) im = np.eye(m) eye_block = im for i ...
def is_stable(self)
Test if VAR model is stable. This function tests stability of the VAR model as described in [1]_. Returns ------- out : bool True if the model is stable. References ---------- .. [1] H. Lütkepohl, "New Introduction to Multiple Time Series ...
3.351847
3.651915
0.917833
if dataset not in datasets: raise ValueError("Example data '{}' not available.".format(dataset)) else: files = datasets[dataset]["files"] url = datasets[dataset]["url"] md5 = datasets[dataset]["md5"] if not isdir(datadir): makedirs(datadir) data = [] fo...
def fetch(dataset="mi", datadir=datadir)
Fetch example dataset. If the requested dataset is not found in the location specified by `datadir`, the function attempts to download it. Parameters ---------- dataset : str Which dataset to load. Currently only 'mi' is supported. datadir : str Path to the storage location of ...
2.665861
2.722334
0.979256
# Test try: yes = self(const.UNDEFINED) is not const.UNDEFINED except (Invalid, SchemaError): yes = False # Remember (lame @cached_property) self.__dict__['supports_undefined'] = yes return yes
def supports_undefined(self)
Test whether this schema supports Undefined. A Schema that supports `Undefined`, when given `Undefined`, should return some value (other than `Undefined`) without raising errors. This is designed to support a very special case like that: ```python Schema(Default(0)).supports_u...
14.096382
14.226315
0.990867