text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_siblings(self):
"""Get a list of sibling accounts associated with provided account."""
method = 'GET'
endpoint = '/rest/v1.1/users/{}/siblings'.format(
self.client.sauce_username)
return self.client.request(method, endpoint) | 0.007246 |
def rel_path(filename):
"""
Function that gets relative path to the filename
"""
return os.path.join(os.getcwd(), os.path.dirname(__file__), filename) | 0.006024 |
def build_diagonals(self):
"""
Builds the diagonals for the coefficient array
"""
##########################################################
# INCORPORATE BOUNDARY CONDITIONS INTO COEFFICIENT ARRAY #
##########################################################
# Roll to keep the pro... | 0.015572 |
def login(self):
"""
Gets and stores an OAUTH token from Rightscale.
"""
log.debug('Logging into RightScale...')
login_data = {
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token,
}
response = self._request('post', self.... | 0.002205 |
def _generate_next_token_helper(self, past_states, transitions):
""" generates next token based previous states """
key = tuple(past_states)
assert key in transitions, "%s" % str(key)
return utils.weighted_choice(transitions[key].items()) | 0.007407 |
def aStockQoutation(self,code):
'''
订阅一只股票的实时行情数据,接收推送
:param code: 股票代码
:return:
'''
#设置监听-->订阅-->调用接口
# 分时
self.quote_ctx.set_handler(RTDataTest())
self.quote_ctx.subscribe(code, SubType.RT_DATA)
ret_code_rt_data, ret_data_rt_data = sel... | 0.005503 |
def strip_ccmp(self, idx):
"""strip(8 byte) wlan.ccmp.extiv
CCMP Extended Initialization Vector
:return: int
number of processed bytes
:return: ctypes.raw
ccmp vector
"""
ccmp_extiv = None
if len(self._packet[idx:]) >= 8:
raw_by... | 0.004505 |
def get_fields_class(self, class_name):
"""
Return all fields of a specific class
:param class_name: the class name
:type class_name: string
:rtype: a list with :class:`EncodedField` objects
"""
l = []
for i in self.get_classes():
for j in i.... | 0.006881 |
def from_dict(cls, d):
"""Instantiate a SemI from a dictionary representation."""
read = lambda cls: (lambda pair: (pair[0], cls.from_dict(pair[1])))
return cls(
variables=map(read(Variable), d.get('variables', {}).items()),
properties=map(read(Property), d.get('propertie... | 0.00616 |
def encrypt(data, key):
'''encrypt the data with the key'''
data = __tobytes(data)
data_len = len(data)
data = ffi.from_buffer(data)
key = ffi.from_buffer(__tobytes(key))
out_len = ffi.new('size_t *')
result = lib.xxtea_encrypt(data, data_len, key, out_len)
ret = ffi.buffer(result, out_l... | 0.00274 |
def translate_file(input_path, output_path):
'''
Translates input JS file to python and saves the it to the output path.
It appends some convenience code at the end so that it is easy to import JS objects.
For example we have a file 'example.js' with: var a = function(x) {return x}
translate_file... | 0.004469 |
def wait_for_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT):
""" The shorter version of wait_for_link_text_visible() """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_link_text_visible(link... | 0.005831 |
def _parse_btrfs_info(data):
'''
Parse BTRFS device info data.
'''
ret = {}
for line in [line for line in data.split("\n") if line][:-1]:
if line.startswith("Label:"):
line = re.sub(r"Label:\s+", "", line)
label, uuid_ = [tkn.strip() for tkn in line.split("uuid:")]
... | 0.001357 |
def savemat(filename, data):
"""Save data to MAT-file:
savemat(filename, data)
The filename argument is either a string with the filename, or
a file like object.
The parameter ``data`` shall be a dict with the variables.
A ``ValueError`` exception is raised if data has invalid format, or if ... | 0.001307 |
def detach(self):
"""If alive then mark as dead and return (obj, func, args, kwargs);
otherwise return None"""
info = self._registry.get(self)
obj = info and info.weakref()
if obj is not None and self._registry.pop(self, None):
return (obj, info.func, info.args, info.... | 0.006006 |
async def handle_frame(self, frame):
"""Handle incoming API frame, return True if this was the expected frame."""
if not isinstance(frame, FrameGetVersionConfirmation):
return False
self.version = frame.version
self.success = True
return True | 0.010204 |
def convert_lrelu(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert leaky relu layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary ... | 0.001274 |
def config_name_from_full_name(full_name):
"""Extract the config name from a full resource name.
>>> config_name_from_full_name('projects/my-proj/configs/my-config')
"my-config"
:type full_name: str
:param full_name:
The full resource name of a config. The full resource name looks like... | 0.00098 |
def _get_logger_file_handles(self):
"""
Find the file handles used by our logger's handlers.
"""
handles = []
for handler in self.logger.handlers:
# The following code works for logging's SysLogHandler,
# StreamHandler, SocketHandler, and their subclasses.... | 0.003115 |
def remove_phenotype(self, institute, case, user, link, phenotype_id,
is_group=False):
"""Remove an existing phenotype from a case
Args:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link... | 0.00385 |
def status(self):
"""Provides current status of processing episode.
Structure of status:
original_filename => formatted_filename, state, messages
:returns: mapping of current processing state
:rtype: dict
"""
return {
self.original: {
... | 0.004141 |
def search_next(self, obj):
"""
Takes the dictionary that is returned by 'search' or 'search_next' function and gets the next batch of results
Args:
obj: dictionary returned by the 'search' or 'search_next' function
Returns:
A dictionary with a data returned by the... | 0.007865 |
def sub_retab(match):
r"""Remove all tabs and convert them into spaces.
PARAMETERS:
match -- regex match; uses re_retab pattern: \1 is text before tab,
\2 is a consecutive string of tabs.
A simple substitution of 4 spaces would result in the following:
to\tlive # original
... | 0.00146 |
async def cancel_task(app: web.Application,
task: asyncio.Task,
*args, **kwargs
) -> Any:
"""
Convenience function for calling `TaskScheduler.cancel(task)`
This will use the default `TaskScheduler` to cancel the given task.
Example:
... | 0.001552 |
def list_namespaced_config_map(self, namespace, **kwargs):
"""
list or watch objects of kind ConfigMap
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_config_map(namespace, ... | 0.002556 |
def add_child_resource_client(self, res_name, res_spec):
"""Add a resource client to the container and start the resource connection"""
res_spec = dict(res_spec)
res_spec['name'] = res_name
res = self.client_resource_factory(
res_spec, parent=self, logger=self._logger)
... | 0.00818 |
def get_2d_markers(
self, component_info=None, data=None, component_position=None, index=None
):
"""Get 2D markers.
:param index: Specify which camera to get 2D from, will be returned as
first entry in the returned array.
"""
return self._get_2d_markers... | 0.010076 |
def RestoreSnapshot(self,name=None):
"""Restores an existing Hypervisor level snapshot.
Supply snapshot name to restore
If no snapshot name is supplied will restore the first snapshot found
>>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').RestoreSnapshot().WaitUntilComplete()
0
"""
if not len(self.da... | 0.038911 |
def get_meta_image_url(request, image):
"""
Resize an image for metadata tags, and return an absolute URL to it.
"""
rendition = image.get_rendition(filter='original')
return request.build_absolute_uri(rendition.url) | 0.004237 |
def filter(self, table, security_groups, filter_string):
"""Naive case-insensitive search."""
query = filter_string.lower()
return [security_group for security_group in security_groups
if query in security_group.name.lower()] | 0.007547 |
def get_wellseries(self, matrix):
"""
Returns the grid as a WellSeries of WellSeries
"""
res = OrderedDict()
for col, cells in matrix.items():
if col not in res:
res[col] = OrderedDict()
for row, cell in cells.items():
res[c... | 0.004082 |
def clear(self):
"""Remove all items."""
self._fwdm.clear()
self._invm.clear()
self._sntl.nxt = self._sntl.prv = self._sntl | 0.012903 |
def find_python_files(dirname):
"""Yield all of the importable Python files in `dirname`, recursively.
To be importable, the files have to be in a directory with a __init__.py,
except for `dirname` itself, which isn't required to have one. The
assumption is that `dirname` was specified directly, so th... | 0.000888 |
def download_member_project_data(cls, member_data, target_member_dir,
max_size=MAX_SIZE_DEFAULT,
id_filename=False):
"""
Download files to sync a local dir to match OH member project data.
:param member_data: This field i... | 0.002761 |
def sigmoid_cross_entropy_with_logits(logits, targets):
"""Sigmoid cross-entropy loss.
Args:
logits: a mtf.Tensor
targets: a mtf.Tensor with the same shape as logits
Returns:
a mtf.Tensor whose shape is equal to logits.shape
Raises:
ValueError: if the shapes do not match.
"""
if logits.sh... | 0.010435 |
def index(
self,
symbol='000001',
market='sh',
category='9',
start='0',
offset='100'):
'''
获取指数k线
K线种类:
- 0 5分钟K线
- 1 15分钟K线
- 2 30分钟K线
- 3 1小时K线
- 4 日K线
- 5 周K线
- 6 月K线
- 7 1分钟
... | 0.003567 |
async def close(self):
"""Close the cursor now (rather than whenever __del__ is called).
The cursor will be unusable from this point forward; an Error
(or subclass) exception will be raised if any operation is attempted
with the cursor.
"""
if self._conn is None:
... | 0.00489 |
def usePointsForInterpolation(self,cNrm,mNrm,interpolator):
'''
Make a basic solution object with a consumption function and marginal
value function (unconditional on the preference shock).
Parameters
----------
cNrm : np.array
Consumption points for interpol... | 0.010808 |
def _pipeline_cell(args, cell_body):
"""Implements the pipeline subcommand in the %%bq magic.
Args:
args: the arguments following '%%bq pipeline'.
cell_body: Cell contents.
"""
name = args.get('name')
if name is None:
raise Exception('Pipeline name was not specified.')
impor... | 0.008806 |
def addFactory(self, identifier, factory):
"""Adds a factory.
After calling this method, remote clients will be able to
connect to it.
This will call ``factory.doStart``.
"""
factory.doStart()
self._factories[identifier] = factory | 0.00692 |
def closed(self):
""" True if ticket was closed in given time frame """
for who, what, old, new in self.history():
if what == "status" and new == "closed":
return True
return False | 0.008621 |
def plugin(name):
"""Executes the selected plugin
Plugins are expected to be found in the kitchen's 'plugins' directory
"""
env.host_string = lib.get_env_host_string()
plug = lib.import_plugin(name)
lib.print_header("Executing plugin '{0}' on "
"{1}".format(name, env.host_s... | 0.001992 |
def caom2(mpc_filename, search_date="2014 07 24.0"):
"""
builds a TSV file in the format of SSOIS by querying for possilbe observations in CADC/CAOM2.
This is a fall back program, should only be useful when SSOIS is behind.
"""
columns = ('Image',
'Ext',
'X',
... | 0.004071 |
def main(logfile=False):
""" Solve River Pollution problem with NAUTILUS V1 and E-NAUTILUS Methods
"""
# Duplicate output to log file
class NAUTILUSOptionValidator(Validator):
def validate(self, document):
if document.text not in "ao":
raise ValidationError(
... | 0.001401 |
def bitmask(*args):
"""! @brief Returns a mask with specified bit ranges set.
An integer mask is generated based on the bits and bit ranges specified by the
arguments. Any number of arguments can be provided. Each argument may be either
a 2-tuple of integers, a list of integers, or an individual in... | 0.008821 |
def describe(self, chunk_summary=False):
"""
Generate an in-depth description of this H2OFrame.
This will print to the console the dimensions of the frame; names/types/summary statistics for each column;
and finally first ten rows of the frame.
:param bool chunk_summary: Retrie... | 0.007479 |
def add_permissions(self, group_name, resource, permissions, url_prefix, auth, session, send_opts):
"""
Args:
group_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
permissions (list): List o... | 0.006614 |
def _encode_codepage(codepage, text):
"""
Args:
codepage (int)
text (text)
Returns:
`bytes`
Encode text using the given code page. Will not fail if a char
can't be encoded using that codepage.
"""
assert isinstance(text, text_type)
if not text:
return b... | 0.001167 |
def encode(data):
"""
Encodes data using PackBits encoding.
"""
if len(data) == 0:
return data
if len(data) == 1:
return b'\x00' + data
data = bytearray(data)
result = bytearray()
buf = bytearray()
pos = 0
repeat_count = 0
MAX_LENGTH = 127
# we can saf... | 0.000576 |
def parse(cls, fptr, offset, length):
"""Parse JPEG 2000 header box.
Parameters
----------
fptr : file
Open file object.
offset : int
Start position of box in bytes.
length : int
Length of the box in bytes.
Returns
---... | 0.003257 |
def sortino_ratio(self, threshold=0.0, ddof=0, freq=None):
"""Return over a threshold per unit of downside deviation.
A performance appraisal ratio that replaces standard deviation
in the Sharpe ratio with downside deviation.
[Source: CFA Institute]
Parameters
---------... | 0.001486 |
def update_session(self, alias, headers=None, cookies=None):
"""Update Session Headers: update a HTTP Session Headers
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of headers merge into session
"""
session = self._cache.switch(alias)
ses... | 0.004545 |
def _evaluate_trigger_rule(
self,
ti,
successes,
skipped,
failed,
upstream_failed,
done,
flag_upstream_failed,
session):
"""
Yields a dependency status that indicate whether the given task instanc... | 0.001225 |
def get_end(pos, alt, category, snvend=None, svend=None, svlen=None):
"""Return the end coordinate for a variant
Args:
pos(int)
alt(str)
category(str)
snvend(str)
svend(int)
svlen(int)
Returns:
end(int)
"""
# If nothing is known we set end to... | 0.000889 |
def env():
"""Verify NVME variables and construct exported variables"""
if cij.ssh.env():
cij.err("cij.nvme.env: invalid SSH environment")
return 1
nvme = cij.env_to_dict(PREFIX, REQUIRED)
nvme["DEV_PATH"] = os.path.join("/dev", nvme["DEV_NAME"])
# get version, chunks, luns and c... | 0.002644 |
def speziale_debyetemp(v, v0, gamma0, q0, q1, theta0):
"""
calculate Debye temperature for the Speziale equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
... | 0.001064 |
def set_selected_radio_button(self):
"""Set selected radio button to 'Do not report'."""
dont_use_button = self.default_input_button_group.button(
len(self._parameter.default_values) - 2)
dont_use_button.setChecked(True) | 0.007813 |
def geometry_linestring(lat, lon, elev):
"""
GeoJSON Linestring. Latitude and Longitude have 2 values each.
:param list lat: Latitude values
:param list lon: Longitude values
:return dict:
"""
logger_excel.info("enter geometry_linestring")
d = OrderedDict()
coordinates = []
temp... | 0.000959 |
def remove_address(self, fqdn, address):
" Remove an address of a domain."
# Get a list of addresses.
for record in self.list_address(fqdn):
if record.address == address:
record.delete()
break | 0.007663 |
def find_cross_contamination(databases, pair, tmpdir='tmp', log='log.txt', threads=1):
"""
Usese mash to find out whether or not a sample has more than one genus present, indicating cross-contamination.
:param databases: A databases folder, which must contain refseq.msh, a mash sketch that has one represent... | 0.004536 |
def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
ret = set()
for name in _iter_service_names():
if _service_is_upstart(name):
if _upstart_is_enabled(name):
ret.add(name)
... | 0.002146 |
async def probe_node_type_major(self, client):
"""Determine if import source node is a CN or MN and which major version API to
use."""
try:
node_pyxb = await self.get_node_doc(client)
except d1_common.types.exceptions.DataONEException as e:
raise django.core.manag... | 0.004193 |
def _print_options_help(self):
"""Print a help screen.
Assumes that self._help_request is an instance of OptionsHelp.
Note: Ony useful if called after options have been registered.
"""
show_all_help = self._help_request.all_scopes
if show_all_help:
help_scopes = list(self._options.known_... | 0.016336 |
def __scale_image(image, scale: float):
"""
Scales the image to a given scale.
:param image:
:param scale:
:return:
"""
height, width, _ = image.shape
width_scaled = int(np.ceil(width * scale))
height_scaled = int(np.ceil(height * scale))
... | 0.005525 |
def get_provides(self, ignored=tuple(), private=False):
"""
The provided API, including the class itself, its fields, and its
methods.
"""
if private:
if self._provides_private is None:
self._provides_private = set(self._get_provides(True))
... | 0.003407 |
def get_attr_desc(instance, attribute, action):
"""
Fetch the appropriate descriptor for the attribute.
:param instance: Model instance
:param attribute: Name of the attribute
:param action: AttributeAction
"""
descs = instance.__jsonapi_attribute_descriptors__.get(attribute, {})
if act... | 0.00165 |
def getSignature(self, signatureKey, serialized):
"""
:type signatureKey: ECPrivateKey
:type serialized: bytearray
"""
try:
return Curve.calculateSignature(signatureKey, serialized)
except InvalidKeyException as e:
raise AssertionError(e) | 0.006452 |
def p_inline_fragment1(self, p):
"""
inline_fragment : SPREAD ON type_condition directives selection_set
"""
p[0] = InlineFragment(type_condition=p[3], selections=p[5],
directives=p[4]) | 0.008097 |
def _handle_final_metric_data(self, data):
"""Call tuner to process final results
"""
id_ = data['parameter_id']
value = data['value']
if id_ in _customized_parameter_ids:
self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value)
else:
... | 0.007732 |
def create_deployment(deployment_name,
token_manager=None,
app_url=defaults.APP_URL):
"""
create a deployment with the specified name
"""
headers = token_manager.get_access_token_headers()
payload = {
'name': deployment_name,
'isAdmin': T... | 0.002729 |
def _conv(self, name, x, filter_size, in_filters, out_filters, strides):
"""Convolution."""
with tf.variable_scope(name):
n = filter_size * filter_size * out_filters
kernel = tf.get_variable(
"DW", [filter_size, filter_size, in_filters, out_filters],
... | 0.003953 |
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstr... | 0.002427 |
def get_wake_on_network():
'''
Displays whether 'wake on network' is on or off if supported
:return: A string value representing the "wake on network" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_wake_on_network
'''
ret = salt.utils.mac_utils.e... | 0.002024 |
def set_log_file(self, logfile):
"""
Set the log file full path including directory path basename and extension.
:Parameters:
#. logFile (string): the full log file path including basename and
extension. If this is given, all of logFileBasename and logFileExtension
... | 0.007396 |
def _parse_ip_addr_show(raw_result):
"""
Parse the 'ip addr list dev' command raw output.
:param str raw_result: os raw result string.
:rtype: dict
:return: The parsed result of the show interface command in a \
dictionary of the form:
::
{
'os_index' : '0',
... | 0.000497 |
def all_files(models=[]):
r'''
Return a list of full path of files matching 'models', sorted in human
numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000).
Files are supposed to be named identically except one variable component
e.g. the list,
test.weights.e5.lstm1200.ldc93s1.pb
... | 0.000759 |
def read(self, job_id):
"""
Reads the information for a specific Batch API request
:param job_id: The id of the job to be read from
:type job_id: str
:return: Response data, either as json or as a regular response.content
object
:rtype: object
... | 0.004505 |
def get_playback_callback(resampler, samplerate, params):
"""Return a sound playback callback.
Parameters
----------
resampler
The resampler from which samples are read.
samplerate : float
The sample rate.
params : dict
Parameters for FM generation.
"""
def call... | 0.000993 |
def assert_lock(fname):
"""
If file is locked then terminate program else lock file.
"""
if not set_lock(fname):
logger.error('File {} is already locked. Terminating.'.format(fname))
sys.exit() | 0.004425 |
def draw(self, mode='triangles', indices=None, check_error=True):
""" Draw the attribute arrays in the specified mode.
Parameters
----------
mode : str | GL_ENUM
'points', 'lines', 'line_strip', 'line_loop', 'triangles',
'triangle_strip', or 'triangle_fan'.
... | 0.004218 |
def _server_whitelist(self):
'''
Returns list of servers that have not errored in the last five minutes.
If all servers have errored in the last five minutes, returns list with
one item, the server that errored least recently.
'''
whitelist = []
for server in self... | 0.004539 |
def prcntiles(x,percents):
'''Equivalent to matlab prctile(x,p), uses linear interpolation.'''
x=np.array(x).flatten()
listx = np.sort(x)
xpcts=[]
lenlistx=len(listx)
refs=[]
for i in range(0,lenlistx):
r=100*((.5+i)/lenlistx) #refs[i] is percentile of listx[i] in matrix x
re... | 0.025584 |
def AppendUnique(self, delete_existing=0, **kw):
"""Append values to existing construction variables
in an Environment, if they're not already there.
If delete_existing is 1, removes existing values first, so
values move to end.
"""
kw = copy_non_reserved_keywords(kw)
... | 0.001318 |
def get_kbr_values(self, searchkey="", searchvalue="", searchtype='s'):
"""
Return dicts of 'key' and 'value' from a knowledge base.
:param kb_name the name of the knowledge base
:param searchkey search using this key
:param searchvalue search using this value
:param sea... | 0.001444 |
def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None):
'''
Check if path exists
path
path to check
profile
Configured Zookeeper profile to authenticate with (Default: None)
hosts
Lists of Zookeeper Hosts (Default: '127.0.0.... | 0.004292 |
def bboxiter(tile_bounds, tiles_per_row_per_region=1):
"""
Iterate through a grid of regions defined by a TileBB.
Args:
tile_bounds (GridBB):
tiles_per_row_per_region: Combine multiple tiles in one region.
E.g. if set to two, four tiles will be combined in one region.
... | 0.000563 |
def min_fill_heuristic(G):
"""Computes an upper bound on the treewidth of graph G based on
the min-fill heuristic for the elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute an upper bound for the treewidth.
Returns
-------
treewidth_upp... | 0.001217 |
def tone_chat(self,
utterances,
content_language=None,
accept_language=None,
**kwargs):
"""
Analyze customer engagement tone.
Use the customer engagement endpoint to analyze the tone of customer service and
customer... | 0.007088 |
def ldirectory(inpath, outpath, args, scope):
"""Compile all *.less files in directory
Args:
inpath (str): Path to compile
outpath (str): Output directory
args (object): Argparse Object
scope (Scope): Scope object or None
"""
yacctab = 'yacctab' if args.debug else None
... | 0.0005 |
def merge_bibtex_with_aux(auxpath, mainpath, extradir, parse=get_bibtex_dict, allow_missing=False):
"""Merge multiple BibTeX files into a single homogeneously-formatted output,
using a LaTeX .aux file to know which records are worth paying attention
to.
The file identified by `mainpath` will be overwri... | 0.002639 |
def _convert_date_time_string(dt_string):
'''
convert string to date time object
'''
dt_string = dt_string.split('.')[0]
dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S')
return dt_obj.strftime('%Y-%m-%d %H:%M:%S') | 0.004132 |
def change_custom_svc_var(self, service, varname, varvalue):
"""Change custom service variable
Format of the line that triggers function call::
CHANGE_CUSTOM_SVC_VAR;<host_name>;<service_description>;<varname>;<varvalue>
:param service: service to edit
:type service: alignak.ob... | 0.003841 |
def serve(content):
"""Write content to a temp file and serve it in browser"""
temp_folder = tempfile.gettempdir()
temp_file_name = tempfile.gettempprefix() + str(uuid.uuid4()) + ".html"
# Generate a file path with a random name in temporary dir
temp_file_path = os.path.join(temp_folder, temp_file_n... | 0.001468 |
def read_cz_lsm_info(fd, byte_order, dtype, count):
"""Read CS_LSM_INFO tag from file and return as numpy.rec.array."""
result = numpy.rec.fromfile(fd, CZ_LSM_INFO, 1,
byteorder=byte_order)[0]
{50350412: '1.3', 67127628: '2.0'}[result.magic_number] # validation
return re... | 0.003086 |
def register_modele(self, modele: Modele):
""" Register a modele onto the lemmatizer
:param modele: Modele to register
"""
self.lemmatiseur._modeles[modele.gr()] = modele | 0.009852 |
def is_child_of_log(self, id_, log_id):
"""Tests if an ``Id`` is a direct child of a log.
arg: id (osid.id.Id): an ``Id``
arg: log_id (osid.id.Id): the ``Id`` of a log
return: (boolean) - ``true`` if this ``id`` is a child of
``log_id,`` ``false`` otherwise
... | 0.002982 |
def __load_dump(self, message):
"""
Calls the hook method to modify the loaded peer description before
giving it to the directory
:param message: The received Herald message
:return: The updated peer description
"""
dump = message.content
if self._hook is... | 0.002865 |
def classes(self):
"""Iterate over the defined Classes."""
defclass = lib.EnvGetNextDefclass(self._env, ffi.NULL)
while defclass != ffi.NULL:
yield Class(self._env, defclass)
defclass = lib.EnvGetNextDefclass(self._env, defclass) | 0.007168 |
def derivative(self, x):
"""Return the derivative at ``x``.
The derivative of the right scalar operator multiplication
follows the chain rule:
``OperatorRightScalarMult(op, s).derivative(y) ==
OperatorLeftScalarMult(op.derivative(s * y), s)``
Parameters
... | 0.002392 |
def integrate(self, min, max, attr=None, info={}):
""" Calculate the total number of points between [min, max).
If attr is given, also calculate the sum of the weight.
This is a M log(N) operation, where M is the number of min/max
queries and N is number of points.
... | 0.002141 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.