code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return pvlib.irradiance.aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth)
def f_aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth)
Calculate angle of incidence :param surface_tilt: :param surface_azimuth: :param solar_zenith: :param solar_azimuth: :return: angle of incidence [deg]
2.447562
3.273393
0.747714
with open(filename, "r") as filep: version_file = filep.read() version_match = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M ) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string...
def find_version(filename)
Search for assignment of __version__ string in given file and return what it is assigned to.
1.628468
1.623622
1.002984
nt = total // 2 # This bar is too near the border if prow-nt < 0 or prow + nt >= edges.shape[0]: return [] s2edges = edges[prow-nt:prow+nt+1, bstart:bend] structure = morph.generate_binary_structure(2,2) # 8 way conection har, num_f = mes.label(s2edges, structure=structure) ...
def find_position(edges, prow, bstart, bend, total=5)
Find a EMIR CSU bar position in a edge image. Parameters ========== edges; ndarray, a 2d image with 1 where is a border, 0 otherwise prow: int, reference 'row' of the bars bstart: int, minimum 'x' position of a bar (0-based) bend: int maximum 'x' position of a ba...
5.642872
5.010965
1.126105
# We compute know the FWHM of the slit # Given the computed position of the slit # Expand 'fexpand' pixels around # and cut an slice in the median filtered image xpregion = expand_region(region, fexpand, fexpand) cslit = img[xpregion] # Collapse it pslit = cslit.mean(axis=axis) ...
def calc_fwhm(img, region, fexpand=3, axis=0)
Compute the FWHM in the direction given by axis
7.271469
7.391676
0.983737
# start must b >= 1 for i in range(start,len(x)-1): a,b,c = x[i-1], x[i], x[i+1] if b - a > 0 and b -c >= 0: return i else: return None
def simple_prot(x, start)
Find the first peak to the right of start
5.029014
4.612921
1.090202
# Find the first peak to the right of cpix next_peak = simple_prot(pslit, cpix) if next_peak is None: raise ValueError dis_peak = next_peak - cpix wpos2 = cpix - dis_peak wpos1 = wpos2 - backw # Compute background in a window of width backw # in a position simetrical to...
def position_half_h(pslit, cpix, backw=4)
Find the position where the value is half of the peak
5.86751
5.826726
1.006999
def swap_coor(x): return x def swap_line(tab): return tab return _locate_bar_gen(icut, epos, transform1=swap_coor, transform2=swap_line )
def locate_bar_l(icut, epos)
Fine position of the left CSU bar
8.825376
8.936509
0.987564
sm = len(icut) def swap_coor(x): return sm - 1 - x def swap_line(tab): return tab[::-1] return _locate_bar_gen(icut, epos, transform1=swap_coor, transform2=swap_line)
def locate_bar_r(icut, epos)
Fine position of the right CSU bar
7.127809
7.238661
0.984686
epos_pix = coor_to_pix_1d(epos) # transform -> epos_pix_s = transform1(epos_pix) icut2 = transform2(icut) # try: res = position_half_h(icut2, epos_pix_s) xint_s, next_peak_s, wpos1_s, wpos2_s, background_level, half_height = res # xint = transform1(xint_...
def _locate_bar_gen(icut, epos, transform1, transform2)
Generic function for the fine position of the CSU
6.66542
6.417489
1.038634
return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))
def overlap(intv1, intv2)
Overlaping of two intervals
1.810932
1.767068
1.024823
# plate scale: 0.1944 arcsec/pixel # conversion factor (in radian/pixel) factor = 0.1944 * np.pi/(180.0*3600) # distance from image center (pixels) r_pix = np.sqrt((x - x0*1000)**2 + (y - y0*1000)**2) # distance from imagen center (radians) r_rad = factor * r_pix # radial distortio...
def exvp_scalar(x, y, x0, y0, c2, c4, theta0, ff)
Convert virtual pixel to real pixel. Parameters ---------- x : array-like of floats X coordinate (pixel). y : array-like of floats Y coordinate (pixel). x0 : float X coordinate of reference pixel, in units of 1E3. y0 : float Y coordinate of reference pixel, in un...
4.241848
3.936433
1.077587
if all([np.isscalar(x), np.isscalar(y)]): xdist, ydist = exvp_scalar(x, y, x0=x0, y0=y0, c2=c2, c4=c4, theta0=theta0, ff=ff) return xdist, ydist elif any([np.isscalar(x), np.isscalar(y)]): raise ValueError("invalid mixture of scalars and arrays") ...
def exvp(x, y, x0, y0, c2, c4, theta0, ff)
Convert virtual pixel(s) to real pixel(s). This function makes use of exvp_scalar(), which performs the conversion for a single point (x, y), over an array of X and Y values. Parameters ---------- x : array-like X coordinate (pixel). y : array-like Y coordinate (pixel). ...
1.709926
1.577975
1.083621
c2, c4, ff, slit_gap, slit_height, theta0, x0, y0, y_baseline = \ return_params(islitlet, csu_bar_slit_center, params, parmodel) xp = np.linspace(1, EMIR_NAXIS1, numpts) slit_dist = (slit_height * 10) + slit_gap # undistorted (constant) y-coordinate of the lower and upper boundaries ...
def expected_distorted_boundaries(islitlet, csu_bar_slit_center, borderlist, params, parmodel, numpts, deg, debugplot=0)
Return expected SpectrumTrail instances associated to a given slitlet. Several SpectrumTrail objects can be computed for the considered slitlet. The parameter borderlist is a list of floats, ranging from 0 to 1, indicating the spatial location of the spectrum trail within the slitlet: 0 means the lower...
4.921147
4.285741
1.14826
for islitlet in range(1, EMIR_NBARS + 1): tmpcolor = micolors[islitlet % 2] tmp_slitlet = 'slitlet' + str(islitlet).zfill(2) if tmp_slitlet in bounddict['contents'].keys(): read_dateobs = list(bounddict['contents'][tmp_slitlet].keys()) read_dateobs.sort() ...
def overplot_boundaries_from_bounddict(ax, bounddict, micolors, linetype='-')
Overplot boundaries on current plot. Parameters ---------- ax : matplotlib axes Current plot axes. bounddict : JSON structure Structure employed to store bounddict information. micolors : list of char List with two characters corresponding to alternating colors for o...
3.06295
2.905417
1.054221
params = Parameters() for mainpar in EXPECTED_PARAMETER_LIST: if mainpar not in bound_param_dict['contents'].keys(): raise ValueError('Parameter ' + mainpar + ' not found!') if bound_param_dict['meta_info']['parmodel'] == "longslit": dumdict = bound_param_dict['cont...
def bound_params_from_dict(bound_param_dict)
Define `~lmfit.parameter.Parameters` object from dictionary. Parameters ---------- bound_param_dict : dictionary Dictionary containing the JSON contents of a boundary parameter file. Returns ------- params : :class:`~lmfit.parameter.Parameters` Parameters object.
2.924792
2.956064
0.989421
hdr = super(StareImageRecipe2, self).set_base_headers(hdr) # Set EXP to 0 hdr['EXP'] = 0 return hdr
def set_base_headers(self, hdr)
Set metadata in FITS headers.
11.373135
7.884345
1.442496
hdr = super(StareImageBaseRecipe, self).set_base_headers(hdr) # Update EXP to 0 hdr['EXP'] = 0 return hdr
def set_base_headers(self, hdr)
Set metadata in FITS headers.
12.087214
8.072882
1.497261
if not name: raise ValueError("Transaction name cannot be empty") #uid = id(self) self.transaction_count += 1 logger.debug("{}. Start transaction {}".format(self.transaction_count, name)) if self.transaction_count == 1: self._transaction_star...
def transaction_start(self, name)
start a transaction this will increment transaction semaphore and pass it to _transaction_start()
4.225957
3.937464
1.073269
if self.transaction_count > 0: logger.debug("{}. Stop transaction".format(self.transaction_count)) if self.transaction_count == 1: self._transaction_stop() self.transaction_count -= 1 return self.transaction_count
def transaction_stop(self)
stop/commit a transaction if ready
3.588995
3.428965
1.04667
if not name: raise ValueError("Transaction name cannot be empty") if self.transaction_count > 0: logger.debug("{}. Failing transaction {}".format(self.transaction_count, name)) if self.transaction_count == 1: self._transaction_fail() ...
def transaction_fail(self, name)
rollback a transaction if currently in one e -- Exception() -- if passed in, bubble up the exception by re-raising it
3.506448
3.628826
0.966276
if self.connected: return self.connected if connection_config: self.connection_config = connection_config self.connected = True try: self._connect(self.connection_config) except Exception as e: self.connected = False self.raise_erro...
def connect(self, connection_config=None, *args, **kwargs)
connect to the interface this will set the raw db connection to self.connection *args -- anything you want that will help the db connect **kwargs -- anything you want that the backend db connection will need to actually connect
3.395957
3.714052
0.914354
if not self.connected: return True self._close() self.connected = False self.log("Closed Connection {}", self.connection_config.interface_name) return True
def close(self)
close an open connection
9.814105
8.29882
1.18259
with self.connection(**query_options) as connection: query_options['connection'] = connection return self._query(query_str, query_args, **query_options)
def query(self, query_str, *query_args, **query_options)
run a raw query on the db query_str -- string -- the query to run *query_args -- if the query_str is a formatting string, pass the values in this **query_options -- any query options can be passed in by using key=val syntax
3.301265
4.55505
0.724748
with self.connection(connection) as connection: name = connection.transaction_name() connection.transaction_start(name) try: yield connection connection.transaction_stop() except Exception as e: connection....
def transaction(self, connection=None, **kwargs)
a simple context manager useful for when you want to wrap a bunch of db calls in a transaction http://docs.python.org/2/library/contextlib.html http://docs.python.org/release/2.5/whatsnew/pep-343.html example -- with self.transaction() # do a bunch of calls ...
4.119804
4.749833
0.867358
with self.connection(**kwargs) as connection: kwargs['connection'] = connection if self.has_table(str(schema), **kwargs): return True try: with self.transaction(**kwargs): self._set_table(schema, **kwargs) for...
def set_table(self, schema, **kwargs)
add the table to the db schema -- Schema() -- contains all the information about the table
3.826208
3.900331
0.980996
with self.connection(kwargs.get('connection', None)) as connection: kwargs['connection'] = connection tables = self.get_tables(table_name, **kwargs) return len(tables) > 0
def has_table(self, table_name, **kwargs)
check to see if a table is in the db table_name -- string -- the table to check return -- boolean -- True if the table exists, false otherwise
3.642513
4.009556
0.908458
with self.connection(**kwargs) as connection: kwargs['connection'] = connection return self._get_tables(str(table_name), **kwargs)
def get_tables(self, table_name="", **kwargs)
get all the tables of the currently connected db table_name -- string -- if you would like to filter the tables list to only include matches with this name return -- list -- a list of table names
4.884986
5.871116
0.832037
with self.connection(**kwargs) as connection: kwargs['connection'] = connection if not self.has_table(str(schema), **kwargs): return True with self.transaction(**kwargs): self._delete_table(schema, **kwargs) return True
def delete_table(self, schema, **kwargs)
remove a table matching schema from the db schema -- Schema()
4.353416
4.231929
1.028707
if not kwargs.get('disable_protection', False): raise ValueError('In order to delete all the tables, pass in disable_protection=True') with self.connection(**kwargs) as connection: kwargs['connection'] = connection self._delete_tables(**kwargs)
def delete_tables(self, **kwargs)
removes all the tables from the db this is, obviously, very bad if you didn't mean to call this, because of that, you have to pass in disable_protection=True, if it doesn't get that passed in, it won't run this method
5.503531
3.789548
1.452292
with self.connection(**kwargs) as connection: kwargs['connection'] = connection return self._get_indexes(schema, **kwargs)
def get_indexes(self, schema, **kwargs)
get all the indexes schema -- Schema() return -- dict -- the indexes in {indexname: fields} format
4.563622
5.33569
0.855301
with self.transaction(**index_options) as connection: index_options['connection'] = connection self._set_index(schema, name, fields, **index_options) return True
def set_index(self, schema, name, fields, **index_options)
add an index to the table schema -- Schema() name -- string -- the name of the index fields -- array -- the fields the index should be on **index_options -- dict -- any index options that might be useful to create the index
3.668494
4.632597
0.791887
r = 0 with self.connection(**kwargs) as connection: kwargs['connection'] = connection try: with self.transaction(**kwargs): r = self._insert(schema, fields, **kwargs) except Exception as e: exc_info = sys....
def insert(self, schema, fields, **kwargs)
Persist d into the db schema -- Schema() fields -- dict -- the values to persist return -- int -- the primary key of the row just inserted
2.966959
3.05204
0.972123
with self.connection(**kwargs) as connection: kwargs['connection'] = connection try: with self.transaction(**kwargs): r = self._update(schema, fields, query, **kwargs) except Exception as e: exc_info = sys.exc_info...
def update(self, schema, fields, query, **kwargs)
Persist the query.fields into the db that match query.fields_where schema -- Schema() fields -- dict -- the values to persist query -- Query() -- will be used to create the where clause return -- int -- how many rows where updated
2.784484
2.988904
0.931607
if not query: query = Query() ret = None with self.connection(**kwargs) as connection: kwargs['connection'] = connection try: if connection.in_transaction(): # we wrap SELECT queries in a transaction if we are in a transaction...
def _get_query(self, callback, schema, query=None, *args, **kwargs)
this is just a common wrapper around all the get queries since they are all really similar in how they execute
4.871297
4.771296
1.020959
ret = self._get_query(self._get_one, schema, query, **kwargs) if not ret: ret = {} return ret
def get_one(self, schema, query=None, **kwargs)
get one row from the db matching filters set in query schema -- Schema() query -- Query() return -- dict -- the matching row
5.107183
5.69207
0.897245
ret = self._get_query(self._get, schema, query, **kwargs) if not ret: ret = [] return ret
def get(self, schema, query=None, **kwargs)
get matching rows from the db matching filters set in query schema -- Schema() query -- Query() return -- list -- a list of matching dicts
5.941807
6.423618
0.924994
if isinstance(format_str, Exception): logger.exception(format_str, *format_args) else: log_level = log_options.get('level', logging.DEBUG) if logger.isEnabledFor(log_level): if format_args: logger.log(log_level, format_str....
def log(self, format_str, *format_args, **log_options)
wrapper around the module's logger format_str -- string -- the message to log *format_args -- list -- if format_str is a string containing {}, then format_str.format(*format_args) is ran **log_options -- level -- something like logging.DEBUG
1.907496
1.929875
0.988404
if not exc_info: exc_info = sys.exc_info() if not isinstance(e, InterfaceError): # allow python's built in errors to filter up through # https://docs.python.org/2/library/exceptions.html #if not hasattr(exceptions, e.__class__.__name__): ...
def raise_error(self, e, exc_info=None)
this is just a wrapper to make the passed in exception an InterfaceError
3.799846
3.37828
1.124787
ret = True # http://stackoverflow.com/questions/6739355/dictcursor-doesnt-seem-to-work-under-psycopg2 connection = query_options.get('connection', None) with self.connection(connection) as connection: cur = connection.cursor() ignore_result = query_option...
def _query(self, query_str, query_args=None, **query_options)
**query_options -- dict ignore_result -- boolean -- true to not attempt to fetch results fetchone -- boolean -- true to only fetch one result count_result -- boolean -- true to return the int count of rows affected
2.637371
2.482959
1.062189
only_where_clause = sql_options.get('only_where_clause', False) symbol_map = { 'in': {'symbol': 'IN', 'list': True}, 'nin': {'symbol': 'NOT IN', 'list': True}, 'is': {'symbol': '=', 'none_symbol': 'IS'}, 'not': {'symbol': '!=', 'none_symbol': 'IS ...
def get_SQL(self, schema, query, **sql_options)
convert the query instance into SQL this is the glue method that translates the generic Query() instance to the SQL specific query, this is where the magic happens **sql_options -- dict count_query -- boolean -- true if this is a count query SELECT only_where_clause -- ...
2.264753
2.236928
1.012439
with self.transaction(**kwargs) as connection: kwargs['connection'] = connection # go through and make sure all foreign key referenced tables exist for field_name, field_val in schema.fields.items(): s = field_val.schema if s: ...
def _set_all_tables(self, schema, **kwargs)
You can run into a problem when you are trying to set a table and it has a foreign key to a table that doesn't exist, so this method will go through all fk refs and make sure the tables exist
5.210258
4.578896
1.137885
current_fields = self.get_fields(schema, **kwargs) for field_name, field in schema.fields.items(): if field_name not in current_fields: if field.required: raise ValueError('Cannot safely add {} on the fly because it is required'.format(field_name)...
def _set_all_fields(self, schema, **kwargs)
this will add fields that don't exist in the table if they can be set to NULL, the reason they have to be NULL is adding fields to Postgres that can be NULL is really light, but if they have a default value, then it can be costly
3.121742
2.921959
1.068373
# Split the uuid into two parts so that we won't run into subdirectory count limits. First part has 3 hex chars, # thus 4k possible values. uuid_hex = get_uuid() return os.path.join(uuid_hex[:3], uuid_hex[3:], filename)
def random_path(instance, filename)
Random path generator for uploads, specify this for upload_to= argument of FileFields
12.072773
11.224669
1.075557
global initialized if initialized: return initialized = True uwsgi.add_timer(signal_number, update_period_s) uwsgi.register_signal(signal_number, MULE, emit)
def initialize(signal_number=DEFAULT_TIMER_SIGNAL_NUMBER, update_period_s=DEFAULT_UPDATE_PERIOD_S)
Initialize metrics, must be invoked at least once prior to invoking any other method.
5.944457
6.222542
0.95531
if not initialized: raise NotInitialized view = { 'version': __version__, 'counters': {}, 'gauges': {}, 'histograms': {}, 'meters': {}, 'timers': {}, } for (ty, module, name), metric in six.iteritems(all_metrics): view[ty]['%s.%s' % ...
def emit(_)
Serialize metrics to the memory mapped buffer.
4.468433
4.074996
1.096549
if not initialized: raise NotInitialized marshalled_metrics_mmap.seek(0) try: uwsgi.lock() marshalled_view = marshalled_metrics_mmap.read( MAX_MARSHALLED_VIEW_SIZE) finally: uwsgi.unlock() return marshal.loads(marshalled_view)
def view()
Get a dictionary representation of current metrics.
7.542601
6.611896
1.140762
start_time_s = time.time() try: yield finally: end_time_s = time.time() delta_s = end_time_s - start_time_s delta_ms = delta_s * 1000 timer(module, name, delta_ms)
def timing(module, name)
Context manager to time a section of code:: with timing(__name__, 'my_timer'): do_some_operation()
2.255785
2.551082
0.884247
timer = get_metric('timers', module, name, Timer(duration_units)) timer.update(delta)
def timer(module, name, delta, duration_units='milliseconds')
Record a timing delta: :: start_time_s = time.time() do_some_operation() end_time_s = time.time() delta_s = end_time_s - start_time_s delta_ms = delta_s * 1000 timer(__name__, 'my_timer', delta_ms)
7.923842
11.209161
0.706908
histogram = get_metric('histograms', module, name, Histogram()) histogram.update(value)
def histogram(module, name, value)
Record a value in a histogram: :: histogram(__name__, 'my_histogram', len(queue))
9.119758
12.404094
0.735222
counter = get_metric('counters', module, name, Counter()) counter.inc(count)
def counter(module, name, count=1)
Record an event's occurence in a counter: :: counter(__name__, 'my_counter')
8.719529
10.061716
0.866605
meter = get_metric('meters', module, name, Meter()) meter.mark(count)
def meter(module, name, count=1)
Record an event rate: :: meter(__name__, 'my_meter', 'event_type')
10.188277
13.814712
0.737495
if isinstance(nodes, BASESTRING): nodes = [nodes] if conn_params is None: conn_params = DEFAULT_CONN_PARAMS logger.debug("Running %s on %s ", label, nodes) remote = ex.get_remote(cmd, nodes, conn_params) remote.run() if not remote.finished_ok: raise Exception('An ...
def exec_command_on_nodes(nodes, cmd, label, conn_params=None)
Execute a command on a node (id or hostname) or on a set of nodes. :param nodes: list of targets of the command cmd. Each must be an execo.Host. :param cmd: string representing the command to run on the remote nodes. :param label: string f...
4.438835
4.90909
0.904207
newobj = super(ProcessedImageProduct, self).convert_out(obj) if newobj: hdulist = newobj.open() hdr = hdulist[0].header if 'EMIRUUID' not in hdr: hdr['EMIRUUID'] = str(uuid.uuid1()) return newobj
def convert_out(self, obj)
Write EMIRUUID header on reduction
5.168025
3.176247
1.627086
if not authorization_info: if 'client_id' in request and 'client_secret' in request: auth_info = ClientSecretPost(endpoint_context).verify(request) auth_info['method'] = 'client_secret_post' elif 'client_assertion' in request: auth_info = JWSAuthnMethod(endp...
def verify_client(endpoint_context, request, authorization_info)
Initiated Guessing ! :param endpoint_context: SrvInfo instance :param request: The request :param authorization_info: Client authentication information :return: dictionary containing client id, client authentication method and possibly access token.
2.412204
2.366713
1.019221
request = RefreshAccessTokenRequest(**request.to_dict()) try: keyjar = self.endpoint_context.keyjar except AttributeError: keyjar = "" request.verify(keyjar=keyjar, opponent_id=client_id) if "client_id" not in request: # Optional for refresh ...
def _post_parse_request(self, request, client_id='', **kwargs)
This is where clients come to refresh their access tokens :param request: The request :param authn: Authentication info, comes from HTTP header :returns:
4.617224
4.919363
0.938582
def char(): return random.choice(string.ascii_letters + string.digits) return "".join(char() for _ in range(length))
def random_id(length)
Generates a random ID of given length
4.784293
4.551731
1.051093
close = getattr(closable, "close", None) if close: # we do not want the library to close file in case we need to # resume, hence make close a no-op # pylint: disable=unused-argument def replacement_close(*args, **kw): pass # pylint: enable=...
def delayed_close(closable)
Delay close until this contextmanager dies
4.018892
3.69699
1.087071
self.set('sid2uid', sid, uid) self.set('uid2sid', uid, sid)
def map_sid2uid(self, sid, uid)
Store the connection between a Session ID and a User ID :param sid: Session ID :param uid: User ID
3.520689
4.39159
0.801689
self.set('sid2sub', sid, sub) self.set('sub2sid', sub, sid)
def map_sid2sub(self, sid, sub)
Store the connection between a Session ID and a subject ID. :param sid: Session ID :param sub: subject ID
3.755537
4.619398
0.812993
res = set() for sid in self.get('uid2sid', uid): res |= set(self.get('sid2sub', sid)) return res
def get_subs_by_uid(self, uid)
Find all subject identifiers that is connected to a User ID. :param uid: A User ID :return: A set of subject identifiers
4.922827
5.068354
0.971287
self.remove('sub2sid', sub, sid) self.remove('sid2sub', sid, sub)
def remove_sid2sub(self, sid, sub)
Remove the connection between a session ID and a Subject :param sid: Session ID :param sub: Subject identifier ´
3.472992
3.08974
1.124041
self.remove('uid2sid', uid, sid) self.remove('sid2uid', sid, uid)
def remove_sid2uid(self, sid, uid)
Remove the connection between a session ID and a Subject :param sid: Session ID :param uid: User identifier ´
3.407642
3.065239
1.111705
for uid in self.get('sid2uid', sid): self.remove('uid2sid', uid, sid) self.delete('sid2uid', sid) for sub in self.get('sid2sub', sid): self.remove('sub2sid', sub, sid) self.delete('sid2sub', sid)
def remove_session_id(self, sid)
Remove all references to a specific Session ID :param sid: A Session ID
2.810519
2.995041
0.938391
for sid in self.get('uid2sid', uid): self.remove('sid2uid', sid, uid) self.delete('uid2sid', uid)
def remove_uid(self, uid)
Remove all references to a specific User ID :param uid: A User ID
4.857149
5.440748
0.892735
for _sid in self.get('sub2sid', sub): self.remove('sid2sub', _sid, sub) self.delete('sub2sid', sub)
def remove_sub(self, sub)
Remove all references to a specific Subject ID :param sub: A Subject ID
6.14035
7.583581
0.80969
"Starts a new experiment" inventory = os.path.join(os.getcwd(), "hosts") conf = Configuration.from_dictionnary(provider_conf) provider = Enos_vagrant(conf) roles, networks = provider.init() check_networks(roles, networks) env["roles"] = roles env["networks"] = networks
def up(force=True, env=None, **kwargs)
Starts a new experiment
12.751976
12.542631
1.016691
def wrapper(origfcn): @functools.wraps(origfcn) def newfcn(*args, **kwargs): argspec = getargspec(origfcn) # use ``inspect`` to get arg names kwargs.update(zip(argspec.args, args)) # convert args to kw # loop over test args for a in test_args: ...
def convert_args(test_fcn, *test_args)
Decorator to be using in formulas to convert ``test_args`` depending on the ``test_fcn``. :param test_fcn: A test function that converts arguments. :type test_fcn: function :param test_args: Names of args to convert using ``test_fcn``. :type test_args: str The following test functions are avai...
3.492627
3.580164
0.975549
attrs = (a for a in dir(cls) if not a.startswith('_')) if as_list: return list(attrs) return attrs
def get_public_attributes(cls, as_list=True)
Return class attributes that are neither private nor magic. :param cls: class :param as_list: [True] set to False to return generator :return: only public attributes of class
2.758814
3.394387
0.812757
newkeys = newitems.viewkeys() # set of the new item keys if any(self.viewkeys() & newkeys): # duplicates raise DuplicateRegItemError(self.viewkeys() & newkeys) self.update(newitems) # register new item # update meta fields kwargs.update(zip(self.meta_names...
def register(self, newitems, *args, **kwargs)
Register newitems in registry. :param newitems: New items to add to registry. When registering new items, keys are not allowed to override existing keys in the registry. :type newitems: mapping :param args: Positional arguments with meta data corresponding to order ...
4.449929
3.398322
1.309449
items = _listify(items) # get all members of Registry except private, special or class meta_names = (m for m in vars(self).iterkeys() if (not m.startswith('_') and m not in dir(Registry))) # check that meta names matches # FIXME: this is so lame. re...
def unregister(self, items)
Remove items from registry. :param items:
5.985033
6.379363
0.938187
if isinstance(o, Q_): return o.magnitude elif isinstance(o, np.ndarray): return o.tolist() else: # raise TypeError if not serializable return super(SimKitJSONEncoder, self).default(o)
def default(self, o)
JSONEncoder default method that converts NumPy arrays and quantities objects to lists.
4.964045
3.937482
1.260715
# pop the meta class from the attributes meta = attr.pop(mcs._meta_cls, types.ClassType(mcs._meta_cls, (), {})) # get a list of the meta public class attributes meta_attrs = get_public_attributes(meta) # check all bases for meta for base in bases: bas...
def set_meta(mcs, bases, attr)
Get all of the ``Meta`` classes from bases and combine them with this class. Pops or creates ``Meta`` from attributes, combines all bases, adds ``_meta`` to attributes with all meta :param bases: bases of this class :param attr: class attributes :return: attributes with...
3.929356
3.78136
1.039138
meta = attr[mcs._meta_attr] # look for parameter file path in meta cls_path = getattr(meta, mcs._path_attr, None) cls_file = getattr(meta, mcs._file_attr, None) # read parameters attr[mcs._param_attr] = {} attr[mcs._param_file] = None # read parameters f...
def set_param_file_or_parameters(mcs, attr)
Set parameters from class attributes that are instances of :class:`~simkit.core.Parameter` or from a parameter file. Any class attributes that are instances of :class:`~simkit.core.Parameter` are popped from the class and added to a the ``parameters`` attribute, which is a dictionary of...
3.086136
3.147565
0.980484
for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj) and issubclass(obj, UserAuthnMethod): try: if obj.__name__ == cls: return obj(**kwargs) except AttributeError: pass
def factory(cls, **kwargs)
Factory method that can be used to easily instantiate a class instance :param cls: The name of the class :param kwargs: Keyword arguments :return: An instance of the class or None if the name doesn't match any known class.
2.872392
2.810036
1.02219
kwargs.update(zip(self.meta_names, args)) # call super method, meta must be passed as kwargs! super(FormulaRegistry, self).register(new_formulas, **kwargs)
def register(self, new_formulas, *args, **kwargs)
Register formula and meta data. * ``islinear`` - ``True`` if formula is linear, ``False`` if non-linear. * ``args`` - position of arguments * ``units`` - units of returns and arguments as pair of tuples * ``isconstant`` - constant arguments not included in covariance :param new...
7.837947
7.674141
1.021345
# TODO: unit tests! # TODO: move this to somewhere else and call it "importy", maybe # core.__init__.py since a lot of modules might use it. module = self.meta.module # module read from parameters package = getattr(self.meta, 'package', None) # package read from meta ...
def import_formulas(self)
Import formulas specified in :attr:`parameters`. :returns: formulas :rtype: dict
4.203159
4.165038
1.009153
return blazar_client.Client(session=session, service_type="reservation", region_name=os.environ["OS_REGION_NAME"])
def create_blazar_client(config, session)
Check the reservation, creates a new one if nescessary.
4.223436
3.800937
1.111157
# we get trixxy here so we can manipulate these values in the wrapped function, # this is one of the first times I wish we were on Python 3 # http://stackoverflow.com/a/9264845/5006 reconn_params = { "count": count, "backoff": backoff } def retry_decorator(func): @w...
def reconnecting(count=None, backoff=None)
this is a very specific decorator meant to be used on Interface classes. It will attempt to reconnect if the connection is closed and run the same method again. TODO -- I think this will have issues with transactions using passed in connections, ie, you pass in a transacting connection to the insert()...
3.784705
3.657159
1.034876
if val is None: return None try: return quote(val, encoding="ascii", safe="/ ") except ValueError: return "utf-8''" + quote(val, encoding="utf-8", safe="/ ")
def escape_header(val)
Escapes a value so that it can be used in a mime header
4.661206
4.17702
1.115917
filename = None mime = None # user passed in a special dict. if isinstance(value, collections.Mapping) and "name" in value and "value" in value: filename = value["name"] try: mime = value["mime"] except KeyError: pass value = value["value"] ...
def make_streams(name, value, boundary, encoding)
Generates one or more streams for each name, value pair
2.281793
2.250459
1.013923
# The len property is needed for requests. # requests checks __len__, then len # Since we cannot implement __len__ because python 32-bit uses 32-bit # sizes, we implement this instead. def stream_len(stream): cur = stream.tell() try: ...
def len(self)
Length of the data stream
7.742774
7.41258
1.044545
return { "Content-Type": ("multipart/form-data; boundary={}".format(self.boundary)), "Content-Length": str(self.len), "Content-Encoding": self.encoding, }
def headers(self)
All headers needed to make a request
3.30253
3.252529
1.015373
"Indexes a thing by the keyfnc to construct pools of things." pools = {} sthings = sorted(things, key=keyfnc) for key, thingz in groupby(sthings, key=keyfnc): pools.setdefault(key, []).extend(list(thingz)) return pools
def mk_pools(things, keyfnc=lambda x: x)
Indexes a thing by the keyfnc to construct pools of things.
5.149545
3.372084
1.527111
"Picks a maximum of n things in a dict of indexed pool of things." pool = pools.get(key) if not pool: return [] things = pool[:n] del pool[:n] return things
def pick_things(pools, key, n)
Picks a maximum of n things in a dict of indexed pool of things.
5.381853
2.811616
1.914149
def onmessage(m): print(m) if m.admin or m.nick == r.user.name: return if "parrot" in m.msg.lower(): r.post_chat("ayy lmao") elif m.msg.lower() in ("lol", "lel", "kek"): r.post_chat("*kok") else: r.post_chat(re.sub...
def listen(room)
Open a volafile room and start listening to it
6.782956
6.93293
0.978368
fraction_pixel = y0_frontier_lower - int(y0_frontier_lower) if fraction_pixel > 0.0: nscan_min = int(y0_frontier_lower) + 1 else: nscan_min = int(y0_frontier_lower) if nscan_min < 1: if resize: nscan_min = 1 else: raise ValueError("nscan_min=...
def nscan_minmax_frontiers(y0_frontier_lower, y0_frontier_upper, resize=False)
Compute valid scan range for provided y0_frontier values. Parameters ---------- y0_frontier_lower : float Ordinate of the lower frontier. y0_frontier_upper : float Ordinate of the upper frontier. resize : bool If True, when the limits are beyond the expected values [1...
1.877523
1.618875
1.15977
result = DtuConfiguration() if len(list_of_objects) == 0: return result list_of_members = result.__dict__.keys() # compute average of all the members of the class for member in list_of_members: result.__dict__[member] = np.mean( [tmp_dtu.__dict__[member] for tmp_...
def average_dtu_configurations(list_of_objects)
Return DtuConfiguration instance with averaged values. Parameters ---------- list_of_objects : python list List of DtuConfiguration instances to be averaged. Returns ------- result : DtuConfiguration instance Object with averaged values.
3.222697
3.131942
1.028977
result = DtuConfiguration() if len(list_of_objects) == 0: return result list_of_members = result.__dict__.keys() # compute maximum difference for each member for member in list_of_members: tmp_array = np.array( [tmp_dtu.__dict__[member] for tmp_dtu in list_of_obj...
def maxdiff_dtu_configurations(list_of_objects)
Return DtuConfiguration instance with maximum differences. Parameters ---------- list_of_objects : python list List of DtuConfiguration instances to be averaged. Returns ------- result : DtuConfiguration instance Object with averaged values.
2.947064
2.716601
1.084835
# read input FITS file with fits.open(fitsobj) as hdulist: image_header = hdulist[extnum].header return cls.define_from_header(image_header)
def define_from_fits(cls, fitsobj, extnum=0)
Define class object from header information in FITS file. Parameters ---------- fitsobj: file object FITS file whose header contains the DTU information needed to initialise the members of this class. extnum : int Extension number (first extension is ...
3.565967
3.996758
0.892215
self = DtuConfiguration() for item in self.__dict__: self.__dict__[item] = inputdict[item] return self
def define_from_dictionary(cls, inputdict)
Define class object from dictionary. Parameters ---------- inputdict : dictionary like object Dictionary like object defining each member of the class.
7.490551
8.783985
0.852751
self = DtuConfiguration() # define DTU variables self.xdtu = xdtu self.ydtu = ydtu self.zdtu = zdtu self.xdtu_0 = xdtu_0 self.ydtu_0 = ydtu_0 self.zdtu_0 = zdtu_0 return self
def define_from_values(cls, xdtu, ydtu, zdtu, xdtu_0, ydtu_0, zdtu_0)
Define class object from from provided values. Parameters ---------- xdtu : float XDTU fits keyword value. ydtu : float YDTU fits keyword value. zdtu : float ZDTU fits keyword value. xdtu_0 : float XDTU_0 fits keyword value...
2.284465
2.242604
1.018666
result = \ (abs(self.xdtu - other.xdtu) <= abserror) and \ (abs(self.ydtu - other.ydtu) <= abserror) and \ (abs(self.zdtu - other.zdtu) <= abserror) and \ (abs(self.xdtu_0 - other.xdtu_0) <= abserror) and \ (abs(self.ydtu_0 - other.ydtu_0) <=...
def closeto(self, other, abserror)
Check that all the members are equal within provided absolute error. Parameters ---------- other : DtuConfiguration object DTU configuration instance to be compared with self. abserror : float Absolute maximum allowed error. Returns ------- ...
1.698171
1.688887
1.005497
output = self.__dict__.copy() for item in output: output[item] = round(output[item], ndigits) return output
def outdict(self, ndigits=3)
Return dictionary structure rounded to a given precision.
3.706164
2.935208
1.262658
if issuer.endswith('/'): _url = issuer[:-1] else: _url = issuer endpoint = {} for name, spec in conf.items(): try: kwargs = spec['kwargs'] except KeyError: kwargs = {} if isinstance(spec['class'], str): _instance = impor...
def build_endpoints(conf, endpoint_context, client_authn_method, issuer)
conf typically contains:: 'provider_config': { 'path': '.well-known/openid-configuration', 'class': ProviderConfiguration, 'kwargs': {} }, :param conf: :param endpoint_context: :param client_authn_method: :param issuer: :return:
2.19782
2.203349
0.997491
s = [] for a in args: s.append('{}:{}'.format(len(a), a)) return ''.join(s)
def lv_pack(*args)
Serializes using length:value format :param args: values :return: string
4.182646
3.856626
1.084535
txt = txt.strip() res = [] while txt: l, v = txt.split(':', 1) res.append(v[:int(l)]) txt = v[int(l):] return res
def lv_unpack(txt)
Deserializes a string of the length:value format :param txt: The input string :return: a list og values
3.062416
3.537882
0.865607
machines = self.provider_conf.machines networks = self.provider_conf.networks _networks = [] for network in networks: ipnet = IPNetwork(network.cidr) _networks.append({ "netpool": list(ipnet)[10:-10], "cidr": network.cidr, ...
def init(self, force_deploy=False)
Reserve and deploys the vagrant boxes. Args: force_deploy (bool): True iff new machines should be started
3.009127
3.055467
0.984834
v = vagrant.Vagrant(root=os.getcwd(), quiet_stdout=False, quiet_stderr=True) v.destroy()
def destroy(self)
Destroy all vagrant box involved in the deployment.
6.737244
4.646513
1.449957
instant_rate = self.count / float(self.tick_interval_s) self.count = 0 if self.initialized: self.rate += (self.alpha * (instant_rate - self.rate)) else: self.rate = instant_rate self.initialized = True
def tick(self)
Mark the passage of time and decay the current rate accordingly.
4.54446
3.857338
1.178134
# initialize resulting CsuConfiguration instance using one of the # input configuration corresponding to the odd-numbered slitlets merged_conf = deepcopy(conf_odd) # update the resulting configuration with the values corresponding # to the even-numbered slitlets for i in range(EMIR_NBARS)...
def merge_odd_even_csu_configurations(conf_odd, conf_even)
Merge CSU configuration using odd- and even-numbered values. The CSU returned CSU configuration include the odd-numbered values from 'conf_odd' and the even-numbered values from 'conf_even'. Parameters ---------- conf_odd : CsuConfiguration instance CSU configuration corresponding to odd-n...
2.942522
2.564006
1.147627