content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def create_swatch_function(admin, field_name):
"""
Creates a function that can be used in list display
"""
def swatch(model):
hex_color = getattr(model, field_name)
return '<div class="admin-tweaks-swatch" style="background-color:#%s;"></div>' % (hex_color)
return swatch | ff15e8874577b26bf3efbc6cccb710321043e13d | 683,496 |
def input_prompt(prompt):
"""
Get user input
"""
return input(prompt) | 76724d278cf68ef2b16b7aa35ee61336a373f9ca | 683,497 |
import os
def _get_package_name(directory_path, trailing_period=True):
"""
This function changes directory path to a package format
apps = apps.
katana/default = katana.default.
Args:
directory_path: directory path that needs to be changed to a package format
trailing_period: if ... | 4249d2314c49a30e0788b6b070a1da0e56cb653b | 683,498 |
def pagemaker():
"""Make a site paginator
Returns:
dict, list: dict, where keys are names for tabs of paginator, values are strings for headers of pages
list of keys is used for create streamlit paginator
"""
p = {'intro': 'Введение',
'cases': 'Динамика заражения',
'infection r... | 798daa6c318bb91f91677173d8da18396ac0d183 | 683,500 |
from typing import List
def alphabetical_binary_search(sorted_list: List, search_name: str) -> int:
"""Alphabetical binary search (for study purpuses)
Args:
sorted_list (List): A list of names (must be ordered)
search_name (str): name to search
Returns:
int: found index or -1
... | 9c13c757051ce0585857b3fd52f0ce8ff257fc01 | 683,501 |
import torch
def compute_loss(inputs, outputs, criterion, edge_criterion):
"""Compute loss automatically based on what the model output dict contains.
'doc_logits' -> document-label CE loss
'para_logits' -> paragraph-label CE loss
'pare_edge_weights' -> additional edge CE loss
"""
if 'para_log... | fac6c23b1654b830d57f9197e22372a90b7d9176 | 683,503 |
def v3_state_away_json():
"""Return a /v1/ss3/subscriptions/<SUBSCRIPTION_ID>/state/away."""
return {
"success": True,
"reason": None,
"state": "AWAY",
"lastUpdated": 1534725096,
"exitDelay": 120
} | b8abb793baebdad7de9f9ff7bd54513173b336b6 | 683,504 |
import base64
def decode_base64(input_string: str) -> bytes:
"""Decode an unpadded standard or urlsafe base64 string to bytes."""
input_bytes = input_string.encode("ascii")
input_len = len(input_bytes)
padding = b"=" * (3 - ((input_len + 3) % 4))
# Passing altchars here allows decoding both stan... | c126aa8eba0f493687bb5d19c93cbbfa09178446 | 683,505 |
import json
def extract_named_args(kwargs):
"""Extract the kwargs"""
inputs = {}
if not kwargs:
return inputs
for k, kwarg in kwargs.items():
try:
if "__dict__" in dir(kwarg):
value = json.dumps(kwarg.__dict__)
elif type(kwarg) in (int, str, floa... | a95767f81c4252fc9f6333b9d714e3638937e4d0 | 683,506 |
import os
def iupg_config_base():
"""
Returns the base path where all the IUPGconfig files are stored.
"""
cur_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(cur_dir, "configs") | f0e23ae2d52980105611a0523e875ab8d549727c | 683,507 |
import glob
import importlib
import sys
def create_dataset_object(**kwargs):
"""
Use dataset_name to find a matching dataset class
Args:
kwargs: arguments specifying dataset and dataset parameters
Returns:
dataset: initialized dataset object
"""
dataset_name = kwargs['datas... | 73c308a6183706acb7f5f7c83eefb07e14a59077 | 683,508 |
def rst_header(text, level, anchor=None):
"""Create a ReST header, including a possible anchor.
Returns a multi-line string.
"""
rst = []
if anchor:
rst.append(f".. _{anchor}:")
rst.append("")
char = " #=-"[level]
if level == 1:
rst.append(char * len(text))
rst.... | 5fe318a16e7575728d5b162a0705b91f4fb34523 | 683,509 |
def normalize_extension(extension):
"""
Normalize extension
Converts given extension to canonical format for storage
:param extension: original extension
:return: normalized extension
"""
extension = extension.lower()
exts = dict()
exts['jpg'] = ['jpeg','jpe','jif','jfif','jfi''jp2'... | 14817187abe2b757f1c987bbc3b11df5613d187c | 683,510 |
import os
def file_exists(fpath):
"""
@param[in] path Path to the file whose existance you want to check.
@returns true if the file exists, otherwise returns false.
"""
return True if os.path.isfile(fpath) else False | 55d7dcb5bbb650981839bf6ec3c55a8dd71f7bfe | 683,511 |
def parseTrackLog(line):
"""Parse trackLog line and return important fields: db, year, month, hgsid,
and a list of tracks"""
#### Sample line being processed ####
# [Sun Mar 05 04:11:27 2017] [error] [client ###.###.###.##] trackLog 0 hg38 hgsid_### cytoBandIdeo:1,cloneEndCTD:2
####
spli... | ac4b1d373671c526f3e9d1cade9648e94c8c9611 | 683,512 |
import re
def getWords(text):
"""From a text input as a string, get the words separated by a space and return it as a list of strings"""
return re.compile('\w+').findall(text) | 96a75090463576034aad8693fe5387f9b59f9711 | 683,513 |
def uuid_rev_part(part):
""" Reverse part of a UUID
"""
res = ""
for i in reversed(range(0, len(part), 2)):
res += part[i]
res += part[i+1]
return res | 410e4ad729b3f1ca1ab38212db47fc2716f05a00 | 683,515 |
def split_image_into_channels(image):
"""Look at each image separately"""
red_channel = image[:, :, 0]
green_channel = image[:, :, 1]
blue_channel = image[:, :, 2]
return red_channel, green_channel, blue_channel | f97ccc1cfc5cf4a7f7cf65ad37e1ff805025c8c2 | 683,516 |
def sqdist(point1, point2, rotmat):
"""
This routine calculates the anisotropic distance between two points
given the coordinates of each point and a definition of the
anisotropy.
This method only consider a single anisotropy senario.
Parameters
----------
point1 : tuple
Coordi... | f81d50b10e6ab27bebd84a442db295965a968982 | 683,518 |
import logging
def turn_off_logging_wrapper(f):
"""wrapper to return logging level to WARNING while executing function.
See :func:`dymoesco.estimation.filters.calc_jacobian` for an example."""
def wrapper(*args, **kwargs):
logger = logging.getLogger()
loglevel = logger.getEffectiveLevel()
logger.setLevel(l... | 0bf2af9693ce29a49791bcb8fabe6b63a2ddd01c | 683,519 |
def _do_eval(match, exp):
"""Used internally to evaluate an expression."""
return eval(exp, globals(), {'m': match}) | 68c5181337985a215ac95d58ec20273b0ad54131 | 683,521 |
def validate( x ):
""" replace newlines, returns, and tabs with blank space """
if x:
if type(x) == str:
x = x.replace("\n", " ")
x = x.replace("\r", " ")
x = x.replace("\t", " ")
return x
else:
return "0" | 771ca11ea00facbb68d70122ae3533cf44d354f2 | 683,522 |
def _is_path_within_scope(scope, fullpath):
"""Check whether the given `fullpath` is within the given `scope`"""
if scope == '/':
return fullpath is not None
fullpath = fullpath.lstrip('/') if fullpath else ''
scope = scope.strip('/')
return (fullpath + '/').startswith(scope + '/') | 44bba2f38cb095adf60e6950ee8e0f3c1fe72c7b | 683,523 |
def age_interp(request):
"""Fixture for age_interp flag."""
return request.param | ff76fa87502a4712a78af556e7bcaa93327ae9bb | 683,524 |
import os
def IsFile(v):
"""Verify the file exists."""
return os.path.isfile(v) | 0db9da93b0b25c7ab323c55b1c2db1ee6af5984b | 683,526 |
def avoids(word, forbidden):
""" Predicate that asks whether word avoids letters in the forbidden string
"""
# Feels like there should be a more efficient way to do this using
# set intersection, but I'll just check the word character by character
for letter in forbidden:
if word.find(letter... | 93ddfceb051c913f14be0a70c372135c311bfb89 | 683,527 |
def get_vocabulary(path_to_vocab):
"""
Return a list of prefixes defining the vocabulary.
"""
vocab = []
with open(path_to_vocab) as f:
for line in f:
line = line.rstrip()
vocab.append(line)
return vocab | 5fecccc86903271da364e821432d4ac507810762 | 683,528 |
def b_delta(rewards,states,alpha):
"""
Implements the Resorla-Wagner (delta) learning rule.
V_intial is 0. Note: Null (0 or '0') states are silently skipped.
Returns two dictionaries containing value and RPE timecourses,
for each state.
"""
# Init
s_names = set(states)
V_dict... | ca8025307de097cdcc629141e944a0b91bcaf4bd | 683,529 |
import sqlite3
def show_vac_top_new_by_id():
"""Get last 100 vacancies sorted by id"""
con = sqlite3.connect("testdb.db")
cur = con.cursor()
sql = "SELECT * FROM calendar ORDER BY id DESC LIMIT 100;"
cur.execute(sql)
vac = cur.fetchall()
con.close()
data_list = []
for i in vac:
... | 71a192acbaa08dd3cc68192ff100fbf568f399b9 | 683,530 |
def get_weight_shapes(num_inputs, layer_sizes, num_outputs):
"""
adapted from original tf_model.get_weight_shapes()
to convert from method to function
"""
weight_shapes = []
input_size = num_inputs
for i, layer in enumerate(layer_sizes):
weight_shapes.append((input_size, layer))
weight_shapes.append((layer,... | 8538bcc37785ee617571a795ba79d2621577b90d | 683,532 |
import warnings
def format_channel_id(ch):
""" Function for formatting an `idelib.dataset.Channel` or `SubChannel`
for display. Renders as only the channel and subchannel IDs (the other
information is shown in the rest of the table).
:param ch: The `idelib.dataset.Channel` or `idelib.data... | 289a579b215f21c58003eff2dbe86c226d71c05f | 683,533 |
def _IsBold(weight):
"""Is this weight considered bold?
Per Dave C, only 700 will be considered bold.
Args:
weight: Font weight.
Returns:
True if weight is considered bold, otherwise False.
"""
return weight == 700 | c0f1305ba836216e0533f73598149f20d2eb8a3d | 683,534 |
def add_attributes(rsrc_id, manifest):
"""Add additional attributes to the manifest."""
proid = rsrc_id[0:rsrc_id.find('.')]
environment = 'prod'
updated = {
'proid': proid,
'environment': environment
}
updated.update(manifest)
return updated | 37dc03c7139dbf72ce58b1465e287369a7dad2ac | 683,535 |
def setup_walkers(cfg_emcee, params, level=0.1):
"""Initialize walkers for emcee.
Parameters
----------
cfg_emcee: dict
Configuration parameters for emcee.
params: asap.Parameter object
Object for model parameters.
level: float, optional
Returns
-------
ini_position... | 7a03d5f451a71f60acd64e7b22e852af99a9cefe | 683,536 |
def pack_4_4(x: int, y: int) -> int:
"""Pack two 4-bit values into an
8-bit value.
x and y must be in range 0..15 inclusive.
Result is in range 0..255 inclusive.
"""
assert 0 <= x <= 15
assert 0 <= y <= 15
return (x << 4) | y | a11b8b398b5f80b7a00437ac6e0ecf2b8e7a76aa | 683,537 |
def _GetLibMetadata(layer):
""" Return a dictionary of library-specific data found in layer."""
globalPrim = layer.GetPrimAtPath('/GLOBAL')
if not globalPrim:
raise Exception("Code generation requires a \"/GLOBAL\" prim with "
"customData to define at least libraryName. GLOBAL prim ... | d2117d0057a57eaeb2ef7ec88ec329c0d19e7848 | 683,538 |
def build_system_info(platform=None,
platform_type=None,
accel_type=None,
cpu_cores=None,
cpu_type=None,
cpu_sockets=None):
"""Information about the system the test was executed on.
Args:
platform (str... | 6fad4e0563929a249a5e8709a20198db3689c2e3 | 683,539 |
def _wcut(l, windowsize, stepsize):
"""
Parameters
l - The length of the input array
windowsize - the size of each window of samples
stepsize - the number of samples to move the window each step
Returns
The length the input array should be so that leftover samples are ignore... | 2a1bd80b8bdd9a54b7ff3899b287064ca9d0b9ca | 683,540 |
import re
def strip_spaces(string):
"""Remove white-space from a string
Parameters
----------
string: str
Returns
-------
str
"""
pattern = re.compile(r'\s+')
return re.sub(pattern, '', string) | d3f2767371b49e3c8adc64eac3f61aa790e3a430 | 683,541 |
def get_mouse_from_id(mouse_id: int):
"""because mice_id are stored as int in datafile, they must be transformed back to the original names"""
return 'M' + str(mouse_id)[:2] | 5e04a6b592f8c60660c2987e2c579b84941b89a6 | 683,542 |
import os
def get_net_driver():
"""
Return the name of the driver for the first alphabetically ordered non-virtual network interface.
Returns:
driver_name (str): name of driver (e.g. ixgbevf)
"""
try:
net_device_list = list()
# Add all non-virtual interfaces to the list an... | 300708ffcdf08a0804ff616d20add8c3077b20db | 683,544 |
def hexint_parser(arg: str) -> int:
"""Parse a hexadecimal starting with 0x into an integer."""
if not arg.startswith("0x"):
raise Exception("Received non-hex integer where hex expected")
return int(arg, 16) | 2033e0df5eac9b5e61851586d22e86d31a7f9833 | 683,545 |
def orbtell(orb):
"""Query current connection read-head position"""
return orb.tell() | 3637f996b8bdb5feed883e045c787fc23abdee45 | 683,546 |
def get_db_credentials()->dict:
"""This is a decorator function, it is use in dev to pass the hardcoded credentials in order to connect to Snowflake
Arguments:
None
Returns:
(str)
"""
return {
'POSTGRES_USER': "",
'POSTGRES_PASSWORD':"",
'POSTGRES_DB':... | 4546445262534b312ebc5b9018c73d6d09fc1c9c | 683,547 |
def eq29p4d7_p(qh, GCp, γE, γa):
"""Equation 29.4-7:
p= qh*GCp*γE*γa (lb ∕ft2)
"""
return qh * GCp * γE * γa | 911d6613a8a6e98a8202473e615320bcd4c885d2 | 683,548 |
import random
def random_bbox(config):
"""Generate a random tlhw with configuration.
Args:
config: Config should have configuration including IMG_SHAPES,
VERTICAL_MARGIN, HEIGHT, HORIZONTAL_MARGIN, WIDTH.
Returns:
tuple: (top, left, height, width)
"""
img_shape = config... | 6399f65e23648122eb28792ec13b3c26af84ae28 | 683,549 |
def get_taxid_of_user_entity_ids(cursor, unification_table, user_entity_ids):
"""
Get Tax IDs of targets using their BIANA user entity ids
"""
query_taxid = ("""SELECT TX.value, TX.type
FROM externalEntityTaxID TX, {} U
WHERE U.externalEntityID = TX.externalE... | 9b2f097722cdca87ac364c734b6e7eca41e43488 | 683,550 |
from datetime import datetime
def from_epoch(seconds):
"""Given seconds since epoch, return a datetime object
Args:
seconds: Seconds since epoch
Returns:
datetime representation of seconds since epoch
"""
return datetime.utcfromtimestamp(float(seconds)) | 308a6275431029a2594ef4585296a2847d215232 | 683,551 |
import torch
def func_attention(query, context, gamma1):
"""
query: B x T x D (text)
context: B x H x W x D (image)
T - (max) length of caption in the batch
"""
# D - size of the feature vector
# B - batch size
B, D = query.size(0), query.size(2)
H, W = context.size(1), context.siz... | 00e1cfc8a455d7fea6139a11e231afa4bcf9f1d5 | 683,552 |
import io
def get_files_from_variables(variables):
"""Takes a variables objects and looks to see if any of the values are file
objects which need to be sent separately.
:param dict variables: the variables to inspect, or ``None``.
:returns: ``(variables, files)``"""
if not variables: return vari... | 141cc5a2e80677f9a9d301f3ca62ee90029f9c5b | 683,553 |
from typing import List
from typing import Dict
from typing import Any
def convert_vars(value: List[str]) -> Dict[str, Any]: # noqa: C901
"""
Process all variables and return a dictionnary of them with the
value converted to the appropriate type.
The list of values is as follows: `key[:type]=value` ... | c4d2bbf4c17337d91c0c6af9618be0f55599bf40 | 683,554 |
def get_client_ip(request):
"""
nginx 透传客户端IP, 增加如下配置:
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR'... | f08c3d675b1dbd308c6c8886fb85b34c5fbf15a6 | 683,555 |
import select
import os
def timed_read(fds, timeout = -1):
"""Read from multiple descriptors with an optional timeout."""
# poll for I/O events
polling = select.poll()
for fd in fds:
polling.register(fd, select.POLLIN)
changed = dict(polling.poll(timeout * 1000))
# and interpret th... | 284aed539d025b85e281b29c0d256765b0f15f70 | 683,556 |
def generate_discovery_cache_key(name, ext):
""" Generate cache key for office web app hosting discovery
name: Operations that you can perform on an Office document
ext: The file formats that are supported for the action
"""
return 'wopi_' + name + '_' + ext | 8e397777f257cd2c52e54b816e8853a211297a34 | 683,557 |
def _word_feats(words):
"""
NLTK word feature generator for the NaiveBayesClassifier
"""
return dict([(word, True) for word in words]) | 19601ae61f23f1a9743443fa51d58d5a6479426d | 683,558 |
def build_machine(network=None,
machine_type=None,
preemptible=None,
service_account=None,
boot_disk_size_gb=None,
disks=None,
accelerators=None,
labels=None,
cpu_platform=None... | 6176c030c63f161343f84536bb39c05da37cd2d4 | 683,559 |
def copy_event_attributes(ev1, ev2):
"""Copy all attributes from one roxar event to another.
Args:
ev1: roxar event to copy into
ev2: roxar event to copy attributes from
Returns:
An updated version of ev1. Unaltered if the two events are not of same type.
"""
if ev1.type == e... | 27f2c8539d832a6d641cf0b91b67c348ff12a7c8 | 683,561 |
def group_by(object_list, key_function):
"""
Return dictionary of objects grouped by keys returned by
`key_function` for each element in `object_list`.
`object_list` does not need to be sorted.
>>> group_by([1, 2, 3, 4, 5], lambda x: x % 2)
{0: [2, 4], 1: [1, 3, 5]}
"""
groups = dict()... | 2dda8d965895f8b1be077d7f3e8f6b9f1f5a77be | 683,562 |
def mass_hpa_tail_boom(
length_tail_boom,
dynamic_pressure_at_manuever_speed,
mean_tail_surface_area,
):
"""
Finds the mass of a tail boom structure of a human powered aircraft (HPA), following Juan Cruz's correlations in
http://journals.sfu.ca/ts/index.php/ts/article/viewFile/760/71... | 8330b2b9c5b533acc7d2aa9b06b6bc53b796dd74 | 683,563 |
def find_first2(l, pred1, pred2):
"""
Find first occurrence in list satisfying two-step predicate.
:param l: list.
:param pred1: predicate on the list elements.
:param pred2: predicate on two list elements.
:return: index of first occurrence in list satisfying pred2(l[index-1], l[index])
or ... | 7d5ec65a573056f617c1e90d9ba980a30ece0ffb | 683,564 |
def rec_pts_noisy(rec, yds, tds):
"""
this function takes number of recieving: yards, receptions and touchdowns and returns fantasy points scored (ppr scoring)
it also prints out yds
"""
print(yds) # works here since we're inside fn
return yds*0.1 + rec*1 + tds*6 | 2951a8d339f404623ecf61948e07605346119ec3 | 683,565 |
def human_readable(delta):
"""Converts a relativedelta list to a human readable string"""
attrs = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
return ['%d %s' % (getattr(delta, attr), getattr(delta, attr) > 1 and attr or attr[:-1])
for attr in attrs if getattr(delta, attr)] | 857d619d8a171bd12140377b3354ee1ae357bc6d | 683,566 |
import time
def timing_decorator(func):
"""
Timing-Decorator for functions
"""
def wrapper(*args, **kwargs):
t1 = time.time()
result = func(*args, **kwargs)
t2 = time.time()
delta = (t2 - t1) * 1000 * 1000 # seconds
print(f"{func.__name__}:{(delta):.4f}ms")
... | 3af1479eda409390737cdfa3bb9509696386abe1 | 683,567 |
import tempfile
import os
from sys import version
import sys
def set_bin_folder(bf_user=None, append_to_python_path=True):
"""
This function set a default build folder that contains the python module compiled
by pykeops.
"""
bf_source = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'... | d26a4bbddd9133978fcba2e3c2038fb5bed50349 | 683,568 |
from datetime import datetime
def meta_from_pid(product_id):
"""Extract metadata contained in a Landsat Product Identifier."""
meta = {}
parts = product_id.split("_")
meta["product_id"] = product_id
meta["sensor"], meta["correction"] = parts[0], parts[1]
meta["path"], meta["row"] = int(parts[2... | 1f2dede4666a3183242f5089d3b917a43532f2cd | 683,570 |
import requests
def check_status(datum):
"""Check that both the url and image link are valid URLs and that the
image link isn't just a redirect.
"""
if requests.get(datum["url"], verify=False).status_code != 200:
return False
get_ = requests.get(datum["image"], verify=False)
if get_.st... | b26cb833e21f75d45402d9041bb8bae59a6009ef | 683,571 |
import os
def expect_file_to_exist(filename):
"""
Return True or False indicating whether the specified file exists
Parameters
----------
filename : string
file to check for existence
Returns
-------
True if the specified file exists; False otherwise
"""
if os.path.i... | 2a17f877211628314a2549bd237cbb7a86cac1b7 | 683,572 |
def fatorial():
""" Retorna o fatorial de um número n """
n = int(input('Digite um número: '))
if n == 1:
return 1
else:
x = n+1
for i in range(0,n):
x = n-1
f = n*x
print(f'x é {x}')
print(f'f é {f}') | 2508a6aae916ae39f507bd723fff960591b939d4 | 683,573 |
def splitquote(line, stopchar=None, lower=False, quotechars = '"\''):
"""
Fast LineSplitter.
Copied from The F2Py Project.
"""
items = []
i = 0
while 1:
try:
char = line[i]; i += 1
except IndexError:
break
l = []
l_append = l.append
... | 49fd550c7040cdccee4191d226d8d3cda27c05f5 | 683,574 |
def second_half(dayinput):
"""
second half solver:
What is the first frequency your device reaches twice?
"""
lines = dayinput.split('\n')
freq_set = {0}
total_freq = 0
while True:
for freq in lines:
total_freq += int(freq)
if total_freq in freq_set:
... | ff0354509fdbfc7911c827288449e5608013aace | 683,575 |
def recursive_find_xml_element( xmlnode, name, _nodes=None ):
"""
recursively finds all XML sub-elements with the name 'name', such as
for nd in recursive_find_xml_element( xmlnode, 'TestList' ):
pass
"""
if _nodes == None:
_nodes = []
for nd in xmlnode:
if nd.t... | 9f3a08ec3f3b3d653d7a3542394cff0fb74db9eb | 683,576 |
from typing import Callable
from typing import Union
import torch
from typing import Dict
from typing import List
from typing import Tuple
from typing import Set
from typing import Any
def _apply_to_tensors(
fn: Callable, container: Union[torch.Tensor, Dict, List, Tuple, Set]
) -> Any:
"""Recursively apply to... | 7c04c81da5626808dc9f70eba3f8882ea032798f | 683,577 |
import click
def get_user_context_obj():
"""Return user context, containing logging and configuration data.
:return: User context object (dict)
"""
return click.get_current_context().obj | 915d4307d2885100531b206842fa750d8d2cbfdc | 683,578 |
def r10s(factor: float = 1) -> float:
"""
The horizontal screw spacing on the mounting rails
of a 10-inch half rack.
"""
return 236.525 * factor | 786593f1ae9fab906e116c01fd39abd3da17a5e9 | 683,579 |
def route_conv(layer_index, module_defs):
""" find the convolutional layers connected by route layer
"""
module_def = module_defs[layer_index]
mtype = module_def['type']
before_conv_id = []
if mtype in ['convolutional', 'shortcut', 'upsample', 'maxpool', 'reorg3d']:
if module_defs[l... | 21287dcb9b543d0ad64300e214b2728a3f89efb9 | 683,580 |
import yaml
def read_experiment_config(config_file):
"""
Read experiment configuration yml file for setting up the optimization.
yml file contains the list of parameters, and whether each parameter is a fixed
parameter or a range parameter. Fixed parameters have a value specified, and range
parame... | 016448b00d77bc28156c6c32eae753f6bc75025b | 683,581 |
def get_ddy(tau, alpha_z, beta_z, g, y, dy, f):
"""
Equation [1]
:param tau: time constant
"""
return (1.0 / tau**2) * (alpha_z * (beta_z * (g - y) - tau*dy) + f) | c3eea58e413f90d52324c16803697bc518403465 | 683,582 |
def unknown_labels(dim):
"""
The labels for the "unknown" basis. Just returns an empty list.
Parameters
----------
dim : int
Dimension
Returns
-------
list
"""
return [] | 37c8afc2ffce715024a2cd497ed44532510d6a69 | 683,583 |
def get_symbols(client, limit=None):
"""
Get all symbols from Binance API
:param client
:param limit
"""
exchange_info = client.get_exchange_info()
if limit:
exchange_info = exchange_info[slice(limit)]
symbols = []
for s in exchange_info["symbols"]:
symbols.append(
... | bb1f04aad66758432fdc4135f46aa49134fc248c | 683,585 |
import torch
from typing import Sequence
from typing import cast
def project_point_cloud_to_map(
xyz_points: torch.Tensor,
bin_axis: str,
bins: Sequence[float],
map_size: int,
resolution_in_cm: int,
flip_row_col: bool,
):
"""Bins an input point cloud into a map tensor with the bins equalin... | 219731336af3891afb57663c16585514f2714795 | 683,586 |
def check_sorted(a):
"""Determines if list is sorted."""
for i, val in enumerate(a):
if i > 0 and val < a[i-1]:
return False
return True | 1c145592d0e062aef024b431842f699b82ad1644 | 683,587 |
def get_split_index_names():
"""
Return a dictionary with the property names of data splits in the WkwData object
"""
index_names = {
"train": "data_train_inds",
"val": "data_validation_inds",
"test": "data_test_inds"}
return index_names | 8d10edd6b6ef924ecce1e0d5a36bce71999affec | 683,588 |
def extract_properties_values_from_json(data, keys):
"""Extracts properties values from the JSON data.
.. note::
Each of key/value pairs into JSON conventionally referred
to as a "property". More information about this convention follow
`JSON Schema documentation <https://json-schema.o... | 91dba86eebd242d7bc1ed98fc4f71b187d50b154 | 683,591 |
def _from_pair_cliffs_to_type(cliff_ox, cliff_oz, qubit):
"""Converts a pair of Paulis Ox and Oz into a type"""
type_ox = [cliff_ox.destabilizer.phase[qubit], cliff_ox.stabilizer.phase[qubit]]
type_oz = [cliff_oz.destabilizer.phase[qubit], cliff_oz.stabilizer.phase[qubit]]
return [type_ox, type_oz] | c7bb118a8cdf5dccc96b1d7abe25dd62930a7a25 | 683,592 |
def tcl_str(string: str = '') -> str:
""" Returns Tcl string surrounded by {}
:param string: Python string.
"""
return ' {' + string + '} ' | 1da215056ee1e455bb256e3551234bc1e9100aa0 | 683,593 |
import csv
def read_user(user_file: str) -> list:
"""
Read the disney plus file and make an appropriate dictionary mapping the id to the vertex
"""
user_lst = []
with open(user_file) as csv_file:
reader1 = csv.reader(csv_file)
next(reader1)
for row in reader1:
u... | 7690f5ff359b69bb309fc8785613cf3046091ed1 | 683,594 |
import stat
import os
def get_files(path):
"""
Given the path to the .bitcoin directory, returns the sorted list of .blk
files contained in that directory
"""
if not stat.S_ISDIR(os.stat(path)[stat.ST_MODE]):
return [path]
files = os.listdir(path)
files = [f for f in files if f.sta... | a5838a03ce6564184ad03f6483352dcb51e0e654 | 683,595 |
def pgrid():
"""Return the grid of parameter for the simulations."""
sigma = 3
orders = [1, 2, 4]
grid = []
sigma_noises = [0, 0.5, 1, 1.5, 2]
for order in orders:
for sigma_noise in sigma_noises:
grid.append((sigma, order, sigma_noise))
return grid | a14387a13d6eb19d570355ea8ea2a29c83305088 | 683,596 |
def make_place_type_dictionary(all_place_types):
""" Make dictionary from list of all place types.
Dictionary keys = place types, values = number of times place type
has been added to all maps
"""
place_type_dictionary = {}
for place in all_place_types:
#split string in tuple... | b06521d57cfc1e8849373d86367098c903f09f13 | 683,597 |
def _styleof(expr, styles):
"""Merge style dictionaries in order"""
style = dict()
for expr_filter, sty in styles:
if expr_filter(expr):
style.update(sty)
return style | 0896ced4b63c149a0f42f3f6ad9f21590fa86371 | 683,598 |
from datetime import datetime
def create_identifier(hint: str = '') -> str:
"""
Can be used to create unique names for files by exploiting the uniqueness of the current date.
Be aware that if two identifiers are created during the same second they are equal!
Follows the form YYYY_MM_DD__hh_mm_ss.
... | 7f2bcae9c107f71be9e8f19235b0f6e470ac1de6 | 683,599 |
import json
def read_conf(filename):
"""Read a JSON file with a mapping between dynobj name to domain names."""
with open(filename) as file_obj:
obj = json.load(file_obj)
for name, value in obj.items():
del obj[name]
obj[str(name)] = value
return obj | b097092077e7512177e99d772b1da273024feddc | 683,600 |
import os
def symmetricKey():
"""create symmetrickey"""
pt = os.urandom(64)
encryptionKey = pt[:32]
macKey = pt[32:64]
return encryptionKey, macKey | 3eb167e234f621ae24d3bd0a0af3bae0adde9937 | 683,601 |
from typing import List
def sieve(n: int) -> List[int]:
"""
A simple implementation of the http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
:param n: Maximum value to search up to, not included.
:return: List of primes upto but not including n.
"""
all_numbers = [True] * n
for i in ran... | 844093a01834878dc3f4d388835c5489674a1f50 | 683,602 |
import csv
import re
def load_ag_data(data_source):
"""
Load raw data from the source file into data variable.
Returns: None
"""
data = []
with open(data_source, 'r', encoding='utf-8') as f:
rdr = csv.reader(f, delimiter=',', quotechar='"')
for row in rdr:
txt = "... | c0baaddcea38251ab9e01f168fff216d2c7b16a9 | 683,603 |
def isValidID(id: str) -> bool:
""" Check for valid ID. """
#return len(id) > 0 and '/' not in id # pi might be ""
return id is not None and '/' not in id | 548d0b03ff33daf6dc541a15b8b5c9c7b8e9393b | 683,604 |
def db_get(achievement_db) -> list:
"""
从数据库获取成绩单
:param achievement_db:
:return:
"""
achievement = []
for achievement_data in achievement_db:
achievement.append(achievement_data.get_dict())
return achievement | 1bb2e5e58fbcf5df3f77d5ceeeca94a3d59415c8 | 683,605 |
import math
def vershik_kerov_logan_shepp(n):
"""
Returns asymptotic value of ℓn for large n.
For a permutation σ∈Sn, let ℓ(σ) denote the maximal length of an increasing subsequence in σ.
Define ℓn = (1/n!) * ∑(σ∈Sn) ℓ(σ),
the average value of ℓ(σ) for a σ chosen uniformly at random from Sn.
... | 5534fa666a5ade4d97ed056f687e8f39947760d4 | 683,606 |
def flip_corner(corner: tuple) -> tuple:
"""
Flip a tuple of a variable amount of sides
:param corner: tuple with number of sides
:return: flipped clock-wise tuple
"""
fliped_sides: list[str] = list()
for s in corner:
if s == 'N':
fliped_sides.append('W')
elif s... | 0dd9ec10f0d330a3b54dc6250f9d511b2a6201ef | 683,609 |
def PolsLiving(t):
"""Number of policies: Living benefits"""
return 0 | 6259e93afe1fb36f52552a20b2e55b5c1d6f4905 | 683,612 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.