content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def update_password(password, value, position=None):
"""Update password with value
:param str password: The password string
:param str value: The character(s) to update with
:param int position: The position in which to insert the character(s)
:return: The updated password
"""
result = list... | 57,400 |
def run_distribute(filename, distribution, graph=None, algo=None):
"""
Run the distribute cli command with the given parameters
"""
filename = instance_path(filename)
algo_opt = '' if algo is None else '-a ' + algo
graph_opt = '' if graph is None else '-g ' + graph
cmd = 'pydcop distribute -... | 57,401 |
def find_pmp(df):
"""simple function to find Pmp on an IV curve"""
return df.product(axis=1).max() | 57,402 |
def chebyshev_distance(v1, v2, norm=False):
"""
return ||v1 - v2||_oo
"""
v1, v2 = check_pairwise_vector(v1, v2, norm)
diff = v1 - v2
K = np.abs(diff).max()
return K | 57,403 |
def get_distances_from_other_points(point_index: int, num_samples: int, distance_matrix: ndarray):
"""Get distances from point i to other points in the dataset.
Args:
point_index: The index of the point.
num_samples: The number of points.
distance_matrix: Condensed distance matrix.
... | 57,404 |
def collect():
"""Collects and aggregates contents of TinyPilot-related logs and files.
Returns:
A large string with the full contents of TinyPilot's debug logs and
configuration files.
"""
try:
# return subprocess.check_output(
# ['sudo', '/opt/tinypilot-privileged/... | 57,405 |
def get_help_option(input_args):
"""Get help about option or values authorized for option."""
global cmdhelp_settings, cmdhelp_option_infolist
global cmdhelp_option_infolist_fields
pos = input_args.find(' ')
if pos > 0:
option = input_args[0:pos]
else:
option = input_args
opt... | 57,406 |
def aggregate_report():
"""Generate a report with total of resources in used and reserved for
each aggregate."""
context = {}
aggregates = Aggregates.objects.all()
for aggregate in aggregates:
# Add aggregate on context dict
if aggregate.name not in context:
context[ag... | 57,407 |
def print_usage(data=None):
"""Nicely print usage data"""
if data is None:
data = LATEST_DATA
print(
" {:2s} {:20s} {:32s} {:3s}% {:3s}%".format(
"id", "hostname", "date", "CPU", "MEM"
)
)
for eid, report in sorted(data.items()):
print(
"{:3.0f... | 57,408 |
async def test_add_pet(client):
"""Test case for add_pet
Add a new pet to the store
"""
body = {
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "n... | 57,409 |
def create_app(object_name):
"""
:argument object_name: the python path of the config object
:return: app
"""
app = Flask(__name__)
app.config.from_object(object_name)
db.init_app(app)
app.register_blueprint(main_blueprint)
return app | 57,410 |
def fix_timestamp(dataframe):
"""
Convert timestamp from UTC into engine timezone and from ISO to format expected by graphs
:param1 dataframe: data frame to process
return: dataframe with converted timestamp column
"""
dataframe["timestamp"] = dataframe["timestamp"].apply(convert_from_utc, args=(__eng... | 57,411 |
def cve_last_week():
"""
Get CVEs from last week of the year
---
tags:
- CVE
responses:
200:
description: Get CVEs from last week of the year
408:
description: Request timeout
"""
# FIXME: get rid of hardcoded year
cves = CVE.query.filter(
2019 =... | 57,412 |
def countYes():
"""Calculate which item has the fewest "yes" answers, and return that item.
Breaks ties by selecting the first key with the lowest amount of .
Precondition: Needs a list of dicts with the correct keys and values.
Postcondition: Return the item with fewest yes answers."""
#... | 57,413 |
def scale(data, remove_outliers=False):
"""
Scales the input and removes outliers
"""
if remove_outliers:
perc_2 = np.zeros(data.shape[1])
perc_98 = np.zeros(data.shape[1])
for i in range(data.shape[1]):
perc_2[i] = np.percentile(data[:, i], 2)
perc_98[i] ... | 57,414 |
def subpixel_values(img, pts):
"""
References:
stackoverflow.com/uestions/12729228/simple-efficient-binlinear-interpolation-of-images-in-numpy-and-python
SeeAlso:
cv2.getRectSubPix(image, patchSize, center[, patch[, patchType]])
"""
# Image info
nChannels = get_num_channels(img)... | 57,415 |
def loadZenMakeMetaFile(filePath):
"""
Load ZenMake common ConfigSet file. Return None if failed
"""
dbfile = db.PyDBFile(filePath, extension = '')
try:
data = dbfile.load(asConfigSet = True)
except EnvironmentError:
return None
return data | 57,416 |
def plot_1d(model, opts, ax):
# type: (KernelModel, Dict[str, Any], Axes) -> None
"""
Create a 1-D image.
"""
q_min, q_max, nq = opts['q_min'], opts['q_max'], opts['nq']
q_min = math.log10(q_min)
q_max = math.log10(q_max)
q = np.logspace(q_min, q_max, nq)
data = empty_data1D(q)
c... | 57,417 |
def readable_timedelta(days):
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
return "{} week(s) and {} day(s).".format(w... | 57,418 |
def test_matching_cname_with_correct_content(session, log_file, capsys):
"""CNAME record on the targeted subdomain, set to the current IP. Should be removed since we want A records instead."""
response = '{"result":{"code":100,"message":"Command Successful"},"records":[{"record_id":"6827626","name":"sub.example... | 57,419 |
def create_net(in_sx, in_sy, out_sx):
"""
Creates a tflearn neural network with the correct
architecture for learning to hear the keyword
"""
net = tflearn.input_data([None, in_sx, in_sy])
net = tflearn.lstm(net, lstm_size, dropout=lstm_dropout)
net = tflearn.fully_connected(net, out_sx, activation='softmax')
n... | 57,420 |
def test_addressrange(proxy):
"""
Address Range (AddressRange)
"""
addressranges = proxy.GetAddressRange()
#result = proxy.CreateAddressPool(pipFrom=None, pipTo=None)
#result = proxy.AddAddressRange(pipFrom, pipTo)
#result = proxy.DeleteAddressRange(pipFrom, pipTo) | 57,421 |
def compute_iou(boxes1, boxes2):
"""
compute_iou() 函数用来计算 IOU 值,即真实检测框与预测检测框(
当然也可以是任意两个检测框)的交集面积比上
它们的并集面积,这个值越大,代表这个预测框与真实框的位置越接近
如果说得到的 IOU 值大于设置的正阈值,那么我们称这个预测框为正预测框(
positive anchor)其中包含着检测目标;
如果说得到的 IOU 值小于于设置的负阈值,那么我们称这个预测框为负预测框(
)negative anchor),其中包含着背景
"""
le... | 57,422 |
def localize_date_utc(date):
"""
Localizes in the UTC timezone the given date object.
:param date: The date object to be localized.
:return: A localized datetime object in the UTC timezone.
TODO :: unit test
"""
return pytz.utc.localize(
datetime.datetime.combine(
date, d... | 57,423 |
def compute_box_3d_tracker(tracker, P):
""" Takes an tracker object and a projection matrix (P) and projects the 3d
bounding box into the image plane.
Returns:
corners_2d: (8,2) array in left image coord.
corners_3d: (8,3) array in in rect camera coord.
"""
# compute ... | 57,424 |
def lang_exists(cursor, lang):
"""Checks if language exists for db"""
query = "SELECT lanname FROM pg_language WHERE lanname = %(lang)s"
cursor.execute(query, {'lang': lang})
return cursor.rowcount > 0 | 57,425 |
def create_init(fields, # type: Iterable[Field]
user_init_fun=None, # type: Callable[[...], Any]
inject_fields=False, # type: bool
user_init_args_before=True # type: bool
):
"""
Creates the new init function that... | 57,426 |
def search_comments_for_terms(terms, comments):
"""
Adds Boolean columns indicating whether a search term was located
Args:
terms {tuple} : a collection of unique search terms
comments {DataFrame} : a Pandas DataFrame with comment data
Returns:
A Pandas DataFrame with the update... | 57,427 |
def calculate_folder_checksum(folderpath, format_checksum=True,
recursive=True):
""" Calculate the checksum of a specified folder
Checksum is calculated with :func:`zlib.crc32`.
Parameters
----------
folderpath: :obj:`str`
Path to the folder for which the chec... | 57,428 |
def update_node_data_join():
"""
This is a route for ALL NODES.
Whenever the PREVIOUS NODE departs from the ring,
all of its data are transfered to us through this route.
"""
start_id = request.form['start_id']
k = int(request.form['k'])
prev_storage = {}
to_be_deleted = {}
for k... | 57,429 |
def load_image(fname=None):
"""Load example image.
"""
if fname is None:
fname = 'chelsea.jpg'
fname = os.path.join(os.path.dirname(__file__), 'data/' + fname)
if len(sys.argv) == 2:
img = PIL.Image.open(sys.argv[1])
else:
img = PIL.Image.open(fname)
return np.arra... | 57,430 |
def isMessageBody(line: str) -> bool:
"""
Returns True if line has more than just whitepsace and unempty or is a comment (contains #)
"""
return not (line.isspace() or line.lstrip().startswith('#')) | 57,431 |
def getHistoricalUmuxChartData(allProjectSnapshots):
"""
UMUX history line chart on project detail page.
Loop thru quarters starting at first meaningful quarter 2 years or less ago.
If a quarter has no (meaningful) snapshot, it gets an empty x-axis tick.
Return: {obj} Chart data with xaxis quarters, scores, and ta... | 57,432 |
def is_number(string):
"""Test whether a string is number-ish. Ignoring units like 'cwt' and 'hd'."""
if string:
string = re.sub(r'\$|[,-/]|cwt|he?a?d?|per', '', string, flags = re.IGNORECASE)
try:
float(string)
result = True
except ValueError:
result... | 57,433 |
def bootstrap_puppet_agent_config():
"""
Adjust various settings in puppet.conf and create an external Facts file
for Puppet-specific stuff.
"""
dmc = '^.+$'
for key, regex in {
'PUPPET_ENVIRONMENT_NAME': dmc,
'PUPPET_SERVER_HOSTNAME': dmc,
'PUPPET_CA_SERVER': dmc,
... | 57,434 |
def downgrade_pan_3d(I_MS , I_PAN, ratio, sensor=None):
"""
downgrade MS and PAN by a ratio factor with given sensor's gains
"""
I_MS=np.double(I_MS)
I_PAN=np.double(I_PAN)
I_MS = np.transpose(I_MS, (2, 0, 1)) #
#I_PAN = np.squeeze(I_PAN) #从数组的形状中删除单维度条目,即把shape中为1... | 57,435 |
def readSedML(*args):
"""
readSedML(self, string filename) -> SedDocument
Reads an SEDML document from a file.
This method is identical to readSedMLFromFile().
If the file named 'filename' does not exist or its content is not
valid SEDML, one or more errors will be logged with the SedDocument
object re... | 57,436 |
def show_status_json():
""" List current status of sensors in json-format """
from my_library import test_socket, ClassDB
from collections import namedtuple, defaultdict
import json
db_ip = server_settings['db_ip']
db_user = server_settings['db_user']
db_pass = server_settings['db_pass']
... | 57,437 |
def get_recommended_dictionary_gcs_path(fuzzer_name):
"""Generate a GCS url to a recommended dictionary.
Returns:
String representing GCS path for a dictionary.
"""
bucket_name = environment.get_value('FUZZ_LOGS_BUCKET')
bucket_subdirectory_name = 'dictionaries'
recommended_dictionary_gcs_path = '/%s/%... | 57,438 |
def PlaneEHfield(z, t=0.0, sig=1.0, mu=mu_0, epsilon=epsilon_0, E0=1.0):
"""
Plane wave propagating downward (negative z (depth))
"""
bunja = -E0 * (mu * sig) ** 0.5 * z * np.exp(-(mu * sig * z ** 2) / (4 * t))
bunmo = 2 * np.pi ** 0.5 * t ** 1.5
Ex = bunja / bunmo
Hy = E0 * np.sqrt(sig ... | 57,439 |
def find_grass_dir():
"""Try to find GRASS install directory."""
if "GISBASE" in os.environ:
return os.environ["GISBASE"]
p = run(["grass", "--config", "path"], capture_output=True)
if p.returncode == 0:
return p.stdout.decode().strip()
else:
raise GrassNotFound() | 57,440 |
def playbook_path(request: SubRequest, tmp_path: Path) -> str:
"""Create a playbook with a role in a temporary directory."""
playbook_text = request.param[0]
role_name = request.param[1]
role_layout = request.param[2]
role_path = tmp_path / role_name
role_path.mkdir()
dict_to_files(role_path... | 57,441 |
def _address_to_placement(address):
"""
Parameters
----------
address : str
The address of a node or an actor pool which running in a ray actor.
Returns
-------
tuple
A tuple consisting of placement group name, bundle index, process index.
"""
parsed_url = urlparse(... | 57,442 |
def ideal_season_state(season_states, conditions_season):
"""Classify ideal season states # (prefer dry rainy over early/late states)"""
(
dry_condition,
dry_early_condition,
dry_late_condition,
rainy_condition,
rainy_early_condition,
rainy_late_condition,
) =... | 57,443 |
def estimate_post_transplant_death(txids, doids):
"""
This function estimate the number of post transplant deaths.
@Input:
@txids: list of patients who received transplants
@doids: list of donated organs
@Output:
@output_totals: number of post transplant deaths for each replication
"""
#set seed
nump.rand... | 57,444 |
def geolytica(location):
"""
# Geolytica
Geocoder.ca - A Canadian and US location geocoder.
Using Geocoder you can retrieve Geolytica's geocoded data from Geocoder.ca.
## Python Example
>>> import geocoder
>>> g = geocoder.geolytica(<address>)
>>> g.lat, g.lng
45.4... | 57,445 |
def draw_raw_tree(filename: str) -> None:
"""Draws a raw tree from ete3 representation
stored in a file
Parameters
----------
filename : str
a name of the file
Returns
-------
None
"""
ts = TreeStyle()
ts.show_leaf_name = False
ts.layout_fn = layout_raw
ts.... | 57,446 |
def write_output_main(commands, main_file):
"""Outputs a standalone latex file containing the code."""
latex_file = open(main_file, "w")
latex_file.write("\\documentclass{article}\n\\usepackage{tikz}\n\\usetikzlibrary{quantikz}\n\\begin{document}\n\\begin{center}\n\\begin{quantikz}\n"
)
latex_file.write... | 57,447 |
def flatten(self):
"""
Takes a diagram of diagrams and returns a diagram.
>>> from discopy.monoidal import *
>>> x, y = Ty('x'), Ty('y')
>>> f0, f1 = Box('f0', x, y), Box('f1', y, x)
>>> g = Box('g', x @ y, y)
>>> d = (Id(y) @ f0 @ Id(x) >> f0.dagger() @ Id(y) @ f0 >>\\
... g @ f1 ... | 57,448 |
def accuracy_count(y_true, y_pred) -> int:
"""
accuracy 计数
Examples:
# 单标签分类
>>> _y_true = [0,1,2,3]
>>> _y_pred = [0,1,2,2]
>>> accuracy_count(_y_true, _y_pred)
3
# 多标签分类:使用 one-hot 标签
>>> _y_true = [[0,1],[1,1],[1,0],[0,0]]
>>> _y_pred = [[... | 57,449 |
def label_image(image_bytes, labels):
"""
Plot an image and corresponding bounding
boxes of detected labels
Parameters
----------
image_bytes : bytes
Image as bytes
labels : [n_label,] dict
Returned from api.get_json() function or from
Rekognition.detect_labels(). E... | 57,450 |
def main():
"""Create and start DragonflyDevice."""
arguments = docopt(__doc__)
device = DragonflyDevice(
inbound=parse_host_and_port(arguments["--inbound"]),
outbound=parse_host_and_port(arguments["--outbound"]),
port=arguments["--port"])
device.run() | 57,451 |
def to_json(data, filename='data.json', indent=4):
"""
Write an object to a json file
:param data: The object
:param filename: The name of the file
:param indent: The indentation of the file
:return: None
"""
with open(filename, 'w') as f:
f.write(json.dumps(data, in... | 57,452 |
def parse_prelink_info():
"""Find and parse the kernel __PRELINK_INFO dictionary."""
segments = _find_prelink_info_segments()
for segment in segments:
seg_size = idc.get_segm_end(segment) - idc.get_segm_start(segment)
prelink_info_string = idc.get_bytes(segment, seg_size)
prelink_info_string = prelink_info_str... | 57,453 |
def test_usage_output():
"""Проверяет вывод справки."""
assert CLI.test([]) == ([CLI.usage], 0) | 57,454 |
async def test_form_invalid_auth(hass):
"""Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
... | 57,455 |
def box_plots(df, plotField, groupField, groupFieldItems):
"""
Returns a dictionary of box plot statistics for the plotField,
where the keys are the unique items in the groupField.
"""
# reduce df and drop the nulls
df = df[[plotField, groupField]].dropna()
# group the requests by type and ... | 57,456 |
def mousePressed():
"""User move when click in x, y coordinates"""
global timer
if maze.tiles.player == 1 and not maze.tiles.gameover:
timer = millis()
maze.control(mouseX, mouseY) | 57,457 |
def model(X_train, Y1_train, Y2_train, X_dev, Y1_dev, Y2_dev, numOutputNodes, learning_rate = 0.0001, iterations = 5000, minibatch_size = 16, print_cost = True, \
layer1 = 100, layer2_1 = 50, layer2_2 = 50, beta1 = 0.01, beta2 = 0.1):
""" Three-layer NN to predict Fe coordination numbers around oxygen.
... | 57,458 |
def define_ncf_flags():
"""Add flags for running ncf_main."""
# Add common flags
flags_core.define_base(export_dir=False)
flags_core.define_performance(
num_parallel_calls=False,
inter_op=True,
intra_op=True,
synthetic_data=False,
max_train_steps=False,
dtype=False,
all... | 57,459 |
def send_shared_files(path):
"""Files used accross different web apps"""
return flask.send_from_directory(SHARED_PATH, path) | 57,460 |
def create_creative_sets(creative_sets):
"""
Creates creative sets in DFP.
Args:
creative sets (arr): an array of objects, each having creative set configuration
Returns:
an array: an array of created creative set IDs
"""
dfp_client = get_client()
creative_set_service = df... | 57,461 |
def get_combinations(limit, numbers_count, combination):
"""Get all combinations of numbers_count numbers summing to limit."""
if sum(combination) >= limit:
return None
if numbers_count == 1:
return [combination + [limit - sum(combination)]]
combinations = []
for number in range(1, l... | 57,462 |
def clear():
"""Clear the buffer.
You must call `show` after clearing the buffer to update the display.
"""
global _current_frame, _scroll, buf
_current_frame = 0
_scroll = [0, 0]
buf = numpy.zeros((DISPLAY_WIDTH, DISPLAY_HEIGHT)) | 57,463 |
def read_el_cards():
"""
Read information about space group from file to list of cards ldcard.
Info in file fitables:
1 P1 Triclinic
choice: 1
centr: false
pcentr: 0, 0, 0
symmetry: X,Y,Z
2 P-1 Triclinic
...
"""
fid = open(F_ITABLES, "r")
... | 57,464 |
def resize_image(
image: pygame.surface.Surface, new_size: Union[List[int], CoordsType]
) -> pygame.surface.Surface:
"""
wrapper for pygame.transform.scale
:param image: pygame.surface.Surface
:param new_size: Union[List[int], Tuple[int, int, int]]
:return: pygame.surface.Surface
"""
ret... | 57,465 |
def isoDuration(value):
"""(str) -- Text of contained (inner) text nodes except for any whose localName
starts with URI, for label and reference parts displaying purposes.
(Footnotes, which return serialized html content of footnote.)
"""
if not isinstance(value, str):
raise TypeErr... | 57,466 |
def _validate_no_overlap(params, error_callback):
"""Validate the provisioning and inspection ip ranges do not overlap"""
dhcp_set = netaddr.IPSet(netaddr.IPRange(params['dhcp_start'],
params['dhcp_end']))
inspection_set = netaddr.IPSet(netaddr.IPRange(params['in... | 57,467 |
def bit_list_to_int(bit_list):
"""
Converts binary number represented as a list of 0's and 1's into its corresponding base 10
integer value.
Args:
bit_list: a binary number represented as a list of 0's and 1's
Returns:
The base 10 integer value of the input binary number
"""
... | 57,468 |
def max_labor_budget_rule(M):
"""
Put upper bound on total labor cost.
Using individual shift variables multiplied by their length and a tour
type specific cost multiplier. Could easily generalize this to make costs
be complex function of time of day, day of week, shift length, tour type,
o... | 57,469 |
def _trace_prefixes(trace: Trace, prefix_length: int) -> list:
"""List of indexes of the position they are in event_names
"""
prefixes = []
for idx, event in enumerate(trace):
if idx == prefix_length:
break
event_name = event['concept:name']
prefixes.append(event_nam... | 57,470 |
def _diff_args(type, options):
"""generate argument list to pass to diff or rcsdiff"""
args = []
if type == CONTEXT:
if "context" in options:
if options["context"] is None:
args.append("--context=-1")
else:
args.append("--context=%i" % options[... | 57,471 |
def prerelease(ctx, prerelease_token, **kwargs):
"""Bump the prerelease part of the version."""
yc = ctx.obj["yc"]
new_config = yc.bump_prerelease(prerelease_token=prerelease_token)
new_config.update(
yc,
ctx.obj["config_path"],
kwargs["dryrun"],
kwargs["git_tag_before"]... | 57,472 |
def email(value: str):
"""
Extract email from document
Example Result: ['crazyvn@gmail.com', 'feedback@tp.com']
"""
_email_pat = r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+'
return re.findall(_email_pat, value) | 57,473 |
def TransposeTable(table):
"""Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]]
"""
... | 57,474 |
def test_bernoulli1():
""" Test bernoulli distribution """
d = bernoulli(1/2)
assert_equal(d.outcomes, (0, 1))
assert_almost_equal(sum(d.pmf), 1) | 57,475 |
def test_find_returns_existing_user(users: Users, test_users):
"""find(user) returns True if user already exists"""
expected_user = test_users[0]
actual_user = users.find(expected_user.email)
assert actual_user == expected_user | 57,476 |
def _parse_belongs_to(key, belongs_to, inventory):
"""Parse all items in a `belongs_to` list.
This function assumes the key defined is a group that has child subgroups,
*not* a group with hosts defined in the group configuration.
:param key: ``str`` Name of key to append to a given entry
:param b... | 57,477 |
def test_asymetric_parquet_pieces(reader_factory, tmpdir):
"""Check that datasets with parquet files that all rows in datasets that have different number of rowgroups can
be fully read """
url = 'file://' + tmpdir.strpath
ROWS_COUNT = 1000
# id_div_700 forces asymetric split between partitions and ... | 57,478 |
def compile_metric_telegraf(
prefix: str,
path: str,
value: str,
type_code: str,
rate: str = "",
tags: typing.Optional[typing.Dict[str, str]] = None,
) -> str:
"""Compile metrics for telegraf."""
rate = serialize_rate(rate)
if tags is None:
return f"{prefix}{path}:{value}|{... | 57,479 |
def _canonicalize_depends_on(
dep_param, *, max_depth: Optional[int] = None
) -> Sequence[DependencyNode]:
"""
For convenience, we allow specifying the depends_on parameter when submitting a job
in numerous ways.
"""
if max_depth is not None:
if isinstance(dep_param, DependencyNode):
... | 57,480 |
def handle_exceptions(func):
"""Catch exceptions and return appropriate HTTP error."""
@wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as err:
return http_500(str(err))
return wrapper | 57,481 |
def extract_data(ctx):
""" Extract the source data """
ctx.run("tar xzf {}".format(FILE_EXPR_TGZ), warn=True)
ctx.run("tar xzf {}".format(FILE_CLIN_TGZ), warn=True)
ctx.run("mv gdac.broadinstitute.org_COADREAD.Merge_rnaseqv2* {}".format(DIR_EXPR)) # noqa
ctx.run("mv gdac.broadinstitute.org_COADREAD... | 57,482 |
def clean_tables():
"""Remove the lexer/parser modules that are dynamically created."""
for f in TABLES:
if os.path.isfile(f):
os.remove(f)
print("Removed " + f) | 57,483 |
def get_gpu_memory_usage() -> pd.DataFrame:
"""Return the free and used memory per GPU device on the node"""
gpu_stats = subprocess.check_output(["nvidia-smi", "--format=csv", "--query-gpu=memory.used,memory.free"])
gpu_df = pd.read_csv(StringIO(gpu_stats.decode("utf-8")), names=["memory.used", "memory.fre... | 57,484 |
def stochastic_RSI_strategy(df: pd.DataFrame, window: int = 14, max_investment: float = 0.1) -> pd.DataFrame:
"""
Stochastic Relative Strength Index Strategy
"""
# https://www.investopedia.com/terms/s/stochrsi.asp
stochRSI = signals.stochastic_relative_strength_index(df, window=window)["signal"]
... | 57,485 |
def test_template_update_badge(tmp_path: Path, cloned_template: Path):
"""Test that the template update badge is properly formatted."""
tag = "v99999.0.0-99999-bye-bye"
with local.cwd(cloned_template):
git("commit", "--allow-empty", "-m", "dumb commit")
git("tag", "--force", tag)
copy(st... | 57,486 |
def test_normal_ridge_comparison(fit_intercept):
"""
Test against sklearn's RidgeCV.
Not testing l1_ratio = 0 because automatic grid generation is not supported
in ElasticNetCV for l1_ratio = 0.
"""
n_samples = 100
n_features = 2
tol = 1e-9
alphas = [1e-4]
n_predict = 10
X,... | 57,487 |
async def migrate_databases():
"""Creates the necessary databases if they don't exist already; or migrates them."""
core_conn = await core_db.connect()
core_txn = await core_conn.begin()
try:
rows = await (await core_conn.execute("SELECT * FROM dbversions")).fetchall()
except OperationalEr... | 57,488 |
def conv3x3(in_planes, out_planes, stride = 1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size = 3, stride = stride, padding = 1, bias = False) | 57,489 |
async def handler(request: web.Request) -> web.Response:
"""
Expose API specification to the world
"""
return web.json_response(request.app["spec"].to_dict(), dumps=ujson.dumps) | 57,490 |
def storage_get_active_by_window(context,
begin,
end=None,
project_id=None):
"""Return storages that were active during window."""
session = get_session()
query = session.query(models.Hardware)
query = query... | 57,491 |
def dns(host, timeout=10):
"""
Return list of ip addresses of a given host. Errors out after timeout seconds.
"""
a = os.popen3("host -t A -W %s %s | awk '{print $4}'"%(timeout,host))
err = a[2].read().strip()
if err:
raise RuntimeError(err)
out = a[1].read()
if 'found' in out:
... | 57,492 |
def eval_against_random_bots(env, trained_agents, random_agents, num_episodes):
"""Evaluates `trained_agents` against `random_agents` for `num_episodes`."""
wins = np.zeros(2)
for player_pos in range(2):
if player_pos == 0:
cur_agents = [trained_agents[0], random_agents[1]]
else:... | 57,493 |
def _get_number_divisiors(number: int):
"""
Function return number of divisiors of a given number.
"""
if number <= 1:
raise ValueError("Number must be greater than 1.")
return len(list(divisior for divisior in range(1, floor(sqrt(number) + 1)) \
... | 57,494 |
def test_async_call_on_pause_when_health_is_enabled(accelize_drm, conf_json, cred_json,
async_handler, live_server, log_file_factory, request):
"""
Test the DRM pause function does perform a async request before pausing
"""
driver = accelize_drm.pytest_fpga_driver[0]
asyn... | 57,495 |
def elog(info, ip, name):
"""функция логгирования"""
logs.error_log.error("%s-> %s: %s" % (ip.ljust(15, '-'), name, info)) | 57,496 |
def mixin_client_features_parser(parser):
"""Add the arguments for the client to the parser
:param parser: the parser configure
"""
gp = add_arg_group(parser, title='Client Features')
parser.add_argument(
'--asyncio',
action='store_true',
default=False,
help='If set... | 57,497 |
def checksum_from_label(path):
"""Extract checksum from a label rather than calculating it.
:param path: Product path
:type path: str
:return: MD5 Sum for the file indicated by path
:rtype: str
"""
checksum = ""
product_label = path.split(".")[0] + ".xml"
if os.path.exists(product_l... | 57,498 |
def docker_send_command(command):
"""Sends the database Docker container a command."""
logger.debug("Sending database container command: %s", command)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.1)
s.connect(('db', 2345))
s.send(bytes(command, 'ascii'))
s.close() | 57,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.