positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def get_values(self): """ returns final values (same result as tf.Session.run()) """ return [self._cache.get(i.name,None) for i in self._original_evals]
returns final values (same result as tf.Session.run())
def _max_width_formatter(string, cols, separator='\n'): """Returns a freshly formatted :param string: string to be formatted :type string: basestring or clint.textui.colored.ColoredString :param cols: max width the text to be formatted :type cols: int :param separator: separator to break rows :type separator: basestring """ is_color = isinstance(string, ColoredString) if is_color: string_copy = string._new('') string = string.s stack = tsplit(string, NEWLINES) for i, substring in enumerate(stack): stack[i] = substring.split() _stack = [] for row in stack: _row = ['',] _row_i = 0 for word in row: if (len(_row[_row_i]) + len(word)) <= cols: _row[_row_i] += word _row[_row_i] += ' ' elif len(word) > cols: # ensure empty row if len(_row[_row_i]): _row[_row_i] = _row[_row_i].rstrip() _row.append('') _row_i += 1 chunks = schunk(word, cols) for i, chunk in enumerate(chunks): if not (i + 1) == len(chunks): _row[_row_i] += chunk _row[_row_i] = _row[_row_i].rstrip() _row.append('') _row_i += 1 else: _row[_row_i] += chunk _row[_row_i] += ' ' else: _row[_row_i] = _row[_row_i].rstrip() _row.append('') _row_i += 1 _row[_row_i] += word _row[_row_i] += ' ' else: _row[_row_i] = _row[_row_i].rstrip() _row = map(str, _row) _stack.append(separator.join(_row)) _s = '\n'.join(_stack) if is_color: _s = string_copy._new(_s) return _s
Returns a freshly formatted :param string: string to be formatted :type string: basestring or clint.textui.colored.ColoredString :param cols: max width the text to be formatted :type cols: int :param separator: separator to break rows :type separator: basestring
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False): """ In-place simplification of segments Args: max_dist_error (float): Min distance error, in meters max_speed_error (float): Min speed error, in km/h topology_only: Boolean, optional. True to keep the topology, neglecting velocity and time accuracy (use common Douglas-Ramen-Peucker). False (default) to simplify segments keeping the velocity between points. Returns: This track """ for segment in self.segments: segment.simplify(eps, max_dist_error, max_speed_error, topology_only) return self
In-place simplification of segments Args: max_dist_error (float): Min distance error, in meters max_speed_error (float): Min speed error, in km/h topology_only: Boolean, optional. True to keep the topology, neglecting velocity and time accuracy (use common Douglas-Ramen-Peucker). False (default) to simplify segments keeping the velocity between points. Returns: This track
def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwargs) found = self._hash.get_node(key) if not found and len(self._down_connections) > 0: raise self.HostListExhausted() return [i for i, h in self.cluster.hosts.iteritems() if h.identifier == found]
The first argument is assumed to be the ``key`` for routing.
def WriteClientSnapshotHistory(self, clients, cursor=None): """Writes the full history for a particular client.""" client_id = clients[0].client_id latest_timestamp = max(client.timestamp for client in clients) query = "" params = { "client_id": db_utils.ClientIDToInt(client_id), "latest_timestamp": mysql_utils.RDFDatetimeToTimestamp(latest_timestamp) } for idx, client in enumerate(clients): startup_info = client.startup_info client.startup_info = None query += """ INSERT INTO client_snapshot_history (client_id, timestamp, client_snapshot) VALUES (%(client_id)s, FROM_UNIXTIME(%(timestamp_{idx})s), %(client_snapshot_{idx})s); INSERT INTO client_startup_history (client_id, timestamp, startup_info) VALUES (%(client_id)s, FROM_UNIXTIME(%(timestamp_{idx})s), %(startup_info_{idx})s); """.format(idx=idx) params.update({ "timestamp_{idx}".format(idx=idx): mysql_utils.RDFDatetimeToTimestamp(client.timestamp), "client_snapshot_{idx}".format(idx=idx): client.SerializeToString(), "startup_info_{idx}".format(idx=idx): startup_info.SerializeToString(), }) client.startup_info = startup_info query += """ UPDATE clients SET last_snapshot_timestamp = FROM_UNIXTIME(%(latest_timestamp)s) WHERE client_id = %(client_id)s AND (last_snapshot_timestamp IS NULL OR last_snapshot_timestamp < FROM_UNIXTIME(%(latest_timestamp)s)); UPDATE clients SET last_startup_timestamp = FROM_UNIXTIME(%(latest_timestamp)s) WHERE client_id = %(client_id)s AND (last_startup_timestamp IS NULL OR last_startup_timestamp < FROM_UNIXTIME(%(latest_timestamp)s)); """ try: cursor.execute(query, params) except MySQLdb.IntegrityError as error: raise db.UnknownClientError(client_id, cause=error)
Writes the full history for a particular client.
def sample_from_data(self, model, data): """Convert incoming sample *data* into a numpy array. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the sample's data, typically retrieved from ``request.args`` or similar. """ values = [] for key, type_name in self.mapping: value_type = self.types[type_name] values.append(value_type(data[key])) if self.unwrap_sample: assert len(values) == 1 return np.array(values[0]) else: return np.array(values, dtype=object)
Convert incoming sample *data* into a numpy array. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the sample's data, typically retrieved from ``request.args`` or similar.
def findBest(self, pattern): """ Returns the *best* match in the region (instead of the first match) """ findFailedRetry = True while findFailedRetry: best_match = None all_matches = self.findAll(pattern) for match in all_matches: if best_match is None or best_match.getScore() < match.getScore(): best_match = match self._lastMatch = best_match if best_match is not None: break path = pattern.path if isinstance(pattern, Pattern) else pattern findFailedRetry = self._raiseFindFailed("Could not find pattern '{}'".format(path)) if findFailedRetry: time.sleep(self._repeatWaitTime) return best_match
Returns the *best* match in the region (instead of the first match)
def is_iterable(obj): """ Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. Strings, however, should be considered as atomic values to look up, not iterables. The same goes for tuples, since they are immutable and therefore valid entries. We don't need to check for the Python 2 `unicode` type, because it doesn't have an `__iter__` attribute anyway. """ return ( hasattr(obj, "__iter__") and not isinstance(obj, str) and not isinstance(obj, tuple) )
Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. Strings, however, should be considered as atomic values to look up, not iterables. The same goes for tuples, since they are immutable and therefore valid entries. We don't need to check for the Python 2 `unicode` type, because it doesn't have an `__iter__` attribute anyway.
def add_all_database_reactions(model, compartments): """Add all reactions from database that occur in given compartments. Args: model: :class:`psamm.metabolicmodel.MetabolicModel`. """ added = set() for rxnid in model.database.reactions: reaction = model.database.get_reaction(rxnid) if all(compound.compartment in compartments for compound, _ in reaction.compounds): if not model.has_reaction(rxnid): added.add(rxnid) model.add_reaction(rxnid) return added
Add all reactions from database that occur in given compartments. Args: model: :class:`psamm.metabolicmodel.MetabolicModel`.
def authenticate(self, username, password): """ Authenticate user on server. :param username: Username used to be authenticated. :type username: six.string_types :param password: Password used to be authenticated. :type password: six.string_types :return: True if successful. :raises: InvalidCredentials, AuthenticationNotSupported, MemcachedException :rtype: bool """ self._username = username self._password = password # Reopen the connection with the new credentials. self.disconnect() self._open_connection() return self.authenticated
Authenticate user on server. :param username: Username used to be authenticated. :type username: six.string_types :param password: Password used to be authenticated. :type password: six.string_types :return: True if successful. :raises: InvalidCredentials, AuthenticationNotSupported, MemcachedException :rtype: bool
def insert_text_to(cursor, text, fmt): """Helper to print text, taking into account backspaces""" while True: index = text.find(chr(8)) # backspace if index == -1: break cursor.insertText(text[:index], fmt) if cursor.positionInBlock() > 0: cursor.deletePreviousChar() text = text[index+1:] cursor.insertText(text, fmt)
Helper to print text, taking into account backspaces
def pw_converter(handler, flt): """Convert column name to filter.""" import peewee as pw if isinstance(flt, Filter): return flt model = handler.model field = getattr(model, flt) if isinstance(field, pw.BooleanField): return PWBoolFilter(flt) if field.choices: choices = [(Filter.default, '---')] + list(field.choices) return PWChoiceFilter(flt, choices=choices) return PWFilter(flt)
Convert column name to filter.
def first_interesting_frame(self): """ Traverse down the frame hierarchy until a frame is found with more than one child """ root_frame = self.root_frame() frame = root_frame while len(frame.children) <= 1: if frame.children: frame = frame.children[0] else: # there are no branches return root_frame return frame
Traverse down the frame hierarchy until a frame is found with more than one child
def infix(self, node, children): 'infix = "(" expr operator expr ")"' _, expr1, operator, expr2, _ = children return operator(expr1, expr2)
infix = "(" expr operator expr ")"
def copy_patches(ptches0): """ return a list of copied input matplotlib patches :param ptches0: list of matploblib.patches objects :return: copyed patches object """ if not isinstance(ptches0, list): ptches0 = list(ptches0) copyed_ptches = [] for pt in ptches0: pth = pt.get_path().deepcopy() ptch = patches.PathPatch(pth, lw=pt.get_lw(), fc=pt.get_fc(), ec=pt.get_ec(), alpha=pt.get_alpha()) copyed_ptches.append(ptch) return copyed_ptches
return a list of copied input matplotlib patches :param ptches0: list of matploblib.patches objects :return: copyed patches object
def put_file(self, file_path, content, content_type=None, compress=None, cache_control=None): """ Args: filename (string): it can contains folders content (string): binary data to save """ return self.put_files([ (file_path, content) ], content_type=content_type, compress=compress, cache_control=cache_control, block=False )
Args: filename (string): it can contains folders content (string): binary data to save
def get_patch_op(self, keypath, value, op='replace'): """ Return an object that describes a change of configuration on the given staging. Setting will be applied on all available HTTP methods. """ if isinstance(value, bool): value = str(value).lower() return {'op': op, 'path': '/*/*/{}'.format(keypath), 'value': value}
Return an object that describes a change of configuration on the given staging. Setting will be applied on all available HTTP methods.
def _to_unicode(s): """ decode a string as ascii or utf8 if possible (as required by the sftp protocol). if neither works, just return a byte string because the server probably doesn't know the filename's encoding. """ try: return s.encode('ascii') except (UnicodeError, AttributeError): try: return s.decode('utf-8') except UnicodeError: return s
decode a string as ascii or utf8 if possible (as required by the sftp protocol). if neither works, just return a byte string because the server probably doesn't know the filename's encoding.
def unit_net_value(self): """ [float] 实时净值 """ if self._units == 0: return np.nan return self.total_value / self._units
[float] 实时净值
def _rsplit(expr, pat=None, n=-1): """ Split each string in the Series/Index by the given delimiter string, starting at the end of the string and working to the front. Equivalent to str.rsplit(). :param expr: :param pat: Separator to split on. If None, splits on whitespace :param n: None, 0 and -1 will be interpreted as return all splits :return: sequence or scalar """ return _string_op(expr, RSplit, output_type=types.List(types.string), _pat=pat, _n=n)
Split each string in the Series/Index by the given delimiter string, starting at the end of the string and working to the front. Equivalent to str.rsplit(). :param expr: :param pat: Separator to split on. If None, splits on whitespace :param n: None, 0 and -1 will be interpreted as return all splits :return: sequence or scalar
def electric_field_amplitude_intensity(s0,Omega=1.0e6): '''This function returns the value of E0 (the amplitude of the electric field) at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the saturation intensity of the D2 line of Rubidium for linearly polarized light.''' e0=hbar*Omega/(e*a0) #This is the electric field scale. I0=2.50399 #mW/cm^2 I0=1.66889451102868 #mW/cm^2 I0=I0/1000*(100**2) #W/m^2 r_ciclic=4.226983616875483 #a0 gamma_D2=2*Pi*6.065e6/Omega # The decay frequency of the D2 line. E0_sat=gamma_D2/r_ciclic/sqrt(2.0) E0_sat=E0_sat*e0 I0=E0_sat**2/2/c/mu0 #return sqrt(c*mu0*s0*I0/2)/e0 #return sqrt(c*mu0*s0*I0)/e0 return sqrt(2*c*mu0*s0*I0)/e0
This function returns the value of E0 (the amplitude of the electric field) at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the saturation intensity of the D2 line of Rubidium for linearly polarized light.
def generate_gradient(self, color_list, size=101): """ Create a gradient of size colors that passes through the colors give in the list (the resultant list may not be exactly size long). The gradient will be evenly distributed. colors should be in hex format eg '#FF00FF' """ list_length = len(color_list) gradient_step = size / (list_length - 1) gradient_data = [] for x in range(list_length): gradient_data.append((int(gradient_step * x), color_list[x])) data = [] for i in range(len(gradient_data) - 1): start, color1 = gradient_data[i] end, color2 = gradient_data[i + 1] color1 = self.hex_2_hsv(color1) color2 = self.hex_2_hsv(color2) steps = end - start for j in range(steps): data.append( self.hsv_2_hex(*self.make_mid_color(color1, color2, j / (steps))) ) data.append(self.hsv_2_hex(*color2)) return data
Create a gradient of size colors that passes through the colors give in the list (the resultant list may not be exactly size long). The gradient will be evenly distributed. colors should be in hex format eg '#FF00FF'
def check(self, request, secret): """Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature. This verifies every element of the signature, including the timestamp's value. Does not alter the request. Keyword arguments: request -- A request object which can be consumed by this API. secret -- The base64-encoded secret key for the HMAC authorization. """ if request.get_header("Authorization") == "": return False ah = self.parse_auth_headers(request.get_header("Authorization")) if "signature" not in ah: return False if request.get_header('x-authorization-timestamp') == '': raise KeyError("X-Authorization-Timestamp is required.") timestamp = int(float(request.get_header('x-authorization-timestamp'))) if timestamp == 0: raise ValueError("X-Authorization-Timestamp must be a valid, non-zero timestamp.") if self.preset_time is None: curr_time = time.time() else: curr_time = self.preset_time if timestamp > curr_time + 900: raise ValueError("X-Authorization-Timestamp is too far in the future.") if timestamp < curr_time - 900: raise ValueError("X-Authorization-Timestamp is too far in the past.") if request.body is not None and request.body != b'': content_hash = request.get_header("x-authorization-content-sha256") if content_hash == '': raise KeyError("X-Authorization-Content-SHA256 is required for requests with a request body.") sha256 = hashlib.sha256() sha256.update(request.body) if content_hash != base64.b64encode(sha256.digest()).decode('utf-8'): raise ValueError("X-Authorization-Content-SHA256 must match the SHA-256 hash of the request body.") return ah["signature"] == self.sign(request, ah, secret)
Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature. This verifies every element of the signature, including the timestamp's value. Does not alter the request. Keyword arguments: request -- A request object which can be consumed by this API. secret -- The base64-encoded secret key for the HMAC authorization.
def write_header(self, chunk): """Write to header. Note: the header stream is only available to write before write body. :param chunk: content to write to header :except TChannelError: Raise TChannelError if the response's flush() has been called """ if self.serializer: header = self.serializer.serialize_header(chunk) else: header = chunk if self.flushed: raise TChannelError("write operation invalid after flush call") if (self.argstreams[0].state != StreamState.completed and self.argstreams[0].auto_close): self.argstreams[0].close() return self.argstreams[1].write(header)
Write to header. Note: the header stream is only available to write before write body. :param chunk: content to write to header :except TChannelError: Raise TChannelError if the response's flush() has been called
def _calc_bkg_bkgrms(self): """ Calculate the background and background RMS estimate in each of the meshes. Both meshes are computed at the same time here method because the filtering of both depends on the background mesh. The ``background_mesh`` and ``background_rms_mesh`` images are equivalent to the low-resolution "MINIBACKGROUND" and "MINIBACK_RMS" background maps in SExtractor, respectively. """ if self.sigma_clip is not None: data_sigclip = self.sigma_clip(self._mesh_data, axis=1) else: data_sigclip = self._mesh_data del self._mesh_data # preform mesh rejection on sigma-clipped data (i.e. for any # newly-masked pixels) idx = self._select_meshes(data_sigclip) self.mesh_idx = self.mesh_idx[idx] # indices for the output mesh self._data_sigclip = data_sigclip[idx] # always a 2D masked array self._mesh_shape = (self.nyboxes, self.nxboxes) self.mesh_yidx, self.mesh_xidx = np.unravel_index(self.mesh_idx, self._mesh_shape) # These properties are needed later to calculate # background_mesh_ma and background_rms_mesh_ma. Note that _bkg1d # and _bkgrms1d are masked arrays, but the mask should always be # False. self._bkg1d = self.bkg_estimator(self._data_sigclip, axis=1) self._bkgrms1d = self.bkgrms_estimator(self._data_sigclip, axis=1) # make the unfiltered 2D mesh arrays (these are not masked) if len(self._bkg1d) == self.nboxes: bkg = self._make_2d_array(self._bkg1d) bkgrms = self._make_2d_array(self._bkgrms1d) else: bkg = self._interpolate_meshes(self._bkg1d) bkgrms = self._interpolate_meshes(self._bkgrms1d) self._background_mesh_unfiltered = bkg self._background_rms_mesh_unfiltered = bkgrms self.background_mesh = bkg self.background_rms_mesh = bkgrms # filter the 2D mesh arrays if not np.array_equal(self.filter_size, [1, 1]): self._filter_meshes() return
Calculate the background and background RMS estimate in each of the meshes. Both meshes are computed at the same time here method because the filtering of both depends on the background mesh. The ``background_mesh`` and ``background_rms_mesh`` images are equivalent to the low-resolution "MINIBACKGROUND" and "MINIBACK_RMS" background maps in SExtractor, respectively.
def keys_in_dict(d, parent_key, keys): """ Create a list of keys from a dict recursively. """ for key, value in d.iteritems(): if isinstance(value, dict): keys_in_dict(value, key, keys) else: if parent_key: prefix = parent_key + "." else: prefix = "" keys.append(prefix + key) return keys
Create a list of keys from a dict recursively.
def add_to(self, parent, name=None, index=None): """Add element to a parent.""" parent.add_child(self, name=name, index=index) return self
Add element to a parent.
def field_cols(model): """ Get the models columns in a friendly SQL format This will be a string of comma separated field names prefixed by the models resource type. TIP: to_manys are not located on the table in Postgres & are instead application references, so any reference to there column names should be pruned! :return: str """ to_many = model.to_many cols = [f for f in model.all_fields if f not in to_many] cols = ', '.join(cols) return cols or None
Get the models columns in a friendly SQL format This will be a string of comma separated field names prefixed by the models resource type. TIP: to_manys are not located on the table in Postgres & are instead application references, so any reference to there column names should be pruned! :return: str
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'from_') and self.from_ is not None: _dict['from'] = self.from_ if hasattr(self, 'to') and self.to is not None: _dict['to'] = self.to if hasattr(self, 'speaker') and self.speaker is not None: _dict['speaker'] = self.speaker if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'final_results') and self.final_results is not None: _dict['final'] = self.final_results return _dict
Return a json dictionary representing this model.
def from_url(cls, url): """ Creates a `~mocpy.moc.MOC` object from a given url. Parameters ---------- url : str The url of a FITS file storing a MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ path = download_file(url, show_progress=False, timeout=60) return cls.from_fits(path)
Creates a `~mocpy.moc.MOC` object from a given url. Parameters ---------- url : str The url of a FITS file storing a MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC.
def ascii2h5(bh_dir=None): """ Convert the Burstein & Heiles (1982) dust map from ASCII to HDF5. """ if bh_dir is None: bh_dir = os.path.join(data_dir_default, 'bh') fname = os.path.join(bh_dir, '{}.ascii') f = h5py.File('bh.h5', 'w') for region in ('hinorth', 'hisouth'): data = np.loadtxt(fname.format(region), dtype='f4') # Reshape and clip data.shape = (210, 201) # (R, N) data = data[:201] # Last 9 records are empty # Use NaNs where no data data[data < -9000] = np.nan dset = f.create_dataset( region, data=data, chunks=True, compression='gzip', compression_opts=3 ) dset.attrs['axes'] = ('R', 'N') dset.attrs['description'] = ( 'HI 21cm column densities, in units of 10*NHYD. ' 'R = 100 + [(90^o-|b|) sin(l)]/[0.3 degrees]. ' 'N = 100 + [(90^o-|b|) cos (l)]/[0.3 degrees].' ) for region in ('rednorth', 'redsouth'): data = np.loadtxt(fname.format(region), dtype='f4') # Reshape and clip data.shape = (94, 1200) # (R, N) data = data[:93] # Last record is empty # Use NaNs where no data data[data < -9000] = np.nan dset = f.create_dataset( region, data=data, chunks=True, compression='gzip', compression_opts=3 ) dset.attrs['axes'] = ('R', 'N') dset.attrs['description'] = ( 'E(B-V), in units of 0.001 mag. ' 'R = (|b| - 10) / (0.6 degrees). ' 'N = (l + 0.15) / 0.3 - 1.' ) f.attrs['description'] = ( 'The Burstein & Heiles (1982) dust map.' ) f.close()
Convert the Burstein & Heiles (1982) dust map from ASCII to HDF5.
def processor_for(content_model_or_slug, exact_page=False): """ Decorator that registers the decorated function as a page processor for the given content model or slug. When a page exists that forms the prefix of custom urlpatterns in a project (eg: the blog page and app), the page will be added to the template context. Passing in ``True`` for the ``exact_page`` arg, will ensure that the page processor is not run in this situation, requiring that the loaded page object is for the exact URL currently being viewed. """ content_model = None slug = "" if isinstance(content_model_or_slug, (str, _str)): try: parts = content_model_or_slug.split(".", 1) content_model = apps.get_model(*parts) except (TypeError, ValueError, LookupError): slug = content_model_or_slug elif issubclass(content_model_or_slug, Page): content_model = content_model_or_slug else: raise TypeError("%s is not a valid argument for page_processor, " "which should be a model subclass of Page in class " "or string form (app.model), or a valid slug" % content_model_or_slug) def decorator(func): parts = (func, exact_page) if content_model: model_name = content_model._meta.object_name.lower() processors[model_name].insert(0, parts) else: processors["slug:%s" % slug].insert(0, parts) return func return decorator
Decorator that registers the decorated function as a page processor for the given content model or slug. When a page exists that forms the prefix of custom urlpatterns in a project (eg: the blog page and app), the page will be added to the template context. Passing in ``True`` for the ``exact_page`` arg, will ensure that the page processor is not run in this situation, requiring that the loaded page object is for the exact URL currently being viewed.
def residue_network(): """The network for the residue example. Current and previous state are all nodes OFF. Diagram:: +~~~~~~~+ +~~~~~~~+ | A | | B | +~~>| (AND) | | (AND) |<~~+ | +~~~~~~~+ +~~~~~~~+ | | ^ ^ | | | | | | +~~~~~+ +~~~~~+ | | | | | +~~~+~~~+ +~+~~~+~+ +~~~+~~~+ | C | | D | | E | | | | | | | +~~~~~~~+ +~~~~~~~+ +~~~~~~~+ Connectivity matrix: +---+---+---+---+---+---+ | . | A | B | C | D | E | +---+---+---+---+---+---+ | A | 0 | 0 | 0 | 0 | 0 | +---+---+---+---+---+---+ | B | 0 | 0 | 0 | 0 | 0 | +---+---+---+---+---+---+ | C | 1 | 0 | 0 | 0 | 0 | +---+---+---+---+---+---+ | D | 1 | 1 | 0 | 0 | 0 | +---+---+---+---+---+---+ | E | 0 | 1 | 0 | 0 | 0 | +---+---+---+---+---+---+ """ tpm = np.array([ [int(s) for s in bin(x)[2:].zfill(5)[::-1]] for x in range(32) ]) tpm[np.where(np.sum(tpm[0:, 2:4], 1) == 2), 0] = 1 tpm[np.where(np.sum(tpm[0:, 3:5], 1) == 2), 1] = 1 tpm[np.where(np.sum(tpm[0:, 2:4], 1) < 2), 0] = 0 tpm[np.where(np.sum(tpm[0:, 3:5], 1) < 2), 1] = 0 cm = np.zeros((5, 5)) cm[2:4, 0] = 1 cm[3:, 1] = 1 return Network(tpm, cm=cm, node_labels=LABELS[:tpm.shape[1]])
The network for the residue example. Current and previous state are all nodes OFF. Diagram:: +~~~~~~~+ +~~~~~~~+ | A | | B | +~~>| (AND) | | (AND) |<~~+ | +~~~~~~~+ +~~~~~~~+ | | ^ ^ | | | | | | +~~~~~+ +~~~~~+ | | | | | +~~~+~~~+ +~+~~~+~+ +~~~+~~~+ | C | | D | | E | | | | | | | +~~~~~~~+ +~~~~~~~+ +~~~~~~~+ Connectivity matrix: +---+---+---+---+---+---+ | . | A | B | C | D | E | +---+---+---+---+---+---+ | A | 0 | 0 | 0 | 0 | 0 | +---+---+---+---+---+---+ | B | 0 | 0 | 0 | 0 | 0 | +---+---+---+---+---+---+ | C | 1 | 0 | 0 | 0 | 0 | +---+---+---+---+---+---+ | D | 1 | 1 | 0 | 0 | 0 | +---+---+---+---+---+---+ | E | 0 | 1 | 0 | 0 | 0 | +---+---+---+---+---+---+
def perform_es_corr(self, lattice, q, step=1e-4): """ Peform Electrostatic Freysoldt Correction """ logger.info("Running Freysoldt 2011 PC calculation (should be " "equivalent to sxdefectalign)") logger.debug("defect lattice constants are (in angstroms)" + str(lattice.abc)) [a1, a2, a3] = ang_to_bohr * np.array(lattice.get_cartesian_coords(1)) logging.debug("In atomic units, lat consts are (in bohr):" + str([a1, a2, a3])) vol = np.dot(a1, np.cross(a2, a3)) # vol in bohr^3 def e_iso(encut): gcut = eV_to_k(encut) # gcut is in units of 1/A return scipy.integrate.quad(lambda g: self.q_model.rho_rec(g * g)**2, step, gcut)[0] * (q**2) / np.pi def e_per(encut): eper = 0 for g2 in generate_reciprocal_vectors_squared(a1, a2, a3, encut): eper += (self.q_model.rho_rec(g2)**2) / g2 eper *= (q**2) * 2 * round(np.pi, 6) / vol eper += (q**2) * 4 * round(np.pi, 6) \ * self.q_model.rho_rec_limit0 / vol return eper eiso = converge(e_iso, 5, self.madetol, self.energy_cutoff) logger.debug("Eisolated : %f", round(eiso, 5)) eper = converge(e_per, 5, self.madetol, self.energy_cutoff) logger.info("Eperiodic : %f hartree", round(eper, 5)) logger.info("difference (periodic-iso) is %f hartree", round(eper - eiso, 6)) logger.info("difference in (eV) is %f", round((eper - eiso) * hart_to_ev, 4)) es_corr = round((eiso - eper) / self.dielectric * hart_to_ev, 6) logger.info("Defect Correction without alignment %f (eV): ", es_corr) return es_corr
Peform Electrostatic Freysoldt Correction
def set_foreign_key(self, parent_table, parent_column, child_table, child_column): """Create a Foreign Key constraint on a column from a table.""" self.execute('ALTER TABLE {0} ADD FOREIGN KEY ({1}) REFERENCES {2}({3})'.format(parent_table, parent_column, child_table, child_column))
Create a Foreign Key constraint on a column from a table.
def check(self, hash_algorithm, offset=0, length=0, block_size=0): """ Ask the server for a hash of a section of this file. This can be used to verify a successful upload or download, or for various rsync-like operations. The file is hashed from ``offset``, for ``length`` bytes. If ``length`` is 0, the remainder of the file is hashed. Thus, if both ``offset`` and ``length`` are zero, the entire file is hashed. Normally, ``block_size`` will be 0 (the default), and this method will return a byte string representing the requested hash (for example, a string of length 16 for MD5, or 20 for SHA-1). If a non-zero ``block_size`` is given, each chunk of the file (from ``offset`` to ``offset + length``) of ``block_size`` bytes is computed as a separate hash. The hash results are all concatenated and returned as a single string. For example, ``check('sha1', 0, 1024, 512)`` will return a string of length 40. The first 20 bytes will be the SHA-1 of the first 512 bytes of the file, and the last 20 bytes will be the SHA-1 of the next 512 bytes. :param str hash_algorithm: the name of the hash algorithm to use (normally ``"sha1"`` or ``"md5"``) :param offset: offset into the file to begin hashing (0 means to start from the beginning) :param length: number of bytes to hash (0 means continue to the end of the file) :param int block_size: number of bytes to hash per result (must not be less than 256; 0 means to compute only one hash of the entire segment) :return: `str` of bytes representing the hash of each block, concatenated together :raises: ``IOError`` -- if the server doesn't support the "check-file" extension, or possibly doesn't support the hash algorithm requested .. note:: Many (most?) servers don't support this extension yet. .. versionadded:: 1.4 """ t, msg = self.sftp._request( CMD_EXTENDED, "check-file", self.handle, hash_algorithm, long(offset), long(length), block_size, ) msg.get_text() # ext msg.get_text() # alg data = msg.get_remainder() return data
Ask the server for a hash of a section of this file. This can be used to verify a successful upload or download, or for various rsync-like operations. The file is hashed from ``offset``, for ``length`` bytes. If ``length`` is 0, the remainder of the file is hashed. Thus, if both ``offset`` and ``length`` are zero, the entire file is hashed. Normally, ``block_size`` will be 0 (the default), and this method will return a byte string representing the requested hash (for example, a string of length 16 for MD5, or 20 for SHA-1). If a non-zero ``block_size`` is given, each chunk of the file (from ``offset`` to ``offset + length``) of ``block_size`` bytes is computed as a separate hash. The hash results are all concatenated and returned as a single string. For example, ``check('sha1', 0, 1024, 512)`` will return a string of length 40. The first 20 bytes will be the SHA-1 of the first 512 bytes of the file, and the last 20 bytes will be the SHA-1 of the next 512 bytes. :param str hash_algorithm: the name of the hash algorithm to use (normally ``"sha1"`` or ``"md5"``) :param offset: offset into the file to begin hashing (0 means to start from the beginning) :param length: number of bytes to hash (0 means continue to the end of the file) :param int block_size: number of bytes to hash per result (must not be less than 256; 0 means to compute only one hash of the entire segment) :return: `str` of bytes representing the hash of each block, concatenated together :raises: ``IOError`` -- if the server doesn't support the "check-file" extension, or possibly doesn't support the hash algorithm requested .. note:: Many (most?) servers don't support this extension yet. .. versionadded:: 1.4
def run_job(self, job_details, workflow, vm_instance_name): """ Execute a workflow on a worker. :param job_details: object: details about job(id, name, created date, workflow version) :param workflow: jobapi.Workflow: url to workflow and parameters to use :param vm_instance_name: name of the instance lando_worker is running on (this passed back in the response) """ self._send(JobCommands.RUN_JOB, RunJobPayload(job_details, workflow, vm_instance_name))
Execute a workflow on a worker. :param job_details: object: details about job(id, name, created date, workflow version) :param workflow: jobapi.Workflow: url to workflow and parameters to use :param vm_instance_name: name of the instance lando_worker is running on (this passed back in the response)
def remove_stream_handlers(logger=None): """ Remove only stream handlers from the specified logger :param logger: logging name or object to modify, defaults to root logger """ if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) new_handlers = [] for handler in logger.handlers: # FileHandler is a subclass of StreamHandler so # 'if not a StreamHandler' does not work if (isinstance(handler, logging.FileHandler) or isinstance(handler, logging.NullHandler) or (isinstance(handler, logging.Handler) and not isinstance(handler, logging.StreamHandler))): new_handlers.append(handler) logger.handlers = new_handlers
Remove only stream handlers from the specified logger :param logger: logging name or object to modify, defaults to root logger
def make_int(value, missing=-1): """Convert string value to long, '' to missing""" if isinstance(value, six.string_types): if not value.strip(): return missing elif value is None: return missing return int(value)
Convert string value to long, '' to missing
def estimate_vt(injections, mchirp_sampler, model_pdf, **kwargs): #Try including ifar threshold '''Based on injection strategy and the desired astro model estimate the injected volume. Scale injections and estimate sensitive volume. Parameters ---------- injections: dictionary Dictionary obtained after reading injections from read_injections mchirp_sampler: function Sampler for producing chirp mass samples for the astro model. model_pdf: function The PDF for astro model in mass1-mass2-spin1z-spin2z space. This is easily extendible to include precession kwargs: key words Inputs for thresholds and astrophysical models Returns ------- injection_chunks: dictionary The input dictionary with VT and VT error included with the injections ''' thr_var = kwargs.get('thr_var') thr_val = kwargs.get('thr_val') nsamples = 1000000 #Used to calculate injected astro volume injections = copy.deepcopy(injections) min_z, max_z = injections['z_range'] V = quad(contracted_dVdc, 0., max_z)[0] z_astro = astro_redshifts(min_z, max_z, nsamples) astro_lum_dist = cosmo.luminosity_distance(z_astro).value mch_astro = np.array(mchirp_sampler(nsamples = nsamples, **kwargs)) mch_astro_det = mch_astro * (1. + z_astro) idx_within = np.zeros(nsamples) for key in injections.keys(): if key == 'z_range': # This is repeated down again and is so continue mchirp = injections[key]['chirp_mass'] min_mchirp, max_mchirp = min(mchirp), max(mchirp) distance = injections[key]['distance'] if injections[key]['d_dist'] == 'uniform': d_min, d_max = min(distance), max(distance) elif injections[key]['d_dist'] == 'dchirp': d_fid_min = min(distance / (mchirp/_mch_BNS)**(5/6.)) d_fid_max = max(distance / (mchirp/_mch_BNS)**(5/6.)) d_min = d_fid_min * (mch_astro_det/_mch_BNS)**(5/6.) d_max = d_fid_max * (mch_astro_det/_mch_BNS)**(5/6.) bound = np.sign((max_mchirp-mch_astro_det)*(mch_astro_det-min_mchirp)) bound += np.sign((d_max - astro_lum_dist)*(astro_lum_dist - d_min)) idx = np.where(bound == 2) idx_within[idx] = 1 inj_V0 = 4*np.pi*V*len(idx_within[idx_within == 1])/float(nsamples) injections['inj_astro_vol'] = inj_V0 # Estimate the sensitive volume z_range = injections['z_range'] V_min = quad(contracted_dVdc, 0., z_range[0])[0] V_max = quad(contracted_dVdc, 0., z_range[1])[0] thr_falloff, i_inj, i_det, i_det_sq = [], 0, 0, 0 gps_min, gps_max = 1e15, 0 keys = injections.keys() for key in keys: if key == 'z_range' or key == 'inj_astro_vol': continue data = injections[key] distance = data['distance'] mass1, mass2 = data['mass1'], data['mass2'] spin1z, spin2z = data['spin1z'], data['spin2z'] mchirp = data['chirp_mass'] gps_min = min(gps_min, min(data['end_time'])) gps_max = max(gps_max, max(data['end_time'])) z_inj = dlum_to_z(distance) m1_sc, m2_sc = mass1/(1 + z_inj), mass2/(1 + z_inj) p_out = model_pdf(m1_sc, m2_sc, spin1z, spin2z) p_out *= pdf_z_astro(z_inj, V_min, V_max) p_in = 0 J = cosmo.luminosity_distance(z_inj + 0.0005).value J -= cosmo.luminosity_distance(z_inj - 0.0005).value J = abs(J)/0.001 # A quick way to get dD_l/dz # Sum probability of injections from j-th set for all the strategies for key2 in keys: if key2 == 'z_range' or key2 == 'inj_astro_vol': continue dt_j = injections[key2] dist_j = dt_j['distance'] m1_j, m2_j = dt_j['mass1'], dt_j['mass2'] s1x_2, s2x_2 = dt_j['spin1x'], dt_j['spin2x'] s1y_2, s2y_2 = dt_j['spin1y'], dt_j['spin2y'] s1z_2, s2z_2 = dt_j['spin1z'], dt_j['spin2z'] s1 = np.sqrt(s1x_2**2 + s1y_2**2 + s1z_2**2) s2 = np.sqrt(s2x_2**2 + s2y_2**2 + s2z_2**2) mch_j = dt_j['chirp_mass'] #Get probability density for injections in mass-distance space if dt_j['m_dist'] == 'totalMass': lomass, himass = min(min(m1_j), min(m2_j), max(max(m1_j), max(m2_j))) lomass_2, himass_2 = lomass, himass elif dt_j['m_dist'] == 'componentMass' or dt_j['m_dist'] == 'log': lomass, himass = min(m1_j), max(m1_j) lomass_2, himass_2 = min(m2_j), max(m2_j) if dt_j['d_dist'] == 'dchirp': l_dist = min(dist_j / (mch_j/_mch_BNS)**(5/6.)) h_dist = max(dist_j / (mch_j/_mch_BNS)**(5/6.)) elif dt_j['d_dist'] == 'uniform': l_dist, h_dist = min(dist_j), max(dist_j) mdist = dt_j['m_dist'] prob_mass = inj_mass_pdf(mdist, mass1, mass2, lomass, himass, lomass_2, himass_2) ddist = dt_j['d_dist'] prob_dist = inj_distance_pdf(ddist, distance, l_dist, h_dist, mchirp) hspin1, hspin2 = max(s1), max(s2) prob_spin = inj_spin_pdf(dt_j['s_dist'], hspin1, spin1z) prob_spin *= inj_spin_pdf(dt_j['s_dist'], hspin2, spin2z) p_in += prob_mass * prob_dist * prob_spin * J * (1 + z_inj)**2 p_in[p_in == 0] = 1e12 p_out_in = p_out/p_in i_inj += np.sum(p_out_in) i_det += np.sum((p_out_in)[data[thr_var] > thr_val]) i_det_sq += np.sum((p_out_in)[data[thr_var] > thr_val]**2) idx_thr = np.where(data[thr_var] > thr_val) thrs = data[thr_var][idx_thr] ratios = p_out_in[idx_thr]/max(p_out_in[idx_thr]) rndn = np.random.uniform(0, 1, len(ratios)) idx_ratio = np.where(ratios > rndn) thr_falloff.append(thrs[idx_ratio]) inj_V0 = injections['inj_astro_vol'] injections['ninj'] = i_inj injections['ndet'] = i_det injections['ndetsq'] = i_det_sq injections['VT'] = ((inj_V0*i_det/i_inj) * (gps_max - gps_min)/31557600) injections['VT_err'] = injections['VT'] * np.sqrt(i_det_sq)/i_det injections['thr_falloff'] = np.hstack(np.array(thr_falloff).flat) return injections
Based on injection strategy and the desired astro model estimate the injected volume. Scale injections and estimate sensitive volume. Parameters ---------- injections: dictionary Dictionary obtained after reading injections from read_injections mchirp_sampler: function Sampler for producing chirp mass samples for the astro model. model_pdf: function The PDF for astro model in mass1-mass2-spin1z-spin2z space. This is easily extendible to include precession kwargs: key words Inputs for thresholds and astrophysical models Returns ------- injection_chunks: dictionary The input dictionary with VT and VT error included with the injections
def set_sqlite_pragmas(self): """ Sets the connection PRAGMAs for the sqlalchemy engine stored in self.engine. It currently sets: - journal_mode to WAL :return: None """ def _pragmas_on_connect(dbapi_con, con_record): dbapi_con.execute("PRAGMA journal_mode = WAL;") event.listen(self.engine, "connect", _pragmas_on_connect)
Sets the connection PRAGMAs for the sqlalchemy engine stored in self.engine. It currently sets: - journal_mode to WAL :return: None
def _set_directories(self): '''Initialize variables based on evidence about the directories.''' if self._dirs['initial'] == None: self._dirs['base'] = discover_base_dir(self._dirs['run']) else: self._dirs['base'] = discover_base_dir(self._dirs['initial']) # now, if 'base' is None (no base directory was found) then the only # allowed operation is init self._update_dirs_on_base() # we might have set the directory variables fine, but the tree # might not exist yet. _tree_ready is a flag for that. self._tree_ready = verify_dir_structure(self._dirs['base']) if self._tree_ready: self._read_site_config()
Initialize variables based on evidence about the directories.
def LSL(self, a): """ Shifts all bits of accumulator A or B or memory location M one place to the left. Bit zero is loaded with a zero. Bit seven of accumulator A or B or memory location M is shifted into the C (carry) bit. This is a duplicate assembly-language mnemonic for the single machine instruction ASL. source code forms: LSL Q; LSLA; LSLB CC bits "HNZVC": naaas """ r = a << 1 self.clear_NZVC() self.update_NZVC_8(a, a, r) return r
Shifts all bits of accumulator A or B or memory location M one place to the left. Bit zero is loaded with a zero. Bit seven of accumulator A or B or memory location M is shifted into the C (carry) bit. This is a duplicate assembly-language mnemonic for the single machine instruction ASL. source code forms: LSL Q; LSLA; LSLB CC bits "HNZVC": naaas
async def zrange(self, name, start, end, desc=False, withscores=False, score_cast_func=float): """ Return a range of values from sorted set ``name`` between ``start`` and ``end`` sorted in ascending order. ``start`` and ``end`` can be negative, indicating the end of the range. ``desc`` a boolean indicating whether to sort the results descendingly ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs ``score_cast_func`` a callable used to cast the score return value """ if desc: return await self.zrevrange(name, start, end, withscores, score_cast_func) pieces = ['ZRANGE', name, start, end] if withscores: pieces.append(b('WITHSCORES')) options = { 'withscores': withscores, 'score_cast_func': score_cast_func } return await self.execute_command(*pieces, **options)
Return a range of values from sorted set ``name`` between ``start`` and ``end`` sorted in ascending order. ``start`` and ``end`` can be negative, indicating the end of the range. ``desc`` a boolean indicating whether to sort the results descendingly ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs ``score_cast_func`` a callable used to cast the score return value
def plus_replacement(random, population, parents, offspring, args): """Performs "plus" replacement. This function performs "plus" replacement, which means that the entire existing population is replaced by the best population-many elements from the combined set of parents and offspring. .. Arguments: random -- the random number generator object population -- the population of individuals parents -- the list of parent individuals offspring -- the list of offspring individuals args -- a dictionary of keyword arguments """ pool = list(offspring) pool.extend(parents) pool.sort(reverse=True) survivors = pool[:len(population)] return survivors
Performs "plus" replacement. This function performs "plus" replacement, which means that the entire existing population is replaced by the best population-many elements from the combined set of parents and offspring. .. Arguments: random -- the random number generator object population -- the population of individuals parents -- the list of parent individuals offspring -- the list of offspring individuals args -- a dictionary of keyword arguments
def remove_asset(self, asset_id, composition_id): """Removes an ``Asset`` from a ``Composition``. arg: asset_id (osid.id.Id): ``Id`` of the ``Asset`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` raise: NotFound - ``asset_id`` ``not found in composition_id`` raise: NullArgument - ``asset_id`` or ``composition_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization fauilure *compliance: mandatory -- This method must be implemented.* """ self._provider_session.remove_asset(self, asset_id, composition_id)
Removes an ``Asset`` from a ``Composition``. arg: asset_id (osid.id.Id): ``Id`` of the ``Asset`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` raise: NotFound - ``asset_id`` ``not found in composition_id`` raise: NullArgument - ``asset_id`` or ``composition_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization fauilure *compliance: mandatory -- This method must be implemented.*
def _read_protos(self, size): """Read next layer protocol type. Positional arguments: * size -- int, buffer size Returns: * str -- next layer's protocol name """ _byte = self._read_unpack(size) _prot = TP_PROTO.get(_byte) return _prot
Read next layer protocol type. Positional arguments: * size -- int, buffer size Returns: * str -- next layer's protocol name
def consolidate(self, args): """ Consolidate the provided arguments. If the provided arguments have matching options, this performs a type conversion. For any option that has a default value and is not present in the provided arguments, the default value is added. Args: args (dict): A dictionary of the provided arguments. Returns: dict: A dictionary with the type converted and with default options enriched arguments. """ result = dict(args) for opt in self: if opt.name in result: result[opt.name] = opt.convert(result[opt.name]) else: if opt.default is not None: result[opt.name] = opt.convert(opt.default) return result
Consolidate the provided arguments. If the provided arguments have matching options, this performs a type conversion. For any option that has a default value and is not present in the provided arguments, the default value is added. Args: args (dict): A dictionary of the provided arguments. Returns: dict: A dictionary with the type converted and with default options enriched arguments.
def _copy_globalization_resources(self): '''Copy the language resource files for python api functions This function copies the TopologySplpy Resource files from Topology toolkit directory into the impl/nl folder of the project. Returns: the list with the copied locale strings''' rootDir = os.path.join(_topology_tk_dir(), "impl", "nl") languageList = [] for dirName in os.listdir(rootDir): srcDir = os.path.join(_topology_tk_dir(), "impl", "nl", dirName) if (os.path.isdir(srcDir)) and (dirName != "include"): dstDir = os.path.join(self._tk_dir, "impl", "nl", dirName) try: print("Copy globalization resources " + dirName) os.makedirs(dstDir) except OSError as e: if (e.errno == 17) and (os.path.isdir(dstDir)): if self._cmd_args.verbose: print("Directory", dstDir, "exists") else: raise srcFile = os.path.join(srcDir, "TopologySplpyResource.xlf") if os.path.isfile(srcFile): res = shutil.copy2(srcFile, dstDir) languageList.append(dirName) if self._cmd_args.verbose: print("Written: " + res) return languageList
Copy the language resource files for python api functions This function copies the TopologySplpy Resource files from Topology toolkit directory into the impl/nl folder of the project. Returns: the list with the copied locale strings
def encrypt(self, plain, algorithm='md5'): """ 简单封装系统加密 :param plain: 待加密内容 :type plain: ``str/bytes`` :param algorithm: 加密算法 :type algorithm: str :return: :rtype: """ plain = helper.to_bytes(plain) return getattr(hashlib, algorithm)(plain).hexdigest()
简单封装系统加密 :param plain: 待加密内容 :type plain: ``str/bytes`` :param algorithm: 加密算法 :type algorithm: str :return: :rtype:
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: FieldContext for this FieldInstance :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldContext """ if self._context is None: self._context = FieldContext( self._version, assistant_sid=self._solution['assistant_sid'], task_sid=self._solution['task_sid'], sid=self._solution['sid'], ) return self._context
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: FieldContext for this FieldInstance :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldContext
def _chunks(l, ncols): """Yield successive n-sized chunks from list, l.""" assert isinstance(ncols, int), "ncols must be an integer" for i in range(0, len(l), ncols): yield l[i: i+ncols]
Yield successive n-sized chunks from list, l.
def mols_from_text(text, no_halt=True, assign_descriptors=True): """Returns molecules generated from sdfile text Throws: StopIteration: if the text does not have molecule ValueError: if Unsupported symbol is found """ if isinstance(text, bytes): t = tx.decode(text) else: t = text # Lazy line splitter. More efficient memory usage than str.split. exp = re.compile(r"[^\n]*\n|.") sp = (x.group(0) for x in re.finditer(exp, t)) for c in mol_supplier(sp, no_halt, assign_descriptors): yield c
Returns molecules generated from sdfile text Throws: StopIteration: if the text does not have molecule ValueError: if Unsupported symbol is found
def _date_from_match(match_object): """ Create a date object from a regular expression match. The regular expression match is expected to be from _RE_DATE or _RE_DATETIME. @param match_object: The regular expression match. @type match_object: B{re}.I{MatchObject} @return: A date object. @rtype: B{datetime}.I{date} """ year = int(match_object.group("year")) month = int(match_object.group("month")) day = int(match_object.group("day")) return datetime.date(year, month, day)
Create a date object from a regular expression match. The regular expression match is expected to be from _RE_DATE or _RE_DATETIME. @param match_object: The regular expression match. @type match_object: B{re}.I{MatchObject} @return: A date object. @rtype: B{datetime}.I{date}
def new_calendar(self, calendar_name): """ Creates a new calendar :param str calendar_name: name of the new calendar :return: a new Calendar instance :rtype: Calendar """ if not calendar_name: return None url = self.build_url(self._endpoints.get('root_calendars')) response = self.con.post(url, data={self._cc('name'): calendar_name}) if not response: return None data = response.json() # Everything received from cloud must be passed as self._cloud_data_key return self.calendar_constructor(parent=self, **{self._cloud_data_key: data})
Creates a new calendar :param str calendar_name: name of the new calendar :return: a new Calendar instance :rtype: Calendar
def __setUpTrakers(self): ''' set symbols ''' for symbol in self.symbols: self.__trakers[symbol]=OneTraker(symbol, self, self.buyingRatio)
set symbols
def _format_list(self, data): """ Format a list to use in javascript """ dataset = "[" i = 0 for el in data: if pd.isnull(el): dataset += "null" else: dtype = type(data[i]) if dtype == int or dtype == float: dataset += str(el) else: dataset += '"' + el + '"' if i < len(data) - 1: dataset += ', ' dataset += "]" return dataset
Format a list to use in javascript
def removeStepListener(listener): """removeStepListener(traci.StepListener) -> bool Remove the step listener from traci's step listener container. Returns True if the listener was removed successfully, False if it wasn't registered. """ if listener in _stepListeners: _stepListeners.remove(listener) return True warnings.warn( "removeStepListener(listener): listener %s not registered as step listener" % str(listener)) return False
removeStepListener(traci.StepListener) -> bool Remove the step listener from traci's step listener container. Returns True if the listener was removed successfully, False if it wasn't registered.
def app_update_state(app_id,state): """ update app state """ try: create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') conn = get_conn() c = conn.cursor() c.execute("UPDATE app SET state='{0}',change_at='{1}' WHERE id='{2}'".format(state, create_at, app_id)) conn.commit() conn.close() print 'UPDATE app %s state to %s succeed!' % (app_id,state) except Exception, e: raise RuntimeError( 'update app %s state to %s failed! %s' % (app_id,state,e) )
update app state
def update_data_frames(network, cluster_weights, dates, hours): """ Updates the snapshots, snapshots weights and the dataframes based on the original data in the network and the medoids created by clustering these original data. Parameters ----------- network : pyPSA network object cluster_weights: dictionary dates: Datetimeindex Returns ------- network """ network.snapshot_weightings = network.snapshot_weightings.loc[dates] network.snapshots = network.snapshot_weightings.index # set new snapshot weights from cluster_weights snapshot_weightings = [] for i in cluster_weights.values(): x = 0 while x < hours: snapshot_weightings.append(i) x += 1 for i in range(len(network.snapshot_weightings)): network.snapshot_weightings[i] = snapshot_weightings[i] # put the snapshot in the right order network.snapshots.sort_values() network.snapshot_weightings.sort_index() return network
Updates the snapshots, snapshots weights and the dataframes based on the original data in the network and the medoids created by clustering these original data. Parameters ----------- network : pyPSA network object cluster_weights: dictionary dates: Datetimeindex Returns ------- network
def predict(rf_model, features): """ Return label and probability estimated. Parameters ---------- rf_model : sklearn.ensemble.RandomForestClassifier The UPSILoN random forests model. features : array_like A list of features estimated by UPSILoN. Returns ------- label : str A predicted label (i.e. class). probability : float Class probability. flag : int Classification flag. """ import numpy as np from upsilon.extract_features.feature_set import get_feature_set feature_set = get_feature_set() # Grab only necessary features. cols = [feature for feature in features if feature in feature_set] cols = sorted(cols) filtered_features = [] for i in range(len(cols)): filtered_features.append(features[cols[i]]) filtered_features = np.array(filtered_features).reshape(1, -1) # Classify. classes = rf_model.classes_ # Note that we're classifying a single source, so [0] need tobe added. probabilities = rf_model.predict_proba(filtered_features)[0] # Classification flag. flag = 0 if features['period_SNR'] < 20. or is_period_alias(features['period']): flag = 1 # Return class, probability, and flag. max_index = np.where(probabilities == np.max(probabilities)) return classes[max_index][0], probabilities[max_index][0], flag
Return label and probability estimated. Parameters ---------- rf_model : sklearn.ensemble.RandomForestClassifier The UPSILoN random forests model. features : array_like A list of features estimated by UPSILoN. Returns ------- label : str A predicted label (i.e. class). probability : float Class probability. flag : int Classification flag.
def _add_data(self, plotter_cls, *args, **kwargs): """ Visualize this data array Parameters ---------- %(Plotter.parameters.no_data)s Returns ------- psyplot.plotter.Plotter The plotter that visualizes the data """ # this method is just a shortcut to the :meth:`Project._add_data` # method but is reimplemented by subclasses as the # :class:`DatasetPlotter` or the :class:`DataArrayPlotter` return plotter_cls(self._da, *args, **kwargs)
Visualize this data array Parameters ---------- %(Plotter.parameters.no_data)s Returns ------- psyplot.plotter.Plotter The plotter that visualizes the data
def _array2image_list(self, array): """ maps 1d vector of joint exposures in list of 2d images of single exposures :param array: 1d numpy array :return: list of 2d numpy arrays of size of exposures """ image_list = [] k = 0 for i in range(self._num_bands): if self._compute_bool[i] is True: num_data = self.num_response_list[i] array_i = array[k:k + num_data] image_i = self._imageModel_list[i].ImageNumerics.array2image(array_i) image_list.append(image_i) k += num_data return image_list
maps 1d vector of joint exposures in list of 2d images of single exposures :param array: 1d numpy array :return: list of 2d numpy arrays of size of exposures
def ping(token_or_hostname=None): """ Send an echo request to a nago host. Arguments: token_or_host_name -- The remote node to ping If node is not provided, simply return pong You can use the special nodenames "server" or "master" """ if not token_or_hostname: return "Pong!" node = nago.core.get_node(token_or_hostname) if not node and token_or_hostname in ('master', 'server'): token_or_hostname = nago.settings.get_option('server') node = nago.core.get_node(token_or_hostname) if not node: try: address = socket.gethostbyname(token_or_hostname) node = nago.core.Node() node['host_name'] = token_or_hostname node['address'] = address node['access'] = 'node' if token_or_hostname == nago.settings.get_option('server'): node['access'] = 'master' node.save() except Exception: raise Exception("'%s' was not found in list of known hosts, and does not resolve to a valid address" % token_or_hostname) return node.send_command('nodes', 'ping')
Send an echo request to a nago host. Arguments: token_or_host_name -- The remote node to ping If node is not provided, simply return pong You can use the special nodenames "server" or "master"
def ssl_options(self): """Check the config to see if SSL configuration options have been passed and replace none, option, and required with the correct values in the certreqs attribute if it is specified. :rtype: dict """ opts = self.namespace.server.get(config.SSL_OPTIONS) or dict() if config.CERT_REQS in opts: opts[config.CERT_REQS] = \ self.CERT_REQUIREMENTS[opts[config.CERT_REQS]] return opts or None
Check the config to see if SSL configuration options have been passed and replace none, option, and required with the correct values in the certreqs attribute if it is specified. :rtype: dict
def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result
The same as hash_file, but also return the file's mode, or None if no mode data is present.
def find_prekeyed(self, value, key): """ Find a value in a node, using a key function. The value is already a key. """ while self is not NULL: direction = cmp(value, key(self.value)) if direction < 0: self = self.left elif direction > 0: self = self.right elif direction == 0: return self.value
Find a value in a node, using a key function. The value is already a key.
def get_lockfile_filename(impl, working_dir): """ Get the absolute path to the chain's indexing lockfile """ lockfile_name = impl.get_virtual_chain_name() + ".lock" return os.path.join(working_dir, lockfile_name)
Get the absolute path to the chain's indexing lockfile
def parameter(self, parameter_id): """Return the specified global parameter (the entire object, not just the value)""" for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: if parameter.id == parameter_id: return parameter raise KeyError("No such parameter exists: " + parameter_id )
Return the specified global parameter (the entire object, not just the value)
def get_message_headers(self, section: Sequence[int] = None, subset: Collection[bytes] = None, inverse: bool = False) -> Writeable: """Get the headers from the message or a ``message/rfc822`` sub-part of the message.. The ``section`` argument can index a nested sub-part of the message. For example, ``[2, 3]`` would get the 2nd sub-part of the message and then index it for its 3rd sub-part. Args: section: Optional nested list of sub-part indexes. subset: Subset of headers to get. inverse: If ``subset`` is given, this flag will invert it so that the headers *not* in ``subset`` are returned. """ ...
Get the headers from the message or a ``message/rfc822`` sub-part of the message.. The ``section`` argument can index a nested sub-part of the message. For example, ``[2, 3]`` would get the 2nd sub-part of the message and then index it for its 3rd sub-part. Args: section: Optional nested list of sub-part indexes. subset: Subset of headers to get. inverse: If ``subset`` is given, this flag will invert it so that the headers *not* in ``subset`` are returned.
def listRuns(self, **kwargs): """ API to list all run dictionary, for example: [{'run_num': [160578, 160498, 160447, 160379]}]. At least one parameter is mandatory. :param logical_file_name: List all runs in the file :type logical_file_name: str :param block_name: List all runs in the block :type block_name: str :param dataset: List all runs in that dataset :type dataset: str :param run_num: List all runs :type run_num: int, string or list """ validParameters = ['run_num', 'logical_file_name', 'block_name', 'dataset'] requiredParameters = {'multiple': validParameters} checkInputParameter(method="listRuns", parameters=kwargs.keys(), validParameters=validParameters, requiredParameters=requiredParameters) return self.__callServer("runs", params=kwargs)
API to list all run dictionary, for example: [{'run_num': [160578, 160498, 160447, 160379]}]. At least one parameter is mandatory. :param logical_file_name: List all runs in the file :type logical_file_name: str :param block_name: List all runs in the block :type block_name: str :param dataset: List all runs in that dataset :type dataset: str :param run_num: List all runs :type run_num: int, string or list
def dre_dc(self, pars): r""" :math:Add formula """ self._set_parameters(pars) # term 1 num1a = np.log(self.w * self.tau) * self.otc * np.sin(self.ang) num1b = self.otc * np.cos(self.ang) * np.pi / 2.0 term1 = (num1a + num1b) / self.denom # term 2 num2 = self.otc * np.sin(self.c / np.pi) * 2 denom2 = self.denom ** 2 term2 = num2 / denom2 # term 3 num3a = 2 * np.log(self.w * self.tau) * self.otc * np.cos(self.ang) num3b = 2 * ((self.w * self.tau) ** 2) * np.pi / 2.0 * np.sin(self.ang) num3c = 2 * np.log(self.w * self.tau) * self.otc2 term3 = num3a - num3b + num3c result = self.sigmai * self.m * (term1 + term2 * term3) return result
r""" :math:Add formula
def poll(self, poll_rate=None, timeout=None): """Return the status of a task or timeout. There are several API calls that trigger asynchronous tasks, such as synchronizing a repository, or publishing or promoting a content view. It is possible to check on the status of a task if you know its UUID. This method polls a task once every ``poll_rate`` seconds and, upon task completion, returns information about that task. :param poll_rate: Delay between the end of one task check-up and the start of the next check-up. Defaults to ``nailgun.entity_mixins.TASK_POLL_RATE``. :param timeout: Maximum number of seconds to wait until timing out. Defaults to ``nailgun.entity_mixins.TASK_TIMEOUT``. :returns: Information about the asynchronous task. :raises: ``nailgun.entity_mixins.TaskTimedOutError`` if the task completes with any result other than "success". :raises: ``nailgun.entity_mixins.TaskFailedError`` if the task finishes with any result other than "success". :raises: ``requests.exceptions.HTTPError`` If the API returns a message with an HTTP 4XX or 5XX status code. """ # See nailgun.entity_mixins._poll_task for an explanation of why a # private method is called. return _poll_task( self.id, # pylint:disable=no-member self._server_config, poll_rate, timeout )
Return the status of a task or timeout. There are several API calls that trigger asynchronous tasks, such as synchronizing a repository, or publishing or promoting a content view. It is possible to check on the status of a task if you know its UUID. This method polls a task once every ``poll_rate`` seconds and, upon task completion, returns information about that task. :param poll_rate: Delay between the end of one task check-up and the start of the next check-up. Defaults to ``nailgun.entity_mixins.TASK_POLL_RATE``. :param timeout: Maximum number of seconds to wait until timing out. Defaults to ``nailgun.entity_mixins.TASK_TIMEOUT``. :returns: Information about the asynchronous task. :raises: ``nailgun.entity_mixins.TaskTimedOutError`` if the task completes with any result other than "success". :raises: ``nailgun.entity_mixins.TaskFailedError`` if the task finishes with any result other than "success". :raises: ``requests.exceptions.HTTPError`` If the API returns a message with an HTTP 4XX or 5XX status code.
def get_dev_mac_learn(devid, auth, url): ''' function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on the target device. :param devid: int value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dict objects which contain the mac learn table of target device id :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_mac_learn = get_dev_mac_learn('10', auth.creds, auth.url) >>> assert type(dev_mac_learn) is list >>> assert 'deviceId' in dev_mac_learn[0] ''' get_dev_mac_learn_url='/imcrs/res/access/ipMacLearn/'+str(devid) f_url = url+get_dev_mac_learn_url try: r = requests.get(f_url, auth=auth, headers=HEADERS) if r.status_code == 200: if len(r.text) < 1: mac_learn_query = {} return mac_learn_query else: mac_learn_query = (json.loads(r.text))['ipMacLearnResult'] return mac_learn_query except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_mac_learn: An Error has occured"
function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on the target device. :param devid: int value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dict objects which contain the mac learn table of target device id :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_mac_learn = get_dev_mac_learn('10', auth.creds, auth.url) >>> assert type(dev_mac_learn) is list >>> assert 'deviceId' in dev_mac_learn[0]
def convert(image, shape, gray=False, dtype='float64', normalize='max'): """Convert image to standardized format. Several properties of the input image may be changed including the shape, data type and maximal value of the image. In addition, this function may convert the image into an ODL object and/or a gray scale image. """ image = image.astype(dtype) if gray: image[..., 0] *= 0.2126 image[..., 1] *= 0.7152 image[..., 2] *= 0.0722 image = np.sum(image, axis=2) if shape is not None: image = skimage.transform.resize(image, shape, mode='constant') image = image.astype(dtype) if normalize == 'max': image /= image.max() elif normalize == 'sum': image /= image.sum() else: assert False return image
Convert image to standardized format. Several properties of the input image may be changed including the shape, data type and maximal value of the image. In addition, this function may convert the image into an ODL object and/or a gray scale image.
async def syscall(self, func, ignoreException = False): """ Call a syscall method and retrieve its return value """ ev = await self.syscall_noreturn(func) if hasattr(ev, 'exception'): if ignoreException: return else: raise ev.exception[1] else: return ev.retvalue
Call a syscall method and retrieve its return value
def hostname(self, value): """ The hostname where the log message was created. Should be the first part of the hostname, or an IP address. Should NOT be set to a fully qualified domain name. """ if value is None: value = socket.gethostname() self._hostname = value
The hostname where the log message was created. Should be the first part of the hostname, or an IP address. Should NOT be set to a fully qualified domain name.
def resource_of_node(resources, node): """ Returns resource of node. """ for resource in resources: model = getattr(resource, 'model', None) if type(node) == model: return resource return BasePageResource
Returns resource of node.
def _set_axis(self,traces,on=None,side='right',title=''): """ Sets the axis in which each trace should appear If the axis doesn't exist then a new axis is created Parameters: ----------- traces : list(str) List of trace names on : string The axis in which the traces should be placed. If this is not indicated then a new axis will be created side : string Side where the axis will be placed 'left' 'right' title : string Sets the title of the axis Applies only to new axis """ fig={} fig_cpy=fig_to_dict(self).copy() fig['data']=fig_cpy['data'] fig['layout']=fig_cpy['layout'] fig=Figure(fig) traces=make_list(traces) def update_data(trace,y): anchor=fig.axis['def'][y]['anchor'] if 'anchor' in fig.axis['def'][y] else 'x1' idx=fig.trace_dict[trace] if isinstance(trace,str) else trace fig['data'][idx]['xaxis']=anchor fig['data'][idx]['yaxis']=y for trace in traces: if on: if on not in fig.axis['def']: raise Exception('"on" axis does not exists: {0}'.format(on)) update_data(trace,y=on) else: curr_x,curr_y=fig.axis['ref'][trace] domain='[0.0, 1.0]' if 'domain' not in fig.axis['def'][curr_y] else str(fig.axis['def'][curr_y]['domain']) try: new_axis=fig.axis['dom']['y'][domain][side] except KeyError: axis=fig.axis['def'][curr_y].copy() ### check overlaying values axis.update(title=title,overlaying=curr_y,side=side,anchor=curr_x) axis_idx=str(fig.axis['len']['y']+1) fig['layout']['yaxis{0}'.format(axis_idx)]=axis new_axis='y{0}'.format(axis_idx) update_data(trace,y=new_axis) for k in list(fig.axis['def'].keys()): id='{0}axis{1}'.format(k[0],k[-1:]) if k not in fig.axis['ref_axis']: try: del fig['layout'][id] except KeyError: pass return fig
Sets the axis in which each trace should appear If the axis doesn't exist then a new axis is created Parameters: ----------- traces : list(str) List of trace names on : string The axis in which the traces should be placed. If this is not indicated then a new axis will be created side : string Side where the axis will be placed 'left' 'right' title : string Sets the title of the axis Applies only to new axis
def cancel_root_generation(self): """Cancel any in-progress root generation attempt. This clears any progress made. This must be called to change the OTP or PGP key being used. Supported methods: DELETE: /sys/generate-root/attempt. Produces: 204 (empty body) :return: The response of the request. :rtype: request.Response """ api_path = '/v1/sys/generate-root/attempt' response = self._adapter.delete( url=api_path, ) return response
Cancel any in-progress root generation attempt. This clears any progress made. This must be called to change the OTP or PGP key being used. Supported methods: DELETE: /sys/generate-root/attempt. Produces: 204 (empty body) :return: The response of the request. :rtype: request.Response
def __callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any """ Calls the registered method in the component for the given event :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong """ comp_callback = self.context.get_callback(event) if not comp_callback: # No registered callback return True # Call it result = comp_callback(self.instance, *args, **kwargs) if result is None: # Special case, if the call back returns nothing return True return result
Calls the registered method in the component for the given event :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong
def essays(self): """Copy essays from the source profile to the destination profile.""" for essay_name in self.dest_user.profile.essays.essay_names: setattr(self.dest_user.profile.essays, essay_name, getattr(self.source_profile.essays, essay_name))
Copy essays from the source profile to the destination profile.
def from_shapely(sgeom, srid=None): """ Create a Geometry from a Shapely geometry and the specified SRID. The Shapely geometry will not be modified. """ if SHAPELY: WKBWriter.defaults["include_srid"] = True if srid: lgeos.GEOSSetSRID(sgeom._geom, srid) return Geometry(sgeom.wkb_hex) else: raise DependencyError("Shapely")
Create a Geometry from a Shapely geometry and the specified SRID. The Shapely geometry will not be modified.
def load_from_json(data): """ Load a :class:`Item` from a dictionary ot string (that will be parsed as json) """ if isinstance(data, str): data = json.loads(data) return Item(data['title'], data['uri'])
Load a :class:`Item` from a dictionary ot string (that will be parsed as json)
def _visibleToRealColumn(self, text, visiblePos): """If \t is used, real position of symbol in block and visible position differs This function converts visible to real. Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short """ if visiblePos == 0: return 0 elif not '\t' in text: return visiblePos else: currentIndex = 1 for currentVisiblePos in self._visibleCharPositionGenerator(text): if currentVisiblePos >= visiblePos: return currentIndex - 1 currentIndex += 1 return None
If \t is used, real position of symbol in block and visible position differs This function converts visible to real. Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short
def get_id(self): """Converts a User ID and parts of a User password hash to a token.""" # This function is used by Flask-Login to store a User ID securely as a browser cookie. # The last part of the password is included to invalidate tokens when password change. # user_id and password_ends_with are encrypted, timestamped and signed. # This function works in tandem with UserMixin.get_user_by_token() user_manager = current_app.user_manager user_id = self.id password_ends_with = '' if user_manager.USER_ENABLE_AUTH0 else self.password[-8:] user_token = user_manager.generate_token( user_id, # User ID password_ends_with, # Last 8 characters of user password ) # print("UserMixin.get_id: ID:", self.id, "token:", user_token) return user_token
Converts a User ID and parts of a User password hash to a token.
def get_from_headers(request, key): """Try to read a value named ``key`` from the headers. """ value = request.headers.get(key) return to_native(value)
Try to read a value named ``key`` from the headers.
def diffuse_advanced(self, heatColumnName=None, time=None, verbose=False): """ Diffusion will send the selected network view and its selected nodes to a web-based REST service to calculate network propagation. Results are returned and represented by columns in the node table. Columns are created for each execution of Diffusion and their names are returned in the response. :param heatColumnName (string, optional): A node column name intended to override the default table column 'diffusion_input'. This represents the query vector and corresponds to h in the diffusion equation. = ['HEKScore', 'JurkatScore', '(Use selected nodes)'] :param time (string, optional): The extent of spread over the network. This corresponds to t in the diffusion equation. :param verbose: print more """ PARAMS=set_param(["heatColumnName","time"],[heatColumnName,time]) response=api(url=self.__url+"/diffuse_advanced", PARAMS=PARAMS, method="POST", verbose=verbose) return response
Diffusion will send the selected network view and its selected nodes to a web-based REST service to calculate network propagation. Results are returned and represented by columns in the node table. Columns are created for each execution of Diffusion and their names are returned in the response. :param heatColumnName (string, optional): A node column name intended to override the default table column 'diffusion_input'. This represents the query vector and corresponds to h in the diffusion equation. = ['HEKScore', 'JurkatScore', '(Use selected nodes)'] :param time (string, optional): The extent of spread over the network. This corresponds to t in the diffusion equation. :param verbose: print more
def license_present(name): ''' Ensures that the specified PowerPath license key is present on the host. name The license key to ensure is present ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if not __salt__['powerpath.has_powerpath'](): ret['result'] = False ret['comment'] = 'PowerPath is not installed.' return ret licenses = [l['key'] for l in __salt__['powerpath.list_licenses']()] if name in licenses: ret['result'] = True ret['comment'] = 'License key {0} already present'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'License key {0} is set to be added'.format(name) return ret data = __salt__['powerpath.add_license'](name) if data['result']: ret['changes'] = {name: 'added'} ret['result'] = True ret['comment'] = data['output'] return ret else: ret['result'] = False ret['comment'] = data['output'] return ret
Ensures that the specified PowerPath license key is present on the host. name The license key to ensure is present
def writefile(filename, content): """ writes the content into the file :param filename: the filename :param content: teh content :return: """ with open(path_expand(filename), 'w') as outfile: outfile.write(content)
writes the content into the file :param filename: the filename :param content: teh content :return:
def add(self, level, message, extra_tags='', *args, **kwargs): """ Queues a message to be stored. The message is only queued if it contained something and its level is not less than the recording level (``self.level``). """ if not message: return # Check that the message level is not less than the recording level. level = int(level) if level < self.level: return # Add the message. self.added_new = True message = Message(level, message, extra_tags=extra_tags) message = self.process_message(message, *args, **kwargs) if message: self._queued_messages.append(message)
Queues a message to be stored. The message is only queued if it contained something and its level is not less than the recording level (``self.level``).
def _exec_callers(xinst, result): """Adds the dependency calls from the specified executable instance to the results dictionary. """ for depkey, depval in xinst.dependencies.items(): if depval.target is not None: if depval.target.name in result: if xinst not in result[depval.target.name]: result[depval.target.name].append(xinst) else: result[depval.target.name] = [xinst] for xname, xvalue in xinst.executables: _exec_callers(xvalue, result)
Adds the dependency calls from the specified executable instance to the results dictionary.
def do_execute_direct(self, code: str, silent: bool = False) -> [str, dict]: """ This is the main method that takes code from the Jupyter cell and submits it to the SAS server :param code: code from the cell :param silent: :return: str with either the log or list """ if not code.strip(): return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}} if self.mva is None: self._allow_stdin = True self._start_sas() if self.lst_len < 0: self._get_lst_len() if code.startswith('Obfuscated SAS Code'): logger.debug("decoding string") tmp1 = code.split() decode = base64.b64decode(tmp1[-1]) code = decode.decode('utf-8') if code.startswith('showSASLog_11092015') == False and code.startswith("CompleteshowSASLog_11092015") == False: logger.debug("code type: " + str(type(code))) logger.debug("code length: " + str(len(code))) logger.debug("code string: " + code) if code.startswith("/*SASKernelTest*/"): res = self.mva.submit(code, "text") else: res = self.mva.submit(code, prompt=self.promptDict) self.promptDict = {} if res['LOG'].find("SAS process has terminated unexpectedly") > -1: print(res['LOG'], '\n' "Restarting SAS session on your behalf") self.do_shutdown(True) return res['LOG'] output = res['LST'] log = res['LOG'] return self._which_display(log, output) elif code.startswith("CompleteshowSASLog_11092015") == True and code.startswith('showSASLog_11092015') == False: full_log = highlight(self.mva.saslog(), SASLogLexer(), HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>", title="Full SAS Log")) return full_log.replace('\n', ' ') else: return self.cachedlog.replace('\n', ' ')
This is the main method that takes code from the Jupyter cell and submits it to the SAS server :param code: code from the cell :param silent: :return: str with either the log or list
def compute_message_authenticator(radius_packet, packed_req_authenticator, shared_secret): """ Computes the "Message-Authenticator" of a given RADIUS packet. """ data = prepare_packed_data(radius_packet, packed_req_authenticator) radius_hmac = hmac.new(shared_secret, data, hashlib.md5) return radius_hmac.digest()
Computes the "Message-Authenticator" of a given RADIUS packet.
def fbresnet152(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['fbresnet152'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
def install(self, goal=None, first=False, replace=False, before=None, after=None): """Install the task in the specified goal (or a new goal with the same name as the task). The placement of the task in the execution list of the goal defaults to the end but can be :rtype : object influence by specifying exactly one of the following arguments: :API: public :param first: Places this task 1st in the goal's execution list. :param replace: Replaces any existing tasks in the goal with this goal. :param before: Places this task before the named task in the goal's execution list. :param after: Places this task after the named task in the goal's execution list. :returns: The goal with task installed. """ goal = Goal.by_name(goal or self.name) goal.install(self, first, replace, before, after) return goal
Install the task in the specified goal (or a new goal with the same name as the task). The placement of the task in the execution list of the goal defaults to the end but can be :rtype : object influence by specifying exactly one of the following arguments: :API: public :param first: Places this task 1st in the goal's execution list. :param replace: Replaces any existing tasks in the goal with this goal. :param before: Places this task before the named task in the goal's execution list. :param after: Places this task after the named task in the goal's execution list. :returns: The goal with task installed.
def find_data_files(source, target, patterns): """ Locates the specified data-files and returns the matches in a data_files compatible format. source is the root of the source data tree. Use '' or '.' for current directory. target is the root of the target data tree. Use '' or '.' for the distribution directory. patterns is a sequence of glob-patterns for the files you want to copy. """ if glob.has_magic(source) or glob.has_magic(target): raise ValueError("Magic not allowed in src, target") ret = {} for pattern in patterns: pattern = os.path.join(source, pattern) for filename in glob.glob(pattern): if os.path.isfile(filename): targetpath = os.path.join( target, os.path.relpath(filename, source) ) path = os.path.dirname(targetpath) ret.setdefault(path, []).append(filename) return sorted(ret.items())
Locates the specified data-files and returns the matches in a data_files compatible format. source is the root of the source data tree. Use '' or '.' for current directory. target is the root of the target data tree. Use '' or '.' for the distribution directory. patterns is a sequence of glob-patterns for the files you want to copy.
def expire(self, key, timeout): """Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. The timeout is cleared only when the key is removed using the :meth:`~tredis.RedisClient.delete` method or overwritten using the :meth:`~tredis.RedisClient.set` or :meth:`~tredis.RedisClient.getset` methods. This means that all the operations that conceptually alter the value stored at the key without replacing it with a new one will leave the timeout untouched. For instance, incrementing the value of a key with :meth:`~tredis.RedisClient.incr`, pushing a new value into a list with :meth:`~tredis.RedisClient.lpush`, or altering the field value of a hash with :meth:`~tredis.RedisClient.hset` are all operations that will leave the timeout untouched. The timeout can also be cleared, turning the key back into a persistent key, using the :meth:`~tredis.RedisClient.persist` method. If a key is renamed with :meth:`~tredis.RedisClient.rename`, the associated time to live is transferred to the new key name. If a key is overwritten by :meth:`~tredis.RedisClient.rename`, like in the case of an existing key ``Key_A`` that is overwritten by a call like ``client.rename(Key_B, Key_A)`` it does not matter if the original ``Key_A`` had a timeout associated or not, the new key ``Key_A`` will inherit all the characteristics of ``Key_B``. .. note:: **Time complexity**: ``O(1)`` :param key: The key to set an expiration for :type key: :class:`str`, :class:`bytes` :param int timeout: The number of seconds to set the timeout to :rtype: bool :raises: :exc:`~tredis.exceptions.RedisError` """ return self._execute( [b'EXPIRE', key, ascii(timeout).encode('ascii')], 1)
Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. The timeout is cleared only when the key is removed using the :meth:`~tredis.RedisClient.delete` method or overwritten using the :meth:`~tredis.RedisClient.set` or :meth:`~tredis.RedisClient.getset` methods. This means that all the operations that conceptually alter the value stored at the key without replacing it with a new one will leave the timeout untouched. For instance, incrementing the value of a key with :meth:`~tredis.RedisClient.incr`, pushing a new value into a list with :meth:`~tredis.RedisClient.lpush`, or altering the field value of a hash with :meth:`~tredis.RedisClient.hset` are all operations that will leave the timeout untouched. The timeout can also be cleared, turning the key back into a persistent key, using the :meth:`~tredis.RedisClient.persist` method. If a key is renamed with :meth:`~tredis.RedisClient.rename`, the associated time to live is transferred to the new key name. If a key is overwritten by :meth:`~tredis.RedisClient.rename`, like in the case of an existing key ``Key_A`` that is overwritten by a call like ``client.rename(Key_B, Key_A)`` it does not matter if the original ``Key_A`` had a timeout associated or not, the new key ``Key_A`` will inherit all the characteristics of ``Key_B``. .. note:: **Time complexity**: ``O(1)`` :param key: The key to set an expiration for :type key: :class:`str`, :class:`bytes` :param int timeout: The number of seconds to set the timeout to :rtype: bool :raises: :exc:`~tredis.exceptions.RedisError`
def join(self, other, **kwargs): """Joins a list or two objects together. Args: other: The other object(s) to join on. Returns: Joined objects. """ if not isinstance(other, list): other = [other] return self._join_list_of_managers(other, **kwargs)
Joins a list or two objects together. Args: other: The other object(s) to join on. Returns: Joined objects.
def build_sourcemap(sources): """ Similar to build_headermap(), but builds a dictionary of includes from the "source" files (i.e. ".c/.cc" files). """ sourcemap = {} for sfile in sources: inc = find_includes(sfile) sourcemap[sfile] = set(inc) return sourcemap
Similar to build_headermap(), but builds a dictionary of includes from the "source" files (i.e. ".c/.cc" files).