content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def delete_instance_template(template_name: str):
"""Returns a ProcessResult from running the command to delete the
measure_worker template for this |experiment|."""
command = [
'gcloud', 'compute', 'instance-templates', 'delete', template_name
]
return new_process.execute(command) | ebf0936b8a17abcb9615941efc8dad1c367537c3 | 3,626,770 |
def create(body):
"""
Create a new grid.
:param (dict) body: A mapping of body param names to values.
:returns: (requests.Response) Returns response directly from requests.
"""
url = build_url(RESOURCE)
return request('post', url, json=body) | ab6e0c50e9c7fa4a76eed0fc2e657d01af479499 | 3,626,771 |
def arr(shape=None, element_type=float,
interval=None,
data=None, copy=True,
file_=None,
order='C'):
"""
Compact and flexible interface for creating numpy arrays,
including several consistency and error checks.
- *shape*: length of each dimension, tuple or int
- *d... | fa9cc6ceb6761cf00236406e5c23bb4ab38e6b6c | 3,626,772 |
def evaluate_template(template: str, prefix="$", sufix="$"):
"""Evaluate a string template; replace all queries by their values
Queries in the template are delimited by prefix and sufix.
Queries should evaluate to strings and should not cause errors.
"""
return Context().evaluate_template(template, ... | 03fc5bab0e4a76911743595f156aac26356b7390 | 3,626,773 |
def rsp_fixpeaks(peaks, troughs=None):
"""Correct RSP peaks.
Low-level function used by `rsp_peaks()` to correct the peaks found by `rsp_findpeaks()`.
Doesn't do anything for now for RSP. See `rsp_peaks()` for details.
Parameters
----------
peaks : list or array or DataFrame or Series or dict
... | 214efc68a59646508cddd0471a45b8b6dcfa1b55 | 3,626,774 |
def get_dfu_devices(*args, **kwargs):
"""Returns a list of USB device which are currently in DFU mode.
Additional filters (like idProduct and idVendor) can be passed in to
refine the search.
"""
# convert to list for compatibility with newer pyusb
return list(usb.core.find(*args, find_all=True,
... | 15b7d6fd53547c19ebfca115f2b8e85acc106b90 | 3,626,775 |
from datetime import datetime
def emailWeeklyOrders():
"""
Emails all the current admins an email containing every users current order.
Returns total emails sent and the email for every admin.
"""
all_orders = get_all_users_orders()
user_login_url = get_login_url()
current_date = date... | 231041367363fe7d9d78763f2a08fb51f66f7bc0 | 3,626,776 |
def content_type(suffix: str) -> str:
"""
Gets the Content-Type header for a type of file.
Arguments:
suffix: Filename suffix.
"""
suffix = normalize_suffix(suffix)
return _content_types.get(suffix, _default_content_type) | 863289460a3e1d6e21c19bb91e391eb21ab9dc36 | 3,626,777 |
def compare_pair(p1, p2, cp1, cp2):
"""Given comparison functions for the first and second part of
the pair, compare the two pairs using the two functions under
lexicographic order.
"""
res1 = cp1(p1[0], p2[0])
if res1 != EQUAL:
return res1
else:
return cp2(p1[1], p2[1]) | efac0863ab8728fb8f2e4dc531bbfd9dfc9b56b1 | 3,626,779 |
import torch
import math
def train_epoch(net, train_iter, loss, updater, device, use_random_iter):
"""Train a net within one epoch (defined in Chapter 8)."""
state, timer = None, d2l.Timer()
metric = d2l.Accumulator(2) # Sum of training loss, no. of tokens
for X, Y in train_iter:
if state is ... | 1d7c9269bbeed0da057891e5347d20c10d6150a8 | 3,626,781 |
import struct
def read_tcp_pac(link_packet, byteorder, link_layer_parser, seconds, suseconds):
"""read tcp data.http only build on tcp, so we do not need to support other protocols."""
state, source, dest, tcp_packet = read_ip_pac(link_packet, byteorder, link_layer_parser)
if state == 0:
return 0,... | 98a263f0a203ec9f9b1c5909278069a3f4cd039c | 3,626,782 |
def basic_metrics(predict, label):
"""
Methods that returns:
true positive
true negative
false positive
false negative
Args:
predict: prediction
label: labels
Returns:
true_pos, true_neg, false_pos, false_neg, sum
"""
true_pos = int(sum(n... | 9d83c98f82b755197f269c889063f60233a76d76 | 3,626,783 |
import json
def hail_metadata(t_path):
"""Create a metadata plot for a Hail Table or MatrixTable.
Parameters
----------
t_path : str
Path to the Hail Table or MatrixTable files.
Returns
-------
:class:`bokeh.plotting.figure.Figure` or :class:`bokeh.models.widgets.panels.Tabs` or ... | 83409fcc121e3c1eaebb64b6a338cfad90018b73 | 3,626,784 |
import uuid
def persist_state(request):
"""Persist arbitrary string in cache.
It will be matched when the user returns from the OAuth server login
page.
"""
state = uuid.uuid4().hex
redirect_url = request.validated['querystring']['redirect']
expiration = float(facebook_conf(request, 'cache... | 3c2e8c0dd0c3e91544861097249e61d9bf55185c | 3,626,785 |
def refactor_lambda(astref, srcpos, argsig, body, cntrl, ecntrl):
"""Update lambda so it captures free variables"""
clist = [] # Definition argument signature
newlist = [] # New list is new item list
_find_refs(argsig, srcpos, body, cntrl, ecntrl, clist, newlist)
if clist:
# Get the ... | 2b1b96ead4fd5e87dc8eaa14eb0bfae9a2d54023 | 3,626,786 |
from typing import Callable
from typing import Type
def register_model_wrapper(name: str) -> Callable[[Type], Type]:
"""
Register a model wrapper so that it is available via the CLI.
>>> @register_model_wrapper("my_model_name")
... class MyModelWrapper:
... pass
"""
def _inner(cls_):... | 966187f08c93324a11b8f6fefffe5cdfb2e921ed | 3,626,787 |
def check_non_empty(object_name: str, engine: sqlalchemy.engine.base.Engine):
"""Check if a Snowflake object has a COUNT() > 0."""
with engine.connect() as con:
count = con.execute(f"SELECT COUNT(*) FROM {object_name}").fetchone()[0]
return count > 0 | 8bb73247f54a117b48f976bec5a89064d3707ba1 | 3,626,788 |
def importManeshFiles():
""" import data from Manesh text files, convert to dataframe, concatenate and filter """
# the raw BP data from Manesh came in 2 files, one for my data and one for Adam Guss's data
rawBPdan = pd.read_table(r"October2016\DanOlson_SFRE_V5_Test3\Strain_Sample_BrkPnts.Test3.txt.Tabbed")... | f4cfa757945388440d9de206dfcee29c78fcfb21 | 3,626,789 |
def construct_select_bijlagen_query(bericht_uri):
"""
Construct a SPARQL query for retrieving all bijlages for a given bericht.
:param bericht_uri: URI of the bericht for which we want to retrieve bijlagen.
:returns: string containing SPARQL query
"""
q = """
PREFIX schema: <http://sche... | 56e9868ddc38c703ac383508cce4e446f0f566a4 | 3,626,790 |
def tologodds(df, y):
"""
Converts column `y` of dataframe `df` to its trimmed logodds.
Name is preserved.
"""
return df.assign(**{y: df[y].pipe(lambda x: trimmed(logodds, x))}) | 294e81a147b0023fedf8e79a741723bc88b02f51 | 3,626,791 |
from typing import List
from typing import Dict
def user_demand_tmp(user_demand: UserDemand) -> List[Dict]:
"""
Log global user demand.
:param scheduler: the scheduler
:return: list of records for logging
"""
result = [{"value": user_demand.value}]
return result | e1be835f330f0744351fa4a9afcdba1c013285b8 | 3,626,792 |
def process_css(css_source, tabid, base_uri):
"""
Wraps urls in css source.
>>> url = 'http://blue360media.com/style.css'
>>> process_css('@import "{}"'.format(url), 0, url) # doctest: +ELLIPSIS
'@import "/proxy?..."'
"""
def _absolutize_css_import(match):
return '@import "{}"'.form... | 2b8e173f36c26c4cba908fa39f71b9407c5006ba | 3,626,793 |
import requests
def get_Meraki_Organization(MERAKI_API_KEY):
"""
Get the Meraki Organizations that the API KEY has access to.
:param MERAKI_API_KEY:
:return:
"""
url = '{}/organizations'.format(BASE_URL)
hdrs = {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Cisco-Meraki-API-Key... | d66905852ba6b355686588477eb13fe13401a4a3 | 3,626,794 |
def check_convergence(x):
""" Check for convergence of the sampler
"""
return False | 989d94991eeecd414c3f6ff85b2d2bc2801d5cbc | 3,626,795 |
from typing import List
import requests
def get_repo_names(url: str = "users/dyvenia/repos") -> List[str]:
"""
Get public repositories names from Dyvenia.
Args:
url (str, optional): API url. Defaults to "users/dyvenia/repos".
Returns:
List[str]: List of repository names
"""
r... | 40c5d1dde34c26553493f15445e5a5a7e8021838 | 3,626,796 |
from typing import Iterable
from re import T
from re import U
from typing import Optional
from typing import Callable
from typing import Iterator
from typing import List
def split(
iterable: Iterable[T],
edges: Iterable[U],
cmp: Optional[Callable[[T, U], bool]] = None,
) -> Iterator[List[T]]:
"""Yield... | 6fe30a650bf4167e21021953490429b77533979a | 3,626,797 |
def where_op(condition, x, y):
"""Return a tensor of elements selected from either :attr:`x` or :attr:`y`, depending on :attr:`condition`.
If the element in condition is larger than 0,
it will take the `x` element, else it will take the `y` element
.. note::
The tensors :attr:`condition`, :at... | c4a34284c8105b8b0319f3e33db9d9ea0d74b0d2 | 3,626,800 |
def get_out_dir(key: str) -> str:
"""
Return the output directory
:param key: output product
"""
return OTD[key] | e510603d93cb72d916c3afab8aeb36756a563326 | 3,626,801 |
def jet_fire_api521(Tvessel):
"""
Incident heat flux of 100 kW/m2
"""
alpha = 0.75
e_flame = 0.33
e_surface = 0.75
h = 40
Tflame = 900 + 273.15
Tradiative = 1100 + 273.15
return stefan_boltzmann(alpha, e_flame, e_surface, h, Tflame, Tradiative, Tvessel) | e7d95073f9e899b8f48e5fc6fcd9505e622dea98 | 3,626,802 |
def ewma(values, window):
"""
Numpy-based implementation of EMA
"""
weights = np.exp(np.linspace(-1., 0., window))
weights /= weights.sum()
ema = np.convolve(weights, values)[window-1:-window+1]
return ema | a544b9a37bf227dcd12246d5ebd83d4788b217c9 | 3,626,803 |
import torch
def prepare_loss_weights(
labels,
pos_cls_weight=1.0,
neg_cls_weight=1.0,
loss_norm_type=LossNormType.NormByNumPositives,
dtype=torch.float32,
):
"""get cls_weights and reg_weights from labels.
"""
cared = labels >= 0
# cared: [N, num_anchors]
positives = labels > ... | 0f3a8bd3d9149c6264aa73f5a4daa0291f56d2e8 | 3,626,804 |
def add_to_leftmost(branch, val):
"""adds value to the leftmost part of the branch and returns the modified branch and 0.
OR returns unchanged change and val if the val cannot be added"""
if val == 0:
return branch, val
if type(branch) is int:
return branch + val, 0
# add to children... | 1c2c3bdccfcb6f4966b9bf9228f092ee17ca49f9 | 3,626,806 |
def normalize_list_of_dict_into_dict(alist):
"""
Info is generated as a list of dict
objects with a single key.
@alist - the list in question.
@return - normalized dict with multiple keys
"""
result = {}
for element in alist:
for key in element.keys():
... | 8de00b0923d07b99085ca3b4d694960aae9fc7f5 | 3,626,807 |
import hashlib
def hashhex(s):
"""Returns a heximal formated SHA1 hash of the input string."""
h = hashlib.sha1()
h.update(s)
return h.hexdigest() | 0d2b0dd9c54b71f3668b971fb81f9d78223acbb2 | 3,626,808 |
def planets(id='', name=''):
"""
Return a planet.
Like: Hoth, Naboo, etc.
"""
response = Render.show(id, name, 'planets')
return response | 1e1944d58b50cf3fed7efc6fe23b888837689a57 | 3,626,812 |
def literal(string):
"""
If `string` is a valid literal in NTriples syntax, return its value, lang tag and type.
Use `None` if there is no language tag or no datatype.
If `string` is not a valid literal return `None`.
"""
match = literal.pattern.match(string)
if not match:
return Non... | a0d805d7b3365366b85c0ce576f75a69680251be | 3,626,813 |
import logging
def make_error_logger(name, level, filename):
"""
Création d'un Logger d'erreur
:param name: nom du logger
:param level: niveau de logging
:param filename: nom du fichier d'erreur
:return: logger
"""
formatter = logging.Formatter("%(asctime)s %(levelname)s - %(messa... | 0d78faa4657af348c06755298c2e1d3f717cd092 | 3,626,814 |
def correlate(a, b, shift, demean=True, normalize=True, domain='freq'):
"""
Cross-correlation of signals a and b with specified maximal shift.
:type a: :class:`~numpy.ndarray`, :class:`~obspy.core.trace.Trace`
:param a: first signal
:type b: :class:`~numpy.ndarray`, :class:`~obspy.core.trace.Trace`... | ff0a4adcde2f62f7de94c31702dd2605ae8f390c | 3,626,815 |
def get_user_idle_time():
"""
Return the amount of time (in seconds) that the user is said to be idle.
This is normally obtained from a lack of keyboard and/or mouse input.
"""
if system == 'Windows':
return get_user_idle_time_windows()
elif system == 'Darwin':
return get_user_idle_time_mac()
raise NotImplem... | bcdb1a9710721b94f2c6c490a8ac9d453cda412a | 3,626,816 |
from typing import Dict
from typing import Any
from typing import Iterable
from typing import Optional
from typing import Tuple
def kwargs_from_config(
config: Dict[str, Any],
required_keys: Iterable[str],
optional_keys: Iterable[str],
renames: Optional[Iterable[Tuple[str, str]]] = None,
) -> Dict[str... | b3acef60b87dc8bb4c00157c169d1968c8751100 | 3,626,817 |
def as_array(a, dtype=DEFAULT_FLOAT_DTYPE):
"""
Converts given :math:`a` variable to *ndarray* with given type.
Parameters
----------
a : object
Variable to convert.
dtype : object
Type to use for conversion.
Returns
-------
ndarray
:math:`a` variable conver... | 5efde6e83812dec9ad16283cf13b4d3d07ba5cd8 | 3,626,818 |
def round_filters(filters, global_params):
"""Round number of filters based on depth multiplier."""
multiplier = global_params.width_coefficient
divisor = global_params.depth_divisor
min_depth = global_params.min_depth
if not multiplier:
return filters
filters *= multiplier
min_dept... | 057d209906cde8287051ea48cf3d97af76e66cf2 | 3,626,819 |
from typing import List
def equal_opportunity(confusion_matrix_list: List[np.ndarray],
tolerance: float = 0.2,
label_index: int = 0) -> np.ndarray:
"""
Checks for equal opportunity between all of the sub-populations.
This function checks if **true positive rate... | f861293ece13ea5dc14c6397fbf99a991bf0f672 | 3,626,820 |
def determine_qc_protocol(project):
"""
Determine the QC protocol for a project
Arguments:
project (AnalysisProject): project instance
Return:
String: QC protocol for the project
"""
# Standard protocols
if project.info.paired_end:
protocol = "standardPE"
else:
... | 6862ab84450d4d4d0ca74ee178b90f5eacb303fb | 3,626,821 |
def entitydata_list_url_query(viewname, kwargs, query_params, more_params):
"""
Helper function for generatinglist URLs
"""
list_url=reverse(viewname, kwargs=kwargs)
return uri_with_params(list_url, query_params, more_params) | 5264a2f45befc9662f22a1febc5451d35881c984 | 3,626,822 |
def _adaptive_order_weno3_robust(q,
i,
j,
recons,
keep_positive,
eps=1.0e-17,
c1=1.0,
c2=... | dc772944d6eb13a02752d995f738b385a01fd7a0 | 3,626,823 |
import torch
def patch_and_fit_physio(time_series, replicates, patch=3, mask=None,
mode='gn', verbose=0):
"""Extract patches from an fMRI time + replicate series and fit parameters.
Parameters
----------
time_series : (replicates, *input_shape) tensor_like
fMRI time s... | f22083e42927d0661a315a0825b1b4344be75e53 | 3,626,824 |
def verify_file_exists(file_name, file_location):
"""
Function to verify if a file exists
:type file_name: String
:param file_name: The name of file to check
:type file_location: String
:param file_location: The location of the file, derive from the os module
:rtype: Boolean
:return: r... | 8ac4869f3f758d9342f9047a6212851f7f463f35 | 3,626,825 |
import math
def plot_cdfs(x, y, ccdf=False):
"""plot cumulative density functions for each column in x, based on
the classification specified in y.
Parameters
----------
x : DataFrame
the experiments to use in the cdfs
y : ndaray
the categorization for the data
ccdf : boo... | 3b98d7b3d474a374d17438b5263af53c20b24b83 | 3,626,826 |
def make_shell_context():
"""Pre-populate the shell environment when running run.py shell."""
return dict(app=keeper_app, db=db, models=models) | 9344b3d30f36c0c1a5b10847d93a92c10e58872c | 3,626,827 |
import contextlib
def _MaybeClosing(fileobj):
"""Returns closing context manager, if given fileobj is not None.
If the given fileobj is none, return nullcontext.
"""
return (contextlib.closing if fileobj else NullContext)(fileobj) | 05db3f9168d69c94513c95f0da396500319e079e | 3,626,828 |
def get_project_page(pid, cache_directory=settings.CACHE_DIRECTORY):
"""Get a project page rendered in HTML given a project ID.
Args:
pid (int): project ID.
cache_directory (str): the directory where cached projects are stored.
Returns:
A string containing the HTML for ... | bff55a1c6e51742cca264199b4ac669fe4b8b855 | 3,626,829 |
def is_slot_bound(module, device, slot):
"""Checks whether a specific slot in a given device is bound to clevis.
Return: <boolean> <error>"""
_unused, err = get_jwe(module, device, slot)
if err:
return False, err
return True, None | c103ae94ef86bad7eb3c3e33818faf20003e18b4 | 3,626,830 |
def to_matplotlib(img):
"""Returns a view of the image from Bob format to matplotlib format.
This function works with images, batches of images, videos, and higher
dimensional arrays that contain images.
Parameters
----------
img : numpy.ndarray
A N dimensional array containing an image... | f769af6d407d16543dc9ec98d8cc35338db47231 | 3,626,831 |
def energy_distance(x, y, **kwargs):
"""
energy_distance(x, y, *, exponent=1)
Computes the estimator for the energy distance of the
random vectors corresponding to :math:`x` and :math:`y`.
Both random vectors must have the same number of components.
Parameters
----------
x: array_like
... | a36d4277ed5cd9da049f129a2d8fa2b50a062ed3 | 3,626,832 |
def train_step(net, optim, batch):
"""
one training step
"""
(loss, net), grads = pax.value_and_grad(loss_fn, has_aux=True)(net, batch)
net, optim = opax.apply_gradients(net, optim, grads)
net = net.replace(rnn=net.gru_pruner(net.rnn))
net = net.replace(o1=net.o1_pruner(net.o1))
net = ne... | 3f3e9fa1f8487bafd0e0b70a673ef3af989e3dfc | 3,626,834 |
def insert_dim(arg, pos=-1):
"""insert 1 fake dimension inside the arg before pos'th dimension"""
shape = [i for i in arg.shape]
shape.insert(pos, 1)
return arg.reshape(shape) | 921cd27894df9910dbc12b31db6eb1f73d47f180 | 3,626,835 |
def encode_captions(captions):
"""
Convert all captions' words into indices.
Input:
- captions: dictionary containing image names and list of corresponding captions
Returns:
- word_to_idx: dictionary of indices for all words
- idx_to_word: list containing all words
- vocab_size... | 2ba216c844723b0925b46d0db7bc8afd6ce0f5b4 | 3,626,836 |
import logging
def post_dataset(conn, dataset_name, project_id=None, description=None,
across_groups=True):
"""Create a new dataset.
Parameters
----------
conn : ``omero.gateway.BlitzGateway`` object
OMERO connection.
dataset_name : str
Name of the Dataset being c... | cd0e57d8184683c403002de085fa5122c1e3458d | 3,626,837 |
def load_stop_words(stop_word_file):
"""
Utility function to load stop words from a file and return as a list of words
@param stop_word_file Path and file name of a file containing stop words.
@return list A list of stop words.
"""
stop_words = []
for line in open(stop_word_file):
if... | 8127aeec8db8f7bc87130ea0d1e5faa4998ac86f | 3,626,838 |
def run_gcloud_command(cmd, project_id):
"""Execute a gcloud command and return the output.
Args:
cmd (list): a list of strings representing the gcloud command to run
project_id (string): append `--project {project_id}` to the command. Most
commands should specify the project ID, for those that don't... | 324345a3fdf687c3d36711c918060715fedfa79a | 3,626,839 |
def convert_gmx_flow_1_to_2(flow: GmxFlow, width: float) -> GmxFlow:
"""Convert flow data from 'GMX_FLOW_1' to 'GMX_FLOW_2'.
This changes the field 'M' to represent the mass density instead of
the total mass in the bin. Thus we also require the width of the system,
in order to calculate the bin volume.... | d1e005bf8adc73c27e4454730a744fb6b464100b | 3,626,840 |
def NullFlagHandler(feature):
""" This handler always returns False """
return False | 7d37ecc8518144b27b43580b7273adf5f68dfdfb | 3,626,841 |
def add_image(axes, path):
"""Add the image given by ``path`` to the plot ``axes``.
:param axes: represents an individual plot
:param path: path to the image
:type axes: matplotlib.pyplot.Axes
:type path: str
:return: mpimg.AxesImage
"""
try:
img = Image.open(path)
retur... | fa574ede75a5f2389380e906090e2d91c92944e9 | 3,626,842 |
from datetime import datetime
def abandonAffaire_reopenParentAffaire_view(request):
"""
Abandon child_affaire, reopen parent child_affaire and reattribute numbers to parent child_affaire.
"""
settings = request.registry.settings
etape_abandon_id = settings['affaire_etape_abandon_id']
etape_re... | c2993de78590f708fc4d7e8c0ed08008a21103b6 | 3,626,843 |
import copy
def find_paths(orbital_graph, starting_node, ending_node, visited_nodes=None):
"""Recursively find all the paths from starting_node to ending_node in the graph
Paths are returned as a list of paths, where paths are a list of nodes.
An empty list means that no valid path exists.
"""
pat... | 55a47542c3d70bbc1f5c722c1e87908e10b3d0e5 | 3,626,845 |
def rp_from_filename(filename, split_char=ELT_SPLIT,
rp_regex=REGEX_RP):
"""Gets the Rp (proton radius?) label from the file name, returns None if
not found.
:param filename: the name of the file to parse
:param split_char: the character which separates filename elements
:param ... | e5cae3428e6a7a30cceab779845b127df52c2ad1 | 3,626,846 |
def check_duplication(request):
"""API check_duplication"""
check_type = request.POST.get('check_type')
name = request.POST.get('username')
if check_type == 'id':
min_limit = settings.ID_MIN_LENGTH
max_limit = settings.ID_MAX_LENGTH
else:
min_limit = settings.NICKNAME_MIN_LE... | 2ef45506ada6b54cc86b1734a0301e6e48bb5ca6 | 3,626,847 |
def _merge_numeric_stats(
left, right,
feature_name):
"""Merge two partial numeric statistics and return the merged statistics."""
# Check if the types from the two partial statistics are not compatible.
# If so, raise an error.
if (left.type is not None and right.type is not None and
left.type !=... | 1eb4ea5a425ea70ae4e02da267d2553a8440376b | 3,626,848 |
import logging
def get_pod_names(client, namespace, name):
"""Get pod names from k8s.
"""
core_api = k8s_client.CoreV1Api(client)
resp = core_api.list_namespaced_pod(
namespace, label_selector=to_selector({TF_JOB_NAME_LABEL: name}))
logging.info("list_namespaced_pod: %s", str(resp))
pod_names = []
f... | 6228ed3a596093260c0b17a95201068b2d70c1d6 | 3,626,849 |
def calculate_drawdown(input_series: pd.Series, is_returns: bool = False) -> pd.Series:
"""Calculate the drawdown (MDD) of historical series. Note that the calculation is done
on cumulative returns (or prices). The definition of drawdown is
DD = (current value - rolling maximum) / rolling maximum
... | 95e128f00f3667e5a22bd114074525feb6063e1c | 3,626,850 |
def search_traversal(**kwargs):
"""Search Traversal in Database"""
db_inst = app.config['ARANGO_CONN']
db_inst.get_database()
graph = db_inst.get_graph(kwargs.get('graph_name'))
try:
traversal_results = graph.traverse(
start_vertex=kwargs.get('start_vertex'),
directi... | 971751adb1970a0bead9e632e00181a4bc3914a9 | 3,626,851 |
def find_matching_nodes(search_for, search_in, matches=[]):
"""
Search Vertex tree 'search_in' for the first isomorphic occurance of the
Vertex tree search_for
Return a list of [(x,y)...] for node in search_for (x) matched with
a pair (y) from search in, such as the two graphs preserve their ... | 9e6696533f7b5e313075fadade8b42fe6f09f0cf | 3,626,852 |
def getStrategicManagementBodies(project):
"""Returns the strategic management bodies for a given project."""
return getManagementBodies(project, MANAGEMENT_BODY_CATEGORY_STRATEGIC) | 526c60342f348f327436f4e1bdcb5c90c7820cbe | 3,626,853 |
def clip(x, min_value, max_value):
"""Element-wise value clipping."""
if max_value is not None and max_value < min_value:
max_value = min_value
if max_value is None:
max_value = np.inf
min_value = _to_tensor(min_value, x.dtype.base_dtype)
max_value = _to_tensor(max_value, x.dtype.bas... | 58ba70a6212b2ab3b37f37aa8a4611bab262be81 | 3,626,854 |
def SendMessage(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Se... | 9c8c9985fe80b22a94678c354774ebe0453fe860 | 3,626,856 |
def getPolicy(lunaToken, policyName, network, account_key=''):
""" Gets a specific policy on a given network in JSON format """
session.headers.update({'Luna-Token': lunaToken})
if network == 'staging':
get_policy_endpoint = "/imaging/v2/network/staging/policies/" + policyName
else:
get... | 52a9c7496813b55e74c19a084a367a5f242a379a | 3,626,857 |
import re
def clean_str(string):
# Remove punctuation
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
"""
string = re.sub(r"[^\u4e00-\u9fff]", " ", string)
string = re.sub(r"\s{2,}", "... | 025a17cfc81217b6115f049694ff205c5a5e93ab | 3,626,858 |
from typing import List
from typing import Tuple
def extract_ops(page: PageObject) -> List[Tuple]:
"""extract all operators"""
content = page.getContents()
if not isinstance(content, ContentStream):
content = ContentStream(content, page.pdf)
return list(content.operations) | 402ec35f7de36dce93ae56b13d535ea8cebc1916 | 3,626,859 |
import requests
def get_project_info(project_name, dnac_jwt_token):
"""
This function will retrieve all templates associated with the project with the name {project_name}
:param project_name: project name
:param dnac_jwt_token: DNA C token
:return: list of all templates, including names and ids
... | 61ff47100853175c76ecf05117d7016842a6745d | 3,626,860 |
import textwrap
import six
def generate(tag_cls):
"""
generate generates documentation for given wrapper tag class
:param tag_cls: wrapper_tag class
:return:
"""
doc = textwrap.dedent(tag_cls.__doc__ or '').strip()
arguments_doc = ""
for ag, arguments in six.iteritems(ArgumentsGroup... | 3b2fb93caa37552f4b4eaff1fc4a1c1d1d1412dd | 3,626,862 |
def load_data(database_filepath):
"""Load data from SQLite into memory.
"""
engine = create_engine(f'sqlite:///{database_filepath}')
df = pd.read_sql_table("Messages", engine)
X = df["message"]
Y = df.drop(["message", "id", "original", "genre"], axis=1)
return X, Y, Y.columns | e8e338d7c08113cd11f1e1efcb16f4687de354c7 | 3,626,863 |
def column_thresh(C, eps):
"""
cleans out C, removes all values below eps.
otherwise
"""
n1 = C.shape[1]
for i in range(n1):
if la.norm(C[:,i], 2) < eps: # norm here defaults to 2 norm for vector
C[:,i]=0
else:
C[:,i]=C[:,i]-eps*C[:,i]/la.norm(C[:,i],2)
... | ba53b3a728ff363a684c0974676430c3850d2c43 | 3,626,864 |
def distance_between_points(p1, p2):
""" Function that computes the euclidean distance between to points.
Returns:
float: distance value
"""
return ((p1['x']-p2['x']) * (p1['x'] - p2['x']) + (p1['y']-p2['y']) * (p1['y']-p2['y'])) ** 0.5 | b8cb563f13f64f0511525e5428d47d9228220915 | 3,626,865 |
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -- A scalar or numpy array of any size.
Return:
s -- sigmoid(z)
"""
#(≈ 1 line of code)
# s = ...
# YOUR CODE STARTS HERE
s = 1/(1+np.exp(-z))
# YOUR CODE ENDS HERE
return s | 868599c3550a0e575d9a39632e0990f3dfc2f782 | 3,626,866 |
from typing import Tuple
from typing import Dict
import copy
def _decompose_expressions(circ: Circuit) -> Tuple[Circuit, bool]:
"""Rewrite a circuit command-wise, decomposing ClassicalExpBox."""
bit_heap = BitHeap()
reg_heap = RegHeap()
# add already used heap variables to heaps
for b in circ.bits... | 8dad1b0e438930541e0604a48114b8d5628db97d | 3,626,867 |
def get_trailing_app_metrics(args):
"""
Returns trailing app_name metrics for a given time period.
Args:
args: dict The parsed args from the request
args.limit: number The max number of apps to return
args.time_range: one of "week", "month", "all_time"
Returns:
[{ name: ... | e0b6f89a83af7250baa16926fcf644ca7b5b0e51 | 3,626,868 |
def get_all_related_objects(opts):
"""
Django 1.8 changed meta api, see
https://docs.djangoproject.com/en/1.8/ref/models/meta/#migrating-old-meta-api
https://code.djangoproject.com/ticket/12663
https://github.com/django/django/pull/3848
:param opts: Options instance
:return: list of relatio... | bc3cc8ec4b83a26ff5c409eb840733ca7bdfaaea | 3,626,869 |
import fastapi
async def fetch_dialog(
customer_id: str,
dialog_id: str,
db: motor_asyncio.AsyncIOMotorClient = fastapi.Depends(mongodb.get_database),
) -> utils.OrjsonResponse:
"""
Fetch a dialog.
- **customer_id**: customer id of the dialog to return
- **dialog_id**: dialog id of the di... | 4fd8f66df8375b5620c400c88446206e5acf337b | 3,626,870 |
def _get(pseudodict, key, single=True):
"""Helper method for getting values from "multi-dict"s"""
matches = [item[1] for item in pseudodict if item[0] == key]
if single:
return matches[0]
else:
return matches | f68156535d897dd719b05d675e66cadc284ce1a3 | 3,626,871 |
from typing import Counter
def guess_domain(tree, blacklist=_DOMAIN_BLACKLIST, get_domain=get_domain):
""" Return most common domain not in a black list. """
domains = [get_domain(href) for href in tree.xpath('//*/@href')]
domains = [d for d in domains if d and d not in blacklist]
if not domains:
... | 0d0c0ab8876092e8e06783cd9b4adaf50d9996cf | 3,626,872 |
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.block_structure.models import BlockStructureModel
from openedx.core.djangoapps.content.block_structure.exceptions import BlockStructureNotFound
def get_course_last_published(course_key):
"""
We use the CourseStructure tabl... | c7a8e503553790ed05ca84a8bfa7ac6decf3bc0d | 3,626,873 |
def rgb_to_hex(rgb_triplet):
"""
Convert a 3-tuple of integers, suitable for use in an ``rgb()``
color triplet, to a normalized hexadecimal value for that color.
Examples:
>>> rgb_to_hex((255, 255, 255))
'#ffffff'
>>> rgb_to_hex((0, 0, 128))
'#000080'
"""
return '#%02x%02x%02x... | 53a21a387e19c8cf989cec868f8862bfcb2dbaed | 3,626,874 |
def dec2stringTime(decim, precision=5):
""" Convert a decimale time or coordinate to a formatted string.
Parameters
----------
decim : int, float
precision : int
Returns
-------
String formatted HH:MM:SS.SSSSS
"""
return hms2stringTime(*dec2sex(decim), precision=precision) | d7ea8334f021dc302c1291556bd5d6a8bb921b46 | 3,626,875 |
def getCartShape(dimension, communicator=None):
"""
Returns :samp:`getCartShapeForSize(dimension, communicator.Get_size())`.
:type dimension: int
:param dimension: Spatial dimension for returned cartesian layout.
:type communicator: :obj:`mpi4py.MPI.Comm`
:param communicator: If :samp:`None... | fe26d0bef1f7e244b1bcbf78cc7754b04790f121 | 3,626,876 |
def gumbel_log_survival(x):
"""Returns log P(g > x) for a standard Gumbel g.
log P(g > x) = log(1 - P(g < x)) = log(1 - exp(-exp(-x))). The implementation
is more numerically robust than a naive implementation of that formula.
Args:
x: The cutoff Gumbel value.
"""
# Adapted from
# https://gist.githu... | 416069914e011f82db4d47dd667c95b8f2539a2d | 3,626,877 |
import platform
def platform_is(requested_platform: str) -> bool:
"""
Compare requested platform with current platform.
Common platforms:
- Win / Windows
- Mac / macOS / Darwin
- Linux
- Unix (Mac, SunOS, BSD unix's)
- *nix / posix (Not Windows)
:return: True if current platform m... | 8e9ca64fc9053369da100da46083685cb6dcd47a | 3,626,878 |
def prepare_bert(content, max_len, bow_vocab_size=1000, vectorizer=None, ctx=mx.cpu()):
"""
Utility function to take text content (e.g. list of document strings), a maximum sequence
length and vocabulary size, returning a data_train object that can be used
by a SeqBowEstimator object for the call to fit... | 76f6ebc3d874668507e8e7b9326a82dbd1b01997 | 3,626,879 |
def to_homogeneous(t, is_point):
"""Makes a homogeneous space tensor given a tensor with ultimate coordinates.
Args:
t: Tensor with shape [..., K], where t is a tensor of points in
K-dimensional space.
is_point: Boolean. True for points, false for directions
Returns:
Tensor with shape [..., K+... | 484668c34b6c61e7e2479ea44c7beb4a0111676b | 3,626,881 |
import zipfile
def name_from_archive(archive_path):
""" Name From Archive """
archive = zipfile.ZipFile(archive_path, allowZip64=True)
xml_data = archive.read("manifest.xml")
elem = etree.fromstring(xml_data)
return elem.get("uuid") | 34c4e89cb75d86cd0d703a79ac0ed70b223a91c0 | 3,626,882 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.