code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _set_original_fields(instance): """ Save fields value, only for non-m2m fields. """ original_fields = {} def _set_original_field(instance, field): if instance.pk is None: original_fields[field] = None else: if isinstance(instance._meta.get_field(field), ForeignKey): # Only get the PK, we don't want to get the object # (which would make an additional request) original_fields[field] = getattr(instance, '{0}_id'.format(field)) else: original_fields[field] = getattr(instance, field) for field in getattr(instance, '_tracked_fields', []): _set_original_field(instance, field) for field in getattr(instance, '_tracked_related_fields', {}).keys(): _set_original_field(instance, field) instance._original_fields = original_fields # Include pk to detect the creation of an object instance._original_fields['pk'] = instance.pk
Save fields value, only for non-m2m fields.
def drag(self, point): """Update the tracball during a drag. Parameters ---------- point : (2,) int The current x and y pixel coordinates of the mouse during a drag. This will compute a movement for the trackball with the relative motion between this point and the one marked by down(). """ point = np.array(point, dtype=np.float32) dx, dy = point - self._pdown mindim = 0.3 * np.min(self._size) target = self._target x_axis = self._pose[:3, 0].flatten() y_axis = self._pose[:3, 1].flatten() z_axis = self._pose[:3, 2].flatten() eye = self._pose[:3, 3].flatten() # Interpret drag as a rotation if self._state == Trackball.STATE_ROTATE: x_angle = -dx / mindim x_rot_mat = transformations.rotation_matrix( x_angle, y_axis, target ) y_angle = dy / mindim y_rot_mat = transformations.rotation_matrix( y_angle, x_axis, target ) self._n_pose = y_rot_mat.dot(x_rot_mat.dot(self._pose)) # Interpret drag as a roll about the camera axis elif self._state == Trackball.STATE_ROLL: center = self._size / 2.0 v_init = self._pdown - center v_curr = point - center v_init = v_init / np.linalg.norm(v_init) v_curr = v_curr / np.linalg.norm(v_curr) theta = (-np.arctan2(v_curr[1], v_curr[0]) + np.arctan2(v_init[1], v_init[0])) rot_mat = transformations.rotation_matrix(theta, z_axis, target) self._n_pose = rot_mat.dot(self._pose) # Interpret drag as a camera pan in view plane elif self._state == Trackball.STATE_PAN: dx = -dx / (5.0 * mindim) * self._scale dy = -dy / (5.0 * mindim) * self._scale translation = dx * x_axis + dy * y_axis self._n_target = self._target + translation t_tf = np.eye(4) t_tf[:3, 3] = translation self._n_pose = t_tf.dot(self._pose) # Interpret drag as a zoom motion elif self._state == Trackball.STATE_ZOOM: radius = np.linalg.norm(eye - target) ratio = 0.0 if dy > 0: ratio = np.exp(abs(dy) / (0.5 * self._size[1])) - 1.0 elif dy < 0: ratio = 1.0 - np.exp(dy / (0.5 * (self._size[1]))) translation = -np.sign(dy) * ratio * radius * z_axis t_tf = np.eye(4) t_tf[:3, 3] = translation self._n_pose = t_tf.dot(self._pose)
Update the tracball during a drag. Parameters ---------- point : (2,) int The current x and y pixel coordinates of the mouse during a drag. This will compute a movement for the trackball with the relative motion between this point and the one marked by down().
def announcement_posted_hook(request, obj): """Runs whenever a new announcement is created, or a request is approved and posted. obj: The Announcement object """ logger.debug("Announcement posted") if obj.notify_post: logger.debug("Announcement notify on") announcement_posted_twitter(request, obj) try: notify_all = obj.notify_email_all except AttributeError: notify_all = False try: if notify_all: announcement_posted_email(request, obj, True) else: announcement_posted_email(request, obj) except Exception as e: logger.error("Exception when emailing announcement: {}".format(e)) messages.error(request, "Exception when emailing announcement: {}".format(e)) raise e else: logger.debug("Announcement notify off")
Runs whenever a new announcement is created, or a request is approved and posted. obj: The Announcement object
def subset(self, selector): """ Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned. """ if isinstance(selector, (list, tuple)): return map(int, selector) selector = SELECTORS.get(selector, selector) mdtop = MDTrajTopology.from_openmm(self.handler.topology) return mdtop.select(selector)
Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned.
def get_options(config_options, local_options, cli_options): """ Figure out what options to use based on the four places it can come from. Order of precedence: * cli_options specified by the user at the command line * local_options specified in the config file for the metric * config_options specified in the config file at the base * DEFAULT_OPTIONS hard coded defaults """ options = DEFAULT_OPTIONS.copy() if config_options is not None: options.update(config_options) if local_options is not None: options.update(local_options) if cli_options is not None: options.update(cli_options) return options
Figure out what options to use based on the four places it can come from. Order of precedence: * cli_options specified by the user at the command line * local_options specified in the config file for the metric * config_options specified in the config file at the base * DEFAULT_OPTIONS hard coded defaults
def _grads(self, x): """ Gets the gradients from the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the gradients, and will raise the original exception if the objective cannot be computed. :param x: the parameters of the model. :type x: np.array """ try: # self._set_params_transformed(x) self.optimizer_array = x self.obj_grads = self._transform_gradients(self.objective_function_gradients()) self._fail_count = 0 except (LinAlgError, ZeroDivisionError, ValueError): #pragma: no cover if self._fail_count >= self._allowed_failures: raise self._fail_count += 1 self.obj_grads = np.clip(self._transform_gradients(self.objective_function_gradients()), -1e100, 1e100) return self.obj_grads
Gets the gradients from the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the gradients, and will raise the original exception if the objective cannot be computed. :param x: the parameters of the model. :type x: np.array
def create(cls, service=None, endpoint=None, data=None, *args, **kwargs): """ Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service. """ cls.validate(data) if service is None and endpoint is None: raise InvalidArguments(service, endpoint) if endpoint is None: sid = service['id'] if isinstance(service, Entity) else service endpoint = 'services/{0}/integrations'.format(sid) # otherwise endpoint should contain the service path too return getattr(Entity, 'create').__func__(cls, endpoint=endpoint, data=data, *args, **kwargs)
Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service.
def run(self): """The method called by the threading library to start the thread.""" while not self._abort: hashes = self._GetHashes(self._hash_queue, self.hashes_per_batch) if hashes: time_before_analysis = time.time() hash_analyses = self.Analyze(hashes) current_time = time.time() self.seconds_spent_analyzing += current_time - time_before_analysis self.analyses_performed += 1 for hash_analysis in hash_analyses: self._hash_analysis_queue.put(hash_analysis) self._hash_queue.task_done() time.sleep(self.wait_after_analysis) else: # Wait for some more hashes to be added to the queue. time.sleep(self.EMPTY_QUEUE_WAIT_TIME)
The method called by the threading library to start the thread.
def execute_function(self, func, *nargs, **kwargs): """ Execute a function object within the execution context. @returns The result of the function call. """ # makes a copy of the func import types fn = types.FunctionType(func.func_code, func.func_globals.copy(), name=func.func_name, argdefs=func.func_defaults, closure=func.func_closure) fn.func_globals.update(self.globals) error_class = Exception if config.catch_rex_errors else None try: return fn(*nargs, **kwargs) except RexError: raise except error_class as e: from inspect import getfile stack = traceback.format_exc() filename = getfile(func) raise RexError("Failed to exec %s:\n\n%s" % (filename, stack))
Execute a function object within the execution context. @returns The result of the function call.
def eval_table(tbl, expression, vm='python', blen=None, storage=None, create='array', vm_kwargs=None, **kwargs): """Evaluate `expression` against columns of a table.""" # setup storage = _util.get_storage(storage) names, columns = _util.check_table_like(tbl) length = len(columns[0]) if vm_kwargs is None: vm_kwargs = dict() # setup vm if vm == 'numexpr': import numexpr evaluate = numexpr.evaluate elif vm == 'python': # noinspection PyUnusedLocal def evaluate(expr, local_dict=None, **kw): # takes no keyword arguments return eval(expr, dict(), local_dict) else: raise ValueError('expected vm either "numexpr" or "python"') # compile expression and get required columns variables = _get_expression_variables(expression, vm) required_columns = {v: columns[names.index(v)] for v in variables} # determine block size for evaluation blen = _util.get_blen_table(required_columns, blen=blen) # build output out = None for i in range(0, length, blen): j = min(i+blen, length) blocals = {v: c[i:j] for v, c in required_columns.items()} res = evaluate(expression, local_dict=blocals, **vm_kwargs) if out is None: out = getattr(storage, create)(res, expectedlen=length, **kwargs) else: out.append(res) return out
Evaluate `expression` against columns of a table.
def delete_statement(cls, prop_nr): """ This serves as an alternative constructor for WDBaseDataType with the only purpose of holding a WD property number and an empty string value in order to indicate that the whole statement with this property number of a WD item should be deleted. :param prop_nr: A WD property number as string :return: An instance of WDBaseDataType """ return cls(value='', snak_type='value', data_type='', is_reference=False, is_qualifier=False, references=[], qualifiers=[], rank='', prop_nr=prop_nr, check_qualifier_equality=True)
This serves as an alternative constructor for WDBaseDataType with the only purpose of holding a WD property number and an empty string value in order to indicate that the whole statement with this property number of a WD item should be deleted. :param prop_nr: A WD property number as string :return: An instance of WDBaseDataType
def slicenet_middle(inputs_encoded, targets, target_space_emb, mask, hparams): """Middle part of slicenet, connecting encoder and decoder.""" def norm_fn(x, name): with tf.variable_scope(name, default_name="norm"): return common_layers.apply_norm(x, hparams.norm_type, hparams.hidden_size, hparams.norm_epsilon) # Flatten targets and embed target_space_id. targets_flat = tf.expand_dims(common_layers.flatten4d3d(targets), axis=2) target_space_emb = tf.tile(target_space_emb, [tf.shape(targets_flat)[0], 1, 1, 1]) # Use attention from each target to look at input and retrieve. targets_shifted = common_layers.shift_right( targets_flat, pad_value=target_space_emb) if hparams.attention_type == "none": targets_with_attention = tf.zeros_like(targets_shifted) else: inputs_padding_bias = (1.0 - mask) * -1e9 # Bias to not attend to padding. targets_with_attention = attention( targets_shifted, inputs_encoded, norm_fn, hparams, bias=inputs_padding_bias) # Positional targets: merge attention and raw. kernel = (hparams.kernel_height, hparams.kernel_width) targets_merged = common_layers.subseparable_conv_block( tf.concat([targets_with_attention, targets_shifted], axis=3), hparams.hidden_size, [((1, 1), kernel)], normalizer_fn=norm_fn, padding="LEFT", separability=4, name="targets_merge") return targets_merged, 0.0
Middle part of slicenet, connecting encoder and decoder.
def url(value): """Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError """ if not url_regex.search(value): message = u"{0} is not a valid URL".format(value) if url_regex.search('http://' + value): message += u". Did you mean: http://{0}".format(value) raise ValueError(message) return value
Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError
def _netid_subscription_url(netid, subscription_codes): """ Return UWNetId resource for provided netid and subscription code or code list """ return "{0}/{1}/subscription/{2}".format( url_base(), netid, (','.join([str(n) for n in subscription_codes]) if isinstance(subscription_codes, (list, tuple)) else subscription_codes))
Return UWNetId resource for provided netid and subscription code or code list
def _set_rc(self): """Method to set the rcparams and defaultParams for this plotter""" base_str = self._get_rc_strings() # to make sure that the '.' is not interpreted as a regex pattern, # we specify the pattern_base by ourselves pattern_base = map(lambda s: s.replace('.', '\.'), base_str) # pattern for valid keys being all formatoptions in this plotter pattern = '(%s)(?=$)' % '|'.join(self._get_formatoptions()) self._rc = rcParams.find_and_replace(base_str, pattern=pattern, pattern_base=pattern_base) user_rc = SubDict(rcParams['plotter.user'], base_str, pattern=pattern, pattern_base=pattern_base) self._rc.update(user_rc.data) self._defaultParams = SubDict(rcParams.defaultParams, base_str, pattern=pattern, pattern_base=pattern_base)
Method to set the rcparams and defaultParams for this plotter
def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo 'Foo Bar' ''' fullname = salt.utils.data.decode(fullname) pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) pre_info['fullname'] = salt.utils.data.decode(pre_info['fullname']) if fullname == pre_info['fullname']: return True _dscl( ['/Users/{0}'.format(name), 'RealName', fullname], # use a 'create' command, because a 'change' command would fail if # current fullname is an empty string. The 'create' will just overwrite # this field. ctype='create' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) current = salt.utils.data.decode(info(name).get('fullname')) return current == fullname
Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo 'Foo Bar'
def make_innermost_setter(setter): """Wraps a setter so it applies to the inner-most results in `kernel_results`. The wrapped setter unwraps `kernel_results` and applies `setter` to the first results without an `inner_results` attribute. Args: setter: A callable that takes the kernel results as well as some `*args` and `**kwargs` and returns a modified copy of those kernel results. Returns: new_setter: A wrapped `setter`. """ @functools.wraps(setter) def _new_setter(kernel_results, *args, **kwargs): """Wrapped setter.""" results_stack = [] while hasattr(kernel_results, 'inner_results'): results_stack.append(kernel_results) kernel_results = kernel_results.inner_results new_kernel_results = setter(kernel_results, *args, **kwargs) for outer_results in reversed(results_stack): new_kernel_results = outer_results._replace( inner_results=new_kernel_results) return new_kernel_results return _new_setter
Wraps a setter so it applies to the inner-most results in `kernel_results`. The wrapped setter unwraps `kernel_results` and applies `setter` to the first results without an `inner_results` attribute. Args: setter: A callable that takes the kernel results as well as some `*args` and `**kwargs` and returns a modified copy of those kernel results. Returns: new_setter: A wrapped `setter`.
def _set_keepalive(self, v, load=False): """ Setter method for keepalive, mapped from YANG variable /interface/tunnel/keepalive (container) If this variable is read-only (config: false) in the source YANG file, then _set_keepalive is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_keepalive() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=keepalive.keepalive, is_container='container', presence=False, yang_name="keepalive", rest_name="keepalive", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Tunnel keepalive', u'cli-sequence-commands': None, u'cli-full-no': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-gre-vxlan', defining_module='brocade-gre-vxlan', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """keepalive must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=keepalive.keepalive, is_container='container', presence=False, yang_name="keepalive", rest_name="keepalive", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Tunnel keepalive', u'cli-sequence-commands': None, u'cli-full-no': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-gre-vxlan', defining_module='brocade-gre-vxlan', yang_type='container', is_config=True)""", }) self.__keepalive = t if hasattr(self, '_set'): self._set()
Setter method for keepalive, mapped from YANG variable /interface/tunnel/keepalive (container) If this variable is read-only (config: false) in the source YANG file, then _set_keepalive is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_keepalive() directly.
def getExtentAddress(self, zoom, extent=None, contained=False): """ Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based on the instance's extent or a user defined extent. Generic method that works with regular and irregular pyramids. Parameters: zoom -- the zoom for which we want the bounding addresses extent (optional) -- the extent ([minX, minY, maxX, maxY]) defaults to the instance extent contained (optional) -- get only tile addresses that contain a coordinate of the extent. For instance if the extent only intersects a tile border, if this option is set to True, this tile will be ignored. defaults to False """ if extent: bbox = extent else: bbox = self.extent minX = bbox[0] maxX = bbox[2] if self.originCorner == 'bottom-left': minY = bbox[3] maxY = bbox[1] elif self.originCorner == 'top-left': minY = bbox[1] maxY = bbox[3] [minCol, minRow] = self.tileAddress(zoom, [minX, maxY]) [maxCol, maxRow] = self.tileAddress(zoom, [maxX, minY]) if contained and minCol != maxCol or minRow != maxRow: parentBoundsMin = self.tileBounds(zoom, minCol, minRow) if self.originCorner == 'bottom-left': if parentBoundsMin[2] == maxX: maxCol -= 1 if parentBoundsMin[3] == minY: maxRow -= 1 elif self.originCorner == 'top-left': if parentBoundsMin[2] == maxX: maxCol -= 1 if parentBoundsMin[1] == minY: maxRow -= 1 return [minRow, minCol, maxRow, maxCol]
Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based on the instance's extent or a user defined extent. Generic method that works with regular and irregular pyramids. Parameters: zoom -- the zoom for which we want the bounding addresses extent (optional) -- the extent ([minX, minY, maxX, maxY]) defaults to the instance extent contained (optional) -- get only tile addresses that contain a coordinate of the extent. For instance if the extent only intersects a tile border, if this option is set to True, this tile will be ignored. defaults to False
def read_namespaced_resource_quota(self, name, namespace, **kwargs): """ read the specified ResourceQuota This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_resource_quota(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the ResourceQuota (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. :param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. :return: V1ResourceQuota If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.read_namespaced_resource_quota_with_http_info(name, namespace, **kwargs) else: (data) = self.read_namespaced_resource_quota_with_http_info(name, namespace, **kwargs) return data
read the specified ResourceQuota This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_resource_quota(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the ResourceQuota (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. :param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. :return: V1ResourceQuota If the method is called asynchronously, returns the request thread.
def create_pattern(cls, userdata): """Create a user data instance with all values the same.""" empty = cls.create_empty(None) userdata_dict = cls.normalize(empty, userdata) return Userdata(userdata_dict)
Create a user data instance with all values the same.
def _stage(self, accepted, count=0): """This is a repeated state in the state removal algorithm""" new5 = self._combine_rest_push() new1 = self._combine_push_pop() new2 = self._combine_push_rest() new3 = self._combine_pop_rest() new4 = self._combine_rest_rest() new = new1 + new2 + new3 + new4 + new5 del new1 del new2 del new3 del new4 del new5 if len(new) == 0: # self.printer() # print 'PDA is empty' # logging.debug('PDA is empty') return None self.statediag = self.statediag + new del new # print 'cleaning...' # It is cheaper to create a new array than to use the old one and # delete a key newstates = [] for key in self.statediag: if len(key.trans) == 0 or key.trans == {}: # rint 'delete '+`key.id` # self.statediag.remove(key) pass else: newstates.append(key) del self.statediag self.statediag = newstates self.quickresponse = {} self.quickresponse_types = {} self.quickresponse_types[0] = [] self.quickresponse_types[1] = [] self.quickresponse_types[2] = [] self.quickresponse_types[3] = [] self.quickresponse_types[4] = [] for state in self.statediag: if state.id not in self.quickresponse: self.quickresponse[state.id] = [state] else: self.quickresponse[state.id].append(state) self.quickresponse_types[state.type].append(state) # else: # print `key.id`+' (type: '+`key.type`+' and sym:'+`key.sym`+')' # print key.trans # print 'checking...' exists = self._check(accepted) if exists == -1: # DEBUGself.printer() # raw_input('next step?') return self._stage(accepted, count + 1) else: # DEBUGself.printer() # print 'Found ' print exists # return self._stage(accepted, count+1) return exists
This is a repeated state in the state removal algorithm
def grid(self, **kw): """ Position a widget in the parent widget in a grid. :param column: use cell identified with given column (starting with 0) :type column: int :param columnspan: this widget will span several columns :type columnspan: int :param in\_: widget to use as container :type in\_: widget :param ipadx: add internal padding in x direction :type ipadx: int :param ipady: add internal padding in y direction :type ipady: int :param padx: add padding in x direction :type padx: int :param pady: add padding in y irection :type pady: int :param row: use cell identified with given row (starting with 0) :type row: int :param rowspan: this widget will span several rows :type rowspan: int :param sticky: "n", "s", "e", "w" or combinations: if cell is larger on which sides will this widget stick to the cell boundary :type sticky: str """ ttk.Scrollbar.grid(self, **kw) self._layout = 'grid'
Position a widget in the parent widget in a grid. :param column: use cell identified with given column (starting with 0) :type column: int :param columnspan: this widget will span several columns :type columnspan: int :param in\_: widget to use as container :type in\_: widget :param ipadx: add internal padding in x direction :type ipadx: int :param ipady: add internal padding in y direction :type ipady: int :param padx: add padding in x direction :type padx: int :param pady: add padding in y irection :type pady: int :param row: use cell identified with given row (starting with 0) :type row: int :param rowspan: this widget will span several rows :type rowspan: int :param sticky: "n", "s", "e", "w" or combinations: if cell is larger on which sides will this widget stick to the cell boundary :type sticky: str
def create_packet(header, data): """Creates an IncomingPacket object from header and data This method is for testing purposes """ packet = IncomingPacket() packet.header = header packet.data = data if len(header) == HeronProtocol.HEADER_SIZE: packet.is_header_read = True if len(data) == packet.get_datasize(): packet.is_complete = True return packet
Creates an IncomingPacket object from header and data This method is for testing purposes
def get(self): """ method to fetch all contents as a list :return: list """ ret_list = [] if hasattr(self, "font"): ret_list.append(self.font) if hasattr(self, "size"): ret_list.append(self.size) if hasattr(self, "text"): ret_list.append(self.text) return ret_list
method to fetch all contents as a list :return: list
def seed_response(self, command, response): # type: (Text, dict) -> MockAdapter """ Sets the response that the adapter will return for the specified command. You can seed multiple responses per command; the adapter will put them into a FIFO queue. When a request comes in, the adapter will pop the corresponding response off of the queue. Example: .. code-block:: python adapter.seed_response('sayHello', {'message': 'Hi!'}) adapter.seed_response('sayHello', {'message': 'Hello!'}) adapter.send_request({'command': 'sayHello'}) # {'message': 'Hi!'} adapter.send_request({'command': 'sayHello'}) # {'message': 'Hello!'} """ if command not in self.responses: self.responses[command] = deque() self.responses[command].append(response) return self
Sets the response that the adapter will return for the specified command. You can seed multiple responses per command; the adapter will put them into a FIFO queue. When a request comes in, the adapter will pop the corresponding response off of the queue. Example: .. code-block:: python adapter.seed_response('sayHello', {'message': 'Hi!'}) adapter.seed_response('sayHello', {'message': 'Hello!'}) adapter.send_request({'command': 'sayHello'}) # {'message': 'Hi!'} adapter.send_request({'command': 'sayHello'}) # {'message': 'Hello!'}
def getEntityType(self, found = None): ''' Method to recover the value of the entity in case it may vary. :param found: The expression to be analysed. :return: The entity type returned will be an s'i3visio.email' for foo@bar.com and an 'i3visio.text' for foo[at]bar[dot]com. ''' # character may be '@' or '.' for character in self.substitutionValues.keys(): for value in self.substitutionValues[character]: if value in found: return "i3visio.text" # If none of the values were found... Returning as usual the 'i3visio.email' string. return self.name
Method to recover the value of the entity in case it may vary. :param found: The expression to be analysed. :return: The entity type returned will be an s'i3visio.email' for foo@bar.com and an 'i3visio.text' for foo[at]bar[dot]com.
def find_log_files(self, sp_key, filecontents=True, filehandles=False): """ Return matches log files of interest. :param sp_key: Search pattern key specified in config :param filehandles: Set to true to return a file handle instead of slurped file contents :return: Yields a dict with filename (fn), root directory (root), cleaned sample name generated from the filename (s_name) and either the file contents or file handle for the current matched file (f). As yield is used, the results can be iterated over without loading all files at once """ # Pick up path filters if specified. # Allows modules to be called multiple times with different sets of files path_filters = getattr(self, 'mod_cust_config', {}).get('path_filters') path_filters_exclude = getattr(self, 'mod_cust_config', {}).get('path_filters_exclude') # Old, depreciated syntax support. Likely to be removed in a future version. if isinstance(sp_key, dict): report.files[self.name] = list() for sf in report.searchfiles: if report.search_file(sp_key, {'fn': sf[0], 'root': sf[1]}): report.files[self.name].append({'fn': sf[0], 'root': sf[1]}) sp_key = self.name logwarn = "Depreciation Warning: {} - Please use new style for find_log_files()".format(self.name) if len(report.files[self.name]) > 0: logger.warn(logwarn) else: logger.debug(logwarn) elif not isinstance(sp_key, str): logger.warn("Did not understand find_log_files() search key") return for f in report.files[sp_key]: # Make a note of the filename so that we can report it if something crashes report.last_found_file = os.path.join(f['root'], f['fn']) # Filter out files based on exclusion patterns if path_filters_exclude and len(path_filters_exclude) > 0: exlusion_hits = (fnmatch.fnmatch(report.last_found_file, pfe) for pfe in path_filters_exclude) if any(exlusion_hits): logger.debug("{} - Skipping '{}' as it matched the path_filters_exclude for '{}'".format(sp_key, f['fn'], self.name)) continue # Filter out files based on inclusion patterns if path_filters and len(path_filters) > 0: inclusion_hits = (fnmatch.fnmatch(report.last_found_file, pf) for pf in path_filters) if not any(inclusion_hits): logger.debug("{} - Skipping '{}' as it didn't match the path_filters for '{}'".format(sp_key, f['fn'], self.name)) continue else: logger.debug("{} - Selecting '{}' as it matched the path_filters for '{}'".format(sp_key, f['fn'], self.name)) # Make a sample name from the filename f['s_name'] = self.clean_s_name(f['fn'], f['root']) if filehandles or filecontents: try: # Custom content module can now handle image files (ftype, encoding) = mimetypes.guess_type(os.path.join(f['root'], f['fn'])) if ftype is not None and ftype.startswith('image'): with io.open (os.path.join(f['root'],f['fn']), "rb") as fh: # always return file handles f['f'] = fh yield f else: # Everything else - should be all text files with io.open (os.path.join(f['root'],f['fn']), "r", encoding='utf-8') as fh: if filehandles: f['f'] = fh yield f elif filecontents: f['f'] = fh.read() yield f except (IOError, OSError, ValueError, UnicodeDecodeError) as e: if config.report_readerrors: logger.debug("Couldn't open filehandle when returning file: {}\n{}".format(f['fn'], e)) f['f'] = None else: yield f
Return matches log files of interest. :param sp_key: Search pattern key specified in config :param filehandles: Set to true to return a file handle instead of slurped file contents :return: Yields a dict with filename (fn), root directory (root), cleaned sample name generated from the filename (s_name) and either the file contents or file handle for the current matched file (f). As yield is used, the results can be iterated over without loading all files at once
def select_ip_version(host, port): """Returns AF_INET4 or AF_INET6 depending on where to connect to.""" # disabled due to problems with current ipv6 implementations # and various operating systems. Probably this code also is # not supposed to work, but I can't come up with any other # ways to implement this. ##try: ## info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, ## socket.SOCK_STREAM, 0, ## socket.AI_PASSIVE) ## if info: ## return info[0][0] ##except socket.gaierror: ## pass if ':' in host and hasattr(socket, 'AF_INET6'): return socket.AF_INET6 return socket.AF_INET
Returns AF_INET4 or AF_INET6 depending on where to connect to.
def length_prefix(length, offset): """Construct the prefix to lists or strings denoting their length. :param length: the length of the item in bytes :param offset: ``0x80`` when encoding raw bytes, ``0xc0`` when encoding a list """ if length < 56: return chr(offset + length) else: length_string = int_to_big_endian(length) return chr(offset + 56 - 1 + len(length_string)) + length_string
Construct the prefix to lists or strings denoting their length. :param length: the length of the item in bytes :param offset: ``0x80`` when encoding raw bytes, ``0xc0`` when encoding a list
def louvain(adjacency_matrix): """ Performs community embedding using the LOUVAIN method. Introduced in: Blondel, V. D., Guillaume, J. L., Lambiotte, R., & Lefebvre, E. (2008). Fast unfolding of communities in large networks. Journal of Statistical Mechanics: Theory and Experiment, 2008(10), P10008. Inputs: - A in R^(nxn): Adjacency matrix of an undirected network represented as a SciPy Sparse COOrdinate matrix. Outputs: - X in R^(nxC_n): The latent space embedding represented as a SciPy Sparse COOrdinate matrix. """ # Convert to networkx undirected graph. adjacency_matrix = nx.from_scipy_sparse_matrix(adjacency_matrix, create_using=nx.Graph()) # Call LOUVAIN algorithm to calculate a hierarchy of communities. tree = community.generate_dendogram(adjacency_matrix, part_init=None) # Embed communities row = list() col = list() append_row = row.append append_col = col.append community_counter = 0 for i in range(len(tree)): partition = community.partition_at_level(tree, i) for n, c in partition.items(): append_row(n) append_col(community_counter + c) community_counter += max(partition.values()) + 1 row = np.array(row) col = np.array(col) data = np.ones(row.size, dtype=np.float64) louvain_features = sparse.coo_matrix((data, (row, col)), shape=(len(partition.keys()), community_counter), dtype=np.float64) return louvain_features
Performs community embedding using the LOUVAIN method. Introduced in: Blondel, V. D., Guillaume, J. L., Lambiotte, R., & Lefebvre, E. (2008). Fast unfolding of communities in large networks. Journal of Statistical Mechanics: Theory and Experiment, 2008(10), P10008. Inputs: - A in R^(nxn): Adjacency matrix of an undirected network represented as a SciPy Sparse COOrdinate matrix. Outputs: - X in R^(nxC_n): The latent space embedding represented as a SciPy Sparse COOrdinate matrix.
def str_if_nested_or_str(s): """Turn input into a native string if possible.""" if isinstance(s, ALL_STRING_TYPES): return str(s) if isinstance(s, (list, tuple)): return type(s)(map(str_if_nested_or_str, s)) if isinstance(s, (dict, )): return stringify_dict_contents(s) return s
Turn input into a native string if possible.
def quantile_normalize(matrix, inplace=False, target=None): """Quantile normalization, allowing for missing values (NaN). In case of nan values, this implementation will calculate evenly distributed quantiles and fill in the missing data with those values. Quantile normalization is then performed on the filled-in matrix, and the nan values are restored afterwards. Parameters ---------- matrix: `ExpMatrix` The expression matrix (rows = genes, columns = samples). inplace: bool Whether or not to perform the operation in-place. [False] target: `numpy.ndarray` Target distribution to use. needs to be a vector whose first dimension matches that of the expression matrix. If ``None``, the target distribution is calculated based on the matrix itself. [None] Returns ------- numpy.ndarray (ndim = 2) The normalized matrix. """ assert isinstance(matrix, ExpMatrix) assert isinstance(inplace, bool) if target is not None: assert isinstance(target, np.ndarray) and \ np.issubdtype(target.dtype, np.float) if not inplace: # make a copy of the original data matrix = matrix.copy() X = matrix.X _, n = X.shape nan = [] # fill in missing values with evenly spaced quantiles for j in range(n): nan.append(np.nonzero(np.isnan(X[:, j]))[0]) if nan[j].size > 0: q = np.arange(1, nan[j].size + 1, dtype=np.float64) / \ (nan[j].size + 1.0) fill = np.nanpercentile(X[:, j], 100 * q) X[nan[j], j] = fill # generate sorting indices A = np.argsort(X, axis=0, kind='mergesort') # mergesort is stable # reorder matrix for j in range(n): matrix.iloc[:, j] = matrix.X[A[:, j], j] # determine target distribution if target is None: # No target distribution is specified, calculate one based on the # expression matrix. target = np.mean(matrix.X, axis=1) else: # Use specified target distribution (after sorting). target = np.sort(target) # generate indices to reverse sorting A = np.argsort(A, axis=0, kind='mergesort') # mergesort is stable # quantile-normalize for j in range(n): matrix.iloc[:, j] = target[A[:, j]] # set missing values to NaN again for j in range(n): if nan[j].size > 0: matrix.iloc[nan[j], j] = np.nan return matrix
Quantile normalization, allowing for missing values (NaN). In case of nan values, this implementation will calculate evenly distributed quantiles and fill in the missing data with those values. Quantile normalization is then performed on the filled-in matrix, and the nan values are restored afterwards. Parameters ---------- matrix: `ExpMatrix` The expression matrix (rows = genes, columns = samples). inplace: bool Whether or not to perform the operation in-place. [False] target: `numpy.ndarray` Target distribution to use. needs to be a vector whose first dimension matches that of the expression matrix. If ``None``, the target distribution is calculated based on the matrix itself. [None] Returns ------- numpy.ndarray (ndim = 2) The normalized matrix.
def on_message(self, message): """Process a message received from remote.""" if self.ws.closed: return None try: safe_call(self.logger.debug, '< %s %r', self, message) # process individual messages for data in self.ddp_frames_from_message(message): self.process_ddp(data) # emit request_finished signal to close DB connections signals.request_finished.send(sender=self.__class__) except geventwebsocket.WebSocketError: self.ws.close()
Process a message received from remote.
def validate(self): """Ensure that the CoerceType block is valid.""" if not (isinstance(self.target_class, set) and all(isinstance(x, six.string_types) for x in self.target_class)): raise TypeError(u'Expected set of string target_class, got: {} {}'.format( type(self.target_class).__name__, self.target_class)) for cls in self.target_class: validate_safe_string(cls)
Ensure that the CoerceType block is valid.
def rm_regions(a, b, a_start_ind, a_stop_ind): '''Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has occured Args ---- a: ndarray Boolean array with regions of contiguous `True` values b: ndarray Boolean array with regions of contiguous `True` values a_start_ind: ndarray indices of start of `a` regions a_stop_ind: ndarray indices of stop of `a` regions Returns ------- a: ndarray Boolean array with regions for which began before a complimentary region in `b` have occured ''' import numpy for i in range(len(a_stop_ind)): next_a_start = numpy.argmax(a[a_stop_ind[i]:]) next_b_start = numpy.argmax(b[a_stop_ind[i]:]) if next_b_start > next_a_start: a[a_start_ind[i]:a_stop_ind[i]] = False return a
Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has occured Args ---- a: ndarray Boolean array with regions of contiguous `True` values b: ndarray Boolean array with regions of contiguous `True` values a_start_ind: ndarray indices of start of `a` regions a_stop_ind: ndarray indices of stop of `a` regions Returns ------- a: ndarray Boolean array with regions for which began before a complimentary region in `b` have occured
def _nextNonSpaceColumn(block, column): """Returns the column with a non-whitespace characters starting at the given cursor position and searching forwards. """ textAfter = block.text()[column:] if textAfter.strip(): spaceLen = len(textAfter) - len(textAfter.lstrip()) return column + spaceLen else: return -1
Returns the column with a non-whitespace characters starting at the given cursor position and searching forwards.
def cli(env, package_keyname, required): """List the categories of a package. :: # List the categories of Bare Metal servers slcli order category-list BARE_METAL_SERVER # List the required categories for Bare Metal servers slcli order category-list BARE_METAL_SERVER --required """ client = env.client manager = ordering.OrderingManager(client) table = formatting.Table(COLUMNS) categories = manager.list_categories(package_keyname) if required: categories = [cat for cat in categories if cat['isRequired']] for cat in categories: table.add_row([ cat['itemCategory']['name'], cat['itemCategory']['categoryCode'], 'Y' if cat['isRequired'] else 'N' ]) env.fout(table)
List the categories of a package. :: # List the categories of Bare Metal servers slcli order category-list BARE_METAL_SERVER # List the required categories for Bare Metal servers slcli order category-list BARE_METAL_SERVER --required
def ParseFileObject(self, parser_mediator, file_object): """Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. """ display_name = parser_mediator.GetDisplayName() self.ParseFileLNKFile(parser_mediator, file_object, display_name)
Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object.
def _fix_channels(self, op, attrs, inputs): """A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number. """ if op not in [mx.sym.Convolution, mx.sym.Deconvolution, mx.sym.FullyConnected]: return attrs weight_name = self._renames[inputs[1]] if not weight_name in self._params: raise ValueError("Unable to get channels/units attr from onnx graph.") else: wshape = self._params[weight_name].shape assert len(wshape) >= 2, "Weights shape is invalid: {}".format(wshape) if op in [mx.sym.FullyConnected]: attrs['num_hidden'] = wshape[0] else: if op == mx.sym.Convolution: # Weight shape for Conv and FC: (M x C x kH x kW) : M is number of # feature maps/hidden and C is number of channels attrs['num_filter'] = wshape[0] elif op == mx.sym.Deconvolution: # Weight shape for DeConv : (C x M x kH x kW) : M is number of # feature maps/filters and C is number of channels attrs['num_filter'] = wshape[1] return attrs
A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number.
def create_binary_annotation(key, value, annotation_type, host): """ Create a zipkin binary annotation object :param key: name of the annotation, such as 'http.uri' :param value: value of the annotation, such as a URI :param annotation_type: type of annotation, such as AnnotationType.I32 :param host: zipkin endpoint object :returns: zipkin binary annotation object """ return zipkin_core.BinaryAnnotation( key=key, value=value, annotation_type=annotation_type, host=host, )
Create a zipkin binary annotation object :param key: name of the annotation, such as 'http.uri' :param value: value of the annotation, such as a URI :param annotation_type: type of annotation, such as AnnotationType.I32 :param host: zipkin endpoint object :returns: zipkin binary annotation object
def _set_below(self, v, load=False): """ Setter method for below, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert/below (container) If this variable is read-only (config: false) in the source YANG file, then _set_below is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_below() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=below.below, is_container='container', presence=False, yang_name="below", rest_name="below", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Below trigger', u'cli-incomplete-no': None}}, namespace='urn:brocade.com:mgmt:brocade-threshold-monitor', defining_module='brocade-threshold-monitor', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """below must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=below.below, is_container='container', presence=False, yang_name="below", rest_name="below", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Below trigger', u'cli-incomplete-no': None}}, namespace='urn:brocade.com:mgmt:brocade-threshold-monitor', defining_module='brocade-threshold-monitor', yang_type='container', is_config=True)""", }) self.__below = t if hasattr(self, '_set'): self._set()
Setter method for below, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert/below (container) If this variable is read-only (config: false) in the source YANG file, then _set_below is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_below() directly.
def print_usage(self, file=None): """ Outputs usage information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout. """ optparse.OptionParser.print_usage(self, file) file.flush()
Outputs usage information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout.
def _compute_delta_beta(self, X, T, E, weights, index=None): """ approximate change in betas as a result of excluding ith row. Good for finding outliers / specific subjects that influence the model disproportionately. Good advice: don't drop these outliers, model them. """ score_residuals = self._compute_score(X, T, E, weights, index=index) d = X.shape[1] scaled_variance_matrix = self.variance_matrix_ * np.tile(self._norm_std.values, (d, 1)).T delta_betas = score_residuals.dot(scaled_variance_matrix) delta_betas.columns = self.hazards_.index return delta_betas
approximate change in betas as a result of excluding ith row. Good for finding outliers / specific subjects that influence the model disproportionately. Good advice: don't drop these outliers, model them.
def check_many(self, domains): """ Check availability for a number of domains. Returns a dictionary mapping the domain names to their statuses as a string ("active"/"free"). """ return dict((item.domain, item.status) for item in self.check_domain_request(domains))
Check availability for a number of domains. Returns a dictionary mapping the domain names to their statuses as a string ("active"/"free").
def analytic_kl_builder(posterior, prior, sample): """A pre-canned builder for the analytic kl divergence.""" del sample return tf.reduce_sum(tfp.distributions.kl_divergence(posterior, prior))
A pre-canned builder for the analytic kl divergence.
def serialize(self): """ Produce YAML version of this catalog. Note that this is not the same as ``.yaml()``, which produces a YAML block referring to this catalog. """ import yaml output = {"metadata": self.metadata, "sources": {}, "name": self.name} for key, entry in self.items(): output["sources"][key] = entry._captured_init_kwargs return yaml.dump(output)
Produce YAML version of this catalog. Note that this is not the same as ``.yaml()``, which produces a YAML block referring to this catalog.
def switch_bucket(self, bucket_key, data_shapes, label_shapes=None): """Switches to a different bucket. This will change ``self.curr_module``. Parameters ---------- bucket_key : str (or any python object) The key of the target bucket. data_shapes : list of (str, tuple) Typically ``data_batch.provide_data``. label_shapes : list of (str, tuple) Typically ``data_batch.provide_label``. """ assert self.binded, 'call bind before switching bucket' if not bucket_key in self._buckets: symbol, data_names, label_names = self._call_sym_gen(bucket_key) module = Module(symbol, data_names, label_names, logger=self.logger, context=self._context, work_load_list=self._work_load_list, fixed_param_names=self._fixed_param_names, state_names=self._state_names, group2ctxs=self._group2ctxs, compression_params=self._compression_params) module.bind(data_shapes, label_shapes, self._curr_module.for_training, self._curr_module.inputs_need_grad, force_rebind=False, shared_module=self._buckets[self._default_bucket_key], grad_req=self._grad_req) if self._monitor is not None: module.install_monitor(self._monitor) self._buckets[bucket_key] = module self._curr_module = self._buckets[bucket_key] self._curr_bucket_key = bucket_key
Switches to a different bucket. This will change ``self.curr_module``. Parameters ---------- bucket_key : str (or any python object) The key of the target bucket. data_shapes : list of (str, tuple) Typically ``data_batch.provide_data``. label_shapes : list of (str, tuple) Typically ``data_batch.provide_label``.
def find_block_end(row, line_list, sentinal, direction=1): """ Searches up and down until it finds the endpoints of a block Rectify with find_paragraph_end in pyvim_funcs """ import re row_ = row line_ = line_list[row_] flag1 = row_ == 0 or row_ == len(line_list) - 1 flag2 = re.match(sentinal, line_) if not (flag1 or flag2): while True: if (row_ == 0 or row_ == len(line_list) - 1): break line_ = line_list[row_] if re.match(sentinal, line_): break row_ += direction return row_
Searches up and down until it finds the endpoints of a block Rectify with find_paragraph_end in pyvim_funcs
def choicebox(message='Pick something.', title='', choices=['program logic error - no choices specified']): """Original doc: Present the user with a list of choices. return the choice that he selects. return None if he cancels the selection selection. """ return psidialogs.choice(message=message, title=title, choices=choices)
Original doc: Present the user with a list of choices. return the choice that he selects. return None if he cancels the selection selection.
def extract_parameters(pil, keys=None): """Extract and return parameter names and values from a pil object Parameters ---------- pil : `Pil` object keys : list List of parameter names, if None, extact all parameters Returns ------- out_dict : dict Dictionary with parameter name, value pairs """ out_dict = {} if keys is None: keys = pil.keys() for key in keys: try: out_dict[key] = pil[key] except ValueError: out_dict[key] = None return out_dict
Extract and return parameter names and values from a pil object Parameters ---------- pil : `Pil` object keys : list List of parameter names, if None, extact all parameters Returns ------- out_dict : dict Dictionary with parameter name, value pairs
def _serialize_to_many(self, key, vals, rlink): """ Make a to_many JSON API compliant :spec: jsonapi.org/format/#document-resource-object-relationships :param key: the string name of the relationship field :param vals: array of dict's containing `rid` & `rtype` keys for the to_many, empty array if no values, & None if the to_manys values are unknown :return: dict as documented in the spec link """ rel = { key: { 'data': [], 'links': { 'related': rlink + '/' + key } } } try: for val in vals: rel[key]['data'].append({ 'id': val['rid'], 'type': val['rtype'], }) except TypeError: del rel[key]['data'] return rel
Make a to_many JSON API compliant :spec: jsonapi.org/format/#document-resource-object-relationships :param key: the string name of the relationship field :param vals: array of dict's containing `rid` & `rtype` keys for the to_many, empty array if no values, & None if the to_manys values are unknown :return: dict as documented in the spec link
def all_terms(self): """Iterate over all of the terms. The self.terms property has only root level terms. This iterator iterates over all terms""" for s_name, s in self.sections.items(): # Yield the section header if s.name != 'Root': yield s # Yield all of the rows for terms in the section for rterm in s: yield rterm for d in rterm.descendents: yield d
Iterate over all of the terms. The self.terms property has only root level terms. This iterator iterates over all terms
def send_last_message(self, msg, connection_id=None): """ Should be used instead of send_message, when you want to close the connection once the message is sent. :param msg: protobuf validator_pb2.Message """ zmq_identity = None if connection_id is not None and self._connections is not None: if connection_id in self._connections: connection_info = self._connections.get(connection_id) if connection_info.connection_type == \ ConnectionType.ZMQ_IDENTITY: zmq_identity = connection_info.connection del self._connections[connection_id] else: LOGGER.debug("Can't send to %s, not in self._connections", connection_id) return self._ready.wait() try: asyncio.run_coroutine_threadsafe( self._send_last_message(zmq_identity, msg), self._event_loop) except RuntimeError: # run_coroutine_threadsafe will throw a RuntimeError if # the eventloop is closed. This occurs on shutdown. pass
Should be used instead of send_message, when you want to close the connection once the message is sent. :param msg: protobuf validator_pb2.Message
def is_element_in_database(element='', database='ENDF_VII'): """will try to find the element in the folder (database) specified Parameters: ========== element: string. Name of the element. Not case sensitive database: string (default is 'ENDF_VII'). Name of folder that has the list of elements Returns: ======= bool: True if element was found in the database False if element could not be found """ if element == '': return False list_entry_from_database = get_list_element_from_database(database=database) if element in list_entry_from_database: return True return False
will try to find the element in the folder (database) specified Parameters: ========== element: string. Name of the element. Not case sensitive database: string (default is 'ENDF_VII'). Name of folder that has the list of elements Returns: ======= bool: True if element was found in the database False if element could not be found
def type_search(self, basetype, symbolstr, origin): """Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbols, e.g. this%sym%sym2%go. :arg origin: an instance of the Module class that started the request. """ symbols = symbolstr.split("%") base, basemod = self.tree_find(basetype, origin, "types") #As long as we keep finding child objects, we can continue #until we run out of symbols in the list i = 1 while isinstance(base, CustomType) and i < len(symbols): #We will look inside the types members and executables if symbols[i] in base.members: #Types can have types inside of them. If the next symbol #is a member, we need to check if it is also a custom type base = base.members[symbols[i]] if base.is_custom: base, basemod = self.tree_find(base.kind, origin, "types") elif symbols[i] in base.executables: base = base.executables[symbols[i]] #We want to keep iterating through until we find a non-type #which is either a non-type member or an executable i += 1 return base
Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbols, e.g. this%sym%sym2%go. :arg origin: an instance of the Module class that started the request.
def _find_glob_matches(in_files, metadata): """Group files that match by globs for merging, rather than by explicit pairs. """ reg_files = copy.deepcopy(in_files) glob_files = [] for glob_search in [x for x in metadata.keys() if "*" in x]: cur = [] for fname in in_files: if fnmatch.fnmatch(fname, "*/%s" % glob_search): cur.append(fname) reg_files.remove(fname) assert cur, "Did not find file matches for %s" % glob_search glob_files.append(cur) return reg_files, glob_files
Group files that match by globs for merging, rather than by explicit pairs.
def is_molecular_function(self, go_term): """ Returns True is go_term has is_a, part_of ancestor of molecular function GO:0003674 """ mf_root = "GO:0003674" if go_term == mf_root: return True ancestors = self.get_isa_closure(go_term) if mf_root in ancestors: return True else: return False
Returns True is go_term has is_a, part_of ancestor of molecular function GO:0003674
def fix_axon_peri_v2(hobj): """Replace reconstructed axon with a stub :param hobj: hoc object """ for i,sec in enumerate(hobj.axon): if i < 2: sec.L = 30 sec.diam = 1 else: sec.L = 1e-6 sec.diam = 1 h.define_shape()
Replace reconstructed axon with a stub :param hobj: hoc object
def _minimal_common_integer(si_0, si_1): """ Calculates the minimal integer that appears in both StridedIntervals. As a wrapper method of _minimal_common_integer_splitted(), this method takes arbitrary StridedIntervals. For more information, please refer to the comment of _minimal_common_integer_splitted(). :param si_0: the first StridedInterval :type si_0: StridedInterval :param si_1: the second StridedInterval :type si_1: StridedInterval :return: the minimal common integer, or None if there is no common integer """ si_0_splitted = si_0._ssplit() si_1_splitted = si_1._ssplit() len_0, len_1 = len(si_0_splitted), len(si_1_splitted) if len_0 == 1 and len_1 == 2: # Swap them so we don't have to handle dual si_0_splitted, si_1_splitted = si_1_splitted, si_0_splitted len_0, len_1 = len_1, len_0 if len_0 == 1 and len_1 == 1: # No splitting was necessary return StridedInterval._minimal_common_integer_splitted(si_0, si_1) if len_0 == 2 and len_1 == 1: int_0 = StridedInterval._minimal_common_integer_splitted(si_0_splitted[0], si_1_splitted[0]) int_1 = StridedInterval._minimal_common_integer_splitted(si_0_splitted[1], si_1_splitted[0]) else: # len_0 == 2 and len_1 == 2 int_0 = StridedInterval._minimal_common_integer_splitted(si_0_splitted[0], si_1_splitted[0]) int_1 = StridedInterval._minimal_common_integer_splitted(si_0_splitted[1], si_1_splitted[1]) if int_0 is None: return int_1 elif int_1 is None: return int_0 else: return int_0
Calculates the minimal integer that appears in both StridedIntervals. As a wrapper method of _minimal_common_integer_splitted(), this method takes arbitrary StridedIntervals. For more information, please refer to the comment of _minimal_common_integer_splitted(). :param si_0: the first StridedInterval :type si_0: StridedInterval :param si_1: the second StridedInterval :type si_1: StridedInterval :return: the minimal common integer, or None if there is no common integer
def _parse_response(response, clazz, is_list=False, resource_name=None): """Parse a Marathon response into an object or list of objects.""" target = response.json()[ resource_name] if resource_name else response.json() if is_list: return [clazz.from_json(resource) for resource in target] else: return clazz.from_json(target)
Parse a Marathon response into an object or list of objects.
def search_for_port(port_glob, req, expected_res): ''' Find the serial port the arm is connected to. ''' # Check that the USB port actually exists, based on the known vendor and # product ID. if usb.core.find(idVendor=0x0403, idProduct=0x6001) is None: return None # Find ports matching the supplied glob. ports = glob.glob(port_glob) if len(ports) == 0: return None for port in ports: with r12_serial_port(port) as ser: if not ser.isOpen(): ser.open() # Write a request out. if sys.version_info[0] == 2: ser.write(str(req).encode('utf-8')) else: ser.write(bytes(req, 'utf-8')) # Wait a short period to allow the connection to generate output. time.sleep(0.1) # Read output from the serial connection check if it's what we want. res = ser.read(ser.in_waiting).decode(OUTPUT_ENCODING) if expected_res in res: return port raise ArmException('ST Robotics connection found, but is not responsive.' + ' Is the arm powered on?') return None
Find the serial port the arm is connected to.
def expand_multirow_data(data): """ Converts multirow cells to a list of lists and informs the number of lines of each row. Returns: tuple: new_data, row_heights """ num_cols = len(data[0]) # number of columns # calculates row heights row_heights = [] for mlrow in data: row_height = 0 for j, cell in enumerate(mlrow): row_height = max(row_height, 1 if not isinstance(cell, (list, tuple)) else len(cell)) row_heights.append(row_height) num_lines = sum(row_heights) # line != row (rows are multiline) # rebuilds table data new_data = [[""]*num_cols for i in range(num_lines)] i0 = 0 for row_height, mlrow in zip(row_heights, data): for j, cell in enumerate(mlrow): if not isinstance(cell, (list, tuple)): cell = [cell] for incr, x in enumerate(cell): new_data[i0+incr][j] = x i0 += row_height return new_data, row_heights
Converts multirow cells to a list of lists and informs the number of lines of each row. Returns: tuple: new_data, row_heights
def get_pltpat(self, plt_ext="svg"): """Return png pattern: {BASE}.png {BASE}_pruned.png {BASE}_upper_pruned.png""" if self.ntplt.desc == "": return ".".join(["{BASE}", plt_ext]) return "".join(["{BASE}_", self.ntplt.desc, ".", plt_ext])
Return png pattern: {BASE}.png {BASE}_pruned.png {BASE}_upper_pruned.png
async def _handle_bad_server_salt(self, message): """ Corrects the currently used server salt to use the right value before enqueuing the rejected message to be re-sent: bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification; """ bad_salt = message.obj self._log.debug('Handling bad salt for message %d', bad_salt.bad_msg_id) self._state.salt = bad_salt.new_server_salt states = self._pop_states(bad_salt.bad_msg_id) self._send_queue.extend(states) self._log.debug('%d message(s) will be resent', len(states))
Corrects the currently used server salt to use the right value before enqueuing the rejected message to be re-sent: bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;
def _split_column_and_labels(self, column_or_label): """Return the specified column and labels of other columns.""" column = None if column_or_label is None else self._get_column(column_or_label) labels = [label for i, label in enumerate(self.labels) if column_or_label not in (i, label)] return column, labels
Return the specified column and labels of other columns.
def status_server(self, port): ''' Starts the progress bar TCP service on the specified port. This service will only be started once per instance, regardless of the number of times this method is invoked. Failure to start the status service is considered non-critical; that is, a warning will be displayed to the user, but normal operation will proceed. ''' if self.status_server_started == False: self.status_server_started = True try: self.status_service = binwalk.core.statuserver.StatusServer(port, self) except Exception as e: binwalk.core.common.warning("Failed to start status server on port %d: %s" % (port, str(e)))
Starts the progress bar TCP service on the specified port. This service will only be started once per instance, regardless of the number of times this method is invoked. Failure to start the status service is considered non-critical; that is, a warning will be displayed to the user, but normal operation will proceed.
def Jacobian_re_im(self, pars): r""" :math:`J` >>> import sip_models.res.cc as cc >>> import numpy as np >>> f = np.logspace(-3, 3, 20) >>> pars = [100, 0.1, 0.04, 0.8] >>> obj = cc.cc(f) >>> J = obj.Jacobian_re_im(pars) """ partials = [] # partials.append(self.dre_dlog10rho0(pars)[:, np.newaxis, :]) partials.append(self.dre_drho0(pars)[:, np.newaxis]) partials.append(self.dre_dm(pars)) # partials.append(self.dre_dlog10tau(pars)) partials.append(self.dre_dtau(pars)) partials.append(self.dre_dc(pars)) # partials.append(self.dim_dlog10rho0(pars)[:, np.newaxis, :]) partials.append(self.dim_drho0(pars)[:, np.newaxis]) partials.append(self.dim_dm(pars)) # partials.append(self.dim_dlog10tau(pars)) partials.append(self.dim_dtau(pars)) partials.append(self.dim_dc(pars)) print('SHAPES') for x in partials: print(x.shape) J = np.concatenate(partials, axis=1) return J
r""" :math:`J` >>> import sip_models.res.cc as cc >>> import numpy as np >>> f = np.logspace(-3, 3, 20) >>> pars = [100, 0.1, 0.04, 0.8] >>> obj = cc.cc(f) >>> J = obj.Jacobian_re_im(pars)
def cmdloop(self): """Start CLI REPL.""" while True: cmdline = input(self.prompt) tokens = shlex.split(cmdline) if not tokens: if self.last_cmd: tokens = self.last_cmd else: print('No previous command.') continue if tokens[0] not in self.commands: print('Invalid command') continue command = self.commands[tokens[0]] self.last_cmd = tokens try: if command(self.state, tokens): break except CmdExit: continue except Exception as e: if e not in self.safe_exceptions: logger.exception('Error!')
Start CLI REPL.
def get_url(self, *paths, **params): """ Returns the URL for this request. :param paths: Additional URL path parts to add to the request :param params: Additional query parameters to add to the request """ path_stack = self._attribute_stack[:] if paths: path_stack.extend(paths) u = self._stack_collapser(path_stack) url = self._url_template % { "domain": self._api_url, "generated_url" : u, } if self._params or params: internal_params = self._params.copy() internal_params.update(params) url += self._generate_params(internal_params) return url
Returns the URL for this request. :param paths: Additional URL path parts to add to the request :param params: Additional query parameters to add to the request
def displayName( self ): """ Return the user friendly name for this node. if the display name \ is not implicitly set, then the words for the object name \ will be used. :return <str> """ if ( not self._displayName ): return projex.text.pretty(self.objectName()) return self._displayName
Return the user friendly name for this node. if the display name \ is not implicitly set, then the words for the object name \ will be used. :return <str>
def get_psf_sky(self, ra, dec): """ Determine the local psf at a given sky location. The psf is returned in degrees. Parameters ---------- ra, dec : float The sky position (degrees). Returns ------- a, b, pa : float The psf semi-major axis, semi-minor axis, and position angle in (degrees). If a psf is defined then it is the psf that is returned, otherwise the image restoring beam is returned. """ # If we don't have a psf map then we just fall back to using the beam # from the fits header (including ZA scaling) if self.data is None: beam = self.wcshelper.get_beam(ra, dec) return beam.a, beam.b, beam.pa x, y = self.sky2pix([ra, dec]) # We leave the interpolation in the hands of whoever is making these images # clamping the x,y coords at the image boundaries just makes sense x = int(np.clip(x, 0, self.data.shape[1] - 1)) y = int(np.clip(y, 0, self.data.shape[2] - 1)) psf_sky = self.data[:, x, y] return psf_sky
Determine the local psf at a given sky location. The psf is returned in degrees. Parameters ---------- ra, dec : float The sky position (degrees). Returns ------- a, b, pa : float The psf semi-major axis, semi-minor axis, and position angle in (degrees). If a psf is defined then it is the psf that is returned, otherwise the image restoring beam is returned.
def Registry(address='https://index.docker.io', **kwargs): """ :return: """ registry = None try: try: registry = V1(address, **kwargs) registry.ping() except RegistryException: registry = V2(address, **kwargs) registry.ping() except OSError: logger.warning( 'Was unable to verify certs for a registry @ {0}. ' 'Will not be able to interact with it for any operations until the certs can be validated.'.format(address) ) return registry
:return:
def import_vmesh(file): """ Imports NURBS volume(s) from volume mesh (vmesh) file(s). :param file: path to a directory containing mesh files or a single mesh file :type file: str :return: list of NURBS volumes :rtype: list :raises GeomdlException: an error occurred reading the file """ imported_elements = [] if os.path.isfile(file): imported_elements.append(exch.import_vol_mesh(file)) elif os.path.isdir(file): files = sorted([os.path.join(file, f) for f in os.listdir(file)]) for f in files: imported_elements.append(exch.import_vol_mesh(f)) else: raise exch.GeomdlException("Input is not a file or a directory") return imported_elements
Imports NURBS volume(s) from volume mesh (vmesh) file(s). :param file: path to a directory containing mesh files or a single mesh file :type file: str :return: list of NURBS volumes :rtype: list :raises GeomdlException: an error occurred reading the file
def write_static_networks(gtfs, output_dir, fmt=None): """ Parameters ---------- gtfs: gtfspy.GTFS output_dir: (str, unicode) a path where to write fmt: None, optional defaulting to "edg" and writing results as ".edg" files If "csv" csv files are produced instead """ if fmt is None: fmt = "edg" single_layer_networks = stop_to_stop_networks_by_type(gtfs) util.makedirs(output_dir) for route_type, net in single_layer_networks.items(): tag = route_types.ROUTE_TYPE_TO_LOWERCASE_TAG[route_type] file_name = os.path.join(output_dir, "network_" + tag + "." + fmt) if len(net.edges()) > 0: _write_stop_to_stop_network_edges(net, file_name, fmt=fmt)
Parameters ---------- gtfs: gtfspy.GTFS output_dir: (str, unicode) a path where to write fmt: None, optional defaulting to "edg" and writing results as ".edg" files If "csv" csv files are produced instead
def get_groups_of_user(config, fas, username): ''' Return the list of (pkgdb) groups to which the user belongs. :arg config: a dict containing the fedmsg config :arg fas: a fedora.client.fas2.AccountSystem object instanciated and loged into FAS. :arg username: the name of a user for which we want to retrieve groups :return: a list of FAS groups to which the user belongs. ''' if not _cache.is_configured: _cache.configure(**config['fmn.rules.cache']) key = cache_key_generator(get_groups_of_user, username) def creator(): if not fas: return [] results = [] for group in fas.person_by_username(username).get('memberships', []): if group['group_type'] == 'pkgdb': results.append(group.name) return results return _cache.get_or_create(key, creator)
Return the list of (pkgdb) groups to which the user belongs. :arg config: a dict containing the fedmsg config :arg fas: a fedora.client.fas2.AccountSystem object instanciated and loged into FAS. :arg username: the name of a user for which we want to retrieve groups :return: a list of FAS groups to which the user belongs.
def check_data(cls, name, dims, is_unstructured): """ A validation method for the data shape The default method does nothing and should be subclassed to validate the results. If the plotter accepts a :class:`InteractiveList`, it should accept a list for name and dims Parameters ---------- name: str or list of str The variable name(s) of the data dims: list of str or list of lists of str The dimension name(s) of the data is_unstructured: bool or list of bool True if the corresponding array is unstructured Returns ------- list of bool or None True, if everything is okay, False in case of a serious error, None if it is intermediate. Each object in this list corresponds to one in the given `name` list of str The message giving more information on the reason. Each object in this list corresponds to one in the given `name`""" if isinstance(name, six.string_types): name = [name] dims = [dims] is_unstructured = [is_unstructured] N = len(name) if len(dims) != N or len(is_unstructured) != N: return [False] * N, [ 'Number of provided names (%i) and dimensions ' '(%i) or unstructured information (%i) are not the same' % ( N, len(dims), len(is_unstructured))] * N return [True] * N, [''] * N
A validation method for the data shape The default method does nothing and should be subclassed to validate the results. If the plotter accepts a :class:`InteractiveList`, it should accept a list for name and dims Parameters ---------- name: str or list of str The variable name(s) of the data dims: list of str or list of lists of str The dimension name(s) of the data is_unstructured: bool or list of bool True if the corresponding array is unstructured Returns ------- list of bool or None True, if everything is okay, False in case of a serious error, None if it is intermediate. Each object in this list corresponds to one in the given `name` list of str The message giving more information on the reason. Each object in this list corresponds to one in the given `name`
def _inject_format_spec(self, value, format_spec): """ value: '{x}', format_spec: 'f' -> '{x:f}' """ t = type(value) return value[:-1] + t(u':') + format_spec + t(u'}')
value: '{x}', format_spec: 'f' -> '{x:f}'
def cminus(a, b): ''' cminus(a, b) returns the difference a - b as a numpy array object. Like numpy's subtract function or a - b syntax, minus will thread over the latest dimension possible. ''' # adding/subtracting a constant to/from a sparse array is an error... spa = sps.issparse(a) spb = sps.issparse(b) if not spa: a = np.asarray(a) if not spb: b = np.asarray(b) if spa: b = np.reshape(b, (1,1)) if len(np.shape(b)) == 0 else b elif spb: a = np.reshape(a, (1,1)) if len(np.shape(a)) == 0 else a return a - b
cminus(a, b) returns the difference a - b as a numpy array object. Like numpy's subtract function or a - b syntax, minus will thread over the latest dimension possible.
def fetch(self): """ Fetch a AvailableAddOnExtensionInstance :returns: Fetched AvailableAddOnExtensionInstance :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, params=params, ) return AvailableAddOnExtensionInstance( self._version, payload, available_add_on_sid=self._solution['available_add_on_sid'], sid=self._solution['sid'], )
Fetch a AvailableAddOnExtensionInstance :returns: Fetched AvailableAddOnExtensionInstance :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance
def dump_guest_stack(self, cpu_id): """Produce a simple stack dump using the current guest state. This feature is not implemented in the 4.0.0 release but may show up in a dot release. in cpu_id of type int The identifier of the Virtual CPU. return stack of type str String containing the formatted stack dump. """ if not isinstance(cpu_id, baseinteger): raise TypeError("cpu_id can only be an instance of type baseinteger") stack = self._call("dumpGuestStack", in_p=[cpu_id]) return stack
Produce a simple stack dump using the current guest state. This feature is not implemented in the 4.0.0 release but may show up in a dot release. in cpu_id of type int The identifier of the Virtual CPU. return stack of type str String containing the formatted stack dump.
def open(self): """Open a comm to the frontend if one isn't already open.""" if self.comm is None: state, buffer_paths, buffers = _remove_buffers(self.get_state()) args = dict(target_name='jupyter.widget', data={'state': state, 'buffer_paths': buffer_paths}, buffers=buffers, metadata={'version': __protocol_version__} ) if self._model_id is not None: args['comm_id'] = self._model_id self.comm = Comm(**args)
Open a comm to the frontend if one isn't already open.
def _update_new_ordered_reqs_count(self): """ Checks if any requests have been ordered since last performance check and updates the performance check data store if needed. :return: True if new ordered requests, False otherwise """ last_num_ordered = self._last_performance_check_data.get('num_ordered') num_ordered = sum(num for num, _ in self.monitor.numOrderedRequests.values()) if num_ordered != last_num_ordered: self._last_performance_check_data['num_ordered'] = num_ordered return True else: return False
Checks if any requests have been ordered since last performance check and updates the performance check data store if needed. :return: True if new ordered requests, False otherwise
def fulfill(self, method, *args, **kwargs): """ Fulfill an HTTP request to Keen's API. """ return getattr(self.session, method)(*args, **kwargs)
Fulfill an HTTP request to Keen's API.
def _copy_artifact(self, tgt, jar, version, typename, suffix='', extension='jar', artifact_ext='', override_name=None): """Copy the products for a target into the artifact path for the jar/version""" genmap = self.context.products.get(typename) product_mapping = genmap.get(tgt) if product_mapping is None: raise ValueError("No product mapping in {} for {}. " "You may need to run some other task first".format(typename, tgt)) for basedir, jars in product_mapping.items(): for artifact in jars: path = self.artifact_path(jar, version, name=override_name, suffix=suffix, extension=extension, artifact_ext=artifact_ext) safe_mkdir(os.path.dirname(path)) shutil.copy(os.path.join(basedir, artifact), path)
Copy the products for a target into the artifact path for the jar/version
def initialize(self): """Initialize croniter and related times""" if self.croniter is None: self.time = time.time() self.datetime = datetime.now(self.tz) self.loop_time = self.loop.time() self.croniter = croniter(self.spec, start_time=self.datetime)
Initialize croniter and related times
def _get_struct_gradientbevelfilter(self): """Get the values for the GRADIENTBEVELFILTER record.""" obj = _make_object("GradientBevelFilter") obj.NumColors = num_colors = unpack_ui8(self._src) obj.GradientColors = [self._get_struct_rgba() for _ in range(num_colors)] obj.GradientRatio = [unpack_ui8(self._src) for _ in range(num_colors)] obj.BlurX = unpack_fixed16(self._src) obj.BlurY = unpack_fixed16(self._src) obj.Angle = unpack_fixed16(self._src) obj.Distance = unpack_fixed16(self._src) obj.Strength = unpack_fixed8(self._src) bc = BitConsumer(self._src) obj.InnerShadow = bc.u_get(1) obj.Knockout = bc.u_get(1) obj.CompositeSource = bc.u_get(1) obj.OnTop = bc.u_get(1) obj.Passes = bc.u_get(4) return obj
Get the values for the GRADIENTBEVELFILTER record.
def _width(self): """For ``self.width``.""" layout = self._instruction.get(GRID_LAYOUT) if layout is not None: width = layout.get(WIDTH) if width is not None: return width return self._instruction.number_of_consumed_meshes
For ``self.width``.
def chained_get(container, path, default=None): """Helper function to perform a series of .get() methods on a dictionary and return a default object type in the end. Parameters ---------- container : dict The dictionary on which the .get() methods should be performed. path : list or tuple The list of keys that should be searched for. default : any (optional, default=None) The object type that should be returned if the search yields no result. """ for key in path: try: container = container[key] except (AttributeError, KeyError, TypeError): return default return container
Helper function to perform a series of .get() methods on a dictionary and return a default object type in the end. Parameters ---------- container : dict The dictionary on which the .get() methods should be performed. path : list or tuple The list of keys that should be searched for. default : any (optional, default=None) The object type that should be returned if the search yields no result.
def Barati_high(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_. .. math:: C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right] - 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4) -2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9.9867\}/Re) +0.1357\exp(-[(Re/1620)^2 + 10370]/Re) - 8.5\times 10^{-3}\{2\ln[\tanh(\tanh(Re))]/\ln(10) - 2825.7162\}/Re + 2.4795 Parameters ---------- Re : float Reynolds number of the sphere, [-] Returns ------- Cd : float Drag coefficient [-] Notes ----- Range is Re <= 1E6 This model is the wider-range model the authors developed. At sufficiently low diameters or Re values, drag is no longer a phenomena. Examples -------- Maching example in [1]_, in a table of calculated values. >>> Barati_high(200.) 0.7730544082789523 References ---------- .. [1] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz Ahmadi. "Development of Empirical Models with High Accuracy for Estimation of Drag Coefficient of Flow around a Smooth Sphere: An Evolutionary Approach." Powder Technology 257 (May 2014): 11-19. doi:10.1016/j.powtec.2014.02.045. ''' Cd = (8E-6*((Re/6530.)**2 + tanh(Re) - 8*log(Re)/log(10.)) - 0.4119*exp(-2.08E43/(Re+Re**2)**4) - 2.1344*exp(-((log(Re**2 + 10.7563)/log(10))**2 + 9.9867)/Re) + 0.1357*exp(-((Re/1620.)**2 + 10370.)/Re) - 8.5E-3*(2*log(tanh(tanh(Re)))/log(10) - 2825.7162)/Re + 2.4795) return Cd
r'''Calculates drag coefficient of a smooth sphere using the method in [1]_. .. math:: C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right] - 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4) -2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9.9867\}/Re) +0.1357\exp(-[(Re/1620)^2 + 10370]/Re) - 8.5\times 10^{-3}\{2\ln[\tanh(\tanh(Re))]/\ln(10) - 2825.7162\}/Re + 2.4795 Parameters ---------- Re : float Reynolds number of the sphere, [-] Returns ------- Cd : float Drag coefficient [-] Notes ----- Range is Re <= 1E6 This model is the wider-range model the authors developed. At sufficiently low diameters or Re values, drag is no longer a phenomena. Examples -------- Maching example in [1]_, in a table of calculated values. >>> Barati_high(200.) 0.7730544082789523 References ---------- .. [1] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz Ahmadi. "Development of Empirical Models with High Accuracy for Estimation of Drag Coefficient of Flow around a Smooth Sphere: An Evolutionary Approach." Powder Technology 257 (May 2014): 11-19. doi:10.1016/j.powtec.2014.02.045.
def open_data(self, url, data=None): """Use "data" URL.""" if not isinstance(url, str): raise URLError('data error: proxy support for data protocol currently not implemented') # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value try: [type, data] = url.split(',', 1) except ValueError: raise IOError('data error', 'bad data URL') if not type: type = 'text/plain;charset=US-ASCII' semi = type.rfind(';') if semi >= 0 and '=' not in type[semi:]: encoding = type[semi+1:] type = type[:semi] else: encoding = '' msg = [] msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': # XXX is this encoding/decoding ok? data = base64.decodebytes(data.encode('ascii')).decode('latin-1') else: data = unquote(data) msg.append('Content-Length: %d' % len(data)) msg.append('') msg.append(data) msg = '\n'.join(msg) headers = email.message_from_string(msg) f = io.StringIO(msg) #f.fileno = None # needed for addinfourl return addinfourl(f, headers, url)
Use "data" URL.
def _insert_vars(self, path: str, data: dict) -> str: """Inserts variables into the ESI URL path. Args: path: raw ESI URL path data: data to insert into the URL Returns: path with variables filled """ data = data.copy() while True: match = re.search(self.VAR_REPLACE_REGEX, path) if not match: return path replace_from = match.group(0) replace_with = str(data.get(match.group(1))) path = path.replace(replace_from, replace_with)
Inserts variables into the ESI URL path. Args: path: raw ESI URL path data: data to insert into the URL Returns: path with variables filled
def independent_get_coefficients(coef, rhouv, s, i, j, k, u, v, unfolding, matrix_form): r"""Get the indices mu, nu, and term coefficients for linear terms. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_matrix(Ne)[1, 1] >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1) >>> unfolding = Unfolding(Ne, real=True, normalized=True) >>> independent_get_coefficients(coef, rhouv, s, i, j, k, u, v, ... unfolding, False) [[1, None, -2.00000000000000, False, False]] """ if matrix_form: coef = -coef Mu = unfolding.Mu mu = Mu(s, i, j) rhouv_isconjugated = False if s == 1: coef_list = [[mu, None, -im(coef), matrix_form, rhouv_isconjugated]] elif s == -1: coef_list = [[mu, None, re(coef), matrix_form, rhouv_isconjugated]] else: coef_list = [[mu, None, coef, matrix_form, rhouv_isconjugated]] return coef_list
r"""Get the indices mu, nu, and term coefficients for linear terms. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_matrix(Ne)[1, 1] >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1) >>> unfolding = Unfolding(Ne, real=True, normalized=True) >>> independent_get_coefficients(coef, rhouv, s, i, j, k, u, v, ... unfolding, False) [[1, None, -2.00000000000000, False, False]]
def summary(self): """ A succinct summary of the Launcher configuration. Unlike the repr, a summary does not have to be complete but must supply key information relevant to the user. """ print("Type: %s" % self.__class__.__name__) print("Batch Name: %r" % self.batch_name) if self.tag: print("Tag: %s" % self.tag) print("Root directory: %r" % self.get_root_directory()) print("Maximum concurrency: %s" % self.max_concurrency) if self.description: print("Description: %s" % self.description)
A succinct summary of the Launcher configuration. Unlike the repr, a summary does not have to be complete but must supply key information relevant to the user.
def get_label_map(opts): ''' Find volume labels from filesystem and return in dict format. ''' result = {} try: # get labels from filesystem for entry in os.scandir(diskdir): if entry.name.startswith('.'): continue if islink(entry.path): target = os.readlink(entry.path) else: target = entry.path result[target] = entry.name if opts.debug: print('\n\nlabel_map:', result) except FileNotFoundError: pass return result
Find volume labels from filesystem and return in dict format.
def set_action_name(self, name): """ Set the name of the top group, if present. """ if self._open and name is not None: self._open[-1].name = name self.notify()
Set the name of the top group, if present.
def hook_up(self, router: UrlDispatcher): """ Dynamically hooks the right webhook paths """ router.add_get(self.webhook_path, self.check_hook) router.add_post(self.webhook_path, self.receive_events)
Dynamically hooks the right webhook paths
def run(cli_args): """ Split the functionality into 2 methods. One for parsing the cli and one that runs the application. """ from .core import Core c = Core( source_file=cli_args["--data-file"], schema_files=cli_args["--schema-file"], extensions=cli_args['--extension'], strict_rule_validation=cli_args['--strict-rule-validation'], fix_ruby_style_regex=cli_args['--fix-ruby-style-regex'], allow_assertions=cli_args['--allow-assertions'], file_encoding=cli_args['--encoding'], ) c.validate() return c
Split the functionality into 2 methods. One for parsing the cli and one that runs the application.
def _run_morfologik(self, words): """ Runs morfologik java jar and assumes that input and output is UTF-8 encoded. """ p = subprocess.Popen( ['java', '-jar', self.jar_path, 'plstem', '-ie', 'UTF-8', '-oe', 'UTF-8'], bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = p.communicate(input=bytes("\n".join(words), "utf-8")) return decode(out, 'utf-8')
Runs morfologik java jar and assumes that input and output is UTF-8 encoded.
def get_events(self): """Get events from the cloud node.""" to_send = {'limit': 50} response = self._send_data('POST', 'admin', 'get-events', to_send) output = {'message': ""} for event in response['events']: desc = "Source IP: {ip}\n" desc += "Datetime: {time}\n" desc += "Indicator: {match}\n" desc += "Method: {method}\n" desc += "URL: {url}\n" desc += "Request Type: {type}\n" desc += "User-Agent: {userAgent}\n" desc += "Contact: {contact}\n" desc += "\n" output['message'] += desc.format(**event) return output
Get events from the cloud node.