code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
event = await self._next_event() if not isinstance(event, Request): raise ConnectionError("Failed to establish a connection", event) msg = None if filter is not None: msg = await filter(event) ...
async def start_server(self, sock: anyio.abc.SocketStream, filter=None): # pylint: disable=W0622 assert self._scope is None self._scope = True self._sock = sock self._connection = WSConnection(ConnectionType.SERVER) try
Start a server WS connection on this socket. Filter: an async callable that gets passed the initial Request. It may return an AcceptConnection message, a bool, or a string (the subprotocol to use). Returns: the Request message.
3.73212
3.172382
1.176441
while True: for event in self._connection.events(): if isinstance(event, Message): # check if we need to buffer if event.message_finished: return self._wrap_data(self._gather_buffers(event)) ...
async def _next_event(self)
Gets the next event.
5.446595
5.357689
1.016594
if self._closed: return self._closed = True if self._scope is not None: await self._scope.cancel() # cancel any outstanding listeners data = self._connection.send(CloseConnection(code=code, reason=reason)) await self._sock.send_all(...
async def close(self, code: int = 1006, reason: str = "Connection closed")
Closes the websocket.
6.74625
6.214086
1.085638
MsgType = TextMessage if isinstance(data, str) else BytesMessage data = MsgType(data=data, message_finished=final) data = self._connection.send(event=data) await self._sock.send_all(data)
async def send(self, data: Union[bytes, str], final: bool = True)
Sends some data down the connection.
7.427315
6.098026
1.217987
if isinstance(event, BytesMessage): self._byte_buffer.write(event.data) elif isinstance(event, TextMessage): self._string_buffer.write(event.data)
def _buffer(self, event: Message)
Buffers an event, if applicable.
3.300754
2.495726
1.322563
if isinstance(event, BytesMessage): buf = self._byte_buffer else: buf = self._string_buffer # yay for code shortening buf.write(event.data) buf.seek(0) data = buf.read() buf.seek(0) buf.truncate() return data
def _gather_buffers(self, event: Message)
Gathers all the data from a buffer.
4.405514
3.8693
1.138582
MsgType = TextMessage if isinstance(data, str) else BytesMessage return MsgType(data=data, frame_finished=True, message_finished=True)
def _wrap_data(data: Union[str, bytes])
Wraps data into the right event.
8.583966
6.161707
1.393115
field_type = "" is_pk = field.options.get('pk', False) if issubclass(field.type, bool): field_type = 'BOOLEAN' elif issubclass(field.type, long): if is_pk: field_type = 'INTEGER PRIMARY KEY' else: field_type =...
def get_field_SQL(self, field_name, field)
returns the SQL for a given field with full type information http://www.sqlite.org/datatype3.html field_name -- string -- the field's name field -- Field() -- the set options for the field return -- string -- the field type (eg, foo BOOL NOT NULL)
2.857313
2.816806
1.014381
query_str = [] query_str.append("CREATE TABLE {} (".format(self._normalize_table_name(schema))) query_fields = [] for field_name, field in schema.fields.items(): query_fields.append(' {}'.format(self.get_field_SQL(field_name, field))) query_str.append(",{}...
def _set_table(self, schema, **kwargs)
http://sqlite.org/lang_createtable.html
2.908107
2.669065
1.08956
query_str = "CREATE {}INDEX IF NOT EXISTS '{}_{}' ON {} ({})".format( 'UNIQUE ' if index_options.get('unique', False) else '', schema, name, self._normalize_table_name(schema), ', '.join((self._normalize_name(f) for f in fields)) ) ...
def _set_index(self, schema, name, fields, **index_options)
https://www.sqlite.org/lang_createindex.html
3.134151
2.720668
1.151979
# http://www.sqlite.org/pragma.html#schema # http://www.mail-archive.com/sqlite-users@sqlite.org/msg22055.html # http://stackoverflow.com/questions/604939/ ret = {} rs = self._query('PRAGMA index_list({})'.format(self._normalize_table_name(schema)), **kwargs) if ...
def _get_indexes(self, schema, **kwargs)
return all the indexes for the given schema
3.32475
3.126959
1.063254
ret = {} query_str = 'PRAGMA table_info({})'.format(self._normalize_table_name(table_name)) fields = self._query(query_str, **kwargs) #pout.v([dict(d) for d in fields]) query_str = 'PRAGMA foreign_key_list({})'.format(self._normalize_table_name(table_name)) fks ...
def _get_fields(self, table_name, **kwargs)
return all the fields for the given table
3.300529
3.276844
1.007228
fstrs = [] k_opts = { 'day': "CAST(strftime('%d', {}) AS integer)", 'hour': "CAST(strftime('%H', {}) AS integer)", 'doy': "CAST(strftime('%j', {}) AS integer)", # day of year 'julian_day': "strftime('%J', {})", # YYYY-MM-DD 'month': "C...
def _normalize_date_SQL(self, field_name, field_kwargs, symbol)
allow extracting information from date http://www.sqlite.org/lang_datefunc.html
3.018919
2.917174
1.034878
fvi = None if sort_dir_str == 'ASC': fvi = (t for t in enumerate(field_vals)) else: fvi = (t for t in enumerate(reversed(field_vals))) query_sort_str = [' CASE {}'.format(self._normalize_name(field_name))] query_args = [] for i, v in ...
def _normalize_sort_SQL(self, field_name, field_vals, sort_dir_str)
allow sorting by a set of values http://stackoverflow.com/questions/3303851/sqlite-and-custom-order-by
3.068046
3.071789
0.998781
kwargs.update(zip(self.meta_names, args)) # dependencies should be a list of other calculations if isinstance(kwargs['dependencies'], basestring): kwargs['dependencies'] = [kwargs['dependencies']] # call super method, now meta can be passed as args or kwargs. ...
def register(self, new_calc, *args, **kwargs)
Register calculations and meta data. * ``dependencies`` - list of prerequisite calculations * ``always_calc`` - ``True`` if calculation ignores thresholds * ``frequency`` - frequency of calculation in intervals or units of time :param new_calc: register new calculation
6.212064
5.745625
1.081182
# open output file and insert header ds9reg.write('# Region file format: DS9 version 4.1\n') ds9reg.write( 'global color=green dashlist=8 3 width=1 font="helvetica 10 ' 'normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 ' 'move=1 delete=1 include=1 source=1\n') ds9re...
def slits_to_ds9_reg(ds9reg, slits)
Transform fiber traces to ds9-region format. Parameters ---------- ds9reg : BinaryIO Handle to output file name in ds9-region format.
2.491209
2.521822
0.987861
dtfmt = '%Y%m%d-%H%M%S' return '%s-%s' % (obj.__class__.__name__, datetime.now().strftime(dtfmt))
def id_maker(obj)
Makes an ID from the object's class name and the datetime now in ISO format. :param obj: the class from which to make the ID :return: ID
3.227588
3.099376
1.041367
# find all edges of dag topsort = [node for node, edge in dag.iteritems() if not edge] # loop through nodes until topologically sorted while len(topsort) < len(dag): num_nodes = len(topsort) # number of nodes # unsorted nodes for node in dag.viewkeys() - set(topsort): ...
def topological_sort(dag)
topological sort :param dag: directed acyclic graph :type dag: dict .. seealso:: `Topographical Sorting <http://en.wikipedia.org/wiki/Topological_sorting>`_, `Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`_
3.181424
3.361802
0.946345
kwargs.update(zip(self.meta_names, args)) # call super method, now meta can be passed as args or kwargs. super(SimRegistry, self).register(sim, **kwargs)
def register(self, sim, *args, **kwargs)
register simulation and metadata. * ``commands`` - list of methods to callable from model :param sim: new simulation
9.799756
11.350941
0.863343
data_objs = { data_src: data.objects.get(data_src) for data_src in data.layer } self._is_data_loaded = all(data_objs.values()) return data_objs
def check_data(self, data)
Check if data loaded for all sources in data layer. :param data: data layer from model :type data: :class:`~simkit.core.layer.Data` :return: dictionary of data sources and objects or `None` if not loaded
6.85013
4.923908
1.391198
self._isinitialized = True # TODO: if calculations are edited, loaded, added, etc. then reset self.calc_order = topological_sort(calc_reg.dependencies)
def initialize(self, calc_reg)
Initialize the simulation. Organize calculations by dependency. :param calc_reg: Calculation registry. :type calc_reg: :class:`~simkit.core.calculation.CalcRegistry`
19.316126
19.440664
0.993594
idx = 0 # index while idx < self.number_intervals: new_idx = yield idx idx += 1 if new_idx: idx = new_idx - 1
def index_iterator(self)
Generator that resumes from same index, or restarts from sent index.
5.992074
5.447239
1.10002
# default progress hook if progress_hook is None: progress_hook = sim_progress_hook progress_hook('simulation paused') self.cmd_queue.put('pause') self._ispaused = True
def pause(self, progress_hook=None)
Pause the simulation. How is this different from stopping it? Maintain info sufficient to restart simulation. Sets ``is_paused`` to True. Will this state allow analysis? changing parameters? What can you do with a paused simulation? Should be capable of saving paused simulation for loadi...
6.818698
6.263712
1.088603
ds9_file = open(filename, 'wt') ds9_file.write(output) ds9_file.close()
def save_ds9(output, filename)
Save ds9 region output info filename. Parameters ---------- output : str String containing the full output to be exported as a ds9 region file. filename : str Output file name.
2.598456
3.040136
0.854717
for limits, rectified, suffix in zip( ['frontiers', 'frontiers', 'boundaries', 'boundaries'], [False, True, False, True], ['rawimage', 'rectified', 'rawimage', 'rectified'] ): output = rectwv_coeff_to_ds9(rectwv_coeff=rectwv_coeff, limit...
def save_four_ds9(rectwv_coeff, debugplot=0)
Save the 4 possible ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugplot : int Debugging level for messages and plots. For details see '...
5.001323
4.709226
1.062027
for spectral_lines, rectified, suffix in zip( ['arc', 'arc', 'oh', 'oh'], [False, True, False, True], ['rawimage', 'rectified', 'rawimage', 'rectified'] ): output = spectral_lines_to_ds9(rectwv_coeff=rectwv_coeff, spectral_lines=spectr...
def save_spectral_lines_ds9(rectwv_coeff, debugplot=0)
Save expected location of arc and OH airglow to ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugplot : int Debugging level for messages and plots. F...
4.208146
4.039975
1.041627
_pinfo = self.package_capabilities() not_supported = {} for key, val in capabilities.items(): try: allowed = _pinfo[key] except KeyError: _pinfo[key] = val else: if isinstance(allowed, bool): ...
def create_providerinfo(self, capabilities)
Dynamically create the provider info response :param capabilities: :return:
2.687799
2.701079
0.995083
write('h', len(value)) write.io.write(value.encode('utf-8'))
def _write_utf8(write, value)
Writes a length-prefixed UTF-8 string.
10.123864
6.75515
1.498688
name = cls._read_utf8(read) if has_name else None if cls is TAG_Compound: # A TAG_Compound is almost identical to Python's native dict() # object, or a Java HashMap. final = {} while True: # Find the type of each tag in a compound...
def read(cls, read, has_name=True)
Read the tag in using the reader `rd`. If `has_name` is `False`, skip reading the tag name.
2.38847
2.390718
0.99906
return '{0}{1}({2!r}): {3!r}'.format( indent_str * indent, self.__class__.__name__, self.name, self.value )
def pretty(self, indent=0, indent_str=' ')
Pretty-print a tag in the same general style as Markus's example output.
2.80266
3.224755
0.869108
super(TAG_Compound, self).update(*args, **kwargs) for key, item in self.items(): if item.name is None: item.name = key
def update(self, *args, **kwargs)
See `__setitem__`.
5.113648
4.116048
1.242368
if little_endian: write = lambda fmt, *args: io.write(pack('<' + fmt, *args)) else: write = lambda fmt, *args: io.write(pack('>' + fmt, *args)) write.io = io self.write(write)
def save(self, io, little_endian=False)
Saves the `NBTFile()` to `io`, which can be any file-like object providing `write()`.
3.026575
2.636518
1.147944
TTYPE = {'code': 'A', 'token': 'T', 'refresh': 'R'} args = {} if code: args['code_handler'] = init_token_handler(ec, code, TTYPE['code']) if token: args['access_token_handler'] = init_token_handler(ec, token, TTYPE['token']) if refresh: args['refresh_token_handler'] =...
def factory(ec, code=None, token=None, refresh=None, **kwargs)
Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance
2.720545
2.641207
1.030038
csum = hashlib.new('sha224') csum.update(rndstr(32).encode('utf-8')) return csum.hexdigest()
def key(self, user="", areq=None)
Return a key (the session id) :param user: User id :param areq: The authorization request :return: An ID
5.498795
6.030352
0.911853
_res = dict(zip(['_id', 'type', 'sid', 'exp'], self.split_token(token))) if _res['type'] != self.type: raise WrongTokenType(_res['type']) else: _res['handler'] = self _res['black_listed'] = self.is_black_listed(token) ...
def info(self, token)
Return token information. :param token: A token :return: dictionary with info about the token
5.943502
5.928087
1.0026
wildcard_zs = set() total_fraction = 0.0 for z, fraction in fractions.items(): if fraction == '?': wildcard_zs.add(z) else: total_fraction += fraction if not wildcard_zs: return fractions balance_fraction = (1.0 - total_fraction) / len(wildcard_...
def process_wildcard(fractions)
Processes element with a wildcard ``?`` weight fraction and returns composition balanced to 1.0.
2.486809
2.230513
1.114905
atomic_fractions = {} for z, mass_fraction in mass_fractions.items(): atomic_fractions[z] = mass_fraction / pyxray.element_atomic_weight(z) total_fraction = sum(atomic_fractions.values()) for z, fraction in atomic_fractions.items(): try: atomic_fractions[z] = fraction...
def convert_mass_to_atomic_fractions(mass_fractions)
Converts a mass fraction :class:`dict` to an atomic fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the values weight fractions. No wildcard are accepted.
2.178515
2.5962
0.839117
# Calculate total atomic mass atomic_masses = {} total_atomic_mass = 0.0 for z, atomic_fraction in atomic_fractions.items(): atomic_mass = pyxray.element_atomic_weight(z) atomic_masses[z] = atomic_mass total_atomic_mass += atomic_fraction * atomic_mass # Create mass fra...
def convert_atomic_to_mass_fractions(atomic_fractions)
Converts an atomic fraction :class:`dict` to a mass fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the values atomic fractions. No wildcard are accepted.
2.210612
2.18229
1.012978
mole_fractions = {} total_mole_fraction = 0.0 for match in CHEMICAL_FORMULA_PATTERN.finditer(formula): symbol, mole_fraction = match.groups() z = pyxray.element_atomic_number(symbol.strip()) if mole_fraction == '': mole_fraction = 1.0 mole_fraction = float...
def convert_formula_to_atomic_fractions(formula)
Converts a chemical formula to an atomic fraction :class:`dict`. Args: formula (str): chemical formula, like Al2O3. No wildcard are accepted.
2.396463
2.571813
0.931819
if not atomic_fractions: return '' if len(atomic_fractions) == 1: z = list(atomic_fractions.keys())[0] return pyxray.element_symbol(z) symbols = [] fractions = [] for z in sorted(atomic_fractions.keys(), reverse=True): symbols.append(pyxray.element_symbol(z)) ...
def generate_name(atomic_fractions)
Generates a name from the composition. The name is generated on the basis of a classical chemical formula.
2.382763
2.384359
0.999331
return cls(cls._key, {z: 1.0}, {z: 1.0}, pyxray.element_symbol(z))
def from_pure(cls, z)
Creates a pure composition. Args: z (int): atomic number
12.523059
12.120146
1.033243
mass_fractions = process_wildcard(mass_fractions) atomic_fractions = convert_mass_to_atomic_fractions(mass_fractions) if not formula: formula = generate_name(atomic_fractions) return cls(cls._key, mass_fractions, atomic_fractions, formula)
def from_mass_fractions(cls, mass_fractions, formula=None)
Creates a composition from a mass fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The keys are atomic numbers and the values weight fractions. Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron will get a m...
4.083456
5.412987
0.754381
atomic_fractions = process_wildcard(atomic_fractions) mass_fractions = convert_atomic_to_mass_fractions(atomic_fractions) if not formula: formula = generate_name(atomic_fractions) return cls(cls._key, mass_fractions, atomic_fractions, formula)
def from_atomic_fractions(cls, atomic_fractions, formula=None)
Creates a composition from an atomic fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The keys are atomic numbers and the values atomic fractions. Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron will ...
4.095366
5.23734
0.781955
samples = [] urls = [self.path_generator.generate_url(url, url_pattern) for _ in range(self.confirmation_factor)] iterator = asyncio.as_completed([self._fetch_sample(url) for url in urls]) for promise in iterator: try: sig = await promise ...
async def _collect_sample(self, url, url_pattern)
Sample collection is meant to be very tolerant to generic failures as failing to obtain the sample has important consequences on the results. - Multiple retries with longer delays - Larger than usual timeout
5.23952
5.227343
1.002329
path = urlparse(url).path directories, filename = os.path.split(path) if len(filename) > 0: pattern = self.get_pattern_for_filename(filename) if directories[-1] != "/": directories += "/" return directories + pattern else: ...
def get_pattern(self, url)
Return the path part of the URL with the last element replaced with its pattern in a regex-like format: \l -> lowercase letters, same as [a-z]+ \L -> uppercase letters, same as [A-Z]+ \i -> letters ignoring case, same as [a-zA-Z]+ \d -> digits, same as \d+ \w -> word characters (...
3.037919
3.249381
0.934922
bounddict = json.loads(open(bounddict_file.name).read()) # return values in case the requested slitlet number is not defined pol_lower_boundary = None pol_upper_boundary = None xmin_lower = None xmax_lower = None xmin_upper = None xmax_upper = None csu_bar_slit_center = None ...
def get_boundaries(bounddict_file, slitlet_number)
Read the bounddict json file and return the polynomial boundaries. Parameters ---------- bounddict_file : file handler File containing the bounddict JSON data. slitlet_number : int Number of slitlet. Returns ------- pol_lower_boundary : numpy polynomial Polynomial d...
2.193086
1.820217
1.204848
def to_host(h): extra = {} # create extra_vars for the nics # network_role = ethX for nic, roles in h["nics"]: for role in roles: extra[role] = nic return Host(h["host"], user="root", extra=extra) enos_roles = {} for role, hosts in ...
def _to_enos_roles(roles)
Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init`
5.500197
5.336235
1.030726
nets = [] for roles, network in networks: nets.append(network.to_enos(roles)) logger.debug(nets) return nets
def _to_enos_networks(networks)
Transform the networks returned by deploy5k. Args: networks (dict): networks returned by :py:func:`enoslib.infra.provider.Provider.init`
6.203685
8.685902
0.714225
_force_deploy = self.provider_conf.force_deploy self.provider_conf.force_deploy = _force_deploy or force_deploy self._provider_conf = self.provider_conf.to_dict() r = api.Resources(self._provider_conf, client=client) r.launch() roles = r.get_roles() netwo...
def init(self, force_deploy=False, client=None)
Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be redeployed Raises: MissingNetworkError: If ...
4.891963
5.423041
0.90207
r = api.Resources(self.provider_conf.to_dict()) # insert force_deploy r.destroy()
def destroy(self)
Destroys the jobs.
47.44894
44.674541
1.062102
url = 'https://en.wikipedia.org/w/api.php' params = {'action': 'query', 'titles': name_en, 'prop': 'langlinks', 'lllimit': 500, 'format': 'json'} r = requests.get(url, params=params) if not r: ra...
def _find_wikipedia_names(self, name_en)
Finds all Wikipedia pages referring to the specified name in English and returns a dictionary where the keys are the language code and the values are the titles of the corresponding pages.
1.994622
1.955804
1.019848
self._responses.append(response) if 'Warning' in response.headers: LOGGER.warning( 'HTTP %s %s Warning (%s): %s (attempt %s)', response.request.method, response.request.url, response.code, response.headers['Warning'], l...
def append_response(self, response)
Append the response to the stack of responses. :param tornado.httpclient.HTTPResponse response: The HTTP response
4.142072
4.100667
1.010097
if not self._responses: return None if self._responses[-1].code >= 400: return self._error_message() return self._deserialize()
def body(self)
Returns the HTTP response body, deserialized if possible. :rtype: mixed
7.627314
6.859312
1.111965
if not self._responses: return None if 'Link' in self._responses[-1].headers: links = [] for l in headers.parse_link(self._responses[-1].headers['Link']): link = {'target': l.target} link.update({k: v for (k, v) in l.parameters...
def links(self)
Return the parsed link header if it was set, returning a list of the links as a dict. :rtype: list(dict()) or None
3.660969
3.357036
1.090536
if isinstance(value, list): return [self._decode(v) for v in value] elif isinstance(value, dict): return {self._decode(k): self._decode(v) for k, v in value.items()} elif isinstance(value, bytes): return value.decode('utf-8') ...
def _decode(self, value)
Decode bytes to UTF-8 strings as a singe value, list, or dict. :param mixed value: The value to decode :rtype: mixed
1.731439
1.785144
0.969916
if not self._responses or not self._responses[-1].body: return None if 'Content-Type' not in self._responses[-1].headers: return self._responses[-1].body try: content_type = algorithms.select_content_type( [headers.parse_content_type( ...
def _deserialize(self)
Try and deserialize a response body based upon the specified content type. :rtype: mixed
2.922588
2.857147
1.022904
body = self._deserialize() return body.get('message', body) if isinstance(body, dict) else body
def _error_message(self)
Try and extract the error message from a HTTP error response. :rtype: str
12.219338
9.613459
1.271066
if not request_headers: request_headers = {} request_headers.setdefault( 'Accept', ', '.join([str(ct) for ct in AVAILABLE_CONTENT_TYPES])) if body: request_headers.setdefault( 'Content-Type', str(content_type) or str(CONTENT_TYPE_MSGPA...
def _http_req_apply_default_headers(self, request_headers, content_type, body)
Set default values for common HTTP request headers :param dict request_headers: The HTTP request headers :param content_type: The mime-type used in the request/response :type content_type: :py:class:`ietfparse.datastructures.ContentType` or str :param mixed body: The request...
2.26665
2.388569
0.948957
if not body or not isinstance(body, (dict, list)): return body content_type = headers.parse_content_type(content_type) if content_type == CONTENT_TYPE_JSON: return self.__hcm_json.dumps(body) elif content_type == CONTENT_TYPE_MSGPACK: return s...
def _http_req_body_serialize(self, body, content_type)
Conditionally serialize the request body value if mime_type is set and it's serializable. :param mixed body: The request body :param str content_type: The content type for the request body :raises: ValueError
3.14037
3.453597
0.909304
# Tornado Request Handler try: return '{}/{}'.format( self.settings['service'], self.settings['version']) except (AttributeError, KeyError): pass # Rejected Consumer if hasattr(self, '_process'): try: r...
def _http_req_user_agent(self)
Return the User-Agent value to specify in HTTP requests, defaulting to ``service/version`` if configured in the application settings, or if used in a consumer, it will attempt to obtain a user-agent from the consumer's process. If it can not auto-set the User-Agent, it defaults to ``spro...
5.275524
4.379258
1.204661
parsed = parse.urlparse(response.request.url) duration = int(response.headers.get('Retry-After', 3)) LOGGER.warning('Rate Limited by %s, retrying in %i seconds', parsed.netloc, duration) return asyncio.sleep(duration)
def _http_resp_rate_limited(response)
Extract the ``Retry-After`` header value if the request was rate limited and return a future to sleep for the specified duration. :param tornado.httpclient.HTTPResponse response: The response :rtype: tornado.concurrent.Future
4.179284
4.153846
1.006124
# Seconds from now on if isinstance(expires, timedelta): expires = expires.total_seconds() # This is just a tiny wrapper around redis_lock # 1) acquire lock or fail # 2) run function # 3) release lock def decorator(f): nonlocal resource if resource is None: ...
def acquires_lock(expires, should_fail=True, should_wait=False, resource=None, prefix=DEFAULT_PREFIX)
Decorator to ensure function only runs when it is unique holder of the resource. Any invocations of the functions before the first is done will raise RuntimeError. Locks are stored in redis with prefix: `lock:acquires_lock` Arguments: expires(timedelta|int): Expiry time of lock, way more than...
3.33656
3.415284
0.97695
links = [Link(href=h, rel=OIC_ISSUER) for h in kwargs['hrefs']] _response = JRD(subject=kwargs['subject'], links=links) info = { 'response': _response.to_json(), 'http_headers': [('Content-type', 'application/json')] } return info
def do_response(self, response_args=None, request=None, **kwargs)
**Placeholder for the time being** :param response_args: :param request: :param kwargs: request arguments :return: Response information
6.218646
6.405673
0.970803
# NOTE(msimonin): We provide only a basic support which focus # Chameleon cloud and its rc files if os.environ.get("OS_IDENTITY_API_VERSION") == "3": logging.info("Creating a v3 Keystone Session") auth = v3.Password( auth_url=os.environ["OS_AUTH_URL"], username=o...
def get_session()
Build the session object.
2.672654
2.606419
1.025412
gclient = glance.Client(GLANCE_VERSION, session=session, region_name=os.environ['OS_REGION_NAME']) images = gclient.images.list() name_ids = [{'name': i['name'], 'id': i['id']} for i in images] if image_name not in list(map(itemgetter('name'), name_ids)): logger....
def check_glance(session, image_name)
Check that the base image is available. Fails if the base image isn't added. This means the image should be added manually.
2.435614
2.584103
0.942538
nclient = nova.Client(NOVA_VERSION, session=session, region_name=os.environ['OS_REGION_NAME']) flavors = nclient.flavors.list() to_id = dict(list(map(lambda n: [n.name, n.id], flavors))) to_flavor = dict(list(map(lambda n: [n.id, n.name], flavors))) return to_id, to_fl...
def check_flavors(session)
Build the flavors mapping returns the mappings id <-> flavor
2.782013
2.644643
1.051943
nclient = nova.Client(NOVA_VERSION, session=session, region_name=os.environ['OS_REGION_NAME']) while True: deployed = [] undeployed = [] for server in servers: c = nclient.servers.get(server.id) if c.addresses != {} and c.status == '...
def wait_for_servers(session, servers)
Wait for the servers to be ready. Note(msimonin): we don't garantee the SSH connection to be ready.
2.876215
2.88495
0.996972
scheduler_hints = scheduler_hints or [] nclient = nova.Client(NOVA_VERSION, session=session, region_name=os.environ['OS_REGION_NAME']) servers = nclient.servers.list( search_opts={'name': '-'.join([DEFAULT_PREFIX, extra_prefix])}) wanted = _get_total_wanted_machin...
def check_servers(session, machines, extra_prefix="", force_deploy=False, key_name=None, image_id=None, flavors='m1.medium', network=None, ext_net=None, scheduler_hints=None)
Checks the servers status for the deployment. If needed, it creates new servers and add a floating ip to one of them. This server can be used as a gateway to the others.
2.905594
2.97315
0.977278
return re.match(r"^%s" % '-'.join([DEFAULT_PREFIX, extra_prefix]), server.name) is not None
def is_in_current_deployment(server, extra_prefix="")
Check if an existing server in the system take part to the current deployment
7.364308
7.491611
0.983007
nclient = neutron.Client('2', session=session, region_name=os.environ['OS_REGION_NAME']) ports = nclient.list_ports() ports_to_update = filter( lambda p: p['network_id'] == network['id'], ports['ports']) logger.info('[nova]: Allowing address pairs for po...
def allow_address_pairs(session, network, subnet)
Allow several interfaces to be added and accessed from the other machines. This is particularly useful when working with virtual ips.
4.5657
4.820073
0.947226
session = get_session() image_id = check_glance(session, provider_conf.image) flavor_to_id, id_to_flavor = check_flavors(session) ext_net, network, subnet = check_network( session, provider_conf.configure_network, provider_conf.network, subnet=provider_conf.subnet, ...
def check_environment(provider_conf)
Check all ressources needed by Enos.
2.576821
2.590803
0.994603
if claimspec is None: # match anything return True matched = False for key, val in claimspec.items(): if key == "value": if value == val: matched = True elif key == "values": if value in val: matched = True elif k...
def claims_match(value, claimspec)
Implements matching according to section 5.5.1 of http://openid.net/specs/openid-connect-core-1_0.html The lack of value is not checked here. Also the text doesn't prohibit having both 'value' and 'values'. :param value: single value :param claimspec: None or dictionary with 'essential', 'value' or...
3.48401
3.438272
1.013303
authn_req = session['authn_req'] if userinfo_claims is None: uic = scope2claims(authn_req["scope"]) # Get only keys allowed by user and update the dict if such info # is stored in session perm_set = session.get('permission') if perm_set: uic = {key: uic...
def collect_user_info(endpoint_context, session, userinfo_claims=None)
Collect information about a user. This can happen in two cases, either when constructing an IdToken or when returning user info through the UserInfo endpoint :param session: Session information :param userinfo_claims: user info claims :return: User info
3.366225
3.397219
0.990877
if def_itc: itc = def_itc else: itc = {} itc.update(id_token_claims(session)) if not itc: return None _claims = by_schema(endpoint_context.id_token_schema, **itc) if _claims: return collect_user_info(endpoint_context, session, _claims) else: r...
def userinfo_in_id_token_claims(endpoint_context, session, def_itc=None)
Collect user info claims that are to be placed in the id token. :param endpoint_context: Endpoint context :param session: Session information :param def_itc: Default ID Token claims :return: User information or None
3.12396
3.171673
0.984956
if self.__value_matrix: return self.__value_matrix self.__value_matrix = [ [value_dp.data for value_dp in value_dp_list] for value_dp_list in self.value_dp_matrix ] return self.__value_matrix
def value_matrix(self)
Converted rows of tabular data. Returns: |list| or |tuple|: Table rows.
3.394348
3.46786
0.978802
if self.__value_dp_matrix is None: self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix( to_value_matrix(self.headers, self.rows) ) return self.__value_dp_matrix
def value_dp_matrix(self)
:return: DataProperty for table data. :rtype: list
4.827532
4.462849
1.081715
invalid_row_idx_list = [] for row_idx, row in enumerate(self.rows): if isinstance(row, (list, tuple)) and len(self.headers) != len(row): invalid_row_idx_list.append(row_idx) if isinstance(row, dict): if not all([header in row for header...
def validate_rows(self)
:raises ValueError:
2.706519
2.563791
1.055671
dict_body = [] for row in self.rows: if not row: continue values = [ (header, value) for header, value in zip(self.headers, row) if value is not None ] if not values: continue dict_bo...
def as_dict(self)
:return: Table data as a |dict| instance. :rtype: dict :Sample Code: .. code:: python from tabledata import TableData TableData( "sample", ["a", "b"], [[1, 2], [3.3, 4.4]] ).as_dict...
3.5362
3.037226
1.164286
Row = namedtuple("Row", self.headers) for value_dp_list in self.value_dp_matrix: if typepy.is_empty_sequence(value_dp_list): continue row = Row(*[value_dp.data for value_dp in value_dp_list]) yield row
def as_tuple(self)
:return: Rows of the table. :rtype: list of |namedtuple| :Sample Code: .. code:: python from tabledata import TableData records = TableData( "sample", ["a", "b"], [[1, 2], [3.3, 4.4]] ...
4.989525
4.754728
1.049382
import pandas dataframe = pandas.DataFrame(self.value_matrix) if not self.is_empty_header(): dataframe.columns = self.headers return dataframe
def as_dataframe(self)
:return: Table data as a ``pandas.DataFrame`` instance. :rtype: pandas.DataFrame :Sample Code: .. code-block:: python from tabledata import TableData TableData( "sample", ["a", "b"], [[1, 2], [3.3,...
8.016304
8.798786
0.911069
return TableData(table_name, list(dataframe.columns.values), dataframe.values.tolist())
def from_dataframe(dataframe, table_name="")
Initialize TableData instance from a pandas.DataFrame instance. :param pandas.DataFrame dataframe: :param str table_name: Table name to create.
6.803899
4.976612
1.367175
@wraps(func) def wrapper(self, *args, **kw): def call(): try: func(self, *args, **kw) except Exception: logger.exception( "failed to call async [%r] with [%r] [%r]", func, args, kw ) ...
def call_async(func)
Decorates a function to be called async on the loop thread
3.385918
2.984217
1.134608
@wraps(func) def wrapper(self, *args, **kw): # Just return when already on the event thread if self.thread.ident == get_ident(): return func(self, *args, **kw) barrier = Barrier(2) result = None ex = None def call(): ...
def call_sync(func)
Decorates a function to be called sync on the loop thread
3.09129
2.905958
1.063777
while self.event.wait(): self.event.clear() while True: with self.lock: if not self.count: break self.count -= 1 with self.condition: self.condition.notify_all()
def target(self)
Thread routine
3.940381
3.348679
1.176697
if sys.platform != "win32": self.loop = asyncio.new_event_loop() else: self.loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(self.loop) barrier.wait() try: self.loop.run_forever() except Exception: sys.exi...
def _loop(self, barrier)
Actual thread
2.46313
2.358321
1.044442
urlparts = urlsplit(ws_url) req = Request("GET", ws_url) cookies = get_cookie_header(cookies, req) if cookies: headers = dict(Cookie=cookies) else: headers = None factory = WebSocketClientFactory(ws_url, headers=headers, loop=self.loop) ...
def create_connection(self, room, ws_url, agent, cookies)
Creates a new connection
2.966213
2.976299
0.996611
# pylint: disable=no-self-use try: if not isinstance(payload, bytes): payload = payload.encode("utf-8") if not proto.connected: raise IOError("not connected") proto.sendMessage(payload) logger.debug("sent: %r", pay...
def __send_message(self, proto, payload)
Sends a message
3.300032
3.281777
1.005563
# pylint: disable=no-self-use try: proto.sendClose() except Exception as ex: logger.exception("Failed to send close") proto.reraise(ex)
def close(self, proto)
Closes a connection
5.567304
6.242012
0.891909
with self.lock, self.enlock: queue = copy(self.queue) self.queue.clear() callbacks = copy(self.callbacks) with self.lock: rm_cb = False for ki, vi in queue.items(): if ki in self.callbacks: for ite...
def process(self)
Process queue for these listeners. Only the items with type that matches
3.461823
3.284786
1.053896
with self.lock: self.callbacks[callback_type].append(callback)
def add(self, callback_type, callback)
Add a new listener
4.513252
4.321261
1.044429
with self.enlock: self.queue[item_type].append(item)
def enqueue(self, item_type, item)
Queue a new data item, make item iterable
9.354885
8.365111
1.118322
# 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...
3.236918
2.98135
1.085722
'''Intersection between two segments.''' try: a1, a2 = a except TypeError: a1 = a.start a2 = a.stop try: b1, b2 = b except TypeError: b1 = b.start b2 = b.stop if a2 <= b1: return None if a1 >= b2: return None # a2 > b1 an...
def intersection(a, b, scale=1)
Intersection between two segments.
1.902376
1.943349
0.978917
'''Intersect slices with a region.''' t = [] for ch in r: a1 = intersection(ch[0], region[0], scale=scale) if a1 is None: continue a2 = intersection(ch[1], region[1], scale=scale) if a2 is None: continue t.append((a1, a2)) return t
def clip_slices(r, region, scale=1)
Intersect slices with a region.
3.263146
3.043458
1.072184
hdr = super(JoinDitheredImagesRecipe, self).set_base_headers(hdr) hdr['IMGOBBL'] = 0 hdr['OBSMODE'] = 'DITHERED_IMAGE' return hdr
def set_base_headers(self, hdr)
Set metadata in FITS headers.
10.093967
7.548776
1.337166
extra_vars = extra_vars or {} tags = tags or [] loader = DataLoader() if basedir: loader.set_basedir(basedir) inventory = EnosInventory(loader=loader, sources=inventory_path, roles=roles) variable_manager = VariableManager(loader=loader, ...
def _load_defaults(inventory_path=None, roles=None, extra_vars=None, tags=None, basedir=False)
Load common defaults data structures. For factorization purpose.
2.755755
2.847254
0.967864
# NOTE(msimonin): inventory could be infered from a host list (maybe) results = [] inventory, variable_manager, loader, options = _load_defaults( inventory_path=inventory_path, roles=roles, extra_vars=extra_vars) callback = _MyCallback(results) passwords = {} tqm = t...
def run_play(play_source, inventory_path=None, roles=None, extra_vars=None, on_error_continue=False)
Run a play. Args: pattern_hosts (str): pattern to describe ansible hosts to target. see https://docs.ansible.com/ansible/latest/intro_patterns.html play_source (dict): ansible task inventory_path (str): inventory to use extra_vars (dict): extra_vars to use on_err...
2.649766
2.492787
1.062973
def filter_results(results, status): _r = [r for r in results if r.status == status and r.task == COMMAND_NAME] s = dict([[r.host, {"stdout": r.payload.get("stdout"), "stderr": r.payload.get("stderr")}] for r in _r]) return s ...
def run_command(pattern_hosts, command, inventory_path=None, roles=None, extra_vars=None, on_error_continue=False)
Run a shell command on some remote hosts. Args: pattern_hosts (str): pattern to describe ansible hosts to target. see https://docs.ansible.com/ansible/latest/intro_patterns.html command (str): the command to run inventory_path (str): inventory to use extra_vars (dict): e...
3.092785
3.311299
0.934009
inventory, variable_manager, loader, options = _load_defaults( inventory_path=inventory_path, roles=roles, extra_vars=extra_vars, tags=tags, basedir=basedir ) passwords = {} for path in playbooks: logger.info("Running playbook %s with vars:\n%s" % (p...
def run_ansible(playbooks, inventory_path=None, roles=None, extra_vars=None, tags=None, on_error_continue=False, basedir='.')
Run Ansible. Args: playbooks (list): list of paths to the playbooks to run inventory_path (str): path to the hosts file (inventory) extra_var (dict): extra vars to pass tags (list): list of tags to run on_error_continue(bool): Don't throw any exception in case a host is ...
2.150705
2.113335
1.017683
def get_devices(facts): devices = [] for interface in facts['ansible_interfaces']: ansible_interface = 'ansible_' + interface # filter here (active/ name...) if 'ansible_' + interface in facts: interface = facts[ansible_interface] ...
def discover_networks(roles, networks, fake_interfaces=None, fake_networks=None)
Checks the network interfaces on the nodes. This enables to auto-discover the mapping interface name <-> network role. Beware, this has a side effect on each Host in roles. Args: roles (dict): role->hosts mapping as returned by :py:meth:`enoslib.infra.provider.Provider.init` ne...
5.876056
5.642327
1.041424