code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _tokenize(self, text): """Tokenizes a piece of text.""" text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This is also applied to the English models now, but it doesn't # matter since the English models were not t...
Tokenizes a piece of text.
def table(self): """a ```pylsdj.Table``` referencing the instrument's table, or None if the instrument doesn't have a table""" if hasattr(self.data, 'table_on') and self.data.table_on: assert_index_sane(self.data.table, len(self.song.tables)) return self.song.tables[self....
a ```pylsdj.Table``` referencing the instrument's table, or None if the instrument doesn't have a table
def findPolymorphisms(self, strSeq, strict = False): """ Compares strSeq with self.sequence. If not 'strict', this function ignores the cases of matching heterozygocity (ex: for a given position i, strSeq[i] = A and self.sequence[i] = 'A/G'). If 'strict' it returns all positions where strSeq differs self,sequence...
Compares strSeq with self.sequence. If not 'strict', this function ignores the cases of matching heterozygocity (ex: for a given position i, strSeq[i] = A and self.sequence[i] = 'A/G'). If 'strict' it returns all positions where strSeq differs self,sequence
def create_stack_template( self, lambda_arn, lambda_name, api_key_required, iam_authorization, authorizer, cors_options=None, ...
Build the entire CF stack. Just used for the API Gateway, but could be expanded in the future.
def start_app(self, app_id, force_launch=False): """ Start an app on the Chromecast. """ self.logger.info("Starting app %s", app_id) self.socket_client.receiver_controller.launch_app(app_id, force_launch)
Start an app on the Chromecast.
def get_price(self, **kwargs): """Price Reference: https://iexcloud.io/docs/api/#price ``1`` per symbol Returns ------- float or pandas.DataFrame Stocks Price endpoint data """ def fmt_p(out): return pd.DataFrame(out...
Price Reference: https://iexcloud.io/docs/api/#price ``1`` per symbol Returns ------- float or pandas.DataFrame Stocks Price endpoint data
def fit(self, X, y, likelihood_args=()): r""" Learn the parameters of a Bayesian generalized linear model (GLM). Parameters ---------- X : ndarray (N, d) array input dataset (N samples, d dimensions). y : ndarray (N,) array targets (N samples) ...
r""" Learn the parameters of a Bayesian generalized linear model (GLM). Parameters ---------- X : ndarray (N, d) array input dataset (N samples, d dimensions). y : ndarray (N,) array targets (N samples) likelihood : Object A likelihood...
def get_parent_log_ids(self, log_id): """Gets the parent ``Ids`` of the given log. arg: log_id (osid.id.Id): the ``Id`` of a log return: (osid.id.IdList) - the parent ``Ids`` of the log raise: NotFound - ``log_id`` is not found raise: NullArgument - ``log_id`` is ``null`` ...
Gets the parent ``Ids`` of the given log. arg: log_id (osid.id.Id): the ``Id`` of a log return: (osid.id.IdList) - the parent ``Ids`` of the log raise: NotFound - ``log_id`` is not found raise: NullArgument - ``log_id`` is ``null`` raise: OperationFailed - unable to comple...
def from_file(pkg_file): """ Return a |PackageReader| instance loaded with contents of *pkg_file*. """ phys_reader = PhysPkgReader(pkg_file) content_types = _ContentTypeMap.from_xml(phys_reader.content_types_xml) pkg_srels = PackageReader._srels_for(phys_reader, PACKAGE_U...
Return a |PackageReader| instance loaded with contents of *pkg_file*.
def get_experiment_fn(args): """Builds the experiment function for learn_runner.run. Args: args: the command line args Returns: A function that returns a tf.learn experiment object. """ def get_experiment(output_dir): # Read schema, input features, and transforms. schema_path_with_target = ...
Builds the experiment function for learn_runner.run. Args: args: the command line args Returns: A function that returns a tf.learn experiment object.
def write_gdf(gdf, fname): """ Fast line-by-line gdf-file write function Parameters ---------- gdf : numpy.ndarray Column 0 is gids, columns 1: are values. fname : str Path to gdf-file. Returns ------- None """ gdf_file = open(fname, '...
Fast line-by-line gdf-file write function Parameters ---------- gdf : numpy.ndarray Column 0 is gids, columns 1: are values. fname : str Path to gdf-file. Returns ------- None
def _read_protos(self, size): """Read next layer protocol type. Positional arguments: * size -- int, buffer size Returns: * str -- link layer protocol name """ _byte = self._read_unpack(4, lilendian=True) _prot = LINKTYPE.get(_byte) ret...
Read next layer protocol type. Positional arguments: * size -- int, buffer size Returns: * str -- link layer protocol name
def _search_within_pe_warnings(self, matches): ''' Just encapsulating a search that takes place fairly often ''' pattern = '|'.join(re.escape(match) for match in matches) exp = re.compile(pattern) if any(exp.search(warning) for warning in self.pefile_handle.get_warnings()): r...
Just encapsulating a search that takes place fairly often
def model_saved(sender, instance, created, raw, using, **kwargs): """ Automatically triggers "created" and "updated" actions. """ opts = get_opts(instance) model = '.'.join([opts.app_label, opts.object_na...
Automatically triggers "created" and "updated" actions.
def close(self): """ Release all resources associated with this factory. """ if self.mdr is None: return exc = (None, None, None) try: self.cursor.close() except: exc = sys.exc_info() try: if self.mdr.__exit_...
Release all resources associated with this factory.
async def async_execute(self, command: Command, password: str = '', timeout: int = EXECUTE_TIMEOUT_SECS) -> Response: """ Execute a command and return response. command: the command instance to be executed password: if specified, will be used to execute ...
Execute a command and return response. command: the command instance to be executed password: if specified, will be used to execute this command (overriding any global password that may have been assigned to the property) timeout: maximum number of seconds to wait fo...
def StreamIDNextDownIDToConnectivity(stream_id_array, next_down_id_array, out_csv_file): """ Creates RAPID connect file from stream_id array and next down id array """ list_all = [] max_count_upstream = 0 for hydroid in n...
Creates RAPID connect file from stream_id array and next down id array
def is_forced_retry(self, method, status_code): """ Is this method/status code retryable? (Based on method/codes whitelists) """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return self.status_forcelist and status_code in self.status...
Is this method/status code retryable? (Based on method/codes whitelists)
def to_zpl( self, quantity=1, pause_and_cut=0, override_pause=False, print_mode='C', print_orientation='N', media_tracking='Y', **kwargs ): """ The most basic ZPL to print the GRF. Since ZPL printers are stateful this may not work and you may need to build your own. "...
The most basic ZPL to print the GRF. Since ZPL printers are stateful this may not work and you may need to build your own.
def plotter(path, show, goodFormat): '''makes some plots creates binned histograms of the results of each module (ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)]) Arguments: path {str} -- path to save plots to show {boolean} -- whethe...
makes some plots creates binned histograms of the results of each module (ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)]) Arguments: path {str} -- path to save plots to show {boolean} -- whether to show plots using python goodFor...
def check_valid_format(figformat): """Check if the specified figure format is valid. If format is invalid the default is returned. Probably installation-dependent """ fig = plt.figure() if figformat in list(fig.canvas.get_supported_filetypes().keys()): logging.info("Nanoplotter: valid o...
Check if the specified figure format is valid. If format is invalid the default is returned. Probably installation-dependent
def synchronized(cls, obj=None): """ synchronize on obj if obj is supplied. :param obj: the obj to lock on. if none, lock to the function :return: return of the func. """ def get_key(f, o): if o is None: key = hash(f) else: ...
synchronize on obj if obj is supplied. :param obj: the obj to lock on. if none, lock to the function :return: return of the func.
def post_save_event_listener(sender, instance, created): """Event listener to create creation and update events.""" if not instance._meta.event_ready: return if created: instance.create_creation_event() else: instance.create_update_event() # Reset the original key insta...
Event listener to create creation and update events.
def remote_jupyter_proxy_url(port): """ Callable to configure Bokeh's show method when a proxy must be configured. If port is None we're asking about the URL for the origin header. """ base_url = os.environ['EXTERNAL_URL'] host = urllib.parse.urlparse(base_url).netloc # If port is ...
Callable to configure Bokeh's show method when a proxy must be configured. If port is None we're asking about the URL for the origin header.
def meson_setup(): """ attempt to build with Meson + Ninja """ meson_exe = shutil.which('meson') ninja_exe = shutil.which('ninja') if not meson_exe or not ninja_exe: raise FileNotFoundError('Meson or Ninja not available') if not (BINDIR / 'build.ninja').is_file(): subproces...
attempt to build with Meson + Ninja
def clicked(self, event): """Print group name and number of items in bin.""" group = event.artist._mt_group n = event.artist._mt_n dt = num2date(event.artist._mt_bin) print("%4i %s events in %s sec beginning at %s" % (n, group, self.bucketsize, dt.strftime("%b %d %H...
Print group name and number of items in bin.
def save_surface_files(note, error, registrations, subject, no_surf_export, no_reg_export, surface_format, surface_path, angle_tag, eccen_tag, label_tag, radius_tag, registration_name): ''' save_surface_files is the calculator that saves the registration data out as...
save_surface_files is the calculator that saves the registration data out as surface files, which are put back in the registration as the value 'surface_files'.
def _aws_encode_changebatch(o): ''' helper method to process a change batch & encode the bits which need encoding. ''' change_idx = 0 while change_idx < len(o['Changes']): o['Changes'][change_idx]['ResourceRecordSet']['Name'] = aws_encode(o['Changes'][change_idx]['ResourceRecordSet']['Name']...
helper method to process a change batch & encode the bits which need encoding.
def set_cmd(name, accepts_value=False): """ Docorator that registers a ':set'-command. """ def decorator(func): SET_COMMANDS[name] = func if accepts_value: SET_COMMANDS_TAKING_VALUE.add(name) return func return decorator
Docorator that registers a ':set'-command.
def match_shortname(self, name, filled_args=None): """Try to convert a prefix into a parameter name. If the result could be ambiguous or there is no matching parameter, throw an ArgumentError Args: name (str): A prefix for a parameter name filled_args (list): A ...
Try to convert a prefix into a parameter name. If the result could be ambiguous or there is no matching parameter, throw an ArgumentError Args: name (str): A prefix for a parameter name filled_args (list): A list of filled positional arguments that will be ...
def source_file(self): """Return an open file for reading the source of the code unit.""" if os.path.exists(self.filename): # A regular text file: open it. return open_source(self.filename) # Maybe it's in a zip file? source = self.file_locator.get_zip_data(self....
Return an open file for reading the source of the code unit.
def _call_numpy(self, x): """Return ``self(x)`` using numpy. Parameters ---------- x : `numpy.ndarray` Input array to be transformed Returns ------- out : `numpy.ndarray` Result of the transform """ if self.halfcomplex: ...
Return ``self(x)`` using numpy. Parameters ---------- x : `numpy.ndarray` Input array to be transformed Returns ------- out : `numpy.ndarray` Result of the transform
def _get_lottery_detail_by_id(self, id): """ 相应彩种历史信息生成 百度详细信息页有两种结构,需要分开处理 """ header = '编号 期号 开奖日期 开奖号码'.split() pt = PrettyTable() pt._set_field_names(header) url = QUERY_DETAIL_URL.format(id=id) import requests content = requests.get(u...
相应彩种历史信息生成 百度详细信息页有两种结构,需要分开处理
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ json = {} json["hash"] = self.Hash.To0xString() json["size"] = self.Size() json["version"] = self.Version json["previousblockh...
Convert object members to a dictionary that can be parsed as JSON. Returns: dict:
def retry_over_time(fun, catch, args=[], kwargs={}, errback=None, max_retries=None, interval_start=2, interval_step=2, interval_max=30): """Retry the function over and over until max retries is exceeded. For each retry we sleep a for a while before we try again, this interval is increased for every...
Retry the function over and over until max retries is exceeded. For each retry we sleep a for a while before we try again, this interval is increased for every retry until the max seconds is reached. :param fun: The function to try :param catch: Exceptions to catch, can be either tuple or a single ...
def parse_config_file(config_file_path): """ Parse a configuration file. Currently only supports .json, .py and properties separated by '=' :param config_file_path: :return: a dict of the configuration properties """ extension = os.path.splitext(config_file_path)[1] if extension == '.pyc': raise Value...
Parse a configuration file. Currently only supports .json, .py and properties separated by '=' :param config_file_path: :return: a dict of the configuration properties
def get_template_object(template_file=''): """Retrieve template. Args: template_file (str): Name of template file. Returns: jinja2.Template: Template ready to render. Raises: AssertionError: Configured path for templates does not exist. :obj:`foremast.exceptions.Forema...
Retrieve template. Args: template_file (str): Name of template file. Returns: jinja2.Template: Template ready to render. Raises: AssertionError: Configured path for templates does not exist. :obj:`foremast.exceptions.ForemastTemplateNotFound`: Requested template ...
def fs_obj_query_info(self, path, follow_symlinks): """Queries information about a file system object (file, directory, etc) in the guest. in path of type str Path to the file system object to gather information about. Guest path style. in follow_symlinks of typ...
Queries information about a file system object (file, directory, etc) in the guest. in path of type str Path to the file system object to gather information about. Guest path style. in follow_symlinks of type bool Information about symbolic links is returned...
def audioread(filename): """Reads an audio signal from file. Supported formats : wav :param filename: filename of the audiofile to load :type filename: str :returns: int, numpy.ndarray -- samplerate, array containing the audio signal """ try: if '.wav' in filename.lower(): ...
Reads an audio signal from file. Supported formats : wav :param filename: filename of the audiofile to load :type filename: str :returns: int, numpy.ndarray -- samplerate, array containing the audio signal
def get_template_attributes(template_id, **kwargs): """ Get a specific attribute by its ID. """ try: attrs_i = db.DBSession.query(Attr).filter(TemplateType.template_id==template_id).filter(TypeAttr.type_id==TemplateType.id).filter(Attr.id==TypeAttr.id).all() log.debug(attrs_i) ...
Get a specific attribute by its ID.
def get_assessment_part(self, assessment_part_id): """Gets the ``AssessmentPart`` specified by its ``Id``. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` to retrieve return: (osid.assessment.authoring.AssessmentPart) - the returned ...
Gets the ``AssessmentPart`` specified by its ``Id``. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` to retrieve return: (osid.assessment.authoring.AssessmentPart) - the returned ``AssessmentPart`` raise: NotFound - no ``AssessmentP...
def update(self, display_name=None, display_description=None): """ Update the specified values on this snapshot. You may specify one or more values to update. If no values are specified as non-None, the call is a no-op; no exception will be raised. """ return self.manager...
Update the specified values on this snapshot. You may specify one or more values to update. If no values are specified as non-None, the call is a no-op; no exception will be raised.
def readline(self, f): """A helper method that only reads uncommented lines""" while True: line = f.readline() if len(line) == 0: raise EOFError line = line[:line.find('#')] line = line.strip() if len(line) > 0: ...
A helper method that only reads uncommented lines
def register(self, newdata, *args, **kwargs): """ Register data in registry. Meta for each data is specified by positional or keyword arguments after the new data and consists of the following: * ``uncertainty`` - Map of uncertainties in percent corresponding to new keys. The ...
Register data in registry. Meta for each data is specified by positional or keyword arguments after the new data and consists of the following: * ``uncertainty`` - Map of uncertainties in percent corresponding to new keys. The uncertainty keys must be a subset of the new data keys. * ...
def create_wtd_psf(skydir, ltc, event_class, event_types, dtheta, egy_bins, cth_bins, fn, nbin=64, npts=1): """Create an exposure- and dispersion-weighted PSF model for a source with spectral parameterization ``fn``. The calculation performed by this method accounts for the influence of ...
Create an exposure- and dispersion-weighted PSF model for a source with spectral parameterization ``fn``. The calculation performed by this method accounts for the influence of energy dispersion on the PSF. Parameters ---------- dtheta : `~numpy.ndarray` egy_bins : `~numpy.ndarray` ...
def to_ipv6(key): """Get IPv6 address from a public key.""" if key[-2:] != '.k': raise ValueError('Key does not end with .k') key_bytes = base32.decode(key[:-2]) hash_one = sha512(key_bytes).digest() hash_two = sha512(hash_one).hexdigest() return ':'.join([hash_two[i:i+4] for i in ran...
Get IPv6 address from a public key.
def replace_validating_webhook_configuration(self, name, body, **kwargs): """ replace the specified ValidatingWebhookConfiguration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_va...
replace the specified ValidatingWebhookConfiguration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_validating_webhook_configuration(name, body, async_req=True) >>> result = thread.get() ...
def read(self, address, size, force=False): """ Read a stream of potentially symbolic bytes from a potentially symbolic address :param address: Where to read from :param size: How many bytes :param force: Whether to ignore permissions :rtype: list """ ...
Read a stream of potentially symbolic bytes from a potentially symbolic address :param address: Where to read from :param size: How many bytes :param force: Whether to ignore permissions :rtype: list
def scan(self, *, items: np.ndarray = None, axis: int = None, layers: Iterable = None, key: str = None, batch_size: int = 8 * 64) -> Iterable[Tuple[int, np.ndarray, loompy.LoomView]]: """ Scan across one axis and return batches of rows (columns) as LoomView objects Args ---- items: np.ndarray the indexes ...
Scan across one axis and return batches of rows (columns) as LoomView objects Args ---- items: np.ndarray the indexes [0, 2, 13, ... ,973] of the rows/cols to include along the axis OR: boolean mask array giving the rows/cols to include axis: int 0:rows or 1:cols batch_size: int the chuncks retur...
def GetMacAddresses(self): """MAC addresses from all interfaces.""" result = set() for interface in self.interfaces: if (interface.mac_address and interface.mac_address != b"\x00" * len(interface.mac_address)): result.add(Text(interface.mac_address.human_readable_address)) return...
MAC addresses from all interfaces.
def GetPlugins(cls): """Retrieves the registered plugins. Yields: tuple[str, type]: name and class of the plugin. """ for plugin_name, plugin_class in iter(cls._plugin_classes.items()): yield plugin_name, plugin_class
Retrieves the registered plugins. Yields: tuple[str, type]: name and class of the plugin.
async def _send_rtcp_pli(self, media_ssrc): """ Send an RTCP packet to report picture loss. """ if self.__rtcp_ssrc is not None: packet = RtcpPsfbPacket(fmt=RTCP_PSFB_PLI, ssrc=self.__rtcp_ssrc, media_ssrc=media_ssrc) await self._send_rtcp(packet)
Send an RTCP packet to report picture loss.
def plot(self): """ return a toyplot barplot of the results table. """ if self.results_table == None: return "no results found" else: bb = self.results_table.sort_values( by=["ABCD", "ACBD"], ascending=[False, True], ...
return a toyplot barplot of the results table.
def set_exception(self, exception): """Set the result of the future to the given exception. Args: exception (:exc:`Exception`): The exception raised. """ # Sanity check: A future can only complete once. if self.done(): raise RuntimeError("set_exception ca...
Set the result of the future to the given exception. Args: exception (:exc:`Exception`): The exception raised.
def post_build(self, p, pay): """Called implicitly before a packet is sent. """ p += pay if self.auxdlen != 0: print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).") print(" Subsequent Group Records are lost!") return ...
Called implicitly before a packet is sent.
def djfrontend_jquery(version=None): """ Returns jQuery JavaScript file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback. Included in HTML5 Boilerplate. """ if version is None: version = getattr(settings, '...
Returns jQuery JavaScript file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback. Included in HTML5 Boilerplate.
def iter_module_paths(modules=None): """ Yield paths of all imported modules.""" modules = modules or list(sys.modules.values()) for module in modules: try: filename = module.__file__ except (AttributeError, ImportError): # pragma: no cover continue if filena...
Yield paths of all imported modules.
def register_json(self, data): """ Register the contents as JSON """ j = json.loads(data) self.last_data_timestamp = \ datetime.datetime.utcnow().replace(microsecond=0).isoformat() try: for v in j: # prepare the sensor entry con...
Register the contents as JSON
def _traverse(self, name, create_missing=False, action=None, value=NO_DEFAULT): """Traverse to the item specified by ``name``. To create missing items on the way to the ``name``d item, pass ``create_missing=True``. This will insert an item for each missing segment in ``name``. The type ...
Traverse to the item specified by ``name``. To create missing items on the way to the ``name``d item, pass ``create_missing=True``. This will insert an item for each missing segment in ``name``. The type and value of item that will be inserted for a missing segment depends on the *next*...
def wordcount(text): '''Returns the count of the words in a file.''' bannedwords = read_file('stopwords.txt') wordcount = {} separated = separate(text) for word in separated: if word not in bannedwords: if not wordcount.has_key(word): wordcount[word] = 1 ...
Returns the count of the words in a file.
def wfreq2vocab(wfreq_file, output_file, top=None, gt=None, records=1000000, verbosity=2): """ Takes a a word unigram file, as produced by text2wfreq and converts it to a vocabulary file. The top parameter allows the user to specify the size of the vocabulary; if the function is called with the para...
Takes a a word unigram file, as produced by text2wfreq and converts it to a vocabulary file. The top parameter allows the user to specify the size of the vocabulary; if the function is called with the parameter top=20000, then the vocabulary will consist of the most common 20,000 words. The gt parameter...
def _interpolate_stream_track_kick_aA(self): """Build interpolations of the stream track near the impact in action-angle coordinates""" if hasattr(self,'_kick_interpolatedObsTrackAA'): #pragma: no cover return None #Already did this #Calculate 1D meanOmega on a fine grid in angle and...
Build interpolations of the stream track near the impact in action-angle coordinates
def _get_types(func, clsm, slf, clss = None, prop_getter = False, unspecified_type = Any, infer_defaults = None): """Helper for get_types and get_member_types. """ func0 = util._actualfunc(func, prop_getter) # check consistency regarding special case with 'self'-keyword if not slf: ...
Helper for get_types and get_member_types.
def show_window_options(self, option=None, g=False): """ Return a dict of options for the window. For familiarity with tmux, the option ``option`` param forwards to pick a single option, forwarding to :meth:`Window.show_window_option`. Parameters ---------- opti...
Return a dict of options for the window. For familiarity with tmux, the option ``option`` param forwards to pick a single option, forwarding to :meth:`Window.show_window_option`. Parameters ---------- option : str, optional show a single option. g : str, opt...
def service_name(self): """ Service name inside the Docker Swarm service_suffix should be a numerical value unique for user {service_prefix}-{service_owner}-{service_suffix} """ if hasattr(self, "server_name") and self.server_name: server_name = self.server_n...
Service name inside the Docker Swarm service_suffix should be a numerical value unique for user {service_prefix}-{service_owner}-{service_suffix}
def _get_best_indexes(logits, n_best_size): """Get the n-best logits from a list.""" index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True) best_indexes = [] for i in range(len(index_and_score)): if i >= n_best_size: break best_indexes.append(index_and...
Get the n-best logits from a list.
def assert_text_equal(self, selector, value, testid=None, **kwargs): """Assert that the element's text is equal to the provided value Args: selector (str): the selector used to find the element value (str): the value that will be compare with the element.text val...
Assert that the element's text is equal to the provided value Args: selector (str): the selector used to find the element value (str): the value that will be compare with the element.text value test_id (str): the test_id or a str Kwargs: ...
def _byteify(input): """ Force the given input to only use `str` instead of `bytes` or `unicode`. This works even if the input is a dict, list, """ if isinstance(input, dict): return {_byteify(key): _byteify(value) for key, value in input.items()} elif isinstance(input, list): re...
Force the given input to only use `str` instead of `bytes` or `unicode`. This works even if the input is a dict, list,
def summarize(logger): """ Creates a short summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task. """ sum...
Creates a short summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task.
def helical_laminar_fd_White(Re, Di, Dc): r'''Calculates Darcy friction factor for a fluid flowing inside a curved pipe such as a helical coil under laminar conditions, using the method of White [1]_ as shown in [2]_. .. math:: f_{curved} = f_{\text{straight,laminar}} \left[1 - \left(1-\l...
r'''Calculates Darcy friction factor for a fluid flowing inside a curved pipe such as a helical coil under laminar conditions, using the method of White [1]_ as shown in [2]_. .. math:: f_{curved} = f_{\text{straight,laminar}} \left[1 - \left(1-\left( \frac{11.6}{De}\right)^{0.45}\rig...
def add_child(self, tree): '''Add a child to the list of this tree's children This tree becomes the added tree's parent ''' tree.parent = self self.children.append(tree) return tree
Add a child to the list of this tree's children This tree becomes the added tree's parent
def not_modified(cls, errors=None): """Shortcut API for HTTP 304 `Not Modified` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'a...
Shortcut API for HTTP 304 `Not Modified` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
def acquire(self): """Attempts to acquire a lock for the J-Link lockfile. If the lockfile exists but does not correspond to an active process, the lockfile is first removed, before an attempt is made to acquire it. Args: self (Jlock): the ``JLock`` instance Returns: ...
Attempts to acquire a lock for the J-Link lockfile. If the lockfile exists but does not correspond to an active process, the lockfile is first removed, before an attempt is made to acquire it. Args: self (Jlock): the ``JLock`` instance Returns: ``True`` if the lock...
def route(bp, *args, **kwargs): """Journey route decorator Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow. :param bp: :class:`flask.Blueprint` object :param args: args to pass along to `Blueprint.route` :param kwargs: - :strict_sla...
Journey route decorator Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow. :param bp: :class:`flask.Blueprint` object :param args: args to pass along to `Blueprint.route` :param kwargs: - :strict_slashes: Enable / disable strict slashes (...
def add_photo_to_observation(observation_id: int, file_object: BinaryIO, access_token: str): """Upload a picture and assign it to an existing observation. :param observation_id: the ID of the observation :param file_object: a file-like object for the picture. Example: open('/Users/nicolasnoe/vespa.jpg', 'r...
Upload a picture and assign it to an existing observation. :param observation_id: the ID of the observation :param file_object: a file-like object for the picture. Example: open('/Users/nicolasnoe/vespa.jpg', 'rb') :param access_token: the access token, as returned by :func:`get_access_token()`
def ndtri(p, name="ndtri"): """The inverse of the CDF of the Normal distribution function. Returns x such that the area under the pdf from minus infinity to x is equal to p. A piece-wise rational approximation is done for the function. This is a port of the implementation in netlib. Args: p: `Tensor`...
The inverse of the CDF of the Normal distribution function. Returns x such that the area under the pdf from minus infinity to x is equal to p. A piece-wise rational approximation is done for the function. This is a port of the implementation in netlib. Args: p: `Tensor` of type `float32`, `float64`. ...
def _write_subset_index_file(options, core_results): """ Write table giving index of subsets, giving number and subset string """ f_path = os.path.join(options['run_dir'], '_subset_index.csv') subset_strs = zip(*core_results)[0] index = np.arange(len(subset_strs)) + 1 df = pd.DataFrame({'su...
Write table giving index of subsets, giving number and subset string
def deserialize_single_input_output(self, transformer, node_path, attributes_map=None): """ :attributes_map: Map of attributes names. For example StandardScaler has `mean_` but is serialized as `mean` :param transformer: Scikit or Pandas transformer :param node: bundle.ml node json file ...
:attributes_map: Map of attributes names. For example StandardScaler has `mean_` but is serialized as `mean` :param transformer: Scikit or Pandas transformer :param node: bundle.ml node json file :param model: bundle.ml model json file :return: Transformer
def curry(f, args_supplied=()): """ Takes a function, and then returns a function that takes each argument for the original function through __call__. You probably shouldn't use this with builtins! Even if it seems to work with a builtin, it might not work properly in previous versions of Python. ...
Takes a function, and then returns a function that takes each argument for the original function through __call__. You probably shouldn't use this with builtins! Even if it seems to work with a builtin, it might not work properly in previous versions of Python.
def geolocation_buses(network, session): """ If geopandas is installed: Use Geometries of buses x/y(lon/lat) and Polygons of Countries from RenpassGisParameterRegion in order to locate the buses Else: Use coordinats of buses to locate foreign buses, which is less accurate. Param...
If geopandas is installed: Use Geometries of buses x/y(lon/lat) and Polygons of Countries from RenpassGisParameterRegion in order to locate the buses Else: Use coordinats of buses to locate foreign buses, which is less accurate. Parameters ---------- network_etrago: : class: `e...
def pool_create(hypervisor, identifier, pool_path): """Storage pool creation. The following values are set in the XML configuration: * name * target/path * target/permission/label """ path = os.path.join(pool_path, identifier) if not os.path.exists(path): os.makedirs(pat...
Storage pool creation. The following values are set in the XML configuration: * name * target/path * target/permission/label
def validate (self): """Returns True if this Sequence is valid, False otherwise. Validation error messages are stored in self.messages. """ if not os.path.isfile(self.pathname): self.message.append('Filename "%s" does not exist.') else: try: with open(self.pathname, 'r') as strea...
Returns True if this Sequence is valid, False otherwise. Validation error messages are stored in self.messages.
def spec_fn(spec_dir='.'): """ Return the filename for a .spec file in this directory. """ specs = [f for f in os.listdir(spec_dir) if os.path.isfile(f) and f.endswith('.spec')] if not specs: raise exception.SpecFileNotFound() if len(specs) != 1: raise exception.Mult...
Return the filename for a .spec file in this directory.
def download(self, bands, download_dir=None, metadata=False): """Download each specified band and metadata.""" super(AWSDownloader, self).validate_bands(bands) if download_dir is None: download_dir = DOWNLOAD_DIR dest_dir = check_create_folder(join(download_dir, self.sceneIn...
Download each specified band and metadata.
def add_transition (self, input_symbol, state, action=None, next_state=None): '''This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method will ignore the action and only set ...
This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state ...
def fit(self, X, y=None): """ Fit the clustering model, computing the centers then embeds the centers into 2D space using the embedding method specified. """ with Timer() as self.fit_time_: # Fit the underlying estimator self.estimator.fit(X, y) ...
Fit the clustering model, computing the centers then embeds the centers into 2D space using the embedding method specified.
def autoconvert(string): """Try to convert variables into datatypes.""" for fn in (boolify, int, float): try: return fn(string) except ValueError: pass return string
Try to convert variables into datatypes.
def now_date(str=False): """Get the current date.""" if str: return datetime.datetime.now().strftime("%Y-%m-%d") return datetime.date.today()
Get the current date.
def resize_contain(image, size, resample=Image.LANCZOS, bg_color=(255, 255, 255, 0)): """ Resize image according to size. image: a Pillow image instance size: a list of two integers [width, height] """ img_format = image.format img = image.copy() img.thumbnail((size[0], size[1...
Resize image according to size. image: a Pillow image instance size: a list of two integers [width, height]
def get_mount_targets(filesystemid=None, mounttargetid=None, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Get all the EFS mount point properties for a specific f...
Get all the EFS mount point properties for a specific filesystemid or the properties for a specific mounttargetid. One or the other must be specified filesystemid (string) - ID of the file system whose mount targets to list Must be specified if mounttargetid is not mounttarg...
def _get_value(self, entity): """Internal helper to get the value for this Property from an entity. For a repeated Property this initializes the value to an empty list if it is not set. """ if entity._projection: if self._name not in entity._projection: raise UnprojectedPropertyError(...
Internal helper to get the value for this Property from an entity. For a repeated Property this initializes the value to an empty list if it is not set.
def get_topology(self, topologyName, callback=None): """get topology""" if callback: self.topology_watchers[topologyName].append(callback) else: topology_path = self.get_topology_path(topologyName) with open(topology_path) as f: data = f.read() topology = Topology() ...
get topology
def p_closed_proposition_list(self, p): """ closed_proposition_list : closed_proposition_list SLASH SLASH closed_proposition | closed_proposition""" if len(p) == 2: p[0] = [p[1]] else: p[0] = p[1] + [p[4]]
closed_proposition_list : closed_proposition_list SLASH SLASH closed_proposition | closed_proposition
def prepare(data): """Restructure/prepare data about trees for output.""" sha = data.get("sha") tree = data.get("tree") return {"sha": sha, "tree": tree}
Restructure/prepare data about trees for output.
def _get_subparser(self, path, group_table=None): """For each part of the path, walk down the tree of subparsers, creating new ones if one doesn't already exist. """ group_table = group_table or {} for length in range(0, len(path)): parent_path = path[:length] ...
For each part of the path, walk down the tree of subparsers, creating new ones if one doesn't already exist.
def normalize(self,asOf=None,multiplier=100): """ Returns a normalized series or DataFrame Example: Series.normalize() Returns: series of DataFrame Parameters: ----------- asOf : string Date format '2015-02-29' multiplier : int Factor by which the results will be adjusted """ if not asOf: ...
Returns a normalized series or DataFrame Example: Series.normalize() Returns: series of DataFrame Parameters: ----------- asOf : string Date format '2015-02-29' multiplier : int Factor by which the results will be adjusted
def get_save_request_from_user(self): """Queries user if grid should be saved""" msg = _("There are unsaved changes.\nDo you want to save?") dlg = GMD.GenericMessageDialog( self.main_window, msg, _("Unsaved changes"), wx.YES_NO | wx.ICON_QUESTION | wx.CANCEL) s...
Queries user if grid should be saved
def githubWebHookConsumer(self, *args, **kwargs): """ Consume GitHub WebHook Capture a GitHub event and publish it via pulse, if it's a push, release or pull request. This method is ``experimental`` """ return self._makeApiCall(self.funcinfo["githubWebHookConsu...
Consume GitHub WebHook Capture a GitHub event and publish it via pulse, if it's a push, release or pull request. This method is ``experimental``
def generate_matching_datasets(self, data_slug): """Return datasets that match data_slug (hub_slug).""" matching_datasets = Dataset.objects.filter( hub_slug=data_slug ).order_by('-date_uploaded') if len(matching_datasets) > 0: return matching_datasets els...
Return datasets that match data_slug (hub_slug).
def energy(self, hamiltonian): r""" The total energy *per unit mass* (e.g., kinetic + potential): Parameters ---------- hamiltonian : `gala.potential.Hamiltonian` The Hamiltonian object to evaluate the energy. Returns ------- E : :class:`~ast...
r""" The total energy *per unit mass* (e.g., kinetic + potential): Parameters ---------- hamiltonian : `gala.potential.Hamiltonian` The Hamiltonian object to evaluate the energy. Returns ------- E : :class:`~astropy.units.Quantity` The to...