text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def generate_headers(self, token):
"""Generate auth headers"""
headers = {}
token = self.encode_token(token)
if self.config["header"]:
headers[self.config["header"]] = token
if self.config["cookie"]:
headers["Set-Cookie"] = dump_cookie(
sel... | 0.004464 |
def get_char(self, offset=0):
"""Return the current character in the working string."""
if not self.has_space(offset=offset):
return ''
return self.string[self.pos + offset] | 0.009524 |
def InitSpecCheck(self):
"""
make an interactive grid in which users can edit specimen names
as well as which sample a specimen belongs to
"""
#wait = wx.BusyInfo("Please wait, working...")
#wx.SafeYield()
self.contribution.propagate_lithology_cols()
spec_... | 0.007534 |
def split_docstring(self, block):
"""Split a code block into a docstring and a body."""
try:
first_line, rest_of_lines = block.split("\n", 1)
except ValueError:
pass
else:
raw_first_line = split_leading_trailing_indent(rem_comment(first_line))[1]
... | 0.006652 |
def keep_vertices(self, indices_to_keep, ret_kept_faces=False):
'''
Keep the given vertices and discard the others, and any faces to which
they may belong.
If `ret_kept_faces` is `True`, return the original indices of the kept
faces. Otherwise return `self` for chaining.
... | 0.002999 |
def __find_sync_range(self, messages, preamble_end: int, search_end: int):
"""
Finding the synchronization works by finding the first difference between two messages.
This is performed for all messages and the most frequent first difference is chosen
:type messages: list of Message
... | 0.00546 |
def update_user(self, user, attributes, attribute_mapping,
force_save=False):
"""Update a user with a set of attributes and returns the updated user.
By default it uses a mapping defined in the settings constant
SAML_ATTRIBUTE_MAPPING. For each attribute, if the user object ... | 0.002685 |
def delete_organization_course(organization, course_key):
"""
Removes an existing organization-course relationship from app/local state
No response currently defined for this operation
"""
try:
relationship = internal.OrganizationCourse.objects.get(
organization=organization['id'... | 0.001488 |
def _machinectl(cmd,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False):
'''
Helper function to run machinectl
'''
prefix = 'machinectl --no-legend --no-pager'
return __salt__['cmd.run_all']('{0} {1}'.format(prefix, cmd),
... | 0.00207 |
def get_ss_value(tag):
"""
Getters for data that also work with implicit transfersyntax
:param tag: the tag to read
"""
# data is int formatted as string so convert te string first and cast to int
if tag.VR == 'OB' or tag.VR == 'UN':
value = struct.unpack('h', tag.value)[0]
retu... | 0.005731 |
def median_low(name, num, minimum=0, maximum=0, ref=None):
'''
Calculates the low mean of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.median_low:
- name: myregentry
- num: 5
'''
return calc(
name=name... | 0.002288 |
def parse_string(self):
"""Parse a regular unquoted string from the token stream."""
aliased_value = LITERAL_ALIASES.get(self.current_token.value.lower())
if aliased_value is not None:
return aliased_value
return String(self.current_token.value) | 0.00692 |
def getBezierPaths(self,origin=None):
"""
This function returns array that can be used as a Cubic Bezier
Path in matplotlib.
The function returns two arrays, the first one contains
the verticies for each particles and has the shape
(Nvert, Nparticles, 2) where Nvert is t... | 0.015102 |
def _filter_update_security_group_rule(rule):
'''Only two fields are allowed for modification:
external_service and external_service_id
'''
allowed = ['external_service', 'external_service_id']
filtered = {}
for k, val in rule.iteritems():
if k in allowed:
if isinstance(... | 0.002242 |
def elliptical(cls, shape, pixel_scale, major_axis_radius_arcsec, axis_ratio, phi, centre=(0., 0.),
invert=False):
""" Setup a mask where unmasked pixels are within an ellipse of an input arc second major-axis and centre.
Parameters
----------
shape: (int, int)
... | 0.008449 |
def delete(sld, tld, nameserver):
'''
Deletes a nameserver. Returns ``True`` if the nameserver was deleted
successfully
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to delete
CLI Example:
.. code-block:: bash
salt '*' n... | 0.003659 |
def create(cls, fields=None, **fields_kwargs):
"""
create an instance of cls with the passed in fields and set it into the db
fields -- dict -- field_name keys, with their respective values
**fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also
... | 0.00969 |
def get_model_indices(cls, index):
'''
Returns the list of model indices (i.e. ModelIndex objects) defined for this index.
:param index: index name.
'''
try:
return cls._idx_name_to_mdl_to_mdlidx[index].values()
except KeyError:
raise KeyError('Cou... | 0.009592 |
def save(self, fname, compression='blosc'):
"""
Save method for the data geometry object
The data will be saved as a 'geo' file, which is a dictionary containing
the elements of a data geometry object saved in the hd5 format using
`deepdish`.
Parameters
--------... | 0.011543 |
def weights(self, matrix_id=0):
"""
Return the frame for the respective weight matrix.
:param: matrix_id: an integer, ranging from 0 to number of layers, that specifies the weight matrix to return.
:returns: an H2OFrame which represents the weight matrix identified by matrix_id
... | 0.007732 |
def get_sn(unit):
"""θ·εζζ¬θ‘ηε₯εζ°ι
Keyword arguments:
unit -- ζζ¬θ‘
Return:
sn -- ε₯ζ°
"""
sn = 0
match_re = re.findall(str(sentence_delimiters), unit)
if match_re:
string = ''.join(match_re)
sn = len(string)
return int(sn) | 0.003195 |
def delete_comment(self, resource_id, ent_id):
"""
Delete a comment
:param resource_id: ...
:param ent_id: ...
"""
self.requester.post(
'/{endpoint}/{entity}/{id}/delete_comment?id={ent_id}',
endpoint=self.endpoint, entity=self.entity,
... | 0.005556 |
def update_object(self, form, obj):
""" Saves the new value to the target object. """
field_name = form.cleaned_data['name']
value = form.cleaned_data['value']
setattr(obj, field_name, value)
save_kwargs = {}
if CAN_UPDATE_FIELDS:
save_kwargs['update_fields'] ... | 0.003953 |
def author_list(self):
''' The list of authors als text, for admin submission list overview.'''
author_list = [self.submitter] + \
[author for author in self.authors.all().exclude(pk=self.submitter.pk)]
return ",\n".join([author.get_full_name() for author in author_list]) | 0.012987 |
def export_saved_model(self, sess, export_dir, tag_set, signatures):
"""Convenience function to access ``TFNode.export_saved_model`` directly from this object instance."""
TFNode.export_saved_model(sess, export_dir, tag_set, signatures) | 0.008197 |
def rsa_encrypt_key_base64_encoded(rsaprivatekey, rsapublickey, plainkey):
# type: (cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey,
# cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey,
# bytes) -> str
"""Encrypt a plaintext key using RSA and PKCS1_OAEP padding
:pa... | 0.00087 |
def init(self, settings_file="zappa_settings.json"):
"""
Initialize a new Zappa project by creating a new zappa_settings.json in a guided process.
This should probably be broken up into few separate componants once it's stable.
Testing these inputs requires monkeypatching with mock, whi... | 0.0067 |
def check(self, defn, msg=None):
"""Uses the byte range in the object definition to determine
the number of bytes and compares to the size defined in the type.
Assumes the defn has 'type' and 'name' attributes, and a slice() method
"""
if isinstance(defn.type, dtype.PrimitiveTyp... | 0.003043 |
def auth(
cls, consumer_key, redirect_uri='http://example.com/', state=None,
):
'''
This is a test method for verifying if oauth worked
http://getpocket.com/developer/docs/authentication
'''
code = cls.get_request_token(consumer_key, redirect_uri, state)
aut... | 0.004739 |
def load_resource(resource_url: str, forceupdate: bool = False):
"""Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the ... | 0.00289 |
def fetch(cls, channel, start, end, host=None, port=None, verbose=False,
connection=None, verify=False, pad=None, allow_tape=None,
scaled=None, type=None, dtype=None):
"""Fetch data from NDS
Parameters
----------
channel : `str`, `~gwpy.detector.Channel`
... | 0.002017 |
def search(ont, searchterm):
"""
Search for things using labels
"""
namedGraph = get_named_graph(ont)
query = """
SELECT ?c ?l WHERE {{
GRAPH <{g}> {{
?c rdfs:label ?l
FILTER regex(?l,'{s}','i')
}}
}}
""".format(s=searchterm, g=namedGraph)
bindings = run_sparql(query... | 0.005181 |
def filter_alias_create_namespace(namespace):
"""
Filter alias name and alias command inside alias create namespace to appropriate strings.
Args
namespace: The alias create namespace.
Returns:
Filtered namespace where excessive whitespaces are removed in strings.
"""
def filter... | 0.003788 |
def get_data_object(data_id, use_data_config=True):
"""
Normalize the data_id and query the server.
If that is unavailable try the raw ID
"""
normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config)
client = DataClient()
data_obj = client.get(normalized_data_... | 0.004175 |
def _set_retain(self, v, load=False):
"""
Setter method for retain, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/l2vpn/evpn/retain (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_retain is considered as a private
method. Backends... | 0.006337 |
def _did_receive_event(self, connection):
""" Receive an event from connection """
if not self._is_running:
return
if connection.has_timeouted:
return
response = connection.response
data = None
if response.status_code != 200:
pushce... | 0.003674 |
def sign(ctx, file, account):
""" Sign a message with an account
"""
if not file:
print_message("Prompting for message. Terminate with CTRL-D", "info")
file = click.get_text_stream("stdin")
m = Message(file.read(), bitshares_instance=ctx.bitshares)
print_message(m.sign(account), "inf... | 0.003096 |
def pdb(self):
"""Start the python debugger
Calling pdb won't do anything in a multithread context
"""
if self.embed_disabled:
self.warning_log("Pdb is disabled when runned from the grid runner because of the multithreading") # noqa
return False
if BROM... | 0.004577 |
def check_constraint(column, lenum, **kwargs):
"""
Returns a SQL CHECK constraint string given a column name and a
:class:`~coaster.utils.classes.LabeledEnum`.
Alembic may not detect the CHECK constraint when autogenerating
migrations, so you may need to do this manually using t... | 0.005203 |
def _dims2shape(*dims):
"""Convert input dimensions to a shape."""
if not dims:
raise ValueError("expected at least one dimension spec")
shape = list()
for dim in dims:
if isinstance(dim, int):
dim = (0, dim)
if isinstance(dim, tuple) and len(dim) == 2:
if... | 0.001285 |
def close(self):
"""Closes the connection.
All outstanding futures for replies will be sent a DisconnectError.
"""
if self._recv_task:
self._recv_task.cancel()
self._disable_monitoring()
if self._monitor_task and not self._monitor_task.done():
s... | 0.004255 |
def _AddProvidesEdges(self, rdf_artifact):
"""Add an edge for every attribute the given artifact provides.
This method adds a directed edge from the artifact node to every attribute
this artifact provides.
Args:
rdf_artifact: The artifact object.
"""
for attribute in rdf_artifact.provide... | 0.005376 |
def sample(self, n, mass_min=0.1, mass_max=10., steps=10000, seed=None):
"""
Sample initial mass values between mass_min and mass_max,
following the IMF distribution.
ADW: Should this be `sample` or `simulate`?
Parameters:
-----------
n : number of samples to dr... | 0.003988 |
def get_n_excluded_patches(self):
"""
Gets number of excluded patches from patches_base:
#patches_base=1.0.0+THIS_NUMBER
"""
base = self.get_patches_base()
if not base:
return 0
p = base.rfind('+')
if p == -1:
return 0
try:
... | 0.004773 |
def next_message(self):
'''called as each msg is ready'''
msg = self.msg
if msg is None:
self.paused = True
if self.paused:
self.root.after(100, self.next_message)
return
try:
speed = float(self.playback.get())
except:
... | 0.001192 |
def setdefault(self, key, value):
"""We may not always be connected to an app, but we still need
to provide a way to the base environment to set it's defaults.
"""
try:
super(FlaskConfigStorage, self).setdefault(key, value)
except RuntimeError:
self._defau... | 0.005764 |
def from_array(a, mode=None, info={}):
"""Create a PNG :class:`Image` object from a 2- or 3-dimensional
array. One application of this function is easy PIL-style saving:
``png.from_array(pixels, 'L').save('foo.png')``.
.. note :
The use of the term *3-dimensional* is for marketing purposes
... | 0.001017 |
def check_data(cls, name, dims, is_unstructured):
"""
A validation method for the data shape
The default method does nothing and should be subclassed to validate
the results. If the plotter accepts a :class:`InteractiveList`, it
should accept a list for name and dims
Pa... | 0.0013 |
def in_use(self):
"""Returns True if there is a :class:`State` object that uses this
``Flow``"""
state = State.objects.filter(flow=self).first()
return bool(state) | 0.010256 |
def render_response(self):
"""Render as a string formatted for HTTP response headers
(detailed 'Set-Cookie: ' style).
"""
# Use whatever renderers are defined for name and value.
# (.attributes() is responsible for all other rendering.)
name, value = self.name, self.value... | 0.002621 |
def result_list(context):
"""
Displays the headers and data list together
"""
view = context['view']
object_list = context['object_list']
headers = list(result_headers(view))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields +... | 0.002 |
def home_handler(self, config=None, prefix=None, **args):
"""Handler for /home redirect path after Google auth.
OAuth ends up back here from Google. Set the account cookie
and close window to trigger next step.
"""
gresponse = self.google_get_token(config, prefix)
gdata ... | 0.00314 |
def _parse_text_DB(self, s):
"""Returns a dict of table interpreted from s.
s should be Json string encoding a dict { table_name : [fields_name,...] , [rows,... ] }"""
dic = self.decode_json_str(s)
new_dic = {}
for table_name, (header, rows) in dic.items():
newl = [{... | 0.006466 |
def set_font(font, section='appearance', option='font'):
"""Set font"""
CONF.set(section, option+'/family', to_text_string(font.family()))
CONF.set(section, option+'/size', float(font.pointSize()))
CONF.set(section, option+'/italic', int(font.italic()))
CONF.set(section, option+'/bold', int(font.bol... | 0.002732 |
def is_compatible_space(space, base_space):
"""Check compatibility of a (power) space with a base space.
Compatibility here means that the spaces are equal or ``space``
is a non-empty power space of ``base_space`` up to different
data types.
Parameters
----------
space, base_space : `Linea... | 0.00053 |
def get_version_info():
"""Extract version information as a dictionary from version.py."""
version_info = {}
with open(os.path.join("refcycle", "version.py"), 'r') as f:
version_code = compile(f.read(), "version.py", 'exec')
exec(version_code, version_info)
return version_info | 0.003236 |
def fallback_findfile(filename):
"""
:param str filename:
:return: try to find the full filename, e.g. in modules, etc
:rtype: str|None
"""
mods = [m for m in sys.modules.values() if m and hasattr(m, "__file__") and filename in m.__file__]
if len(mods) == 0:
return None
alt_fn = ... | 0.002125 |
def append_cluster_attribute(self, index_canvas, index_cluster, data, marker = None, markersize = None):
"""!
@brief Append cluster attribure for cluster on specific canvas.
@details Attribute it is data that is visualized for specific cluster using its color, marker and markersize if last tw... | 0.012899 |
def update(cls, first_name=None, middle_name=None, last_name=None,
public_nick_name=None, address_main=None, address_postal=None,
avatar_uuid=None, tax_resident=None, document_type=None,
document_number=None, document_country_of_issuance=None,
document_front_a... | 0.002994 |
def laplacian_pyramid_image(shape, n_levels=4, sd=None):
"""Simple laplacian pyramid paramaterization of an image.
For more flexibility, use a sum of lowres_tensor()s.
Args:
shape: shape of resulting image, [batch, width, height, channels].
n_levels: number of levels of laplacian pyarmid.
... | 0.003049 |
def html_to_rgb(html):
"""Convert the HTML color to (r, g, b).
Parameters:
:html:
the HTML definition of the color (#RRGGBB or #RGB or a color name).
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
Throws:
:ValueError:
If html is neither... | 0.01184 |
async def dump_blob(elem, elem_type=None):
"""
Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_is_blob = isinstance(elem, x.BlobType)
data = getattr(elem, x.BlobType.DATA_ATTR) if elem_is_bl... | 0.001845 |
def _set_scores(self):
"""
Set anomaly scores using a weighted sum.
"""
anom_scores_ema = self.exp_avg_detector.run()
anom_scores_deri = self.derivative_detector.run()
anom_scores = {}
for timestamp in anom_scores_ema.timestamps:
# Compute a weighted a... | 0.005411 |
def p_ConstValue_float(p):
"""ConstValue : FLOAT"""
p[0] = model.Value(type=model.Value.FLOAT, value=p[1]) | 0.027273 |
def _login_authentication(self, login, password, authz_id=""):
"""SASL LOGIN authentication
:param login: username
:param password: clear password
:return: True on success, False otherwise.
"""
extralines = [b'"%s"' % base64.b64encode(login.encode("utf-8")),
... | 0.003413 |
def _fix_call_activities_signavio(self, bpmn, filename):
"""
Signavio produces slightly invalid BPMN for call activity nodes... It
is supposed to put a reference to the id of the called process in to
the calledElement attribute. Instead it stores a string (which is the
name of th... | 0.000955 |
def one_cycle_scheduler(lr_max:float, **kwargs:Any)->OneCycleScheduler:
"Instantiate a `OneCycleScheduler` with `lr_max`."
return partial(OneCycleScheduler, lr_max=lr_max, **kwargs) | 0.021164 |
def modify_folder_grant(
self,
folder_ids,
perm,
zid=None,
grantee_name=None,
gt='usr',
flags=None
):
"""
:param folder_ids: list of ids
:param perm: permission to grant to the user on folder(s)
:param zid: id of user to grant r... | 0.002573 |
def add_display_name(self, display_name):
"""Adds a display_name.
arg: display_name (displayText): the new display name
raise: InvalidArgument - ``display_name`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``display_name`` is ``... | 0.004304 |
def update_journals(self):
"""773 journal translations."""
for field in record_get_field_instances(self.record, '773'):
subs = field_get_subfield_instances(field)
new_subs = []
for idx, (key, value) in enumerate(subs):
if key == 'p':
... | 0.003788 |
def r_hat(self):
"""Get rhat data for the variable."""
_, y_vals, values, colors = self.labels_ticks_and_vals()
for y, value, color in zip(y_vals, values, colors):
if value.ndim != 2 or value.shape[0] < 2:
yield y, None, color
else:
yield y... | 0.005698 |
def _needs_elements(self, f):
''' Decorator used to make sure that there are elements prior to running the task. '''
@wraps(f)
def wrapper(self, *args, **kwargs):
if self.elements == None:
self.getelements()
return f(self, *args, **kwargs)
return wrapper | 0.040293 |
def gradients(ys, xs, grad_ys=None):
"""Compute gradients in dtf.
Args:
ys: a list of Tensors
xs: a list of Tensors
grad_ys: an optional list of Tensors
Returns:
grad_xs: a list of Tensors
"""
graph = ys[0].graph
if not grad_ys:
grad_ys = [Constant(y.mesh, 1.0, y.shape, y.dtype).output... | 0.012637 |
def unget_bytes(self, string):
"""Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object"""
self.unprocessed_bytes.extend(string[i:i + 1]
for i in range(len(string))) | 0.00625 |
def fetch(self, is_dl_forced=False):
'''connection details for DISCO'''
cxn = {}
cxn['host'] = 'nif-db.crbs.ucsd.edu'
cxn['database'] = 'disco_crawler'
cxn['port'] = '5432'
cxn['user'] = config.get_config()['user']['disco']
cxn['password'] = config.get_config()['k... | 0.004224 |
def _apply_axes_mapping(self, target, inverse=False):
"""
Apply the transposition to the target iterable.
Parameters
----------
target - iterable
The iterable to transpose. This would be suitable for things
such as a shape as well as a list of ``__getitem... | 0.001676 |
def _setup(self):
"""
Generates _reverse_map from _map
"""
ValueMap._setup(self)
cls = self.__class__
if cls._map is not None:
cls._size = max(self._map.keys()) + 1 | 0.00885 |
def getPiGosper(n):
"""Returns a list containing first n digits of Pi
"""
mypi = piGenGosper()
result = []
if n > 0:
result += [next(mypi) for i in range(n)]
mypi.close()
return result | 0.004545 |
def refresh_from_server(self):
"""Refresh the group from the server in place."""
group = self.manager.get(id=self.id)
self.__init__(self.manager, **group.data) | 0.010929 |
def set_attributes(path, archive=None, hidden=None, normal=None,
notIndexed=None, readonly=None, system=None, temporary=None):
'''
Set file attributes for a file. Note that the normal attribute
means that all others are false. So setting it will clear all others.
Args:
path... | 0.000754 |
def commit_index(self, message):
"""
Commit the current index.
:param message: str
:return: str the generated commit sha
"""
tree_id = self.write_tree()
args = ['commit-tree', tree_id, '-p', self.ref_head]
# todo, this can end in a race-condition with ot... | 0.005848 |
def import_str(self, csv, params={}):
"""
Imports a CSV string.
https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.create
"""
if not self._canvas_account_id:
raise MissingAccountID()
params["import_type"] = SISImportModel.CSV_IMPO... | 0.003534 |
def initialise_logging(level: str, target: str, short_format: bool):
"""Initialise basic logging facilities"""
try:
log_level = getattr(logging, level)
except AttributeError:
raise SystemExit(
"invalid log level %r, expected any of 'DEBUG', 'INFO', 'WARNING', 'ERROR' or 'CRITICAL... | 0.004983 |
def _not_empty(self, view, slice_):
"""Checks if the density is too low. """
img2d = self._get_axis(self._image, view, slice_)
return (np.count_nonzero(img2d) / img2d.size) > self._min_density | 0.009217 |
def STORE_SLICE_1(self, instr):
'obj[lower:] = expr'
lower = self.ast_stack.pop()
value = self.ast_stack.pop()
expr = self.ast_stack.pop()
kw = dict(lineno=instr.lineno, col_offset=0)
slice = _ast.Slice(lower=lower, step=None, upper=None, **kw)
subscr = _ast.Subs... | 0.006263 |
def get_data_size(self, sport, plan, from_day, from_month, from_year, to_day, to_month, to_year, event_id=None,
event_name=None, market_types_collection=None, countries_collection=None,
file_type_collection=None, session=None):
"""
Returns a dictionary of file... | 0.005666 |
def is_valid_query(self, query):
"""
Return True if the search query is valid.
e.g.:
* not empty,
* not too short,
"""
# No query, no item
if not query:
return False
# Query is too short, no item
if len(query) < self.get_query_... | 0.005319 |
def traverse(self, root = None, display = None, q = Stack()):
'''
API: traverse(self, root = None, display = None, q = Stack())
Description:
Traverses tree starting from node named root. Used strategy (BFS,
DFS) is controlled by argument q. It is a DFS if q is Queue(), BF... | 0.009924 |
def set_ssl(self,
for_hosts=[],
key_file=None,
cert_file=None,
ca_certs=None,
cert_validator=None,
ssl_version=DEFAULT_SSL_VERSION,
password=None):
"""
Sets up SSL configuration for the given ... | 0.009116 |
def order_enum(field, members):
"""
Make an annotation value that can be used to sort by an enum field.
``field``
The name of an EnumChoiceField.
``members``
An iterable of Enum members in the order to sort by.
Use like:
.. code-block:: python
desired_order = [MyEnum... | 0.000769 |
def locateChild(self, context, segments):
"""
Unwrap the wrapped resource if HTTPS is already being used, otherwise
wrap it in a helper which will preserve the wrapping all the way down
to the final resource.
"""
request = IRequest(context)
if request.isSecure():
... | 0.006667 |
def lookup_job_tasks(self,
statuses,
user_ids=None,
job_ids=None,
job_names=None,
task_ids=None,
task_attempts=None,
labels=None,
create... | 0.007692 |
def company(random=random, *args, **kwargs):
"""
Produce a company name
>>> mock_random.seed(0)
>>> company(random=mock_random)
'faculty of applied chimp'
>>> mock_random.seed(1)
>>> company(random=mock_random)
'blistersecret studios'
>>> mock_random.seed(2)
>>> company(random=m... | 0.000509 |
def feature_list():
"""
Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc
Returns
-------
list
List of :class:`.Feature` objects
"""
lib_features_c_array = ctypes.POINTER(Feature)()
lib_features_size = ctypes.c_size_t()
... | 0.007576 |
def event_log_filter_between_date(start, end, utc):
"""betweenDate Query filter that SoftLayer_EventLog likes
:param string start: lower bound date in mm/dd/yyyy format
:param string end: upper bound date in mm/dd/yyyy format
:param string utc: utc offset. Defaults to '+0000'
"""
return {
... | 0.003676 |
def dir2cart(d):
"""
Converts a list or array of vector directions in degrees (declination,
inclination) to an array of the direction in cartesian coordinates (x,y,z)
Parameters
----------
d : list or array of [dec,inc] or [dec,inc,intensity]
Returns
-------
cart : array of [x,y,z]... | 0.001775 |
def _set_roi_mask(self, roi_mask):
"""Sets a new ROI mask."""
if isinstance(roi_mask,
np.ndarray): # not (roi_mask is None or roi_mask=='auto'):
self._verify_shape_compatibility(roi_mask, 'ROI set')
self.roi_mask = roi_mask
self.roi_list = np.... | 0.009042 |
def element_statistics(tree, element_type):
"""
Prints the names and counts of all elements present in an
`etree._ElementTree`, e.g. a SaltDocument::
SStructure: 65
SSpan: 32
SToken: 154
STextualDS: 1
Parameters
----------
tree : lxml.etree._ElementTree
... | 0.001408 |
def set(self, value):
"""
Sets the value of the object
:param value:
An integer
:raises:
ValueError - when an invalid value is passed
"""
if not isinstance(value, int_types):
raise TypeError(unwrap(
'''
... | 0.002725 |
def setCurrentRecord(self, record):
"""
Sets the current record for this tree to the inputed record.
:param record | <orb.Table>
"""
if self.isLoading():
self._tempCurrentRecord = record
return
for i in range(self.t... | 0.008677 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.