code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def query_pre_approvals(self, initial_date, final_date, page=None,
max_results=None):
""" query pre-approvals by date range """
last_page = False
results = []
while last_page is False:
search_result = self._consume_query_pre_approvals(
... | query pre-approvals by date range |
def get_found_locations():
"""
INFO:__main__:found HELP in 1572
INFO:__main__:found MATHS in 1704
INFO:__main__:found ROCKS in 1975
#random.seed(1572)
#garbage = ''.join([chr(random.randint(32,122)) for x in range(100000)])
#wrd_location = garbage.find('HELP')
#print(wrd_location) # 7383... | INFO:__main__:found HELP in 1572
INFO:__main__:found MATHS in 1704
INFO:__main__:found ROCKS in 1975
#random.seed(1572)
#garbage = ''.join([chr(random.randint(32,122)) for x in range(100000)])
#wrd_location = garbage.find('HELP')
#print(wrd_location) # 73834
#print(garbage[wrd_location:wrd_l... |
def GuinierPorodGuinier(q, G, Rg1, alpha, Rg2):
"""Empirical Guinier-Porod-Guinier scattering
Inputs:
-------
``q``: independent variable
``G``: factor for the first Guinier-branch
``Rg1``: the first radius of gyration
``alpha``: the power-law exponent
``Rg2``: the s... | Empirical Guinier-Porod-Guinier scattering
Inputs:
-------
``q``: independent variable
``G``: factor for the first Guinier-branch
``Rg1``: the first radius of gyration
``alpha``: the power-law exponent
``Rg2``: the second radius of gyration
Formula:
--------
... |
def upload_to_cache_server(fpath):
"""Uploads .torrent file to a cache server.
Returns upload file URL.
:rtype: str
"""
url_base = 'http://torrage.info'
url_upload = '%s/autoupload.php' % url_base
url_download = '%s/torrent.php?h=' % url_base
file_field = 'torrent'
try:
im... | Uploads .torrent file to a cache server.
Returns upload file URL.
:rtype: str |
def V_horiz_guppy(D, L, a, h, headonly=False):
r'''Calculates volume of a tank with guppy heads, according to [1]_.
.. math::
V_f = A_fL + \frac{2aR^2}{3}\cos^{-1}\left(1 - \frac{h}{R}\right)
+\frac{2a}{9R}\sqrt{2Rh - h^2}(2h-3R)(h+R)
.. math::
Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h... | r'''Calculates volume of a tank with guppy heads, according to [1]_.
.. math::
V_f = A_fL + \frac{2aR^2}{3}\cos^{-1}\left(1 - \frac{h}{R}\right)
+\frac{2a}{9R}\sqrt{2Rh - h^2}(2h-3R)(h+R)
.. math::
Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h)\sqrt{2Rh - h^2}
Parameters
----------
... |
def _apply_record_checks(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply record checks on `r`."""
for check, modulus in self._record_checks:
if i % modu... | Apply record checks on `r`. |
def driver(self):
"""
Return the driver of this agent related to. None if the driver is not ready to bind.
Returns:
:py:class:`inherit from Poco <poco.pocofw.Poco>`: the driver of this agent related to.
"""
if not self._driver:
raise AttributeError("`dri... | Return the driver of this agent related to. None if the driver is not ready to bind.
Returns:
:py:class:`inherit from Poco <poco.pocofw.Poco>`: the driver of this agent related to. |
def summary(dataset_uri, format):
"""Report summary information about a dataset."""
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
creator_username = dataset._admin_metadata["creator_username"]
frozen_at = dataset._admin_metadata["frozen_at"]
num_items = len(dataset.identifiers)
tot_size = su... | Report summary information about a dataset. |
def __ComputeUploadConfig(self, media_upload_config, method_id):
"""Fill out the upload config for this method."""
config = base_api.ApiUploadInfo()
if 'maxSize' in media_upload_config:
config.max_size = self.__MaxSizeToInt(
media_upload_config['maxSize'])
if ... | Fill out the upload config for this method. |
def faves(self, option):
"""
Set whether to filter by a user's faves list. Options available are
user.ONLY, user.NOT, and None; default is None.
"""
params = join_params(self.parameters, {"faves": option})
return self.__class__(**params) | Set whether to filter by a user's faves list. Options available are
user.ONLY, user.NOT, and None; default is None. |
def on_success(self, metadata):
""" Called when a SUCCESS message has been received.
"""
handler = self.handlers.get("on_success")
if callable(handler):
handler(metadata)
handler = self.handlers.get("on_summary")
if callable(handler):
handler() | Called when a SUCCESS message has been received. |
def storeToXML(self, out, comment=None, encoding='UTF-8'):
"""
Write the `Properties` object's entries (in unspecified order) in XML
properties format to ``out``.
:param out: a file-like object to write the properties to
:type out: binary file-like object
:param comment:... | Write the `Properties` object's entries (in unspecified order) in XML
properties format to ``out``.
:param out: a file-like object to write the properties to
:type out: binary file-like object
:param comment: if non-`None`, ``comment`` will be output as a
``<comment>`` eleme... |
def remove_choice(self, choice_name):
"""Adds a choice for the experiment"""
self.choice_names.remove(choice_name)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices", escape.json_encode(self.choice_names))
self.refresh() | Adds a choice for the experiment |
def explode_dn(dn, notypes=0, flags=0):
"""
explode_dn(dn [, notypes=0]) -> list
This function takes a DN and breaks it up into its component parts.
The notypes parameter is used to specify that only the component's
attribute values be returned and not the attribute types.
"""
if not dn:
... | explode_dn(dn [, notypes=0]) -> list
This function takes a DN and breaks it up into its component parts.
The notypes parameter is used to specify that only the component's
attribute values be returned and not the attribute types. |
def question_image_filepath(instance, filename):
"""
Function DocString
"""
return '/'.join(['images', str(instance.question_level), str(instance.question_level_id), binascii.b2a_hex(os.urandom(15)), filename]) | Function DocString |
def set_imap_cb(self, w, index):
"""This callback is invoked when the user selects a new intensity
map from the preferences pane."""
name = imap.get_names()[index]
self.t_.set(intensity_map=name) | This callback is invoked when the user selects a new intensity
map from the preferences pane. |
def move_up(self):
"""
Try to select the button above the currently selected one.
If a button is not there, wrap down to the bottom of the menu and select the last button.
"""
old_index = self.current_index
self.current_index -= 1
self.__wrap_index()
self.... | Try to select the button above the currently selected one.
If a button is not there, wrap down to the bottom of the menu and select the last button. |
def _tree_to_labels(X, single_linkage_tree, min_cluster_size=10,
cluster_selection_method='eom',
allow_single_cluster=False,
match_reference_implementation=False):
"""Converts a pretrained tree and cluster size into a
set of labels and probabilities.
... | Converts a pretrained tree and cluster size into a
set of labels and probabilities. |
def run():
"""Main script entry to handle the arguments given to the script."""
_parser_options()
set_verbose(args["verbose"])
if _check_global_settings():
_load_db()
else:
exit(-1)
#Check the server configuration against the script arguments passed in.
_setup_server()
... | Main script entry to handle the arguments given to the script. |
def unregister(self, bucket, name):
"""
Remove the function from the registry by name
"""
assert bucket in self, 'Bucket %s is unknown' % bucket
if not name in self[bucket]:
raise NotRegistered('The function %s is not registered' % name)
del self[bucket][name] | Remove the function from the registry by name |
def rand_email():
"""Random email.
Usage Example::
>>> rand_email()
Z4Lljcbdw7m@npa.net
"""
name = random.choice(string.ascii_letters) + \
rand_str(string.ascii_letters + string.digits, random.randint(4, 14))
domain = rand_str(string.ascii_lowercase, random.randint(2, ... | Random email.
Usage Example::
>>> rand_email()
Z4Lljcbdw7m@npa.net |
def has_in_url_path(url, subs):
"""Test if any of `subs` strings is present in the `url` path."""
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
return any([sub in path for sub in subs]) | Test if any of `subs` strings is present in the `url` path. |
def oortC(self,R,t=0.,nsigma=None,deg=False,phi=0.,
epsrel=1.e-02,epsabs=1.e-05,
grid=None,gridpoints=101,returnGrids=False,
derivRGrid=None,derivphiGrid=None,derivGridpoints=101,
derivHierarchgrid=False,
hierarchgrid=False,nlevels=2,integrate_method... | NAME:
oortC
PURPOSE:
calculate the Oort function C at (R,phi,t)
INPUT:
R - radius at which to calculate C (can be Quantity)
phi= azimuth (rad unless deg=True; can be Quantity)
t= time at which to evaluate the DF (can be a list or ndarray; if ... |
def get_trades(self, pair="SWTH_NEO", start_time=None, end_time=None, limit=5000):
"""
Function to fetch a list of filled trades for the parameters requested.
Execution of this function is as follows::
get_trades(pair="SWTH_NEO", limit=3)
The expected return result for this... | Function to fetch a list of filled trades for the parameters requested.
Execution of this function is as follows::
get_trades(pair="SWTH_NEO", limit=3)
The expected return result for this function is as follows::
[{
'id': '15bb16e2-7a80-4de1-bb59-bcaff877dee0',... |
def owner_profile(self) -> Profile:
""":class:`Profile` instance of the story item's owner."""
if not self._owner_profile:
self._owner_profile = Profile.from_id(self._context, self._node['owner']['id'])
return self._owner_profile | :class:`Profile` instance of the story item's owner. |
def float_range(start=0, stop=None, step=1):
"""
Much like the built-in function range, but accepts floats
>>> tuple(float_range(0, 9, 1.5))
(0.0, 1.5, 3.0, 4.5, 6.0, 7.5)
"""
start = float(start)
while start < stop:
yield start
start += step | Much like the built-in function range, but accepts floats
>>> tuple(float_range(0, 9, 1.5))
(0.0, 1.5, 3.0, 4.5, 6.0, 7.5) |
def most_free_pixel(self):
""" Find the black pixel with the largest distance from the white pixels.
Returns
-------
:obj:`numpy.ndarray`
2-vector containing the most free pixel
"""
dist_tf = self.to_distance_im()
max_px = np.where(dist_tf == np.max(d... | Find the black pixel with the largest distance from the white pixels.
Returns
-------
:obj:`numpy.ndarray`
2-vector containing the most free pixel |
def connect_checkable_button(instance, prop, widget):
"""
Connect a boolean callback property with a Qt button widget.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : Q... | Connect a boolean callback property with a Qt button widget.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This should implement th... |
def get_output(script):
"""Gets command output from shell logger."""
with logs.debug_time(u'Read output from external shell logger'):
commands = _get_last_n(const.SHELL_LOGGER_LIMIT)
for command in commands:
if command['command'] == script:
lines = _get_output_lines(c... | Gets command output from shell logger. |
def itershuffle(iterable, bufsize=1000):
"""Shuffle an iterator. This works by holding `bufsize` items back
and yielding them sometime later. Obviously, this is not unbiased –
but should be good enough for batching. Larger bufsize means less bias.
From https://gist.github.com/andres-erbsen/1307752
... | Shuffle an iterator. This works by holding `bufsize` items back
and yielding them sometime later. Obviously, this is not unbiased –
but should be good enough for batching. Larger bufsize means less bias.
From https://gist.github.com/andres-erbsen/1307752
iterable (iterable): Iterator to shuffle.
bu... |
def load_file(self, filepath, chname=None, wait=True,
create_channel=True, display_image=True,
image_loader=None):
"""Load a file and display it.
Parameters
----------
filepath : str
The path of the file to load (must reference a local fil... | Load a file and display it.
Parameters
----------
filepath : str
The path of the file to load (must reference a local file).
chname : str, optional
The name of the channel in which to display the image.
wait : bool, optional
If `True`, then ... |
def sendRequest(self, name, args):
"""sends a request to the peer"""
(respEvt, id) = self.newResponseEvent()
self.sendMessage({"id":id, "method":name, "params": args})
return respEvt | sends a request to the peer |
def tseries_between(self, tstart=None, tend=None):
"""Return time series data between requested times.
Args:
tstart (float): starting time. Set to None to start at the
beginning of available data.
tend (float): ending time. Set to None to stop at the end of
... | Return time series data between requested times.
Args:
tstart (float): starting time. Set to None to start at the
beginning of available data.
tend (float): ending time. Set to None to stop at the end of
available data.
Returns:
:class... |
def get_by_id_or_404(self, id, **kwargs):
"""Gets by a instance instance r raises a 404 is one isn't found."""
obj = self.get_by_id(id=id, **kwargs)
if obj:
return obj
raise Http404 | Gets by a instance instance r raises a 404 is one isn't found. |
def write_value(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the value of the Boolean object to the output stream.
Args:
ostream (Stream): A buffer to contain the encoded bytes of the
value of a Boolean object. Usually a BytearrayStream object.
... | Write the value of the Boolean object to the output stream.
Args:
ostream (Stream): A buffer to contain the encoded bytes of the
value of a Boolean object. Usually a BytearrayStream object.
Required.
kmip_version (KMIPVersion): An enumeration defining the... |
def _make_sparse_blocks(self, variable, records, data):
'''
Handles the data for the variable with sparse records.
Organizes the physical record numbers into blocks in a list:
[[start_rec1,end_rec1,data_1], [start_rec2,enc_rec2,data_2], ...]
Place consecutive physical records i... | Handles the data for the variable with sparse records.
Organizes the physical record numbers into blocks in a list:
[[start_rec1,end_rec1,data_1], [start_rec2,enc_rec2,data_2], ...]
Place consecutive physical records into a single block
If all records are physical, this calls _make_sp... |
def spawn(self, *targets: Callable, count: int = 1, **process_kwargs):
r"""
Produce one or many child process(s) bound to this context.
:param \*targets:
Passed on to the :py:class:`Process` constructor, one at a time.
:param count:
The number of processes to sp... | r"""
Produce one or many child process(s) bound to this context.
:param \*targets:
Passed on to the :py:class:`Process` constructor, one at a time.
:param count:
The number of processes to spawn for each item in ``targets``.
:param \*\*process_kwargs:
... |
def get_marginal_topic_distrib(doc_topic_distrib, doc_lengths):
"""
Return marginal topic distribution p(T) (topic proportions) given the document-topic distribution (theta)
`doc_topic_distrib` and the document lengths `doc_lengths`. The latter can be calculated with `get_doc_lengths()`.
"""
unnorm ... | Return marginal topic distribution p(T) (topic proportions) given the document-topic distribution (theta)
`doc_topic_distrib` and the document lengths `doc_lengths`. The latter can be calculated with `get_doc_lengths()`. |
def recursive_getattr(obj: Any, attr: str, *args) -> Any:
""" Recursive ``getattar``.
This can be used as a drop in for the standard ``getattr(...)``. Credit to:
https://stackoverflow.com/a/31174427
Args:
obj: Object to retrieve the attribute from.
attr: Name of the attribute, with eac... | Recursive ``getattar``.
This can be used as a drop in for the standard ``getattr(...)``. Credit to:
https://stackoverflow.com/a/31174427
Args:
obj: Object to retrieve the attribute from.
attr: Name of the attribute, with each successive attribute separated by a ".".
Returns:
Th... |
def draw_confusion_matrix(matrix):
'''Draw confusion matrix for MNIST.'''
fig = tfmpl.create_figure(figsize=(7,7))
ax = fig.add_subplot(111)
ax.set_title('Confusion matrix for MNIST classification')
tfmpl.plots.confusion_matrix.draw(
ax, matrix,
axis_labels=['Digit ' + str(x) fo... | Draw confusion matrix for MNIST. |
def import_ecdsakey_from_private_pem(pem, scheme='ecdsa-sha2-nistp256', password=None):
"""
<Purpose>
Import the private ECDSA key stored in 'pem', and generate its public key
(which will also be included in the returned ECDSA key object). In addition,
a keyid identifier for the ECDSA key is generated.... | <Purpose>
Import the private ECDSA key stored in 'pem', and generate its public key
(which will also be included in the returned ECDSA key object). In addition,
a keyid identifier for the ECDSA key is generated. The object returned
conforms to:
{'keytype': 'ecdsa-sha2-nistp256',
'scheme': 'e... |
def _deserialize_default(cls, cls_target, obj_raw):
"""
:type cls_target: T|type
:type obj_raw: int|str|bool|float|list|dict|None
:rtype: T
"""
if cls._is_deserialized(cls_target, obj_raw):
return obj_raw
elif type(obj_raw) == dict:
retur... | :type cls_target: T|type
:type obj_raw: int|str|bool|float|list|dict|None
:rtype: T |
def get_data_view(self, data_view_id):
"""
Retrieves a summary of information for a given data view
- view id
- name
- description
- columns
:param data_view_id: The ID number of the data view to which the
run belongs, as a string
... | Retrieves a summary of information for a given data view
- view id
- name
- description
- columns
:param data_view_id: The ID number of the data view to which the
run belongs, as a string
:type data_view_id: str |
def get_length(self):
"""
Calculate and return the length of the line as a sum of lengths
of all its segments.
:returns:
Total length in km.
"""
length = 0
for i, point in enumerate(self.points):
if i != 0:
length += point.... | Calculate and return the length of the line as a sum of lengths
of all its segments.
:returns:
Total length in km. |
def parametrize(self, operator, params):
"""
Return a parser that parses an operator with parameters.
"""
return (CaselessKeyword(operator, identChars=alphanums) +
self.parameter(params)) | Return a parser that parses an operator with parameters. |
def create(self, roomId=None, toPersonId=None, toPersonEmail=None,
text=None, markdown=None, files=None, **request_parameters):
"""Post a message, and optionally a attachment, to a room.
The files parameter is a list, which accepts multiple values to allow
for future expansion, b... | Post a message, and optionally a attachment, to a room.
The files parameter is a list, which accepts multiple values to allow
for future expansion, but currently only one file may be included with
the message.
Args:
roomId(basestring): The room ID.
toPersonId(ba... |
def strip_prompt(self, *args, **kwargs):
"""Strip the trailing router prompt from the output."""
a_string = super(FlexvnfSSH, self).strip_prompt(*args, **kwargs)
return self.strip_context_items(a_string) | Strip the trailing router prompt from the output. |
def generate_mix2pl_dataset(n, m, useDirichlet=True):
"""
Description:
Generate a mixture of 2 Plackett-Luce models dataset
and return the parameters and votes.
Parameters:
n: number of votes to generate
m: number of alternatives
useDiric... | Description:
Generate a mixture of 2 Plackett-Luce models dataset
and return the parameters and votes.
Parameters:
n: number of votes to generate
m: number of alternatives
useDirichlet: boolean flag to use the Dirichlet distribution |
def get_data_files(dirname):
"""Return data files in directory *dirname*"""
flist = []
for dirpath, _dirnames, filenames in os.walk(dirname):
for fname in filenames:
flist.append(osp.join(dirpath, fname))
return flist | Return data files in directory *dirname* |
def get_staff_updater(cls):
"""
This returns a function for passing to a signal.
"""
from django.core.exceptions import ImproperlyConfigured
if not issubclass(cls, BaseStaffMember):
raise ImproperlyConfigured("%s is not a sublass of StaffMember" % cls)
def update_staff_member(sender, in... | This returns a function for passing to a signal. |
def account_unfollow(self, id):
"""
Unfollow a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/unfollow'.format(str(id))
return self.__api_request('POST', url) | Unfollow a user.
Returns a `relationship dict`_ containing the updated relationship to the user. |
def find_video_detail_by_id(self, video_id, ext=None):
"""doc: http://cloud.youku.com/docs?id=46
"""
url = 'https://api.youku.com/videos/show.json'
params = {
'client_id': self.client_id,
'video_id': video_id
}
if ext:
params['ext'] = e... | doc: http://cloud.youku.com/docs?id=46 |
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler) | Unregister a property observer from *all* observed properties. |
def snapshots(self, xml_bytes):
"""Parse the XML returned by the C{DescribeSnapshots} function.
@param xml_bytes: XML bytes with a C{DescribeSnapshotsResponse} root
element.
@return: A list of L{Snapshot} instances.
TODO: ownersSet, restorableBySet, ownerId, volumeSize, des... | Parse the XML returned by the C{DescribeSnapshots} function.
@param xml_bytes: XML bytes with a C{DescribeSnapshotsResponse} root
element.
@return: A list of L{Snapshot} instances.
TODO: ownersSet, restorableBySet, ownerId, volumeSize, description,
ownerAlias. |
def my_application(api):
"""An example application.
- Registers a webhook with mbed cloud services
- Requests the value of a resource
- Prints the value when it arrives
"""
device = api.list_connected_devices().first()
print('using device #', device.id)
api.delete_device_subscriptions(d... | An example application.
- Registers a webhook with mbed cloud services
- Requests the value of a resource
- Prints the value when it arrives |
def convert_from_ik_angles(self, joints):
""" Convert from IKPY internal representation to poppy representation. """
if len(joints) != len(self.motors) + 2:
raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors) + 2))
joints = [rad2deg(j) for j in jo... | Convert from IKPY internal representation to poppy representation. |
def db_set_indexing(cls, is_indexing, impl, working_dir):
"""
Set lockfile path as to whether or not the system is indexing.
NOT THREAD SAFE, USE ONLY FOR CRASH DETECTION.
"""
indexing_lockfile_path = config.get_lockfile_filename(impl, working_dir)
if is_indexing:
... | Set lockfile path as to whether or not the system is indexing.
NOT THREAD SAFE, USE ONLY FOR CRASH DETECTION. |
def hist(self, dimension=None, num_bins=20, bin_range=None,
adjoin=True, individually=True, **kwargs):
"""Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
... | Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimension(s) to compute histogram on
num_bins (int, optional): Number of bins
bin_range (t... |
def get_extreme(self, target_prop, maximize=True, min_temp=None,
max_temp=None, min_doping=None, max_doping=None,
isotropy_tolerance=0.05, use_average=True):
"""
This method takes in eigenvalues over a range of carriers,
temperatures, and doping levels, a... | This method takes in eigenvalues over a range of carriers,
temperatures, and doping levels, and tells you what is the "best"
value that can be achieved for the given target_property. Note that
this method searches the doping dict only, not the full mu dict.
Args:
target_prop... |
def addNewLvls(self):
"""
+---------------------+----------------------+
| Standard Levels | New Levels |
+---------------+-----+----------------+-----+
| Name |Level| Name |Level|
+===============+=====+================+=====+
| ... | +---------------------+----------------------+
| Standard Levels | New Levels |
+---------------+-----+----------------+-----+
| Name |Level| Name |Level|
+===============+=====+================+=====+
| | |RAISEMSG | 99 ... |
def _find_exits(self, src_block, target_block):
"""
Source block has more than one exit, and through some of those exits, the control flow can eventually go to
the target block. This method returns exits that lead to the target block.
:param src_block: The block that has multiple ... | Source block has more than one exit, and through some of those exits, the control flow can eventually go to
the target block. This method returns exits that lead to the target block.
:param src_block: The block that has multiple exits.
:param target_block: The target block to reach.
... |
def make_stream_features(self, stream, features):
"""Add SASL features to the <features/> element of the stream.
[receving entity only]
:returns: update <features/> element."""
mechs = self.settings['sasl_mechanisms']
if mechs and not stream.authenticated:
sub = Ele... | Add SASL features to the <features/> element of the stream.
[receving entity only]
:returns: update <features/> element. |
def logpdf(x, shape, loc=0.0, scale=1.0, skewness=1.0):
"""
Log PDF for the Skew-t distribution
Parameters
----------
x : np.array
random variables
shape : float
The degrees of freedom for the skew-t distribution
loc : np.array
The location parameter for the skew-t... | Log PDF for the Skew-t distribution
Parameters
----------
x : np.array
random variables
shape : float
The degrees of freedom for the skew-t distribution
loc : np.array
The location parameter for the skew-t distribution
scale : float
The scale of the distributi... |
def json_schema_to_click_type(schema: dict) -> tuple:
"""
A generic handler of a single property JSON schema to :class:`click.ParamType` converter
:param schema: JSON schema property to operate on
:return: Tuple of :class:`click.ParamType`, `description`` of option and optionally a :class:`click.Choice... | A generic handler of a single property JSON schema to :class:`click.ParamType` converter
:param schema: JSON schema property to operate on
:return: Tuple of :class:`click.ParamType`, `description`` of option and optionally a :class:`click.Choice`
if the allowed values are a closed list (JSON schema ``enum... |
def repolist(status='', media=None):
"""
Get the list of ``yum`` repositories.
Returns enabled repositories by default. Extra *status* may be passed
to list disabled repositories if necessary.
Media and debug repositories are kept disabled, except if you pass *media*.
::
import burla... | Get the list of ``yum`` repositories.
Returns enabled repositories by default. Extra *status* may be passed
to list disabled repositories if necessary.
Media and debug repositories are kept disabled, except if you pass *media*.
::
import burlap
# Install a package that may be includ... |
def references(self):
""" list: External links, or references, listed anywhere on the \
MediaWiki page
Note:
Not settable
Note
May include external links within page that are not \
technically cited anywhere """
if... | list: External links, or references, listed anywhere on the \
MediaWiki page
Note:
Not settable
Note
May include external links within page that are not \
technically cited anywhere |
def calculate(self, scene, xaxis, yaxis):
"""
Calculates the grid data before rendering.
:param scene | <XChartScene>
xaxis | <XChartAxis>
yaxis | <XChartAxis>
"""
# build the grid location
s... | Calculates the grid data before rendering.
:param scene | <XChartScene>
xaxis | <XChartAxis>
yaxis | <XChartAxis> |
def _generate_main_files_header(notebook_object, notebook_title="Notebook Title",
notebook_description="Notebook Description"):
"""
Internal function that is used for generation of the 'MainFiles' notebooks header.
----------
Parameters
----------
notebook_object... | Internal function that is used for generation of the 'MainFiles' notebooks header.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the header will be created.
notebook_title : None or str
Title of the Notebook.
notebook_descr... |
def get_member_ids():
"""Return all member ids of the portal.
"""
pm = get_tool("portal_membership")
member_ids = pm.listMemberIds()
# How can it be possible to get member ids with None?
return filter(lambda x: x, member_ids) | Return all member ids of the portal. |
def aggregate(name):
""" Perform an aggregation request. """
cube = get_cube(name)
result = cube.aggregate(aggregates=request.args.get('aggregates'),
drilldowns=request.args.get('drilldown'),
cuts=request.args.get('cut'),
or... | Perform an aggregation request. |
def appendleft(self, item):
"""Add item to the left side of the GeventDeque.
This method does not block. Either the GeventDeque grows to
consume available memory, or if this GeventDeque has and is at
maxlen, the rightmost item is removed.
"""
self._deque.appendleft(item... | Add item to the left side of the GeventDeque.
This method does not block. Either the GeventDeque grows to
consume available memory, or if this GeventDeque has and is at
maxlen, the rightmost item is removed. |
def update_hpx_skymap_allsky(map_in, map_out):
""" 'Update' a HEALPix skymap
This checks map_out exists and creates it from map_in if it does not.
If map_out does exist, this adds the data in map_in to map_out
"""
if map_out is None:
in_hpx = map_in.hpx
out_hpx = HPX.create_hpx(in_h... | 'Update' a HEALPix skymap
This checks map_out exists and creates it from map_in if it does not.
If map_out does exist, this adds the data in map_in to map_out |
def Grieves_Thodos(zs, Tcs, Aijs):
r'''Calculates critical temperature of a mixture according to
mixing rules in [1]_.
.. math::
T_{cm} = \sum_{i} \frac{T_{ci}}{1 + (1/x_i)\sum_j A_{ij} x_j}
For a binary mxiture, this simplifies to:
.. math::
T_{cm} = \frac{T_{c1}}{1 + (x_2/x_1)A_... | r'''Calculates critical temperature of a mixture according to
mixing rules in [1]_.
.. math::
T_{cm} = \sum_{i} \frac{T_{ci}}{1 + (1/x_i)\sum_j A_{ij} x_j}
For a binary mxiture, this simplifies to:
.. math::
T_{cm} = \frac{T_{c1}}{1 + (x_2/x_1)A_{12}} + \frac{T_{c2}}
{1 + (x_... |
def create(self, title, description=None, private=False):
"""
Create a new collection.
This requires the 'write_collections' scope.
:param title [string]: The title of the collection. (Required.)
:param description [string]: The collection’s description. (Optional.)
:par... | Create a new collection.
This requires the 'write_collections' scope.
:param title [string]: The title of the collection. (Required.)
:param description [string]: The collection’s description. (Optional.)
:param private [boolean]: Whether to make this collection private. (Optional; defa... |
def _srvc_closing_routine(self, closing):
"""Routine to close an hdf5 file
The file is closed only when `closing=True`. `closing=True` means that
the file was opened in the current highest recursion level. This prevents re-opening
and closing of the file if `store` or `load` are called ... | Routine to close an hdf5 file
The file is closed only when `closing=True`. `closing=True` means that
the file was opened in the current highest recursion level. This prevents re-opening
and closing of the file if `store` or `load` are called recursively. |
def ggsave(name, plot, data=None, *args, **kwargs):
"""Save a GGStatements object to destination name
@param name output file name. if None, don't run R command
@param kwargs keyword args to pass to ggsave. The following are special
keywords for the python save method
data: a python da... | Save a GGStatements object to destination name
@param name output file name. if None, don't run R command
@param kwargs keyword args to pass to ggsave. The following are special
keywords for the python save method
data: a python data object (list, dict, DataFrame) used to populate
... |
def get_max_size(self, commands):
"""Returns the largest name length of the specified command list.
Parameters
------------
commands: Sequence[:class:`Command`]
A sequence of commands to check for the largest size.
Returns
--------
:class:`int`
... | Returns the largest name length of the specified command list.
Parameters
------------
commands: Sequence[:class:`Command`]
A sequence of commands to check for the largest size.
Returns
--------
:class:`int`
The maximum width of the commands. |
def inferTM(self, bottomUp, externalInput):
"""
Run inference and return the set of predicted cells
"""
self.reset()
# print >> sys.stderr, "Bottom up: ", bottomUp
# print >> sys.stderr, "ExternalInput: ",externalInput
self.tm.compute(bottomUp,
basalInput=externalInput,
... | Run inference and return the set of predicted cells |
def reset_query_marks(self):
"""
set or reset hyb and neighbors marks to atoms.
"""
for ml in (self.__reagents, self.__reactants, self.__products):
for m in ml:
if hasattr(m, 'reset_query_marks'):
m.reset_query_marks()
self.flush_ca... | set or reset hyb and neighbors marks to atoms. |
def formatmonth(self, theyear, themonth, withyear=True, net=None, qs=None, template='happenings/partials/calendar/month_table.html'):
"""Return a formatted month as a table."""
context = self.get_context()
context['month_start_date'] = date(self.yr, self.mo, 1)
context['week_rows'] = []
... | Return a formatted month as a table. |
def encode_float(encoder, pcm, frame_size, max_data_bytes):
"""Encodes an Opus frame from floating point input"""
pcm = ctypes.cast(pcm, c_float_pointer)
data = (ctypes.c_char * max_data_bytes)()
result = _encode_float(encoder, pcm, frame_size, data, max_data_bytes)
if result < 0:
raise Op... | Encodes an Opus frame from floating point input |
def getObj(self):
'''
getObj - Fetch (if not fetched) and return the obj associated with this data.
'''
if self.obj is None:
if not self.pk:
return None
self.obj = self.foreignModel.objects.get(self.pk)
return self.obj | getObj - Fetch (if not fetched) and return the obj associated with this data. |
def calculate_inner_product_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, C] ---> [N, C']
2. [N, C, 1, 1] ---> [N, C', 1, 1]
'''
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
check_input_and_output_types(operator, good_inp... | Allowed input/output patterns are
1. [N, C] ---> [N, C']
2. [N, C, 1, 1] ---> [N, C', 1, 1] |
def modprobe(module, persist=True):
"""Load a kernel module and configure for auto-load on reboot."""
cmd = ['modprobe', module]
log('Loading kernel module %s' % module, level=INFO)
subprocess.check_call(cmd)
if persist:
persistent_modprobe(module) | Load a kernel module and configure for auto-load on reboot. |
def get_settings(infile):
"""Read settings from input file.
:param infile: Input file for JSON settings.
:type infile: file or str path
:return: Settings parsed from file
:rtype: dict
"""
settings = yaml.load(_as_file(infile))
if not hasattr(settings, 'keys'):
raise ValueError("... | Read settings from input file.
:param infile: Input file for JSON settings.
:type infile: file or str path
:return: Settings parsed from file
:rtype: dict |
def _replace(self, data, replacements):
"""
Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result.
"""
for find, repl in replacements:
data = data.replace(find, repl)
return data | Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result. |
def combine_sources(sources, chunksize=None):
r""" Combines multiple data sources to stream from.
The given source objects (readers and transformers, eg. TICA) are concatenated in dimension axis during iteration.
This can be used to couple arbitrary features in order to pass them to an Estimator expecting ... | r""" Combines multiple data sources to stream from.
The given source objects (readers and transformers, eg. TICA) are concatenated in dimension axis during iteration.
This can be used to couple arbitrary features in order to pass them to an Estimator expecting only one source,
which is usually the case. Al... |
def battery2_send(self, voltage, current_battery, force_mavlink1=False):
'''
2nd Battery status
voltage : voltage in millivolts (uint16_t)
current_battery : Battery current, in 10*milliamperes (1 = 10 milliampere), -1: autopilo... | 2nd Battery status
voltage : voltage in millivolts (uint16_t)
current_battery : Battery current, in 10*milliamperes (1 = 10 milliampere), -1: autopilot does not measure the current (int16_t) |
def findLibrary(name):
"""
Look for a library in the system.
Emulate the algorithm used by dlopen.
`name`must include the prefix, e.g. ``libpython2.4.so``
"""
assert is_unix, "Current implementation for Unix only (Linux, Solaris, AIX)"
lib = None
# Look in the LD_LIBRARY_PATH
lp =... | Look for a library in the system.
Emulate the algorithm used by dlopen.
`name`must include the prefix, e.g. ``libpython2.4.so`` |
def upload(self, photo_file, **kwds):
"""
Endpoint: /photo/upload.json
Uploads the specified photo filename.
"""
with open(photo_file, 'rb') as in_file:
result = self._client.post("/photo/upload.json",
files={'photo': in_file},
... | Endpoint: /photo/upload.json
Uploads the specified photo filename. |
def _filter_dates(dates, time_difference):
"""
Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list... | Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list of datetimes `d1<=d2<=...<=dn` such that `d[i+1]-di > time_dif... |
def convert_embedding(net, node, model, builder):
"""Convert an embedding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A ne... | Convert an embedding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. |
def enable_api_key(apiKey, region=None, key=None, keyid=None, profile=None):
'''
enable the given apiKey.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.enable_api_key api_key
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | enable the given apiKey.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.enable_api_key api_key |
def _update_list_store(config_m, list_store, ignore_keys=None):
"""Generic method to create list store for a given config model
:param ConfigModel config_m: Config model to read into list store
:param Gtk.ListStore list_store: List store to be filled
:param list ignore_keys: List of key... | Generic method to create list store for a given config model
:param ConfigModel config_m: Config model to read into list store
:param Gtk.ListStore list_store: List store to be filled
:param list ignore_keys: List of keys that should be ignored |
def get_context_data(self, **kwargs):
"""
Hook for adding arguments to the context.
"""
context = {'obj': self.object }
if 'queryset' in kwargs:
context['conf_msg'] = self.get_confirmation_message(kwargs['queryset'])
context.update(kwargs)
return cont... | Hook for adding arguments to the context. |
def get_linenumbers(functions, module, searchstr='def {}(image):\n'):
"""Returns a dictionary which maps function names to line numbers.
Args:
functions: a list of function names
module: the module to look the functions up
searchstr: the string to search for
Returns:
A di... | Returns a dictionary which maps function names to line numbers.
Args:
functions: a list of function names
module: the module to look the functions up
searchstr: the string to search for
Returns:
A dictionary with functions as keys and their line numbers as values. |
def start(self):
"""Start the logger background synchronization service. This allows you to not need to
worry about syncing with ConnectorDB - you just insert into the Logger, and the Logger
will by synced every syncperiod."""
with self.synclock:
if self.syncthread is not No... | Start the logger background synchronization service. This allows you to not need to
worry about syncing with ConnectorDB - you just insert into the Logger, and the Logger
will by synced every syncperiod. |
def update_sma(self, step):
"""
Calculate an updated value for the semimajor axis, given the
current value and the step value.
The step value must be managed by the caller to support both
modes: grow outwards and shrink inwards.
Parameters
----------
ste... | Calculate an updated value for the semimajor axis, given the
current value and the step value.
The step value must be managed by the caller to support both
modes: grow outwards and shrink inwards.
Parameters
----------
step : float
The step value.
R... |
def run(self, quil_program, classical_addresses: List[int] = None,
trials=1):
"""
Run a Quil program multiple times, accumulating the values deposited in
a list of classical addresses.
:param Program quil_program: A Quil program.
:param classical_addresses: The class... | Run a Quil program multiple times, accumulating the values deposited in
a list of classical addresses.
:param Program quil_program: A Quil program.
:param classical_addresses: The classical memory to retrieve. Specified as a list of
integers that index into a readout register named ... |
def detect(agent, fill_none=False):
"""
fill_none: if name/version is not detected respective key is still added to the result with value None
"""
result = dict(platform=dict(name=None, version=None))
_suggested_detectors = []
for info_type in detectorshub:
detectors = _suggested_detect... | fill_none: if name/version is not detected respective key is still added to the result with value None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.