positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def start(cls, _init_logging=True):
"""
Arrange for the subprocess to be started, if it is not already running.
The parent process picks a UNIX socket path the child will use prior to
fork, creates a socketpair used essentially as a semaphore, then blocks
waiting for the child t... | Arrange for the subprocess to be started, if it is not already running.
The parent process picks a UNIX socket path the child will use prior to
fork, creates a socketpair used essentially as a semaphore, then blocks
waiting for the child to indicate the UNIX socket is ready for use.
:p... |
def dbscan(points, eps, minpts):
"""
Implementation of [DBSCAN]_ (*A density-based algorithm for discovering
clusters in large spatial databases with noise*). It accepts a list of
points (lat, lon) and returns the labels associated with the points.
References
----------
.. [DBSCAN] Ester, M... | Implementation of [DBSCAN]_ (*A density-based algorithm for discovering
clusters in large spatial databases with noise*). It accepts a list of
points (lat, lon) and returns the labels associated with the points.
References
----------
.. [DBSCAN] Ester, M., Kriegel, H. P., Sander, J., & Xu, X. (1996... |
def bread(stream):
""" Decode a file or stream to an object.
"""
if hasattr(stream, "read"):
return bdecode(stream.read())
else:
handle = open(stream, "rb")
try:
return bdecode(handle.read())
finally:
handle.close() | Decode a file or stream to an object. |
def run(expnum, ccd, version, dry_run=False, prefix="", force=False, ignore_dependency=False):
"""Run the OSSOS mopheader script.
"""
message = storage.SUCCESS
logging.info("Attempting to get status on header for {} {}".format(expnum, ccd))
if storage.get_status(task, prefix, expnum, version, ccd) ... | Run the OSSOS mopheader script. |
def __struct_params_s(obj, separator=', ', f=repr, fmt='%s = %s'):
"""method wrapper for printing all elements of a struct"""
s = separator.join([__single_param(obj, n, f, fmt) for n in dir(obj) if __inc_param(obj, n)])
return s | method wrapper for printing all elements of a struct |
def find_interfaces(device, **kwargs):
"""
:param device:
:return:
"""
interfaces = []
try:
for cfg in device:
try:
interfaces.extend(usb_find_desc(cfg, find_all=True, **kwargs))
except:
pass
except:
pass
return inte... | :param device:
:return: |
def storage_pools(self):
"""
Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching.
:return: a `list` of all the `System` objects known to the cluster.
:rtype: list
"""
self.connection._check_login()
response = self.connecti... | Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching.
:return: a `list` of all the `System` objects known to the cluster.
:rtype: list |
def show_Certificate(cert, short=False):
"""
Print Fingerprints, Issuer and Subject of an X509 Certificate.
:param cert: X509 Certificate to print
:param short: Print in shortform for DN (Default: False)
:type cert: :class:`asn1crypto.x509.Certificate`
:type short: Boolean
... | Print Fingerprints, Issuer and Subject of an X509 Certificate.
:param cert: X509 Certificate to print
:param short: Print in shortform for DN (Default: False)
:type cert: :class:`asn1crypto.x509.Certificate`
:type short: Boolean |
def _fill_with_zeros(partials, rows, zero=None):
"""Find and return values from rows for all partials. In cases where no
row matches a partial, zero is assumed as value. For a row, the first
(n-1) fields are assumed to be the partial, and the last field,
the value, where n is the total number of fields ... | Find and return values from rows for all partials. In cases where no
row matches a partial, zero is assumed as value. For a row, the first
(n-1) fields are assumed to be the partial, and the last field,
the value, where n is the total number of fields in each row. It is
assumed that there is a unique ro... |
def plot_movie(*args, **kwargs):
"""
Generate a movie from received instances of World and show them.
See also plot_movie_with_elegans and plot_movie_with_matplotlib.
Parameters
----------
worlds : list of World
Worlds to render.
interactive : bool, default True
Choose a vis... | Generate a movie from received instances of World and show them.
See also plot_movie_with_elegans and plot_movie_with_matplotlib.
Parameters
----------
worlds : list of World
Worlds to render.
interactive : bool, default True
Choose a visualizer. If False, show the plot with matplot... |
async def _start_payloads(self):
"""Start all queued payloads"""
with self._lock:
for coroutine in self._payloads:
task = self.event_loop.create_task(coroutine())
self._tasks.add(task)
self._payloads.clear()
await asyncio.sleep(0) | Start all queued payloads |
def channels_voice_greeting_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/voice-api/greetings#create-greetings"
api_path = "/api/v2/channels/voice/greetings.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/voice-api/greetings#create-greetings |
def match(self, route):
"""
Match input route and return new Message instance
with parsed content
"""
_resource = trim_resource(self.resource)
self.method = self.method.lower()
resource_match = route.resource_regex.search(_resource)
if resource_match is No... | Match input route and return new Message instance
with parsed content |
def check_whitelist_blacklist(value, whitelist=None, blacklist=None):
'''
Check a whitelist and/or blacklist to see if the value matches it.
value
The item to check the whitelist and/or blacklist against.
whitelist
The list of items that are white-listed. If ``value`` is found
... | Check a whitelist and/or blacklist to see if the value matches it.
value
The item to check the whitelist and/or blacklist against.
whitelist
The list of items that are white-listed. If ``value`` is found
in the whitelist, then the function returns ``True``. Otherwise,
it return... |
def _PathList_key(self, pathlist):
"""
Returns the key for memoization of PathLists.
Note that we want this to be pretty quick, so we don't completely
canonicalize all forms of the same list. For example,
'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically
represe... | Returns the key for memoization of PathLists.
Note that we want this to be pretty quick, so we don't completely
canonicalize all forms of the same list. For example,
'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically
represent the same list if you're executing from $ROOT, but
... |
def add_callback(self, cb):
""" Register cb as a new callback. Will not register duplicates. """
if ((cb in self.callbacks) is False):
self.callbacks.append(cb) | Register cb as a new callback. Will not register duplicates. |
def probability_density(self, X):
"""Compute density function for given copula family."""
self.check_fit()
U, V = self.split_matrix(X)
if self.theta == 1:
return np.multiply(U, V)
else:
a = np.power(np.multiply(U, V), -1)
tmp = np.power(-np.... | Compute density function for given copula family. |
def reconnect(self):
'''
Try to reconnect and re-authenticate with the server.
'''
log.debug('Closing the SSH socket.')
try:
self.ssl_skt.close()
except socket.error:
log.error('The socket seems to be closed already.')
log.debug('Re-opening... | Try to reconnect and re-authenticate with the server. |
def add_label_work_count(self):
"""Adds to each result row a count of the number of works within the
label contain that n-gram.
This counts works that have at least one witness carrying the
n-gram.
This correctly handles cases where an n-gram has only zero
counts for a ... | Adds to each result row a count of the number of works within the
label contain that n-gram.
This counts works that have at least one witness carrying the
n-gram.
This correctly handles cases where an n-gram has only zero
counts for a given work (possible with zero-fill followe... |
def match(apikey, pcmiter, samplerate, duration, channels=2, metadata=None):
"""Given a PCM data stream, perform fingerprinting and look up the
metadata for the audio. pcmiter must be an iterable of blocks of
PCM data (buffers). duration is the total length of the track in
seconds (an integer). metadata... | Given a PCM data stream, perform fingerprinting and look up the
metadata for the audio. pcmiter must be an iterable of blocks of
PCM data (buffers). duration is the total length of the track in
seconds (an integer). metadata may be a dictionary containing
existing metadata for the file (optional keys: "... |
def _min_depth(self):
"""Finds minimum path length from the root.
Notes
-----
Internal method. Do not call directly.
Returns
-------
int
Minimum path length from the root.
"""
if "min_depth" in self.__dict__:
return self.... | Finds minimum path length from the root.
Notes
-----
Internal method. Do not call directly.
Returns
-------
int
Minimum path length from the root. |
def new(self, dev_t_high, dev_t_low):
# type: (int, int) -> None
'''
Create a new Rock Ridge POSIX device number record.
Parameters:
dev_t_high - The high-order 32-bits of the device number.
dev_t_low - The low-order 32-bits of the device number.
Returns:
... | Create a new Rock Ridge POSIX device number record.
Parameters:
dev_t_high - The high-order 32-bits of the device number.
dev_t_low - The low-order 32-bits of the device number.
Returns:
Nothing. |
def inSignJoy(self):
""" Returns if the object is in its sign of joy. """
return props.object.signJoy[self.obj.id] == self.obj.sign | Returns if the object is in its sign of joy. |
def set_config_item(self, key, value):
"""
Set a config key to a provided value.
The value can be a list for the keys supporting multiple values.
"""
try:
old_value = self.get_config_item(key)
except KeyError:
old_value = None
# Ge... | Set a config key to a provided value.
The value can be a list for the keys supporting multiple values. |
def get(self, name):
"""Get the attribute with the given *name*.
The returned object is a :class:`.Attribute` instance. Raises
:exc:`ValueError` if no attribute has this name. Since multiple
attributes can have the same name, we'll return the last match, since
all but the last a... | Get the attribute with the given *name*.
The returned object is a :class:`.Attribute` instance. Raises
:exc:`ValueError` if no attribute has this name. Since multiple
attributes can have the same name, we'll return the last match, since
all but the last are ignored by the MediaWiki pars... |
def extension_elements_to_elements(extension_elements, schemas):
""" Create a list of elements each one matching one of the
given extension elements. This is of course dependent on the access
to schemas that describe the extension elements.
:param extension_elements: The list of extension elements
... | Create a list of elements each one matching one of the
given extension elements. This is of course dependent on the access
to schemas that describe the extension elements.
:param extension_elements: The list of extension elements
:param schemas: Imported Python modules that represent the different
... |
def check_access_token(self, request_token):
"""Checks that the token contains only safe characters
and is no shorter than lower and no longer than upper.
"""
lower, upper = self.access_token_length
return (set(request_token) <= self.safe_characters and
lower <= l... | Checks that the token contains only safe characters
and is no shorter than lower and no longer than upper. |
def calculate_convolution_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, C, H, W] ---> [N, C, H', W']
'''
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
params = operator.raw_operator.convolution
input_shape = operator.inputs[... | Allowed input/output patterns are
1. [N, C, H, W] ---> [N, C, H', W'] |
def run(self):
"""Main logic for this thread to execute."""
if platform.system() == 'Windows':
# Windows doesn't support file-like objects for select(), so fall back
# to raw_input().
response = input(''.join((self._message,
os.linesep,
... | Main logic for this thread to execute. |
def centerdistance(image, voxelspacing = None, mask = slice(None)):
r"""
Takes a simple or multi-spectral image and returns its voxel-wise center distance in
mm. A multi-spectral image must be supplied as a list or tuple of its spectra.
Optionally a binary mask can be supplied to select the voxels ... | r"""
Takes a simple or multi-spectral image and returns its voxel-wise center distance in
mm. A multi-spectral image must be supplied as a list or tuple of its spectra.
Optionally a binary mask can be supplied to select the voxels for which the feature
should be extracted.
The center dista... |
def receive(self, sock):
"""Receive a message on ``sock``."""
msg = None
data = b''
recv_done = False
recv_len = -1
while not recv_done:
buf = sock.recv(BUFSIZE)
if buf is None or len(buf) == 0:
raise Exception("socket closed")
if recv_len == -1:
recv_len = stru... | Receive a message on ``sock``. |
def isMember(userid, password, group):
"""Test to see if the given userid/password combo is an authenticated member of group.
userid: CADC Username (str)
password: CADC Password (str)
group: CADC GMS group (str)
"""
try:
certfile = getCert(userid, password)
group_url = get... | Test to see if the given userid/password combo is an authenticated member of group.
userid: CADC Username (str)
password: CADC Password (str)
group: CADC GMS group (str) |
def flatten(self, obj):
"""Return a list with the field values
"""
return [self._serialize(f, obj) for f in self.fields] | Return a list with the field values |
def nearby(word):
'''
Nearby word
'''
w = any2unicode(word)
# read from cache
if w in _cache_nearby: return _cache_nearby[w]
words, scores = [], []
try:
for x in _vectors.neighbours(w):
words.append(x[0])
scores.append(x[1])
except: pass # ignore key ... | Nearby word |
def kitchen_delete(backend, kitchen):
"""
Provide the name of the kitchen to delete
"""
click.secho('%s - Deleting kitchen %s' % (get_datetime(), kitchen), fg='green')
master = 'master'
if kitchen.lower() != master.lower():
check_and_print(DKCloudCommandRunner.delete_kitchen(backend.dki,... | Provide the name of the kitchen to delete |
def searchsorted(self, value, side="left", sorter=None):
"""
Find indices where elements should be inserted to maintain order.
.. versionadded:: 0.24.0
Find the indices into a sorted array `self` (a) such that, if the
corresponding elements in `value` were inserted before the i... | Find indices where elements should be inserted to maintain order.
.. versionadded:: 0.24.0
Find the indices into a sorted array `self` (a) such that, if the
corresponding elements in `value` were inserted before the indices,
the order of `self` would be preserved.
Assuming tha... |
def i2c_read_request(self, address, register, number_of_bytes, read_type,
cb=None, cb_type=None):
"""
This method issues an i2c read request for a single read,continuous
read or a stop, specified by the read_type.
Because different i2c devices return data at diff... | This method issues an i2c read request for a single read,continuous
read or a stop, specified by the read_type.
Because different i2c devices return data at different rates,
if a callback is not specified, the user must first call this method
and then call i2c_read_data after waiting fo... |
def get_elementary_deformations(cryst, n=5, d=2):
'''Generate elementary deformations for elastic tensor calculation.
The deformations are created based on the symmetry of the crystal and
are limited to the non-equivalet axes of the crystal.
:param cryst: Atoms object, basic structure
:param n: in... | Generate elementary deformations for elastic tensor calculation.
The deformations are created based on the symmetry of the crystal and
are limited to the non-equivalet axes of the crystal.
:param cryst: Atoms object, basic structure
:param n: integer, number of deformations per non-equivalent axis
... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkflowCumulativeStatisticsContext for this WorkflowCumulativeStatisticsInstance
:rtype: twilio.... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkflowCumulativeStatisticsContext for this WorkflowCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.... |
def _flush_pending_events(self):
'''
Send pending frames that are in the event queue.
'''
while len(self._pending_events) and \
isinstance(self._pending_events[0], Frame):
self._connection.send_frame(self._pending_events.popleft()) | Send pending frames that are in the event queue. |
def order_dict_by(dict_, key_order):
r"""
Reorders items in a dictionary according to a custom key order
Args:
dict_ (dict_): a dictionary
key_order (list): custom key order
Returns:
OrderedDict: sorted_dict
CommandLine:
python -m utool.util_dict --exec-order_dict... | r"""
Reorders items in a dictionary according to a custom key order
Args:
dict_ (dict_): a dictionary
key_order (list): custom key order
Returns:
OrderedDict: sorted_dict
CommandLine:
python -m utool.util_dict --exec-order_dict_by
Example:
>>> # ENABLE_DO... |
def fill_rect(framebuf, x, y, width, height, color):
"""Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws
both the outline and interior."""
# pylint: disable=too-many-arguments
while height > 0:
index = (y >> 3) * framebuf.stride + x
... | Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws
both the outline and interior. |
def head(self, url, *args, **kwargs):
"""
Send HEAD request without checking the response.
Note that ``_check_response`` is not called, as there will be no
response body to check.
:param str url: The URL to make the request to.
"""
with LOG_JWS_HEAD().context():... | Send HEAD request without checking the response.
Note that ``_check_response`` is not called, as there will be no
response body to check.
:param str url: The URL to make the request to. |
def draw_latent_variables(self, nsims=5000):
""" Draws latent variables from the model (for Bayesian inference)
Parameters
----------
nsims : int
How many draws to take
Returns
----------
- np.ndarray of draws
"""
if self.latent_varia... | Draws latent variables from the model (for Bayesian inference)
Parameters
----------
nsims : int
How many draws to take
Returns
----------
- np.ndarray of draws |
def interrupt(self, interrupt):
"""Perform the shutdown of this server and save the exception."""
self._interrupt = True
self.stop()
self._interrupt = interrupt | Perform the shutdown of this server and save the exception. |
def get_query_results(self, job_id, offset=None, limit=None,
page_token=None, timeout=0):
"""Execute the query job indicated by the given job id. This is direct
mapping to bigquery api
https://cloud.google.com/bigquery/docs/reference/v2/jobs/getQueryResults
Par... | Execute the query job indicated by the given job id. This is direct
mapping to bigquery api
https://cloud.google.com/bigquery/docs/reference/v2/jobs/getQueryResults
Parameters
----------
job_id : str
The job id of the query to check
offset : optional
... |
def IPT_to_XYZ(cobj, *args, **kwargs):
"""
Converts IPT to XYZ.
"""
ipt_values = numpy.array(cobj.get_value_tuple())
lms_values = numpy.dot(
numpy.linalg.inv(IPTColor.conversion_matrices['lms_to_ipt']),
ipt_values)
lms_prime = numpy.sign(lms_values) * numpy.abs(lms_values) ** (1... | Converts IPT to XYZ. |
def merge_related_samples(file_name, out_prefix, no_status):
"""Merge related samples.
:param file_name: the name of the input file.
:param out_prefix: the prefix of the output files.
:param no_status: is there a status column in the file?
:type file_name: str
:type out_prefix: str
:type n... | Merge related samples.
:param file_name: the name of the input file.
:param out_prefix: the prefix of the output files.
:param no_status: is there a status column in the file?
:type file_name: str
:type out_prefix: str
:type no_status: boolean
In the output file, there are a pair of sampl... |
def solarReturnJD(jd, lon, forward=True):
""" Finds the julian date before or after
'jd' when the sun is at longitude 'lon'.
It searches forward by default.
"""
sun = swe.sweObjectLon(const.SUN, jd)
if forward:
dist = angle.distance(sun, lon)
else:
dist = -angle.distan... | Finds the julian date before or after
'jd' when the sun is at longitude 'lon'.
It searches forward by default. |
def beam_kev(self,get_error=False):
"""
Get the beam energy in kev, based on typical biases:
itw (or ite bias) - bias15 - platform bias
if get_error: fetch error in value, rather than value
"""
# get epics pointer
epics =... | Get the beam energy in kev, based on typical biases:
itw (or ite bias) - bias15 - platform bias
if get_error: fetch error in value, rather than value |
def load_factory(name, directory, configuration=None):
""" Load a factory and have it initialize in a particular directory
:param name: the name of the plugin to load
:param directory: the directory where the factory will reside
:return:
"""
for entry_point in pkg_resources.iter_entry_points(ENT... | Load a factory and have it initialize in a particular directory
:param name: the name of the plugin to load
:param directory: the directory where the factory will reside
:return: |
def lang_direction(request):
"""
Sets lang_direction context variable to whether the language is RTL or LTR
"""
if lang_direction.rtl_langs is None:
lang_direction.rtl_langs = getattr(settings, "RTL_LANGUAGES", set())
return {"lang_direction": "rtl" if request.LANGUAGE_CODE in lang_directio... | Sets lang_direction context variable to whether the language is RTL or LTR |
def _set_status_self(self, key=JobDetails.topkey, status=JobStatus.unknown):
"""Set the status of this job, both in self.jobs and
in the `JobArchive` if it is present. """
fullkey = JobDetails.make_fullkey(self.full_linkname, key)
if fullkey in self.jobs:
self.jobs[fullkey].s... | Set the status of this job, both in self.jobs and
in the `JobArchive` if it is present. |
def _elim_adj(adj, n):
"""eliminates a variable, acting on the adj matrix of G,
returning set of edges that were added.
Parameters
----------
adj: dict
A dict of the form {v: neighbors, ...} where v are
vertices in a graph and neighbors is a set.
Returns
----------
new_... | eliminates a variable, acting on the adj matrix of G,
returning set of edges that were added.
Parameters
----------
adj: dict
A dict of the form {v: neighbors, ...} where v are
vertices in a graph and neighbors is a set.
Returns
----------
new_edges: set of edges that were ... |
def monitor(self, name, cb, request=None, notify_disconnect=False):
"""Create a subscription.
:param str name: PV name string
:param callable cb: Processing callback
:param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default.
:param bool ... | Create a subscription.
:param str name: PV name string
:param callable cb: Processing callback
:param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default.
:param bool notify_disconnect: In additional to Values, the callback may also be call with ... |
def set_gcc():
"""Try to use GCC on OSX for OpenMP support."""
# For macports and homebrew
if 'darwin' in platform.platform().lower():
gcc = extract_gcc_binaries()
if gcc is not None:
os.environ["CC"] = gcc
os.environ["CXX"] = gcc
else:
global u... | Try to use GCC on OSX for OpenMP support. |
def __callServer(self, method="", params={}, data={}, callmethod='GET', content='application/json'):
"""
A private method to make HTTP call to the DBS Server
:param method: REST API to call, e.g. 'datasets, blocks, files, ...'.
:type method: str
:param params: Parameters to the ... | A private method to make HTTP call to the DBS Server
:param method: REST API to call, e.g. 'datasets, blocks, files, ...'.
:type method: str
:param params: Parameters to the API call, e.g. {'dataset':'/PrimaryDS/ProcessedDS/TIER'}.
:type params: dict
:param callmethod: The HTTP ... |
def mnest_basename(self):
"""Full path to basename
"""
if not hasattr(self, '_mnest_basename'):
s = self.labelstring
if s=='0_0':
s = 'single'
elif s=='0_0-0_1':
s = 'binary'
elif s=='0_0-0_1-0_2':
s ... | Full path to basename |
def account_pin(self, id):
"""
Pin / endorse a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/pin'.format(str(id))
return self.__api_request('POST', url) | Pin / endorse a user.
Returns a `relationship dict`_ containing the updated relationship to the user. |
def build_git_url(self):
"""
get build git url.
:return: build git url or None if not found
"""
# pylint: disable=len-as-condition
if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None):
return self.dutinformation.get(0).build.gitu... | get build git url.
:return: build git url or None if not found |
def from_raster(cls, raster, properties, product='visual'):
"""Initialize a GeoFeature object with a GeoRaster
Parameters
----------
raster : GeoRaster
the raster in the feature
properties : dict
Properties.
product : str
product assoc... | Initialize a GeoFeature object with a GeoRaster
Parameters
----------
raster : GeoRaster
the raster in the feature
properties : dict
Properties.
product : str
product associated to the raster |
def set_data(self, data):
"""Set table data"""
if data is not None:
self.model.set_data(data, self.dictfilter)
self.sortByColumn(0, Qt.AscendingOrder) | Set table data |
def import_parallel_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN parallel gateway.
Parallel gateway doesn't have additional attributes. Separate method is used to improve code readability.
:param diagram... | Adds to graph the new element that represents BPMN parallel gateway.
Parallel gateway doesn't have additional attributes. Separate method is used to improve code readability.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param process_id: string object, representing... |
def collapse_group_expr(groupx,cols,ret_row):
"collapses columns matching the group expression. I'm sure this is buggy; look at a real DB's imp of this."
for i,col in enumerate(cols.children):
if col==groupx: ret_row[i]=ret_row[i][0]
return ret_row | collapses columns matching the group expression. I'm sure this is buggy; look at a real DB's imp of this. |
def send_message(self, chat_id, text, **options):
"""
Send a text message to chat
:param int chat_id: ID of the chat to send the message to
:param str text: Text to send
:param options: Additional sendMessage options
(see https://core.telegram.org/bots/api#sendmessag... | Send a text message to chat
:param int chat_id: ID of the chat to send the message to
:param str text: Text to send
:param options: Additional sendMessage options
(see https://core.telegram.org/bots/api#sendmessage) |
def close_monomers(self, group, cutoff=4.0):
"""Returns a list of Monomers from within a cut off distance of the Monomer
Parameters
----------
group: BaseAmpal or Subclass
Group to be search for Monomers that are close to this Monomer.
cutoff: float
Dista... | Returns a list of Monomers from within a cut off distance of the Monomer
Parameters
----------
group: BaseAmpal or Subclass
Group to be search for Monomers that are close to this Monomer.
cutoff: float
Distance cut off.
Returns
-------
ne... |
def filter(self, chamber, congress=CURRENT_CONGRESS, **kwargs):
"""
Takes a chamber and Congress,
OR state and district, returning a list of members
"""
check_chamber(chamber)
kwargs.update(chamber=chamber, congress=congress)
if 'state' in kwargs and 'district' ... | Takes a chamber and Congress,
OR state and district, returning a list of members |
def parse(cls, uri):
""" Parse URI-string and return WURI object
:param uri: string to parse
:return: WURI
"""
uri_components = urlsplit(uri)
adapter_fn = lambda x: x if x is not None and (isinstance(x, str) is False or len(x)) > 0 else None
return cls(
scheme=adapter_fn(uri_components.scheme),
us... | Parse URI-string and return WURI object
:param uri: string to parse
:return: WURI |
def read_relative_file(filename):
"""
Return the contents of the given file.
Its path is supposed relative to this module.
"""
path = join(dirname(abspath(__file__)), filename)
with io.open(path, encoding='utf-8') as f:
return f.read() | Return the contents of the given file.
Its path is supposed relative to this module. |
def compute_vest_stat(vest_dict, ref_aa, somatic_aa, codon_pos,
stat_func=np.mean,
default_val=0.0):
"""Compute missense VEST score statistic.
Note: non-missense mutations are intentially not filtered out and will take
a default value of zero.
Parameters
... | Compute missense VEST score statistic.
Note: non-missense mutations are intentially not filtered out and will take
a default value of zero.
Parameters
----------
vest_dict : dict
dictionary containing vest scores across the gene of interest
ref_aa: list of str
list of reference... |
def do_max(environment, value, case_sensitive=False, attribute=None):
"""Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max v... | Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute. |
def pbs_for_set_with_merge(document_path, document_data, merge):
"""Make ``Write`` protobufs for ``set()`` methods.
Args:
document_path (str): A fully-qualified document path.
document_data (dict): Property names and values to use for
replacing a document.
merge (Optional[bo... | Make ``Write`` protobufs for ``set()`` methods.
Args:
document_path (str): A fully-qualified document path.
document_data (dict): Property names and values to use for
replacing a document.
merge (Optional[bool] or Optional[List<apispec>]):
If True, merge all fields; ... |
def get_snapshot_command_history(self, name, limit=20, offset=0, view=None):
"""
Retrieve a list of commands triggered by a snapshot policy.
@param name: The name of the snapshot policy.
@param limit: Maximum number of commands to retrieve.
@param offset: Index of first command to retrieve.
@pa... | Retrieve a list of commands triggered by a snapshot policy.
@param name: The name of the snapshot policy.
@param limit: Maximum number of commands to retrieve.
@param offset: Index of first command to retrieve.
@param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_reda... |
def clear_coordinate_conditions(self):
"""stub"""
if (self.get_zone_conditions_metadata().is_read_only() or
self.get_zone_conditions_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map['coordinateConditions'] = \
self._coordinate_c... | stub |
def data(self, data):
"""Called for text between tags"""
if self.state == STATE_SOURCE_ID:
self.context.audit_record.source_id = int(data) # Audit ids can be 64 bits
elif self.state == STATE_DATETIME:
dt = datetime.datetime.strptime(data, "%Y-%m-%dT%H:%M:%S")
... | Called for text between tags |
def singleChoiceParam(parameters, name, type_converter = str):
""" single choice parameter value. Returns -1 if no value was chosen.
:param parameters: the parameters tree.
:param name: the name of the parameter.
:param type_converter: function to convert the chosen value to a different type (e.g. str, ... | single choice parameter value. Returns -1 if no value was chosen.
:param parameters: the parameters tree.
:param name: the name of the parameter.
:param type_converter: function to convert the chosen value to a different type (e.g. str, float, int). default = 'str |
def _BuildAuthenticatorResponse(self, app_id, client_data, plugin_response):
"""Builds the response to return to the caller."""
encoded_client_data = self._Base64Encode(client_data)
signature_data = str(plugin_response['signatureData'])
key_handle = str(plugin_response['keyHandle'])
response = {
... | Builds the response to return to the caller. |
def plot_PSD(self, xlim=None, units="kHz", show_fig=True, timeStart=None, timeEnd=None, *args, **kwargs):
"""
plot the pulse spectral density.
Parameters
----------
xlim : array_like, optional
The x limits of the plotted PSD [LowerLimit, UpperLimit]
Defau... | plot the pulse spectral density.
Parameters
----------
xlim : array_like, optional
The x limits of the plotted PSD [LowerLimit, UpperLimit]
Default value is [0, SampleFreq/2]
units : string, optional
Units of frequency to plot on the x axis - defaults... |
def reverse(viewname, subdomain=None, scheme=None, args=None, kwargs=None,
current_app=None):
"""
Reverses a URL from the given parameters, in a similar fashion to
:meth:`django.core.urlresolvers.reverse`.
:param viewname: the name of URL
:param subdomain: the subdomain to use for URL rever... | Reverses a URL from the given parameters, in a similar fashion to
:meth:`django.core.urlresolvers.reverse`.
:param viewname: the name of URL
:param subdomain: the subdomain to use for URL reversing
:param scheme: the scheme to use when generating the full URL
:param args: positional arguments used ... |
def renavactive(request, pattern):
"""
{% renavactive request "^/a_regex" %}
"""
if re.search(pattern, request.path):
return getattr(settings, "NAVHELPER_ACTIVE_CLASS", "active")
return getattr(settings, "NAVHELPER_NOT_ACTIVE_CLASS", "") | {% renavactive request "^/a_regex" %} |
def DbGetServerInfo(self, argin):
""" Get info about host, mode and level for specified server
:param argin: server name
:type: tango.DevString
:return: server info
:rtype: tango.DevVarStringArray """
self._log.debug("In DbGetServerInfo()")
return self.db.get_ser... | Get info about host, mode and level for specified server
:param argin: server name
:type: tango.DevString
:return: server info
:rtype: tango.DevVarStringArray |
def _run_qc_tools(bam_file, data):
"""Run a set of third party quality control tools, returning QC directory and metrics.
:param bam_file: alignments in bam format
:param data: dict with all configuration information
:returns: dict with output of different tools
"""
from bcbio.qc i... | Run a set of third party quality control tools, returning QC directory and metrics.
:param bam_file: alignments in bam format
:param data: dict with all configuration information
:returns: dict with output of different tools |
def is_available(self):
"""
Returns `True` if *any* view handler in the class is currently
available via its `is_available` method.
"""
if self.is_always_available:
return True
for viewname in self.__views__:
if getattr(self, viewname).is_available... | Returns `True` if *any* view handler in the class is currently
available via its `is_available` method. |
def local_error(self, originalValue, calculatedValue):
"""Calculates the error between the two given values.
:param list originalValue: List containing the values of the original data.
:param list calculatedValue: List containing the values of the calculated TimeSeries that
co... | Calculates the error between the two given values.
:param list originalValue: List containing the values of the original data.
:param list calculatedValue: List containing the values of the calculated TimeSeries that
corresponds to originalValue.
:return: Returns the error... |
def application(handler, adapter_cls=WerkzeugAdapter):
"""Converts an anillo function based handler in a
wsgi compiliant application function.
:param adapter_cls: the wsgi adapter implementation (default: wekrzeug)
:returns: wsgi function
:rtype: callable
"""
adapter = adapter_cls()
de... | Converts an anillo function based handler in a
wsgi compiliant application function.
:param adapter_cls: the wsgi adapter implementation (default: wekrzeug)
:returns: wsgi function
:rtype: callable |
def show_link(self):
'''show link information'''
for master in self.mpstate.mav_master:
linkdelay = (self.status.highest_msec - master.highest_msec)*1.0e-3
if master.linkerror:
print("link %u down" % (master.linknum+1))
else:
print("lin... | show link information |
def validate_df(df, dm, con=None):
"""
Take in a DataFrame and corresponding data model.
Run all validations for that DataFrame.
Output is the original DataFrame with some new columns
that contain the validation output.
Validation columns start with:
presence_pass_ (checking that req'd colum... | Take in a DataFrame and corresponding data model.
Run all validations for that DataFrame.
Output is the original DataFrame with some new columns
that contain the validation output.
Validation columns start with:
presence_pass_ (checking that req'd columns are present)
type_pass_ (checking that ... |
def from_sequence(cls, sequence, phos_3_prime=False):
"""Creates a DNA duplex from a nucleotide sequence.
Parameters
----------
sequence: str
Nucleotide sequence.
phos_3_prime: bool, optional
If false the 5' and the 3' phosphor will be omitted.
""... | Creates a DNA duplex from a nucleotide sequence.
Parameters
----------
sequence: str
Nucleotide sequence.
phos_3_prime: bool, optional
If false the 5' and the 3' phosphor will be omitted. |
def hdel(self, *args):
"""
This command on the model allow deleting many instancehash fields with
only one redis call. You must pass hash names to retrieve as arguments
"""
if args and not any(arg in self._instancehash_fields for arg in args):
raise ValueError("Only I... | This command on the model allow deleting many instancehash fields with
only one redis call. You must pass hash names to retrieve as arguments |
def json2pattern(s):
"""
Convert JSON format to a query pattern.
Includes even mongo shell notation without quoted key names.
"""
# make valid JSON by wrapping field names in quotes
s, _ = re.subn(r'([{,])\s*([^,{\s\'"]+)\s*:', ' \\1 "\\2" : ', s)
# handle shell values that are not valid JS... | Convert JSON format to a query pattern.
Includes even mongo shell notation without quoted key names. |
def log_request(self, code="-", size="-"):
"""
Logs a request to the server
"""
self._service.log(logging.DEBUG, '"%s" %s', self.requestline, code) | Logs a request to the server |
def write_fc3_to_hdf5(fc3,
filename='fc3.hdf5',
p2s_map=None,
compression=None):
"""Write third-order force constants in hdf5 format.
Parameters
----------
force_constants : ndarray
Force constants
shape=(n_satom, n_satom... | Write third-order force constants in hdf5 format.
Parameters
----------
force_constants : ndarray
Force constants
shape=(n_satom, n_satom, n_satom, 3, 3, 3) or
(n_patom, n_satom, n_satom,3,3,3), dtype=double
filename : str
Filename to be used.
p2s_map : ndarray, opti... |
def index_run(record_path, keep_json, check_duplicate):
"""
Convert raw JSON records into sqlite3 DB.
Normally RASH launches a daemon that takes care of indexing.
See ``rash daemon --help``.
"""
from .config import ConfigStore
from .indexer import Indexer
cfstore = ConfigStore()
in... | Convert raw JSON records into sqlite3 DB.
Normally RASH launches a daemon that takes care of indexing.
See ``rash daemon --help``. |
def create_string_array(self, key, value):
"""Create method of CRUD operation for string array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
dat... | Create method of CRUD operation for string array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. |
def value(self):
"""convenience method to just get one value or tuple of values for the query"""
field_vals = None
field_names = self.fields_select.names()
fcount = len(field_names)
if fcount:
d = self._query('get_one')
if d:
field_vals = [... | convenience method to just get one value or tuple of values for the query |
def _get_coord_cell_node_coord(self, coord, coords=None, nans=None,
var=None):
"""
Get the boundaries of an unstructed coordinate
Parameters
----------
coord: xr.Variable
The coordinate whose bounds should be returned
%(CFDe... | Get the boundaries of an unstructed coordinate
Parameters
----------
coord: xr.Variable
The coordinate whose bounds should be returned
%(CFDecoder.get_cell_node_coord.parameters.no_var|axis)s
Returns
-------
%(CFDecoder.get_cell_node_coord.returns)s |
def sanity_check(vcs):
"""Do sanity check before making changes
Check that we are not on a tag and/or do not have local changes.
Returns True when all is fine.
"""
if not vcs.is_clean_checkout():
q = ("This is NOT a clean checkout. You are on a tag or you have "
"local changes... | Do sanity check before making changes
Check that we are not on a tag and/or do not have local changes.
Returns True when all is fine. |
def make_objs(names, out_dir=''):
"""
Make object file names for cl.exe and link.exe.
"""
objs = [replace_ext(name, '.obj') for name in names]
if out_dir:
objs = [os.path.join(out_dir, obj) for obj in objs]
return objs | Make object file names for cl.exe and link.exe. |
def findViewsContainingPoint(self, (x, y), _filter=None):
'''
Finds the list of Views that contain the point (x, y).
'''
if not _filter:
_filter = lambda v: True
return [v for v in self.views if (v.containsPoint((x,y)) and _filter(v))] | Finds the list of Views that contain the point (x, y). |
def getAPOBECFrequencies(dotAlignment, orig, new, pattern):
"""
Gets mutation frequencies if they are in a certain pattern.
@param dotAlignment: result from calling basePlotter
@param orig: A C{str}, naming the original base
@param new: A C{str}, what orig was mutated to
@param pattern: A C{str... | Gets mutation frequencies if they are in a certain pattern.
@param dotAlignment: result from calling basePlotter
@param orig: A C{str}, naming the original base
@param new: A C{str}, what orig was mutated to
@param pattern: A C{str}m which pattern we're looking for
(must be one of 'cPattern', '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.