code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid)
user_input = web.input()
# First, check for a particular submission
if "submission" in user_input:
submission = self.database... | GET request |
def removeTextAll(self, text):
'''
removeTextAll - Removes ALL occuraces of given text in a text node (i.e. not part of a tag)
@param text <str> - text to remove
@return list <str> - All text node containing #text BEFORE the text was removed.
Empty list if n... | removeTextAll - Removes ALL occuraces of given text in a text node (i.e. not part of a tag)
@param text <str> - text to remove
@return list <str> - All text node containing #text BEFORE the text was removed.
Empty list if no text removed
NOTE: To remove a node, @se... |
def add_membership_listener(self, member_added=None, member_removed=None, fire_for_existing=False):
"""
Helper method for adding membership listeners
:param member_added: (Function), Function to be called when a member is added, in the form of f(member)
(optional).
:param member... | Helper method for adding membership listeners
:param member_added: (Function), Function to be called when a member is added, in the form of f(member)
(optional).
:param member_removed: (Function), Function to be called when a member is removed, in the form of f(member)
(optional).
... |
def split(series):
'''
Split values.
The index is dropped, but this may change in the future.
Parameters
----------
series : ~pandas.Series[~pytil.numpy.ArrayLike]
Series with array-like values.
Returns
-------
~pandas.Series
Series with values split across rows.
... | Split values.
The index is dropped, but this may change in the future.
Parameters
----------
series : ~pandas.Series[~pytil.numpy.ArrayLike]
Series with array-like values.
Returns
-------
~pandas.Series
Series with values split across rows.
Examples
--------
>... |
def xml_import(self,
filepath=None,
xml_content = None,
markings=None,
identifier_ns_uri = None,
uid = None,
**kargs):
"""
Call this function for generic import of an XML file with the foll... | Call this function for generic import of an XML file with the following arguments:
- filename: Path to XML file
- markings (optional): List of information objects with which the imported object
should be marked
- identifier_ns_uri: Namespace of the identifiers, if identifiers are to b... |
def get_storage(request):
""" Gets a Credentials storage object provided by the Django OAuth2 Helper
object.
Args:
request: Reference to the current request object.
Returns:
An :class:`oauth2.client.Storage` object.
"""
storage_model = oauth2_settings.storage_model
user_prop... | Gets a Credentials storage object provided by the Django OAuth2 Helper
object.
Args:
request: Reference to the current request object.
Returns:
An :class:`oauth2.client.Storage` object. |
def for_latitude_longitude(cls, latitude, longitude, zoom):
"""Creates a tile from lat/lon in WGS84"""
point = Point.from_latitude_longitude(latitude=latitude, longitude=longitude)
pixel_x, pixel_y = point.pixels(zoom=zoom)
return cls.for_pixels(pixel_x=pixel_x, pixel_y=pixel_y, zoom=zoo... | Creates a tile from lat/lon in WGS84 |
def plot(self, ax_list=None, fontsize=12, **kwargs):
"""
Plot relaxation history i.e. the results of the last iteration of each SCF cycle.
Args:
ax_list: List of axes. If None a new figure is produced.
fontsize: legend fontsize.
kwargs: keyword arguments are ... | Plot relaxation history i.e. the results of the last iteration of each SCF cycle.
Args:
ax_list: List of axes. If None a new figure is produced.
fontsize: legend fontsize.
kwargs: keyword arguments are passed to ax.plot
Returns: matplotlib figure |
def genslices(n):
"""Generate all possible slices for a single dimension."""
def range_with_none():
yield None
yield from range(-n, n+1)
for t in product(range_with_none(), range_with_none(), range_with_none()):
s = slice(*t)
if s.step != 0:
yield s | Generate all possible slices for a single dimension. |
def strlen(state, s):
"""
strlen symbolic model.
Algorithm: Walks from end of string not including NULL building ITE tree when current byte is symbolic.
:param State state: current program state
:param int s: Address of string
:return: Symbolic strlen result
:rtype: Expression or int
"... | strlen symbolic model.
Algorithm: Walks from end of string not including NULL building ITE tree when current byte is symbolic.
:param State state: current program state
:param int s: Address of string
:return: Symbolic strlen result
:rtype: Expression or int |
def coreBurkAlpha(self, R, Rs, rho0, r_core, ax_x, ax_y):
"""
deflection angle
:param R:
:param Rs:
:param rho0:
:param r_core:
:param ax_x:
:param ax_y:
:return:
"""
x = R * Rs ** -1
p = Rs * r_core ** -1
gx = sel... | deflection angle
:param R:
:param Rs:
:param rho0:
:param r_core:
:param ax_x:
:param ax_y:
:return: |
def check_for_named_partition(self, schema, table, partition_name):
"""
Checks whether a partition with a given name exists
:param schema: Name of hive schema (database) @table belongs to
:type schema: str
:param table: Name of hive table @partition belongs to
:type sche... | Checks whether a partition with a given name exists
:param schema: Name of hive schema (database) @table belongs to
:type schema: str
:param table: Name of hive table @partition belongs to
:type schema: str
:partition: Name of the partitions to check for (eg `a=b/c=d`)
:... |
def set_outlets(self, pores=[], overwrite=False):
r"""
Set the locations through which defender exits the network.
This is only necessary if 'trapping' was set to True when ``setup``
was called.
Parameters
----------
pores : array_like
Locations where... | r"""
Set the locations through which defender exits the network.
This is only necessary if 'trapping' was set to True when ``setup``
was called.
Parameters
----------
pores : array_like
Locations where the defender can exit the network. Any defender
... |
def get_track_by_id(session, track_id, track_point_limit=None, track_point_offset=None):
"""
Gets a specific track
"""
tracking_data = {}
if track_point_limit:
tracking_data['track_point_limit'] = track_point_limit
if track_point_offset:
tracking_data['track_point_offset'] = tra... | Gets a specific track |
def get_user():
'''
Get the current user
'''
if HAS_PWD:
ret = pwd.getpwuid(os.geteuid()).pw_name
elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32:
ret = salt.utils.win_functions.get_current_user()
else:
raise CommandExecutionError(
'Required exte... | Get the current user |
def move(self, target_parent, name=None, include_children=True, include_instances=True):
"""
Move the `Part` to target parent, both of them the same category.
.. versionadded:: 2.3
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: ... | Move the `Part` to target parent, both of them the same category.
.. versionadded:: 2.3
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basest... |
def last_update_time(self) -> float:
"""The last time at which the report was modified."""
stdout = self.stdout_interceptor
stderr = self.stderr_interceptor
return max([
self._last_update_time,
stdout.last_write_time if stdout else 0,
stderr.last_writ... | The last time at which the report was modified. |
def key_verify(rsakey, signature, message, digest):
"""Verify the given signature with the RSA key."""
padding = _asymmetric.padding.PKCS1v15()
if isinstance(rsakey, _asymmetric.rsa.RSAPrivateKey):
rsakey = rsakey.public_key()
try:
rsakey.verify(signature, message, padding, digest)
... | Verify the given signature with the RSA key. |
def writeObject(self, obj, output, setReferencePosition=False):
"""Serializes the given object to the output. Returns output.
If setReferencePosition is True, will set the position the
object was written.
"""
def proc_variable_length(format, length):
result = b'... | Serializes the given object to the output. Returns output.
If setReferencePosition is True, will set the position the
object was written. |
def clear_sent_messages(self, offset=None):
""" Deletes sent MailerMessage records """
if offset is None:
offset = getattr(settings, 'MAILQUEUE_CLEAR_OFFSET', defaults.MAILQUEUE_CLEAR_OFFSET)
if type(offset) is int:
offset = datetime.timedelta(hours=offset)
dele... | Deletes sent MailerMessage records |
def add(self, data, header, row=None, subheader=None):
"""Filter `data` by arguments of this SummaryStats instance,
then apply `pd.describe()` and format the statistics
Parameters
----------
data : pd.DataFrame or pd.Series
data for which summary statistics should be... | Filter `data` by arguments of this SummaryStats instance,
then apply `pd.describe()` and format the statistics
Parameters
----------
data : pd.DataFrame or pd.Series
data for which summary statistics should be computed
header : str
column name for descrip... |
def get_cached_menus():
"""Return the menus from the cache or generate them if needed."""
items = cache.get(CACHE_KEY)
if items is None:
menu = generate_menu()
cache.set(CACHE_KEY, menu.items)
else:
menu = Menu(items)
return menu | Return the menus from the cache or generate them if needed. |
def add_package(self, name):
"""
Registers a single package
:param name: (str) The effect package to add
"""
name, cls_name = parse_package_string(name)
if name in self.package_map:
return
package = EffectPackage(name)
package.load()
... | Registers a single package
:param name: (str) The effect package to add |
def write_data(fo, datum, schema):
"""Write a datum of data to output stream.
Paramaters
----------
fo: file-like
Output file
datum: object
Data to write
schema: dict
Schemda to use
"""
record_type = extract_record_type(schema)
logical_type = extract_logical... | Write a datum of data to output stream.
Paramaters
----------
fo: file-like
Output file
datum: object
Data to write
schema: dict
Schemda to use |
def get_conn(self):
"""
Retrieves connection to Cloud Translate
:return: Google Cloud Translate client object.
:rtype: Client
"""
if not self._client:
self._client = Client(credentials=self._get_credentials())
return self._client | Retrieves connection to Cloud Translate
:return: Google Cloud Translate client object.
:rtype: Client |
def download_file(self, bucket, key, filename, extra_args=None,
expected_size=None):
"""Downloads the object's contents to a file
:type bucket: str
:param bucket: The name of the bucket to download from
:type key: str
:param key: The name of the key to dow... | Downloads the object's contents to a file
:type bucket: str
:param bucket: The name of the bucket to download from
:type key: str
:param key: The name of the key to download from
:type filename: str
:param filename: The name of a file to download to.
:type ext... |
def purge_existing_ovb(nova_api, neutron):
"""Purge any trace of an existing OVB deployment.
"""
LOG.info('Cleaning up OVB environment from the tenant.')
for server in nova_api.servers.list():
if server.name in ('bmc', 'undercloud'):
server.delete()
if server.name.startswith(... | Purge any trace of an existing OVB deployment. |
def init(self, sys_clock, swo_clock, console):
"""! @brief Configures trace graph and starts thread.
This method performs all steps required to start up SWV. It first calls the target's
trace_start() method, which allows for target-specific trace initialization. Then it
configur... | ! @brief Configures trace graph and starts thread.
This method performs all steps required to start up SWV. It first calls the target's
trace_start() method, which allows for target-specific trace initialization. Then it
configures the TPIU and ITM modules. A simple trace data processin... |
def tag(self, sentence, tokenize=True):
"""Tag a string `sentence`.
:param str or list sentence: A string or a list of sentence strings.
:param tokenize: (optional) If ``False`` string has to be tokenized before
(space separated string).
"""
#: Do not process empty ... | Tag a string `sentence`.
:param str or list sentence: A string or a list of sentence strings.
:param tokenize: (optional) If ``False`` string has to be tokenized before
(space separated string). |
def _indent_change(change, out, options, indent):
"""
recursive function to print indented change descriptions
"""
show_unchanged = getattr(options, "show_unchanged", False)
show_ignored = getattr(options, "show_ignored", False)
show = False
desc = change.get_description()
if change.i... | recursive function to print indented change descriptions |
def parse(rmk: str) -> RemarksData:
"""
Finds temperature and dewpoint decimal values from the remarks
"""
rmkdata = {}
for item in rmk.split(' '):
if len(item) in [5, 9] and item[0] == 'T' and item[1:].isdigit():
rmkdata['temperature_decimal'] = core.make_number(_tdec(item[1:5],... | Finds temperature and dewpoint decimal values from the remarks |
def state_size(self) -> Sequence[Shape]:
'''Returns the MDP state size.'''
return self._sizes(self._compiler.rddl.state_size) | Returns the MDP state size. |
def build_suite(args):
"""Build a test suite by loading TAP files or a TAP stream."""
loader = Loader()
if len(args.files) == 0 or args.files[0] == "-":
suite = loader.load_suite_from_stdin()
else:
suite = loader.load(args.files)
return suite | Build a test suite by loading TAP files or a TAP stream. |
def cleanup_handlers(event=None):
"""Remove handlers of a given `event`. If no event is informed, wipe
out all events registered.
Be careful!! This function is intended to help when writing tests
and for debugging purposes. If you call it, all handlers associated
to an event (or to all of them) wil... | Remove handlers of a given `event`. If no event is informed, wipe
out all events registered.
Be careful!! This function is intended to help when writing tests
and for debugging purposes. If you call it, all handlers associated
to an event (or to all of them) will be disassociated. Which means
that ... |
def generate_table_shared_access_signature(self, table_name, permission=None,
expiry=None, start=None, id=None,
ip=None, protocol=None,
start_pk=None, start_rk=None,
... | Generates a shared access signature for the table.
Use the returned signature with the sas_token parameter of TableService.
:param str table_name:
The name of the table to create a SAS token for.
:param TablePermissions permission:
The permissions associated with the sha... |
def TensorBoardWSGIApp(logdir, plugins, multiplexer, reload_interval,
path_prefix='', reload_task='auto'):
"""Constructs the TensorBoard application.
Args:
logdir: the logdir spec that describes where data will be loaded.
may be a directory, or comma,separated list of directories, ... | Constructs the TensorBoard application.
Args:
logdir: the logdir spec that describes where data will be loaded.
may be a directory, or comma,separated list of directories, or colons
can be used to provide named directories
plugins: A list of base_plugin.TBPlugin subclass instances.
multiplexe... |
def _restart_stream(self):
"""Restart the stream as needed after SASL and StartTLS negotiation."""
self._input_state = "restart"
self._output_state = "restart"
self.features = None
self.transport.restart()
if self.initiator:
self._send_stream_start(self.stream... | Restart the stream as needed after SASL and StartTLS negotiation. |
def clear_intersection(self, other_dict):
"""
Clears out locals and globals from this scope where the key-value pair matches
with other_dict.
This allows cleanup of temporary variables that may have washed up into this
Scope.
Arguments
---------
other_di... | Clears out locals and globals from this scope where the key-value pair matches
with other_dict.
This allows cleanup of temporary variables that may have washed up into this
Scope.
Arguments
---------
other_dict: a :class:`dict` to be used to determine scope clearance.
... |
def get_dip(self):
"""
Compute dip of each surface element and return area-weighted average
value (in range ``(0, 90]``).
Given that dip values are constrained in the range (0, 90], the simple
formula for weighted mean is used.
"""
areas = self._get_areas()
... | Compute dip of each surface element and return area-weighted average
value (in range ``(0, 90]``).
Given that dip values are constrained in the range (0, 90], the simple
formula for weighted mean is used. |
def register_backend(name, backend, allow_overwrite=False):
"""Register new backend.
Args:
name (str): The name of backend.
gateclass (type): The type object of backend
allow_overwrite (bool, optional): If True, allow to overwrite the existing backend.
... | Register new backend.
Args:
name (str): The name of backend.
gateclass (type): The type object of backend
allow_overwrite (bool, optional): If True, allow to overwrite the existing backend.
Otherwise, raise the ValueError.
Raises:
ValueEr... |
def json(self, conversion: _Text = 'badgerfish') -> Mapping:
"""A JSON Representation of the XML. Default is badgerfish.
:param conversion: Which conversion method to use. (`learn more <https://github.com/sanand0/xmljson#conventions>`_)
"""
if not self._json:
if conversion ... | A JSON Representation of the XML. Default is badgerfish.
:param conversion: Which conversion method to use. (`learn more <https://github.com/sanand0/xmljson#conventions>`_) |
def declare_actor(self, actor): # pragma: no cover
"""Declare a new actor on this broker. Declaring an Actor
twice replaces the first actor with the second by name.
Parameters:
actor(Actor): The actor being declared.
"""
self.emit_before("declare_actor", actor)
... | Declare a new actor on this broker. Declaring an Actor
twice replaces the first actor with the second by name.
Parameters:
actor(Actor): The actor being declared. |
def get_local_densities(data, kernel_mult = 2.0, metric = 'manhattan'):
"""For each sample point of the data-set 'data', estimate a local density in feature
space by counting the number of neighboring data-points within a particular
region centered around that sample point.
Parameters
-... | For each sample point of the data-set 'data', estimate a local density in feature
space by counting the number of neighboring data-points within a particular
region centered around that sample point.
Parameters
----------
data : array of shape (n_samples, n_features)
The data-se... |
def endpoint_get(auth=None, **kwargs):
'''
Get a single endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_get id=02cffaa173b2460f98e40eda3748dae5
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.get_endpoint(**kwargs) | Get a single endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_get id=02cffaa173b2460f98e40eda3748dae5 |
def pxconfig(self, line):
"""configure default targets/blocking for %px magics"""
args = magic_arguments.parse_argstring(self.pxconfig, line)
if args.targets:
self.view.targets = self._eval_target_str(args.targets)
if args.block is not None:
self.view.block = args... | configure default targets/blocking for %px magics |
def is_ordered_mapping(obj):
"""Checks whether given object is an ordered mapping,
e.g. a :class:`OrderedDict`.
:return: ``True`` if argument is an ordered mapping, ``False`` otherwise
"""
if not (is_mapping(obj) and hasattr(obj, '__reversed__')):
return False
# PyPy has a bug where the... | Checks whether given object is an ordered mapping,
e.g. a :class:`OrderedDict`.
:return: ``True`` if argument is an ordered mapping, ``False`` otherwise |
def Ts2(self, srcName, reoptimize=False, approx=True,
tol=None, MaxIterations=10, verbosity=0):
"""Computes the TS value for a source indicated by "srcName."
If "reoptimize=True" is selected this function will reoptimize
the model up to "MaxIterations" given the tolerance "tol"
... | Computes the TS value for a source indicated by "srcName."
If "reoptimize=True" is selected this function will reoptimize
the model up to "MaxIterations" given the tolerance "tol"
(default is the tolerance selected for the overall fit). If
"appox=True" is selected (the default) it will... |
def _get_result_paths(self, data):
""" Set the result paths """
result = {}
result['Output'] = ResultPath(
Path=self.Parameters['--output'].Value,
IsWritten=self.Parameters['--output'].isOn())
result['ClusterFile'] = ResultPath(
Path=self.Parameters... | Set the result paths |
def search_items(self, mode, request):
"""Invoke query/scan by name.
Response always includes "Count" and "ScannedCount"
:param str mode: "query" or "scan"
:param request: Unpacked into :func:`boto3.DynamoDB.Client.query` or :func:`boto3.DynamoDB.Client.scan`
"""
valida... | Invoke query/scan by name.
Response always includes "Count" and "ScannedCount"
:param str mode: "query" or "scan"
:param request: Unpacked into :func:`boto3.DynamoDB.Client.query` or :func:`boto3.DynamoDB.Client.scan` |
def plot_job_history(jobs, interval='year'):
"""Plots the job history of the user from the given list of jobs.
Args:
jobs (list): A list of jobs with type IBMQjob.
interval (str): Interval over which to examine.
Returns:
fig: A Matplotlib figure instance.
"""
def get_date(j... | Plots the job history of the user from the given list of jobs.
Args:
jobs (list): A list of jobs with type IBMQjob.
interval (str): Interval over which to examine.
Returns:
fig: A Matplotlib figure instance. |
def create_database(self, instance, name, character_set=None,
collate=None):
"""Creates a database with the specified name on the given instance."""
return instance.create_database(name, character_set=character_set,
collate=collate) | Creates a database with the specified name on the given instance. |
def createCommit(self, varBind, **context):
"""Create Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually create requested Managed
Object In... | Create Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually create requested Managed
Object Instance. When multiple Managed Objects Instances are cre... |
def compute_layer(cls, data, params, layout):
"""
Calculate statistics for this layers
This is the top-most computation method for the
stat. It does not do any computations, but it
knows how to verify the data, partition it call the
next computation method and merge resu... | Calculate statistics for this layers
This is the top-most computation method for the
stat. It does not do any computations, but it
knows how to verify the data, partition it call the
next computation method and merge results.
stats should not override this method.
Para... |
def freeze(self, tmp_dir):
"""Copies a secret into a particular location"""
for sfile in self.secrets():
src_file = hard_path(sfile, self.opt.secrets)
if not os.path.exists(src_file):
raise aomi_excep.IceFile("%s secret not found at %s" %
... | Copies a secret into a particular location |
def _handle_module(args):
"""
Handles the -m argument.
"""
module = _get_module_filename(args.module)
if not module:
_error("Could not load module or package: %r", args.module)
elif isinstance(module, Unparseable):
_error("Could not determine module source: %r", args.module)
... | Handles the -m argument. |
def termset_ancestors(self, terms):
"""
reflexive ancestors
Arguments
---------
terms - a set or list of class IDs
Returns: set of class IDs
"""
ancs = set()
for term in terms:
ancs = ancs.union(self.ontology.ancestors(term))
... | reflexive ancestors
Arguments
---------
terms - a set or list of class IDs
Returns: set of class IDs |
def get_all_synIdx(self):
"""
Auxilliary function to set up class attributes containing
synapse locations given as LFPy.Cell compartment indices
This function takes no inputs.
Parameters
----------
None
Returns
-------
synIdx : dict
... | Auxilliary function to set up class attributes containing
synapse locations given as LFPy.Cell compartment indices
This function takes no inputs.
Parameters
----------
None
Returns
-------
synIdx : dict
`output[cellindex][populationindex][... |
def _to_bfloat16_unbiased(x, noise):
"""Convert a float32 to a bfloat16 using randomized roundoff.
Args:
x: A float32 Tensor.
noise: a float32 Tensor with values in [0, 1), broadcastable to tf.shape(x)
Returns:
A float32 Tensor.
"""
x_sign = tf.sign(x)
# Make sure x is positive. If it is zero,... | Convert a float32 to a bfloat16 using randomized roundoff.
Args:
x: A float32 Tensor.
noise: a float32 Tensor with values in [0, 1), broadcastable to tf.shape(x)
Returns:
A float32 Tensor. |
def full_symbol(self):
"""Returns the symbol under the cursor AND additional contextual
symbols in the case of %-separated lists of type members."""
if self._full_symbol is None:
self._full_symbol = self._symbol_extract(cache.RE_FULL_CURSOR, brackets=True)
return self._full_... | Returns the symbol under the cursor AND additional contextual
symbols in the case of %-separated lists of type members. |
def set_config_file(name):
'''
Sets the configuration's name. This function is intended to be used from
states.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.set_config_file name=/etc/syslog-ng
'''
global __SYSLOG_NG_CONFIG_FILE
old = __SYSLOG_NG_CONFIG_FILE
__SYSL... | Sets the configuration's name. This function is intended to be used from
states.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.set_config_file name=/etc/syslog-ng |
def group_layout(path, files, **kwargs):
""" Make a well layout in chunks of two from a list of files
path: str
Location to make the well html file
files: list of pycbc.workflow.core.Files
This list of images to show in order within the well layout html file.
Every two are placed on... | Make a well layout in chunks of two from a list of files
path: str
Location to make the well html file
files: list of pycbc.workflow.core.Files
This list of images to show in order within the well layout html file.
Every two are placed on the same row. |
async def echo_all(app, message):
"""Send and recieve a message from all running echo servers"""
# Loop through all registered server addresses
for address in app.kv.get_prefix('address.').values():
# Parse the host and port from the stored address
host, port = address.decode().split(':')
... | Send and recieve a message from all running echo servers |
def generate_document_vector(self, doc, mode='tfidf'):
"""
Returns a representation of the specified document as a feature vector
weighted according the mode specified (by default tf-dif).
A custom weighting function can also be passed which receives the hashedindex
instance, th... | Returns a representation of the specified document as a feature vector
weighted according the mode specified (by default tf-dif).
A custom weighting function can also be passed which receives the hashedindex
instance, the selected term and document as parameters.
The result will be ret... |
def dataset_path(cls, project, dataset):
"""Return a fully-qualified dataset string."""
return google.api_core.path_template.expand(
"projects/{project}/datasets/{dataset}", project=project, dataset=dataset
) | Return a fully-qualified dataset string. |
def height(cls, path):
"""
Get the locally-stored block height
"""
if os.path.exists( path ):
sb = os.stat( path )
h = (sb.st_size / BLOCK_HEADER_SIZE) - 1
return h
else:
return None | Get the locally-stored block height |
def enable_hardware_breakpoint(self, dwThreadId, address):
"""
Enables the hardware breakpoint at the given address.
@see:
L{define_hardware_breakpoint},
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint... | Enables the hardware breakpoint at the given address.
@see:
L{define_hardware_breakpoint},
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint},
L{disable_hardware_breakpoint}
L{erase_hardware_brea... |
def _get_new_batch(self, ds_type:DatasetType)->Collection[Tensor]:
"Retrieves new batch of DatasetType, and detaches it."
return self.learn.data.one_batch(ds_type=ds_type, detach=True, denorm=False, cpu=False) | Retrieves new batch of DatasetType, and detaches it. |
def GetRequestXML(self, method, *args):
"""Get the raw SOAP XML for a request.
Args:
method: The method name.
*args: A list of arguments to be passed to the method.
Returns:
An element containing the raw XML that would be sent as the request.
"""
self.suds_client.set_options(nose... | Get the raw SOAP XML for a request.
Args:
method: The method name.
*args: A list of arguments to be passed to the method.
Returns:
An element containing the raw XML that would be sent as the request. |
def push(self, move):
'''
Updates the position with the given move and puts it onto a stack.
Null moves just increment the move counters, switch turns and forfeit
en passant capturing.
No validation is performed. For performance moves are assumed to be at
least pseudo leg... | Updates the position with the given move and puts it onto a stack.
Null moves just increment the move counters, switch turns and forfeit
en passant capturing.
No validation is performed. For performance moves are assumed to be at
least pseudo legal. Otherwise there is no guarantee that t... |
def dttm_sql_literal(self, dttm, is_epoch_in_utc):
"""Convert datetime object to a SQL expression string
If database_expression is empty, the internal dttm
will be parsed as the string with the pattern that
the user inputted (python_date_format)
If database_expression is not emp... | Convert datetime object to a SQL expression string
If database_expression is empty, the internal dttm
will be parsed as the string with the pattern that
the user inputted (python_date_format)
If database_expression is not empty, the internal dttm
will be parsed as the sql senten... |
def is_hidden(path):
"""Check if file is hidden."""
hidden = False
f = os.path.basename(path)
if f[:1] in ('.', b'.'):
# Count dot file as hidden on all systems
hidden = True
elif _PLATFORM == 'windows':
# On Windows, look for `FILE_ATTRIBUTE_HIDDEN`
FILE_ATTRIBUTE_H... | Check if file is hidden. |
def _to_tree(self, rule_node):
"""Converts a RuleNode parse tree to a lark Tree."""
orig_rule = self.orig_rules[rule_node.rule.alias]
children = []
for child in rule_node.children:
if isinstance(child, RuleNode):
children.append(self._to_tree(child))
... | Converts a RuleNode parse tree to a lark Tree. |
def make_executable(path, fatal=True):
"""
:param str|None path: chmod file with 'path' as executable
:param bool|None fatal: Abort execution on failure if True
:return int: 1 if effectively done, 0 if no-op, -1 on failure
"""
if is_executable(path):
return 0
if is_dryrun():
... | :param str|None path: chmod file with 'path' as executable
:param bool|None fatal: Abort execution on failure if True
:return int: 1 if effectively done, 0 if no-op, -1 on failure |
def write(self, fptr):
"""Write a UUID list box to file.
"""
num_uuids = len(self.ulst)
length = 4 + 4 + 2 + num_uuids * 16
write_buffer = struct.pack('>I4sH', length, b'ulst', num_uuids)
fptr.write(write_buffer)
for j in range(num_uuids):
fptr.write(... | Write a UUID list box to file. |
def has(self, module_name, class_name, attribute_name):
"""
Parameters
----------
module_name: String
The analysis_path of the module
class_name: String
The analysis_path of the class
attribute_name: String
The analysis_path of the attr... | Parameters
----------
module_name: String
The analysis_path of the module
class_name: String
The analysis_path of the class
attribute_name: String
The analysis_path of the attribute
Returns
-------
has_prior: bool
T... |
def findhight(data, ignoret=None, threshold=20):
""" Find bad time ranges from distribution of candidates.
ignoret is list of tuples [(t0, t1), (t2, t3)] defining ranges to ignore.
threshold is made above std of candidate distribution in time.
Returns the time (in seconds) and counts for bins above thr... | Find bad time ranges from distribution of candidates.
ignoret is list of tuples [(t0, t1), (t2, t3)] defining ranges to ignore.
threshold is made above std of candidate distribution in time.
Returns the time (in seconds) and counts for bins above threshold. |
def round_optimum(self, x):
"""
Rounds some value x to a feasible value in the design space.
x is expected to be a vector or an array with a single row
"""
x = np.array(x)
if not ((x.ndim == 1) or (x.ndim == 2 and x.shape[0] == 1)):
raise ValueError("Unexpecte... | Rounds some value x to a feasible value in the design space.
x is expected to be a vector or an array with a single row |
def _translate_timeperiod(self, timeperiod):
""" method translates given timeperiod to the grouped timeperiod """
if self.time_grouping == 1:
# no translation is performed for identity grouping
return timeperiod
# step 1: tokenize timeperiod into: (year, month, day, hour... | method translates given timeperiod to the grouped timeperiod |
def _print(self, msg=None, always=False):
"""A wrapper around print that only prints if we are not running in
quiet mode"""
if always or not self.commons['cmdlineopts'].quiet:
if msg:
print_(msg)
else:
print_() | A wrapper around print that only prints if we are not running in
quiet mode |
def _GetKeys(self, top_level, keys, depth=1):
"""Helper function to return keys nested in a plist dict.
By default this function will return the values for the named keys requested
by a plugin in match dictionary object. The default setting is to look
a single layer down from the root (same as the chec... | Helper function to return keys nested in a plist dict.
By default this function will return the values for the named keys requested
by a plugin in match dictionary object. The default setting is to look
a single layer down from the root (same as the check for plugin
applicability). This level is suitab... |
def _encodeTimestamp(timestamp):
""" Encodes a 7-octet timestamp from the specified date
Note: the specified timestamp must have a UTC offset set; you can use gsmmodem.util.SimpleOffsetTzInfo for simple cases
:param timestamp: The timestamp to encode
:type timestamp: datetime.datetime
... | Encodes a 7-octet timestamp from the specified date
Note: the specified timestamp must have a UTC offset set; you can use gsmmodem.util.SimpleOffsetTzInfo for simple cases
:param timestamp: The timestamp to encode
:type timestamp: datetime.datetime
:return: The encoded timestamp
:rtyp... |
def get_time():
"""Get time from a locally running NTP server"""
time_request = '\x1b' + 47 * '\0'
now = struct.unpack("!12I", ntp_service.request(time_request, timeout=5.0).data.read())[10]
return time.ctime(now - EPOCH_START) | Get time from a locally running NTP server |
def release_lock(self, verbose=VERBOSE, raiseError=RAISE_ERROR):
"""
Release the lock when set and close file descriptor if opened.
:Parameters:
#. verbose (bool): Whether to be verbose about errors when encountered
#. raiseError (bool): Whether to raise error exception ... | Release the lock when set and close file descriptor if opened.
:Parameters:
#. verbose (bool): Whether to be verbose about errors when encountered
#. raiseError (bool): Whether to raise error exception when encountered
:Returns:
#. result (boolean): Whether the lock... |
def get_coding_potential_cutoff(ref_gtf, ref_fasta, data):
"""
estimate the coding potential cutoff that best classifies
coding/noncoding transcripts by splitting the reference
annotation into a test and training set and determining
the cutoff where the sensitivity and specificity meet
"""
t... | estimate the coding potential cutoff that best classifies
coding/noncoding transcripts by splitting the reference
annotation into a test and training set and determining
the cutoff where the sensitivity and specificity meet |
def getmodule(object):
"""Return the module an object was defined in, or None if not found."""
if ismodule(object):
return object
if isclass(object):
return sys.modules.get(object.__module__)
try:
file = getabsfile(object)
except TypeError:
return None
if modulesb... | Return the module an object was defined in, or None if not found. |
def search_and_extract_orfs_matching_protein_database(self,
unpack,
search_method,
maximum_range,
thread... | As per aa_db_search() except slightly lower level. Search an
input read set (unpack) and then extract the proteins that hit together
with their containing nucleotide sequences.
Parameters
----------
output_search_file: str
path to hmmsearch output table or diamond ba... |
def decompile(input_, file_, output, format_, jar, limit, decompiler):
"""
Decompile an APK and create Control Flow Graphs.
Example:
\b
$ androguard resources.arsc
"""
from androguard import session
if file_ and input_:
print("Can not give --input and positional argument! "... | Decompile an APK and create Control Flow Graphs.
Example:
\b
$ androguard resources.arsc |
def functions(self):
"""
Access the functions
:returns: twilio.rest.serverless.v1.service.function.FunctionList
:rtype: twilio.rest.serverless.v1.service.function.FunctionList
"""
if self._functions is None:
self._functions = FunctionList(self._version, servi... | Access the functions
:returns: twilio.rest.serverless.v1.service.function.FunctionList
:rtype: twilio.rest.serverless.v1.service.function.FunctionList |
def _scan_soot_block(self, cfg_job, current_func_addr):
"""
Generate a list of successors (generating them each as entries) to IRSB.
Updates previous CFG nodes with edges.
:param CFGJob cfg_job: The CFGJob instance.
:param int current_func_addr: Address of the current function
... | Generate a list of successors (generating them each as entries) to IRSB.
Updates previous CFG nodes with edges.
:param CFGJob cfg_job: The CFGJob instance.
:param int current_func_addr: Address of the current function
:return: a list of successors
:rtype: list |
def _GetUsernameFromProfilePath(self, path):
"""Retrieves the username from a Windows profile path.
Trailing path path segment are ignored.
Args:
path (str): a Windows path with '\\' as path segment separator.
Returns:
str: basename which is the last path segment.
"""
# Strip trai... | Retrieves the username from a Windows profile path.
Trailing path path segment are ignored.
Args:
path (str): a Windows path with '\\' as path segment separator.
Returns:
str: basename which is the last path segment. |
def IV(abf,T1,T2,plotToo=True,color='b'):
"""
Given two time points (seconds) return IV data.
Optionally plots a fancy graph (with errorbars)
Returns [[AV],[SD]] for the given range.
"""
rangeData=abf.average_data([[T1,T2]]) #get the average data per sweep
AV,SD=rangeData[:,0,0],rangeData[:,... | Given two time points (seconds) return IV data.
Optionally plots a fancy graph (with errorbars)
Returns [[AV],[SD]] for the given range. |
def _do_main(self, commands):
"""
:type commands: list of VSCtlCommand
"""
self._reset()
self._init_schema_helper()
self._run_prerequisites(commands)
idl_ = idl.Idl(self.remote, self.schema_helper)
seqno = idl_.change_seqno
while True:
... | :type commands: list of VSCtlCommand |
def mesh(self, mesh_size=1, extra_height=0.1, edge=True, attach=True):
"""
Generates a set of points distributed in a mesh that covers the
whole Place and computes their height.
Generates a xy mesh with a given mesh_size in the
Place.surface's domain and computes the S... | Generates a set of points distributed in a mesh that covers the
whole Place and computes their height.
Generates a xy mesh with a given mesh_size in the
Place.surface's domain and computes the Surface's height for the
nodes. This mesh is alligned with the main directions `x` an... |
def add_entry_listener(self, include_value=False, key=None, added_func=None, removed_func=None, clear_all_func=None):
"""
Adds an entry listener for this multimap. The listener will be notified for all multimap add/remove/clear-all
events.
:param include_value: (bool), whether received ... | Adds an entry listener for this multimap. The listener will be notified for all multimap add/remove/clear-all
events.
:param include_value: (bool), whether received event should include the value or not (optional).
:param key: (object), key for filtering the events (optional).
:param ad... |
def get_values(self, config_manager, ignore_mismatches, obj_hook=DotDict):
"""Return a nested dictionary representing the values in the ini file.
In the case of this ValueSource implementation, both parameters are
dummies."""
if self.delayed_parser_instantiation:
try:
... | Return a nested dictionary representing the values in the ini file.
In the case of this ValueSource implementation, both parameters are
dummies. |
def arnoldi_res(A, V, H, ip_B=None):
"""Measure Arnoldi residual.
:param A: a linear operator that can be used with scipy's aslinearoperator
with ``shape==(N,N)``.
:param V: Arnoldi basis matrix with ``shape==(N,n)``.
:param H: Hessenberg matrix: either :math:`\\underline{H}_{n-1}` with
``s... | Measure Arnoldi residual.
:param A: a linear operator that can be used with scipy's aslinearoperator
with ``shape==(N,N)``.
:param V: Arnoldi basis matrix with ``shape==(N,n)``.
:param H: Hessenberg matrix: either :math:`\\underline{H}_{n-1}` with
``shape==(n,n-1)`` or :math:`H_n` with ``shape=... |
def DEFINE_multichoice(self, name, default, choices, help, constant=False):
"""Choose multiple options from a list."""
self.AddOption(
type_info.MultiChoice(
name=name, default=default, choices=choices, description=help),
constant=constant) | Choose multiple options from a list. |
def get_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS):
"""
Returns a handle to the process with I{at least} the access rights
requested.
@note:
If a handle was previously opened and has the required access
rights, it's reused. If not, a new handle is o... | Returns a handle to the process with I{at least} the access rights
requested.
@note:
If a handle was previously opened and has the required access
rights, it's reused. If not, a new handle is opened with the
combination of the old and new access rights.
@typ... |
def loop_until_closed(self):
''' Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any re... | Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
use case. |
def extract_dynamic_part(uri):
""" Extract dynamic url part from :uri: string.
:param uri: URI string that may contain dynamic part.
"""
for part in uri.split('/'):
part = part.strip()
if part.startswith('{') and part.endswith('}'):
return clean_dynamic_uri(part) | Extract dynamic url part from :uri: string.
:param uri: URI string that may contain dynamic part. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.