content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_data(database_filepath):
"""
Load data from sqlite database
Arguments:
database_filepath: path to database file
"""
engine = create_engine(f'sqlite:///{database_filepath}')
sql = 'SELECT * FROM DisasterPipeline'
df = pd.read_sql(sql, engine)
x = df.message
... | 5,319,500 |
def affine_transform(source : Image, destination : Image = None, transform : Union[np.ndarray, AffineTransform3D, AffineTransform] = None, linear_interpolation : bool = False, auto_size:bool = False) -> Image:
"""
Applies an affine transform to an image.
Parameters
----------
source : Image
... | 5,319,501 |
def plot_exp(conf,true_ps,pred_ps,scores,target,fn,outliers=[],legend=True):
"""
Plots an experiement for the distance between true locations and
predictions.
Parameters
----------
conf : numpy.ndarray
The confidence values for each point.
true_ps : numpy.ndarray
The true lo... | 5,319,502 |
def minify_css_directory2(source, target):
"""
Move CSS resources from source directory to target directory and minify. Using rcssmin.
"""
import rcssmin
if os.path.isdir(source):
if not os.path.exists(target):
os.makedirs(target)
for root, dirs, files in os.walk(sourc... | 5,319,503 |
def create_host(values):
"""Create a host from the values."""
return IMPL.create_host(values) | 5,319,504 |
def check_latitude(lat):
"""Assert that latitude is valid.
Raises:
ValueError: Latitude out of range
"""
if lat < -90 or lat > 90:
raise ValueError("Latitude (%f) out of range [-90 - 90]" % lat) | 5,319,505 |
def parse_arguments():
"""Parse the command line arguments.
Returns:
Parsed arguments.
"""
parser = argparse.ArgumentParser(description='tail for BAMs')
parser.add_argument(
'filenames',
help='BAMs on which to perform the tail operation',
nargs='*',
metavar='... | 5,319,506 |
def get_distance(lat_a, long_a, lat_b, long_b):
"""
Returns the distance, in meters, between two points
Uses the haversine formula, i.e.:
a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
c = 2 ⋅ atan2( √a, √(1−a) )
d = R ⋅ c
Keep in mind this is an "as the crow flies" type of estimation
Parameters:
... | 5,319,507 |
def format_heading(level, text):
"""Create a heading of <level> [1, 2 or 3 supported]."""
underlining = ['=', '-', '~', ][level-1] * len(text)
return '%s\n%s\n\n' % (text, underlining) | 5,319,508 |
def get_list_of_temps(temp_string):
"""
A function to process an argument string line to an array of temperatures
"""
success = True
error = ""
temps = None
arr_string = temp_string.split(",")
arr_string_len = len(arr_string)
temps = np.zeros(arr_string_len)
for i in range(arr_string_len... | 5,319,509 |
def test():
"""Test
:param:
:return:
"""
print('!! Begin Test!..')
return encrypt("vigenere","hello","lemon") | 5,319,510 |
def get_new_size_zoom(current_size, target_size):
"""
Returns size (width, height) to scale image so
smallest dimension fits target size.
"""
scale_w = target_size[0] / current_size[0]
scale_h = target_size[1] / current_size[1]
scale_by = max(scale_w, scale_h)
return (int(current_size[0]... | 5,319,511 |
def get_name_component(x509_name, component):
"""Gets single name component from X509 name."""
value = ""
for c in x509_name.get_components():
if c[0] == component:
value = c[1]
return value | 5,319,512 |
def hurst(ts):
""" the implewmentation on the blog http://www.quantstart.com
http://www.quantstart.com/articles/Basics-of-Statistical-Mean-Reversion-Testing
Returns the Hurst Exponent of the time series vector ts"""
# Create the range of lag values
lags = range(2, 100)
# Calculate the arra... | 5,319,513 |
def _bunchify(b):
"""Ensure all dict elements are Bunch."""
assert isinstance(b, dict)
b = Bunch(b)
for k in b:
if isinstance(b[k], dict):
b[k] = Bunch(b[k])
return b | 5,319,514 |
def generate_random_username():
"""Generate function
Generates a random username for anonymous users.
:returns: String with the anonymous username
"""
random.seed()
return 'anon-' + str(random.randint(0, MAX_INT_ANONYMOUS)) | 5,319,515 |
def subvolume_snapshot(source, dest=None, name=None, read_only=False):
"""
Create a snapshot of a source subvolume
source
Source subvolume from where to create the snapshot
dest
If only dest is given, the subvolume will be named as the
basename of the source
name
Na... | 5,319,516 |
def load_from_zip_file(
load_path: Union[str, pathlib.Path, io.BufferedIOBase],
load_data: bool = True,
custom_objects: Optional[Dict[str, Any]] = None,
device: Union[torch.device, str] = "auto",
verbose: int = 0,
print_system_info: bool = False,
) -> (Tuple[Optional[Dict[str, Any]], Optional[Te... | 5,319,517 |
def GetRadar(dt):
""" Simulate radar range to object at 1K altidue and moving at 100m/s.
Adds about 5% measurement noise. Returns slant range to the object.
Call once for each new measurement at dt time from last call.
"""
if not hasattr (GetRadar, "posp"):
GetRadar.posp = 0
vel = 100 ... | 5,319,518 |
def get_gin_feature(inputs, neigh_idx, k):
"""
Aggregate neighbor features for each point with GIN
GIN conv layer:
Xu, Keyulu, Weihua Hu, Jure Leskovec, and Stefanie Jegelka.
"How Powerful are Graph Neural Networks?."
arXiv:1810.00826 (2018).
Args:
inputs: (batch_size, num_vertices... | 5,319,519 |
def artPuttyCtx(q=1,e=1,aco=1,alp="string",asc="string",alc="string",acl="float",acu="float",asl="string",asm=1,bsc="string",bs="float",bra=1,brf=1,cl="string",cll="float",clu="float",clr=1,clc="float",cl1="float",cl4="[float, float, float, float]",cl3="[float, float, float]",cr="string",cf=1,cfo=1,crl="float",cru="flo... | 5,319,520 |
def gen_training_matrix(directory_path, output_file, cols_to_ignore):
"""
Reads the csv files in directory_path and assembles the training matrix with
the features extracted using the functions from EEG_feature_extraction.
Parameters:
directory_path (str): directory containing the CSV files to process.
outpu... | 5,319,521 |
def benchmark_hve_sigle_operation():
"""
"""
group_params = dict()
group_params[256] = parse_params_from_string(pairingcurves.PAIRING_CURVE_TYPE_A1_256_SAMPLE)
group_params[512] = parse_params_from_string(pairingcurves.PAIRING_CURVE_TYPE_A1_512_SAMPLE)
group_params[1024] = parse_params_from_stri... | 5,319,522 |
def five_crops(image, crop_size):
""" Returns the central and four corner crops of `crop_size` from `image`. """
image_size = tf.shape(image)[:2]
crop_margin = tf.subtract(image_size, crop_size)
assert_size = tf.assert_non_negative(
crop_margin, message='Crop size must be smaller or equal to the... | 5,319,523 |
async def test_create_entry_with_hostname(hass):
"""Test that the user step works with printer hostname."""
with patch(
"brother.Brother._get_data",
return_value=json.loads(load_fixture("brother_printer_data.json")),
):
flow = config_flow.BrotherConfigFlow()
flow.hass = hass
... | 5,319,524 |
def get_tfms(conf: DictConfig) -> Dict[str, A.Compose]:
"""
Loads in albumentation augmentations for train, valid, test
from given config as a dictionary.
"""
trn_tfms = [
load_obj(i["class_name"])(**i["params"]) for i in conf.augmentation.train
]
val_tfms = [
load_obj(i["cla... | 5,319,525 |
def load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):
"""
:param m:
:param data_portal:
:param scenario_directory:
:param subproblem:
:param stage:
:return:
"""
project_period_list, spec_params_dict = spec_determine_inputs(
scenario_directory=scenar... | 5,319,526 |
def song_line(line):
"""Parse one line
Parameters
----------
line: str
One line in the musixmatch dataset
Returns
-------
dict
track_id: Million song dataset track id, track_id_musixmatch:
Musixmatch track id and bag_of_words: Bag of words dict in
{word: cou... | 5,319,527 |
def _select_command_reply(replies: list, command: int, seq: int=None):
"""
Find a valid command reply
returns dict
"""
filtered_replies = list(filter(lambda x: x["cmd"] == command, replies))
if seq is not None:
filtered_replies = list(filter(lambda x: x["seq"] == seq, filtered_replies))... | 5,319,528 |
def remove_st_less_than(dataframe, column='ST', less_than=0.001):
"""
Remove any entry with an ST less than specified
Args:
dataframe (pandas.Dataframe): dataframe containing sensitivity analysis output
column (str): Column name, default is 'ST'
less_than (float): Remove anything le... | 5,319,529 |
def count_positives_sum_negatives2(arr):
"""
More space efficient, but not as concise as above
"""
if not arr:
return arr
count = 0
total = 0
for num in arr:
if num > 0:
count += 1
else:
total += num
return [count, total] | 5,319,530 |
def read_json(url, cached=True):
"""Read JSON content from url."""
content = read(url, cached)
return json.loads(content) if content else None | 5,319,531 |
def uninstall(lockdown: LockdownClient, bundle_id):
""" uninstall app by given bundle_id """
InstallationProxyService(lockdown=lockdown).uninstall(bundle_id) | 5,319,532 |
def main():
"""
main for expandflows.py
Usage: expandflows.py net_file linkmap_file
net_file is the network file for the full (expanded, not reduced) network
linkmap_file is the reduced network link mapping from from reducenetwork.py
Input is a flow file on stdin (renumberd from reduced netw... | 5,319,533 |
def spherical_Lloyd(radius,
num_cells,
dimension=3,
fixed='center',
approximation='monte-carlo',
approx_n=5000,
max_iter=500,
momentum=0.9,
verbose=0):
"""C... | 5,319,534 |
def get_online_version():
"""Download update info and parse it."""
page = http.default_session.get(UPDATE_URL).json()
version = page.get('tag_name', None)
if os.name == 'nt':
try:
url = next((x['browser_download_url'] for x in page['assets'] if
x['content_type'] == '... | 5,319,535 |
def log_errors(func):
"""
Helper to print errors to stderr, since an issue with
Django Debug Toolbar prevents exceptions
from threads from being logged to the console.
"""
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as... | 5,319,536 |
def test_timezone_valid(
middleware_instance,
middleware_request,
mock_timezone):
"""
If the request session has a valid timezone set, that timezone
should be activated.
"""
middleware_request.session['django_timezone'] = 'America/New_York'
middleware_instance(middleware... | 5,319,537 |
def most2tt3(fname, fname2=None):
"""
Converts MOST topo file to tt3 format.
"""
f = open(fname).readlines()
mn = f[0].split()
ncols = int(mn[0])
nrows = int(mn[1])
xll = float(f[1])
dx = float(f[2]) - xll
xll = xll - 360.
yll = float(f[nrows+ncols])
dy = float(f[nrows+... | 5,319,538 |
def first_primes(n: Integral) -> list:
"""
Generates a list of the first n primes. A cast will be used if the input is not an integer
"""
n = int(n) - 1
bank = []
track = 2
while len(bank) < n + 1:
if all(track % y for y in range(2, min(track, 11))):
bank.append(... | 5,319,539 |
def place_submission(origin_folder, sub_path, folder_name, assignment_name, score_path, ddl, record_ref = 'sis_id.txt'):
"""
move the submissions from download folder to the right folders,
also make record of the ids without submission.
"""
files = os.listdir(origin_folder) # read the file names ... | 5,319,540 |
def test_submit_script_rerunnable(scheduler, template, aiida_caplog):
"""Test that setting the ``rerunnable`` option gives a warning."""
template.rerunnable = True
scheduler.get_submit_script(template)
assert 'rerunnable' in aiida_caplog.text
assert 'has no effect' in aiida_caplog.text | 5,319,541 |
def is_ne_atom(phi: Formula):
""" Return whether the given formula is an inequality """
return isinstance(phi, Atom) and phi.predicate.symbol == BuiltinPredicateSymbol.NE | 5,319,542 |
def fact(n):
"""Return the factorial of the given number."""
r = 1
while n > 0:
r = r * n
n = n - 1
return r | 5,319,543 |
def getCoatThickCorr(f, materials, wavelength, dOpt, dTE, dTR):
"""Finite coating thickness correction
:f: frequency array in Hz
:materials: gwinc optic materials structure
:wavelength: laser wavelength
:wBeam: beam radius (at 1 / e**2 power)
:dOpt: coating layer thickness array (Nlayer x 1)
... | 5,319,544 |
def create_logdir(directory, algorithm, env_name, config_path):
"""
Create a directory inside the specified directory for
logging experiment results and return its path name.
Include the environment name (Sharpe, etc.) in the directory name,
and also copy the config
"""
experiment_dir = f"... | 5,319,545 |
def create_purchase(row):
"""Creates Purchase object based on BeautifulSoup table row object"""
name = next(itertools.islice(row.stripped_strings, 0, 1))
id = row.a['data-character-id']
price = "".join(next(itertools.islice(row.stripped_strings, 3, 4)).split())
level = len(row.find_all(src=BASE_LEVE... | 5,319,546 |
def test_is_comment(line, expected):
"""Test if line if comment."""
r = config_reader._is_comment(line)
assert r == expected | 5,319,547 |
def accuracy(predictions, targets):
"""
Computes the prediction accuracy, i.e. the average of correct predictions
of the network.
Args:
predictions: 2D float array of size [batch_size, n_classes]
labels: 2D int array of size [batch_size, n_classes]
with one-hot encoding. Ground truth la... | 5,319,548 |
def find_main(args):
"""Dump cloudtail json event records from the vault having
some value matching the globstring.
A vault file is a dictionary of "Records" containing an array
of json objects, one json object per cloudtrail event.
There is a large variety of events, each with a
different json schem... | 5,319,549 |
def prepare_intercancer_data(jx_dir):
"""
:param jx_dir:
:return:
"""
jx_counts = {}
count_df_dict = {'jx': [], 'top_x': []}
for cancer in _TCGA_ABBR:
logging.info('starting cancer {}'.format(cancer))
jx_file, flag, prev_glob = get_jx_prev_filename(jx_dir, cancer)
if... | 5,319,550 |
def load_tough_corners(fname):
"""
Load the mesh of the domain; discared by default. Use VTK_output = .TRUE. to obtain from MeshMaker_V2
fname shoud be the CORNERS file
"""
ndim = 3
verts = {}
cells = []
elemnames = []
f = open(fname,"r")
enum = -1
elem = []
for l in f:
... | 5,319,551 |
def gen_mindrecord():
"""gen mindreocrd according exactly schema"""
fw = FileWriter(MINDRECORD_FILE_NAME)
schema = {"bbox": {"type": "float32", "shape": [-1]},
"image": {"type": "bytes"},
"image_filename": {"type": "string"},
"label": {"type": "int32"},
... | 5,319,552 |
def main():
"""
solves transcription regulation model and plot results
"""
import cmepy.solver
import cmepy.recorder
m = create_model()
solver = cmepy.solver.create(
m,
sink = True,
time_dependencies = create_time_dependencies()
)
recorder ... | 5,319,553 |
def dumps(obj, bytes=False):
"""WARNING: can mutate obj"""
if bytes:
out = io.BytesIO()
else:
out = io.StringIO()
dump(obj, out)
return out.getvalue() | 5,319,554 |
def evaluate_results(model, contexts, layer_dimension, all_tasks_test_data, superposition, task_index, first_average, use_MLP, batch_size, use_PSP=False):
"""
Evaluate the results on test data with or without using superposition. Return accuracy, AUROC and AUPRC.
:param model: torch model instance
:par... | 5,319,555 |
def list_column(column, original_name):
"""Get all non nan values from column."""
if original_name == 'original_formatted':
list_filled = [[x for x in row if str(x) != 'nan'] for row in column]
else:
list_filled = [[_] for _ in column]
return list_filled | 5,319,556 |
def query_audioobject(identifier: str = None, title: str = None, contributor: str = None,
creator: str = None, source: str = None, format_: str = None, name: str = None,
date: str = None, encodingformat: str = None,
embedurl: str = None, url: str = None,... | 5,319,557 |
def test_create_new_grant_alt2(cbcsdk_mock):
"""Test creation of a grant and the profile inside it with more options."""
def respond_to_profile_grant(url, body, **kwargs):
ret = copy.deepcopy(POST_PROFILE_IN_GRANT_RESP_2)
ret['profile_uuid'] = body['profile_uuid']
return ret
cbcsdk_... | 5,319,558 |
def main(cwd=''):
"""
Main routine to call them all
Args:
cwd (str): current working directory
"""
result = {}
files = ['data/result_PFASST_1_NEW.dat', 'data/result_PFASST_2_NEW.dat', 'data/result_PFASST_4_NEW.dat',
'data/result_PFASST_6_NEW.dat', 'data/result_PFASST_12_NE... | 5,319,559 |
def configure_te_tunnel(device, tunnel_name,\
ip_config_subcmd, intf_type, intf_number):
"""creates tunnel with ip address.
Args :
device (`obj`): Device object
tunnel_name (`str`): Tunnel Name
ip_config_subcmd (`str`): subcommands for configuring ip address in tunnel
... | 5,319,560 |
def stats() -> str:
""" GET /api/v1/stats
Return:
- the number of each objects
"""
from models.user import User
stats = {}
stats['users'] = User.count()
return jsonify(stats) | 5,319,561 |
def main(args=None):
"""The main function; parses options and plots"""
# ---------- build and read options ----------
from optparse import OptionParser
optParser = OptionParser()
optParser.add_option("-n", "--net", dest="net", metavar="FILE",
help="Defines the network to rea... | 5,319,562 |
def create_split(
dataset_builder: tfds.core.DatasetBuilder,
batch_size: int,
train: bool,
dtype: tf.DType = tf.float32,
image_size: int = IMAGE_SIZE,
cache: bool = False,
) -> tf.data.Dataset:
"""Creates a split from the ImageNet dataset using TensorFlow Datasets.
Args:
dataset_builder... | 5,319,563 |
def randomString(stringLength=16):
"""Generate a random hex-string of fixed length """
# """Generate a random string of fixed length """
# letters = string.ascii_lowercase + string.ascii_uppercase + string.digits
# return ''.join(random.choice(letters) for i in range(stringLength))
return ''.join(ch... | 5,319,564 |
def get_uri():
"""
POST body:
{
domain: string representing the domain name
term: string or number referring to be used on composing the URI for the element
}
:return:
{
uri: string with the URI for the resource
}
"""
payload = request.json
uri = DomainUR... | 5,319,565 |
async def test_discovered_by_dhcp_or_discovery_adds_missing_unique_id(
hass, source, data
):
"""Test we add a missing unique id to the config entry."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: f"elks://{MOCK_IP_ADDRESS}"},
)
config_entry.add_to_hass(hass)
... | 5,319,566 |
def split_in_groups(key_func, l, continuous=True, max_group_size=None):
"""
Split the list `l` into groups according to the `key_func`.
Go over the list and group the elements with the same key value together.
If ``continuous==False``, groups all elements with the same key together regardless of wh... | 5,319,567 |
def delete_orderitem(request, id=None):
"""
Deleting orderitems in current order CART
"""
if request.method == "POST":
order_to_delete = OrderItem.objects.get(id=id)
order_to_delete.delete()
return redirect('create-order') | 5,319,568 |
def call_gspan_from_library(file_path):
""" Runs the gSpan algorithm to find frequent subgraphs """
from gspan_mining.config import parser
from gspan_mining.gspan import gSpan
# args_str = ' -s ' + str(s) + ' -l ' + str(l) + ' -u 4 -v False ' + '-p ' + str(plot) + ' ' + file_path
old_stdout = sys.s... | 5,319,569 |
def fix_external_paths():
"""fixes external paths in a maya scene
"""
from anima.env import mayaEnv
m_env = mayaEnv.Maya()
if m_env.get_current_version():
m_env.replace_external_paths() | 5,319,570 |
def test_invalid_options(
testdir, dir_value, dir_error):
"""
Make sure that pytest reports an ERROR immediatelly when invalid
options are specified.
For a file or directory which doesn't exist, "/none" path is used (see
parametrize decorator).
For a file or directory which is expected... | 5,319,571 |
def moments_dbs(data, xi_n, t_bootstrap=0.5, r_bootstrap=500, eps_stop=1.0,
verbose=False, diagn_plots=False, sort=True):
"""Double-bootstrap procedure for moments estimator.
Parameters
----------
data : (N, ) array_like
_Numpy_ array for which double-bootstrap is performed.
... | 5,319,572 |
def test_input_shapes():
"""Test the expected input and output shape."""
model, model_info = utils.load_model("test/test.tflite")
for input_detail, (_, shape) in zip(model.input_details, model_info["inputs"]):
assert tuple(input_detail["shape"][1:]) == tuple(shape)
for output_detail, (_, shape... | 5,319,573 |
def http_headers(headers=None):
"""Construct common HTTP headers from the jomiel options.
Args:
headers (dict): additional headers to use
Returns:
A headers dictionary ready to be used with `requests`
"""
result = {"user-agent": opts.http_user_agent}
if headers:
result... | 5,319,574 |
def stock_classify_board() -> dict:
"""
http://vip.stock.finance.sina.com.cn/mkt/
:return: 股票分类字典
:rtype: dict
"""
url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodes"
r = requests.get(url)
data_json = r.json()
big_dict = {}
class_n... | 5,319,575 |
def compute_rgroup_dataframe(pdb_df: pd.DataFrame) -> pd.DataFrame:
"""Return the atoms that are in R-groups and not the backbone chain.
:param pdb_df: DataFrame to compute R group dataframe from
:type pdb_df: pd.DataFrame
:returns: Dataframe containing R-groups only (backbone atoms removed)
:rtype... | 5,319,576 |
def train_top_model():
"""trains the classifier"""
train_data = np.load(open('bottleneck_features_train.npy', 'rb'))
train_labels = np.array([0] * nb_train_samples_benign + [1] * nb_train_samples_malignant)
validation_data = np.load(open('bottleneck_features_validation.npy', 'rb'))
validation_label... | 5,319,577 |
def test_nf_false_flag_toggle_lacp_passive(topology, step, main_setup):
"""Toggle 'lacp' flag to 'passive' with 'false' flag.
The source code must handle also the possibility to retrieve from OVSDB the
'lacp-fallback-ab' flag with 'false' even when by default the flag is not
present.
To disable LA... | 5,319,578 |
def find_requests(spec: Dict) -> Dict:
"""
Returns a Dict like:
{
'pets': {
'create_a_pet': {'method': 'POST', 'url': 'http://petstore.swagger.io/v1/pets'},
'info_for_a_pet': {'method': 'GET', 'url': 'http://petstore.swagger.io/v1/pets/:petId'},
'list_pets': {'met... | 5,319,579 |
def flatten_ordered(dd, separator='_', prefix='', is_list_fn=lambda x: isinstance(x, list)):
"""Flatten a nested dictionary/list
Args:
separator: how to separate different hirearchical levels
prefix: what to pre-append to the function
is_list_fn: function to determine whether to split the lis... | 5,319,580 |
def error_internal_server(error):
""" Return default JSON error message for unhandled Internal Server error """
return APIError.default_handler(APIInternalError) | 5,319,581 |
def mkdir():
"""Make directory to save files in."""
path = os.path.join(RDIR, SDIR)
if not os.path.exists(path):
os.mkdir(path) | 5,319,582 |
def FRECPX(cpu_context: ProcessorContext, instruction: Instruction):
"""Floating-point reciprocal square root (scalar form)"""
logger.debug("%s instruction not currently implemented.", instruction.mnem) | 5,319,583 |
def apply_functions(lst, functions):
"""
:param lst: list of values
:param functions: list of functions to apply to each value.
Each function has 2 inputs: index of value and value
:return: [func(x) for x in lst], i.e apply the respective function to each
of the values
"""
assert len(ls... | 5,319,584 |
def plot_graph(
codepath,
filename="graph",
directory="./",
code2in = [0,1,0,1,2,1,2,3,2,3],
code2out = [0,0,1,1,1,2,2,2,3,3],
):
""" Plot the final searched model
Args:
codepath: path to the saved .pth file, generated from the searching script.
arch_code_a: architecture code... | 5,319,585 |
def test_pipeline_index():
"""Testing something."""
df = _test_df()
drop_num1 = SilentDropStage('num1')
drop_num2 = SilentDropStage('num2')
drop_char = SilentDropStage('char')
pipeline = PdPipeline([drop_num1, drop_num2, drop_char])
assert len(pipeline) == 3
assert pipeline[0] == drop_nu... | 5,319,586 |
def rotate_image(image, rotation):
"""
Rotate the image givent eh cv2 rotation code
"""
return cv2.rotate(image, rotation) | 5,319,587 |
def location_normalize(location):
"""
Normalize location name `location`
"""
#translation_table = dict.fromkeys(map(ord, '!@#$*;'), None)
def _remove_chars(chars, string):
return ''.join(x for x in string if x not in chars)
location = location.lower().replace('_', ' ').replace('+', ' ')... | 5,319,588 |
def remove_car(garage_id, car_id): # noqa: E501
"""remove car from garage
# noqa: E501
:param garage_id: id of garage
:type garage_id: int
:param car_id: id of car
:type car_id: int
:rtype: None
"""
with get_db() as con:
cur = con.execute('''
delete from... | 5,319,589 |
def check_execute(command, timeout=None,
sandbox_profile=None, max_retries=1,
stdout=sys.stdout, stderr=sys.stderr,
**kwargs):
"""Check execute a given command.
>>> check_execute(['echo', 'Hello, World!'])
0
"""
if timeout is None:
timeo... | 5,319,590 |
def review(items, config):
"""Reviews the incoming item and returns a Review for it
:param items: a list of items that must be `Sentence` instances.
:param config: a configuration map
:returns: one or more Review objects for the input items
:rtype: list of dict
"""
# We require a list: much... | 5,319,591 |
def create(words, vector_length, window_size):
"""Create new word2vec model."""
w2vmodel = {}
for col in words.columns:
if col in words:
w2vmodel[col] = gs.models.Word2Vec([list(words[col])], min_count=1, size=vector_length,
window=window_size, seed=... | 5,319,592 |
def aga_graph(
adata,
solid_edges='aga_adjacency_tree_confidence',
dashed_edges='aga_adjacency_full_confidence',
layout=None,
root=0,
groups=None,
color=None,
threshold_solid=None,
threshold_dashed=1e-6,
fontsize=None,
node_size_sca... | 5,319,593 |
def rotate(location, direction=CLOCKWISE):
"""
Find a stronghold 120 degrees clockwise or counter-clockwise from location.
location is an tuple of x and z. direction can either be CLOCKWISE or
COUNTERCLOCKWISE.
"""
location = Point(*location)
x = simplify(cos(direction) * location.x + -sin(d... | 5,319,594 |
async def check_series_changes(client):
"""
:param client:
:return:
"""
stored_series_json: List[Dict[str, any]] = await plugin.read_data("stored_shows")
stored_tags_json: List[Dict[str, any]] = await plugin.read_data("stored_tags")
stored_profiles_json: List[Dict[str, any]] = await plugin... | 5,319,595 |
def main():
"""Run the program."""
csrf_token = get_csrf_token()
captcha_rand = get_captcha_rand()
get_captcha_img()
username = input("Enter username> ")
password = input("Enter password> ")
captcha = input("Enter CAPTCHA ({})> "
.format(os.path.abspath("captcha_img")))
... | 5,319,596 |
def checkWin():
"""Analyze the scores of the players and check win, return player1 or player2 as a string"""
if player1.score < player2.score:
return "player 2"
else:
return "player 1" | 5,319,597 |
def credits(request):
"""A view that outputs the result of a credit query."""
md = request.matchdict
model = model_from_matchdict(md)
items = items_from_matchdict(md, model)
date = date_from_matchdict(md)
return model.bulk_credits(
items,
*(s for s in md['types'].split('+') if s)... | 5,319,598 |
def dict_is_test(data):
"""helper function to check whether passed argument is a proper :class:`dict` object describing a test.
:param dict data: value to check
:rtype: bool
"""
return (
isinstance(data, dict)
and "type" in data
and data["type"] == "test"
and "id" in... | 5,319,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.