code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _split_stock_code(self, code):
stock_str = str(code)
split_loc = stock_str.find(".")
'''do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original cod... | do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original code |
def get_variable_for_feature(self, feature_key, variable_key):
""" Get the variable with the given variable key for the given feature.
Args:
feature_key: The key of the feature for which we are getting the variable.
variable_key: The key of the variable we are getting.
Returns:
Variable ... | Get the variable with the given variable key for the given feature.
Args:
feature_key: The key of the feature for which we are getting the variable.
variable_key: The key of the variable we are getting.
Returns:
Variable with the given key in the given variation. |
def get_institute_usage(institute, start, end):
"""Return a tuple of cpu hours and number of jobs for an institute
for a given period
Keyword arguments:
institute --
start -- start date
end -- end date
"""
try:
cache = InstituteCache.objects.get(
institute=institute,... | Return a tuple of cpu hours and number of jobs for an institute
for a given period
Keyword arguments:
institute --
start -- start date
end -- end date |
def itruediv(a, b):
"Same as a /= b."
if type(a) == int or type(a) == long:
a = float(a)
a /= b
return a | Same as a /= b. |
def filename(self, value):
"""Deprecated, user `source'."""
warnings.warn(
"The 'filename' attribute will be removed in future versions. "
"Use 'source' instead.",
DeprecationWarning, stacklevel=2
)
self.source = value | Deprecated, user `source'. |
def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0):
"""Writes a buffer into memory. This routine assumes that memory has
already been erased.
"""
xfer_count = 0
xfer_bytes = 0
xfer_total = len(buf)
xfer_base = addr
while xfer_bytes < xfer_total:
if __v... | Writes a buffer into memory. This routine assumes that memory has
already been erased. |
def from_yaml(self, node):
'''
Implementes a !from_yaml constructor with the following syntax:
!from_yaml filename key
Arguments:
filename: Filename of external YAML document from which to load,
relative to the current YAML file.
key... | Implementes a !from_yaml constructor with the following syntax:
!from_yaml filename key
Arguments:
filename: Filename of external YAML document from which to load,
relative to the current YAML file.
key: Key from external YAML document to ret... |
def state(self) -> SessionState:
"""The state of the managed Spark session."""
if self.session_id is None:
raise ValueError("session not yet started")
session = self.client.get_session(self.session_id)
if session is None:
raise ValueError("session not found - it m... | The state of the managed Spark session. |
def set_xticklabels_position(self, position):
"""Specify the position of the axis tick labels.
This is generally only useful for multiplots containing only one
row. This can be used to e.g. alternatively draw the tick labels
on the bottom or the top of the subplot.
:param posi... | Specify the position of the axis tick labels.
This is generally only useful for multiplots containing only one
row. This can be used to e.g. alternatively draw the tick labels
on the bottom or the top of the subplot.
:param position: 'top' or 'bottom' to specify the position of the
... |
def sample_outcomes(probs, n):
"""
For a discrete probability distribution ``probs`` with outcomes 0, 1, ..., k-1 draw ``n``
random samples.
:param list probs: A list of probabilities.
:param Number n: The number of random samples to draw.
:return: An array of samples drawn from distribution pr... | For a discrete probability distribution ``probs`` with outcomes 0, 1, ..., k-1 draw ``n``
random samples.
:param list probs: A list of probabilities.
:param Number n: The number of random samples to draw.
:return: An array of samples drawn from distribution probs over 0, ..., len(probs) - 1
:rtype:... |
def twoDimensionalHistogram(title, title_x, title_y,
z, bins_x, bins_y,
lim_x=None, lim_y=None,
vmin=None, vmax=None):
"""
Create a two-dimension histogram plot or binned map.
If using the outputs of np.histogram2d, remembe... | Create a two-dimension histogram plot or binned map.
If using the outputs of np.histogram2d, remember to transpose the histogram.
INPUTS |
def _fw_rule_update(self, drvr_name, data):
"""Firewall Rule update routine.
Function to decode the updated rules and call routines that
in turn calls the device routines to update rules.
"""
LOG.debug("FW Update %s", data)
tenant_id = data.get('firewall_rule').get('tena... | Firewall Rule update routine.
Function to decode the updated rules and call routines that
in turn calls the device routines to update rules. |
def sync(self):
"""Keep the repository in sync.
This method will synchronize the repository with its 'origin',
fetching newest objects and updating references. It uses low
level commands which allow to keep track of which things
have changed in the repository.
The metho... | Keep the repository in sync.
This method will synchronize the repository with its 'origin',
fetching newest objects and updating references. It uses low
level commands which allow to keep track of which things
have changed in the repository.
The method also returns a list of ha... |
def predict(self, dataset, output_type='class', batch_size=64):
"""
Return predictions for ``dataset``, using the trained logistic
regression model. Predictions can be generated as class labels,
probabilities that the target value is True, or margins (i.e. the
distance of the obs... | Return predictions for ``dataset``, using the trained logistic
regression model. Predictions can be generated as class labels,
probabilities that the target value is True, or margins (i.e. the
distance of the observations from the hyperplane separating the
classes). `probability_vector` ... |
def insert(self, index, option):
"""
Insert a new `option` in the ButtonGroup at `index`.
:param int option:
The index of where to insert the option.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the f... | Insert a new `option` in the ButtonGroup at `index`.
:param int option:
The index of where to insert the option.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value. |
def Generate(self, items, token=None):
"""Generates archive from a given collection.
Iterates the collection and generates an archive by yielding contents
of every referenced AFF4Stream.
Args:
items: Iterable of rdf_client_fs.StatEntry objects
token: User's ACLToken.
Yields:
Bin... | Generates archive from a given collection.
Iterates the collection and generates an archive by yielding contents
of every referenced AFF4Stream.
Args:
items: Iterable of rdf_client_fs.StatEntry objects
token: User's ACLToken.
Yields:
Binary chunks comprising the generated archive. |
def _handleEsc(self):
""" Handler for CTRL+Z keypresses """
if self._typingSms:
self.serial.write(self.ESC_CHARACTER)
self._typingSms = False
self.inputBuffer = []
self.cursorPos = 0 | Handler for CTRL+Z keypresses |
def get_taskruns(project_id, limit=100, offset=0, last_id=None):
"""Return a list of task runs for a given project ID.
:param project_id: PYBOSSA Project ID
:type project_id: integer
:param limit: Number of returned items, default 100
:type limit: integer
:param offset: Offset for the query, de... | Return a list of task runs for a given project ID.
:param project_id: PYBOSSA Project ID
:type project_id: integer
:param limit: Number of returned items, default 100
:type limit: integer
:param offset: Offset for the query, default 0
:type offset: integer
:param last_id: id of the last tas... |
def load_child_sections_for_section(context, section, count=None):
'''
Returns all child sections
If the `locale_code` in the context is not the main language, it will
return the translations of the live articles.
'''
page = section.get_main_language_page()
locale = context.get('locale_code'... | Returns all child sections
If the `locale_code` in the context is not the main language, it will
return the translations of the live articles. |
def get_attributes(self):
"""
Used by the uni_form_tags to get helper attributes
"""
items = {}
items['form_method'] = self.form_method.strip()
items['form_tag'] = self.form_tag
items['form_style'] = self.form_style.strip()
if self.form_action:
... | Used by the uni_form_tags to get helper attributes |
def pages(self, limit=0):
"""Return iterator for pages"""
if limit > 0:
self.iterator.limit = limit
return self.iterator | Return iterator for pages |
def parse_metadata(metadata_obj: Metadata, metadata_dictionary: dict) -> None:
""" Adds to a Metadata object any DublinCore or dts:Extensions object
found in the given dictionary
:param metadata_obj:
:param metadata_dictionary:
"""
for key, value_set in metadata_dictionary.get("https://w3id.org... | Adds to a Metadata object any DublinCore or dts:Extensions object
found in the given dictionary
:param metadata_obj:
:param metadata_dictionary: |
def get_command_line(self):
"""Returns the command line for the job."""
# In python 2, the command line is unicode, which needs to be converted to string before pickling;
# In python 3, the command line is bytes, which can be pickled directly
return loads(self.command_line) if isinstance(self.command_li... | Returns the command line for the job. |
def fresh_jwt_required(fn):
"""
A decorator to protect a Flask endpoint.
If you decorate an endpoint with this, it will ensure that the requester
has a valid and fresh access token before allowing the endpoint to be
called.
See also: :func:`~flask_jwt_extended.jwt_required`
"""
@wraps(... | A decorator to protect a Flask endpoint.
If you decorate an endpoint with this, it will ensure that the requester
has a valid and fresh access token before allowing the endpoint to be
called.
See also: :func:`~flask_jwt_extended.jwt_required` |
def draw_quadmesh(data, obj):
"""Returns the PGFPlots code for an graphics environment holding a
rendering of the object.
"""
content = []
# Generate file name for current object
filename, rel_filepath = files.new_filename(data, "img", ".png")
# Get the dpi for rendering and store the o... | Returns the PGFPlots code for an graphics environment holding a
rendering of the object. |
def on_btn_upload(self, event):
"""
Try to run upload_magic.
Open validation mode if the upload file has problems.
"""
if not self.check_for_uncombined_files():
return
outstring="upload_magic.py"
print("-I- running python script:\n %s"%(outstring))
... | Try to run upload_magic.
Open validation mode if the upload file has problems. |
def eqstr(a, b):
"""
Determine whether two strings are equivalent.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html
:param a: Arbitrary character string.
:type a: str
:param b: Arbitrary character string.
:type b: str
:return: True if A and B are equivalent.
:rt... | Determine whether two strings are equivalent.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html
:param a: Arbitrary character string.
:type a: str
:param b: Arbitrary character string.
:type b: str
:return: True if A and B are equivalent.
:rtype: bool |
def kwargs(self):
"""combine GET and POST params to be passed to the controller"""
kwargs = dict(self.query_kwargs)
kwargs.update(self.body_kwargs)
return kwargs | combine GET and POST params to be passed to the controller |
def run_mainloop_with(self, target):
"""Start the OS's main loop to process asyncronous BLE events and then
run the specified target function in a background thread. Target
function should be a function that takes no parameters and optionally
return an integer response code. When the t... | Start the OS's main loop to process asyncronous BLE events and then
run the specified target function in a background thread. Target
function should be a function that takes no parameters and optionally
return an integer response code. When the target function stops
executing or return... |
def update_alias(self, addressid, data):
"""Update alias address"""
return self.api_call(
ENDPOINTS['aliases']['update'],
dict(addressid=addressid),
body=data) | Update alias address |
def police_priority_map_conform_map_pri6_conform(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name_key = ET.SubElement(police_priority_map... | Auto Generated Code |
def importable(obj):
"""Check if an object can be serialised as a qualified name. This is done
by checking that a ``look_up(object_name(obj))`` gives back the same
object.
.. |importable| replace:: :py:func:`importable`"""
try:
return look_up(object_name(obj)) is obj
except (AttributeEr... | Check if an object can be serialised as a qualified name. This is done
by checking that a ``look_up(object_name(obj))`` gives back the same
object.
.. |importable| replace:: :py:func:`importable` |
def cleanup(self):
''' Stop backgroud thread and cleanup resources '''
self._processing_stop = True
self._wakeup_processing_thread()
self._processing_stopped_event.wait(3) | Stop backgroud thread and cleanup resources |
def add_tree(self, tree, parent=None):
"""
Add `tree` into database.
Args:
tree (obj): :class:`.Tree` instance.
parent (ref, default None): Reference to parent tree. This is used
for all sub-trees in recursive call.
"""
if tree.path in sel... | Add `tree` into database.
Args:
tree (obj): :class:`.Tree` instance.
parent (ref, default None): Reference to parent tree. This is used
for all sub-trees in recursive call. |
def file_finder(dirname="."):
"""
Find the files in ``dirname`` under Mercurial version control
according to the setuptools spec (see
http://peak.telecommunity.com/DevCenter/setuptools#adding-support-for-other-revision-control-systems
).
"""
import distutils.log
dirname = dirname or '.'
try:
valid_mgrs = man... | Find the files in ``dirname`` under Mercurial version control
according to the setuptools spec (see
http://peak.telecommunity.com/DevCenter/setuptools#adding-support-for-other-revision-control-systems
). |
def get_dimension_index(self, dimension):
"""Get the index of the requested dimension.
Args:
dimension: Dimension to look up by name or by index
Returns:
Integer index of the requested dimension
"""
if isinstance(dimension, int):
if (dimensio... | Get the index of the requested dimension.
Args:
dimension: Dimension to look up by name or by index
Returns:
Integer index of the requested dimension |
def query(self, u, v):
""":returns: the lowest common ancestor of u and v
:complexity: O(log n)
"""
# -- assume w.l.o.g. that v is not higher than u in the tree
if self.level[u] > self.level[v]:
u, v = v, u
# -- put v at the same level as u
depth = len... | :returns: the lowest common ancestor of u and v
:complexity: O(log n) |
def write(grp, out_path):
""" Write a GRP to a text file.
Args:
grp (list): GRP object to write to new-line delimited text file
out_path (string): output path
Returns:
None
"""
with open(out_path, "w") as f:
for x in grp:
f.write(str(x) + "\n") | Write a GRP to a text file.
Args:
grp (list): GRP object to write to new-line delimited text file
out_path (string): output path
Returns:
None |
def description_from_content(self):
"""
Returns the first block or sentence of the first content-like
field.
"""
description = ""
# Use the first RichTextField, or TextField if none found.
for field_type in (RichTextField, models.TextField):
if not des... | Returns the first block or sentence of the first content-like
field. |
def get_local_references(tb, max_string_length=1000):
"""
Find the values of the local variables within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value)
"""
if 'self' in tb.tb_frame.f_locals:
_locals = [('self', repr(tb.tb_frame.f_local... | Find the values of the local variables within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value) |
def compress_json(data):
""" Take a Python data object. Convert to JSON and compress using lzstring """
json_string = json.dumps(data).encode('utf-8', 'ignore').decode('utf-8')
# JSON.parse() doesn't handle `NaN`, but it does handle `null`.
json_string = json_string.replace('NaN', 'null');
x = lzstr... | Take a Python data object. Convert to JSON and compress using lzstring |
def elementInActiveFormattingElements(self, name):
"""Check if an element exists between the end of the active
formatting elements and the last marker. If it does, return it, else
return false"""
for item in self.activeFormattingElements[::-1]:
# Check for Marker first becau... | Check if an element exists between the end of the active
formatting elements and the last marker. If it does, return it, else
return false |
def subpt(method, target, et, abcorr, obsrvr):
"""
Deprecated: This routine has been superseded by the CSPICE
routine :func:`subpnt`. This routine is supported for purposes of
backward compatibility only.
Compute the rectangular coordinates of the sub-observer point on
a target body at a partic... | Deprecated: This routine has been superseded by the CSPICE
routine :func:`subpnt`. This routine is supported for purposes of
backward compatibility only.
Compute the rectangular coordinates of the sub-observer point on
a target body at a particular epoch, optionally corrected for
planetary (light t... |
def _GetMetadataRequest(self, metadata_url, params=None, timeout=None):
"""Performs a GET request with the metadata headers.
Args:
metadata_url: string, the URL to perform a GET request on.
params: dictionary, the query parameters in the GET request.
timeout: int, timeout in seconds for metad... | Performs a GET request with the metadata headers.
Args:
metadata_url: string, the URL to perform a GET request on.
params: dictionary, the query parameters in the GET request.
timeout: int, timeout in seconds for metadata requests.
Returns:
HTTP response from the GET request.
Rais... |
def AgregarAjusteFisico(self, cantidad, cantidad_cabezas=None,
cantidad_kg_vivo=None, **kwargs):
"Agrega campos al detalle de item por un ajuste fisico"
d = {'cantidad': cantidad,
'cantidadCabezas': cantidad_cabezas,
'cantidadKgVivo': cantidad_kg_v... | Agrega campos al detalle de item por un ajuste fisico |
def add_comment(self, comment, metadata=""):
"""
Add a canned comment
:type comment: str
:param comment: New canned comment
:type metadata: str
:param metadata: Optional metadata
:rtype: dict
:return: A dictionnary containing canned comment description
... | Add a canned comment
:type comment: str
:param comment: New canned comment
:type metadata: str
:param metadata: Optional metadata
:rtype: dict
:return: A dictionnary containing canned comment description |
def get_jamo_class(jamo):
"""Determine if a jamo character is a lead, vowel, or tail.
Integers and U+11xx characters are valid arguments. HCJ consonants are not
valid here.
get_jamo_class should return the class ["lead" | "vowel" | "tail"] of a
given character or integer.
Note: jamo class dire... | Determine if a jamo character is a lead, vowel, or tail.
Integers and U+11xx characters are valid arguments. HCJ consonants are not
valid here.
get_jamo_class should return the class ["lead" | "vowel" | "tail"] of a
given character or integer.
Note: jamo class directly corresponds to the Unicode 7... |
def style(self, index, *args):
"""
Add style to your axis, one at a time
args are of the form::
<axis color>,
<font size>,
<alignment>,
<drawing control>,
<tick mark color>
APIPARAM: chxs
"""
args = color_args(ar... | Add style to your axis, one at a time
args are of the form::
<axis color>,
<font size>,
<alignment>,
<drawing control>,
<tick mark color>
APIPARAM: chxs |
def push_update(self, params, values):
"""
Perform a parameter update and keep track of the change on the state.
Same call structure as :func:`peri.states.States.update`
"""
curr = self.get_values(params)
self.stack.append((params, curr))
self.update(params, value... | Perform a parameter update and keep track of the change on the state.
Same call structure as :func:`peri.states.States.update` |
def attach_template(self, _template, _key, **unbound_var_values):
"""Attaches the template to this such that _key=this layer.
Note: names were chosen to avoid conflicts with any likely unbound_var keys.
Args:
_template: The template to construct.
_key: The key that this layer should replace.
... | Attaches the template to this such that _key=this layer.
Note: names were chosen to avoid conflicts with any likely unbound_var keys.
Args:
_template: The template to construct.
_key: The key that this layer should replace.
**unbound_var_values: The values for the unbound_vars.
Returns:
... |
def download(self, field):
"""Download a file.
:param field: file field to download
:type field: string
:rtype: a file handle
"""
if not field.startswith('output'):
raise ValueError("Only processor results (output.* fields) can be downloaded")
if fi... | Download a file.
:param field: file field to download
:type field: string
:rtype: a file handle |
def dump_object(self, obj):
"""
Called to encode unrecognized object.
:param object obj: the object to encode
:return: the encoded object
:raises TypeError: when `obj` cannot be encoded
This method is passed as the ``default`` keyword parameter
to :func:`json.du... | Called to encode unrecognized object.
:param object obj: the object to encode
:return: the encoded object
:raises TypeError: when `obj` cannot be encoded
This method is passed as the ``default`` keyword parameter
to :func:`json.dumps`. It provides default representations for
... |
def _cache_from_source(path: str) -> str:
"""Return the path to the cached file for the given path. The original path
does not have to exist."""
cache_path, cache_file = os.path.split(importlib.util.cache_from_source(path))
filename, _ = os.path.splitext(cache_file)
return os.path.join(cache_path, f... | Return the path to the cached file for the given path. The original path
does not have to exist. |
def regexp_filter(self_or_cls, pattern):
"""
Builds a parameter filter using the supplied pattern (may be a
general Python regular expression)
"""
def inner_filter(name, p):
name_match = re.search(pattern,name)
if name_match is not None:
re... | Builds a parameter filter using the supplied pattern (may be a
general Python regular expression) |
def _get_baremetal_switches(self, port):
"""Get switch ip addresses from baremetal transaction.
This method is used to extract switch information
from the transaction where VNIC_TYPE is baremetal.
:param port: Received port transaction
:returns: list of all switches
:re... | Get switch ip addresses from baremetal transaction.
This method is used to extract switch information
from the transaction where VNIC_TYPE is baremetal.
:param port: Received port transaction
:returns: list of all switches
:returns: list of only switches which are active |
def GTax(x, ax):
"""
Compute transpose of gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient transpose is to be computed
Returns
-------
xg : ndarray
Output array
"""
slc0 = (slice(None),) * a... | Compute transpose of gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient transpose is to be computed
Returns
-------
xg : ndarray
Output array |
def slug(request, url):
"""Look up a page by url (which is a tree of slugs)"""
page = None
if url:
for slug in url.split('/'):
if not slug:
continue
try:
page = Page.objects.get(slug=slug, parent=page)
except Page.DoesNotExist:
... | Look up a page by url (which is a tree of slugs) |
def complete_dict(
self,
values_dict):
"""
Keys of nested dictionaries can be arbitrary objects.
"""
if self.orientation != "rows":
values_dict = transpose_nested_dictionary(values_dict)
row_keys, column_keys = collect_nested_keys(values_dict)... | Keys of nested dictionaries can be arbitrary objects. |
def _indent(text, level=1):
''' Does a proper indenting for Sphinx rst '''
prefix = ' ' * (4 * level)
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if line.strip() else line)
return ''.join(prefixed_lines()) | Does a proper indenting for Sphinx rst |
def callable_check(func, arg_count=1, arg_value=None, allow_none=False):
"""Check whether func is callable, with the given number of positional arguments. Returns True if check
succeeded, False otherwise."""
if func is None:
if not allow_none:
raise ValueError('cal... | Check whether func is callable, with the given number of positional arguments. Returns True if check
succeeded, False otherwise. |
def read_padding(fp, size, divisor=2):
"""
Read padding bytes for the given byte size.
:param fp: file-like object
:param divisor: divisor of the byte alignment
:return: read byte size
"""
remainder = size % divisor
if remainder:
return fp.read(divisor - remainder)
return b'... | Read padding bytes for the given byte size.
:param fp: file-like object
:param divisor: divisor of the byte alignment
:return: read byte size |
def cost(self,
tileStorage=0,
fileStorage=0,
featureStorage=0,
generatedTileCount=0,
loadedTileCount=0,
enrichVariableCount=0,
enrichReportCount=0,
serviceAreaCount=0,
geocodeCount=0):
"""
... | returns the cost values for a given portal
Inputs:
tileStorage - int - numbe of tiles to store in MBs
fileStorage - int - size of file to store in MBs
featureStorage - int - size in MBs
generateTileCount - int - number of tiles to genearte on site
loadedTileCount -in... |
def main():
"""MAIN"""
config = {
"api": {
"services": [
{
"name": "my_api",
"testkey": "testval",
},
],
"calls": {
"hello_world": {
"delay": 5,
... | MAIN |
def percent_point(self, y, V):
"""Compute the inverse of conditional cumulative distribution :math:`C(u|v)^-1`
Args:
y: `np.ndarray` value of :math:`C(u|v)`.
v: `np.ndarray` given value of v.
"""
self.check_fit()
if self.theta < 0:
return V
... | Compute the inverse of conditional cumulative distribution :math:`C(u|v)^-1`
Args:
y: `np.ndarray` value of :math:`C(u|v)`.
v: `np.ndarray` given value of v. |
def match_box_with_gt(self, boxes, iou_threshold):
"""
Args:
boxes: Nx4
Returns:
BoxProposals
"""
if self.is_training:
with tf.name_scope('match_box_with_gt_{}'.format(iou_threshold)):
iou = pairwise_iou(boxes, self.gt_boxes) #... | Args:
boxes: Nx4
Returns:
BoxProposals |
def custom_callback(self, view_func):
"""
Wrapper function to use a custom callback.
The custom OIDC callback will get the custom state field passed in with
redirect_to_auth_server.
"""
@wraps(view_func)
def decorated(*args, **kwargs):
plainreturn, dat... | Wrapper function to use a custom callback.
The custom OIDC callback will get the custom state field passed in with
redirect_to_auth_server. |
def metainfo_to_protobuf(self) -> bytes:
'''encode card_transfer info to protobuf'''
card = cardtransferproto()
card.version = self.version
card.amount.extend(self.amount)
card.number_of_decimals = self.number_of_decimals
if self.asset_specific_data:
if not i... | encode card_transfer info to protobuf |
def _get_resource_params(self, resource, for_update=False):
"""Get dictionary containing all parameters for the given resource.
When getting params for a coordinate frame update, only name and
description are returned because they are the only fields that can
be updated.
Args:
... | Get dictionary containing all parameters for the given resource.
When getting params for a coordinate frame update, only name and
description are returned because they are the only fields that can
be updated.
Args:
resource (intern.resource.boss.resource.BossResource): A su... |
def acquire(self,blocking=True,timeout=None):
"""Attempt to acquire this lock.
If the optional argument "blocking" is True and "timeout" is None,
this methods blocks until is successfully acquires the lock. If
"blocking" is False, it returns immediately if the lock could not
be... | Attempt to acquire this lock.
If the optional argument "blocking" is True and "timeout" is None,
this methods blocks until is successfully acquires the lock. If
"blocking" is False, it returns immediately if the lock could not
be acquired. Otherwise, it blocks for at most "timeout" se... |
def get_groupname(taskfileinfo):
"""Return a suitable name for a groupname for the given taskfileinfo.
:param taskfileinfo: the taskfile info for the file that needs a group when importing/referencing
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: None
:rtype: None
:rai... | Return a suitable name for a groupname for the given taskfileinfo.
:param taskfileinfo: the taskfile info for the file that needs a group when importing/referencing
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: None
:rtype: None
:raises: None |
def __get_live_version(self):
"""
Get a live version string using versiontools
"""
try:
import versiontools
except ImportError:
return None
else:
return str(versiontools.Version.from_expression(self.name)) | Get a live version string using versiontools |
def add_nodes(network_id, nodes,**kwargs):
"""
Add nodes to network
"""
start_time = datetime.datetime.now()
names=[] # used to check uniqueness of node name
for n_i in nodes:
if n_i.name in names:
raise HydraError("Duplicate Node Name: %s"%(n_i.name))
nam... | Add nodes to network |
def get_voms_proxy_user():
"""
Returns the owner of the voms proxy.
"""
out = _voms_proxy_info(["--identity"])[1].strip()
try:
return re.match(r".*\/CN\=([^\/]+).*", out.strip()).group(1)
except:
raise Exception("no valid identity found in voms proxy: {}".format(out)) | Returns the owner of the voms proxy. |
def encode(self, word, max_length=4, zero_pad=True):
"""Return the Phonex code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4)
zero_pad : bool
Pad the ... | Return the Phonex code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4)
zero_pad : bool
Pad the end of the return value with 0s to achieve a max_length
... |
def _get_adjustment(mag, year, mmin, completeness_year, t_f, mag_inc=0.1):
'''
If the magnitude is greater than the minimum in the completeness table
and the year is greater than the corresponding completeness year then
return the Weichert factor
:param float mag:
Magnitude of an earthquake... | If the magnitude is greater than the minimum in the completeness table
and the year is greater than the corresponding completeness year then
return the Weichert factor
:param float mag:
Magnitude of an earthquake
:param float year:
Year of earthquake
:param np.ndarray completeness... |
def decouple(fn):
"""
Inverse operation of couple.
Create two functions of one argument and one return from a function that
takes two arguments and has two returns
Examples
--------
>>> h = lambda x: (2*x**3, 6*x**2)
>>> f, g = decouple(h)
>>> f(5)
250
>>> g(5)
150
... | Inverse operation of couple.
Create two functions of one argument and one return from a function that
takes two arguments and has two returns
Examples
--------
>>> h = lambda x: (2*x**3, 6*x**2)
>>> f, g = decouple(h)
>>> f(5)
250
>>> g(5)
150 |
def getCenter(self):
'''
Gets the center coords of the View
@author: U{Dean Morin <https://github.com/deanmorin>}
'''
(left, top), (right, bottom) = self.getCoords()
x = left + (right - left) / 2
y = top + (bottom - top) / 2
return (x, y) | Gets the center coords of the View
@author: U{Dean Morin <https://github.com/deanmorin>} |
def indices_within_times(times, start, end):
"""
Return an index array into times that lie within the durations defined by start end arrays
Parameters
----------
times: numpy.ndarray
Array of times
start: numpy.ndarray
Array of duration start times
end: numpy.ndarray
... | Return an index array into times that lie within the durations defined by start end arrays
Parameters
----------
times: numpy.ndarray
Array of times
start: numpy.ndarray
Array of duration start times
end: numpy.ndarray
Array of duration end times
Returns
-------
... |
def update_continuously(records, update_interval=600):
"""Update `records` every `update_interval` seconds"""
while True:
for record in records:
try:
record.update()
except (ApiError, RequestException):
pass
time.sleep(update_interval) | Update `records` every `update_interval` seconds |
def simple_search(self, *keywords):
"""
Perform a simple search for case insensitive substring matches.
:param keywords: The string(s) to search for.
:returns: The matched password names (a generator of strings).
Only passwords whose names matches *all* of the given keywords a... | Perform a simple search for case insensitive substring matches.
:param keywords: The string(s) to search for.
:returns: The matched password names (a generator of strings).
Only passwords whose names matches *all* of the given keywords are
returned. |
def get_name(tags_or_instance_or_id):
"""Helper utility to extract name out of tags dictionary or intancce.
[{'Key': 'Name', 'Value': 'nexus'}] -> 'nexus'
Assert fails if there's more than one name.
Returns '' if there's less than one name.
"""
ec2 = get_ec2_resource()
if hasattr(tags_or_inst... | Helper utility to extract name out of tags dictionary or intancce.
[{'Key': 'Name', 'Value': 'nexus'}] -> 'nexus'
Assert fails if there's more than one name.
Returns '' if there's less than one name. |
def zip_html(self):
"""
Compress HTML documentation into a zip file.
"""
zip_fname = os.path.join(BUILD_PATH, 'html', 'pandas.zip')
if os.path.exists(zip_fname):
os.remove(zip_fname)
dirname = os.path.join(BUILD_PATH, 'html')
fnames = os.listdir(dirnam... | Compress HTML documentation into a zip file. |
def get_prep_value(self, value):
"""Returns field's value prepared for saving into a database."""
if isinstance(value, LocalizedValue):
prep_value = LocalizedValue()
for k, v in value.__dict__.items():
if v is None:
prep_value.set(k, '')
... | Returns field's value prepared for saving into a database. |
def _import_next_layer(self, proto, length, error=False):
"""Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Keyword arguments:
* error -- bool, if function call on error... | Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Keyword arguments:
* error -- bool, if function call on error
Returns:
* bool -- flag if extraction of next l... |
def get_jobs(self):
""" Retrieve all jobs"""
url_jenkins = urijoin(self.base_url, "api", "json")
response = self.fetch(url_jenkins)
return response.text | Retrieve all jobs |
def _recv_flow(self, method_frame):
'''
Receive a flow control command from the broker
'''
self.channel._active = method_frame.args.read_bit()
args = Writer()
args.write_bit(self.channel.active)
self.send_frame(MethodFrame(self.channel_id, 20, 21, args))
... | Receive a flow control command from the broker |
def invalid_example_number(region_code):
"""Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed and will have the correct
cou... | Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed and will have the correct
country code. It may also be a valid *short* number... |
def refresh(path=None):
"""Convenience method for setting the git executable path."""
global GIT_OK
GIT_OK = False
if not Git.refresh(path=path):
return
if not FetchInfo.refresh():
return
GIT_OK = True | Convenience method for setting the git executable path. |
def from_value(self, value):
""" Function infers TDS type from Python value.
:param value: value from which to infer TDS type
:return: An instance of subclass of :class:`BaseType`
"""
if value is None:
sql_type = NVarCharType(size=1)
else:
sql_typ... | Function infers TDS type from Python value.
:param value: value from which to infer TDS type
:return: An instance of subclass of :class:`BaseType` |
def create(cls, issue_id, *, properties=None, auto_commit=False):
"""Creates a new Issue object with the properties and tags provided
Attributes:
issue_id (str): Unique identifier for the issue object
account (:obj:`Account`): Account which owns the issue
properties ... | Creates a new Issue object with the properties and tags provided
Attributes:
issue_id (str): Unique identifier for the issue object
account (:obj:`Account`): Account which owns the issue
properties (dict): Dictionary of properties for the issue object. |
def set_image(self):
"""This code must be in its own method since the fetch functions need
credits to be set. m2m fields are not yet set at the end of either the
save method or post_save signal."""
if not self.image:
scrape_image(self)
# If still no image then use f... | This code must be in its own method since the fetch functions need
credits to be set. m2m fields are not yet set at the end of either the
save method or post_save signal. |
def clear_output(self, stdout=True, stderr=True, other=True):
"""Clear the output of the cell receiving output."""
if stdout:
print('\033[2K\r', file=io.stdout, end='')
io.stdout.flush()
if stderr:
print('\033[2K\r', file=io.stderr, end='')
io.stde... | Clear the output of the cell receiving output. |
def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "ascii" # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.... | Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this. |
def __minimum_noiseless_description_length(self, clusters, centers):
"""!
@brief Calculates splitting criterion for input clusters using minimum noiseless description length criterion.
@param[in] clusters (list): Clusters for which splitting criterion should be calculated.
... | !
@brief Calculates splitting criterion for input clusters using minimum noiseless description length criterion.
@param[in] clusters (list): Clusters for which splitting criterion should be calculated.
@param[in] centers (list): Centers of the clusters.
@return (d... |
def outline_segments(self, mask_background=False):
"""
Outline the labeled segments.
The "outlines" represent the pixels *just inside* the segments,
leaving the background pixels unmodified.
Parameters
----------
mask_background : bool, optional
Set ... | Outline the labeled segments.
The "outlines" represent the pixels *just inside* the segments,
leaving the background pixels unmodified.
Parameters
----------
mask_background : bool, optional
Set to `True` to mask the background pixels (labels = 0) in
the... |
def _uri(self, url):
"""Returns request absolute URI"""
if url and not url.startswith('/'):
# Then this must be a proxy request.
return url
uri = "{0}://{1}{2}{3}".format(
self._protocol,
self.real_connection.host,
self._port_postfix(),... | Returns request absolute URI |
async def founder(self, root):
"""Regional Founder. Returned even if the nation has ceased to
exist.
Returns
-------
an :class:`ApiQuery` of :class:`Nation`
an :class:`ApiQuery` of None
If the region is Game-Created and doesn't have a founder.
"""
... | Regional Founder. Returned even if the nation has ceased to
exist.
Returns
-------
an :class:`ApiQuery` of :class:`Nation`
an :class:`ApiQuery` of None
If the region is Game-Created and doesn't have a founder. |
def set_sqlite_pragmas(self):
"""
Sets the connection PRAGMAs for the sqlalchemy engine stored in self.engine.
It currently sets:
- journal_mode to WAL
:return: None
"""
def _pragmas_on_connect(dbapi_con, con_record):
dbapi_con.execute("PRAGMA journ... | Sets the connection PRAGMAs for the sqlalchemy engine stored in self.engine.
It currently sets:
- journal_mode to WAL
:return: None |
def _determineVolumeSize(self, source_type, source_uuid):
"""
Determine the minimum size the volume needs to be for the source.
Returns the size in GiB.
"""
nova = self.novaclient
if source_type == 'image':
# The size returned for an image is in bytes. Round u... | Determine the minimum size the volume needs to be for the source.
Returns the size in GiB. |
def experiment_data(self, commit=None, must_contain_results=False):
"""
:param commit: the commit that all the experiments should have happened or None to include all
:type commit: str
:param must_contain_results: include only tags that contain results
:type must_contain_results:... | :param commit: the commit that all the experiments should have happened or None to include all
:type commit: str
:param must_contain_results: include only tags that contain results
:type must_contain_results: bool
:return: all the experiment data
:rtype: dict |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.