code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def A_multiple_hole_cylinder(Do, L, holes):
r'''Returns the surface area of a cylinder with multiple holes.
Calculation will naively return a negative value or other impossible
result if the number of cylinders added is physically impossible.
Holes may be of different shapes, but must be perpendicular t... | r'''Returns the surface area of a cylinder with multiple holes.
Calculation will naively return a negative value or other impossible
result if the number of cylinders added is physically impossible.
Holes may be of different shapes, but must be perpendicular to the
axis of the cylinder.
.. math::
... |
def project_gdf(gdf, to_crs=None, to_latlong=False):
"""
Project a GeoDataFrame to the UTM zone appropriate for its geometries'
centroid.
The simple calculation in this function works well for most latitudes, but
won't work for some far northern locations like Svalbard and parts of far
northern... | Project a GeoDataFrame to the UTM zone appropriate for its geometries'
centroid.
The simple calculation in this function works well for most latitudes, but
won't work for some far northern locations like Svalbard and parts of far
northern Norway.
Parameters
----------
gdf : GeoDataFrame
... |
def dqdv_cycles(cycles, **kwargs):
"""Convenience functions for creating dq-dv data from given capacity and
voltage cycles.
Returns a DataFrame with a 'voltage' and a 'incremental_capacity'
column.
Args:
cycles (pandas.DataFrame): the cycle data ('cycle', 'voltage',
... | Convenience functions for creating dq-dv data from given capacity and
voltage cycles.
Returns a DataFrame with a 'voltage' and a 'incremental_capacity'
column.
Args:
cycles (pandas.DataFrame): the cycle data ('cycle', 'voltage',
'capacity', 'direction' (1 or -1)).
... |
def _remove_header(self, data, options):
'''Remove header from data'''
version_info = self._get_version_info(options['version'])
header_size = version_info['header_size']
if options['flags']['timestamp']:
header_size += version_info['timestamp_size']
data = data[he... | Remove header from data |
def body(self):
"""Returns the HTTP response body, deserialized if possible.
:rtype: mixed
"""
if not self._responses:
return None
if self._responses[-1].code >= 400:
return self._error_message()
return self._deserialize() | Returns the HTTP response body, deserialized if possible.
:rtype: mixed |
def _matches(self, entities=None, extensions=None, domains=None,
regex_search=False):
"""
Checks whether the file matches all of the passed entities and
extensions.
Args:
entities (dict): A dictionary of entity names -> regex patterns.
extensions... | Checks whether the file matches all of the passed entities and
extensions.
Args:
entities (dict): A dictionary of entity names -> regex patterns.
extensions (str, list): One or more file extensions to allow.
domains (str, list): One or more domains the file must matc... |
def set_value(file, element, value):
'''
Sets the value of the matched xpath element
CLI Example:
.. code-block:: bash
salt '*' xml.set_value /tmp/test.xml ".//element" "new value"
'''
try:
root = ET.parse(file)
relement = root.find(element)
except AttributeError:
... | Sets the value of the matched xpath element
CLI Example:
.. code-block:: bash
salt '*' xml.set_value /tmp/test.xml ".//element" "new value" |
def get_commit_date(commit, tz_name):
'''
Get datetime of commit comitted_date
'''
return set_date_tzinfo(
datetime.fromtimestamp(mktime(commit.committed_date)),
tz_name=tz_name) | Get datetime of commit comitted_date |
def calculate_variable(self, variable = None, period = None, use_baseline = False):
"""
Compute and return the variable values for period and baseline or reform tax_benefit_system
"""
if use_baseline:
assert self.baseline_simulation is not None, "self.baseline_simulation is N... | Compute and return the variable values for period and baseline or reform tax_benefit_system |
def get_host_ipv6addr_info(ipv6addr=None, mac=None,
discovered_data=None,
return_fields=None, **api_opts):
'''
Get host ipv6addr information
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_ipv6addr_i... | Get host ipv6addr information
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 |
def __step4(self):
"""
Find a noncovered zero and prime it. If there is no starred zero
in the row containing this primed zero, Go to Step 5. Otherwise,
cover this row and uncover the column containing the starred
zero. Continue in this manner until there are no uncovered zeros
... | Find a noncovered zero and prime it. If there is no starred zero
in the row containing this primed zero, Go to Step 5. Otherwise,
cover this row and uncover the column containing the starred
zero. Continue in this manner until there are no uncovered zeros
left. Save the smallest uncovere... |
def clear_mpi_env_vars():
"""
from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.
This context manager is a hacky way to clear those environment... | from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.
This context manager is a hacky way to clear those environment variables temporarily such as when we... |
def sort_languages(self, order=Qt.AscendingOrder):
"""
Sorts the Model languages.
:param order: Order. ( Qt.SortOrder )
"""
self.beginResetModel()
self.__languages = sorted(self.__languages, key=lambda x: (x.name), reverse=order)
self.endResetModel() | Sorts the Model languages.
:param order: Order. ( Qt.SortOrder ) |
def _close(self, id):
"""
Respond to a CLOSE command, dumping some data onto the stream. As with
WRITE, this returns an empty acknowledgement.
An occurrence of I{Close} on the wire, together with the response
generated by this method, might have this apperance::
C:... | Respond to a CLOSE command, dumping some data onto the stream. As with
WRITE, this returns an empty acknowledgement.
An occurrence of I{Close} on the wire, together with the response
generated by this method, might have this apperance::
C: -Command: Close
C: -Ask: 1
... |
def make_url_fetcher(dispatcher=None,
next_fetcher=weasyprint.default_url_fetcher):
"""Return an function suitable as a ``url_fetcher`` in WeasyPrint.
You generally don’t need to call this directly.
If ``dispatcher`` is not provided, :func:`make_flask_url_dispatcher`
is called to ... | Return an function suitable as a ``url_fetcher`` in WeasyPrint.
You generally don’t need to call this directly.
If ``dispatcher`` is not provided, :func:`make_flask_url_dispatcher`
is called to get one. This requires a request context.
Otherwise, it must be a callable that take an URL and return eith... |
def output(self,delimiter = '\t', freqlist = None):
"""Generator yielding formatted strings expressing the time and probabily for each item in the distribution"""
for type, prob in self:
if freqlist:
if isinstance(type,list) or isinstance(type, tuple):
yie... | Generator yielding formatted strings expressing the time and probabily for each item in the distribution |
def IsPathSuffix(mod_path, path):
"""Checks whether path is a full path suffix of mod_path.
Args:
mod_path: Must be an absolute path to a source file. Must not have
file extension.
path: A relative path. Must not have file extension.
Returns:
True if path is a full path suffix of mod_p... | Checks whether path is a full path suffix of mod_path.
Args:
mod_path: Must be an absolute path to a source file. Must not have
file extension.
path: A relative path. Must not have file extension.
Returns:
True if path is a full path suffix of mod_path. False otherwise. |
def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]:
"""Parse all dependencies out of the requirements.txt file."""
essential_packages: PackagesType = {}
other_packages: PackagesType = {}
duplicates: Set[str] = set()
with open("requirements.txt", "r") as req_file:
section... | Parse all dependencies out of the requirements.txt file. |
def services(self):
"""
Gets the services object which will provide the ArcGIS Server's
admin information about services and folders.
"""
if self._resources is None:
self.__init()
if "services" in self._resources:
url = self._url + "/services"
... | Gets the services object which will provide the ArcGIS Server's
admin information about services and folders. |
def compute(self, sensorToBodyByColumn, sensorToSpecificObjectByColumn):
"""
Compute the
"body's location relative to a specific object"
from an array of
"sensor's location relative to a specific object"
and an array of
"sensor's location relative to body"
These arrays consist of ... | Compute the
"body's location relative to a specific object"
from an array of
"sensor's location relative to a specific object"
and an array of
"sensor's location relative to body"
These arrays consist of one module per cortical column.
This is a metric computation, similar to that of... |
def choices(self):
"""Available choices for characters to be generated."""
if self._choices:
return self._choices
for n in os.listdir(self._voicedir):
if len(n) == 1 and os.path.isdir(os.path.join(self._voicedir, n)):
self._choices.append(n)
return... | Available choices for characters to be generated. |
def swagger_schema(self, request):
"""Render API Schema."""
if self.parent is None:
return {}
spec = APISpec(
self.parent.name, self.parent.cfg.get('VERSION', ''),
plugins=['apispec.ext.marshmallow'], basePatch=self.prefix
)
for paths, handle... | Render API Schema. |
def pos(self):
''' Tries to decide about the part of speech. '''
tags = []
if self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()'):
info = self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()')[0]
if info == 'Substantiv':
tags.append('NN')
if i... | Tries to decide about the part of speech. |
def init(db_url, alembic_ini=None, debug=False, create=False):
""" Create the tables in the database using the information from the
url obtained.
:arg db_url, URL used to connect to the database. The URL contains
information with regards to the database engine, the host to
connect to, the u... | Create the tables in the database using the information from the
url obtained.
:arg db_url, URL used to connect to the database. The URL contains
information with regards to the database engine, the host to
connect to, the user and password and the database name.
ie: <engine>://<user>... |
def get_canonical_request(self, req, cano_headers, signed_headers):
"""
Create the AWS authentication Canonical Request string.
req -- Requests PreparedRequest object. Should already
include an x-amz-content-sha256 header
cano_headers -- Canonical ... | Create the AWS authentication Canonical Request string.
req -- Requests PreparedRequest object. Should already
include an x-amz-content-sha256 header
cano_headers -- Canonical Headers section of Canonical Request, as
returned by get_canon... |
def create_collection(self, name):
"""Create a new collection as member of self.
See DAVResource.create_collection()
"""
assert "/" not in name
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
path = util.join_uri(self.path, name)
fp = self.p... | Create a new collection as member of self.
See DAVResource.create_collection() |
def get_local_config_file(cls, filename):
"""Find local file to setup default values.
There is a pre-fixed logic on how the search of the configuration
file is performed. If the highes priority configuration file is found,
there is no need to search for the next. From highest to lowest
... | Find local file to setup default values.
There is a pre-fixed logic on how the search of the configuration
file is performed. If the highes priority configuration file is found,
there is no need to search for the next. From highest to lowest
priority:
1. **Local:** Configuratio... |
def mode_key_up(self, viewer, keyname):
"""This method is called when a key is pressed in a mode and was
not handled by some other handler with precedence, such as a
subcanvas.
"""
# Is this a mode key?
if keyname not in self.mode_map:
# <== no
ret... | This method is called when a key is pressed in a mode and was
not handled by some other handler with precedence, such as a
subcanvas. |
def set_backend(backend_name: str):
"""Sets backend (local or aws)"""
global _backend, _backend_name
_backend_name = backend_name
assert not ncluster_globals.task_launched, "Not allowed to change backend after launching a task (this pattern is error-prone)"
if backend_name == 'aws':
_backend = aws_backen... | Sets backend (local or aws) |
def imrescale(img, scale, return_scale=False, interpolation='bilinear'):
"""Resize image while keeping the aspect ratio.
Args:
img (ndarray): The input image.
scale (float or tuple[int]): The scaling factor or maximum size.
If it is a float number, then the image will be rescaled by... | Resize image while keeping the aspect ratio.
Args:
img (ndarray): The input image.
scale (float or tuple[int]): The scaling factor or maximum size.
If it is a float number, then the image will be rescaled by this
factor, else if it is a tuple of 2 integers, then the image wi... |
def get_courses_in_account(self, account_id, params={}):
"""
Returns a list of courses for the passed account ID.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.courses_api
"""
if "published" in params:
params["published"] = "true" if params["pu... | Returns a list of courses for the passed account ID.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.courses_api |
def run(bam_file, data, out_dir):
""" Run SignatureGenerator to create normalize vcf that later will be input of qsignature_summary
:param bam_file: (str) path of the bam_file
:param data: (list) list containing the all the dictionary
for this sample
:param out_dir: (str) path of t... | Run SignatureGenerator to create normalize vcf that later will be input of qsignature_summary
:param bam_file: (str) path of the bam_file
:param data: (list) list containing the all the dictionary
for this sample
:param out_dir: (str) path of the output
:returns: (string) output n... |
def xpathContextSetCache(self, active, value, options):
"""Creates/frees an object cache on the XPath context. If
activates XPath objects (xmlXPathObject) will be cached
internally to be reused. @options: 0: This will set the
XPath object caching: @value: This will set the maximum
... | Creates/frees an object cache on the XPath context. If
activates XPath objects (xmlXPathObject) will be cached
internally to be reused. @options: 0: This will set the
XPath object caching: @value: This will set the maximum
number of XPath objects to be cached per slot There are 5... |
def parse(string, is_file=False, obj=False):
""" Convert a JSON string to dict/object """
try:
if obj is False:
if is_file:
return system_json.load(string)
return system_json.loads(string, encoding='utf8')
else:
... | Convert a JSON string to dict/object |
def from_requirement(cls, provider, requirement, parent):
"""Build an instance from a requirement.
"""
candidates = provider.find_matches(requirement)
if not candidates:
raise NoVersionsAvailable(requirement, parent)
return cls(
candidates=candidates,
... | Build an instance from a requirement. |
def get_chat_administrators(self, *args, **kwargs):
"""See :func:`get_chat_administrators`"""
return get_chat_administrators(*args, **self._merge_overrides(**kwargs)).run() | See :func:`get_chat_administrators` |
def _run_listeners(self, line):
"""
Each listener's associated regular expression is matched against raw IRC
input. If there is a match, the listener's associated function is called
with all the regular expression's matched subgroups.
"""
for regex, callbacks in self.list... | Each listener's associated regular expression is matched against raw IRC
input. If there is a match, the listener's associated function is called
with all the regular expression's matched subgroups. |
def ipfn_df(self, df, aggregates, dimensions, weight_col='total'):
"""
Runs the ipfn method from a dataframe df, aggregates/marginals and the dimension(s) preserved.
For example:
from ipfn import ipfn
import pandas as pd
age = [30, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, ... | Runs the ipfn method from a dataframe df, aggregates/marginals and the dimension(s) preserved.
For example:
from ipfn import ipfn
import pandas as pd
age = [30, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50]
distance = [10,20,30,40,10,20,30,40,10,20,30,40]
m = [8., 4., 6., 7... |
def edit_distance_matrix(train_x, train_y=None):
"""Calculate the edit distance.
Args:
train_x: A list of neural architectures.
train_y: A list of neural architectures.
Returns:
An edit-distance matrix.
"""
if train_y is None:
ret = np.zeros((train_x.shape[0], train_x... | Calculate the edit distance.
Args:
train_x: A list of neural architectures.
train_y: A list of neural architectures.
Returns:
An edit-distance matrix. |
def transfer(self, transfer_payload=None, *, from_user, to_user):
"""Transfer this entity to another owner on the backing
persistence layer
Args:
transfer_payload (dict): Payload for the transfer
from_user (any): A user based on the model specified by the
... | Transfer this entity to another owner on the backing
persistence layer
Args:
transfer_payload (dict): Payload for the transfer
from_user (any): A user based on the model specified by the
persistence layer
to_user (any): A user based on the model speci... |
def __findFirstMissing(self, array, start, end):
"""
Find the smallest elements missing in a sorted array.
Returns:
int: The smallest element missing.
"""
if (start > end):
return end + 1
if (start != array[start]):
return start
... | Find the smallest elements missing in a sorted array.
Returns:
int: The smallest element missing. |
def colored(cls, color, message):
"""
Small function to wrap a string around a color
Args:
color (str): name of the color to wrap the string with, must be one
of the class properties
message (str): String to wrap with the color
Returns:
... | Small function to wrap a string around a color
Args:
color (str): name of the color to wrap the string with, must be one
of the class properties
message (str): String to wrap with the color
Returns:
str: the colored string |
def _raw_to_der(self, raw_signature):
"""Convert signature from RAW encoding to DER encoding."""
component_length = self._sig_component_length()
if len(raw_signature) != int(2 * component_length):
raise ValueError("Invalid signature")
r_bytes = raw_signature[:component_lengt... | Convert signature from RAW encoding to DER encoding. |
def _pick_selected_option(cls):
"""
Select handler for authors.
"""
for option in cls.select_el:
# if the select is empty
if not hasattr(option, "selected"):
return None
if option.selected:
return option.value
... | Select handler for authors. |
def cublasCher2k(handle, uplo, trans, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Rank-2k operation on Hermitian matrix.
"""
status = _libcublas.cublasCher2k_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],... | Rank-2k operation on Hermitian matrix. |
def _overwrite_special_dates(midnight_utcs,
opens_or_closes,
special_opens_or_closes):
"""
Overwrite dates in open_or_closes with corresponding dates in
special_opens_or_closes, using midnight_utcs for alignment.
"""
# Short circuit when noth... | Overwrite dates in open_or_closes with corresponding dates in
special_opens_or_closes, using midnight_utcs for alignment. |
def establish(self, call_id, timeout, limit=None,
retry=None, max_retries=None):
"""Waits for the call is accepted by workers and starts to collect the
results.
"""
rejected = 0
retried = 0
results = []
result_queue = self.result_queues[call_id]
... | Waits for the call is accepted by workers and starts to collect the
results. |
def from_schema(cls, schema, *args, **kwargs):
"""
Construct a resolver from a JSON schema object.
:argument schema schema: the referring schema
:rtype: :class:`RefResolver`
"""
return cls(schema.get(u"id", u""), schema, *args, **kwargs) | Construct a resolver from a JSON schema object.
:argument schema schema: the referring schema
:rtype: :class:`RefResolver` |
def whoami(self) -> dict:
"""Returns the basic information about the authenticated character.
Obviously doesn't do anything if this Preston instance is not
authenticated, so it returns an empty dict.
Args:
None
Returns:
character info if authenticated, ... | Returns the basic information about the authenticated character.
Obviously doesn't do anything if this Preston instance is not
authenticated, so it returns an empty dict.
Args:
None
Returns:
character info if authenticated, otherwise an empty dict |
def _set_axis_position(self, axes, axis, option):
"""
Set the position and visibility of the xaxis or yaxis by
supplying the axes object, the axis to set, i.e. 'x' or 'y'
and an option to specify the position and visibility of the axis.
The option may be None, 'bare' or positiona... | Set the position and visibility of the xaxis or yaxis by
supplying the axes object, the axis to set, i.e. 'x' or 'y'
and an option to specify the position and visibility of the axis.
The option may be None, 'bare' or positional, i.e. 'left' and
'right' for the yaxis and 'top' and 'bottom... |
def hwpack_names():
"""return installed hardware package names."""
ls = hwpack_dir().listdir()
ls = [x.name for x in ls]
ls = [x for x in ls if x != 'tools']
arduino_included = 'arduino' in ls
ls = [x for x in ls if x != 'arduino']
ls.sort()
if arduino_included:
ls = ['arduino'] ... | return installed hardware package names. |
def stream(self):
"""Which stream, if any, the client is under"""
stream = self._p4dict.get('stream')
if stream:
return Stream(stream, self._connection) | Which stream, if any, the client is under |
def updateObj(self, event):
"""Put this object in the search box"""
name = self.objList.get("active")
self.SearchVar.set(name)
self.object_info.set(str(self.kbos.get(name, '')))
return | Put this object in the search box |
def _checkJobGraphAcylicDFS(self, stack, visited, extraEdges):
"""
DFS traversal to detect cycles in augmented job graph.
"""
if self not in visited:
visited.add(self)
stack.append(self)
for successor in self._children + self._followOns + extraEdges[se... | DFS traversal to detect cycles in augmented job graph. |
def request(self, host, handler, request_body, verbose):
'''Send xml-rpc request using proxy'''
#We get a traceback if we don't have this attribute:
self.verbose = verbose
url = 'http://' + host + handler
request = urllib2.Request(url)
request.add_data(request_body)
... | Send xml-rpc request using proxy |
def clear_lock(remote=None):
'''
Clear update.lk
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked.
'''
def _do_clear_lock(repo):
def _add_error(errlist, rep... | Clear update.lk
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked. |
def process_result(self, raw_result):
"""
Performs actions on the raw result from the XML-RPC response.
If a `results_class` is defined, the response will be converted
into one or more object instances of that class.
"""
if self.results_class and raw_result:
... | Performs actions on the raw result from the XML-RPC response.
If a `results_class` is defined, the response will be converted
into one or more object instances of that class. |
def check_validity(self):
""""Raise error if any invalid attribute found."""
# pianoroll
if not isinstance(self.pianoroll, np.ndarray):
raise TypeError("`pianoroll` must be a numpy array.")
if not (np.issubdtype(self.pianoroll.dtype, np.bool_)
or np.issubdtype... | Raise error if any invalid attribute found. |
def up(self,x,L_change = 12):
"""
Upsample and filter the signal
"""
y = L_change*ssd.upsample(x,L_change)
y = signal.sosfilt(self.sos,y)
return y | Upsample and filter the signal |
def get_phi_ss(imt, mag, params):
"""
Returns the single station phi (or it's variance) for a given magnitude
and intensity measure type according to equation 5.14 of Al Atik (2015)
"""
C = params[imt]
if mag <= 5.0:
phi = C["a"]
elif mag > 6.5:
phi = C["b"]
else:
... | Returns the single station phi (or it's variance) for a given magnitude
and intensity measure type according to equation 5.14 of Al Atik (2015) |
def remove_attribute(self, ont_id: str, operator: Account, attrib_key: str, payer: Account, gas_limit: int,
gas_price: int):
"""
This interface is used to send a Transaction object which is used to remove attribute.
:param ont_id: OntId.
:param operator: an Acco... | This interface is used to send a Transaction object which is used to remove attribute.
:param ont_id: OntId.
:param operator: an Account object which indicate who will sign for the transaction.
:param attrib_key: a string which is used to indicate which attribute we want to remove.
:par... |
def copy(self,*args,**kwargs):
'''
Returns a copy of the current data object
:param flag: if an argument is provided, this returns an updated copy of current object (ie. equivalent to obj.copy();obj.update(flag)), optimising the memory (
:keyword True deep: deep copies the ... | Returns a copy of the current data object
:param flag: if an argument is provided, this returns an updated copy of current object (ie. equivalent to obj.copy();obj.update(flag)), optimising the memory (
:keyword True deep: deep copies the object (object data will be copied as well). |
def filter_queryset(self, value, queryset):
"""
Filter the queryset to all instances matching the given attribute.
"""
filter_kwargs = {self.field_name: value}
return queryset.filter(**filter_kwargs) | Filter the queryset to all instances matching the given attribute. |
def download(url: str, filename: str,
skip_cert_verify: bool = True) -> None:
"""
Downloads a URL to a file.
Args:
url: URL to download from
filename: file to save to
skip_cert_verify: skip SSL certificate check?
"""
log.info("Downloading from {} to {}", url, fi... | Downloads a URL to a file.
Args:
url: URL to download from
filename: file to save to
skip_cert_verify: skip SSL certificate check? |
def make_save_locals_impl():
"""
Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at
module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger
... | Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at
module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger
lock being taken in different order in d... |
def get_child_objective_banks(self, objective_bank_id):
"""Gets the children of the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` to query
return: (osid.learning.ObjectiveBankList) - the children of the
objective bank
raise: NotFound - ``objec... | Gets the children of the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` to query
return: (osid.learning.ObjectiveBankList) - the children of the
objective bank
raise: NotFound - ``objective_bank_id`` is not found
raise: NullArgument - ``object... |
def toString(self, format_='fasta-ss', structureSuffix=':structure'):
"""
Convert the read to a string in PDB format (sequence & structure). This
consists of two FASTA records, one for the sequence then one for the
structure.
@param format_: Either 'fasta-ss' or 'fasta'. In the ... | Convert the read to a string in PDB format (sequence & structure). This
consists of two FASTA records, one for the sequence then one for the
structure.
@param format_: Either 'fasta-ss' or 'fasta'. In the former case, the
structure information is returned. Otherwise, plain FASTA is
... |
def add_type(type_, func=None):
"""
Adds a custom type to L{TYPE_MAP}. A custom type allows fine grain control
of what to encode to an AMF data stream.
@raise TypeError: Unable to add as a custom type (expected a class or callable).
@raise KeyError: Type already exists.
@see: L{get_type} and L{... | Adds a custom type to L{TYPE_MAP}. A custom type allows fine grain control
of what to encode to an AMF data stream.
@raise TypeError: Unable to add as a custom type (expected a class or callable).
@raise KeyError: Type already exists.
@see: L{get_type} and L{remove_type} |
def is_zero_user(self):
"""返回当前用户是否为三零用户,其实是四零: 赞同0,感谢0,提问0,回答0.
:return: 是否是三零用户
:rtype: bool
"""
return self.upvote_num + self.thank_num + \
self.question_num + self.answer_num == 0 | 返回当前用户是否为三零用户,其实是四零: 赞同0,感谢0,提问0,回答0.
:return: 是否是三零用户
:rtype: bool |
def is_entailed_by(self, other):
"""
Means merging other with self does not produce any new information.
"""
if not set(self.include.keys()).issubset(set(other.include.keys())):
return False
if not self.exclude.isuperset(other.exclude):
return False
... | Means merging other with self does not produce any new information. |
def _read_multiline(self, init_data):
"""Reads multiline symbols (ususally comments)
:param init_data: initial data (parsed from the line containing keyword)
:return: parsed value of the multiline symbol
:rtype: str
"""
result = init_data
first = True
wh... | Reads multiline symbols (ususally comments)
:param init_data: initial data (parsed from the line containing keyword)
:return: parsed value of the multiline symbol
:rtype: str |
def get_title (self):
"""Return title of page the URL refers to.
This is per default the filename or the URL."""
if self.title is None:
url = u""
if self.base_url:
url = self.base_url
elif self.url:
url = self.url
se... | Return title of page the URL refers to.
This is per default the filename or the URL. |
def cleanup(self):
"""cleanup configuration: stop and remove all servers"""
for _id, shard in self._shards.items():
if shard.get('isServer', False):
Servers().remove(shard['_id'])
if shard.get('isReplicaSet', False):
ReplicaSets().remove(shard['_id... | cleanup configuration: stop and remove all servers |
def listModules(self):
"""Return an alphabetical list of all modules."""
modules = list(self.modules.items())
modules.sort()
return [module for name, module in modules] | Return an alphabetical list of all modules. |
def _bnot16(ins):
''' Negates top (Bitwise NOT) of the stack (16 bits in HL)
'''
output = _16bit_oper(ins.quad[2])
output.append('call __BNOT16')
output.append('push hl')
REQUIRES.add('bnot16.asm')
return output | Negates top (Bitwise NOT) of the stack (16 bits in HL) |
def find_and_patch_entry(soup, entry):
"""
Modify soup so Dash.app can generate TOCs on the fly.
"""
link = soup.find("a", {"class": "headerlink"}, href="#" + entry.anchor)
tag = soup.new_tag("a")
tag["name"] = APPLE_REF_TEMPLATE.format(entry.type, entry.name)
if link:
link.parent.in... | Modify soup so Dash.app can generate TOCs on the fly. |
def _handleAnonymousEvents(self, component, action, data, client):
"""Handler for anonymous (public) events"""
try:
event = self.anonymous_events[component][action]['event']
self.log("Firing anonymous event: ", component, action,
str(data)[:20], lvl=network)... | Handler for anonymous (public) events |
def _make_git(config_info):
"""This function initializes and Git SCM tool object."""
git_args = {}
def _add_value(value, key):
args_key, args_value = _GIT_ARG_FNS[key](value)
git_args[args_key] = args_value
devpipeline_core.toolsupport.args_builder("git", config_info, _GIT_ARGS, _add_v... | This function initializes and Git SCM tool object. |
def baseglob(pat, base):
"""Given a pattern and a base, return files that match the glob pattern
and also contain the base."""
return [f for f in glob(pat) if f.startswith(base)] | Given a pattern and a base, return files that match the glob pattern
and also contain the base. |
def prefix_dirs(path):
"""
Return an iterable of all prefix directories of path, descending from root.
"""
_dirname = posixpath.dirname
path = path.strip('/')
out = []
while path != '':
path = _dirname(path)
out.append(path)
return reversed(out) | Return an iterable of all prefix directories of path, descending from root. |
def focus_right(pymux):
" Move focus to the right. "
_move_focus(pymux,
lambda wp: wp.xpos + wp.width + 1,
lambda wp: wp.ypos) | Move focus to the right. |
def mode(series):
"""
pandas mode is "empty if nothing has 2+ occurrences."
this method always returns something:
nan if the series is empty/nan), breaking ties arbitrarily
"""
if series.notnull().sum() == 0:
return np.nan
else:
return series.value_counts().idxmax() | pandas mode is "empty if nothing has 2+ occurrences."
this method always returns something:
nan if the series is empty/nan), breaking ties arbitrarily |
def send(command, data):
"""Send command to Training Service.
command: CommandType object.
data: string payload.
"""
global _lock
try:
_lock.acquire()
data = data.encode('utf8')
assert len(data) < 1000000, 'Command too long'
msg = b'%b%06d%b' % (command.value, len... | Send command to Training Service.
command: CommandType object.
data: string payload. |
def from_parameter(cls: Type[UnlockParameterType], parameter: str) -> Optional[Union[SIGParameter, XHXParameter]]:
"""
Return UnlockParameter instance from parameter string
:param parameter: Parameter string
:return:
"""
sig_param = SIGParameter.from_parameter(parameter... | Return UnlockParameter instance from parameter string
:param parameter: Parameter string
:return: |
def save_act(self, path=None):
"""Save model to a pickle located at `path`"""
if path is None:
path = os.path.join(logger.get_dir(), "model.pkl")
with tempfile.TemporaryDirectory() as td:
save_variables(os.path.join(td, "model"))
arc_name = os.path.join(td, "... | Save model to a pickle located at `path` |
async def peer(client: Client, peer_signed_raw: str) -> ClientResponse:
"""
POST a Peer signed raw document
:param client: Client to connect to the api
:param peer_signed_raw: Peer signed raw document
:return:
"""
return await client.post(MODULE + '/peering/peers', {'peer': peer_signed_raw}... | POST a Peer signed raw document
:param client: Client to connect to the api
:param peer_signed_raw: Peer signed raw document
:return: |
def removeFileSafely(filename,clobber=True):
""" Delete the file specified, but only if it exists and clobber is True.
"""
if filename is not None and filename.strip() != '':
if os.path.exists(filename) and clobber: os.remove(filename) | Delete the file specified, but only if it exists and clobber is True. |
def compute_amount(self):
"""Auto-assign and return the total amount for this tax."""
self.amount = self.base_amount * self.aliquot / 100
return self.amount | Auto-assign and return the total amount for this tax. |
def ask_user(d):
"""Wrap sphinx.quickstart.ask_user, and add additional questions."""
# Print welcome message
msg = bold('Welcome to the Hieroglyph %s quickstart utility.') % (
version(),
)
print(msg)
msg = """
This will ask questions for creating a Hieroglyph project, and then ask
some... | Wrap sphinx.quickstart.ask_user, and add additional questions. |
def request(self,
method,
path,
options=None,
payload=None,
heartbeater=None,
retry_count=0):
"""
Make a request to the Service Registry API.
@param method: HTTP method ('POST', 'GET', etc.).
... | Make a request to the Service Registry API.
@param method: HTTP method ('POST', 'GET', etc.).
@type method: C{str}
@param path: Path to be appended to base URL ('/sessions', etc.).
@type path: C{str}
@param options: Options to be encoded as query parameters in the URL.
@t... |
def SendReply(self, response, tag=None):
"""Allows this flow to send a message to its parent flow.
If this flow does not have a parent, the message is ignored.
Args:
response: An RDFValue() instance to be sent to the parent.
tag: If specified, tag the result with this tag.
Raises:
V... | Allows this flow to send a message to its parent flow.
If this flow does not have a parent, the message is ignored.
Args:
response: An RDFValue() instance to be sent to the parent.
tag: If specified, tag the result with this tag.
Raises:
ValueError: If responses is not of the correct ty... |
def get_command_response_from_cache(self, device_id, command, command2):
"""Gets response"""
key = self.create_key_from_command(command, command2)
command_cache = self.get_cache_from_file(device_id)
if device_id not in command_cache:
command_cache[device_id] = {}
... | Gets response |
def _negf(ins):
''' Changes sign of top of the stack (48 bits)
'''
output = _float_oper(ins.quad[2])
output.append('call __NEGF')
output.extend(_fpush())
REQUIRES.add('negf.asm')
return output | Changes sign of top of the stack (48 bits) |
def shrink_text_file(filename, max_size, removal_marker=None):
"""Shrink a text file to approximately maxSize bytes
by removing lines from the middle of the file.
"""
file_size = os.path.getsize(filename)
assert file_size > max_size
# We partition the file into 3 parts:
# A) start: maxSize/... | Shrink a text file to approximately maxSize bytes
by removing lines from the middle of the file. |
def list_adb_devices_by_usb_id():
"""List the usb id of all android devices connected to the computer that
are detected by adb.
Returns:
A list of strings that are android device usb ids. Empty if there's
none.
"""
out = adb.AdbProxy().devices(['-l'])
clean_lines = new_str(out, ... | List the usb id of all android devices connected to the computer that
are detected by adb.
Returns:
A list of strings that are android device usb ids. Empty if there's
none. |
def _getDriver(self):
""" Connect to GCE """
driverCls = get_driver(Provider.GCE)
return driverCls(self._clientEmail,
self._googleJson,
project=self._projectId,
datacenter=self._zone) | Connect to GCE |
def set_edist_powerlaw_gamma(self, gmin, gmax, delta, ne_cc):
"""Set the energy distribution function to a power law in the Lorentz factor
**Call signature**
*gmin*
The minimum Lorentz factor of the distribution
*gmax*
The maximum Lorentz factor of the distribution
... | Set the energy distribution function to a power law in the Lorentz factor
**Call signature**
*gmin*
The minimum Lorentz factor of the distribution
*gmax*
The maximum Lorentz factor of the distribution
*delta*
The power-law index of the distribution
... |
def apply_filters(query, args):
"""
Apply all QueryFilters, validating the querystring in the process.
"""
pre_joins = []
for querystring_key, filter_value in args.items(multi=True):
if querystring_key in filter_registry:
cls_inst = filter_registry[querystring_key]
qu... | Apply all QueryFilters, validating the querystring in the process. |
def decaying(start, stop, decay):
"""Yield an infinite series of linearly decaying values."""
def clip(value):
return max(value, stop) if (start > stop) else min(value, stop)
nr_upd = 1.
while True:
yield clip(start * 1./(1. + decay * nr_upd))
nr_upd += 1 | Yield an infinite series of linearly decaying values. |
async def lock(self, container = None):
"Wait for lock acquire"
if container is None:
container = RoutineContainer.get_container(self.scheduler)
if self.locked:
pass
elif self.lockroutine:
await LockedEvent.createMatcher(self)
else:
... | Wait for lock acquire |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.