code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def peers(**kwargs):
ntp_peers = salt.utils.napalm.call(
napalm_device,
'get_ntp_peers',
**{
}
)
if not ntp_peers.get('result'):
return ntp_peers
ntp_peers_list = list(ntp_peers.get('out', {}).keys())
ntp_peers['out'] = ntp_peers_list
return ntp_peers | Returns a list the NTP peers configured on the network device.
:return: configured NTP peers as list.
CLI Example:
.. code-block:: bash
salt '*' ntp.peers
Example output:
.. code-block:: python
[
'192.168.0.1',
'172.17.17.1',
'172.17.17.2',
'2400:cb00:6:1024::c71b:840a'
] |
def transform(self, data, centers=None):
centers = centers or self.centers_
hypercubes = [
self.transform_single(data, cube, i) for i, cube in enumerate(centers)
]
hypercubes = [cube for cube in hypercubes if len(cube)]
return hypercubes | Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`.
Empty hypercubes are removed from the result
Parameters
===========
data: array-like
Data to find in entries in cube. Warning: first column must be index column.
centers: list of array-like
Center points for all cubes as returned by `self.fit`. Default is to use `self.centers_`.
Returns
=========
hypercubes: list of array-like
list of entries in each hypercobe in `data`. |
def set_color(self, ipaddr, hue, sat, bri, kel, fade):
cmd = {"payloadtype": PayloadType.SETCOLOR,
"target": ipaddr,
"hue": hue,
"sat": sat,
"bri": bri,
"kel": kel,
"fade": fade}
self._send_command(cmd) | Send SETCOLOR message. |
def validate_model(self):
model: AssetAllocationModel = self.get_asset_allocation_model()
model.logger = self.logger
valid = model.validate()
if valid:
print(f"The model is valid. Congratulations")
else:
print(f"The model is invalid.") | Validate the model |
def capture_heroku_database(self):
self.print_message("Capturing database backup for app '%s'" % self.args.source_app)
args = [
"heroku",
"pg:backups:capture",
"--app=%s" % self.args.source_app,
]
if self.args.use_pgbackups:
args = [
"heroku",
"pgbackups:capture",
"--app=%s" % self.args.source_app,
"--expire",
]
subprocess.check_call(args) | Capture Heroku database backup. |
def clone(self, parent=None):
a = Attribute(self.qname(), self.value)
a.parent = parent
return a | Clone this object.
@param parent: The parent for the clone.
@type parent: L{element.Element}
@return: A copy of this object assigned to the new parent.
@rtype: L{Attribute} |
def _get_at_from_session(self):
try:
return self.request.session['oauth_%s_access_token'
% get_token_prefix(
self.request_token_url)]
except KeyError:
raise OAuthError(
_('No access token saved for "%s".')
% get_token_prefix(self.request_token_url)) | Get the saved access token for private resources from the session. |
def GenerateDSP(dspfile, source, env):
version_num = 6.0
if 'MSVS_VERSION' in env:
version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
if version_num >= 10.0:
g = _GenerateV10DSP(dspfile, source, env)
g.Build()
elif version_num >= 7.0:
g = _GenerateV7DSP(dspfile, source, env)
g.Build()
else:
g = _GenerateV6DSP(dspfile, source, env)
g.Build() | Generates a Project file based on the version of MSVS that is being used |
def estimate_sub_second_time(files, interval=0.0):
if interval <= 0.0:
return [exif_time(f) for f in tqdm(files, desc="Reading image capture time")]
onesecond = datetime.timedelta(seconds=1.0)
T = datetime.timedelta(seconds=interval)
for i, f in tqdm(enumerate(files), desc="Estimating subsecond time"):
m = exif_time(f)
if not m:
pass
if i == 0:
smin = m
smax = m + onesecond
else:
m0 = m - T * i
smin = max(smin, m0)
smax = min(smax, m0 + onesecond)
if not smin or not smax:
return None
if smin > smax:
print('Interval not compatible with EXIF times')
return None
else:
s = smin + (smax - smin) / 2
return [s + T * i for i in range(len(files))] | Estimate the capture time of a sequence with sub-second precision
EXIF times are only given up to a second of precision. This function
uses the given interval between shots to estimate the time inside that
second that each picture was taken. |
def delete(self):
response = self.session.request("delete:Message", [ self.message_id ])
self.data = response
return self | Delete the draft. |
def is_manifest_valid(self, manifest_id):
response = self.get_manifest_validation_result(manifest_id)
if response.status_code != 200:
raise Exception(response.status_code)
content = json.loads(response.content)
if not content['processed']:
return None
if content['valid']:
return True
return content['validation'] | Check validation shortcut
:param: manifest_id (string) id received in :method:`validate_manifest`
:returns:
* True if manifest was valid
* None if manifest wasn't checked yet
* validation dict if not valid |
def verify_token(self, token, **kwargs):
nonce = kwargs.get('nonce')
token = force_bytes(token)
if self.OIDC_RP_SIGN_ALGO.startswith('RS'):
if self.OIDC_RP_IDP_SIGN_KEY is not None:
key = self.OIDC_RP_IDP_SIGN_KEY
else:
key = self.retrieve_matching_jwk(token)
else:
key = self.OIDC_RP_CLIENT_SECRET
payload_data = self.get_payload_data(token, key)
payload = json.loads(payload_data.decode('utf-8'))
token_nonce = payload.get('nonce')
if self.get_settings('OIDC_USE_NONCE', True) and nonce != token_nonce:
msg = 'JWT Nonce verification failed.'
raise SuspiciousOperation(msg)
return payload | Validate the token signature. |
def from_cif_file(cif_file, source='', comment=''):
r = CifParser(cif_file)
structure = r.get_structures()[0]
return Header(structure, source, comment) | Static method to create Header object from cif_file
Args:
cif_file: cif_file path and name
source: User supplied identifier, i.e. for Materials Project this
would be the material ID number
comment: User comment that goes in header
Returns:
Header Object |
def _output_format(self, out, fmt_j=None, fmt_p=None):
if self.output_format == 'pandas':
if fmt_p is not None:
return fmt_p(out)
else:
return self._convert_output(out)
if fmt_j:
return fmt_j(out)
return out | Output formatting handler |
def to_api_repr(self):
resource = {self.entity_type: self.entity_id}
if self.role is not None:
resource["role"] = self.role
return resource | Construct the API resource representation of this access entry
Returns:
Dict[str, object]: Access entry represented as an API resource |
def save_cert(domain, master):
result = __salt__['cmd.run_all'](["icinga2", "pki", "save-cert", "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.cert".format(get_certs_path(), domain), "--trustedcert",
"{0}trusted-master.crt".format(get_certs_path()), "--host", master], python_shell=False)
return result | Save the certificate for master icinga2 node.
Returns::
icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.save_cert domain.tld master.domain.tld |
def validate_attribute(attr, name, expected_type=None, required=False):
if expected_type:
if type(expected_type) == list:
if not _check_type(attr, expected_type):
raise InvalidTypeError(name, type(attr), expected_type)
else:
if not _check_type(attr, [expected_type]):
raise InvalidTypeError(name, type(attr), expected_type)
if required and not attr:
raise RequiredAttributeError(name) | Validates that an attribute meets expectations.
This function will check if the given attribute value matches a necessary
type and/or is not None, an empty string, an empty list, etc. It will raise
suitable exceptions on validation failure.
@param attr The value to validate.
@param name The attribute name to use in exceptions.
@param expected_type The type the value must be. If None, no check is
performed. If a list, attr must match one type in the list.
@param required If the value must not be empty, e.g. not an empty string.
@raises InvalidTypeError
@raises RequiredAttributeError |
def _flush(self):
if not self.enabled:
return
try:
try:
self.lock.acquire()
self.flush()
except Exception:
self.log.error(traceback.format_exc())
finally:
if self.lock.locked():
self.lock.release() | Decorator for flushing handlers with an lock, catching exceptions |
async def get_available_abilities(self, units: Union[List[Unit], Units], ignore_resource_requirements=False) -> List[List[AbilityId]]:
return await self._client.query_available_abilities(units, ignore_resource_requirements) | Returns available abilities of one or more units. |
def remove_whitespace(s):
ignores = {}
for ignore in html_ignore_whitespace_re.finditer(s):
name = "{}{}{}".format(r"{}", uuid.uuid4(), r"{}")
ignores[name] = ignore.group()
s = s.replace(ignore.group(), name)
s = whitespace_re(r' ', s).strip()
for name, val in ignores.items():
s = s.replace(name, val)
return s | Unsafely attempts to remove HTML whitespace. This is not an HTML parser
which is why its considered 'unsafe', but it should work for most
implementations. Just use on at your own risk.
@s: #str
-> HTML with whitespace removed, ignoring <pre>, script, textarea and code
tags |
def _check_if_ins_is_dup(self, start, insertion):
is_dup = False
variant_start = None
dup_candidate_start = start - len(insertion) - 1
dup_candidate = self._ref_seq[dup_candidate_start:dup_candidate_start + len(insertion)]
if insertion == dup_candidate:
is_dup = True
variant_start = dup_candidate_start + 1
return is_dup, variant_start | Helper to identify an insertion as a duplicate
:param start: 1-based insertion start
:type start: int
:param insertion: sequence
:type insertion: str
:return (is duplicate, variant start)
:rtype (bool, int) |
def relpath(self, start='.'):
cwd = self._next_class(start)
return cwd.relpathto(self) | Return this path as a relative path,
based from `start`, which defaults to the current working directory. |
def makeaddress(self, label):
addr = address.new(label)
if not addr.repo:
addr.repo = self.address.repo
if not addr.path:
addr.path = self.address.path
return addr | Turn a label into an Address with current context.
Adds repo and path if given a label that only has a :target part. |
def create_hook(self, auth, repo_name, hook_type, config, events=None, organization=None, active=False):
if events is None:
events = ["push"]
data = {
"type": hook_type,
"config": config,
"events": events,
"active": active
}
url = "/repos/{o}/{r}/hooks".format(o=organization, r=repo_name) if organization is not None \
else "/repos/{r}/hooks".format(r=repo_name)
response = self.post(url, auth=auth, data=data)
return GogsRepo.Hook.from_json(response.json()) | Creates a new hook, and returns the created hook.
:param auth.Authentication auth: authentication object, must be admin-level
:param str repo_name: the name of the repo for which we create the hook
:param str hook_type: The type of webhook, either "gogs" or "slack"
:param dict config: Settings for this hook (possible keys are
``"url"``, ``"content_type"``, ``"secret"``)
:param list events: Determines what events the hook is triggered for. Default: ["push"]
:param str organization: Organization of the repo
:param bool active: Determines whether the hook is actually triggered on pushes. Default is false
:return: a representation of the created hook
:rtype: GogsRepo.Hook
:raises NetworkFailure: if there is an error communicating with the server
:raises ApiFailure: if the request cannot be serviced |
def set_line_width(self, width):
"Set line width"
self.line_width=width
if(self.page>0):
self._out(sprintf('%.2f w',width*self.k)) | Set line width |
def apply_with_summary(input_layer, operation, *op_args, **op_kwargs):
return layers.apply_activation(input_layer.bookkeeper,
input_layer.tensor,
operation,
activation_args=op_args,
activation_kwargs=op_kwargs) | Applies the given operation to `input_layer` and create a summary.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_kwargs: Keyword arguments for the operation.
Returns:
A new layer with operation applied. |
def is_merged(sheet, row, column):
for cell_range in sheet.merged_cells:
row_low, row_high, column_low, column_high = cell_range
if (row in range(row_low, row_high)) and \
(column in range(column_low, column_high)):
if ((column_high - column_low) < sheet.ncols - 1) and \
((row_high - row_low) < sheet.nrows - 1):
return (True, cell_range)
return False | Check if a row, column cell is a merged cell |
def _acronym_lic(self, license_statement):
pat = re.compile(r'\(([\w+\W?\s?]+)\)')
if pat.search(license_statement):
lic = pat.search(license_statement).group(1)
if lic.startswith('CNRI'):
acronym_licence = lic[:4]
else:
acronym_licence = lic.replace(' ', '')
else:
acronym_licence = ''.join(
[w[0]
for w in license_statement.split(self.prefix_lic)[1].split()])
return acronym_licence | Convert license acronym. |
def setup(self, helper=None, **create_kwargs):
if self.created:
return
self.set_helper(helper)
self.create(**create_kwargs)
return self | Setup this resource so that is ready to be used in a test. If the
resource has already been created, this call does nothing.
For most resources, this just involves creating the resource in Docker.
:param helper:
The resource helper to use, if one was not provided when this
resource definition was created.
:param **create_kwargs: Keyword arguments passed to :meth:`.create`.
:returns:
This definition instance. Useful for creating and setting up a
resource in a single step::
volume = VolumeDefinition('volly').setup(helper=docker_helper) |
def import_(zone, path):
ret = {'status': True}
_dump_cfg(path)
res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format(
zone=zone,
path=path,
))
ret['status'] = res['retcode'] == 0
ret['message'] = res['stdout'] if ret['status'] else res['stderr']
if ret['message'] == '':
del ret['message']
else:
ret['message'] = _clean_message(ret['message'])
return ret | Import the configuration to memory from stable storage.
zone : string
name of zone
path : string
path of file to export to
CLI Example:
.. code-block:: bash
salt '*' zonecfg.import epyon /zones/epyon.cfg |
def create_window(size=None, samples=16, *, fullscreen=False, title=None, threaded=True) -> Window:
if size is None:
width, height = 1280, 720
else:
width, height = size
if samples < 0 or (samples & (samples - 1)) != 0:
raise Exception('Invalid number of samples: %d' % samples)
window = Window.__new__(Window)
window.wnd = glwnd.create_window(width, height, samples, fullscreen, title, threaded)
return window | Create the main window.
Args:
size (tuple): The width and height of the window.
samples (int): The number of samples.
Keyword Args:
fullscreen (bool): Fullscreen?
title (bool): The title of the window.
threaded (bool): Threaded?
Returns:
Window: The main window. |
def dump(*args, **kwargs):
kwargs.update(dict(cls=NumpyEncoder,
sort_keys=True,
indent=4,
separators=(',', ': ')))
return _json.dump(*args, **kwargs) | Dump a numpy.ndarray to file stream.
This works exactly like the usual `json.dump()` function,
but it uses our custom serializer. |
def wildcard_allowed_actions(self, pattern=None):
wildcard_allowed = []
for statement in self.statements:
if statement.wildcard_actions(pattern) and statement.effect == "Allow":
wildcard_allowed.append(statement)
return wildcard_allowed | Find statements which allow wildcard actions.
A pattern can be specified for the wildcard action |
def NegateQueryFilter(es_query):
query = es_query.to_dict().get("query", {})
filtered = query.get("filtered", {})
negated_filter = filtered.get("filter", {})
return Not(**negated_filter) | Return a filter removing the contents of the provided query. |
def _pause(self):
if self._input_func in self._netaudio_func_list:
body = {"cmd0": "PutNetAudioCommand/CurEnter",
"cmd1": "aspMainZone_WebUpdateStatus/",
"ZoneName": "MAIN ZONE"}
try:
if self.send_post_command(
self._urls.command_netaudio_post, body):
self._state = STATE_PAUSED
return True
else:
return False
except requests.exceptions.RequestException:
_LOGGER.error("Connection error: pause command not sent.")
return False | Send pause command to receiver command via HTTP post. |
def _create_batches(self, X, batch_size, shuffle_data=True):
if shuffle_data:
X = shuffle(X)
if batch_size > X.shape[0]:
batch_size = X.shape[0]
max_x = int(np.ceil(X.shape[0] / batch_size))
X = np.resize(X, (max_x, batch_size, X.shape[-1]))
return X | Create batches out of a sequence of data.
This function will append zeros to the end of your data to ensure that
all batches are even-sized. These are masked out during training. |
def _bubbleP(cls, T):
c = cls._blend["bubble"]
Tj = cls._blend["Tj"]
Pj = cls._blend["Pj"]
Tita = 1-T/Tj
suma = 0
for i, n in zip(c["i"], c["n"]):
suma += n*Tita**(i/2.)
P = Pj*exp(Tj/T*suma)
return P | Using ancillary equation return the pressure of bubble point |
def fetchThreads(self, thread_location, before=None, after=None, limit=None):
threads = []
last_thread_timestamp = None
while True:
if limit and len(threads) >= limit:
break
candidates = self.fetchThreadList(
before=last_thread_timestamp, thread_location=thread_location
)
if len(candidates) > 1:
threads += candidates[1:]
else:
break
last_thread_timestamp = threads[-1].last_message_timestamp
if (before is not None and int(last_thread_timestamp) > before) or (
after is not None and int(last_thread_timestamp) < after
):
break
if before is not None or after is not None:
for t in threads:
last_message_timestamp = int(t.last_message_timestamp)
if (before is not None and last_message_timestamp > before) or (
after is not None and last_message_timestamp < after
):
threads.remove(t)
if limit and len(threads) > limit:
return threads[:limit]
return threads | Get all threads in thread_location.
Threads will be sorted from newest to oldest.
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: Fetch only thread before this epoch (in ms) (default all threads)
:param after: Fetch only thread after this epoch (in ms) (default all threads)
:param limit: The max. amount of threads to fetch (default all threads)
:return: :class:`models.Thread` objects
:rtype: list
:raises: FBchatException if request failed |
def output(output_id, name, value_class=NumberValue):
def _init():
return value_class(
name,
input_id=output_id,
is_input=False,
index=-1
)
def _decorator(cls):
setattr(cls, output_id, _init())
return cls
return _decorator | Add output to controller |
def create_attributes(klass, attributes, previous_object=None):
if previous_object is not None:
return {'name': attributes.get('name', previous_object.name)}
return {
'name': attributes.get('name', ''),
'defaultLocale': attributes['default_locale']
} | Attributes for space creation. |
def convert_random_normal(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
mean = float(attrs.get("loc", 0))
scale = float(attrs.get("scale", 1.0))
shape = convert_string_to_list(attrs.get('shape', '[]'))
dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get('dtype', 'float32'))]
node = onnx.helper.make_node(
'RandomNormal',
input_nodes,
[name],
mean=mean,
scale=scale,
dtype=dtype,
shape=shape,
name=name
)
return [node] | Map MXNet's random_normal operator attributes to onnx's RandomNormal
operator and return the created node. |
def include(self):
include_param = self.qs.get('include', [])
if current_app.config.get('MAX_INCLUDE_DEPTH') is not None:
for include_path in include_param:
if len(include_path.split('.')) > current_app.config['MAX_INCLUDE_DEPTH']:
raise InvalidInclude("You can't use include through more than {} relationships"
.format(current_app.config['MAX_INCLUDE_DEPTH']))
return include_param.split(',') if include_param else [] | Return fields to include
:return list: a list of include information |
def change_keys(obj, convert):
if isinstance(obj, (str, int, float)):
return obj
if isinstance(obj, dict):
new = obj.__class__()
for k, v in obj.items():
new[convert(k)] = change_keys(v, convert)
elif isinstance(obj, (list, set, tuple)):
new = obj.__class__(change_keys(v, convert) for v in obj)
else:
return obj
return new | Recursively goes through the dictionary obj and replaces keys with the convert function. |
def iter_nautilus(method):
solution = None
while method.current_iter:
preference_class = init_nautilus(method)
pref = preference_class(method, None)
default = ",".join(map(str, pref.default_input()))
while method.current_iter:
method.print_current_iteration()
pref_input = _prompt_wrapper(
u"Preferences: ",
default=default,
validator=VectorValidator(method, pref),
)
cmd = _check_cmd(pref_input)
if cmd:
solution = method.zh
break
pref = preference_class(
method, np.fromstring(pref_input, dtype=np.float, sep=",")
)
default = ",".join(map(str, pref.pref_input))
solution, _ = method.next_iteration(pref)
if cmd and list(cmd)[0] == "c":
break
return solution | Iterate NAUTILUS method either interactively, or using given preferences if given
Parameters
----------
method : instance of NAUTILUS subclass
Fully initialized NAUTILUS method instance |
def upcoming_shabbat(self):
if self.is_shabbat:
return self
saturday = self.gdate + datetime.timedelta(
(12 - self.gdate.weekday()) % 7)
return HDate(saturday, diaspora=self.diaspora, hebrew=self.hebrew) | Return the HDate for either the upcoming or current Shabbat.
If it is currently Shabbat, returns the HDate of the Saturday. |
def compute_layers(elements: List[Keccak256]) -> List[List[Keccak256]]:
elements = list(elements)
assert elements, 'Use make_empty_merkle_tree if there are no elements'
if not all(isinstance(item, bytes) for item in elements):
raise ValueError('all elements must be bytes')
if any(len(item) != 32 for item in elements):
raise HashLengthNot32()
if len(elements) != len(set(elements)):
raise ValueError('Duplicated element')
leaves = sorted(item for item in elements)
tree = [leaves]
layer = leaves
while len(layer) > 1:
paired_items = split_in_pairs(layer)
layer = [hash_pair(a, b) for a, b in paired_items]
tree.append(layer)
return tree | Computes the layers of the merkletree.
First layer is the list of elements and the last layer is a list with a
single entry, the merkleroot. |
def fill_in_by_selector(self, selector, value):
elem = find_element_by_jquery(world.browser, selector)
elem.clear()
elem.send_keys(value) | Fill in the form element matching the CSS selector. |
def ffPDC(self):
A = self.A()
return np.abs(A * self.nfft / np.sqrt(np.sum(A.conj() * A, axis=(0, 2),
keepdims=True))) | Full frequency partial directed coherence.
.. math:: \mathrm{ffPDC}_{ij}(f) =
\\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}} |
def get_example_extractions(fname):
"Get extractions from one of the examples in `cag_examples`."
with open(fname, 'r') as f:
sentences = f.read().splitlines()
rdf_xml_dict = {}
for sentence in sentences:
logger.info("Reading \"%s\"..." % sentence)
html = tc.send_query(sentence, 'cwms')
try:
rdf_xml_dict[sentence] = tc.get_xml(html, 'rdf:RDF',
fail_if_empty=True)
except AssertionError as e:
logger.error("Got error for %s." % sentence)
logger.exception(e)
return rdf_xml_dict | Get extractions from one of the examples in `cag_examples`. |
def _check_smart_storage_message(self):
ssc_mesg = self.smart_storage_config_message
result = True
raid_message = ""
for element in ssc_mesg:
if "Success" not in element['MessageId']:
result = False
raid_message = element['MessageId']
return result, raid_message | Check for smart storage message.
:returns: result, raid_message |
def ip2hex(ip):
parts = ip.split(".")
if len(parts) != 4: return None
ipv = 0
for part in parts:
try:
p = int(part)
if p < 0 or p > 255: return None
ipv = (ipv << 8) + p
except:
return None
return ipv | Converts an ip to a hex value that can be used with a hex bit mask |
def get_locations_from_coords(self, longitude, latitude, levels=None):
resp = requests.get(SETTINGS['url'] + '/point/4326/%s,%s?generation=%s' % (longitude, latitude, SETTINGS['generation']))
resp.raise_for_status()
geos = []
for feature in resp.json().itervalues():
try:
geo = self.get_geography(feature['codes']['MDB'],
feature['type_name'].lower())
if not levels or geo.geo_level in levels:
geos.append(geo)
except LocationNotFound as e:
log.warn("Couldn't find geo that Mapit gave us: %s" % feature, exc_info=e)
return geos | Returns a list of geographies containing this point. |
def content_create(self, key, model, contentid, meta, protected=False):
params = {'id': contentid, 'meta': meta}
if protected is not False:
params['protected'] = 'true'
data = urlencode(params)
path = PROVISION_MANAGE_CONTENT + model + '/'
return self._request(path,
key, data, 'POST', self._manage_by_cik) | Creates a content entity bucket with the given `contentid`.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---create-content-entity.
Args:
key: The CIK or Token for the device
model:
contentid: The ID used to name the entity bucket
meta:
protected: Whether or not this is restricted to certain device serial numbers only. |
def add(self, operator):
if not isinstance(operator, Scope):
raise ParameterError('Operator {} must be a TaskTransformer '
'or FeatureExtractor'.format(operator))
for key in operator.fields:
self._time[key] = []
for tdim, idx in enumerate(operator.fields[key].shape, 1):
if idx is None:
self._time[key].append(tdim) | Add an operator to the Slicer
Parameters
----------
operator : Scope (TaskTransformer or FeatureExtractor)
The new operator to add |
def configure():
log_levels = {
5: logging.NOTSET,
4: logging.DEBUG,
3: logging.INFO,
2: logging.WARNING,
1: logging.ERROR,
0: logging.CRITICAL
}
logging.captureWarnings(True)
root_logger = logging.getLogger()
if settings.CFG["debug"]:
details_format = logging.Formatter(
'%(name)s (%(filename)s:%(lineno)s) [%(levelname)s] %(message)s')
details_hdl = logging.StreamHandler()
details_hdl.setFormatter(details_format)
root_logger.addHandler(details_hdl)
else:
brief_format = logging.Formatter('%(message)s')
console_hdl = logging.StreamHandler()
console_hdl.setFormatter(brief_format)
root_logger.addHandler(console_hdl)
root_logger.setLevel(log_levels[int(settings.CFG["verbosity"])])
configure_plumbum_log()
configure_migrate_log()
configure_parse_log() | Load logging configuration from our own defaults. |
def precision_score(y_true, y_pred, average='micro', suffix=False):
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pred_entities)
score = nb_correct / nb_pred if nb_pred > 0 else 0
return score | Compute the precision.
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability of the classifier not to label as positive a sample.
The best value is 1 and the worst value is 0.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
score : float.
Example:
>>> from seqeval.metrics import precision_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> precision_score(y_true, y_pred)
0.50 |
def get_status(self):
result = ''
if self._data_struct is not None:
result = self._data_struct[KEY_STATUS]
return result | Return the status embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed. |
def _service_by_name(name):
services = _available_services()
name = name.lower()
if name in services:
return services[name]
for service in six.itervalues(services):
if service['file_path'].lower() == name:
return service
basename, ext = os.path.splitext(service['filename'])
if basename.lower() == name:
return service
return False | Return the service info for a service by label, filename or path |
def tasks_all_replaced_predicate(
service_name,
old_task_ids,
task_predicate=None
):
try:
task_ids = get_service_task_ids(service_name, task_predicate)
except DCOSHTTPException:
print('failed to get task ids for service {}'.format(service_name))
task_ids = []
print('waiting for all task ids in "{}" to change:\n- old tasks: {}\n- current tasks: {}'.format(
service_name, old_task_ids, task_ids))
for id in task_ids:
if id in old_task_ids:
return False
if len(task_ids) < len(old_task_ids):
return False
return True | Returns whether ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searching for tasks
:type task_predicate: func
:return: True if none of old_task_ids are still present in the service
:rtype: bool |
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True):
graph = tf.get_default_graph()
assert graph.unique_name(scope, False) == scope, (
'Scope "%s" already exists. Provide explicit scope names when '
'importing multiple instances of the model.') % scope
t_input, t_prep_input = self.create_input(t_input, forget_xy_shape)
tf.import_graph_def(
self.graph_def, {self.input_name: t_prep_input}, name=scope)
self.post_import(scope) | Import model GraphDef into the current graph. |
def fileMD5(filename, partial=True):
filesize = os.path.getsize(filename)
md5 = hash_md5()
block_size = 2**20
try:
if (not partial) or filesize < 2**24:
with open(filename, 'rb') as f:
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
else:
count = 16
with open(filename, 'rb') as f:
while True:
data = f.read(block_size)
count -= 1
if count == 8:
f.seek(-2**23, 2)
if not data or count == 0:
break
md5.update(data)
except IOError as e:
sys.exit(f'Failed to read {filename}: {e}')
return md5.hexdigest() | Calculate partial MD5, basically the first and last 8M
of the file for large files. This should signicicantly reduce
the time spent on the creation and comparison of file signature
when dealing with large bioinformat ics datasets. |
def _find_file_meta(metadata, bucket_name, saltenv, path):
env_meta = metadata[saltenv] if saltenv in metadata else {}
bucket_meta = {}
for bucket in env_meta:
if bucket_name in bucket:
bucket_meta = bucket[bucket_name]
files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta)))
for item_meta in files_meta:
if 'Key' in item_meta and item_meta['Key'] == path:
try:
item_meta['ETag'] = item_meta['ETag'].strip('"')
except KeyError:
pass
return item_meta | Looks for a file's metadata in the S3 bucket cache file |
def copymode(self, target):
shutil.copymode(self.path, self._to_backend(target)) | Copies the mode of this file on the `target` file.
The owner is not copied. |
def _add_example_helper(self, example):
for label, example_field in example.fields.items():
if not any(label == f.name for f in self.all_fields):
raise InvalidSpec(
"Example for '%s' has unknown field '%s'." %
(self.name, label),
example_field.lineno, example_field.path,
)
for field in self.all_fields:
if field.name in example.fields:
example_field = example.fields[field.name]
try:
field.data_type.check_example(example_field)
except InvalidSpec as e:
e.msg = "Bad example for field '{}': {}".format(
field.name, e.msg)
raise
elif field.has_default or isinstance(field.data_type, Nullable):
pass
else:
raise InvalidSpec(
"Missing field '%s' in example." % field.name,
example.lineno, example.path)
self._raw_examples[example.label] = example | Validates examples for structs without enumerated subtypes. |
def rowsum_stdev(x, beta):
r
n = x.size
betabar = (1.0/n) * np.dot(x, beta)
stdev = np.sqrt((1.0/n) *
np.sum(np.power(np.multiply(x, beta) - betabar, 2)))
return stdev/betabar | r"""Compute row sum standard deviation.
Compute for approximation x, the std dev of the row sums
s(x) = ( 1/n \sum_k (x_k beta_k - betabar)^2 )^(1/2)
with betabar = 1/n dot(beta,x)
Parameters
----------
x : array
beta : array
Returns
-------
s(x)/betabar : float
Notes
-----
equation (7) in Livne/Golub |
def extract_references_from_string(source,
is_only_references=True,
recid=None,
reference_format="{title} {volume} ({year}) {page}",
linker_callback=None,
override_kbs_files=None):
docbody = source.split('\n')
if not is_only_references:
reflines, dummy, dummy = extract_references_from_fulltext(docbody)
else:
refs_info = get_reference_section_beginning(docbody)
if not refs_info:
refs_info, dummy = find_numeration_in_body(docbody)
refs_info['start_line'] = 0
refs_info['end_line'] = len(docbody) - 1,
reflines = rebuild_reference_lines(
docbody, refs_info['marker_pattern'])
parsed_refs, stats = parse_references(
reflines,
recid=recid,
reference_format=reference_format,
linker_callback=linker_callback,
override_kbs_files=override_kbs_files,
)
return parsed_refs | Extract references from a raw string.
The first parameter is the path to the file.
It returns a tuple (references, stats).
If the string does not only contain references, improve accuracy by
specifing ``is_only_references=False``.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_string(path, reference_format="{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_string(path, override_kbs_files={'journals': 'my/path/to.kb'}) |
def markers(self, values):
if not isinstance(values, list):
raise TypeError("Markers must be a list of objects")
self.options["markers"] = values | Set the markers.
Args:
values (list): list of marker objects.
Raises:
ValueError: Markers must be a list of objects. |
def getOPOrUserServices(openid_services):
op_services = arrangeByType(openid_services, [OPENID_IDP_2_0_TYPE])
openid_services = arrangeByType(openid_services,
OpenIDServiceEndpoint.openid_type_uris)
return op_services or openid_services | Extract OP Identifier services. If none found, return the
rest, sorted with most preferred first according to
OpenIDServiceEndpoint.openid_type_uris.
openid_services is a list of OpenIDServiceEndpoint objects.
Returns a list of OpenIDServiceEndpoint objects. |
def _filter_sources(self, sources):
filtered, hosts = [], []
for source in sources:
if 'error' in source:
continue
filtered.append(source)
hosts.append(source['host_name'])
return sorted(filtered, key=lambda s:
self._hosts_by_success(hosts).index(s['host_name'])) | Remove sources with errors and return ordered by host success.
:param sources: List of potential sources to connect to.
:type sources: list
:returns: Sorted list of potential sources without errors.
:rtype: list |
def verify_month(self, now):
return self.month == "*" or str(now.month) in self.month.split(" ") | Verify the month |
def _peek(tokens, n=0):
return tokens.peek(n=n, skip=_is_comment, drop=True) | peek and drop comments |
def __set_name(self, value):
if not value or not len(value):
raise ValueError("Invalid name.")
self.__name = value | Sets the name of the treatment.
@param value:str |
def setbpf(self, bpf):
self._bpf = min(bpf, self.BPF)
self._rng_n = int((self._bpf + self.RNG_RANGE_BITS - 1) / self.RNG_RANGE_BITS) | Set number of bits per float output |
def OpenFileObject(cls, path_spec_object, resolver_context=None):
if not isinstance(path_spec_object, path_spec.PathSpec):
raise TypeError('Unsupported path specification type.')
if resolver_context is None:
resolver_context = cls._resolver_context
if path_spec_object.type_indicator == definitions.TYPE_INDICATOR_MOUNT:
if path_spec_object.HasParent():
raise errors.PathSpecError(
'Unsupported mount path specification with parent.')
mount_point = getattr(path_spec_object, 'identifier', None)
if not mount_point:
raise errors.PathSpecError(
'Unsupported path specification without mount point identifier.')
path_spec_object = mount_manager.MountPointManager.GetMountPoint(
mount_point)
if not path_spec_object:
raise errors.MountPointError(
'No such mount point: {0:s}'.format(mount_point))
file_object = resolver_context.GetFileObject(path_spec_object)
if not file_object:
resolver_helper = cls._GetResolverHelper(path_spec_object.type_indicator)
file_object = resolver_helper.NewFileObject(resolver_context)
file_object.open(path_spec=path_spec_object)
return file_object | Opens a file-like object defined by path specification.
Args:
path_spec_object (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built in context which is not multi process safe.
Returns:
FileIO: file-like object or None if the path specification could not
be resolved.
Raises:
PathSpecError: if the path specification is incorrect.
TypeError: if the path specification type is unsupported. |
def comment_set(self):
ct = ContentType.objects.get_for_model(self.__class__)
qs = Comment.objects.filter(
content_type=ct,
object_pk=self.pk)
qs = qs.exclude(is_removed=True)
qs = qs.order_by('-submit_date')
return qs | Get the comments that have been submitted for the chat |
def mosaic_info(name, pretty):
cl = clientv1()
echo_json_response(call_and_wrap(cl.get_mosaic_by_name, name), pretty) | Get information for a specific mosaic |
def get_tags_of_recurring_per_page(self, recurring_id, per_page=1000, page=1):
return self._get_resource_per_page(
resource=RECURRING_TAGS,
per_page=per_page,
page=page,
params={'recurring_id': recurring_id},
) | Get tags of recurring per page
:param recurring_id: the recurring id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list |
def clean_already_reported(self, comments, file_name, position,
message):
for comment in comments:
if ((comment['path'] == file_name and
comment['position'] == position and
comment['user']['login'] == self.requester.username)):
return [m for m in message if m not in comment['body']]
return message | message is potentially a list of messages to post. This is later
converted into a string. |
def process_queue(queue=None, **kwargs):
while True:
item = queue.get()
if item is None:
queue.task_done()
logger.info(f"{queue}: exiting process queue.")
break
filename = os.path.basename(item)
try:
queue.next_task(item, **kwargs)
except Exception as e:
queue.task_done()
logger.warn(f"{queue}: item={filename}. {e}\n")
logger.exception(e)
sys.stdout.write(
style.ERROR(
f"{queue}. item={filename}. {e}. Exception has been logged.\n"
)
)
sys.stdout.flush()
break
else:
logger.info(f"{queue}: Successfully processed {filename}.\n")
queue.task_done() | Loops and waits on queue calling queue's `next_task` method.
If an exception occurs, log the error, log the exception,
and break. |
def set(self, key, value):
changed = super().set(key=key, value=value)
if not changed:
return False
self._log.info('Saving configuration to "%s"...', self._filename)
with open(self._filename, 'w') as stream:
stream.write(self.content)
self._log.info('Saved configuration to "%s".', self._filename)
return True | Updates the value of the given key in the file.
Args:
key (str): Key of the property to update.
value (str): New value of the property.
Return:
bool: Indicates whether or not a change was made. |
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if number == 0:
return 0
if number < MIN_WEI or number > MAX_WEI:
raise ValueError("value must be between 1 and 2**256 - 1")
unit_value = units[unit.lower()]
with localcontext() as ctx:
ctx.prec = 999
d_number = decimal.Decimal(value=number, context=ctx)
result_value = d_number / unit_value
return result_value | Takes a number of wei and converts it to any other ether unit. |
def get_anki_phrases_english(limit=None):
texts = set()
for lang in ANKI_LANGUAGES:
df = get_data(lang)
phrases = df.eng.str.strip().values
texts = texts.union(set(phrases))
if limit and len(texts) >= limit:
break
return sorted(texts) | Return all the English phrases in the Anki translation flashcards
>>> len(get_anki_phrases_english(limit=100)) > 700
True |
def get_ssl(self, host_and_port=None):
if not host_and_port:
host_and_port = self.current_host_and_port
return self.__ssl_params.get(host_and_port) | Get SSL params for the given host.
:param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port |
def search(self):
for cb in SearchUrl.search_callbacks:
try:
v = cb(self)
if v is not None:
return v
except Exception as e:
raise | Search for a url by returning the value from the first callback that
returns a non-None value |
def wait_for_signal(self, timeout=None):
timeout_ms = int(timeout * 1000) if timeout else win32event.INFINITE
win32event.WaitForSingleObject(self.signal_event, timeout_ms) | wait for the signal; return after the signal has occurred or the
timeout in seconds elapses. |
def publish(self, artifact):
self.env.add_artifact(artifact)
self._log(logging.DEBUG, "Published {} to domain.".format(artifact)) | Publish artifact to agent's environment.
:param artifact: artifact to be published
:type artifact: :py:class:`~creamas.core.artifact.Artifact` |
def entity_to_protobuf(entity):
entity_pb = entity_pb2.Entity()
if entity.key is not None:
key_pb = entity.key.to_protobuf()
entity_pb.key.CopyFrom(key_pb)
for name, value in entity.items():
value_is_list = isinstance(value, list)
value_pb = _new_value_pb(entity_pb, name)
_set_protobuf_value(value_pb, value)
if name in entity.exclude_from_indexes:
if not value_is_list:
value_pb.exclude_from_indexes = True
for sub_value in value_pb.array_value.values:
sub_value.exclude_from_indexes = True
_set_pb_meaning_from_entity(
entity, name, value, value_pb, is_list=value_is_list
)
return entity_pb | Converts an entity into a protobuf.
:type entity: :class:`google.cloud.datastore.entity.Entity`
:param entity: The entity to be turned into a protobuf.
:rtype: :class:`.entity_pb2.Entity`
:returns: The protobuf representing the entity. |
def extract_followups(task):
callbacks = task.request.callbacks
errbacks = task.request.errbacks
task.request.callbacks = None
return {'link': callbacks, 'link_error': errbacks} | Retrieve callbacks and errbacks from provided task instance, disables
tasks callbacks. |
def to_ufo_family_user_data(self, ufo):
if not self.use_designspace:
ufo.lib[FONT_USER_DATA_KEY] = dict(self.font.userData) | Set family-wide user data as Glyphs does. |
def read_electrodes(self, electrodes):
for nr, electrode in enumerate(electrodes):
index = self.get_point_id(
electrode, self.char_lengths['electrode'])
self.Electrodes.append(index) | Read in electrodes, check if points already exist |
def read_json_flag(fobj):
if isinstance(fobj, string_types):
with open(fobj, 'r') as fobj2:
return read_json_flag(fobj2)
txt = fobj.read()
if isinstance(txt, bytes):
txt = txt.decode('utf-8')
data = json.loads(txt)
name = '{ifo}:{name}:{version}'.format(**data)
out = DataQualityFlag(name, active=data['active'],
known=data['known'])
try:
out.description = data['metadata'].get('flag_description', None)
except KeyError:
pass
else:
out.isgood = not data['metadata'].get(
'active_indicates_ifo_badness', False)
return out | Read a `DataQualityFlag` from a segments-web.ligo.org JSON file |
def get_lyrics_letssingit(song_name):
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics | Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement |
def _construct_request(self):
if self.parsed_endpoint.scheme == 'https':
conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)
else:
conn = httplib.HTTPConnection(self.parsed_endpoint.netloc)
head = {
"Accept": "application/json",
"User-Agent": USER_AGENT,
API_TOKEN_HEADER_NAME: self.api_token,
}
if self.api_version in ['0.1', '0.01a']:
head[API_VERSION_HEADER_NAME] = self.api_version
return conn, head | Utility for constructing the request header and connection |
def create_map(self, pix):
k0 = self._m0.shift_to_coords(pix)
k1 = self._m1.shift_to_coords(pix)
k0[np.isfinite(k1)] = k1[np.isfinite(k1)]
k0[~np.isfinite(k0)] = 0
return k0 | Create a new map with reference pixel coordinates shifted
to the pixel coordinates ``pix``.
Parameters
----------
pix : `~numpy.ndarray`
Reference pixel of new map.
Returns
-------
out_map : `~numpy.ndarray`
The shifted map. |
def topics(self, exclude_internal_topics=True):
topics = set(self._partitions.keys())
if exclude_internal_topics:
return topics - self.internal_topics
else:
return topics | Get set of known topics.
Arguments:
exclude_internal_topics (bool): Whether records from internal topics
(such as offsets) should be exposed to the consumer. If set to
True the only way to receive records from an internal topic is
subscribing to it. Default True
Returns:
set: {topic (str), ...} |
def show_popup(self, *args, **kwargs):
self.mw = JB_MainWindow(parent=self, flags=QtCore.Qt.Dialog)
self.mw.setWindowTitle(self.popuptitle)
self.mw.setWindowModality(QtCore.Qt.ApplicationModal)
w = QtGui.QWidget()
self.mw.setCentralWidget(w)
vbox = QtGui.QVBoxLayout(w)
pte = QtGui.QPlainTextEdit()
pte.setPlainText(self.get_popup_text())
vbox.addWidget(pte)
d = self.cursor().pos() - self.mw.mapToGlobal(self.mw.pos())
self.mw.move(d)
self.mw.show() | Show a popup with a textedit
:returns: None
:rtype: None
:raises: None |
def _get_op_name(op, special):
opname = op.__name__.strip('_')
if special:
opname = '__{opname}__'.format(opname=opname)
return opname | Find the name to attach to this method according to conventions
for special and non-special methods.
Parameters
----------
op : binary operator
special : bool
Returns
-------
op_name : str |
def get_word(byte_iterator):
byte_values = list(itertools.islice(byte_iterator, 2))
try:
word = (byte_values[0] << 8) | byte_values[1]
except TypeError, err:
raise TypeError("Can't build word from %s: %s" % (repr(byte_values), err))
return word | return a uint16 value
>>> g=iter([0x1e, 0x12])
>>> v=get_word(g)
>>> v
7698
>>> hex(v)
'0x1e12' |
def _openResources(self):
arr = self._fun()
check_is_an_array(arr)
self._array = arr | Evaluates the function to result an array |
def get_setting_with_envfallback(setting, default=None, typecast=None):
try:
from django.conf import settings
except ImportError:
return default
else:
fallback = getattr(settings, setting, default)
value = os.environ.get(setting, fallback)
if typecast:
value = typecast(value)
return value | Get the given setting and fall back to the default of not found in
``django.conf.settings`` or ``os.environ``.
:param settings: The setting as a string.
:param default: The fallback if ``setting`` is not found.
:param typecast:
A function that converts the given value from string to another type.
E.g.: Use ``typecast=int`` to convert the value to int before returning. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.