content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_list_of_encodings() -> list:
"""
Get a list of all implemented encodings.
! Adapt if new encoding is added !
:return: List of all possible encodings
"""
return ['raw', '012', 'onehot', '101'] | 6e0749eb45f85afe4e5c7414e4d23e67335ba2b5 | 709,799 |
def region_to_bin(chr_start_bin, bin_size, chr, start):
"""Translate genomic region to Cooler bin idx.
Parameters:
----------
chr_start_bin : dict
Dictionary translating chromosome id to bin start index
bin_size : int
Size of the bin
chr : str
Chromosome
start : int
... | f17b132048b0ceb4bbf2a87b77327d0d63b3fd64 | 709,800 |
import os
def get_img_name(img_path: str):
"""
Get the name from the image path.
Args:
img_path (str): a/b.jpg or a/b.png ...
Returns:
name (str): a/b.jpg -> b
"""
image_name = os.path.split(img_path)[-1].split('.')[0]
return image_name | 290bcaa133fd414874838f42c2781980954b98ef | 709,801 |
def word_distance(word1, word2):
"""Computes the number of differences between two words.
word1, word2: strings
Returns: integer
"""
assert len(word1) == len(word2)
count = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
count += 1
return count | b3279744c628f3adc05a28d9ab7cc520744b540c | 709,803 |
def CheckVPythonSpec(input_api, output_api, file_filter=None):
"""Validates any changed .vpython files with vpython verification tool.
Args:
input_api: Bag of input related interfaces.
output_api: Bag of output related interfaces.
file_filter: Custom function that takes a path (relative to client root)... | d6e888b5ce6fec4bbdb35452b3c0572702430c06 | 709,804 |
def make_loc(caller):
"""
turn caller location into a string
"""
# return caller["file"] + ":" + caller["func"] + ":" + caller["line"]
return caller["file"] + ":" + str(caller["line"]) | e0db31ffd5c76636938bfe66184f9a2a6fbca496 | 709,806 |
import difflib
import sys
def diff(file1, file2):
"""
Compare two files, ignoring line end differences
If there are differences, print them to stderr in unified diff format.
@param file1 The full pathname of the first file to compare
@param file2 The full pathname of the second file to compare
... | 980090001ce265afd736e97396315a6a3b72441e | 709,807 |
def processData(list_pc, imo):
"""
Cette fonction traite les données de getData pour écrire une seule string
prête à être copié dans le csv et qui contient toutes les lignes d'un bateau
"""
str_pc = ''
for i in range(len(list_pc)):
if list_pc[i] == 'Arrival (UTC)':
tab = list... | abb9d0a8d9f3f1ed35e4f991a3ac14e51621f104 | 709,808 |
def convertInt(s):
"""Tells if a string can be converted to int and converts it
Args:
s : str
Returns:
s : str
Standardized token 'INT' if s can be turned to an int, s otherwise
"""
try:
int(s)
return "INT"
except:
return s | a0eae31b69d4efcf8f8595e745316ea8622e24b3 | 709,809 |
import torch
def pairwise_distance(A, B):
"""
Compute distance between points in A and points in B
:param A: (m,n) -m points, each of n dimension. Every row vector is a point, denoted as A(i).
:param B: (k,n) -k points, each of n dimension. Every row vector is a point, denoted as B(j).
:return: ... | 2142b94f91f9e762d1a8b134fdda4789c564455d | 709,810 |
def get_coaches(soup):
"""
scrape head coaches
:param soup: html
:return: dict of coaches for game
"""
coaches = soup.find_all('tr', {'id': "HeadCoaches"})
# If it picks up nothing just return the empty list
if not coaches:
return coaches
coaches = coaches[0].find... | 784b355adb885b0eb4f26e72168475e1abbe4d1f | 709,811 |
import os
def save_bedtools(cluster_regions, clusters, assigned_dir):
"""
Given cluster regions file saves all bedtools sanely and returns result
:param cluster_regions:
:return:
"""
for region in cluster_regions:
output_file = "%s.%s.real.BED" % (clusters, region)
cluster_regi... | 5ef6ee5fd56eb3e6c0659b9979defcab6d9acefb | 709,814 |
import random
def about_garble():
"""
about_garble
Returns one of several strings for the about page
"""
garble = ["leverage agile frameworks to provide a robust synopsis for high level overviews.",
"iterate approaches to corporate strategy and foster collaborative thinking t... | c391891f97a7bc6df5287173aa160713cdfff675 | 709,815 |
def runningSum(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
5% faster
100% less memory
"""
sum = 0
runningSum = [0] * len(nums)
for i in range(len(nums)):
for j in range(i+1):
runningSum[i] += nums[j]
return runningSum | 393849c4aa1d23b15717748066e21abceaf6d5d9 | 709,816 |
def coerce(from_, to, **to_kwargs):
"""
A preprocessing decorator that coerces inputs of a given type by passing
them to a callable.
Parameters
----------
from : type or tuple or types
Inputs types on which to call ``to``.
to : function
Coercion function to call on inputs.
... | 61ccce8b9ffbec3e76aa9e78face469add28437e | 709,817 |
import os
import logging
def get_module_config_filename():
"""Returns the path of the module configuration file (e.g. 'app.yaml').
Returns:
The path of the module configuration file.
Raises:
KeyError: The MODULE_YAML_PATH environment variable is not set.
"""
module_yaml_path = os... | b46b7d51817b93dd6b5e026b4e8b52503b2b432a | 709,818 |
def Binary(value):
"""construct an object capable of holding a binary (long) string value."""
return value | 2a33d858b23ac2d72e17ea8ede294c5311cb74be | 709,819 |
import configparser
def parse_config_to_dict(cfg_file, section):
""" Reads config file and returns a dict of parameters.
Args:
cfg_file: <String> path to the configuration ini-file
section: <String> section of the configuration file to read
Returns:
cfg: <dict> configuration param... | 021e3594f3130e502934379c0f5c1ecea228017b | 709,820 |
def FormatRow(Cn, Row, COLSP):
"""
"""
fRow = ""
for i, c in enumerate(Row):
sc = str(c)
lcn = len(Cn[i])
sc = sc[ 0 : min(len(sc), lcn+COLSP-2) ]
fRow += sc + " "*(COLSP+lcn-len(sc))
return fRow | 53d43fc897d1db5ed3c47d6046d90548939b1298 | 709,822 |
from typing import Dict
from typing import Tuple
def _change_relationships(edge: Dict) -> Tuple[bool, bool]:
"""Validate relationship."""
if 'increases' in edge[1]['relation'] or edge[1]['relation'] == 'positive_correlation':
return True, True
elif 'decreases' in edge[1]['relation'] or edge[1]['re... | b826eb1eb7bd1e7eed7fd8577b5c04d827a75e56 | 709,823 |
def c_str_repr(str_):
"""Returns representation of string in C (without quotes)"""
def byte_to_repr(char_):
"""Converts byte to C code string representation"""
char_val = ord(char_)
if char_ in ['"', '\\', '\r', '\n']:
return '\\' + chr(char_val)
elif (ord(' ') <= cha... | e7cce729a00a7d2a35addf95eb097a3caa06bedd | 709,824 |
import math
def mag_inc(x, y, z):
"""
Given *x* (north intensity), *y* (east intensity), and *z*
(vertical intensity) all in [nT], return the magnetic inclincation
angle [deg].
"""
h = math.sqrt(x**2 + y**2)
return math.degrees(math.atan2(z, h)) | f4036358625dd9d032936afc373e53bef7c1e6e1 | 709,825 |
def _parse_disambiguate(disambiguatestatsfilename):
"""Parse disambiguation stats from given file.
"""
disambig_stats = [-1, -1, -1]
with open(disambiguatestatsfilename, "r") as in_handle:
header = in_handle.readline().strip().split("\t")
if header == ['sample', 'unique species A pairs',... | bb05ec857181f032ae9c0916b4364b772ff7c412 | 709,826 |
def clean_vigenere(text):
"""Convert text to a form compatible with the preconditions imposed by Vigenere cipher."""
return ''.join(ch for ch in text.upper() if ch.isupper()) | d7c3fc656ede6d07d6e9bac84a051581364c63a0 | 709,827 |
def f_score(r: float, p: float, b: int = 1):
"""
Calculate f-measure from recall and precision.
Args:
r: recall score
p: precision score
b: weight of precision in harmonic mean
Returns:
val: value of f-measure
"""
try:
val = (1 + b ** 2) * (p * r) / (b *... | d12af20e30fd80cb31b2cc119d5ea79ce2507c4b | 709,829 |
import os
def get_all_sub_folders(folder_path):
"""get all sub folders to list
Parameters
----------
folder_path : str
Returns
-------
list
"""
sub_folders = []
for path in os.listdir(folder_path):
full_path = os.path.join(folder_path, path)
if os.path.isdir(f... | 65afa34dadbf4cdd37ebd7feeab9aca9b03570ad | 709,830 |
def role_generator(role):
"""Closure function returning a role function."""
return lambda *args, **kwargs: role.run(*args, **kwargs) | 35dd1a54cb53a6435633c39608413c2d0b9fe841 | 709,831 |
def in_scope(repository_data):
"""Return whether the given repository is in scope for the configuration.
Keyword arguments:
repository_data -- data for the repository
"""
if "scope" in repository_data["configuration"] and repository_data["configuration"]["scope"] == "all":
return True
... | 0e521f805f69a1c6f306700680d42fbe76595c3a | 709,832 |
def eval_blocking(lamb, mu, k):
"""Finds the blocking probability of a queue.
Args:
lamb (float): The rate into the queue.
mu (float): The rate out of the queue.
k (int): Maximum number of customers able to be in the queue.
"""
rho = lamb/mu
return rho**k*((1-rho)/(1-rho**(k... | 4c1ea7f5f7984fb24c85a5c1c6c77cdbc2e1e76a | 709,834 |
def identity_show(client, resource_group_name, account_name):
"""
Show the identity for Azure Cognitive Services account.
"""
sa = client.get(resource_group_name, account_name)
return sa.identity if sa.identity else {} | 19018c895f3fdf0b2b79788547bf80a400724336 | 709,835 |
import math
def get_angle(p1, p2):
"""Get the angle between two points."""
return math.atan2(p2[1] - p1[1], p2[0] - p1[0]) | a29ea1ed74a6c071cf314d1c38c6e2f920bd1c3a | 709,836 |
def per_application():
"""
:return:
a seeder function that always returns 1, ensuring at most one delegate is ever spawned
for the entire application.
"""
return lambda msg: 1 | 7ecc568846ab484557e768ad372f4faf85238401 | 709,837 |
import requests
from bs4 import BeautifulSoup
def get_job_information(url):
""" Uses bs4 to grab the information from each job container based on the url.
Parameters
----------
url : str
Career builder url of any job
Returns
------
job_data : dict
Contains Job Name, Compa... | a5c0b53338dbacc7fe0e7c7eb91b66855968af2b | 709,838 |
def simulation_test(**kwargs):
"""Decorate a unit test and mark it as a simulation test.
The arguments provided to this decorator will be passed to
:py:meth:`~reviewbot.tools.testing.testcases.BaseToolTestCase
.setup_simulation_test`.
Args:
**kwargs (dict):
Keyword arguments to... | 56aa51374e66bb765bfc3d4da51e3254d06c0b55 | 709,839 |
def region_filter(annos, annotation):
"""filter for Region annotations.
The 'time' parameter can match either 'time' or 'timeEnd' parameters.
"""
result = []
for anno in annos:
time = annotation.get("time")
timeEnd = annotation.get("timeEnd")
for key in ['text', 'tags']:
... | 3ca4c6ba39d44370b3022f5eb17a25e0e1c9f056 | 709,840 |
import os
import subprocess
import json
def run_flow(command, contents):
"""Run Flow command on a given contents."""
read, write = os.pipe()
os.write(write, str.encode(contents))
os.close(write)
try:
output = subprocess.check_output(
command, stderr=subprocess.STDOUT, stdin=re... | 5621c321d0fb35518aabfb04f0f1b088be2bfa79 | 709,841 |
def social_bonus_count(user, count):
"""Returns True if the number of social bonus the user received equals to count."""
return user.actionmember_set.filter(social_bonus_awarded=True).count() >= count | b2469833f315410df266cd0a9b36933edb1f9ac6 | 709,842 |
def read_labels(labels_path):
"""Reads list of labels from a file"""
with open(labels_path, 'rb') as f:
return [w.strip() for w in f.readlines()] | 3ebc61c76dd1ae83b73aa8b77584661c08a51321 | 709,844 |
def _gcs_uri_rewriter(raw_uri):
"""Rewrite GCS file paths as required by the rewrite_uris method.
The GCS rewriter performs no operations on the raw_path and simply returns
it as the normalized URI. The docker path has the gs:// prefix replaced
with gs/ so that it can be mounted inside a docker image.
Args:... | 6e476860cb175dd2936cc0c080d3be1d09e04b77 | 709,845 |
def remove_apostrophe(text):
"""Remove apostrophes from text"""
return text.replace("'", " ") | c7d918e56646a247564a639462c4f4d26bb27fc4 | 709,846 |
def generate_initials(text):
"""
Extract initials from a string
Args:
text(str): The string to extract initials from
Returns:
str: The initials extracted from the string
"""
if not text:
return None
text = text.strip()
if text:
split_text = text.split(" ... | 709e53392c790585588da25290a80ab2d19309f8 | 709,847 |
def part_allocation_count(build, part, *args, **kwargs):
""" Return the total number of <part> allocated to <build> """
return build.getAllocatedQuantity(part) | 84c94ca4e1b1006e293851189d17f63fc992b420 | 709,848 |
import itertools
import os
def count_frames(directory):
"""
counts the number of consecutive pickled frames in directory
Args:
directory: str of directory
Returns:
0 for none, otherwise >0
"""
for i in itertools.count(start=0):
pickle_file = os.path.join(directory, ... | 94df6183e34a5d498493f20c03b00346bc38c50f | 709,849 |
def __parse_sql(sql_rows):
"""
Parse sqlite3 databse output. Modify this function if you have a different
database setup. Helper function for sql_get().
Parameters:
sql_rows (str): output from SQL SELECT query.
Returns:
dict
"""
column_names... | 09c61da81af069709dd020b8643425c4c6964137 | 709,850 |
import json
def load_default_data() -> dict[str, str]:
"""Finds and opens a .json file with streamer data.
Reads from the file and assigns the data to streamer_list.
Args:
None
Returns:
A dict mapping keys (Twitch usernames) to their corresponding URLs.
Each row is repre... | bfeef64922fb4144228e031b9287c06525c4254d | 709,851 |
def get_value_key(generator, name):
"""
Return a key for the given generator and name pair.
If name None, no key is generated.
"""
if name is not None:
return f"{generator}+{name}"
return None | 0ad630299b00a23d029ea15543982125b792ad53 | 709,852 |
import sys
def check_if_string(data):
"""
Takes a data as argument and checks if the provided argument is an
instance of string or not
Args:
data: Data to check for.
Returns:
result: Returns a boolean if the data provided is instance or not
"""
if sys.version_info[0] == 2... | 403aabfde1c0d2f3c1ec4610cf83a4abe644acdb | 709,853 |
def int_to_bigint(value):
"""Convert integers larger than 64 bits to bytearray
Smaller integers are left alone
"""
if value.bit_length() > 63:
return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
return value | 0f2d64887dc15d1902b8e10b0257a187ed75187f | 709,854 |
import argparse
import sys
def cmd_line_parser():
"""
This function parses the command line parameters and arguments
"""
parser = argparse.ArgumentParser(usage="python " + sys.argv[0] + " [-h] [passive/active] -d [Domain] [Options]", epilog='\tExample: \r\npython ' + sys.argv[0] + " passive -d baidu.c... | b00ed099de4f2db3c66367e07278c9c0c67f3633 | 709,855 |
def CSourceForElfSymbolTable(variable_prefix, names, str_offsets):
"""Generate C source definition for an ELF symbol table.
Args:
variable_prefix: variable name prefix
names: List of symbol names.
str_offsets: List of symbol name offsets in string table.
Returns:
String containing C source fragme... | 233c55815cf5b72092d3c60be42caffc95570c22 | 709,856 |
def perdidas (n_r,n_inv,n_x,**kwargs):
"""Calcula las perdidas por equipos"""
n_t=n_r*n_inv*n_x
for kwargs in kwargs:
n_t=n_t*kwargs
return n_t | 157825059ad192ba90991bff6206b289755ce0ba | 709,858 |
def get_user(isamAppliance, user):
"""
Get permitted features for user
NOTE: Getting an unexplained error for this function, URL maybe wrong
"""
return isamAppliance.invoke_get("Get permitted features for user",
"/authorization/features/users/{0}/v1".format(user)) | 0b2fd6c58e2623f8400daa942c83bd0757edd21f | 709,859 |
def wordcount_for_reddit(data, search_word):
"""Return the number of times a word has been used."""
count = 0
for result in data: # do something which each result from scrape
for key in result:
stringed_list = str(result[key])
text_list = stringed_list.split()
fo... | b0967aa896191a69cd1b969589b34522299ff415 | 709,860 |
def calc_precision(gnd_assignments, pred_assignments):
"""
gnd_clusters should be a torch tensor of longs, containing
the assignment to each cluster
assumes that cluster assignments are 0-based, and no 'holes'
"""
precision_sum = 0
assert len(gnd_assignments.size()) == 1
assert len(pred... | 536e25aa8e3b50e71beedaab3f2058c79d9957e3 | 709,861 |
def __get_app_package_path(package_type, app_or_model_class):
"""
:param package_type:
:return:
"""
models_path = []
found = False
if isinstance(app_or_model_class, str):
app_path_str = app_or_model_class
elif hasattr(app_or_model_class, '__module__'):
app_path_str = ap... | f08685ef47af65c3e74a76de1f64eb509ecc17b9 | 709,862 |
def convert_where_clause(clause: dict) -> str:
"""
Convert a dictionary of clauses to a string for use in a query
Parameters
----------
clause : dict
Dictionary of clauses
Returns
-------
str
A string representation of the clauses
"""
out = "{"
for key in c... | 8b135c799df8d16c116e6a5282679ba43a054684 | 709,863 |
def truncate_string(string: str, max_length: int) -> str:
"""
Truncate a string to a specified maximum length.
:param string: String to truncate.
:param max_length: Maximum length of the output string.
:return: Possibly shortened string.
"""
if len(string) <= max_length:
return strin... | c7d159feadacae5a692b1f4d95da47a25dd67c16 | 709,864 |
def negative_height_check(height):
"""Check the height return modified if negative."""
if height > 0x7FFFFFFF:
return height - 4294967296
return height | 4d319021f9e1839a17b861c92c7319ad199dfb42 | 709,865 |
import requests
def get_now(pair):
"""
Return last info for crypto currency pair
:param pair: ex: btc-ltc
:return:
"""
info = {'marketName': pair, 'tickInterval': 'oneMin'}
return requests.get('https://bittrex.com/Api/v2.0/pub/market/GetLatestTick', params=info).json() | b5db7ba5c619f8369c052a37e010229db7f78186 | 709,866 |
def hsv(h: float, s: float, v: float) -> int:
"""Convert HSV to RGB.
:param h: Hue (0.0 to 1.0)
:param s: Saturation (0.0 to 1.0)
:param v: Value (0.0 to 1.0)
"""
return 0xFFFF | 638c1784f54ee51a3b7439f15dab45053a8c3099 | 709,867 |
def clamp(minVal, val, maxVal):
"""Clamp a `val` to be no lower than `minVal`, and no higher than `maxVal`."""
return max(minVal, min(maxVal, val)) | 004b9a393e69ca30f925da4cb18a8f93f12aa4ef | 709,868 |
from functools import reduce
import operator
def product(numbers):
"""Return the product of the numbers.
>>> product([1,2,3,4])
24
"""
return reduce(operator.mul, numbers, 1) | 102ac352025ffff64a862c4c5ccbdbc89bdf807e | 709,869 |
def solution(N):
"""
This is a fairly simple task.
What we need to do is:
1. Get string representation in binary form (I love formatted string literals)
2. Measure biggest gap of zeroes (pretty self explanatory)
"""
# get binary representation of number
binary_repr = f"{N:b}"
# in... | 54b9dffe219fd5d04e9e3e3b07e4cb0120167a6f | 709,870 |
def meta_caption(meta) -> str:
"""makes text from metadata for captioning video"""
caption = ""
try:
caption += meta.title + " - "
except (TypeError, LookupError, AttributeError):
pass
try:
caption += meta.artist
except (TypeError, LookupError, AttributeError):
... | 6ef117eb5d7a04adcee25a755337909bfe142014 | 709,871 |
def notNone(arg,default=None):
""" Returns arg if not None, else returns default. """
return [arg,default][arg is None] | 71e6012db54b605883491efdc389448931f418d0 | 709,872 |
def transform_and_normalize(vecs, kernel, bias):
"""应用变换,然后标准化
"""
if not (kernel is None or bias is None):
vecs = (vecs + bias).dot(kernel)
return vecs / (vecs**2).sum(axis=1, keepdims=True)**0.5 | bb32cd5c74df7db8d4a6b6e3ea211b0c9b79db47 | 709,873 |
def swap_flies(dataset, indices, flies1=0, flies2=1):
"""Swap flies in dataset.
Caution: datavariables are currently hard-coded!
Caution: Swap *may* be in place so *might* will alter original dataset.
Args:
dataset ([type]): Dataset for which to swap flies
indices ([type]): List of ind... | 1f1941d8d6481b63efd1cc54fcf13f7734bccf8b | 709,874 |
import traceback
import os
def format_exception_with_frame_info(e_type, e_value, e_traceback, shorten_filenames=False):
"""Need to suppress thonny frames to avoid confusion"""
_traceback_message = "Traceback (most recent call last):\n"
_cause_message = getattr(
traceback,
"_cause_message... | f698739f88271bc6c15554be3750bc550f5102a7 | 709,875 |
import subprocess
def get_volumes(fn):
"""Return number of volumes in nifti"""
return int(subprocess.check_output(['fslnvols', fn])) | 67596f0583295f837197e20dd95b1c04fe705ea4 | 709,876 |
import socket
def find_available_port():
"""Find an available port.
Simple trick: open a socket to localhost, see what port was allocated.
Could fail in highly concurrent setups, though.
"""
s = socket.socket()
s.bind(('localhost', 0))
_address, port = s.getsockname()
s.close()
r... | 1d81ff79fa824bc8b38c121a632890973f0639ea | 709,877 |
import hashlib
def calculate_hash(filepath, hash_name):
"""Calculate the hash of a file. The available hashes are given by the hashlib module. The available hashes can be listed with hashlib.algorithms_available."""
hash_name = hash_name.lower()
if not hasattr(hashlib, hash_name):
raise Exception... | 975fe0a2a4443ca3abc67ed950fb7200409f2497 | 709,878 |
def default_mp_value_parameters():
"""Set the different default parameters used for mp-values.
Returns
-------
dict
A default parameter set with keys: rescale_pca (whether the PCA should be
scaled by variance explained) and nb_permutations (how many permutations to
calculate emp... | 0dcac3981154fbf0cc1fa0eeed6e83a1e1b63294 | 709,879 |
def deep_copy(obj):
"""Make deep copy of VTK object."""
copy = obj.NewInstance()
copy.DeepCopy(obj)
return copy | c00c4ff44dad5c0c018152f489955f08e633f5ed | 709,880 |
def loss_calc(settings, all_batch, market_batch):
""" Calculates nn's NEGATIVE loss.
Args:
settings: contains the neural net
all_batch: the inputs to neural net
market_batch: [open close high low] used to calculate loss
Returns:
cost: loss - l1 penalty
"""
loss = set... | fdca1bb0fa86d1972c2a0f8b1fab10183e98fb4e | 709,881 |
def group_result(result, func):
"""
:param result: A list of rows from the database: e.g. [(key, data1), (key, data2)]
:param func: the function to reduce the data e.g. func=median
:return: the data that is reduced. e.g. [(key, (data1+data2)/2)]
"""
data = {}
for key, value in result:
... | 7687521c216210badcda5ee54bd59a3bc6a234bd | 709,883 |
import os
def cleanup_path(paths, removedir=True):
""" remove unreable files and directories from the input path collection,
skipped include two type of elements: unwanted directories if removedir is True
or unaccessible files/directories
"""
checked = []
skipped = []
for ele in paths:
... | 36105a4617ea0cfffc870dd083540f81aaf56079 | 709,884 |
import os
import glob
def _findPlugInfo(rootDir):
""" Find every pluginInfo.json files below the root directory.
:param str rootDir: the search start from here
:return: a list of files path
:rtype: [str]
"""
files = []
for root, dirnames, filenames in os.walk(rootDir):
files.extend... | d3367d8f71598d1fa1303baec0d4f6803b1293b2 | 709,885 |
import os
import fnmatch
def rec_search(wildcard):
"""
Traverse all subfolders and match files against the wildcard.
Returns:
A list of all matching files absolute paths.
"""
matched = []
for dirpath, _, files in os.walk(os.getcwd()):
fn_files = [os.path.join(dirpath, fn_file)... | 47e8bd48956de87a72c996795f94b69979bf992f | 709,886 |
import os
def get_username():
"""Return username
Return a useful username even if we are running under HT-Condor.
Returns
-------
str : username
"""
batch_system = os.environ.get('BATCH_SYSTEM')
if batch_system == 'HTCondor':
return os.environ.get('USER', '*Unknown user*')
... | 1e199e7e38ed6532253ee1f7f229bb1baffc5538 | 709,888 |
def matrix2list(mat):
"""Create list of lists from blender Matrix type."""
return list(map(list, list(mat))) | 9b4b598eb33e4d709e15fd826f23d06653659318 | 709,890 |
def convert_handle(handle):
"""
Takes string handle such as 1: or 10:1 and creates a binary number accepted
by the kernel Traffic Control.
"""
if isinstance(handle, str):
major, minor = handle.split(':') # "major:minor"
minor = minor if minor else '0'
return int(major, 16)... | ed4ef5107178bd809a421e0b66c621d9bdaceef1 | 709,891 |
def get_height(img):
"""
Returns the number of rows in the image
"""
return len(img) | 765babc9fbc1468ef5045fa925843934462a3d32 | 709,893 |
def wpt_ask_for_name_and_coords():
"""asks for name and coordinates of waypoint that should be created"""
name = input("Gib den Namen des Wegpunkts ein: ")
print("Gib die Koordinaten ein (Format: X XX°XX.XXX, X XXX°XX.XXX)")
coordstr = input(">> ")
return name, coordstr | d38a728c5a6ecd1fde9500175ea5895ade8c6880 | 709,894 |
def sum_squares(n):
"""
Returns: sum of squares from 1 to n-1
Example: sum_squares(5) is 1+4+9+16 = 30
Parameter n: The number of steps
Precondition: n is an int > 0
"""
# Accumulator
total = 0
for x in range(n):
total = total + x*x
return total | 669a5aa03a9d9a9ffe74e48571250ffa38a7d319 | 709,895 |
def froc_curve_per_side(df_gt, df_pred, thresholds, verbose, cases="all"):
"""
Compute FROC curve per side/breast. All lesions in a breast are considered TP if
any lesion in that breast is detected.
"""
assert cases in ["all", "cancer", "benign"]
if not cases == "all":
df_exclude = df_g... | 6a113856a920f775be3ce652fa09d9d79fb9be00 | 709,897 |
import platform
def check_platform():
"""
str returned
"""
return platform.system() | 73e813c55807e7d84517cb7ce51ce9db34e42c23 | 709,898 |
def save(self, fname="", ext="", slab="", **kwargs):
"""Saves all current database information.
APDL Command: SAVE
Parameters
----------
fname
File name and directory path (248 characters maximum,
including the characters needed for the directory path).
An unspecified direc... | ddc79dc0f54e32d6cd96e115ad9842c1689c17b1 | 709,900 |
def _token_text(token):
"""Helper to get the text of a antlr token w/o the <EOF>"""
istream = token.getInputStream()
if istream is None:
return token.text
n = istream.size
if token.start >= n or token.stop >= n:
return []
return token.text | 0821c44eea9dfc229034bebc45211f8e6336c552 | 709,901 |
def get_dict_or_generate(dictionary, key, generator):
"""Get value from dict or generate one using a function on the key"""
if key in dictionary:
return dictionary[key]
value = generator(key)
dictionary[key] = value
return value | e31cd2b6661cf45e5345ce57d1e628174e6fd732 | 709,902 |
def createNotInConfSubGraph(graphSet, possibleSet):
"""
Return a subgraph by removing all incoming
edges to nodes in the possible set.
"""
subGraph = {}
for i in graphSet:
subGraph[i] = graphSet[i] - possibleSet
return subGraph | d3cbee9049416d7ff865306713e9a12f26717fae | 709,903 |
import random
def get_random_instance() -> random.Random:
"""
Returns the Random instance in the random module level.
"""
return random._inst | ee66055275153ce8c3eae67eade6e32e50fe1d79 | 709,904 |
import cgitb
def FormatException(exc_info):
"""Gets information from exception info tuple.
Args:
exc_info: exception info tuple (type, value, traceback)
Returns:
exception description in a list - wsgi application response format.
"""
return [cgitb.handler(exc_info)] | 733c2170a08f9880f8c191c1c6a52ee1ab455b7f | 709,905 |
def _infer_added_params(kw_params):
"""
Infer values for proplot's "added" parameters from stylesheets.
"""
kw_proplot = {}
mpl_to_proplot = {
'font.size': ('tick.labelsize',),
'axes.titlesize': (
'abc.size', 'suptitle.size', 'title.size',
'leftlabel.size', 'r... | fec171caef3562344ee86684edc944b0d08af3f3 | 709,906 |
def rename_to_monet_latlon(ds):
"""Short summary.
Parameters
----------
ds : type
Description of parameter `ds`.
Returns
-------
type
Description of returned object.
"""
if "lat" in ds.coords:
return ds.rename({"lat": "latitude", "lon": "longitude"})
el... | 18647e3bbf82bae9d02db3e965c0ddfd51ddd6dd | 709,907 |
def get_smallerI(x, i):
"""Return true if string x is smaller or equal to i. """
if len(x) <= i:
return True
else:
return False | 1588ef998f4914aa943a063546112766060a9cbf | 709,908 |
def unfold(raw_log_line):
"""Take a raw syslog line and unfold all the multiple levels of
newline-escaping that have been inflicted on it by various things.
Things that got python-repr()-ized, have '\n' sequences in them.
Syslog itself looks like it uses #012.
"""
lines = raw_log_line \
... | 9e23bdd82ac15086468a383a1ef98989aceee25e | 709,909 |
def helperFunction():
"""A helper function created to return a value to the test."""
value = 10 > 0
return value | 2c4f2e5303aca2a50648860de419e8f94581fee7 | 709,910 |
from datetime import datetime
def ts(timestamp_string: str):
"""
Convert a DataFrame show output-style timestamp string into a datetime value
which will marshall to a Hive/Spark TimestampType
:param timestamp_string: A timestamp string in "YYYY-MM-DD HH:MM:SS" format
:return: A datetime object
... | 1902e75ab70c7869686e3a374b22fa80a6dfcf1a | 709,911 |
def nl_to_break( text ):
"""
Text may have newlines, which we want to convert to <br />
when formatting for HTML display
"""
text=text.replace("<", "<") # To avoid HTML insertion
text=text.replace("\r", "")
text=text.replace("\n", "<br />")
return text | d2baf1c19fae686ae2c4571416b4cad8be065474 | 709,912 |
import requests
import logging
def get_page_state(url):
"""
Checks page's current state by sending HTTP HEAD request
:param url: Request URL
:return: ("ok", return_code: int) if request successful,
("error", return_code: int) if error response code,
(None, error_message: str)... | f7b7db656968bed5e5e7d332725e4d4707f2b14b | 709,913 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.