content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def extract_tables(sql):
"""
获取sql语句中的库、表名
:param sql:
:return:
"""
tables = list()
for i in extract_tables_by_sql_parse(sql):
tables.append({
"schema": i.schema,
"name": i.name,
})
return tables | 62,200 |
def session_wrapper(send_message=True, private=False):
"""Create a session, handle permissions, handle exceptions and prepare some entities."""
def real_decorator(func):
"""Parametrized decorator closure."""
@wraps(func)
def wrapper(update, context):
session = get_session()
... | 62,201 |
def fetch_j_league_schedule(year: int = 1992) -> pd.DataFrame:
"""Load J League schedule dataset."""
url = "https://data.j-league.or.jp/SFMS01/search"
params = {"competition_years": year, "lang": "en"}
response = requests.get(url, params=params)
attrs = {"class": "table-base00 search-table"}
na... | 62,202 |
def cancel_job(request, job_id):
"""
Cancels the current job.
:param request: Django request object.
:param job_id: id of the job.
:return: Redirects to relevant view.
"""
should_redirect = False
# to decide which page to forward if not coming from any http referrer.
# this happens... | 62,203 |
def scripts(page_content: Optional[Dict]) -> List[str]:
"""
.. _`example reference server`: https://github.com/stellar/django-polaris/tree/master/example
Replace this function with another by passing it to
``register_integrations()`` as described in
:doc:`Registering Integrations</register_integrat... | 62,204 |
def simplesubspec(signal, wlen, inc, NIS, a, b):
"""
simple spectral subtraction denoise
:param signal: noisy speech signal
:param wlen: frame length
:param inc: frame shift
:param NIS: leading unvoiced segment frame number
:param a: over subtraction factor
:param b: gain compensation factor
:return output: de... | 62,205 |
def get_possible_topologies(no_ami_fgs, no_alde_fgs):
"""
Determine possible topologies based on the FGs in BBs.
"""
if no_ami_fgs == 2 and no_alde_fgs == 3:
pos_topo = ['2p3', '4p6', '4p62', '6p9']
elif no_ami_fgs == 3 and no_alde_fgs == 3:
pos_topo = ['1p1', '4p4']
return po... | 62,206 |
def test_mech_instance_get_tools_state_silly(mock_locate, mock_fallback,
mechfile_one_entry):
"""Test get_tools_state method."""
inst = mech.mech.MechInstance('first', mechfile_one_entry)
# just for code coverage
inst.tools_state = 'running'
assert inst.g... | 62,207 |
def DownloadUsingGsutil(filename):
"""Downloads the given file from Google Storage chrome-wintoolchain bucket."""
temp_dir = tempfile.mkdtemp()
assert os.path.basename(filename) == filename
target_path = os.path.join(temp_dir, filename)
gsutil = download_from_google_storage.Gsutil(
download_from_google_... | 62,208 |
def hits(batter_id=None):
"""Get the number of hits for each historical batter. If batterId is specified, only that batter is returned.
`batter_id` is a single string UUID or list of string UUIDs.
Returns dictionary {batter_id: count}"""
params = {}
if batter_id:
params['batterId'] = prepar... | 62,209 |
def valid_axes(
draw,
ndim,
pos_only=False,
single_axis_only=False,
permit_none=True,
min_dim=0,
max_dim=None,
):
""" Hypothesis search strategy: Given array dimensionality, generate valid
`axis` arguments (including `None`) for numpy's sequential functions.
Examples from this s... | 62,210 |
def index_intellectuels() :
"""
Route permettant l'affichage de l'index des intellectuels enregistrés
:return : affichage du template index_intellectuels.html
"""
titre="index_intellectuels"
#On vérifie que la base de données n'est pas vide
intellectuells = Intellectuel.query.all()
if len(intellectuells) ==... | 62,211 |
def renumber_window(sess_name, win_id_from, win_id_to):
"""
renumber the window in session
"""
p = (sess_name + ':' + str(win_id_from), \
sess_name + ':' + str(win_id_to))
cmd = (CMD_MOVE_WINDOW % p).split(config.CMD_SEP)
util.exec_cmd(cmd) | 62,212 |
def data_file(f):
"""Get absolute path for file inside pythondata_cpu_serv."""
fn = os.path.join(data_location, f)
fn = os.path.abspath(fn)
if not os.path.exists(fn):
raise IOError("File {f} doesn't exist in pythondata_cpu_serv".format(f))
return fn | 62,213 |
def random_split_by_user(dataset,
user_id='user_id',
item_id='item_id',
max_num_users=1000,
item_test_proportion=.2,
random_seed=0):
"""Create a recommender-friendly train-test split of the p... | 62,214 |
def read_yaml(content: Text, reader_type: Union[Text, List[Text]] = "safe") -> Any:
"""Parses yaml from a text.
Args:
content: A text containing yaml content.
reader_type: Reader type to use. By default "safe" will be used
Raises:
ruamel.yaml.parser.ParserError: If there was an err... | 62,215 |
def describe_argparser():
"""
Return an argument parser for the describe function
"""
parser = argparse.ArgumentParser()
parser.add_argument("variant", help="Variant to describe, example: RV64GC")
return parser | 62,216 |
def float2binary(number, precision: int):
"""Convert float to binary
https://ryanstutorials.net/binary-tutorial/binary-floating-point.php
"""
sign_bit = 1 if number < 0 else 0
whole, dec = str(number).split(".")
whole_bit = bin(int(whole)) | 62,217 |
def _GetSheriffForTest(test):
"""Gets the Sheriff for a test, or None if no sheriff."""
if test.sheriff:
return test.sheriff.get()
return None | 62,218 |
def smooth_surround_LS_v1(p, is_obs, sd_dv):
"""
Smooth via LS on each vic in a loop.
:param p: n, n_vic
:param is_obs: n, n_vic
:param sd_dv:
:return:
x: n, n_vic, 2
"""
n, n_vic = p.shape
x0 = np.zeros((n_vic, 2))
P0 = np.zeros((n_vic, 2, 2))
P0[:] = np.eye(2) * 1e8... | 62,219 |
def read_only_sync_on_open(conn: NetworkDriver) -> None:
"""
Async cisco_asa read-only on_open callable
Args:
conn: NetworkDriver object
Returns:
N/A
Raises:
N/A
"""
conn.acquire_priv(desired_priv=conn.default_desired_privilege_level)
conn.send_command(command... | 62,220 |
def run(name, noprint, nobatch_reading):
"""
Run your producer.
In case you are running simple producer will generate jobs to pipelines and
automatically exit.
In case you are running batch producer will generate batches and automatically
start batch reading process. To disable auto-reading sp... | 62,221 |
def booth(args):
""" Booth function
Global minimum: f(1.0,3.0) = 0.0
Search domain: -10.0 <= x, y <= 10.0
"""
return (args[0] + 2*args[1] - 7)**2 + (2*args[0] + args[1] - 5)**2 | 62,222 |
def test_books_get_single_book(client):
"""."""
stubber = Stubber(app.extensions["dynamodb"].table.meta.client)
stubber.add_response(
"get_item",
{
"Item": {
"pk": {"S": "book_id#1d3e7061-c364-4966-bf39-dbe53f1377f8"},
"sk": {"S": "book_id#1d3e706... | 62,223 |
def is_cms_app(app_name):
"""
Return whether the given application is a CMS app
"""
for pat in appsettings.FLUENT_DASHBOARD_CMS_APP_NAMES:
if fnmatch(app_name, pat):
return True
return False | 62,224 |
def deeplabv3_resnet101(pretrained=False, progress=True,
num_classes=21, aux_loss=None, **kwargs):
"""Constructs a DeepLabV3 model with a ResNet-101 backbone.
Args:
pretrained (bool): If True, returns a model pre-trained on COCO train2017 which
contains the same clas... | 62,225 |
def query_model(master_df, query_sid):
"""
NOTE: Fields containing enzyme, compound PubChem sid, and SMILES string must be named
['entry', 'PubChem', 'SMILES'] respectively
"""
# get query SMILES string & pair query compound with each unique enzyme in the master DataFrame
updated_df = pair_q... | 62,226 |
def makeset(weatherpart):
"""
with open("WeatherWear/clothes.csv") as f:
reader = csv.reader(f)
next(reader)
data = []
for row in reader:
data.append(
[float(cell) for cell in row[:13]]
)
clothes = data
"""
clothes = [[0.0... | 62,227 |
def create_soup(url):
"""
Create soup object from url
"""
try:
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
return soup
except Exception as e:
print("[ERROR] Error occurred in requesting html from SBB, requested url: {} is unavailable.".f... | 62,228 |
def get_vtk_edges(vtkdata):
"""
Get mesh edges.
Parameters
----------
vtkdata : VTK object
Mesh, scalar, vector and tensor data.
Returns
-------
edges : VTK object
Mesh, scalar, vector and tensor data.
"""
edges = vtk.vtkExtractEdges()
if vtk_version < 6:
... | 62,229 |
def setup_yaml():
""" https://stackoverflow.com/a/8661021 """
represent_dict_order = lambda self, data: self.represent_mapping('tag:yaml.org,2002:map',
data.items())
yaml.add_representer(OrderedDict, represent_dict_order) | 62,230 |
def DispatchKeyForTagSpecOrNone(tag_spec):
"""For a provided tag_spec, generates its dispatch key.
If the value (or value_casei) is used, uses the first value from the
protoascii.
Args:
tag_spec: an instance of type validator_pb2.TagSpec.
Returns:
a string indicating the dispatch key, or None.
""... | 62,231 |
def test_jednostka_wydzial_time_trigger_delete_1():
"""Sprawdź, czy po zmianie jednostka_id trigger zwróci błąd.
"""
u1 = mommy.make(Uczelnia)
w1 = mommy.make(Wydzial, uczelnia=u1)
j1 = mommy.make(Jednostka, uczelnia=u1)
j2 = mommy.make(Jednostka, uczelnia=u1)
jw1 = Jednostka_Wydzial.obje... | 62,232 |
def convert_column_to_input(column: Column) -> InputField:
"""Converts a sqlalchemy column into a graphql field or input field"""
sqla_type = type(column.type)
gql_type = convert_input_type(sqla_type)
return InputField(gql_type) | 62,233 |
def rainbow_search(x, y, step):
"""Returns RGB color tuple
"""
xs = math.sin((step) / 100.0) * 20.0
ys = math.cos((step) / 100.0) * 20.0
scale = ((math.sin(step / 60.0) + 1.0) / 5.0) + 0.2
r = math.sin((x + xs) * scale) + math.cos((y + xs) * scale)
g = math.sin((x + xs) * scale) + math.c... | 62,234 |
def check_accuracy(sess, dset, x, scores, training=None):
"""
Check accuracy on a classification model.
Inputs:
- sess: A TensorFlow Session that will be used to run the graph
- dset: A Dataset object on which to check accuracy
- x: A TensorFlow placeholder Tensor where input images should be f... | 62,235 |
def check_codes(df, col, schema_codes):
"""
Get values not in list of codes.
Parameters
----------
df : pd.DataFrame
col : str
pd.DataFrame column name
schema_codes : array_like
List of allowed values
Returns
-------
array_like
Invalid values
>>> in... | 62,236 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Ring binary sensors from a config entry."""
ring = hass.data[DOMAIN][config_entry.entry_id]["api"]
devices = hass.data[DOMAIN][config_entry.entry_id]["devices"]
entities = [
RingBinarySensor(config_entry.entry_id... | 62,237 |
def orbit_number_validator(orbit_number: str) -> Optional[str]:
"""Validates the parameter to check whether it is a valid orbit number
(1 To 999999)
Args:
orbit_number::str
Value that could be orbit number either single value or a range
Returns:
val::Optional[str]
... | 62,238 |
def get_result(data: bytes):
"""start the thrift client and transform data to server through the client"""
with TransportClient(host=config.THRIFT_HOST, port=config.THRIFT_PORT) as client:
res = client.send(data)
return res | 62,239 |
def trace(verbosity: int, req_level: int, str_to_print: str = ''):
"""
Prints string only if `req_level` is not greater than `verbosity`
:param verbosity: accepted level of verbosity defined by the caller
:param req_level: required level of verbosity defined by the callee
:param str_to_print: strin... | 62,240 |
def generate_pwd(number=8):
"""
Generate radom secure password
:return: random string for pasword
"""
generater = pwgen.pwgen
password = generater(number)
return password | 62,241 |
def downloaddb(args):
"""
Download the AGFusion database from github
"""
if args.genome is not None:
if args.genome not in GENOME_SHORTCUTS:
print('Invalid genome shortcut! Use -a to see available shortcuts.')
exit()
else:
species = GENOME_SHORTCUTS[a... | 62,242 |
def check_devices_connectivity(nr: Nornir) -> bool:
"""
This function will test the connectivity to each devices
:param nr:
:return bool: True if ALL devices are reachable
"""
devices = nr.filter()
if len(devices.inventory.hosts) == 0:
raise Exception(f"[{ERROR_HEADER}] no device ... | 62,243 |
def map_remove_by_value_rank_range_relative(
bin_name, value, offset, return_type, count=None, inverted=False):
"""Create a map remove by value rank range relative operation
Create map remove by value relative to rank range operation.
Server removes and returns map items nearest to value and greate... | 62,244 |
def _has_scf_convergence_message(output_str):
""" Assess whether the output file string contains the
message signaling successful convergence of the SCF procedure.
:param output_str: string of the program's output file
:type output_str: str
:rtype: bool
"""
pattern = 'Conve... | 62,245 |
def append_measure_register(program: Program,
qubits: List = None,
trials: int = 10,
ham: PauliSum = None) -> Program:
"""Creates readout register, MEASURE instructions for register and wraps
in ``trials`` numshots.
Paramet... | 62,246 |
def configure (command = None, condition = None, options = None):
"""
Configures a new resource compilation command specific to a condition,
usually a toolset selection condition. The possible options are:
* <rc-type>(rc|windres) - Indicates the type of options the command
... | 62,247 |
def lmfitter(time, data, model, uncertainty=None, verbose=True, **kwargs):
"""Use lmfit
Parameters
----------
data: sequence
The observational data
model: ExoCTK.lightcurve_fitting.models.Model
The model to fit
uncertainty: np.ndarray (optional)
The uncertainty on the (s... | 62,248 |
def recursive_any_to_dict(anyElement):
"""
Recursive any nested type into a dict (so that it can be JSON'able).
:param anyElement: Just about any 'attrs-ized' instance variable type in Python.
:return: A dict structure
"""
if isinstance(anyElement, dict):
simple_dict = {}
for key... | 62,249 |
def make_html(ne_list, filename, start_time):
"""Save the report as a HTML file"""
#Keep list of accessible nodes
reachable_nodes=[]
#ne_list contains link status of all nodes
for item in ne_list:
#Use node names if available else use IP
try:
item[0]=n... | 62,250 |
def genListHeaders(P4Graph):
""" Generate the dictionnary of headers.
P4Graph : JSon imported file
Name, size
"""
headers = OrderedDict()
return headers | 62,251 |
def print_info(hamiltonian, zero_modes, expected_zero_modes):
"""Print the given operators for easy comparison.
"""
print('========================')
print('Hamiltonian:')
print(qy.convert(hamiltonian,'Fermion'))
print('Expected zero modes:')
qy.print_operators(expected_zero_modes)
... | 62,252 |
def colorize(s, color, bold=False, reverse=False, start=None, end=None):
"""
Colorize a string with the color given.
:param string s: The string to colorize.
:param color: The color to use.
:type color: :class:`Colors` class
:param bool bold: Whether to mark up in bold.
:param bool reverse:... | 62,253 |
def getLinkImage(pageCont):
"""
Extrae el link de la imagen de una obra contenida en pageCont
:param pageCont:
:return: Link de la imagen de la obra
"""
linksImagen = []
imagenInfo = pageCont.find(class_="section-viewer")
for img in imagenInfo.findAll('img'): # Obtención de todos los i... | 62,254 |
def keep (fn, collection):
"""
Returns a list of the non-None results of (fn item). Note, this means False
return values will be included. The function should be free of side-effects.
"""
for val in collection:
res = fn(val)
if (res is not None):
yield res | 62,255 |
def join_url(url, *paths):
"""
Joins individual URL strings together, and returns a single string.
Usage::
>>> join_url("pillar:5000", "shots")
'pillar:5000/shots'
"""
assert isinstance(url, string_type), 'URL must be string type, not %r' % url
url_parts = [url.rstrip('/')]
... | 62,256 |
def has_liked(obj, user_or_id):
"""whether the objects is liked by an user.
:param obj: Any Django model instance.
:param user_or_id: :class:`~hashup.users.models.User` instance or id.
"""
obj_type = get_obj_type_for_model(obj)
if isinstance(user_or_id, get_user_model()):
user_id = use... | 62,257 |
def get_existing_mirrored_repos(ssh_host: str) -> Dict[str, str]:
"""Gathers information about the libraries that are currently mirrored."""
run_result = subprocess.run(["ssh", ssh_host, f"bash -c 'sha256sum {GO_DEPS_WWWW_DIR}/*'"], check=True, stdout=subprocess.PIPE)
existing_mirrored_repos = {}
for l... | 62,258 |
def train():
"""Train deepSpeech for a number of steps.
This function build a set of ops required to build the model and optimize
weights.
"""
with tf.Graph().as_default(), tf.device('/cpu'):
# Learning rate set up
learning_rate, global_step = set_learning_rate()
# Create ... | 62,259 |
def plot_overlays(stat_imgs, contour_imgs, bg_img=None,
figsize=(2.5, 3), title_fontsize=32, title='', **kwargs):
"""Plots each contour_imgs as an overlay of its corresponding `stat_imgs`.
`contour_imgs` and `stat_imgs` must have the same length."""
from matplotlib import pyplot as plt
... | 62,260 |
def _int_to_riff(i: int, length: int) -> bytes:
"""Convert an int to its byte representation in a RIFF file.
Represents integers as unsigned integers in *length* bytes encoded
in little-endian.
Args:
i (int):
The integer to represent.
length (int):
The number of... | 62,261 |
def configure_scorers(config):
"""Configures the scorer objects"""
for scorer in _SCORERS_:
scorer.config = {key[len(scorer.sid) + 1:]: value for key, value in config.iteritems() if key.startswith('{0}.'.format(scorer.sid))}
logging.info('Configuring %s: %s', scorer.sid, scorer.config)
s... | 62,262 |
def read(filename):
"""
Read the file
"""
if "time" not in filename.name:
args = dict(unpack=True, comments="P", skiprows=2)
else:
args = dict(unpack=True, delimiter=":", usecols=1)
data = np.loadtxt(filename, **args)
return data | 62,263 |
def get_site_surveys(client: SymphonyClient, location: Location) -> List[SiteSurvey]:
"""Retrieve all site survey completed in the location.
Args:
location ( `pyinventory.consts.Location` ): could be retrieved from getLocation or addLocation api
Returns:
List[ `pyinventory.... | 62,264 |
def confirm(prompt=None, resp=False):
"""prompts for yes or no response from the user. Returns True for yes and
False for no.
'resp' should be set to the default value assumed by the caller when
user simply types ENTER.
>>> confirm(prompt='Create Directory?', resp=True)
Create Directory? [y]|n... | 62,265 |
def backwardEliminationP(x, y, sl):
"""Function that applies a Backward Elimination
on a model with p-values only
Arguments:
x {Array} -- The Predictors values
y {Array} -- The Dependent Variable
sl {Float} -- The Significance Level
Returns:
Array -- The New Optimized M... | 62,266 |
def sample_odb_fixture():
"""Get the fully qualified path to the sample odb file."""
return str(pathlib.Path(__file__).parent.parent / "resources" / "sample.odb") | 62,267 |
def day_of_week(df):
"""Return weekday/weekend using NHTSA convention."""
hr = df['HOUR']
day = df['DAY_WEEK']
conditions = [
(((day == 2) & hr.between(6, 23)) | day.isin([3, 4, 5]) |
((day == 6) & (hr.between(0, 17) | (hr == 24)))),
(((day == 6) & hr.between(18, 23)) |... | 62,268 |
def echo_msg(msg: str):
"""Echo a message by parameter."""
print(msg) | 62,269 |
def C_r(m_pert, m_c, a, j1, j2):
""" Constant from resonant part of disturbing function (M+D equation 8.32) """
alpha = (j2/(j2-1))**(2/3)
P = 2*np.pi*np.sqrt(a**3/m_c)
n = 2*np.pi/P
return (m_pert/m_c)*n*alpha*f_d(j1, alpha) | 62,270 |
def f_arc_range(start, stop, sides):
"""
returns a generator that yields a sequence of angles to get from start to stop for a polygon of
given number of sides.
The first number is always start. The last number will be <= stop.
angles in radians.
returns angle in radians
"""
... | 62,271 |
def to_iterable(item):
"""Converts an item or iterable into an iterable."""
if isinstance(item, six.string_types):
return [item]
elif isinstance(item, collections.Iterable):
return item
else:
return [item] | 62,272 |
def reproject(link, node, epsg):
"""
reporoject link and node geodataframes
for nodes, update X and Y columns
"""
link = link.to_crs(epsg=epsg)
node = node.to_crs(epsg=epsg)
node["X"] = node["geometry"].apply(lambda p: p.x)
node["Y"] = node["geometry"].apply(lambda p: p.y)
retur... | 62,273 |
def rpsls(name):
"""compares the result of the difference
in the player's choices and the computer
to determine and print the winner"""
player_number = name_to_number(name)
comp_number = random.randrange(0, 5)
diff = (player_number - comp_number) % 5
if (diff == 1) or (diff == 2):
... | 62,274 |
def task_project1_setup():
"""
Sets up the environment for Project 1.
"""
def invoke_create_extension_hypopg(psql):
sql = f"CREATE EXTENSION IF NOT EXISTS hypopg;"
return f'PGPASSWORD={DB_PASSWORD} psql --host=localhost --dbname={DEFAULT_DB} --username={DB_USERNAME} --command="{sql}"'
... | 62,275 |
def policy_evaluation(mdp: Mdp, policy, V, gamma, epsilon=0.01):
"""Policy evaluation algorithm.
Parameters
----------
mdp : Mdp
markov decision process instance
policy : vector
vector with action to choose on each state index
V : vector
V(s) - vector with values for eac... | 62,276 |
def conv2d(conv_input, n, kernel, stride, pad, name='', bias=True, init_method=None, scale=0.1):
"""
define simple 2d convlution
"""
if init_method == 'kaiming_normal':
std = nn.initializer.calc_normal_std_he_forward(
conv_input.shape[1], n, kernel=(kernel, kernel))
w_init =... | 62,277 |
def get_accuracy(params_repl, nbr_samples):
"""Returns accuracy evaluated on the test set."""
good = total = 0
steps = nbr_samples // batch_size #20000 // batch_size
for _, batch in zip(tqdm.trange(steps), ds_test.as_numpy_iterator()):
predicted = vit_apply_repl(params_repl, batch['image'])
is_same = p... | 62,278 |
def binary_search(ib, sequence_offset, search_range, sorted_sequence, value, right, out_dtype):
"""Common IR generator for binary search used by CPU and GPU backends.
`sorted_sequence` is a N-D Buffer whose innermost dimension we want to search for `value`,
and `search_range` is the size of the innermost d... | 62,279 |
def genbank_features_parser(input_filename):
""" Return dictionary with features contains inside a genbank file.
:param str input_filename: genbank formated file
"""
logger.warning("deprecated. please use GenBank.genbank_features_parser instead")
new_feature = {}
records = {}
feature_list =... | 62,280 |
def test_it_sbd(it_default_fixture, text, expected_sents):
"""Italian language SBD tests"""
segments = it_default_fixture.segment(text)
segments = [s.strip() for s in segments]
assert segments == expected_sents | 62,281 |
def copy2(a, b):
"""Copy a tree structure from *a* to *b*"""
for c in a:
node = CATHElement(c.tag, c.attrib, b)
b.append(node)
copy2(c, node) | 62,282 |
def delete_equipment_port_type(
client: SymphonyClient, equipment_port_type_id: str
) -> None:
"""This function deletes an equipment port type.
It can get only the requested equipment port type ID
Args:
equipment_port_type_id (str): equipment port type ID
Example:
... | 62,283 |
def guess_shape(dic):
"""
Determine data shape and complexity from Bruker dictionary.
Returns
-------
shape : tuple
Shape of data in Bruker binary file (R+I for all dimensions).
cplex : bool
True for complex data in last (direct) dimension, False otherwise.
"""
# determ... | 62,284 |
def diff_element_with_children():
"""Construct a DiffElement that has some diffs of its own as well as a child diff with additional diffs."""
# parent_element has differing "role" attribute, while "location" does not differ
parent_element = DiffElement("device", "device1", {"name": "device1"})
parent_el... | 62,285 |
def test_exists_exists(mock_get_all):
"""Return True if vsp exists in SDC."""
vsp_1 = Vsp(name="one")
vsp_1.identifier = "1234"
vsp_1.version = "1.1"
mock_get_all.return_value = [vsp_1]
vsp = Vsp(name="one")
assert vsp.exists() | 62,286 |
def cohort_preview():
"""List the samples, cases, and counts a given set of cohort filters would produce"""
code = None
response_obj = None
st_logger.write_text_log_entry(log_name, activity_message.format(request.method, request.full_path))
try:
cohort_counts = get_cohort_counts()
... | 62,287 |
def rle(inarray):
""" run length encoding. Partial credit to R rle function.
Multi datatype arrays catered for including non Numpy
returns: tuple (runlengths, startpositions, values) """
ia = np.asarray(inarray) # force numpy
n = len(ia)
if n == 0:
return (None, ... | 62,288 |
def extract_coordinates_combined(ref, trj, sel_string, out_name, start_frame=0, verbose=False):
"""
Extracts selected coordinates from several trajectory files.
Parameters
----------
ref : list of str
File names for the reference topologies.
Can read all MDAnalysis... | 62,289 |
def scale_svg(path, name, w, h, scale_factor):
"""Given an svg of size (w, h), make an svg scaled by scale_factor and save a file
in the same directory named name_WxH.svg where W = scale_factor x w and H =
scale_factor x h"""
W = scale_factor * w
H = scale_factor * h
# scaled_image = sg.SVGFigur... | 62,290 |
def fill_holes(self, layer):
"""apply the fill holes operation (key-binding: SHIFT-D)
This function applies the fill holes operation on the selected label pixels
Parameters
----------
viewer : Segmentify Viewer
Returns
-------
The procssed image
"""
labeled = extract_label(lay... | 62,291 |
def route_search(search_string):
"""
Searches through titles.
Parameters
----------
search_string : str
The search string.
Returns
-------
A JSON string that contains a list of the found titles grouped by categories.
"""
result = _search_video_titles(search_string)
... | 62,292 |
def katamari():
"""creates and returns the katamari object"""
k = Katamari()
return k | 62,293 |
def fft_fftn(*args, **kwargs):
"""Call the core fft library function fftn.
If the anfft library is used, enable 'measure' optimization.
"""
if using_fft_library == "anfft":
return fft.fftn(*args, measure=True, **kwargs)
else:
return fft.fftn(*args, **kwargs) | 62,294 |
def cmd_summary(args):
"""Generate human & machine readable summary of results"""
from autograde.cli.util import load_patched, render, list_results, merge_results, b64str, plot_fraud_matrix, \
plot_score_distribution, summarize_results
path = Path(args.result or Path.cwd()).expanduser().absolute()... | 62,295 |
def total() -> int:
"""
The total amount of space provided by the storage.
:return: The amount of storage space in Bytes.
"""
storage = psutil.disk_usage('/')
return storage.total | 62,296 |
def validate_study(study):
""" Check that a list of kf_ids for studies is given """
if len(study) != 11 or study[:3] != 'SD_':
raise ValidationError(
_('%(value)s is not a valid study kf_id'),
params={'value': study},
) | 62,297 |
def folder_name(c):
"""Return salitized name of chat to be used as a folder name."""
c = c.replace(os.path.sep, "|")
d = os.path.join(backup_dir, c)
return d | 62,298 |
def test_get_ring_centroids(pdb_df):
"""Test the function get_ring_centroids."""
ring_atom_TYR = get_ring_atoms(pdb_df, "TYR")
assert len(ring_atom_TYR) == 32
centroid_TYR = get_ring_centroids(ring_atom_TYR)
assert len(centroid_TYR) == 16
ring_atom_PHE = get_ring_atoms(pdb_df, "PHE")
assert... | 62,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.