code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _OpenCollectionPath(coll_path):
"""Tries to open various types of collections at the given path."""
hunt_collection = results.HuntResultCollection(coll_path)
if hunt_collection and hunt_collection[0].payload:
return hunt_collection
indexed_collection = sequential_collection.GeneralIndexedCollection(col... | Tries to open various types of collections at the given path. |
def unpack_rsp(cls, rsp_pb):
"""Unpack the init connect response"""
ret_type = rsp_pb.retType
ret_msg = rsp_pb.retMsg
if ret_type != RET_OK:
return RET_ERROR, ret_msg, None
res = {}
if rsp_pb.HasField('s2c'):
res['server_version'] = rsp_pb.s2c.se... | Unpack the init connect response |
def setup(applicationName,
applicationType=None,
style='plastique',
splash='',
splashType=None,
splashTextColor='white',
splashTextAlign=None,
theme=''):
"""
Wrapper system for the QApplication creation process to handle all proper
... | Wrapper system for the QApplication creation process to handle all proper
pre-application setup. This method will verify that there is no application
running, creating one if necessary. If no application is created, a None
value is returned - signaling that there is already an app running. If you
... |
def _call(self, method, params):
"""Retrive the given resource.
:param resource: resource to retrieve
:param params: dict with the HTTP parameters needed to retrieve
the given resource
"""
url = self.base_url % {'token': self.bot_token, 'method': method}
log... | Retrive the given resource.
:param resource: resource to retrieve
:param params: dict with the HTTP parameters needed to retrieve
the given resource |
def _export_to2marc(self, key, value):
"""Populate the ``595`` MARC field."""
def _is_for_cds(value):
return 'CDS' in value
def _is_for_hal(value):
return 'HAL' in value and value['HAL']
def _is_not_for_hal(value):
return 'HAL' in value and not value['HAL']
result = []
... | Populate the ``595`` MARC field. |
def pubkey(self, identity, ecdh=False):
"""Return public key."""
curve_name = identity.get_curve_name(ecdh=ecdh)
log.debug('"%s" getting public key (%s) from %s',
identity.to_string(), curve_name, self)
addr = identity.get_bip32_address(ecdh=ecdh)
result = self.... | Return public key. |
def set_seed(seed: int):
""" Set random seed for python, numpy and pytorch RNGs """
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed) | Set random seed for python, numpy and pytorch RNGs |
def loadFromCheckpoint(savedModelDir, newSerialization=False):
""" Load saved model.
:param savedModelDir: (string)
Directory of where the experiment is to be or was saved
:returns: (:class:`nupic.frameworks.opf.model.Model`) The loaded model
instance.
"""
if newSerializati... | Load saved model.
:param savedModelDir: (string)
Directory of where the experiment is to be or was saved
:returns: (:class:`nupic.frameworks.opf.model.Model`) The loaded model
instance. |
def baseline(y_true, y_score=None):
"""
Number of positive labels divided by number of labels,
or zero if there are no labels
"""
if len(y_true) > 0:
return np.nansum(y_true)/count(y_true, countna=False)
else:
return 0.0 | Number of positive labels divided by number of labels,
or zero if there are no labels |
def create_entity(self):
"""Create a new entity.
The entity will have a higher UID than any previously associated
with this world.
:return: the new entity
:rtype: :class:`essence.Entity`"""
self._highest_id_seen += 1
entity = Entity(self._highest_id_seen, self)
... | Create a new entity.
The entity will have a higher UID than any previously associated
with this world.
:return: the new entity
:rtype: :class:`essence.Entity` |
async def _connect_and_read(self):
"""Retreives and connects to Slack's RTM API.
Makes an authenticated call to Slack's RTM API to retrieve
a websocket URL. Then connects to the message server and
reads event messages as they come in.
If 'auto_reconnect' is specified we
... | Retreives and connects to Slack's RTM API.
Makes an authenticated call to Slack's RTM API to retrieve
a websocket URL. Then connects to the message server and
reads event messages as they come in.
If 'auto_reconnect' is specified we
retrieve a new url and reconnect any time the... |
def compile_compiler_bridge(self, context):
"""Compile the compiler bridge to be used by zinc, using our scala bootstrapper.
It will compile and cache the jar, and materialize it if not already there.
:param context: The context of the task trying to compile the bridge.
This is mostly n... | Compile the compiler bridge to be used by zinc, using our scala bootstrapper.
It will compile and cache the jar, and materialize it if not already there.
:param context: The context of the task trying to compile the bridge.
This is mostly needed to use its scheduler to create digests of the... |
def from_int(cls, integer):
"""
Constructs a `Deleted` using the `tinyint` value of the `rev_deleted`
column of the `revision` MariaDB table.
* DELETED_TEXT = 1
* DELETED_COMMENT = 2
* DELETED_USER = 4
* DELETED_RESTRICTED = 8
"""
bin_string = bin... | Constructs a `Deleted` using the `tinyint` value of the `rev_deleted`
column of the `revision` MariaDB table.
* DELETED_TEXT = 1
* DELETED_COMMENT = 2
* DELETED_USER = 4
* DELETED_RESTRICTED = 8 |
def normalize(pw):
""" Lower case, and change the symbols to closest characters"""
pw_lower = pw.lower()
return ''.join(helper.L33T.get(c, c) for c in pw_lower) | Lower case, and change the symbols to closest characters |
def _MergeTaskStorage(self, storage_writer):
"""Merges a task storage with the session storage.
This function checks all task stores that are ready to merge and updates
the scheduled tasks. Note that to prevent this function holding up
the task scheduling loop only the first available task storage is m... | Merges a task storage with the session storage.
This function checks all task stores that are ready to merge and updates
the scheduled tasks. Note that to prevent this function holding up
the task scheduling loop only the first available task storage is merged.
Args:
storage_writer (StorageWrite... |
def run_task_class(self, class_path, **options):
""" Runs a CumulusCI task class with task options via kwargs.
Use this keyword to run logic from CumulusCI tasks which have not
been configured in the project's cumulusci.yml file. This is
most useful in cases where a test ne... | Runs a CumulusCI task class with task options via kwargs.
Use this keyword to run logic from CumulusCI tasks which have not
been configured in the project's cumulusci.yml file. This is
most useful in cases where a test needs to use task logic for
logic unique to the tes... |
def pyquil_to_tk(prog: Program) -> Circuit:
"""
Convert a :py:class:`pyquil.Program` to a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` .
Note that not all pyQuil operations are currently supported by pytket.
:param prog: A circuit to be converted
:return: The converted circuit
"""
... | Convert a :py:class:`pyquil.Program` to a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` .
Note that not all pyQuil operations are currently supported by pytket.
:param prog: A circuit to be converted
:return: The converted circuit |
def disconnect_node(node, target_obj_result, graph, debug):
""" Disconnects `node` from `target_obj`
Args
----
node: LVLoadAreaCentreDing0, i.e.
Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0)
target_obj_result: LVLoadAreaCentreDing0, i.e.
Origin node - Ding0 graph obj... | Disconnects `node` from `target_obj`
Args
----
node: LVLoadAreaCentreDing0, i.e.
Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0)
target_obj_result: LVLoadAreaCentreDing0, i.e.
Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0)
graph: :networkx:`NetworkX Grap... |
def set_card_standard(self, title, text, smallImageUrl=None,
largeImageUrl=None):
"""Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. ... | Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. Content of Standard type card.
smallImageUrl: str. URL of small image. Cannot exceed 2,000
... |
def posthoc_mackwolfe(a, val_col, group_col, p=None, n_perm=100, sort=False, p_adjust=None):
'''Mack-Wolfe Test for Umbrella Alternatives.
In dose-finding studies one may assume an increasing treatment effect with
increasing dose level. However, the test subject may actually succumb to
toxic effects a... | Mack-Wolfe Test for Umbrella Alternatives.
In dose-finding studies one may assume an increasing treatment effect with
increasing dose level. However, the test subject may actually succumb to
toxic effects at high doses, which leads to decresing treatment
effects [1]_, [2]_.
The scope of the Mack-W... |
def _read_dataset_metadata(self):
"""Reads dataset metadata.
Returns:
instance of DatasetMetadata
"""
blob = self.storage_client.get_blob(
'dataset/' + self.dataset_name + '_dataset.csv')
buf = BytesIO()
blob.download_to_file(buf)
buf.seek(0)
return eval_lib.DatasetMetadat... | Reads dataset metadata.
Returns:
instance of DatasetMetadata |
def _create_key_manager(self, get_match_fuzzy, set_match_fuzzy,
get_enable_vi_bindings, set_enable_vi_bindings,
get_show_completion_columns,
set_show_completion_columns,
get_show_help, set_show_help,
... | Create and initialize the keybinding manager.
:type get_fuzzy_match: callable
:param get_fuzzy_match: Gets the fuzzy matching config.
:type set_fuzzy_match: callable
:param set_fuzzy_match: Sets the fuzzy matching config.
:type get_enable_vi_bindings: callable
:param g... |
def install_config_kibana(self):
"""
install and config kibana
:return:
"""
if self.prompt_check("Download and install kibana"):
self.kibana_install()
if self.prompt_check("Configure and autostart kibana"):
self.kibana_config() | install and config kibana
:return: |
def sudoku(G):
"""Solving Sudoku
:param G: integer matrix with 0 at empty cells
:returns bool: True if grid could be solved
:modifies: G will contain the solution
:complexity: huge, but linear for usual published 9x9 grids
"""
global N, N2, N4
if len(G) == 16: # for a 16 x ... | Solving Sudoku
:param G: integer matrix with 0 at empty cells
:returns bool: True if grid could be solved
:modifies: G will contain the solution
:complexity: huge, but linear for usual published 9x9 grids |
def result(self):
"""
The result of the job if available
throws ValueError is result is not available yet
throws ApiError if server returned an error indicating program execution was not successful
or if the job was cancelled
"""
if not self.is_done():
... | The result of the job if available
throws ValueError is result is not available yet
throws ApiError if server returned an error indicating program execution was not successful
or if the job was cancelled |
def skip(self, regex):
"""
Like :meth:`scan`, but return the number of characters matched.
>>> s = Scanner("test string")
>>> s.skip('test ')
5
"""
return self.scan_full(regex, return_string=False, advance_pointer=True) | Like :meth:`scan`, but return the number of characters matched.
>>> s = Scanner("test string")
>>> s.skip('test ')
5 |
def write_csvs(self, dirname: PathLike, skip_data: bool = True, sep: str = ','):
"""Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
---... | Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
----------
dirname
Name of directory to which to export.
skip_data
... |
def detx(self, det_id, t0set=None, calibration=None):
"""Retrieve the detector file for given detector id
If t0set is given, append the calibration data.
"""
url = 'detx/{0}?'.format(det_id) # '?' since it's ignored if no args
if t0set is not None:
url += '&t0set=... | Retrieve the detector file for given detector id
If t0set is given, append the calibration data. |
def flag(self, key, env=None):
"""Feature flagging system
write flags to redis
$ dynaconf write redis -s DASHBOARD=1 -e premiumuser
meaning: Any premium user has DASHBOARD feature enabled
In your program do::
# premium user has access to dashboard?
>>> i... | Feature flagging system
write flags to redis
$ dynaconf write redis -s DASHBOARD=1 -e premiumuser
meaning: Any premium user has DASHBOARD feature enabled
In your program do::
# premium user has access to dashboard?
>>> if settings.flag('dashboard', 'premiumuser'... |
def __create_dir_property(self, dir_name, docstring):
"""
Generate getter and setter for a directory property.
"""
property_name = "{}_dir".format(dir_name)
private_name = "_" + property_name
setattr(self, private_name, None)
def fget(self):
return g... | Generate getter and setter for a directory property. |
def get_resource_search_session_for_bin(self, bin_id):
"""Gets a resource search session for the given bin.
arg: bin_id (osid.id.Id): the ``Id`` of the bin
return: (osid.resource.ResourceSearchSession) - ``a
ResourceSearchSession``
raise: NotFound - ``bin_id`` not fo... | Gets a resource search session for the given bin.
arg: bin_id (osid.id.Id): the ``Id`` of the bin
return: (osid.resource.ResourceSearchSession) - ``a
ResourceSearchSession``
raise: NotFound - ``bin_id`` not found
raise: NullArgument - ``bin_id`` is ``null``
... |
def select_inputs(self, address: str, amount: int) -> dict:
'''finds apropriate utxo's to include in rawtx, while being careful
to never spend old transactions with a lot of coin age.
Argument is intiger, returns list of apropriate UTXO's'''
utxos = []
utxo_sum = Decimal(0)
... | finds apropriate utxo's to include in rawtx, while being careful
to never spend old transactions with a lot of coin age.
Argument is intiger, returns list of apropriate UTXO's |
def lookup_users(self, user_ids=None, screen_names=None, include_entities=None, tweet_mode=None):
""" Perform bulk look up of users from user ID or screen_name """
post_data = {}
if include_entities is not None:
include_entities = 'true' if include_entities else 'false'
p... | Perform bulk look up of users from user ID or screen_name |
def register(self, name, obj):
"""Registers an unique type description"""
if name in self.all:
log.debug('register: %s already existed: %s', name, obj.name)
# code.interact(local=locals())
raise DuplicateDefinitionException(
'register: %s already exist... | Registers an unique type description |
def replace_cluster_role(self, name, body, **kwargs):
"""
replace the specified ClusterRole
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_cluster_role(name, body, async_req=True)
... | replace the specified ClusterRole
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_cluster_role(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:... |
def create(
name,
attributes=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Create an SQS queue.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.create myqueue region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, pr... | Create an SQS queue.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.create myqueue region=us-east-1 |
def run(self, *, delay=None):
"""Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself.
"""
self.broker.enqueue(self.messages[0], delay=delay)
... | Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself. |
def find_max_label_length(labels):
"""Return the maximum length for the labels."""
length = 0
for i in range(len(labels)):
if len(labels[i]) > length:
length = len(labels[i])
return length | Return the maximum length for the labels. |
def index_of_reports(self, report, account_id):
"""
Index of Reports.
Shows all reports that have been run for the account of a specific type.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["a... | Index of Reports.
Shows all reports that have been run for the account of a specific type. |
def __get_translation(self, surah, ayah, lang):
"""
Perform http request to get translation from given surah, ayah and
language.
Parameter:
:surah -- Surah index from API pages.
:ayat -- Ayat key.
:lang -- Language code.
R... | Perform http request to get translation from given surah, ayah and
language.
Parameter:
:surah -- Surah index from API pages.
:ayat -- Ayat key.
:lang -- Language code.
Return:
:string -- Translation from given surah and ... |
def convertPixelXYToLngLat(self, pixelX, pixelY, level):
'''
converts a pixel x, y to a latitude and longitude.
'''
mapSize = self.getMapDimensionsByZoomLevel(level)
x = (self.clipValue(pixelX, 0, mapSize - 1) / mapSize) - 0.5
y = 0.5 - (self.clipValue(pixelY, 0, mapSize ... | converts a pixel x, y to a latitude and longitude. |
def onRefreshPluginData(self, plugin_name, data):
"""
Frontend requests a data refresh
:param plugin_name: Name of plugin that changed
:type plugin_name: str
:param data: Additional data
:type data: None
:rtype: None
"""
logger.info(u"onRefreshPlu... | Frontend requests a data refresh
:param plugin_name: Name of plugin that changed
:type plugin_name: str
:param data: Additional data
:type data: None
:rtype: None |
def roundness(im):
"""
from astropy.io import fits as pyfits
data=pyfits.getdata('j94f05bgq_flt.fits',ext=1)
star0=data[403:412,423:432]
star=data[396:432,3522:3558]
In [53]: findobj.roundness(star0)
Out[53]: 0.99401955054989544
In [54]: findobj.roundness(star)
Out[54]: 0.83091919980... | from astropy.io import fits as pyfits
data=pyfits.getdata('j94f05bgq_flt.fits',ext=1)
star0=data[403:412,423:432]
star=data[396:432,3522:3558]
In [53]: findobj.roundness(star0)
Out[53]: 0.99401955054989544
In [54]: findobj.roundness(star)
Out[54]: 0.83091919980660645 |
def _namify_arguments(mapping):
"""
Ensure that a mapping of names to parameters has the parameters set to the
correct name.
"""
result = []
for name, parameter in mapping.iteritems():
parameter.name = name
result.append(parameter)
return result | Ensure that a mapping of names to parameters has the parameters set to the
correct name. |
def copy_path_to_clipboard(i):
"""
Input: {
(add_quotes) - if 'yes', add quotes
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
... | Input: {
(add_quotes) - if 'yes', add quotes
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
} |
def has_delete_permission(self, request, obj=None):
"""
Implement a lookup for object level permissions. Basically the same as
ModelAdmin.has_delete_permission, but also passes the obj parameter in.
"""
if settings.TREE_EDITOR_OBJECT_PERMISSIONS:
opts = self.opts
... | Implement a lookup for object level permissions. Basically the same as
ModelAdmin.has_delete_permission, but also passes the obj parameter in. |
def get_graphviz_dirtree(self, engine="automatic", **kwargs):
"""
Generate directory graph in the DOT language. The graph show the files and directories
in the node workdir.
Returns: graphviz.Digraph <https://graphviz.readthedocs.io/en/stable/api.html#digraph>
"""
if eng... | Generate directory graph in the DOT language. The graph show the files and directories
in the node workdir.
Returns: graphviz.Digraph <https://graphviz.readthedocs.io/en/stable/api.html#digraph> |
def list_vm_images_sub(access_token, subscription_id):
'''List VM images in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of a list of VM images.
'''
endpoint = '... | List VM images in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of a list of VM images. |
def build_and_start(query, directory):
"""This function will create and then start a new Async task with the
default callbacks argument defined in the decorator."""
Async(target=grep, args=[query, directory]).start() | This function will create and then start a new Async task with the
default callbacks argument defined in the decorator. |
def _get_pos(self):
"""
Get current position for scroll bar.
"""
if self._canvas.height >= self._max_height:
return 0
else:
return self._canvas.start_line / (self._max_height - self._canvas.height + 1) | Get current position for scroll bar. |
def proto_01_13_steps025dual(abf=exampleABF):
"""IC steps. See how hyperpol. step affects things."""
swhlab.ap.detect(abf)
standard_groupingForInj(abf,200)
for feature in ['freq','downslope']:
swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info
swhlab.plot.save(abf,tag='A_... | IC steps. See how hyperpol. step affects things. |
def discard_between(
self,
min_rank=None,
max_rank=None,
min_score=None,
max_score=None,
):
"""
Remove members whose ranking is between *min_rank* and *max_rank*
OR whose score is between *min_score* and *max_score* (both ranges
inclusive). If ... | Remove members whose ranking is between *min_rank* and *max_rank*
OR whose score is between *min_score* and *max_score* (both ranges
inclusive). If no bounds are specified, no members will be removed. |
def handle_register_or_upload(post_data, files, user, repository):
"""Process a `register` or `upload` comment issued via distutils.
This method is called with the authenticated user.
"""
name = post_data.get('name')
version = post_data.get('version')
if settings.LOCALSHOP_VERSIONING_TYPE:
... | Process a `register` or `upload` comment issued via distutils.
This method is called with the authenticated user. |
def _hexify(data, chunksize=None):
"""Convert a binary string into its hex encoding, broken up into chunks
of I{chunksize} characters separated by a space.
@param data: the binary string
@type data: string
@param chunksize: the chunk size. Default is L{dns.rdata._hex_chunksize}
@rtype: string
... | Convert a binary string into its hex encoding, broken up into chunks
of I{chunksize} characters separated by a space.
@param data: the binary string
@type data: string
@param chunksize: the chunk size. Default is L{dns.rdata._hex_chunksize}
@rtype: string |
def _update_scsi_devices(scsis_old_new, current_disks):
'''
Returns a list of vim.vm.device.VirtualDeviceSpec specifying the scsi
properties as input the old and new configs are defined in a dictionary.
scsi_diffs
List of old and new scsi properties
'''
device_config_specs = []
if ... | Returns a list of vim.vm.device.VirtualDeviceSpec specifying the scsi
properties as input the old and new configs are defined in a dictionary.
scsi_diffs
List of old and new scsi properties |
def _get_subcats(self, recurse=False):
""" Get the subcategories of this category
recurse -- whether to include their subcategories as well
"""
if recurse:
# No need to filter
return sorted([Category(e) for e in self._subcats_recursive],
... | Get the subcategories of this category
recurse -- whether to include their subcategories as well |
def reindex_model_on_save(sender, document, **kwargs):
'''(Re/Un)Index Mongo document on post_save'''
if current_app.config.get('AUTO_INDEX'):
reindex.delay(document) | (Re/Un)Index Mongo document on post_save |
def dataframe_to_smp(dataframe,smp_filename,name_col="name",
datetime_col="datetime",value_col="value",
datetime_format="dd/mm/yyyy",
value_format="{0:15.6E}",
max_name_len=12):
""" write a dataframe as an smp file
Parameters
... | write a dataframe as an smp file
Parameters
----------
dataframe : pandas.DataFrame
smp_filename : str
smp file to write
name_col: str
the column in the dataframe the marks the site namne
datetime_col: str
the column in the dataframe that is a datetime instance
value... |
def copyKeyMultipart(srcBucketName, srcKeyName, srcKeyVersion, dstBucketName, dstKeyName, sseAlgorithm=None, sseKey=None,
copySourceSseAlgorithm=None, copySourceSseKey=None):
"""
Copies a key from a source key to a destination key in multiple parts. Note that if the
destination key exis... | Copies a key from a source key to a destination key in multiple parts. Note that if the
destination key exists it will be overwritten implicitly, and if it does not exist a new
key will be created. If the destination bucket does not exist an error will be raised.
:param str srcBucketName: The name of the b... |
def _set_tieBreaking(self, v, load=False):
"""
Setter method for tieBreaking, mapped from YANG variable /brocade_mpls_rpc/show_mpls_te_path/input/tieBreaking (tie-breaking)
If this variable is read-only (config: false) in the
source YANG file, then _set_tieBreaking is considered as a private
method.... | Setter method for tieBreaking, mapped from YANG variable /brocade_mpls_rpc/show_mpls_te_path/input/tieBreaking (tie-breaking)
If this variable is read-only (config: false) in the
source YANG file, then _set_tieBreaking is considered as a private
method. Backends looking to populate this variable should
... |
def fit(self, Xs=None, ys=None, Xt=None, yt=None):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like,... | Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The class labels
... |
def process_json(filename):
"""
Converts a DOE CODE .json file into DOE CODE projects
Yields DOE CODE records from a DOE CODE .json file
"""
logger.debug('Processing DOE CODE json: %s', filename)
doecode_json = json.load(open(filename))
for record in doecode_json['records']:
yield... | Converts a DOE CODE .json file into DOE CODE projects
Yields DOE CODE records from a DOE CODE .json file |
def verify(password_hash, password):
"""
Takes the output of scryptsalsa208sha256 and compares it against
a user provided password to see if they are the same
:param password_hash: bytes
:param password: bytes
:rtype: boolean
.. versionadded:: 1.2
"""
ensure(len(password_hash) == ... | Takes the output of scryptsalsa208sha256 and compares it against
a user provided password to see if they are the same
:param password_hash: bytes
:param password: bytes
:rtype: boolean
.. versionadded:: 1.2 |
def ogr2ogr(src, dst, options):
"""
a simple wrapper for gdal.VectorTranslate aka `ogr2ogr <https://www.gdal.org/ogr2ogr.html>`_
Parameters
----------
src: str or :osgeo:class:`ogr.DataSource`
the input data set
dst: str
the output data set
options: dict
additional p... | a simple wrapper for gdal.VectorTranslate aka `ogr2ogr <https://www.gdal.org/ogr2ogr.html>`_
Parameters
----------
src: str or :osgeo:class:`ogr.DataSource`
the input data set
dst: str
the output data set
options: dict
additional parameters passed to gdal.VectorTranslate;
... |
def create_waveform_generator(variable_params, data,
recalibration=None, gates=None,
**static_params):
"""Creates a waveform generator for use with a model.
Parameters
----------
variable_params : list of str
The names of the parameter... | Creates a waveform generator for use with a model.
Parameters
----------
variable_params : list of str
The names of the parameters varied.
data : dict
Dictionary mapping detector names to either a
:py:class:`<pycbc.types.TimeSeries TimeSeries>` or
:py:class:`<pycbc.types... |
def network_profile_name_list(self, obj):
"""Get AP profile names."""
profile_list = pointer(WLAN_PROFILE_INFO_LIST())
self._wlan_get_profile_list(self._handle,
byref(obj['guid']),
byref(profile_list))
profiles = ca... | Get AP profile names. |
def _all_recall_native_type(self, data, ptitem, prefix):
"""Checks if loaded data has the type it was stored in. If not converts it.
:param data: Data item to be checked and converted
:param ptitem: HDf5 Node or Leaf from where data was loaded
:param prefix: Prefix for recalling the dat... | Checks if loaded data has the type it was stored in. If not converts it.
:param data: Data item to be checked and converted
:param ptitem: HDf5 Node or Leaf from where data was loaded
:param prefix: Prefix for recalling the data type from the hdf5 node attributes
:return:
... |
def DictReader(ltsvfile, labels=None, dict_type=dict):
"""Make LTSV Reader for reading selected labels.
:param ltsvfile: iterable of lines.
:param labels: sequence of labels.
:return: generator of record in {label: value, ...} form.
"""
for rec in reader(ltsvfile, labels):
yield dict_... | Make LTSV Reader for reading selected labels.
:param ltsvfile: iterable of lines.
:param labels: sequence of labels.
:return: generator of record in {label: value, ...} form. |
def get_feature_variable_boolean(self, feature_key, variable_key, user_id, attributes=None):
""" Returns value for a certain boolean variable attached to a feature flag.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is ... | Returns value for a certain boolean variable attached to a feature flag.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
... |
def __try_parse_number(self, string):
"""Try to parse a string to a number, else return False."""
try:
return int(string)
except ValueError:
try:
return float(string)
except ValueError:
return False | Try to parse a string to a number, else return False. |
def block_compute(x_start, x_stop,
y_start, y_stop,
z_start, z_stop,
origin=(0, 0, 0),
block_size=(512, 512, 16)):
"""
Get bounding box coordinates (in 3D) of small cutouts to request in
order to reconstitute a larger cutout.
Argum... | Get bounding box coordinates (in 3D) of small cutouts to request in
order to reconstitute a larger cutout.
Arguments:
x_start (int): The lower bound of dimension x
x_stop (int): The upper bound of dimension x
y_start (int): The lower bound of dimension y
y_stop (int): The upper ... |
def d3logpdf_dlink3(self, link_f, y, Y_metadata=None):
"""
Third order derivative log-likelihood function at y given link(f) w.r.t link(f)
.. math::
\\frac{d^{3} \\ln p(y_{i}|\\lambda(f_{i}))}{d^{3}\\lambda(f)} = 0
:param link_f: latent variables link(f)
:type link_... | Third order derivative log-likelihood function at y given link(f) w.r.t link(f)
.. math::
\\frac{d^{3} \\ln p(y_{i}|\\lambda(f_{i}))}{d^{3}\\lambda(f)} = 0
:param link_f: latent variables link(f)
:type link_f: Nx1 array
:param y: data
:type y: Nx1 array
:par... |
def loc(lexer: Lexer, start_token: Token) -> Optional[Location]:
"""Return a location object.
Used to identify the place in the source that created a given parsed object.
"""
if not lexer.no_location:
end_token = lexer.last_token
source = lexer.source
return Location(
... | Return a location object.
Used to identify the place in the source that created a given parsed object. |
def union(self, sig: Scope) -> Scope:
""" Create a new Set produce by the union of 2 Set """
new = Scope(sig=self._hsig.values(), state=self.state)
new |= sig
return new | Create a new Set produce by the union of 2 Set |
def filer(filelist):
"""
Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension)
:param filelist: list of files to parse
:return filedict: dictionary of stain name: /sequencepath/strain_name.extension
"""
# Initialise the dictionary
filedict = dict()
... | Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension)
:param filelist: list of files to parse
:return filedict: dictionary of stain name: /sequencepath/strain_name.extension |
def initialize_tracer(self, io_loop=None):
"""
Initialize Jaeger Tracer based on the passed `jaeger_client.Config`.
Save it to `opentracing.tracer` global variable.
Only the first call to this method has any effect.
"""
with Config._initialized_lock:
if Confi... | Initialize Jaeger Tracer based on the passed `jaeger_client.Config`.
Save it to `opentracing.tracer` global variable.
Only the first call to this method has any effect. |
def runDia(diagram):
"""Generate the diagrams using Dia."""
ifname = '{}.dia'.format(diagram)
ofname = '{}.png'.format(diagram)
cmd = 'dia -t png-libart -e {} {}'.format(ofname, ifname)
print(' {}'.format(cmd))
subprocess.call(cmd, shell=True)
return True | Generate the diagrams using Dia. |
def edit(self, obj_id, parameters, create_if_not_exists=False):
"""
Edit an item with option to create if it doesn't exist
:param obj_id: int
:param create_if_not_exists: bool
:param parameters: dict
:return: dict|str
"""
if create_if_not_exists:
... | Edit an item with option to create if it doesn't exist
:param obj_id: int
:param create_if_not_exists: bool
:param parameters: dict
:return: dict|str |
def ns(self):
"""Get the namespace of a node """
ret = libxml2mod.xmlNodeGetNs(self._o)
if ret is None:return None
__tmp = xmlNs(_obj=ret)
return __tmp | Get the namespace of a node |
def minOpar(self,dangle,tdisrupt=None,_return_raw=False):
"""
NAME:
minOpar
PURPOSE:
return the approximate minimum parallel frequency at a given angle
INPUT:
dangle - parallel angle
OUTPUT:
minimum frequency that gets to this pa... | NAME:
minOpar
PURPOSE:
return the approximate minimum parallel frequency at a given angle
INPUT:
dangle - parallel angle
OUTPUT:
minimum frequency that gets to this parallel angle
HISTORY:
2015-12-28 - Written - Bovy (UofT) |
def request(self, method, url, erc, **kwargs):
"""Abstract base method for making requests to the Webex Teams APIs.
This base method:
* Expands the API endpoint URL to an absolute URL
* Makes the actual HTTP request to the API endpoint
* Provides support for Webex Te... | Abstract base method for making requests to the Webex Teams APIs.
This base method:
* Expands the API endpoint URL to an absolute URL
* Makes the actual HTTP request to the API endpoint
* Provides support for Webex Teams rate-limiting
* Inspects response codes an... |
def compose(*funcs):
"""Compose `funcs` to a single function.
>>> compose(operator.abs, operator.add)(-2,-3)
5
>>> compose()('nada')
'nada'
>>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2)
[1, 2]
"""
# slightly optimized for most common cases and hence verbose
i... | Compose `funcs` to a single function.
>>> compose(operator.abs, operator.add)(-2,-3)
5
>>> compose()('nada')
'nada'
>>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2)
[1, 2] |
def _finalize(self):
"""Dump traces using cPickle."""
container = {}
try:
for name in self._traces:
container[name] = self._traces[name]._trace
container['_state_'] = self._state_
file = open(self.filename, 'w+b')
std_pickle.dump(c... | Dump traces using cPickle. |
def generate(ast_tree: ast.Tree, model_name: str):
"""
:param ast_tree: AST to generate from
:param model_name: class to generate
:return: sympy source code for model
"""
component_ref = ast.ComponentRef.from_string(model_name)
ast_tree_new = copy.deepcopy(ast_tree)
ast_walker = TreeWalk... | :param ast_tree: AST to generate from
:param model_name: class to generate
:return: sympy source code for model |
def pop_object(self, element):
'''
Pop the object element if the object contains an higher TLP then allowed.
'''
redacted_text = "Redacted. Object contained TLP value higher than allowed."
element['id'] = ''
element['url'] = ''
element['type'] = ''
eleme... | Pop the object element if the object contains an higher TLP then allowed. |
async def find_deleted(self, seq_set: SequenceSet,
selected: SelectedMailbox) -> Sequence[int]:
"""Return all the active message UIDs that have the ``\\Deleted`` flag.
Args:
seq_set: The sequence set of the possible messages.
selected: The selected mai... | Return all the active message UIDs that have the ``\\Deleted`` flag.
Args:
seq_set: The sequence set of the possible messages.
selected: The selected mailbox session. |
def summary(self):
"""
Gets summary (e.g. residuals, deviance, pValues) of model on
training set. An exception is thrown if
`trainingSummary is None`.
"""
if self.hasSummary:
return GeneralizedLinearRegressionTrainingSummary(
super(GeneralizedL... | Gets summary (e.g. residuals, deviance, pValues) of model on
training set. An exception is thrown if
`trainingSummary is None`. |
def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
if isinstance(self.fee, Amount):
self.fee = Amount("{0:.8f} {1}".format(self.fee.to_double(), self.currency))
else:
self.fee = Amount("{0:.8f} {1}".format(self.fee, self.c... | Load the commodities for Amounts in this object. |
def messageRemote(self, cmdObj, consequence=None, **args):
"""
Send a message to the peer identified by the target, via the
given L{Command} object and arguments.
@param cmdObj: a L{twisted.protocols.amp.Command}, whose serialized
form will be the message.
@param conseq... | Send a message to the peer identified by the target, via the
given L{Command} object and arguments.
@param cmdObj: a L{twisted.protocols.amp.Command}, whose serialized
form will be the message.
@param consequence: an L{IDeliveryConsequence} provider which will
handle the result... |
def get_compression_filter(byte_counts):
"""Determine whether or not to use a compression on the array stored in
a hierarchical data format, and which compression library to use to that purpose.
Compression reduces the HDF5 file size and also helps improving I/O efficiency
for large datasets... | Determine whether or not to use a compression on the array stored in
a hierarchical data format, and which compression library to use to that purpose.
Compression reduces the HDF5 file size and also helps improving I/O efficiency
for large datasets.
Parameters
----------
byte_co... |
def to_filespec(cls, args, root='', exclude=None):
"""Return a dict representation of this glob list, relative to the buildroot.
The format of the dict is {'globs': [ 'list', 'of' , 'strings' ]
(optional) 'exclude' : [{'globs' : ... }, ...] }
The globs are in zglobs format.
"""
... | Return a dict representation of this glob list, relative to the buildroot.
The format of the dict is {'globs': [ 'list', 'of' , 'strings' ]
(optional) 'exclude' : [{'globs' : ... }, ...] }
The globs are in zglobs format. |
def split_iter(src, sep=None, maxsplit=None):
"""Splits an iterable based on a separator, *sep*, a max of
*maxsplit* times (no max by default). *sep* can be:
* a single value
* an iterable of separators
* a single-argument callable that returns True when a separator is
encountered
... | Splits an iterable based on a separator, *sep*, a max of
*maxsplit* times (no max by default). *sep* can be:
* a single value
* an iterable of separators
* a single-argument callable that returns True when a separator is
encountered
``split_iter()`` yields lists of non-separator valu... |
def _try_redeem_disposable_app(file, client):
"""
Attempt to redeem a one time code registred on the client.
"""
redeemedClient = client.redeem_onetime_code(None)
if redeemedClient is None:
return None
else:
return _BlotreDisposableApp(file,
redeemedClient.client,
... | Attempt to redeem a one time code registred on the client. |
def daily_pr_intensity(pr, thresh='1 mm/day', freq='YS'):
r"""Average daily precipitation intensity
Return the average precipitation over wet days.
Parameters
----------
pr : xarray.DataArray
Daily precipitation [mm/d or kg/m²/s]
thresh : str
precipitation value over which a day is... | r"""Average daily precipitation intensity
Return the average precipitation over wet days.
Parameters
----------
pr : xarray.DataArray
Daily precipitation [mm/d or kg/m²/s]
thresh : str
precipitation value over which a day is considered wet. Default : '1 mm/day'
freq : str, optional... |
def path_exists(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path-like object that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is emp... | Validate that ``value`` is a path-like object that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyVal... |
async def _init_writer(self):
"""
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
"""
async with self._initialization_lock:
if not self.initialized:
self.stream = await aiofiles.open(
f... | Open the current base file with the (original) mode and encoding.
Return the resulting stream. |
def aligned_covariance(fit, type='noise'):
"""
Covariance rescaled so that eigenvectors sum to 1
and rotated into data coordinates from PCA space
"""
cov = fit._covariance_matrix(type)
# Rescale eigenvectors to sum to 1
cov /= N.linalg.norm(cov)
return dot(fit.axes,cov) | Covariance rescaled so that eigenvectors sum to 1
and rotated into data coordinates from PCA space |
def getRemoteObject(self, busName, objectPath, interfaces=None,
replaceKnownInterfaces=False):
"""
Creates a L{RemoteDBusObject} instance to represent the
specified DBus object. If explicit interfaces are not
supplied, DBus object introspection will be used to ob... | Creates a L{RemoteDBusObject} instance to represent the
specified DBus object. If explicit interfaces are not
supplied, DBus object introspection will be used to obtain
them automatically.
@type busName: C{string}
@param busName: Name of the bus exporting the desired object
... |
def generate_readme(catalog, export_path=None):
"""Genera una descripción textual en formato Markdown sobre los
metadatos generales de un catálogo (título, editor, fecha de
publicación, et cetera), junto con:
- estado de los metadatos a nivel catálogo,
- estado global de los metadatos,
... | Genera una descripción textual en formato Markdown sobre los
metadatos generales de un catálogo (título, editor, fecha de
publicación, et cetera), junto con:
- estado de los metadatos a nivel catálogo,
- estado global de los metadatos,
- cantidad de datasets federados y no federados,
... |
def identity_factor(self):
"""
Returns the identity factor.
Def: The identity factor of a factor has the same scope and cardinality as the original factor,
but the values for all the assignments is 1. When the identity factor is multiplied with
the factor it returns th... | Returns the identity factor.
Def: The identity factor of a factor has the same scope and cardinality as the original factor,
but the values for all the assignments is 1. When the identity factor is multiplied with
the factor it returns the factor itself.
Returns
-----... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.