content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getOutputDeviceNames():
"""Obtain the names of all audio output devices on the system.
@return: The names of all output devices on the system.
@rtype: [str, ...]
@note: Depending on number of devices being fetched, this may take some time (~3ms)
"""
return [name for ID, name in _getOutputDevices()] | 5,300,400 |
def did_info(Y, treated_units, control_units, T0):
""" Return Difference-in-Difference information on setup
:param Y: Matrix of outcomes
:param treated_units:
:param control_units:
:param T0:
:returns: (Synthetic controls Y, R2 for controls post-treatment)
"""
import sklearn
import p... | 5,300,401 |
def help():
"""
Shows this help information.
"""
return __salt__["sys.doc"]("minionutil") | 5,300,402 |
def _get_integration_times(start_year: int, end_year: int, time_step: int):
"""
Get a list of timesteps from start_year to end_year, spaced by time_step.
"""
n_iter = int(round((end_year - start_year) / time_step)) + 1
return np.linspace(start_year, end_year, n_iter).tolist() | 5,300,403 |
def add_layers_to_end_of_conn_mat(conn_mat, num_add_layers):
""" Adds layers with no edges and returns. """
new_num_layers = conn_mat.shape[0] + num_add_layers
conn_mat.resize((new_num_layers, new_num_layers))
return conn_mat | 5,300,404 |
def read_url(url, headers):
"""
Reads the url, processes it and returns a StringIO object to aid reading
:Parameters:
url: str
the url to request and read from
headers: dict
The right set of headers for requesting from http://nseindia.com
:returns: _io.StringIO object of the resp... | 5,300,405 |
def setup_logger():
"""Configure logging facility."""
global logger
logging.basicConfig(
level=getattr(logging, cmdline.verbose.upper()),
format='%(levelname)s:%(name)s: %(message)s',
)
logger = logging.getLogger(Script.name) | 5,300,406 |
def getVaultPath():
"""
Returns the vault location (either default or user defined)
"""
global args, vaultPathDefault
if args.vault_location:
return args.vault_location
return vaultPathDefault | 5,300,407 |
def verify(token, access_token=None):
"""Verify a cognito JWT"""
# get the key id from the header, locate it in the cognito keys
# and verify the key
header = jwt.get_unverified_header(token)
key = [k for k in JWKS if k["kid"] == header['kid']][0]
id_token = jwt.decode(token, key, audience=conf[... | 5,300,408 |
def test_calc_ticker_arg(testfiles_dir, transactions, exchange_rates_mock):
"""Testing the capgains calc command and providing a ticker"""
filepath = create_csv_file(testfiles_dir,
"calctickertest.csv",
transactions_to_list(transactions),
... | 5,300,409 |
def logerrplot(x,y,xerr=None,yerr=None,logaxes='y',boundscale=.5,**kwargs):
"""
fixes log plots to be upper bounds in the event of zero-data or errorbars
that go below zero
logaxes can be 'x','y',or,'xy'
"""
from numpy import where,array,zeros,ones,ndarray,float64
from pylab import errorbar... | 5,300,410 |
def recount_correlations_removing_station(
cd, station, remove_station, days_apart=60
):
"""
Method to recount the number of correlations of each station and each
correlation period after removing a station.
Parameters
----------
station_code: TYPE
DESCRIPTION.
Returns
----... | 5,300,411 |
def index_append(graf_list) -> None:
"""
adds indexes to the list to be searched
:param graf_list: list of tasks to add
:return: None
"""
for task in graf_list:
indexs_to_check.append(task)
return None | 5,300,412 |
def retrieve_noaa_folder_path():
"""
Helper function to retrieve the path to the NOAA folder in PydroXL
Returns
-------
str
folder path to the NOAA folder as string
"""
folder_path = path_to_NOAA()
if not os.path.exists(folder_path):
raise RuntimeError("the folder does ... | 5,300,413 |
def is_input():
"""
Utility to check if there is input available.
Returns
-------
is_input: ``bool``
``True`` if there is data in sys.stdin
"""
return select.select([sys.stdin], [], [], 1) == ([sys.stdin], [], []) | 5,300,414 |
def test_sticker_set_search(user):
"""A simple normal search should result in default values on the context object."""
context = Context("set pack test", "", user)
assert context.mode == Context.STICKER_SET_MODE
assert len(context.tags) == 1
assert context.tags[0] == "test" | 5,300,415 |
def assemble_convection_parts(domain: Domain):
"""Compute the convection inner products of trial and test function for each pair of
cell vertices.
"""
parts = []
for i in range(domain.dim):
@skfem.BilinearForm
def convection_component(u, v, w, i=i):
return grad(u)[i] * ... | 5,300,416 |
def write_config(lib, config_path, overwrite=False):
"""Write the configuration of the given :class:`tc.App` or :class:`Library` to the given path."""
if inspect.isclass(lib):
raise ValueError(f"write_app expects an instance of App, not a class: {lib}")
import json
import pathlib
config =... | 5,300,417 |
def create_app():
"""
Flask application factory.
"""
app = Flask(__name__)
app.config.update(
SECRET_KEY=config.ODP.UI.DAP.FLASK_KEY,
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_SAMESITE='Lax',
CLIENT_ID=config.ODP.UI.DAP.CLIENT_ID,
CLIENT_SECRET=config.ODP.UI.... | 5,300,418 |
def parse_genomecov(filename):
"""Parse median genome coverage from covmed output.
Assumes median coverage is the top left value in the text file."""
sample_id = get_sample(filename)
try:
mediancov = pd.read_table(filename, delim_whitespace = True, header = None).iloc[0,0]
except pd.io.c... | 5,300,419 |
def make_t0(df):
"""
Make "timepoint 0" data for each condition by copying the group of uninfected cells from the lowest
moi and timepoint, for each moi and strain,
Receive and return dataframe.
"""
# get the minimal timepoint and moi in the experiment
timepoints = sorted(df['timepoin... | 5,300,420 |
def data_zero(max_number, pieces_per_player):
"""
Force player0 to have at least half of his pieces of zero number, including double zero.
Randomly distribute pieces among the other players.
Valid pieces are all integer tuples of the form:
(i, j) 0 <= i <= j <= max_number
Each player will ha... | 5,300,421 |
def run_console():
"""Entry point for console_scripts """
if '-c' not in sys.argv[1:] and '--console' not in sys.argv[1:]:
sys.argv.append('--console')
main(sys.argv[1:]) | 5,300,422 |
def getAddressByAmp(lnglat):
"""
逆地理编码,通过高德地图api
:param lnglat:
:return:
"""
key = "efe4e9291a4a665ff691c55e3a3b871d"
url = "https://restapi.amap.com/v3/geocode/regeo?"
params = {
"key": key,
"location": lnglat
}
headers = {
"Content-type": "application/j... | 5,300,423 |
def style_loss(feats, style_layers, style_targets, style_weights):
"""
Computes the style loss at a set of layers.
Inputs:
- feats: list of the features at every layer of the current image, as produced by
the extract_features function.
- style_layers: List of layer indices into feats giving t... | 5,300,424 |
def cobbler_delete_server(serverid):
"""Delete a server from cobbler
.. :quickref: Cobbler; Delete a server by server id
**Example Request**:
.. sourcecode:: http
DELETE /api/v2/cobbler/servers/<serverid> HTTP/1.1
Content-Type: application/json
**Example Re... | 5,300,425 |
def get_download_clientpack(
api_client, name=None, fileformat=None, fileFormat=None, **kwargs
): # noqa: E501
"""get_download_clientpack # noqa: E501
Returns clientpack file. Clientpacks are files with the necessary information and credentials for an overlay client to be connected to the VNS3 topology ... | 5,300,426 |
def color_name(data, bits):
"""Color names in #RRGGBB format, given the number of bits for each component."""
ret = ["#"]
for i in range(3):
ret.append("%02X" % (data[i] << (8 - bits[i])))
return ''.join(ret) | 5,300,427 |
def is_valid_gadget(gadget, bad_chars):
"""Determine if a gadget is valid (i.e., contains no bad characters).
Args:
gadget (Gadget): A namedtuple-like object with `shellcode` and `asm`
fields.
bad_chars (bytearray): The bad characters not allowed to be present.
Returns:
... | 5,300,428 |
def month(dt):
""" For a given datetime, return the matching first-day-of-month date. """
return dt.date().replace(day=1) | 5,300,429 |
def test_ibss_open_fixed_bssid(dev):
"""IBSS open (no security) and fixed BSSID"""
ssid="ibss"
bssid="02:11:22:33:44:55"
try:
dev[0].request("AP_SCAN 2")
add_ibss(dev[0], ssid, key_mgmt="NONE", bssid=bssid, beacon_int="150")
dev[0].request("REASSOCIATE")
dev[1].request("... | 5,300,430 |
def create_buckets_ordered_randomly(
nparts_lhs: int,
nparts_rhs: int,
*,
generator: random.Random,
) -> List[Bucket]:
"""Return all buckets, randomly permuted.
Produce buckets for [0, #LHS) x [0, #RHS) and shuffle them.
"""
buckets = create_buckets_ordered_lexicographically(nparts_lhs... | 5,300,431 |
def renew_arc_proxy(password="", lifetime="8 days", proxy_file=None):
"""
Renews the arc proxy using a password *password* and a default *lifetime* of 8 days, which is
internally parsed by :py:func:`law.util.parse_duration` where the default input unit is hours.
To ensure that the *password* it is not v... | 5,300,432 |
def extract_features(sourcedir):
"""
This function parses a directory for images, extracts their labels, applies
ImageNet preprocessing and extracts CNN codes from the final average pooling
layer in ResNet50.
Params:
sourcedir: The root directory to parse for images.
Returns:
F... | 5,300,433 |
def regression_on_terrain_ridge_lasso(filename, method, degree_arr, lambda_arr, k=5):
"""
Info:
Perform RIDGE/LASSO regression on ".tif" terrain data for all degrees
in degree_arr and all alphas in 10**lambda_arr.
MSE is evaluated by using k-fold CV.
Input:
* filename: names of files in dat... | 5,300,434 |
def get_parametric_distribution_for_action_space(action_space):
"""Returns an action distribution parametrization based on the action space.
Args:
action_space: action space of the environment
"""
if isinstance(action_space, gym.spaces.Discrete):
return CategoricalDistribution(action_space.n,
... | 5,300,435 |
def show_help():
"""
Help on common operations.
"""
from denim.environment import get_environments
import denim
print """
Common operations with Denim (%(version)s).
Provision server:
> fab {%(environments)s} init
Deploy (require a source control revision to be supplied. i.e. master):
> fab {... | 5,300,436 |
def find_vigenere_key(cipher, keylen):
"""Breaks a vigenere cipher with known keylen"""
key = []
for block in utility.transpose(cipher, keylen):
_, k, _ = find_single_byte_xor_key(block)
key.append(k)
return bytes(key) | 5,300,437 |
def client_dual_1() -> testing.TestClient:
"""Create testing client"""
return testing.TestClient(app_dual_1) | 5,300,438 |
def Variable_Point_to_Probability(train, forecast, alpha=0.3, beta=1):
"""Data driven placeholder for model error estimation.
ErrorRange = beta * (En + alpha * En-1 [cum sum of En])
En = abs(0.5 - QTP) * D
D = abs(Xn - ((Avg % Change of Train * Xn-1) + Xn-1))
Xn = Forecast Value
QTP = Percentil... | 5,300,439 |
def count_frequency(df, col):
"""Count the number of occurence value in a column."""
df['Freq'] = df.groupby(col)[col].transform('count')
return df | 5,300,440 |
def _get_all_objs(container, classname):
"""Get all `neo` objects of a given type from a container.
The objects can be any list, dict, or other iterable or mapping containing
neo objects of a particular class, as well as any neo object that can hold
the object.
Objects are searched recursively, so ... | 5,300,441 |
def paired_dot_distance(par_xy: np.ndarray,
dau_xy: np.ndarray
) -> Tuple[np.ndarray]:
"""Calculates error for normalized dot distance and error along line
NOTE:
- x, y are switched in this function relative to the image.
TODO:
- Better docst... | 5,300,442 |
def upgrade(target='heads'):
"""Run migrations to upgrade the database."""
get_alembic().upgrade(target) | 5,300,443 |
def project(B, nodes, create_using=None):
"""Return the graph of the the given bipartite graph projected onto
a subset of nodes.
The nodes retain their names and are connected in the resulting
graph if have an edge to a common node in the original graph.
Parameters
----------
B : NetworkX... | 5,300,444 |
def DBSCAN(M, eps=0.5, min_pts=5, d='euclidean'):
"""
Performs DBSCAN clustering.
M: matrix to use
eps: Epsilon for DBSCAN algorithm, Neighbourhood to find points in
min_pts: Threshold to consider neighbourhood dense.
d: Distance metric to use.
"""
dbscan_obj = clus... | 5,300,445 |
def _do_ramp(psi_0,H,basis,v,E_final,V_final):
"""
Auxiliary function to evolve the state and calculate the entropies after the
ramp.
--- arguments ---
psi_0: initial state
H: time-dependent Hamiltonian
basis: spin_basis_1d object containing the spin basis (required for Sent)
E_final, V_final: eigensystem of H(... | 5,300,446 |
def create_dns_record(public_ip: str, dns_name: str, healthcheck_id: str = None):
"""Create a Route53 multi-value A record, optionally with healthcheck."""
client = boto3.client("route53")
# set identifiers are used in multi-value record sets to uniquely id a record
hash_str = f"{public_ip}/{dns_name}"... | 5,300,447 |
def extract_tty_phone(service_center):
""" Extract a TTY phone number if one exists from the service_center
entry in the YAML. """
tty_phones = [p for p in service_center['phone'] if 'TTY' in p]
if len(tty_phones) > 0:
return tty_phones[0] | 5,300,448 |
def get_nature(nature_id):
"""Retrieves a set of information about a nature.
Keyword arguments:
nature_id (int) -- the ID of the nature (0-24)
"""
db = get_cursor()
query = 'SELECT `id`, `name`, `atk`, `def`, `spe`, `spa`, `spd` FROM `natures` WHERE `id` = ?'
nature = db.execute(query, (n... | 5,300,449 |
def test_edtf_to_datetime_limit():
"""Test lowest possible date."""
y = parse_edtf_level0('1000')
assert edtf_to_datetime(y, 'lower') == datetime(1000, 1, 1)
assert edtf_to_datetime(y, 'upper') == datetime(1000, 12, 31) | 5,300,450 |
def get_data_dir() -> str:
"""Get a filepath to the drem data directory.
Returns:
str: Filepath to the drem data directory
"""
cwd = Path(__file__)
base_dir = cwd.resolve().parents[3]
data_dir = base_dir / "data"
return str(data_dir) | 5,300,451 |
def get_sites_by_processing_status(s_status, sorting_desc=False):
"""
Gets sites by processing status
:param s_status: str - The chosen processing status
:param sorting_desc: bool - Sorting order: True (desc), False (asc - default in PONY)
:return: sites_names: list of str - The url of the sites i... | 5,300,452 |
def listen(stream):
"""
Args:
stream:
"""
chunk = stream_config['frames_per_buffer']
rate = stream_config['rate']
# the data structure within which the main listening will be stored
listen_history = deque(maxlen=(rate / chunk) * LISTEN_HISTORY)
# the data structure within whic... | 5,300,453 |
def debugpathcopies(ui, repo, rev1, rev2, *pats, **opts):
"""show copies between two revisions"""
ctx1 = scmutil.revsingle(repo, rev1)
ctx2 = scmutil.revsingle(repo, rev2)
m = scmutil.match(ctx1, pats, opts)
for dst, src in sorted(copies.pathcopies(ctx1, ctx2, m).items()):
ui.write(b'%s -> %... | 5,300,454 |
def _encode_json(tokenizer, sample_json: dict, max_sequence_length: int) -> Dict:
"""
Method enrich utterance json with encoded utterance, value and label for training later.
:param tokenizer: BERT tokenizer
:param sample_json: utterance JSON
:param max_sequence_length: max sequence length (BERT pa... | 5,300,455 |
def exportBushfire(bushfire,folder=None,merged_bushfires=None):
"""
export bushfire as geojson file
bushfire should be a Bushfire or BushfireSnapshot object
"""
bushfire = get_bushfire(bushfire)
if merged_bushfires:
merged_bushfires = get_bushfire(merged_bushfires)
if bus... | 5,300,456 |
def is_trimesh_installed(raise_exception: Boolean = False) -> Boolean:
"""
Returns whether *Trimesh* is installed and available.
Parameters
----------
raise_exception
Whether to raise an exception if *Trimesh* is unavailable.
Returns
-------
:class:`bool`
Whether *Trime... | 5,300,457 |
def get_unshare_path():
"""Find the path to the unshare utility."""
return shutil.which('unshare') | 5,300,458 |
def handle_reaction_removed_event(
user_email: str, incident_id: int, event: dict = None, db_session=None
):
"""Handles an event where a reaction is removed from a message."""
pass | 5,300,459 |
def l3_interface_group_id(ne_id):
"""
L3 Interface Group Id
"""
return 0x50000000 + (ne_id & 0x0fffffff) | 5,300,460 |
def test_webdriver_not_subclassed():
"""A registered subtype of WebDriver should work with isinstance checks."""
class MyWebDriver:
def __init__(self, *args, **kwargs):
super(MyWebDriver, self).__init__(*args, **kwargs)
# Test that non registered class instance is not instance of Remote... | 5,300,461 |
def LogStatusFrame(*args, **kwargs):
"""LogStatusFrame(wxFrame pFrame, String msg)"""
return _misc_.LogStatusFrame(*args, **kwargs) | 5,300,462 |
def output_include_file(nodes_s, elements_s, pid, filename, velocity = [], angle = []):
"""Same function as output_keyword_file,
but with the absence of property and material.
Args:
nodes_s (array): Nodes matrix.
elements_s (array): Elements matrix.
pid (int): Described before.
... | 5,300,463 |
def set_safari_cookie(request):
"""
Special handling for Safari's third party cookie blocking: when showing a private link, user will be forwarded
to this view on WARC_HOST to have an arbitrary cookie set, so Safari will let us set an authorization cookie
in the iframe. Once we set the cooki... | 5,300,464 |
def eat_arguments(node, text):
"""
gets the (parameters) appended to the +tag
"""
DEL = r'(?P<argend>\))|(?P<has_value>=)'
ATTR = r'\s*(?P<attribute>[\w\-:\.#]+)\s*'
VAL = r'\s*"(?P<value>.*?)"\s*'
tokens = re.compile('|'.join((VAL, ATTR, DEL))).finditer(text)
for mo in tokens:
type_ = mo.lastg... | 5,300,465 |
def draw_measurements(image: np.ndarray, skeleton: np.ndarray, measurements, color):
"""
Draw overlays on top of an image to represent the worm measurements:
circles to indicate the width at three points along the worm body: head, midbody and tail
"""
if np.any(np.isnan(skeleton)):
return
... | 5,300,466 |
def checkpoint(func, inputs, params, flag, final_nograd=0):
"""
Evaluate a function without caching intermediate activations, allowing for
reduced memory at the expense of extra compute in the backward pass.
:param func: the function to evaluate.
:param inputs: the argument sequence to pass to `fun... | 5,300,467 |
def get_data(name):
"""Utility for convenient data loading."""
images, labels = extract_images()
images = np.reshape(images, list(images.shape) + [1, ])
rng = np.random.RandomState(seed=47)
# inds = rng.choice(len(images), int(len(images) / 5 * 4))
# print(inds)
if name == 'train' or name... | 5,300,468 |
def check_unlogged(tasks, logs, user, log_date):
"""Given a queryset of tasks, a queryset of logs and a log date, checks for
unlogged tasks and creates new logs where needed, returning True.
Returns False if no new logs are created."""
unlogged = []
# Check for unlogged tasks
for task in tasks:... | 5,300,469 |
def _pipeline_runtime(jobs):
"""Compute the runtim of the pipeline"""
times = []
now = datetime.now()
# collect the times
for j in jobs:
if j.start_date:
s = j.start_date
e = j.finish_date if j.finish_date else now
times.append((s, e))
times = sorted(t... | 5,300,470 |
def publish(config: str, url: str, version: str = None):
"""
Request the API server to publish a given config version to a cloud bucket
URL
"""
body = [{"name": "url from CLI", "url": url}]
if version is None:
output(state.api.tools.publish(config, body=body).body)
else:
outp... | 5,300,471 |
def VerifyGKEFlags(args, release_track, product):
"""Raise ConfigurationError if args includes OnePlatform only arguments."""
error_msg = ('The `{flag}` flag is not supported with Cloud Run for Anthos '
'deployed on Google Cloud. Specify `--platform {platform}` or '
'run `gcloud config... | 5,300,472 |
def addresses(x: bytes) -> list:
""" Creating a list of IPv4 addresses from a byte string
Args:
x: source bytesting
Returns:
A list of one or multiple IPv4 addresses
"""
x = x[4:]
addr: list = []
while len(x) > 0:
single_address: bytes = x[5:9]
... | 5,300,473 |
def __max_group_mass__(groupMass, parameters):
# type: (pandas.DataFrame, LFParameters) -> pandas.DataFrame
"""Replace the m/z value of each row by the m/z with the highest
sample mean intensity.
Keyword Arguments:
groupMass -- mass or feature cluster
parameters -- LipidFinder's PeakFi... | 5,300,474 |
def color_from_string(cstr):
"""
Return a Geosoft color number from a color string.
:param cstr: color string (see below)
:returns: color
Colour strings may be "R", "G", "B", "C", "M", "Y",
"H", "S", "V", or "K" or a combination of these
characters, each followed by up to three di... | 5,300,475 |
def corr_pred_gold(gold, pred, eval_type=EvalTypes.NODE):
"""Given a golden tree/sentence and a predicted tree/sentence, this counts correctly
predicted nodes/tokens (true positives), all predicted nodes/tokens (true + false
positives), and all golden nodes/tokens (true positives + false negatives).
@p... | 5,300,476 |
def adapt(data):
"""
适配内容
:param data:
:return:
"""
verify_data = []
global month_ago
global stop_flog
for item in data:
content = item.text.split("\n")
content_len = len(content)
if content_len == 6 or content_len == 7:
# 修改没有服务器地址的IP
... | 5,300,477 |
def get_value(amount, currency):
"""
Returns the value of the transfer in the representation of the
currency it is in, without symbols
That is, 1000 cents as 10.00, 1000 yen as 1000
"""
if currency in DECIMAL_CURRENCIES:
return Decimal(amount)/Decimal(100)
return Decimal(amount) | 5,300,478 |
def subaward_types_are_valid_groups(type_list):
"""Check to ensure the award type list is a subset of one and only one award group.
Groups: are "Procurement" and "Assistance"
If false, the award type codes aren't a subset of either category.
"""
is_procurement = set(type_list).difference(set(procur... | 5,300,479 |
def parse_none(func):
"""Decorator for a parser which can parse None
Args:
callable: function to be decorated
Returns:
callable: func with attr indicating it can parse None
"""
setattr(func, _PARSE_NONE_ATTR, True)
return func | 5,300,480 |
def test_activate(fixtures):
"""Test the 'activate' command"""
runner = CliRunner()
help_result = runner.invoke(cli.cli, ["node", "activate", "--help"])
assert help_result.exit_code == 0
assert (
"Interactive routine for activating a storage node located at ROOT."
in help_result.out... | 5,300,481 |
def set_max_width(data, keys=False):
"""Sets the max width of tables displayed using Kivy's RecycleView.
The max width parameters are stored as global variables to prevent having
to set them for each and every row. Instead, they are set once when the
RecycleView is instantiated.
Args:
data... | 5,300,482 |
def register(request):
"""
Register new user.
Args:
request (HttpRequest):
Request with user `name`, `first_name` and `password` passed with
the `GET` method.
Returns:
An `HttpResponse` with search results.
"""
if request.method == 'POST':
user... | 5,300,483 |
def make_tag_list(tag_dict):
""" make list from tag dictionary """
tag_list = tag_dict.keys()
# needless because keys doesn't overlap.
# tag_list = list(set(tag_list))
# but, in python3, type of tag_list is not list, it is dict_key.
tag_list = list(tag_list)
tag_list.sort()
return tag_li... | 5,300,484 |
def temp_dynamics(
models: dict,
) -> np.ndarray:
"""Returns the new zone temperatures based on the current state."""
zone_temp = np.zeros(Z, dtype=np.float64)
for z in range(Z):
y = np.array(models[z]["ss_C"]).squeeze() * models[z]["x_k"].squeeze()
zone_temp[z] = y + models[z]["mean_ou... | 5,300,485 |
def logsig(x):
""" logsig activation function """
return 1.0 / (1.0 + exp(-x)) | 5,300,486 |
def delete_db_cluster_parameter_group(DBClusterParameterGroupName=None):
"""
Deletes a specified DB cluster parameter group. The DB cluster parameter group to be deleted can\'t be associated with any DB clusters.
See also: AWS API Documentation
Exceptions
:example: response = client.delete... | 5,300,487 |
def filter_cpgkeys_using_bedfile(cpgKeys, bedFileName):
"""
Keep only cpg keys in bed file range, return set of keys
:param cpgKeys:
:param bedFileName:
:return:
"""
cpgBed = calldict2bed(cpgKeys)
coordBed = get_region_bed(bedFileName)
intersectBed = intersect_bed_regions(cpgBed, coo... | 5,300,488 |
def adjust_prices(utilities, caps, budgets, prices, n):
"""return the new prices"""
cleared_bool = clearing(np.sum(allocate(utilities, caps, budgets, prices, n), axis=0), utilities, caps)
# Find clearing prices
while not np.all(cleared_bool):
if not cleared_bool[0]:
for i in range(n)... | 5,300,489 |
def send_receipt_email(application_id):
"""
Send a receipt email
Args:
application_id(str): the application id to send an email for
"""
# NOTE: this receipt email includes a whole payment history so it'd more of a snapshot
try:
application = BootcampApplication.objects.prefetch_... | 5,300,490 |
def symmetricTensor(a,b,c):
"""
symmetric tensor product from section 5.2 of Song et al. (2014)
"""
term1 = np.tensordot(np.tensordot(a,b,0),c,0)
term2 = np.tensordot(np.tensordot(c,a,0),b,0)
term3 = np.tensordot(np.tensordot(b,c,0),a,0)
return term1+term2+term3 | 5,300,491 |
def sentinel(name):
"""Create a unique, one-off object with a useful repr"""
def __repr__(_):
return f'<{name}>'
return type(name, (), {'__repr__': __repr__})() | 5,300,492 |
def clifford_attractor(lvl, a, b, c, d):
"""
Inputs:
lvl -- integer, number of iterations
a, b, c, d -- numeric parameters
Return a tuple with two 1D numpy arrays, each of size lvl + 1,
with calculated xy coordinates.
"""
lvl += 1
# Containers to store xy compone... | 5,300,493 |
def main(spark):
"""
Reads in JSON and gets table. Applies required processing and saves results.
"""
# Read JSON file and register DataFrame as a SQL temporary view.
github_json = spark.read.json("2017-10-01-10.json.gz")
github_json.createOrReplaceTempView('GithubEvents')
# SQL query to se... | 5,300,494 |
def OutputRevenue(time,X,y, original_price, product_id):
"""
Note that the revenue computed is what it would have been
if the price is best up.
"""
n_weeks = len(time)
# accumate arrays of best_demand, original demand, and best_price_change array.
best_price_changes = np.zeros(n_weeks)
... | 5,300,495 |
def diskAverage(s,r_out,bins=50,avgFlag=True):
"""
Computes the accretion disk mass-averaged for x via the following equation:
integral of 2*pisigma*x*r*dr / integral of 2*pi*sigma*r*dr.
Sigma, e,a... calculated on the fly to ensure that they are all evaluated at
the same location.
Paramete... | 5,300,496 |
def datestr(datetime_inst):
""" make iso time string from datetime instance
"""
return datetime_inst.isoformat("T") | 5,300,497 |
def read_csv(fname, params_dict):
"""
Reads csv file.
Paramenters
-----------
fname : str
Path to file name.
params_dict : dict
Dict with paramenters for parsing csv file.
`csv_delimiter`, `proteins_column`, `proteins_delimiter`
Returns
-------
A DataFram... | 5,300,498 |
def minimal_spanning_tree(graph, mode='Prim', starting_node=None):
"""
Args:
graph: weighted adjacency matrix as 2d np.array
mode: method for calculating minimal spanning tree
starting_node: node number to start construction of minimal spanning tree (Prim)
Returns:
minimal s... | 5,300,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.