code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self = CsuConfiguration() # declare lists to store configuration of CSU bars self._csu_bar_left = [] self._csu_bar_right = [] self._csu_bar_slit_center = [] self._csu_bar_slit_width = [] for i in range(EMIR_NBARS): ibar = i + 1 ...
def define_from_header(cls, image_header)
Define class members directly from FITS header. Parameters ---------- image_header : instance of hdulist.header Header content from a FITS file.
2.934021
2.91355
1.007026
outdict = {} for i in range(EMIR_NBARS): ibar = i + 1 cbar = 'slitlet' + str(ibar).zfill(2) outdict[cbar] = {} outdict[cbar]['_csu_bar_left'] = \ round(self._csu_bar_left[i], ndigits) outdict[cbar]['_csu_bar_right'] = ...
def outdict(self, ndigits=3)
Return dictionary structure rounded to a given precision.
2.496307
2.436383
1.024596
list_ok = [] for i in range(EMIR_NBARS): slitlet_ok = minwidth <= self._csu_bar_slit_width[i] <= maxwidth if slitlet_ok: list_ok.append(i + 1) return list_ok
def widths_in_range_mm( self, minwidth=EMIR_MINIMUM_SLITLET_WIDTH_MM, maxwidth=EMIR_MAXIMUM_SLITLET_WIDTH_MM )
Return list of slitlets which width is within given range Parameters ---------- minwidth : float Minimum slit width (mm). maxwidth : float Maximum slit width (mm). Returns ------- list_ok : list List of booleans indicating whe...
5.354278
5.054981
1.059208
'''Encloses function backported from old photutils''' gout = circular_overlap_grid(x_min, x_max, y_min, y_max, nx, ny, r_out, 1, 1) gin = circular_overlap_grid(x_min, x_max, y_min, y_max, nx, ny, r_in, 1, 1) return gout - gin
def encloses_annulus(x_min, x_max, y_min, y_max, nx, ny, r_in, r_out)
Encloses function backported from old photutils
3.369344
2.552856
1.319833
''' center: [x,y], center of first pixel is [0,0] ''' x_min = -0.5 - xc x_max = img.shape[1] - 0.5 - xc y_min = -0.5 - yc y_max = img.shape[1] - 0.5 - yc mm = encloses_annulus(x_min, x_max, y_min, y_max, img.shape[1], img.shape[0], r_i...
def comp_back_with_annulus(img, xc, yc, r_in, r_out, frac=0.1)
center: [x,y], center of first pixel is [0,0]
4.212373
3.630261
1.16035
# protections naxis2, naxis1 = image_2k2k.shape if naxis1 != EMIR_NAXIS1: raise ValueError('Unexpected naxis1') if naxis2 != EMIR_NAXIS2: raise ValueError('Unexpected naxis2') # extract slitlet region slitlet2d = image_2k2k[(self.bb_ns1_...
def extract_slitlet2d(self, image_2k2k)
Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : numpy array Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2) Returns ------- slitlet2d : numpy array Image corresponding to the slitlet reg...
4.749906
3.913056
1.213861
if resampling not in [1, 2]: raise ValueError("Unexpected resampling value=" + str(resampling)) # check image dimension naxis2, naxis1 = slitlet2d.shape if naxis1 != self.bb_nc2_orig - self.bb_nc1_orig + 1: raise ValueError("Unexpected slitlet2d_rect na...
def rectify(self, slitlet2d, resampling, inverse=False)
Rectify slitlet using computed transformation. Parameters ---------- slitlet2d : numpy array Image containing the 2d slitlet image. resampling : int 1: nearest neighbour, 2: flux preserving interpolation. inverse : bool If true, the inverse re...
3.126655
2.975563
1.050777
title = "Slitlet#" + str(self.islitlet) ax = ximshow(slitlet2d, title=title, first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig), show=False) xdum = np.linspace(1, EMIR_NAXIS1, num=EMIR_NAXIS1) ylower = self.list_spectrails[0](xdum) ...
def ximshow_unrectified(self, slitlet2d)
Display unrectified image with spectrails and frontiers. Parameters ---------- slitlet2d : numpy array Array containing the unrectified slitlet image.
3.86369
3.660897
1.055394
title = "Slitlet#" + str(self.islitlet) + " (rectify)" ax = ximshow(slitlet2d_rect, title=title, first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig), show=False) # grid with fitted transformation: spectrum trails xx = np.arange(0, self.bb_...
def ximshow_rectified(self, slitlet2d_rect)
Display rectified image with spectrails and frontiers. Parameters ---------- slitlet2d_rect : numpy array Array containing the rectified slitlet image
4.515308
4.451956
1.01423
verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg]) _payload = verifier.unpack(token) if is_expired(_payload['exp']): raise ToOld('Token has expired') return _payload['sid'], _payload['ttype']
def info(self, token)
Return type of Token (A=Access code, T=Token, R=Refresh token) and the session id. :param token: A token :return: tuple of token type and session id
7.28335
8.231801
0.884782
verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg]) _payload = verifier.unpack(token) return is_expired(_payload['exp'], when)
def is_expired(self, token, when=0)
Evaluate whether the token has expired or not :param token: The token :param when: The time against which to check the expiration 0 means now. :return: True/False
5.997146
7.232504
0.829194
ws = await create_websocket( url, headers=headers, subprotocols=subprotocols) try: yield ws finally: await ws.close()
async def open_websocket(url: str, headers: Optional[list] = None, subprotocols: Optional[list] = None)
Opens a websocket.
3.389417
2.887816
1.173695
url = yarl.URL(url) args = {} if headers: args["headers"] = headers # automatically use ssl if it's websocket secure if ssl is None: ssl = url.scheme == "wss" if ssl: if ssl is True: ssl = SSLContext() args["ssl_context"] = ssl args["auto...
async def create_websocket(url: str, ssl: Optional[SSLContext] = None, headers: Optional[list] = None, subprotocols: Optional[list] = None)
A more low-level form of open_websocket. You are responsible for closing this websocket.
4.566817
4.286615
1.065367
ws = await create_websocket_client( sock, addr=addr, path=path, headers=headers, subprotocols=subprotocols) try: yield ws finally: await ws.close()
async def open_websocket_client(sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[list] = None, subprotocols: Optional[list] = None)
Create a websocket on top of a socket.
2.907146
2.302767
1.262458
ws = Websocket() await ws.start_client( sock, addr=addr, path=path, headers=headers, subprotocols=subprotocols) return ws
async def create_websocket_client(sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, subprotocols: Optional[List[str]] = None)
A more low-level form of create_websocket_client. You are responsible for closing this websocket.
4.325337
3.834125
1.128116
start = int(EUI(mac_start)) end = int(EUI(mac_end)) for i_mac in range(start, end, step): mac = EUI(int(EUI(i_mac)) + 1) ip = ['10'] + [str(int(i, 2)) for i in mac.bits().split('-')[-3:]] yield str(mac).replace('-', ':'), '.'.join(ip)
def range_mac(mac_start, mac_end, step=1)
Iterate over mac addresses (given as string).
3.731484
3.662856
1.018736
try: result = query.one() if result.has_expired(self._expirations): raise NotFoundError return result except (NoResultFound, MultipleResultsFound): raise NotFoundError
def _one(self, query)
Gets one row from the query. Raises NotFoundError if there isn't a row or if there are multiple rows
4.858922
4.271894
1.137417
result = query.first() if result is None: raise NotFoundError else: if result.has_expired(self._expirations): raise NotFoundError return result
def _first(self, query)
Gets the first row of the query. Raises NotFoundError if there isn't a row
4.906124
4.632868
1.058982
if query.count() > 0: results = query.all() for result in results: if result.has_expired(self._expirations): raise NotFoundError return results else: raise NotFoundError
def _all(self, query)
Gets all rows of the query. Raises a NotFoundError if there are 0 rows
4.816942
3.858861
1.248281
if item._dto_type in self._expirations and self._expirations[item._dto_type] == 0: # The expiration time has been set to 0 -> shoud not be cached return item.updated() self._session().merge(item)
def _put(self, item: SQLBaseObject)
Puts a item into the database. Updates lastUpdate column
10.131244
8.642488
1.17226
if cls._dto_type in self._expirations and self._expirations[cls._dto_type] == 0: # The expiration time has been set to 0 -> shoud not be cached return session = self._session for item in items: item = cls(**item) item.updated() ...
def _put_many(self, items: Iterable[DtoObject], cls)
Puts many items into the database. Updates lastUpdate column for each of them
6.476345
5.631695
1.149981
if user_info_claims is None: return copy.copy(userinfo) else: result = {} missing = [] optional = [] for key, restr in user_info_claims.items(): try: result[key] = userinfo[key] exce...
def filter(self, userinfo, user_info_claims=None)
Return only those claims that are asked for. It's a best effort task; if essential claims are not present no error is flagged. :param userinfo: A dictionary containing the available info for one user :param user_info_claims: A dictionary specifying the asked for claims :return: ...
2.646181
2.43882
1.085025
files = list() rooms = dict() msg = str() for part in data["message"]: ptype = part["type"] if ptype == "text": val = part["value"] msg += val elif ptype == "break": msg += "\n" elif...
def from_data(room, conn, data)
Construct a ChatMessage instance from raw protocol data
2.962945
2.84781
1.040429
ca = math.cos(angle) sa = math.sin(angle) return np.array([[ca, -sa], [sa, ca]])
def create_rot2d(angle)
Create 2D rotation matrix
2.183956
2.14515
1.01809
from matplotlib.patches import Ellipse if logger is None: logger = logging.getLogger(__name__) region = bounding_box.slice ref_x = region[1].start ref_y = region[0].start logger.debug('region ofset is %s, %s', ref_x, ref_y) subimage = data[region].copy() bkg = sep.Backgro...
def comp_centroid(data, bounding_box, debug_plot=False, plot_reference=None, logger=None)
Detect objects in a region and return the centroid of the brightest one
2.715544
2.618381
1.037108
_cntx = self.endpoint_context client_info = _cntx.cdb[client_id] alg_dict = get_sign_and_encrypt_algorithms(_cntx, client_info, 'id_token', sign=sign, encrypt=encrypt) _authn...
def sign_encrypt(self, session_info, client_id, code=None, access_token=None, user_info=None, sign=True, encrypt=False, extra_claims=None)
Signed and or encrypt a IDToken :param session_info: Session information :param client_id: Client ID :param code: Access grant :param access_token: Access Token :param user_info: User information :param sign: If the JWT should be signed :param encrypt: If the JWT...
3.319574
3.304577
1.004538
# import module containing the layer class mod = importlib.import_module(module, package) # get layer class definition from the module self.sources[src_cls] = getattr(mod, src_cls)
def add(self, src_cls, module, package=None)
Add layer class to model. This method may be overloaded by layer. :param src_cls: layer class to add, should not start with underscores :type src_cls: str :param module: Python module that contains layer class :type module: str :param package: optional package containing module ...
5.528083
4.879217
1.132986
super(Data, self).add(data_source, module, package) # only update layer info if it is missing! if data_source not in self.layer: # copy data source parameters to :attr:`Layer.layer` self.layer[data_source] = {'module': module, 'package': package} # add a ...
def add(self, data_source, module, package=None)
Add data_source to model. Tries to import module, then looks for data source class definition. :param data_source: Name of data source to add. :type data_source: str :param module: Module in which data source resides. Can be absolute or relative. See :func:`importlib.import_...
5.991246
6.748741
0.887758
if self.sources[data_source]._meta.data_reader.is_file_reader: filename = kwargs.get('filename') path = kwargs.get('path', '') rel_path = kwargs.get('rel_path', '') if len(args) > 0: filename = args[0] if len(args) > 1: ...
def open(self, data_source, *args, **kwargs)
Open filename to get data for data_source. :param data_source: Data source for which the file contains data. :type data_source: str Positional and keyword arguments can contain either the data to use for the data source or the full path of the file which contains data for the d...
3.273113
3.254241
1.005799
for k, v in self.layer.iteritems(): self.add(k, v['module'], v.get('package')) filename = v.get('filename') path = v.get('path') if filename: # default path for data is in ../data if not path: path = rel...
def load(self, rel_path=None)
Add data_sources to layer and open files with data for the data_source.
3.82378
3.379366
1.131508
# check if opening file if 'filename' in value: items = [k for k, v in self.reg.data_source.iteritems() if v == data_src] self.reg.unregister(items) # remove items from Registry # open file and register new data self.open(dat...
def edit(self, data_src, value)
Edit data layer. :param data_src: Name of :class:`DataSource` to edit. :type data_src: str :param value: Values to edit. :type value: dict
7.639223
7.459342
1.024115
items = self.objects[data_src].data.keys() # items to edit self.reg.unregister(items) # remove items from Registry self.layer.pop(data_src) # remove data source from layer self.objects.pop(data_src) # remove data_source object self.sources.pop(data_src)
def delete(self, data_src)
Delete data sources.
5.403089
5.199805
1.039095
super(Formulas, self).add(formula, module, package) # only update layer info if it is missing! if formula not in self.layer: # copy formula source parameters to :attr:`Layer.layer` self.layer[formula] = {'module': module, 'package': package} self.objects[...
def add(self, formula, module, package=None)
Import module (from package) with formulas, import formulas and add them to formula registry. :param formula: Name of the formula source to add/open. :param module: Module containing formula source. :param package: [Optional] Package of formula source module. .. seealso:: ...
6.555593
6.376769
1.028043
for k, v in self.layer.iteritems(): self.add(k, v['module'], v.get('package'))
def load(self, _=None)
Add formulas to layer.
11.27404
8.291697
1.359678
super(Calculations, self).add(calc, module, package) # only update layer info if it is missing! if calc not in self.layer: # copy calc source parameters to :attr:`Layer.layer` self.layer[calc] = {'module': module, 'package': package} # instantiate the cal...
def add(self, calc, module, package=None)
Add calc to layer.
6.249356
5.884264
1.062045
super(Outputs, self).add(output, module, package) # only update layer info if it is missing! if output not in self.layer: # copy output source parameters to :attr:`Layer.layer` self.layer[output] = {'module': module, 'package': package} # instantiate the ...
def add(self, output, module, package=None)
Add output to
6.080834
6.061125
1.003252
super(Simulations, self).add(sim, module, package) # only update layer info if it is missing! if sim not in self.layer: # copy simulation source parameters to :attr:`Layer.layer` self.layer[sim] = {'module': module, 'package': package}
def add(self, sim, module, package=None)
Add simulation to layer.
8.374898
6.719816
1.246299
for k, v in self.layer.iteritems(): self.add(k, v['module'], v.get('package')) filename = v.get('filename') path = v.get('path') if filename: warnings.warn(DeprecationWarning(SIMFILE_LOAD_WARNING)) # default path for data i...
def load(self, rel_path=None)
Add sim_src to layer.
5.217791
4.65967
1.119777
# pvlib converts Python datetime objects to pandas DatetimeIndex solpos = pvlib.solarposition.get_solarposition(times, latitude, longitude) # solpos is a pandas DataFrame, so unpack the desired values # return shape is (2, NOBS), so unc_wrapper sees 2 dependent variables return solpos['apparent...
def f_solpos(times, latitude, longitude)
Calculate solar position for lat/long at times. :param times: Python :class:`datetime.datetime` object. :type times: list :param latitude: latitude [degrees] :type latitude: float :param longitude: longitude [degrees] :type longitude: float :returns: apparent zenith, azimuth
8.764025
10.545808
0.831043
am_abs = am_abs.squeeze() # make a DataFrame for time series arguments df = pd.DataFrame( {'solar_zenith': solar_zenith, 'solar_azimuth': solar_azimuth, 'dni': dni, 'ghi': ghi, 'dhi': dhi, 'dni_extra': dni_extra, 'am_abs': am_abs}, index=times ) # calculate tot...
def f_total_irrad(times, surface_tilt, surface_azimuth, solar_zenith, solar_azimuth, dni, ghi, dhi, dni_extra, am_abs, model='haydavies')
Calculate total irradiance :param times: timestamps :param surface_tilt: panel tilt from horizontal [deg] :param surface_azimuth: panel azimuth from north [deg] :param solar_zenith: refracted solar zenith angle [deg] :param solar_azimuth: solar azimuth [deg] :param dni: direct normal irradiance...
2.020909
2.063405
0.979405
if type(array) is not np.ndarray: raise ValueError("array=" + str(array) + " must be a numpy.ndarray") array_min = array.min() array_max = array.max() z1, z2 = z1z2 delta = array_max - array_min b_flux = (z2 - z1) / delta c_flux = (z2 * array_min - z1 * array_max) / delta ...
def rescale_array_to_z1z2(array, z1z2=(-1.0, 1.0))
Rescale the values in a numpy array to the [z1,z2] interval. The transformation is carried out following the relation array_rs = b_flux * array - c_flux as explained in Appendix B1 of Cardiel (2009, MNRAS, 396, 680) Parameters ---------- array : numpy array Numpy array to be rescaled. ...
2.673111
2.194664
1.218005
if type(array_rs) is not np.ndarray: raise ValueError( "array_rs=" + str(array_rs) + "must be a numpy.ndarray") b_flux, c_flux = coef_rs array = (array_rs + c_flux) / b_flux return array
def rescale_array_from_z1z2(array_rs, coef_rs=None)
Restore the values in a numpy array rescaled to the [z1,z2] interval. The transformation is carried out following the relation array = (array_rs + c_flux)/b_flux as explained in Appendix B1 of Cardiel (2009, MNRAS, 396, 680) Parameters ---------- array_rs : numpy array Numpy array prev...
4.15867
3.368912
1.234425
if class_to_decorate is None: return functools.partial(with_meta, add_init_kwargs=add_init_kwargs) if add_init_kwargs: def get_extra_args_function(self): return {k: v for k, v in self.get_meta().items() if not k.startswith('_')} add_args_to_init_call(class_to_decorate...
def with_meta(class_to_decorate=None, add_init_kwargs=True)
Class decorator to enable a class (and it's sub-classes) to have a 'Meta' class attribute. :type class_to_decorate: class :param bool add_init_kwargs: Pass Meta class members to constructor :rtype: class
2.310568
2.509426
0.920756
merged_attributes = Struct() for class_ in reversed(cls.mro()): if hasattr(class_, 'Meta'): for key, value in class_.Meta.__dict__.items(): merged_attributes[key] = value return merged_attributes
def get_meta(cls)
Collect all members of any contained :code:`Meta` class declarations from the given class or any of its base classes. (Sub class values take precedence.) :type cls: class :rtype: Struct
3.702786
3.341073
1.108263
next_index = functools.partial(next, itertools.count()) __init__orig = class_to_decorate.__init__ @functools.wraps(__init__orig, assigned=['__doc__']) def __init__(self, *args, **kwargs): object.__setattr__(self, '_index', next_index()) __init__orig(self, *args, **kwargs) se...
def creation_ordered(class_to_decorate)
Class decorator that ensures that instances will be ordered after creation order when sorted. :type class_to_decorate: class :rtype: class
2.366475
2.482477
0.953271
if member_class is None and is_member is None: raise TypeError("get_members either needs a member_class parameter or an is_member check function (or both)") members = OrderedDict() for base in cls.__bases__: if _parameter is None: inherited_members = get_members(base, membe...
def get_members(cls, member_class=None, is_member=None, sort_key=None, _parameter=None)
Collect all class level attributes matching the given criteria. :param class member_class: Class(es) to collect :param is_member: Function to determine if an object should be collected :param sort_key: Function to invoke on members to obtain ordering (Default is to use ordering from `creation_o...
3.85117
3.821486
1.007768
if member_class is None and is_member is None: raise TypeError("The @declarative decorator needs either a member_class parameter or an is_member check function (or both)") def decorator(class_to_decorate): class DeclarativeMeta(class_to_decorate.__class__): # noinspection PyTyp...
def declarative(member_class=None, parameter='members', add_init_kwargs=True, sort_key=default_sort_key, is_member=None)
Class decorator to enable classes to be defined in the style of django models. That is, @declarative classes will get an additional argument to constructor, containing an OrderedDict with all class members matching the specified type. :param class member_class: Class(es) to collect :par...
2.434536
2.468331
0.986309
try: return object.__getattribute__(func, '__tri_declarative_signature') except AttributeError: pass try: if sys.version_info[0] < 3: # pragma: no mutate names, _, varkw, defaults = inspect.getargspec(func) # pragma: no mutate else: names, _, v...
def get_signature(func)
:type func: Callable :rtype: str
2.8555
2.904233
0.98322
namespaces = {} result = dict(values) for key, value in values.items(): parts = key.split('__', 1) # pragma: no mutate if len(parts) == 2: prefix, name = parts if prefix not in namespaces: initial_namespace = values.get(prefix) if...
def collect_namespaces(values)
Gather mappings with keys of the shape '<base_key>__<sub_key>' as new dicts under '<base_key>', indexed by '<sub_key>'. >>> foo = dict( ... foo__foo=1, ... foo__bar=2, ... bar__foo=3, ... bar__bar=4, ... foo_baz=5, ... baz=6 ... ) >>> assert collect_namespac...
2.53301
2.686068
0.943018
prefix += '__' result = {k[len(prefix):]: v for k, v in kwargs.items() if k.startswith(prefix)} if defaults is not None: return setdefaults(result, defaults) else: return result
def extract_subkeys(kwargs, prefix, defaults=None)
Extract mappings of the shape '<base_key>__<sub_key>' to new mappings under '<sub_key>'. >>> foo = { ... 'foo__foo': 1, ... 'foo__bar': 2, ... 'baz': 3, ... } >>> assert extract_subkeys(foo, 'foo', defaults={'quux': 4}) == { ... 'foo': 1, ... 'bar': 2, ... 'q...
3.094291
3.635012
0.851246
for k, v in d2.items(): d.setdefault(k, v) return d
def setdefaults(d, d2)
:type d: dict :type d2: dict :rtype: dict
2.406729
2.965944
0.811455
path = path.split('__') for name in path: obj = getattr(obj, name) if obj is None: return None return obj
def getattr_path(obj, path)
Get an attribute path, as defined by a string separated by '__'. getattr_path(foo, 'a__b__c') is roughly equivalent to foo.a.b.c but will short circuit to return None if something on the path is None.
2.581016
2.162356
1.193613
path = path.split('__') o = obj for name in path[:-1]: o = getattr(o, name) setattr(o, path[-1], value) return obj
def setattr_path(obj, path, value)
Set an attribute path, as defined by a string separated by '__'. setattr_path(foo, 'a__b__c', value) is equivalent to "foo.a.b.c = value".
2.424998
2.391922
1.013828
doc_by_filename = _generate_rst_docs(classes=classes, missing_objects=missing_objects) # pragma: no mutate for filename, doc in doc_by_filename: # pragma: no mutate with open(directory + filename, 'w') as f2: # pragma: no mutate f2.write(doc)
def generate_rst_docs(directory, classes, missing_objects=None)
Generate documentation for tri.declarative APIs :param directory: directory to write the .rst files into :param classes: list of classes to generate documentation for :param missing_objects: tuple of objects to count as missing markers, if applicable
3.375561
3.601092
0.937371
if keys is None: keys = reg.keys() reg_cls = type(reg) new_reg = reg_cls() mk = {} # empty dictionary for meta keys # loop over registry meta names for m in reg_cls.meta_names: mstar = getattr(reg, m, None) # current value of metakey in registry if not mstar: ...
def reg_copy(reg, keys=None)
Make a copy of a subset of a registry. :param reg: source registry :param keys: keys of registry items to copy :return: copied registry subset
5.20259
5.263131
0.988497
# number of formula arguments that are not constant argn = len(vargs) # number of observations must be the same for all vargs nobs = 1 c = [] # FIXME: can just loop ver varg, don't need indices I think, do we? for m in xrange(argn): a = vargs[...
def get_covariance(datargs, outargs, vargs, datvar, outvar)
Get covariance matrix. :param datargs: data arguments :param outargs: output arguments :param vargs: variable arguments :param datvar: variance of data arguments :param outvar: variance of output arguments :return: covariance
3.95569
4.021331
0.983677
rooms = set(r.conn for r in rooms) for room in rooms: room.validate_listeners() with ARBITRATOR.condition: while any(r.connected for r in rooms): ARBITRATOR.condition.wait() rooms = [r for r in rooms if r.run_queues()] if not rooms: r...
def listen_many(*rooms)
Listen for changes in all registered listeners in all specified rooms
6.175844
5.860547
1.0538
ws_url = ( f"{BASE_WS_URL}?room={self.room.room_id}&cs={checksum}&nick={username}" f"&rn={random_id(6)}&t={int(time.time() * 1000)}&transport=websocket&EIO=3" ) if password: ws_url += f"&password={password}" elif key: ws_url += f"...
def connect(self, username, checksum, password=None, key=None)
Connect to websocket through asyncio http interface
5.40325
5.185522
1.041988
if self.last_ack == self.proto.max_id: return LOGGER.debug("ack (%d)", self.proto.max_id) self.last_ack = self.proto.max_id self.send_message(f"4{to_json([self.proto.max_id])}")
def send_ack(self)
Send an ack message
5.693378
5.398537
1.054615
obj = {"fn": fun, "args": list(args)} obj = [self.proto.max_id, [[0, ["call", obj]], self.proto.send_count]] self.send_message(f"4{to_json(obj)}") self.proto.send_count += 1
def make_call(self, fun, *args)
Makes a regular API call
8.605462
8.630408
0.997109
cid, event = self.handler.register_callback() argscp = list(args) argscp.append(cid) self.make_call(fun, *argscp) return event
def make_call_with_cb(self, fun, *args)
Makes an API call with a callback to wait for
7.724852
8.679787
0.889982
if not isinstance(params, dict): raise ValueError("params argument must be a dictionary") kw = dict( params=params, headers={"Origin": BASE_URL, "Referer": f"{BASE_URL}/r/{self.room.name}"}, ) return self.get(BASE_REST_URL + call, **kw).json(...
def make_api_call(self, call, params)
Make a REST API call
4.921655
4.731742
1.040136
self.exception = ex self.process_queues(forced=True)
def reraise(self, ex)
Reraise an exception passed by the event thread
20.057934
17.29911
1.159478
if self.connected: obj = [self.proto.max_id, [[2], self.proto.send_count]] ARBITRATOR.send_sync_message(self.proto, f"4{to_json(obj)}") self.proto.send_count += 1 ARBITRATOR.close(self.proto) self.listeners.clear() self.proto.connected = ...
def close(self)
Closes connection pair
7.933199
7.503799
1.057224
self.__ensure_barrier() while self.connected: try: if self.__lastping > self.__lastpong: raise IOError("Last ping remained unanswered") self.send_message("2") self.send_ack() self.__lastping = time...
async def on_open(self)
DingDongmaster the connection is open
6.437217
5.868586
1.096894
# https://github.com/socketio/engine.io-protocol LOGGER.debug("new frame [%r]", new_data) try: what = int(new_data[0]) data = new_data[1:] data = data and from_json(data) if what == 0: self.ping_interval = float(data["ping...
def on_message(self, new_data)
Processes incoming messages according to engine-io rules
3.674527
3.488165
1.053427
if not self.connected: # wait for errors set by reraise method time.sleep(1) if self.exception: # pylint: disable=raising-bad-type raise self.exception raise ConnectionError(f"{self.room} is not connected") thread...
def add_listener(self, event_type, callback)
Add a listener for specific event type. You'll need to actually listen for changes using the listen method
9.130756
9.19711
0.992785
with self.lock: listeners = self.listeners.values() for listener in listeners: listener.enqueue(event_type, data) self.must_process = True
def enqueue_data(self, event_type, data)
Enqueue a data item for specific event type
5.290138
4.922785
1.074623
with self.lock: if (not forced and not self.must_process) or not self.queues_enabled: return self.must_process = False ARBITRATOR.awaken()
def process_queues(self, forced=False)
Process queues if any have data queued
8.349719
8.207871
1.017282
thread = get_thread_ident() with self.lock: return [l for tid, l in self.listeners.items() if tid == thread]
def __listeners_for_thread(self)
All Listeners for the current thread
6.36342
4.870748
1.306457
if self.exception: # pylint: disable=raising-bad-type raise self.exception listeners = self.__listeners_for_thread if not sum(len(l) for l in listeners): raise ValueError("No active listeners")
def validate_listeners(self)
Validates that some listeners are actually registered
7.496628
7.001759
1.070678
self.validate_listeners() with ARBITRATOR.condition: while self.connected: ARBITRATOR.condition.wait() if not self.run_queues(): break
def listen(self)
Listen for changes in all registered listeners.
11.361771
9.624522
1.180502
if self.exception: # pylint: disable=raising-bad-type raise self.exception listeners = self.__listeners_for_thread return sum(l.process() for l in listeners) > 0
def run_queues(self)
Run all queues that have data queued
9.467374
8.51247
1.112177
def getter(self): return self.config[key] def setter(self, val): if admin and not self.admin: raise RuntimeError( f"You can't set the {key} key without mod privileges" ) self.__set_config_value(self.config...
def __add_prop(self, key, admin=False)
Add gettable and settable room config property during runtime
4.283215
4.087822
1.047799
self.check_owner() params = {"room": self.room_id, "config": to_json({key: value})} resp = self.conn.make_api_call("setRoomConfig", params) if "error" in resp: raise RuntimeError(f"{resp['error'].get('message') or resp['error']}") return resp
def __set_config_value(self, key, value)
Sets a value for a room config
4.951442
4.253143
1.164184
if not self.name: room_resp = self.conn.get(BASE_URL + "/new") room_resp.raise_for_status() url = room_resp.url try: self.name = re.search(r"r/(.+?)$", url).group(1) except Exception: raise IOError("Failed to c...
def __get_config(self)
Really connect
4.036791
3.912554
1.031754
if once: # we listen for time event and return false so our # run_queues function will be also falsy and break the loop self.add_listener("time", lambda _: False) return self.conn.listen()
def listen(self, once=False)
Listen for changes in all registered listeners. Use add_listener before calling this funcion to listen for desired events or set `once` to True to listen for initial room information
22.809145
20.28109
1.124651
self.__files = OrderedDict( item for item in self.__files.items() if not item[1].expired )
def __expire_files(self)
Because files are always unclean
7.349083
6.058576
1.213005
k, v = kv if v is not None: self.__files.update({k: v}) else: with suppress(KeyError): del self.__files[k]
def filedict(self, kv)
Updates filedict with single file entry or deletes given key if the value is False. Shouldn't be used by the user.
4.258317
3.207702
1.327529
req = self.conn.get(BASE_URL + "/user/" + name) if req.status_code != 200 or not name: return None return self.conn.make_api_call("getUserInfo", {"name": name})
def get_user_stats(self, name)
Return data about the given user. Returns None if user does not exist.
5.607709
5.011824
1.118896
if len(msg) > self.config.max_message: raise ValueError( f"Chat message must be at most {self.config.max_message} characters." ) while not self.user.nick: with ARBITRATOR.condition: ARBITRATOR.condition.wait() if is_a:...
def post_chat(self, msg, is_me=False, is_a=False)
Posts a msg to this room's chat. Set me=True if you want to /me
3.951405
4.009948
0.985401
with delayed_close( filename if hasattr(filename, "read") else open(filename, "rb") ) as file: filename = upload_as or os.path.split(filename)[1] try: file.seek(0, 2) if file.tell() > self.config.max_file: ...
def upload_file( self, filename, upload_as=None, blocksize=None, callback=None, information_callback=None, allow_timeout=False, )
Uploads a file with given filename to this room. You may specify upload_as to change the name it is uploaded as. You can also specify a blocksize and a callback if you wish. Returns the file's id on success and None on failure.
3.38432
3.476765
0.973411
if hasattr(self, "conn"): self.conn.close() del self.conn if hasattr(self, "user"): del self.user
def close(self)
Close connection to this room
4.159931
3.437514
1.210157
key, value = kv self.__user_info[key] = value
def user_info(self, kv)
Sets user_info dict entry through a tuple.
8.914886
3.925828
2.270829
if not isinstance(fid, str): raise TypeError("Your file ID must be a string") try: info = self.conn.make_call_with_cb("getFileinfo", fid).get(timeout=5) if not info: warnings.warn( f"Your query for file with ID: '{fid}' fa...
def fileinfo(self, fid)
Ask lain about what he knows about given file. If the given file exists in the file dict, it will get updated.
7.62936
6.93216
1.100575
# Wait for server to set username if not set already. while not self.user.nick: with ARBITRATOR.condition: ARBITRATOR.condition.wait() while True: params = { "name": self.user.nick, "room": self.room_id, ...
def _generate_upload_key(self, allow_timeout=False)
Generates a new upload key
4.5766
4.528913
1.010529
self.check_owner() if not isinstance(ids, list): raise TypeError("You must specify list of files to delete!") self.conn.make_call("deleteFiles", ids)
def delete_files(self, ids)
Remove one or more files
7.569033
7.01837
1.07846
if not self.owner and not self.admin: raise RuntimeError("You need more street creed to do this") new_owner = new_owner.strip().lower() if not new_owner: raise ValueError("Empty strings cannot be new owners") self.__set_config_value("owner", new_owner)
def transfer_owner(self, new_owner)
You had good run at it, it's time for someone else to get dirty
6.996301
6.804993
1.028113
if not self.owner and not self.admin: raise RuntimeError("Not enough street creed to do this") janitor = janitor.strip().lower() if not janitor: raise ValueError("Empty strings cannot be janitors") if janitor in self.config.janitors: return...
def add_janitor(self, janitor)
Add janitor to the room
4.468834
4.139602
1.079532
if not self.owner and not self.admin: raise RuntimeError("Not enough street creed to do this") janitor = janitor.strip().lower() if not janitor: raise ValueError("Empty strings cannot be janitors") if janitor not in self.config.janitors: re...
def remove_janitor(self, janitor)
Remove janitor from the room
4.589288
4.182637
1.097223
def decorator(fn): @wraps(fn) def decorated(*args, **kwargs): # Constructs the environment # --env or env are reserved keyword to reuse existing env k_env = kwargs.get("--env") or kwargs.get("env") if new: kwargs["env"] = _make_env...
def enostask(new=False)
Decorator for an Enos Task. This decorator lets you define a new Enos task and helps you manage the environment. It injects the environment in the function called. Args: new (bool): indicates if a new environment must be created. Usually this is set on the first task of the workflow. ...
4.881347
4.71436
1.035421
env = { "config": {}, # The config "resultdir": "", # Path to the result directory "config_file": "", # The initial config file "nodes": {}, # Roles with nodes "phase": "", # Last phase that have been run ...
def _make_env(resultdir=None)
Loads the env from `resultdir` if not `None` or makes a new one. An Enos environment handles all specific variables of an experiment. This function either generates a new environment or loads a previous one. If the value of `resultdir` is `None`, then this function makes a new environment and return it...
3.055629
3.164831
0.965495
env_path = os.path.join(env["resultdir"], "env") if os.path.isdir(env["resultdir"]): with open(env_path, "w") as f: yaml.dump(env, f)
def _save_env(env)
Saves one environment. Args: env (dict): the env dict to save.
3.102027
4.210304
0.73677
def decorator(*args, **kwargs): # If no directory is provided, set the default one resultdir = kwargs.get("--env", SYMLINK_NAME) # Check if the env file exists env_path = os.path.join(resultdir, "env") if not os.path.isfile(env_path): raise Exception("The fil...
def _check_env(fn)
Decorator for an Enos Task. This decorator checks if an environment file exists.
4.536268
4.662856
0.972852
# Compute file path of results directory resultdir_name = name or "enos_" + datetime.today().isoformat() resultdir_path = os.path.abspath(resultdir_name) # Raise error if a related file exists if os.path.isfile(resultdir_path): raise EnosFilePathError(resultdir_path, ...
def _set_resultdir(name=None)
Set or get the directory to store experiment results. Looks at the `name` and create the directory if it doesn"t exist or returns it in other cases. If the name is `None`, then the function generates an unique name for the results directory. Finally, it links the directory to `SYMLINK_NAME`. Args...
3.427488
3.27014
1.048117
kwargs.update(zip(self.meta_names, args)) # check uncertainty has units of percent uncertainty = kwargs['uncertainty'] variance = kwargs['variance'] isconstant = kwargs['isconstant'] # check uncertainty is percent if uncertainty: for k0, d in ...
def register(self, newdata, *args, **kwargs)
Register data in registry. Meta for each data is specified by positional or keyword arguments after the new data and consists of the following: * ``uncertainty`` - Map of uncertainties in percent corresponding to new keys. The uncertainty keys must be a subset of the new data keys. * ...
3.807596
3.200902
1.189538
# extension must start with a dot if not ext.startswith('.'): # prepend extension with a dot ext = '.%s' % ext # cache file is filename with extension cache_file = '%s%s' % (self.filename, ext) # if filename already ends with extension or there's ...
def _is_cached(self, ext='.json')
Determine if ``filename`` is cached using extension ``ex`` a string. :param ext: extension used to cache ``filename``, default is '.json' :type ext: str :return: True if ``filename`` is cached using extensions ``ex`` :rtype: bool
4.149065
4.318237
0.960824
# make pycharm by defining inferred objects meta = getattr(self, DataSourceBase._meta_attr) param_file = getattr(self, DataSourceBase._param_file) # JSONEncoder removes units and converts arrays to lists # save last time file was modified utc_mod_time = list(time...
def saveas_json(self, save_name)
Save :attr:`data`, :attr:`param_file`, original :attr:`data_reader` and UTC modification time as keys in JSON file. If data is edited then it should be saved using this method. Non-JSON data files are also saved using this method. :param save_name: Name to save JSON file as, ".json" is ...
5.566792
4.770852
1.166834
data_reg.update(edits) self._is_saved = False
def edit(self, edits, data_reg)
Edit data in :class:`Data_Source`. Sets :attr:`issaved` to ``False``.
9.322305
5.910421
1.577266
# protection if not isinstance(s, str): print('type(s): ', type(s)) print('ERROR: function expected a string parameter') # initialize empty output set_slitlets = set() # remove leading blank spaces s = re.sub('^ *', '', s) # remove trailing blank spaces s = re.sub...
def list_slitlets_from_string(s, islitlet_min, islitlet_max)
Return list of slitlets from string specification. Parameters ---------- s : string String defining the slitlets. The slitlets must be specify as a set of n1[,n2[,step]] tuples. If only n1 is provided, the slitlet number n1 is considered. When n1 and n2 are given but step is...
2.356879
2.275109
1.035941