code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def walk_egg(egg_dir): """Walk an unpacked egg's contents, skipping the metadata directory""" walker = os.walk(egg_dir) base,dirs,files = walker.next() if 'EGG-INFO' in dirs: dirs.remove('EGG-INFO') yield base,dirs,files for bdf in walker: yield bdf
Walk an unpacked egg's contents, skipping the metadata directory
def log(self, uuid=None, organization=None, from_date=None, to_date=None): """"List enrollment information available in the registry. Method that returns a list of enrollments. If <uuid> parameter is set, it will return the enrollments related to that unique identity; if <organization> ...
List enrollment information available in the registry. Method that returns a list of enrollments. If <uuid> parameter is set, it will return the enrollments related to that unique identity; if <organization> parameter is given, it will return the enrollments related to that organization...
def if_has_delegate(delegate): """Wrap a delegated instance attribute function. Creates a decorator for methods that are delegated in the presence of a results wrapper. This enables duck-typing by ``hasattr`` returning True according to the sub-estimator. This function was adapted from scikit-lear...
Wrap a delegated instance attribute function. Creates a decorator for methods that are delegated in the presence of a results wrapper. This enables duck-typing by ``hasattr`` returning True according to the sub-estimator. This function was adapted from scikit-learn, which defines ``if_delegate_has...
def ping(self): """ Notify the queue that this task is still active. """ if self.finished is not None: raise AlreadyFinished() with self._db_conn() as conn: success = conn.query(''' UPDATE %s SET last_contact=%%(now)s, ...
Notify the queue that this task is still active.
def isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0): """ Python 3.4 does not have math.isclose, so we need to steal it and add it here. """ try: return math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol) except AttributeError: # Running on older version of python, fall back to hand-rol...
Python 3.4 does not have math.isclose, so we need to steal it and add it here.
def run_foreach_or_conditional(self, context): """Run the foreach sequence or the conditional evaluation. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate. """ logger.debug("starting") # friendly reminder [] list obj...
Run the foreach sequence or the conditional evaluation. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
def toggle_item(self, item, test_func, field_name=None): """ Toggles the section based on test_func. test_func takes an item and returns a boolean. If it returns True, the item will be added to the given section. It will be removed from the section otherwise. Intended f...
Toggles the section based on test_func. test_func takes an item and returns a boolean. If it returns True, the item will be added to the given section. It will be removed from the section otherwise. Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL. Behavior ...
def get_beam(header): """ Create a :class:`AegeanTools.fits_image.Beam` object from a fits header. BPA may be missing but will be assumed to be zero. if BMAJ or BMIN are missing then return None instead of a beam object. Parameters ---------- header : HDUHeader The fits header. ...
Create a :class:`AegeanTools.fits_image.Beam` object from a fits header. BPA may be missing but will be assumed to be zero. if BMAJ or BMIN are missing then return None instead of a beam object. Parameters ---------- header : HDUHeader The fits header. Returns ------- beam : ...
def _elect_source_replication_group( self, over_replicated_rgs, partition, ): """Decide source replication-group based as group with highest replica count. """ return max( over_replicated_rgs, key=lambda rg: rg.count_replica...
Decide source replication-group based as group with highest replica count.
def _remove_qs(self, url): ''' Removes a query string from a URL before signing. :param url: The URL to strip. :type url: str ''' scheme, netloc, path, query, fragment = urlsplit(url) return urlunsplit((scheme, netloc, path, '', fragment))
Removes a query string from a URL before signing. :param url: The URL to strip. :type url: str
def config(self, config): """Set config values from config dictionary.""" for section, data in config.items(): for variable, value in data.items(): self.set_value(section, variable, value)
Set config values from config dictionary.
def _Load(self,location): """Load all networks associated with the given location. https://www.centurylinkcloud.com/api-docs/v2/#get-network-list#request """ # https://api.ctl.io/v2-experimental/networks/ALIAS/WA1 for network in clc.v2.API.Call('GET','/v2-experimental/networks/%s/%s' % (self.alias,location)...
Load all networks associated with the given location. https://www.centurylinkcloud.com/api-docs/v2/#get-network-list#request
def update_store_credit_by_id(cls, store_credit_id, store_credit, **kwargs): """Update StoreCredit Update attributes of StoreCredit This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_store...
Update StoreCredit Update attributes of StoreCredit This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_store_credit_by_id(store_credit_id, store_credit, async=True) >>> result = thread.get...
def compile_foreign_key(line, context, attributes, primary_key, attr_sql, foreign_key_sql, index_sql): """ :param line: a line from a table definition :param context: namespace containing referenced objects :param attributes: list of attribute names already in the declaration -- to be updated by this fu...
:param line: a line from a table definition :param context: namespace containing referenced objects :param attributes: list of attribute names already in the declaration -- to be updated by this function :param primary_key: None if the current foreign key is made from the dependent section. Otherwise it is ...
def gen_table(self, inner_widths, inner_heights, outer_widths): """Combine everything and yield every line of the entire table with borders. :param iter inner_widths: List of widths (no padding) for each column. :param iter inner_heights: List of heights (no padding) for each row. :para...
Combine everything and yield every line of the entire table with borders. :param iter inner_widths: List of widths (no padding) for each column. :param iter inner_heights: List of heights (no padding) for each row. :param iter outer_widths: List of widths (with padding) for each column. ...
def traceroute(host): ''' Performs a traceroute to a 3rd party host .. versionchanged:: 2015.8.0 Added support for SunOS .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = ...
Performs a traceroute to a 3rd party host .. versionchanged:: 2015.8.0 Added support for SunOS .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org
def create(self, create_missing=None): """Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1381129 <https://bugzilla.redhat.com/show_bug.cgi?id=1381129>`_. """ return type(self)( self._server_config, ...
Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1381129 <https://bugzilla.redhat.com/show_bug.cgi?id=1381129>`_.
def compile(self, session=None): """ Before calling the standard compile function, check to see if the size of the data has changed and add variational parameters appropriately. This is necessary because the shape of the parameters depends on the shape of the data. """ ...
Before calling the standard compile function, check to see if the size of the data has changed and add variational parameters appropriately. This is necessary because the shape of the parameters depends on the shape of the data.
def config_xml_to_dict(contents, result, parse_job=True): """ Convert the contents of a XML config file into the corresponding dictionary :: dictionary[key_1] = value_1 dictionary[key_2] = value_2 ... dictionary[key_n] = value_n :param bytes contents: the XML configurat...
Convert the contents of a XML config file into the corresponding dictionary :: dictionary[key_1] = value_1 dictionary[key_2] = value_2 ... dictionary[key_n] = value_n :param bytes contents: the XML configuration contents :param bool parse_job: if ``True``, parse the job pro...
def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` ...
Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.objec...
def move_editorstack_data(self, start, end): """Reorder editorstack.data so it is synchronized with the tab bar when tabs are moved.""" if start < 0 or end < 0: return else: steps = abs(end - start) direction = (end-start) // steps # +1 for rig...
Reorder editorstack.data so it is synchronized with the tab bar when tabs are moved.
def groups_setPurpose(self, *, channel: str, purpose: str, **kwargs) -> SlackResponse: """Sets the purpose for a private channel. Args: channel (str): The channel id. e.g. 'G1234567890' purpose (str): The new purpose for the channel. e.g. 'My Purpose' """ kwargs....
Sets the purpose for a private channel. Args: channel (str): The channel id. e.g. 'G1234567890' purpose (str): The new purpose for the channel. e.g. 'My Purpose'
def optimize(function, x0, cons=[], ftol=0.2, disp=0, plot=False): """ **Optimization method based on Brent's method** First, a bracket (a b c) is sought that contains the minimum (b value is smaller than both a or c). The bracket is then recursively halfed. Here we apply some modifications to ensure our sug...
**Optimization method based on Brent's method** First, a bracket (a b c) is sought that contains the minimum (b value is smaller than both a or c). The bracket is then recursively halfed. Here we apply some modifications to ensure our suggested point is not too close to either a or c, because that could be pr...
def __process_equalities(self, equalities, momentequalities): """Generate localizing matrices Arguments: equalities -- list of equality constraints equalities -- list of moment equality constraints """ monomial_sets = [] n_rows = 0 le = 0 if equal...
Generate localizing matrices Arguments: equalities -- list of equality constraints equalities -- list of moment equality constraints
def create_topology(self, topologyName, topology): """ crate topology """ if not topology or not topology.IsInitialized(): raise_(StateException("Topology protobuf not init properly", StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()[2]) path = self.get_topology_path(...
crate topology
def _collect_block_lines(self, msgs_store, node, msg_state): """Recursively walk (depth first) AST to collect block level options line numbers. """ for child in node.get_children(): self._collect_block_lines(msgs_store, child, msg_state) first = node.fromlineno ...
Recursively walk (depth first) AST to collect block level options line numbers.
def api_version(self, v): """Set the api_version and associated configurations.""" self._api_version = v if (self._api_version >= '2.0'): self.default_quality = 'default' self.allowed_qualities = ['default', 'color', 'bitonal', 'gray'] else: # versions 1.0 and 1....
Set the api_version and associated configurations.
def unscale_and_snap_to_nearest(x, tune_params, eps): """helper func that snaps a scaled variable to the nearest config""" x_u = [i for i in x] for i, v in enumerate(tune_params.values()): #create an evenly spaced linear space to map [0,1]-interval #to actual values, giving each value an equ...
helper func that snaps a scaled variable to the nearest config
def add_item(self, item, replace = False): """ Add an item to the roster. This will not automatically update the roster on the server. :Parameters: - `item`: the item to add - `replace`: if `True` then existing item will be replaced, otherwise a `V...
Add an item to the roster. This will not automatically update the roster on the server. :Parameters: - `item`: the item to add - `replace`: if `True` then existing item will be replaced, otherwise a `ValueError` will be raised on conflict :Types: ...
def get_colors(n, cmap='viridis', start=0., stop=1., alpha=1., return_hex=False): """ Return n-length list of RGBa colors from the passed colormap name and alpha. Parameters ---------- n : int number of colors cmap : string name of a colormap start : float where to s...
Return n-length list of RGBa colors from the passed colormap name and alpha. Parameters ---------- n : int number of colors cmap : string name of a colormap start : float where to start in the colorspace stop : float where to end in the colorspace alpha : flo...
def check_known_host(user=None, hostname=None, key=None, fingerprint=None, config=None, port=None, fingerprint_hash_type=None): ''' Check the record in known_hosts file, either by its value or by fingerprint (it's enough to set up either key or fingerprint, you don't need to set up ...
Check the record in known_hosts file, either by its value or by fingerprint (it's enough to set up either key or fingerprint, you don't need to set up both). If provided key or fingerprint doesn't match with stored value, return "update", if no value is found for a given host, return "add", otherwise ...
def send(*args, **kwargs): """ A basic interface around both queue and send_now. This honors a global flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should be queued or not. A per call ``queue`` or ``now`` keyword argument can be used to always override the default global behavio...
A basic interface around both queue and send_now. This honors a global flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should be queued or not. A per call ``queue`` or ``now`` keyword argument can be used to always override the default global behavior.
def get_es_label(obj, def_obj): """ Returns object with label for an object that goes into the elacticsearch 'label' field args: obj: data object to update def_obj: the class instance that has defintion values """ label_flds = LABEL_FIELDS if def_obj.es_defs.get('kds_esLabel...
Returns object with label for an object that goes into the elacticsearch 'label' field args: obj: data object to update def_obj: the class instance that has defintion values
def p_param_def_type(p): """ param_def : ID typedef """ if p[2] is not None: api.check.check_type_is_explicit(p.lineno(1), p[1], p[2]) p[0] = make_param_decl(p[1], p.lineno(1), p[2])
param_def : ID typedef
def save_stream(self, key, binary=False): """ Return a managed file-like object into which the calling code can write arbitrary data. :param key: :return: A managed stream-like object """ s = io.BytesIO() if binary else io.StringIO() yield s self....
Return a managed file-like object into which the calling code can write arbitrary data. :param key: :return: A managed stream-like object
def get_placeholders(self, format_string): """ Parses the format_string and returns a set of placeholders. """ placeholders = set() # Tokenize the format string and process them for token in self.tokens(format_string): if token.group("placeholder"): ...
Parses the format_string and returns a set of placeholders.
def reset(self, value=None): """ Resets the start time of the interval to now or the specified value. """ if value is None: value = time.clock() self.start = value if self.value_on_reset: self.value = self.value_on_reset
Resets the start time of the interval to now or the specified value.
def featurewise_norm(x, mean=None, std=None, epsilon=1e-7): """Normalize every pixels by the same given mean and std, which are usually compute from all examples. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). mean : float Value ...
Normalize every pixels by the same given mean and std, which are usually compute from all examples. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). mean : float Value for subtraction. std : float Value for division. ep...
def _getStrippedValue(value, strip): """Like the strip() string method, except the strip argument describes different behavior: If strip is None, whitespace is stripped. If strip is a string, the characters in the string are stripped. If strip is False, nothing is stripped.""" if strip is Non...
Like the strip() string method, except the strip argument describes different behavior: If strip is None, whitespace is stripped. If strip is a string, the characters in the string are stripped. If strip is False, nothing is stripped.
def clean_helper(B, obj, clean_func): """ Clean object, intercepting and collecting any missing-relation or unique-constraint errors and returning the relevant resource ids/fields. Returns: - tuple: (<dict of non-unique fields>, <dict of missing refs>) """ try: clean_func(obj) ...
Clean object, intercepting and collecting any missing-relation or unique-constraint errors and returning the relevant resource ids/fields. Returns: - tuple: (<dict of non-unique fields>, <dict of missing refs>)
def _generate_event_listener_caller(executables: List[str]) -> LockEventListener: """ TODO :param executables: :return: """ def event_listener_caller(key: str): for executable in executables: try: process = subprocess.Popen([executable, key], stderr=subprocess...
TODO :param executables: :return:
def skip(self, content): """ Get whether to skip this I{content}. Should be skipped when the content is optional and value is either None or an empty list. @param content: Content to skip. @type content: L{Object} @return: True if content is to be skipped. ...
Get whether to skip this I{content}. Should be skipped when the content is optional and value is either None or an empty list. @param content: Content to skip. @type content: L{Object} @return: True if content is to be skipped. @rtype: bool
def log_combinations(n, counts, name="log_combinations"): """Multinomial coefficient. Given `n` and `counts`, where `counts` has last dimension `k`, we compute the multinomial coefficient as: ```n! / sum_i n_i!``` where `i` runs over all `k` classes. Args: n: Floating-point `Tensor` broadcastable wi...
Multinomial coefficient. Given `n` and `counts`, where `counts` has last dimension `k`, we compute the multinomial coefficient as: ```n! / sum_i n_i!``` where `i` runs over all `k` classes. Args: n: Floating-point `Tensor` broadcastable with `counts`. This represents `n` outcomes. counts: Fl...
def report_error(title=None, data={}, caught=None, is_fatal=False): """Format a crash report and send it somewhere relevant. There are two types of crashes: fatal crashes (backend errors) or non-fatal ones (just reporting a glitch, but the api call did not fail)""" # Don't report errors if NO_ERROR_REP...
Format a crash report and send it somewhere relevant. There are two types of crashes: fatal crashes (backend errors) or non-fatal ones (just reporting a glitch, but the api call did not fail)
def get_response_handler(self): """Return the Endpoints defined :attr:`Endpoint.response_handler`. :returns: A instance of the Endpoint specified :class:`ResonseHandler`. :rtype: :class:`ResponseHandler` """ assert self.response_handler is not None, \ 'Please define ...
Return the Endpoints defined :attr:`Endpoint.response_handler`. :returns: A instance of the Endpoint specified :class:`ResonseHandler`. :rtype: :class:`ResponseHandler`
def load_HEP_data( ROOT_filename = "output.root", tree_name = "nominal", maximum_number_of_events = None ): """ Load HEP data and return dataset. """ ROOT_file = open_ROOT_file(ROOT_filename) tree = ROOT_file.Get(tree_name) number_of_e...
Load HEP data and return dataset.
def refresh_ip(self, si, logger, session, vcenter_data_model, resource_model, cancellation_context, app_request_json): """ Refreshes IP address of virtual machine and updates Address property on the resource :param vim.ServiceInstance si: py_vmomi service instance :pa...
Refreshes IP address of virtual machine and updates Address property on the resource :param vim.ServiceInstance si: py_vmomi service instance :param logger: :param vCenterShell.driver.SecureCloudShellApiSession session: cloudshell session :param GenericDeployedAppResourceModel resource_...
def _npy_num2fits(d, table_type='binary', write_bitcols=False): """ d is the full element from the descr For vector,array columns the form is the total counts followed by the code. For array columns with dimension greater than 1, the dim is set to (dim1, dim2, ...) So it is treated lik...
d is the full element from the descr For vector,array columns the form is the total counts followed by the code. For array columns with dimension greater than 1, the dim is set to (dim1, dim2, ...) So it is treated like an extra dimension
def hwstatus_send(self, Vcc, I2Cerr, force_mavlink1=False): ''' Status of key hardware Vcc : board voltage (mV) (uint16_t) I2Cerr : I2C error count (uint8_t) ''' return self.send(se...
Status of key hardware Vcc : board voltage (mV) (uint16_t) I2Cerr : I2C error count (uint8_t)
def delta(x_i, j, s, N): """ delta_i_j_s """ flag = j == EMMMixPLAggregator.c(x_i, s) if flag and s < len(x_i): return 1 elif s == N: found_equal = False for l in range(len(x_i)): if j == EMMMixPLAggregator.c(x_i, l): ...
delta_i_j_s
def setAnimation(self,obj,animation,transition=None,force=False): """ Sets the animation to be used by the object. See :py:meth:`Actor.setAnimation()` for more information. """ self.ensureModelData(obj) data = obj._modeldata # Validity check ...
Sets the animation to be used by the object. See :py:meth:`Actor.setAnimation()` for more information.
def get_detail_view(self, request, object, opts=None): """ Instantiates and returns the view class that will generate the actual context for this plugin. """ view = self.get_view(request, self.view_class, opts) view.object = object return view
Instantiates and returns the view class that will generate the actual context for this plugin.
def coef_(self): """ Coefficients property .. note:: Coefficients are defined only for linear learners Coefficients are only defined when the linear model is chosen as base learner (`booster=gblinear`). It is not defined for other base learner types, such as...
Coefficients property .. note:: Coefficients are defined only for linear learners Coefficients are only defined when the linear model is chosen as base learner (`booster=gblinear`). It is not defined for other base learner types, such as tree learners (`booster=gbtree`). ...
def url_for(self, endpoint, explicit=False, **items): '''Returns a valid XBMC plugin URL for the given endpoint name. endpoint can be the literal name of a function, or it can correspond to the name keyword arguments passed to the route decorator. Currently, view names must be u...
Returns a valid XBMC plugin URL for the given endpoint name. endpoint can be the literal name of a function, or it can correspond to the name keyword arguments passed to the route decorator. Currently, view names must be unique across all plugins and modules. There are not names...
def matchToString(dnaMatch, read1, read2, matchAmbiguous=True, indent='', offsets=None): """ Format a DNA match as a string. @param dnaMatch: A C{dict} returned by C{compareDNAReads}. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read}...
Format a DNA match as a string. @param dnaMatch: A C{dict} returned by C{compareDNAReads}. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of one of its subclasses. @param matchAmbiguous: If C{True}, ambiguous nucleotides that ar...
def configure(self, component, all_dependencies): ''' Ensure all config-time files have been generated. Return a dictionary of generated items. ''' r = {} builddir = self.buildroot # only dependencies which are actually valid can contribute to the # config d...
Ensure all config-time files have been generated. Return a dictionary of generated items.
def sort_by_list_order(sortlist, reflist, reverse=False, fltr=False, slemap=None): """ Sort a list according to the order of entries in a reference list. Parameters ---------- sortlist : list List to be sorted reflist : list Reference list defining sorting ord...
Sort a list according to the order of entries in a reference list. Parameters ---------- sortlist : list List to be sorted reflist : list Reference list defining sorting order reverse : bool, optional (default False) Flag indicating whether to sort in reverse order fltr : bool...
def load_modules(self, data=None, proxy=None): ''' Load up the modules for remote compilation via ssh ''' self.functions = self.wrapper self.utils = salt.loader.utils(self.opts) self.serializers = salt.loader.serializers(self.opts) locals_ = salt.loader.minion_mod...
Load up the modules for remote compilation via ssh
def remove_instance(self): """ Remove the instance from the related fields (delete the field if it's a simple one, or remove the instance from the field if it's a set/list/ sorted_set) """ with fields.FieldLock(self.related_field): related_pks = self() ...
Remove the instance from the related fields (delete the field if it's a simple one, or remove the instance from the field if it's a set/list/ sorted_set)
def artifacts(self): """ Property for accessing :class:`ArtifactManager` instance, which is used to manage artifacts. :rtype: yagocd.resources.artifact.ArtifactManager """ if self._artifact_manager is None: self._artifact_manager = ArtifactManager(session=self._sessi...
Property for accessing :class:`ArtifactManager` instance, which is used to manage artifacts. :rtype: yagocd.resources.artifact.ArtifactManager
def update_points(self): """ 椭圆的近似图形:72边形 """ n = max(8, min(72, int(2*sqrt(self.r_x+self.r_y)))) d = pi * 2 / n x, y, r_x, r_y = self.x, self.y, self.r_x, self.r_y ps = [] for i in range(n): ps += [(x + r_x * sin(d * i)), (y + r_y * cos(d * i))] self...
椭圆的近似图形:72边形
def _raise_if_null(self, other): """ :raises ValueError: if either self or other is a null Interval """ if self.is_null(): raise ValueError("Cannot compare null Intervals!") if hasattr(other, 'is_null') and other.is_null(): raise ValueError("Cannot compare...
:raises ValueError: if either self or other is a null Interval
def populate_initial_services(): """ Populate a fresh installed Hypermap instances with basic services. """ services_list = ( ( 'Harvard WorldMap', 'Harvard WorldMap open source web geospatial platform', 'Hypermap:WorldMap', 'http://worldmap.harvar...
Populate a fresh installed Hypermap instances with basic services.
def _request(self, req_type, url, **kwargs): """ Make a request via the `requests` module. If the result has an HTTP error status, convert that to a Python exception. """ logger.debug('%s %s' % (req_type, url)) result = self.session.request(req_type, url, **kwargs) ...
Make a request via the `requests` module. If the result has an HTTP error status, convert that to a Python exception.
def auto_no_thousands(self): """Like self.auto but calculates the next unit if >999.99.""" if self._value >= 1000000000000: return self.TiB, 'TiB' if self._value >= 1000000000: return self.GiB, 'GiB' if self._value >= 1000000: return self.MiB, 'MiB' ...
Like self.auto but calculates the next unit if >999.99.
def activate(self, tourfile=None, minsize=10000, backuptour=True): """ Select contigs in the current partition. This is the setup phase of the algorithm, and supports two modes: - "de novo": This is useful at the start of a new run where no tours available. We select the stron...
Select contigs in the current partition. This is the setup phase of the algorithm, and supports two modes: - "de novo": This is useful at the start of a new run where no tours available. We select the strong contigs that have significant number of links to other contigs in the parti...
def transformer_clean(): """No dropout, label smoothing, max_length.""" hparams = transformer_base_v2() hparams.label_smoothing = 0.0 hparams.layer_prepostprocess_dropout = 0.0 hparams.attention_dropout = 0.0 hparams.relu_dropout = 0.0 hparams.max_length = 0 return hparams
No dropout, label smoothing, max_length.
def image_bytes(b, filename=None, inline=1, width='auto', height='auto', preserve_aspect_ratio=None): """ Return a bytes string that displays image given by bytes b in the terminal If filename=None, the filename defaults to "Unnamed file" width and height are strings, following the format ...
Return a bytes string that displays image given by bytes b in the terminal If filename=None, the filename defaults to "Unnamed file" width and height are strings, following the format N: N character cells. Npx: N pixels. N%: N percent of the session's width or height. 'auto...
def decrease_user_property(self, user_id, property_name, value=0, headers=None, endpoint_url=None): """ Decrease a user's property by a value. :param str user_id: identified user's ID :param str property_name: user property name to increase :param number value: amount by which t...
Decrease a user's property by a value. :param str user_id: identified user's ID :param str property_name: user property name to increase :param number value: amount by which to decrease the property :param dict headers: custom request headers (if isn't set default values are used) ...
def to_dict(self, properties=None): """Return a dictionary containing Compound data. Optionally specify a list of the desired properties. synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is because they each require an extra request. ...
Return a dictionary containing Compound data. Optionally specify a list of the desired properties. synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is because they each require an extra request.
def to_n_ref(self, fill=0, dtype='i1'): """Transform each genotype call into the number of reference alleles. Parameters ---------- fill : int, optional Use this value to represent missing calls. dtype : dtype, optional Output dtype. Retu...
Transform each genotype call into the number of reference alleles. Parameters ---------- fill : int, optional Use this value to represent missing calls. dtype : dtype, optional Output dtype. Returns ------- out : ndarray, int8, sh...
def remove_targets(self, type, kept=None): '''Remove targets of certain type''' if kept is None: kept = [ i for i, x in enumerate(self._targets) if not isinstance(x, type) ] if len(kept) == len(self._targets): return self ...
Remove targets of certain type
def tile_to_path(self, tile): '''return full path to a tile''' return os.path.join(self.cache_path, self.service, tile.path())
return full path to a tile
def create_poll(title, options, multi=True, permissive=True, captcha=False, dupcheck='normal'): """ Create a strawpoll. Example: new_poll = strawpy.create_poll('Is Python the best?', ['Yes', 'No']) :param title: :param options: :param multi: :param permissive: :param captcha: ...
Create a strawpoll. Example: new_poll = strawpy.create_poll('Is Python the best?', ['Yes', 'No']) :param title: :param options: :param multi: :param permissive: :param captcha: :param dupcheck: :return: strawpy.Strawpoll object
def generate_namelist_file(self, rapid_namelist_file): """ Generate rapid_namelist file. Parameters ---------- rapid_namelist_file: str Path of namelist file to generate from parameters added to the RAPID manager. """ log("Generating RAPID...
Generate rapid_namelist file. Parameters ---------- rapid_namelist_file: str Path of namelist file to generate from parameters added to the RAPID manager.
def get_extract_method(path): """Returns `ExtractMethod` to use on resource at path. Cannot be None.""" info_path = _get_info_path(path) info = _read_info(info_path) fname = info.get('original_fname', path) if info else path return _guess_extract_method(fname)
Returns `ExtractMethod` to use on resource at path. Cannot be None.
def instantiate(config): """ instantiate all registered vodka applications Args: config (dict or MungeConfig): configuration object """ for handle, cfg in list(config["apps"].items()): if not cfg.get("enabled", True): continue app = get_application(handle) ...
instantiate all registered vodka applications Args: config (dict or MungeConfig): configuration object
def _get_programs_dict(): """ Builds and returns programs dictionary This will have to import the packages in COLLABORATORS_S in order to get their absolute path. Returns: dictionary: {"packagename": [ExeInfo0, ...], ...} "packagename" examples: "f311.explorer", "numpy" """ global...
Builds and returns programs dictionary This will have to import the packages in COLLABORATORS_S in order to get their absolute path. Returns: dictionary: {"packagename": [ExeInfo0, ...], ...} "packagename" examples: "f311.explorer", "numpy"
def scalarVectorDecorator(func): """Decorator to return scalar outputs as a set""" @wraps(func) def scalar_wrapper(*args,**kwargs): if numpy.array(args[1]).shape == () \ and numpy.array(args[2]).shape == (): #only if both R and z are scalars scalarOut= True ar...
Decorator to return scalar outputs as a set
def get_en_words() -> Set[str]: """ Returns a list of English words which can be used to filter out code-switched sentences. """ pull_en_words() with open(config.EN_WORDS_PATH) as words_f: raw_words = words_f.readlines() en_words = set([word.strip().lower() for word in raw_words]) ...
Returns a list of English words which can be used to filter out code-switched sentences.
def load_stubs(self, log_mem=False): """Load all events in their `stub` (name, alias, etc only) form. Used in `update` mode. """ # Initialize parameter related to diagnostic output of memory usage if log_mem: import psutil process = psutil.Process(os.getp...
Load all events in their `stub` (name, alias, etc only) form. Used in `update` mode.
def get_gammadot(F, mc, q, e): """ Compute gamma dot from Barack and Cutler (2004) :param F: Orbital frequency [Hz] :param mc: Chirp mass of binary [Solar Mass] :param q: Mass ratio of binary :param e: Eccentricity of binary :returns: dgamma/dt """ # chirp mass mc *= SOLAR2S ...
Compute gamma dot from Barack and Cutler (2004) :param F: Orbital frequency [Hz] :param mc: Chirp mass of binary [Solar Mass] :param q: Mass ratio of binary :param e: Eccentricity of binary :returns: dgamma/dt
def is_std_string(type_): """ Returns True, if type represents C++ `std::string`, False otherwise. """ if utils.is_str(type_): return type_ in string_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in s...
Returns True, if type represents C++ `std::string`, False otherwise.
def Write(self, packet): """See base class.""" out = bytearray([0] + packet) # Prepend the zero-byte (report ID) os.write(self.dev, out)
See base class.
def add_batch(self, nlive=500, wt_function=None, wt_kwargs=None, maxiter=None, maxcall=None, save_bounds=True, print_progress=True, print_func=None, stop_val=None): """ Allocate an additional batch of (nested) samples based on the combined set of previous samp...
Allocate an additional batch of (nested) samples based on the combined set of previous samples using the specified weight function. Parameters ---------- nlive : int, optional The number of live points used when adding additional samples in the batch. Def...
def row(self): """ Game Dataset(Row) :return: { 'retro_game_id': Retrosheet Game id 'game_type': Game Type(S/R/F/D/L/W) 'game_type_des': Game Type Description (Spring Training or Regular Season or Wild-card Game or Divisional Series or LCS or World...
Game Dataset(Row) :return: { 'retro_game_id': Retrosheet Game id 'game_type': Game Type(S/R/F/D/L/W) 'game_type_des': Game Type Description (Spring Training or Regular Season or Wild-card Game or Divisional Series or LCS or World Series) 'st_fl': Sprin...
def check_coin_a_phrase_from(text): """Check the text.""" err = "misc.illogic.coin" msg = "You can't coin an existing phrase. Did you mean 'borrow'?" regex = "to coin a phrase from" return existence_check(text, [regex], err, msg, offset=1)
Check the text.
def size(self): ''' Return the size in bits Return None if the size is not known Returns: int ''' t = self._type if t.startswith('uint'): return int(t[len('uint'):]) if t.startswith('int'): return int(t[len('int'...
Return the size in bits Return None if the size is not known Returns: int
def _add_blockhash_to_state_changes(storage: SQLiteStorage, cache: BlockHashCache) -> None: """Adds blockhash to ContractReceiveXXX and ActionInitChain state changes""" batch_size = 50 batch_query = storage.batch_query_state_changes( batch_size=batch_size, filters=[ ('_type', 'r...
Adds blockhash to ContractReceiveXXX and ActionInitChain state changes
def ray_shooting(self, x, y, kwargs, k=None): """ maps image to source position (inverse deflection) :param x: x-position (preferentially arcsec) :type x: numpy array :param y: y-position (preferentially arcsec) :type y: numpy array :param kwargs: list of keyword...
maps image to source position (inverse deflection) :param x: x-position (preferentially arcsec) :type x: numpy array :param y: y-position (preferentially arcsec) :type y: numpy array :param kwargs: list of keyword arguments of lens model parameters matching the lens model classe...
def write_matrix_to_tsv(net, filename=None, df=None): ''' This will export the matrix in net.dat or a dataframe (optional df in arguments) as a tsv file. Row/column categories will be saved as tuples in tsv, which can be read back into the network object. ''' import pandas as pd if df is None: df = n...
This will export the matrix in net.dat or a dataframe (optional df in arguments) as a tsv file. Row/column categories will be saved as tuples in tsv, which can be read back into the network object.
def generate_variables(name, n_vars=1, hermitian=None, commutative=True): """Generates a number of commutative or noncommutative variables :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1...
Generates a number of commutative or noncommutative variables :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1 if n_vars > 1. :type name: str. :param n_vars: The number of variables. ...
def analog_write(self, pin, value): """ Set the specified pin to the specified value. :param pin: Pin number :param value: Pin value :return: No return value """ if self._command_handler.ANALOG_MESSAGE + pin < 0xf0: command = [self._command_handler...
Set the specified pin to the specified value. :param pin: Pin number :param value: Pin value :return: No return value
def shutdown(self): """Close all file handles and stop all motors.""" self.stop_balance.set() # Stop balance thread self.motor_left.stop() self.motor_right.stop() self.gyro_file.close() self.touch_file.close() self.encoder_left_file.close() self.encoder_r...
Close all file handles and stop all motors.
async def _unwatch(self, conn): "Unwatches all previously specified keys" await conn.send_command('UNWATCH') res = await conn.read_response() return self.watching and res or True
Unwatches all previously specified keys
def get_mean_threshold_from_calibration(gdac, mean_threshold_calibration): '''Calculates the mean threshold from the threshold calibration at the given gdac settings. If the given gdac value was not used during caluibration the value is determined by interpolation. Parameters ---------- gdacs : arr...
Calculates the mean threshold from the threshold calibration at the given gdac settings. If the given gdac value was not used during caluibration the value is determined by interpolation. Parameters ---------- gdacs : array like The GDAC settings where the threshold should be determined from th...
def plotAccuracyDuringSequenceInference(dirName, title="", yaxis=""): """ Plot accuracy vs number of locations """ # Read in results file with open(os.path.join(dirName, "sequence_batch_high_dec_normal_features.pkl"), "rb") as f: results = cPickle.load(f) locationRange = [] featureRange =...
Plot accuracy vs number of locations
def get_sample_size(self, key=None): """ Returns the number of samples in the input data @ In, key, an optional 2-tuple specifying a min-max id pair used for determining which partition size should be returned. If not specified then the size of the entire data set...
Returns the number of samples in the input data @ In, key, an optional 2-tuple specifying a min-max id pair used for determining which partition size should be returned. If not specified then the size of the entire data set will be returned. @ Out, an integer ...
def _request_auth(self, registry): """ self, username, password=None, email=None, registry=None, reauth=False, insecure_registry=False, dockercfg_path=None): """ if registry: if registry.auth: registry.auth.load_dockercfg() try:...
self, username, password=None, email=None, registry=None, reauth=False, insecure_registry=False, dockercfg_path=None):
def main(args): """first we need sorted genepreds""" cmd = ['sort',args.reference,'--gpd','--tempdir',args.tempdir,'--threads', str(args.threads),'-o',args.tempdir+'/ref.sorted.gpd'] sys.stderr.write(cmd+"\n") gpd_sort(cmd) cmd = ['sort',args.gpd,'--gpd','--tempdir',args.tempdir,'--threads', ...
first we need sorted genepreds