code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def sepBy(p, sep): '''`sepBy(p, sep)` parses zero or more occurrences of p, separated by `sep`. Returns a list of values returned by `p`.''' return separated(p, sep, 0, maxt=float('inf'), end=False)
`sepBy(p, sep)` parses zero or more occurrences of p, separated by `sep`. Returns a list of values returned by `p`.
async def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ await self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) ...
Get raw predicate information for given request class, and cache for subsequent calls.
def _transport_interceptor(self, callback): """Takes a callback function and returns a function that takes headers and messages and places them on the main service queue.""" def add_item_to_queue(header, message): queue_item = ( Priority.TRANSPORT, ne...
Takes a callback function and returns a function that takes headers and messages and places them on the main service queue.
def is_anagram(s, t): """ :type s: str :type t: str :rtype: bool """ maps = {} mapt = {} for i in s: maps[i] = maps.get(i, 0) + 1 for i in t: mapt[i] = mapt.get(i, 0) + 1 return maps == mapt
:type s: str :type t: str :rtype: bool
def v_from_i(resistance_shunt, resistance_series, nNsVth, current, saturation_current, photocurrent, method='lambertw'): ''' Device voltage at the given device current for the single diode model. Uses the single diode model (SDM) as described in, e.g., Jain and Kapoor 2004 [1]. The so...
Device voltage at the given device current for the single diode model. Uses the single diode model (SDM) as described in, e.g., Jain and Kapoor 2004 [1]. The solution is per Eq 3 of [1] except when resistance_shunt=numpy.inf, in which case the explict solution for voltage is used. Ideal device pa...
def lookup(self, hostname): """ Return a dict (`SSHConfigDict`) of config options for a given hostname. The host-matching rules of OpenSSH's ``ssh_config`` man page are used: For each parameter, the first obtained value will be used. The configuration files contain sections sep...
Return a dict (`SSHConfigDict`) of config options for a given hostname. The host-matching rules of OpenSSH's ``ssh_config`` man page are used: For each parameter, the first obtained value will be used. The configuration files contain sections separated by ``Host`` specifications, and t...
def ccdmask(flat1, flat2=None, mask=None, lowercut=6.0, uppercut=6.0, siglev=1.0, mode='region', nmed=(7, 7), nsig=(15, 15)): """Find cosmetic defects in a detector using two flat field images. Two arrays representing flat fields of different exposure times are required. Cosmetic defects are se...
Find cosmetic defects in a detector using two flat field images. Two arrays representing flat fields of different exposure times are required. Cosmetic defects are selected as points that deviate significantly of the expected normal distribution of pixels in the ratio between `flat2` and `flat1`. The m...
def delete_dashboard(self, id, **kwargs): # noqa: E501 """Delete a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_dashboard(id, asy...
Delete a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_dashboard(id, async_req=True) >>> result = thread.get() :param asyn...
def remove_from_category(self, category): """Removes this object from a given category. :param Category category: :return: """ ctype = ContentType.objects.get_for_model(self) self.categories.model.objects.filter(category=category, content_type=ctype, object_id=self.id).d...
Removes this object from a given category. :param Category category: :return:
def com_adobe_fonts_check_family_consistent_upm(ttFonts): """Fonts have consistent Units Per Em?""" upm_set = set() for ttFont in ttFonts: upm_set.add(ttFont['head'].unitsPerEm) if len(upm_set) > 1: yield FAIL, ("Fonts have different units per em: {}." ).format(sorte...
Fonts have consistent Units Per Em?
def pypi( click_ctx, requirements, index=None, python_version=3, exclude_packages=None, output=None, subgraph_check_api=None, no_transitive=True, no_pretty=False, ): """Manipulate with dependency requirements using PyPI.""" requirements = [requirement.strip() for requirement ...
Manipulate with dependency requirements using PyPI.
def verify_signature(self, signing_key, message, signature, padding_method, signing_algorithm=None, hashing_algorithm=None, digital_signature_alg...
Verify a message signature. Args: signing_key (bytes): The bytes of the signing key to use for signature verification. Required. message (bytes): The bytes of the message that corresponds with the signature. Required. signature (bytes): The by...
def _setLearningMode(self, l4Learning = False, l2Learning=False): """ Sets the learning mode for L4 and L2. """ for column in self.L4Columns: column.setParameter("learn", 0, l4Learning) for column in self.L2Columns: column.setParameter("learningMode", 0, l2Learning)
Sets the learning mode for L4 and L2.
def format(self, status, headers, environ, bucket, delay): """ Formats a response entity. Returns a tuple of the desired status code and the formatted entity. The default status code is passed in, as is a dictionary of headers. :param status: The default status code. Should b...
Formats a response entity. Returns a tuple of the desired status code and the formatted entity. The default status code is passed in, as is a dictionary of headers. :param status: The default status code. Should be returned to the caller, or an alternate selected. The...
def move(self, x, y): """Changes the overlay's position relative to the IFramebuffer. in x of type int in y of type int """ if not isinstance(x, baseinteger): raise TypeError("x can only be an instance of type baseinteger") if not isinstance(y, baseinteger)...
Changes the overlay's position relative to the IFramebuffer. in x of type int in y of type int
def from_word2vec(fname, fvocab=None, binary=False): """ Load the input-hidden weight matrix from the original C word2vec-tool format. Note that the information stored in the file is incomplete (the binary tree is missing), so while you can query for word similarity etc., you cannot continue training ...
Load the input-hidden weight matrix from the original C word2vec-tool format. Note that the information stored in the file is incomplete (the binary tree is missing), so while you can query for word similarity etc., you cannot continue training with a model loaded this way. `binary` is a boolean indic...
def append(self, item): """ See :meth:`list.append()` method Calls observer ``self.observer(UpdateType.CREATED, item, index)`` where **index** is *item position* """ self.real_list.append(item) self.observer(UpdateType.CREATED, item, len(self.real_list) - 1)
See :meth:`list.append()` method Calls observer ``self.observer(UpdateType.CREATED, item, index)`` where **index** is *item position*
def bilinear_sampling(input_layer, x, y, name=PROVIDED): """Performs bilinear sampling. This must be a rank 4 Tensor. Implements the differentiable sampling mechanism with bilinear kernel in https://arxiv.org/abs/1506.02025. Given (x, y) coordinates for each output pixel, use bilinear sampling on the input_...
Performs bilinear sampling. This must be a rank 4 Tensor. Implements the differentiable sampling mechanism with bilinear kernel in https://arxiv.org/abs/1506.02025. Given (x, y) coordinates for each output pixel, use bilinear sampling on the input_layer to fill the output. Args: input_layer: The chaina...
def validate(self, instance, value): """Checks that value is a complex number Floats and Integers are coerced to complex numbers """ try: compval = complex(value) if not self.cast and ( abs(value.real - compval.real) > TOL or ...
Checks that value is a complex number Floats and Integers are coerced to complex numbers
def stringify(self) : "a pretty str version of getChain()" l = [] h = self.head while h : l.append(str(h._key)) h = h.nextDoc return "<->".join(l)
a pretty str version of getChain()
def parse_version(str_): """ Parses the program's version from a python variable declaration. """ v = re.findall(r"\d+.\d+.\d+", str_) if v: return v[0] else: print("cannot parse string {}".format(str_)) raise KeyError
Parses the program's version from a python variable declaration.
def send_signal(self, backend, signal): """ Sends the `signal` signal to `backend`. Raises ValueError if `backend` is not registered with the client. Returns the result. """ backend = self._expand_host(backend) if backend in self.backends: try: ...
Sends the `signal` signal to `backend`. Raises ValueError if `backend` is not registered with the client. Returns the result.
def wgs84togcj02(lng, lat): """ WGS84转GCJ02(火星坐标系) :param lng:WGS84坐标系的经度 :param lat:WGS84坐标系的纬度 :return: """ if out_of_china(lng, lat): # 判断是否在国内 return lng, lat dlat = transformlat(lng - 105.0, lat - 35.0) dlng = transformlng(lng - 105.0, lat - 35.0) radlat = lat / 180...
WGS84转GCJ02(火星坐标系) :param lng:WGS84坐标系的经度 :param lat:WGS84坐标系的纬度 :return:
def _get_imported_module(self, module_name): """try to get imported module reference by its name""" # if imported module on module_set add to list imp_mod = self.by_name.get(module_name) if imp_mod: return imp_mod # last part of import section might not be a module ...
try to get imported module reference by its name
def isect(list1, list2): r""" returns list1 elements that are also in list2. preserves order of list1 intersect_ordered Args: list1 (list): list2 (list): Returns: list: new_list Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import * # NOQA ...
r""" returns list1 elements that are also in list2. preserves order of list1 intersect_ordered Args: list1 (list): list2 (list): Returns: list: new_list Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list1 = ['featweig...
def start(self): """ Starts the dependency manager """ self._context.add_service_listener( self, self.requirement.filter, self.requirement.specification )
Starts the dependency manager
def getDelOps(self, buid): ''' Get a list of storage operations to delete this property from the buid. Args: buid (bytes): The node buid. Returns: (tuple): The storage operations ''' return ( ('prop:del', (buid, self.form.name, self.n...
Get a list of storage operations to delete this property from the buid. Args: buid (bytes): The node buid. Returns: (tuple): The storage operations
def from_css(Class, csstext, encoding=None, href=None, media=None, title=None, validate=None): """parse CSS text into a Styles object, using cssutils """ styles = Class() cssStyleSheet = cssutils.parseString(csstext, encoding=encoding, href=href, media=media, title=title, validate=valida...
parse CSS text into a Styles object, using cssutils
def blob_handler(self, cmd): """Process a BlobCommand.""" # These never pass through directly. We buffer them and only # output them if referenced by an interesting command. self.blobs[cmd.id] = cmd self.keep = False
Process a BlobCommand.
def _algebraic_rules_scalar(): """Set the default algebraic rules for scalars""" a = wc("a", head=SCALAR_VAL_TYPES) b = wc("b", head=SCALAR_VAL_TYPES) x = wc("x", head=SCALAR_TYPES) y = wc("y", head=SCALAR_TYPES) z = wc("z", head=SCALAR_TYPES) indranges__ = wc("indranges__", head=IndexRange...
Set the default algebraic rules for scalars
def _unique_ordered_lines(line_numbers): """ Given a list of line numbers, return a list in which each line number is included once and the lines are ordered sequentially. """ if len(line_numbers) == 0: return [] # Ensure lines are unique by putting them in ...
Given a list of line numbers, return a list in which each line number is included once and the lines are ordered sequentially.
def question_detail(request, topic_slug, slug): """ A detail view of a Question. Simply redirects to a detail page for the related :model:`faq.Topic` (:view:`faq.views.topic_detail`) with the addition of a fragment identifier that links to the given :model:`faq.Question`. E.g. ``/faq/topic-slug...
A detail view of a Question. Simply redirects to a detail page for the related :model:`faq.Topic` (:view:`faq.views.topic_detail`) with the addition of a fragment identifier that links to the given :model:`faq.Question`. E.g. ``/faq/topic-slug/#question-slug``.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict
Return a json dictionary representing this model.
def invert_pixel_mask(mask): '''Invert pixel mask (0->1, 1(and greater)->0). Parameters ---------- mask : array-like Mask. Returns ------- inverted_mask : array-like Inverted Mask. ''' inverted_mask = np.ones(shape=(80, 336), dtype=np.dtype('>u1')) ...
Invert pixel mask (0->1, 1(and greater)->0). Parameters ---------- mask : array-like Mask. Returns ------- inverted_mask : array-like Inverted Mask.
def _validate_arguments(self): """method to sanitize model parameters Parameters --------- None Returns ------- None """ if self._has_terms(): [term._validate_arguments() for term in self._terms] return self
method to sanitize model parameters Parameters --------- None Returns ------- None
def random_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """Sleep a random amount of time between wait_random_min and wait_random_max""" return random.randint(self._wait_random_min, self._wait_random_max)
Sleep a random amount of time between wait_random_min and wait_random_max
def safe_read_file(file_path: Path) -> str: """Read a text file. Several text encodings are tried until the file content is correctly decoded. :raise GuesslangError: when the file encoding is not supported :param file_path: path to the input file :return: text file content """ for encoding ...
Read a text file. Several text encodings are tried until the file content is correctly decoded. :raise GuesslangError: when the file encoding is not supported :param file_path: path to the input file :return: text file content
def get_fermi(self, c, T, rtol=0.01, nstep=50, step=0.1, precision=8): """ Finds the fermi level at which the doping concentration at the given temperature (T) is equal to c. A greedy algorithm is used where the relative error is minimized by calculating the doping at a grid which ...
Finds the fermi level at which the doping concentration at the given temperature (T) is equal to c. A greedy algorithm is used where the relative error is minimized by calculating the doping at a grid which is continuously become finer. Args: c (float): doping concentration....
def stl(A, b): r"""Shortcut to ``solve_triangular(A, b, lower=True, check_finite=False)``. Solve linear systems :math:`\mathrm A \mathbf x = \mathbf b` when :math:`\mathrm A` is a lower-triangular matrix. Args: A (array_like): A lower-triangular matrix. b (array_like): Ordinate values....
r"""Shortcut to ``solve_triangular(A, b, lower=True, check_finite=False)``. Solve linear systems :math:`\mathrm A \mathbf x = \mathbf b` when :math:`\mathrm A` is a lower-triangular matrix. Args: A (array_like): A lower-triangular matrix. b (array_like): Ordinate values. Returns: ...
def GetHostMemUsedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemUsedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def get_table_info(conn, tablename): """Returns TableInfo object""" r = conn.execute("pragma table_info('{}')".format(tablename)) ret = TableInfo(((row["name"], row) for row in r)) return ret
Returns TableInfo object
def wait_for_element_not_present(self, locator): """ Synchronization helper to wait until some element is removed from the page :raises: ElementVisiblityTimeout """ for i in range(timeout_seconds): if self.driver.is_element_present(locator): time.slee...
Synchronization helper to wait until some element is removed from the page :raises: ElementVisiblityTimeout
def autoset_id(self): """ If the :attr:`id_` already has a non-false (false is also the empty string!) value, this method is a no-op. Otherwise, the :attr:`id_` attribute is filled with :data:`RANDOM_ID_BYTES` of random data, encoded by :func:`aioxmpp.utils.to_nmtoken`. ...
If the :attr:`id_` already has a non-false (false is also the empty string!) value, this method is a no-op. Otherwise, the :attr:`id_` attribute is filled with :data:`RANDOM_ID_BYTES` of random data, encoded by :func:`aioxmpp.utils.to_nmtoken`. .. note:: This method...
def ip2long(ip): """Convert a dotted-quad ip address to a network byte order 32-bit integer. >>> ip2long('127.0.0.1') 2130706433 >>> ip2long('127.1') 2130706433 >>> ip2long('127') 2130706432 >>> ip2long('127.0.0.256') is None True :param ip: Dotted-quad ip address (eg. '1...
Convert a dotted-quad ip address to a network byte order 32-bit integer. >>> ip2long('127.0.0.1') 2130706433 >>> ip2long('127.1') 2130706433 >>> ip2long('127') 2130706432 >>> ip2long('127.0.0.256') is None True :param ip: Dotted-quad ip address (eg. '127.0.0.1'). :type ip...
def generate(self): """ Generates and returns a numeric captcha image in base64 format. Saves the correct answer in `session['captcha_answer']` Use later as: src = captcha.generate() <img src="{{src}}"> """ answer = self.rand.randrange(se...
Generates and returns a numeric captcha image in base64 format. Saves the correct answer in `session['captcha_answer']` Use later as: src = captcha.generate() <img src="{{src}}">
def populate(self, priority, address, rtr, data): """ -DB1 last 2 bits = channel -DB1 first 6 bist = pulses -DB2-5 = pulse counter -DB6-7 = ms/pulse :return: None """ assert isinstance(data, bytes) ...
-DB1 last 2 bits = channel -DB1 first 6 bist = pulses -DB2-5 = pulse counter -DB6-7 = ms/pulse :return: None
def apply_classifier(self, name, samples=None, subset=None): """ Apply a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier to apply. subset : str The subset of samples to apply the...
Apply a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier to apply. subset : str The subset of samples to apply the classifier to. Returns ------- name : str
def plot_ranges_from_cli(opts): """Parses the mins and maxs arguments from the `plot_posterior` option group. Parameters ---------- opts : ArgumentParser The parsed arguments from the command line. Returns ------- mins : dict Dictionary of parameter name -> specified mi...
Parses the mins and maxs arguments from the `plot_posterior` option group. Parameters ---------- opts : ArgumentParser The parsed arguments from the command line. Returns ------- mins : dict Dictionary of parameter name -> specified mins. Only parameters that were s...
def dist_iter(self, g_nums, ats_1, ats_2, invalid_error=False): """ Iterator over selected interatomic distances. Distances are in Bohrs as with :meth:`dist_single`. See `above <toc-generators_>`_ for more information on calling options. Parameters ---------- g...
Iterator over selected interatomic distances. Distances are in Bohrs as with :meth:`dist_single`. See `above <toc-generators_>`_ for more information on calling options. Parameters ---------- g_nums |int| or length-R iterable |int| or |None| -- ...
def add_contact(self, phone_number: str, first_name: str, last_name: str=None, on_success: callable=None): """ Add contact by phone number and name (last_name is optional). :param phone: Valid phone number for contact. :param first_name: First name to use. :param last_name: Last ...
Add contact by phone number and name (last_name is optional). :param phone: Valid phone number for contact. :param first_name: First name to use. :param last_name: Last name to use. Optional. :param on_success: Callback to call when adding, will contain success status and the current con...
def monthly_mean_at_each_ind(monthly_means, sub_monthly_timeseries): """Copy monthly mean over each time index in that month. Parameters ---------- monthly_means : xarray.DataArray array of monthly means sub_monthly_timeseries : xarray.DataArray array of a timeseries at sub-monthly ...
Copy monthly mean over each time index in that month. Parameters ---------- monthly_means : xarray.DataArray array of monthly means sub_monthly_timeseries : xarray.DataArray array of a timeseries at sub-monthly time resolution Returns ------- xarray.DataArray with eath mont...
def matlab_compatible(name): """ make a channel name compatible with Matlab variable naming Parameters ---------- name : str channel name Returns ------- compatible_name : str channel name compatible with Matlab """ compatible_name = [ch if ch in ALLOWED_MATLAB_CH...
make a channel name compatible with Matlab variable naming Parameters ---------- name : str channel name Returns ------- compatible_name : str channel name compatible with Matlab
def get_mcu_definition(self, project_file): """ Parse project file to get mcu definition """ # TODO: check the extension here if it's valid IAR project or we # should at least check if syntax is correct check something IAR defines and return error if not project_file = join(getcwd(), pro...
Parse project file to get mcu definition
def _get_f2rx(self, C, r_x, r_1, r_2): """ Defines the f2 scaling coefficient defined in equation 10 """ drx = (r_x - r_1) / (r_2 - r_1) return self.CONSTS["h4"] + (C["h5"] * drx) + (C["h6"] * (drx ** 2.))
Defines the f2 scaling coefficient defined in equation 10
def warn_on_var_indirection(self) -> bool: """If True, warn when a Var reference cannot be direct linked (iff use_var_indirection is False)..""" return not self.use_var_indirection and self._opts.entry( WARN_ON_VAR_INDIRECTION, True )
If True, warn when a Var reference cannot be direct linked (iff use_var_indirection is False)..
def _handleCallInitiated(self, regexMatch, callId=None, callType=1): """ Handler for "outgoing call initiated" event notification line """ if self._dialEvent: if regexMatch: groups = regexMatch.groups() # Set self._dialReponse to (callId, callType) ...
Handler for "outgoing call initiated" event notification line
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data["properties"] raw_content = properties.get("addressSpace", None) if raw_content is not None: address_space = AddressSpace.from_raw_data(raw_content) proper...
Create a new model using raw API response.
def _trade(self, security, price=0, amount=0, volume=0, entrust_bs="buy"): """ 调仓 :param security: :param price: :param amount: :param volume: :param entrust_bs: :return: """ stock = self._search_stock_info(security) balance = self....
调仓 :param security: :param price: :param amount: :param volume: :param entrust_bs: :return:
def configure(cls, name, config, prefix='depot.'): """Configures an application depot. This configures the application wide depot from a settings dictionary. The settings dictionary is usually loaded from an application configuration file where all the depot options are specified with a...
Configures an application depot. This configures the application wide depot from a settings dictionary. The settings dictionary is usually loaded from an application configuration file where all the depot options are specified with a given ``prefix``. The default ``prefix`` is *depot.*...
def decrypt(self, data): """ Decrypts an encrypted (SK, 46) IKE payload using self.SK_er :param data: Encrypted IKE payload including headers (payloads.SK()) :return: next_payload, data_containing_payloads :raise IkeError: If packet is corrupted. """ next_payload...
Decrypts an encrypted (SK, 46) IKE payload using self.SK_er :param data: Encrypted IKE payload including headers (payloads.SK()) :return: next_payload, data_containing_payloads :raise IkeError: If packet is corrupted.
def _get_options(ret=None): ''' Returns options used for the MySQL connection. ''' defaults = {'host': 'salt', 'user': 'salt', 'pass': 'salt', 'db': 'salt', 'port': 3306, 'ssl_ca': None, 'ssl_cert': None, ...
Returns options used for the MySQL connection.
def setClockShowDate(kvalue, **kwargs): ''' Set whether the date is visible in the clock CLI Example: .. code-block:: bash salt '*' gnome.setClockShowDate <True|False> user=<username> ''' if kvalue is not True and kvalue is not False: return False _gsession = _GSettings(u...
Set whether the date is visible in the clock CLI Example: .. code-block:: bash salt '*' gnome.setClockShowDate <True|False> user=<username>
async def clear(self, using_db=None) -> None: """ Clears ALL relations. """ db = using_db if using_db else self.model._meta.db through_table = Table(self.field.through) query = ( db.query_class.from_(through_table) .where(getattr(through_table, sel...
Clears ALL relations.
def _getArrays(items, attr, defaultValue): """Return arrays with equal size of item attributes from a list of sorted "items" for fast and convenient data processing. :param attr: list of item attributes that should be added to the returned array. :param defaultValue: if an item is missing an at...
Return arrays with equal size of item attributes from a list of sorted "items" for fast and convenient data processing. :param attr: list of item attributes that should be added to the returned array. :param defaultValue: if an item is missing an attribute, the "defaultValue" is added to th...
def merge_leaderboards(self, destination, keys, aggregate='SUM'): ''' Merge leaderboards given by keys with this leaderboard into a named destination leaderboard. @param destination [String] Destination leaderboard name. @param keys [Array] Leaderboards to be merged with the current lea...
Merge leaderboards given by keys with this leaderboard into a named destination leaderboard. @param destination [String] Destination leaderboard name. @param keys [Array] Leaderboards to be merged with the current leaderboard. @param options [Hash] Options for merging the leaderboards.
def load_cml(cml_filename): """Load the molecules from a CML file Argument: | ``cml_filename`` -- The filename of a CML file. Returns a list of molecule objects with optional molecular graph attribute and extra attributes. """ parser = make_parser() parser.setFeature(fea...
Load the molecules from a CML file Argument: | ``cml_filename`` -- The filename of a CML file. Returns a list of molecule objects with optional molecular graph attribute and extra attributes.
def set_uid(self): """Change the user of the running process""" if self.user: uid = getpwnam(self.user).pw_uid try: os.setuid(uid) except Exception: message = ('Unable to switch ownership to {0}:{1}. ' + 'Did ...
Change the user of the running process
def options(self, **options): """Adds input options for the underlying data source. You can set the following option(s) for reading files: * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps in the JSON/CSV datasources or partition values...
Adds input options for the underlying data source. You can set the following option(s) for reading files: * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps in the JSON/CSV datasources or partition values. If it isn't set, it use...
def copy(self, filename, id_=-1, pre_callback=None, post_callback=None): """Copy a package or script to all repos. Determines appropriate location (for file shares) and type based on file extension. Args: filename: String path to the local file to copy. id_: Pac...
Copy a package or script to all repos. Determines appropriate location (for file shares) and type based on file extension. Args: filename: String path to the local file to copy. id_: Package or Script object ID to target. For use with JDS and CDP DP's on...
def authenticate(cmd_args, endpoint='', force=False): """Returns an OAuth token that can be passed to the server for identification. If FORCE is False, it will attempt to use a cached token or refresh the OAuth token. """ server = server_url(cmd_args) network.check_ssl() access_token = None ...
Returns an OAuth token that can be passed to the server for identification. If FORCE is False, it will attempt to use a cached token or refresh the OAuth token.
def gps_0(self): """ GPS position information (:py:class:`GPSInfo`). """ return GPSInfo(self._eph, self._epv, self._fix_type, self._satellites_visible)
GPS position information (:py:class:`GPSInfo`).
def _next_dir_gen(self, root): """Generator for next directory element in the document. Args: root: root element in the XML tree. Yields: GCSFileStat for the next directory. """ for e in root.getiterator(common._T_COMMON_PREFIXES): yield common.GCSFileStat( self._path +...
Generator for next directory element in the document. Args: root: root element in the XML tree. Yields: GCSFileStat for the next directory.
def cell(self, row_idx, col_idx): """Return cell at *row_idx*, *col_idx*. Return value is an instance of |_Cell|. *row_idx* and *col_idx* are zero-based, e.g. cell(0, 0) is the top, left cell in the table. """ return _Cell(self._tbl.tc(row_idx, col_idx), self)
Return cell at *row_idx*, *col_idx*. Return value is an instance of |_Cell|. *row_idx* and *col_idx* are zero-based, e.g. cell(0, 0) is the top, left cell in the table.
def individuals(self, ind_ids=None): """Return information about individuals Args: ind_ids (list(str)): List of individual ids Returns: individuals (Iterable): Iterable with Individuals """ if ind_ids: for ...
Return information about individuals Args: ind_ids (list(str)): List of individual ids Returns: individuals (Iterable): Iterable with Individuals
def write(self, handle): '''Write metadata and point + analog frames to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. ''' if not self._frames...
Write metadata and point + analog frames to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle.
def run(**options): """ _run_ Run the dockerstache process to render templates based on the options provided If extend_context is passed as options it will be used to extend the context with the contents of the dictionary provided via context.update(extend_context) """ with Dotfil...
_run_ Run the dockerstache process to render templates based on the options provided If extend_context is passed as options it will be used to extend the context with the contents of the dictionary provided via context.update(extend_context)
async def get_status(self, filters=None, utc=False): """Return the status of the model. :param str filters: Optional list of applications, units, or machines to include, which can use wildcards ('*'). :param bool utc: Display time as UTC in RFC3339 format """ client...
Return the status of the model. :param str filters: Optional list of applications, units, or machines to include, which can use wildcards ('*'). :param bool utc: Display time as UTC in RFC3339 format
def pad_shape_right_with_ones(x, ndims): """Maybe add `ndims` ones to `x.shape` on the right. If `ndims` is zero, this is a no-op; otherwise, we will create and return a new `Tensor` whose shape is that of `x` with `ndims` ones concatenated on the right side. If the shape of `x` is known statically, the shape ...
Maybe add `ndims` ones to `x.shape` on the right. If `ndims` is zero, this is a no-op; otherwise, we will create and return a new `Tensor` whose shape is that of `x` with `ndims` ones concatenated on the right side. If the shape of `x` is known statically, the shape of the return value will be as well. Args...
def get(self, sid): """ Constructs a CredentialListContext :param sid: Fetch by unique credential list Sid :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext "...
Constructs a CredentialListContext :param sid: Fetch by unique credential list Sid :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext
def fields2jsonschema(self, fields, schema=None, use_refs=True, dump=True, name=None): """Return the JSON Schema Object for a given marshmallow :class:`Schema <marshmallow.Schema>`. Schema may optionally provide the ``title`` and ``description`` class Meta options. https://github.com/OA...
Return the JSON Schema Object for a given marshmallow :class:`Schema <marshmallow.Schema>`. Schema may optionally provide the ``title`` and ``description`` class Meta options. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject Example: :: ...
def parser(): """Return search query parser.""" query_parser = current_app.config['COLLECTIONS_QUERY_PARSER'] if isinstance(query_parser, six.string_types): query_parser = import_string(query_parser) return query_parser
Return search query parser.
def _really_start_hb(self): """callback for delayed heartbeat start Only start the hb loop if we haven't been closed during the wait. """ if self._beating and not self.hb_stream.closed(): self._hb_periodic_callback.start()
callback for delayed heartbeat start Only start the hb loop if we haven't been closed during the wait.
def find_permission_view_menu(self, permission_name, view_menu_name): """ Finds and returns a PermissionView by names """ permission = self.find_permission(permission_name) view_menu = self.find_view_menu(view_menu_name) if permission and view_menu: return...
Finds and returns a PermissionView by names
def format(self, exclude_class=False): """Format this exception as a string including class name. Args: exclude_class (bool): Whether to exclude the exception class name when formatting this exception Returns: string: a multiline string with the message,...
Format this exception as a string including class name. Args: exclude_class (bool): Whether to exclude the exception class name when formatting this exception Returns: string: a multiline string with the message, class name and key value paramete...
def _load_data(self, group, record_offset=0, record_count=None): """ get group's data block bytes""" has_yielded = False offset = 0 _count = record_count channel_group = group.channel_group if group.data_location == v23c.LOCATION_ORIGINAL_FILE: # go to the fi...
get group's data block bytes
def detect_phantomjs(version='2.1'): ''' Detect if PhantomJS is avaiable in PATH, at a minimum version. Args: version (str, optional) : Required minimum version for PhantomJS (mostly for testing) Returns: str, path to PhantomJS ''' if settings.phantomjs_path() is not N...
Detect if PhantomJS is avaiable in PATH, at a minimum version. Args: version (str, optional) : Required minimum version for PhantomJS (mostly for testing) Returns: str, path to PhantomJS
def variable_map_items(variable_map): """Yields an iterator over (string, variable) pairs in the variable map. In general, variable maps map variable names to either a `tf.Variable`, or list of `tf.Variable`s (in case of sliced variables). Args: variable_map: dict, variable map over which to iterate. Y...
Yields an iterator over (string, variable) pairs in the variable map. In general, variable maps map variable names to either a `tf.Variable`, or list of `tf.Variable`s (in case of sliced variables). Args: variable_map: dict, variable map over which to iterate. Yields: (string, tf.Variable) pairs.
def _add_mac_token(self, uri, http_method='GET', body=None, headers=None, token_placement=AUTH_HEADER, ext=None, **kwargs): """Add a MAC token to the request authorization header. Warning: MAC token support is experimental as the spec is not yet stable. """ if tok...
Add a MAC token to the request authorization header. Warning: MAC token support is experimental as the spec is not yet stable.
def do_one_iteration(self): """step eventloop just once""" if self.control_stream: self.control_stream.flush() for stream in self.shell_streams: # handle at most one request per iteration stream.flush(zmq.POLLIN, 1) stream.flush(zmq.POLLOUT)
step eventloop just once
def list_installed(): ''' Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed ''' result = __salt__['pkg.version'](_package_name(), versions_as_list=True) if result is None: return [] if six.PY2: return s...
Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed
def check_cv(cv=3, y=None, classifier=False): """Dask aware version of ``sklearn.model_selection.check_cv`` Same as the scikit-learn version, but works if ``y`` is a dask object. """ if cv is None: cv = 3 # If ``cv`` is not an integer, the scikit-learn implementation doesn't # touch th...
Dask aware version of ``sklearn.model_selection.check_cv`` Same as the scikit-learn version, but works if ``y`` is a dask object.
def is_period_arraylike(arr): """ Check whether an array-like is a periodical array-like or PeriodIndex. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a periodical array-like or PeriodInd...
Check whether an array-like is a periodical array-like or PeriodIndex. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a periodical array-like or PeriodIndex instance. Examples -------- ...
def identify_protocol(method, value): # type: (str, Union[str, RequestType]) -> str """ Loop through protocols, import the protocol module and try to identify the id or request. """ for protocol_name in PROTOCOLS: protocol = importlib.import_module(f"federation.protocols.{protocol_name}.prot...
Loop through protocols, import the protocol module and try to identify the id or request.
def blackbox_and_coarse_grain(blackbox, coarse_grain): """Validate that a coarse-graining properly combines the outputs of a blackboxing. """ if blackbox is None: return for box in blackbox.partition: # Outputs of the box outputs = set(box) & set(blackbox.output_indices) ...
Validate that a coarse-graining properly combines the outputs of a blackboxing.
def _handle_utf8_payload(body, properties): """Update the Body and Properties to the appropriate encoding. :param bytes|str|unicode body: Message payload :param dict properties: Message properties :return: """ if 'content_encoding' not in properties: propert...
Update the Body and Properties to the appropriate encoding. :param bytes|str|unicode body: Message payload :param dict properties: Message properties :return:
def schur_complement(mat, row, col): """ compute the schur complement of the matrix block mat[row:,col:] of the matrix mat """ a = mat[:row, :col] b = mat[:row, col:] c = mat[row:, :col] d = mat[row:, col:] return a - b.dot(d.I).dot(c)
compute the schur complement of the matrix block mat[row:,col:] of the matrix mat
def append_op(self, operation): """Append an :class:`Operation <stellar_base.operation.Operation>` to the list of operations. Add the operation specified if it doesn't already exist in the list of operations of this :class:`Builder` instance. :param operation: The operation to ...
Append an :class:`Operation <stellar_base.operation.Operation>` to the list of operations. Add the operation specified if it doesn't already exist in the list of operations of this :class:`Builder` instance. :param operation: The operation to append to the list of operations. :...
def count_names_by_namespace(graph, namespace): """Get the set of all of the names in a given namespace that are in the graph. :param pybel.BELGraph graph: A BEL graph :param str namespace: A namespace keyword :return: A counter from {name: frequency} :rtype: collections.Counter :raises IndexE...
Get the set of all of the names in a given namespace that are in the graph. :param pybel.BELGraph graph: A BEL graph :param str namespace: A namespace keyword :return: A counter from {name: frequency} :rtype: collections.Counter :raises IndexError: if the namespace is not defined in the graph.
def deleteThreads(self, thread_ids): """ Deletes threads :param thread_ids: Thread IDs to delete. See :ref:`intro_threads` :return: Whether the request was successful :raises: FBchatException if request failed """ thread_ids = require_list(thread_ids) da...
Deletes threads :param thread_ids: Thread IDs to delete. See :ref:`intro_threads` :return: Whether the request was successful :raises: FBchatException if request failed
def logout(self): """ Logout and remove vid """ response = None try: response = requests.delete( urls.login(), headers={ 'Cookie': 'vid={}'.format(self._vid)}) except requests.exceptions.RequestException as ex: r...
Logout and remove vid