content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def emtpy_cols(cols, rows, plas, model):
"""
Helper function for shrink_dict.
Iterates over the given model and removes all numbers of the coordinates
from the items in the model. this way there will be remaining lists of
empty cols, rows and plas. Returns a list of the 3 lists.
"""
for (x_c... | 410b13b0b0d527237c794be04f708e31cf39293f | 651,196 |
import math
def rbf_kernel(a, b, sigma=1):
"""An implementation of the radial basis function kernel.
Args:
a: A vector
b: A vector
sigma: The radius of the kernel
"""
distance = (a - b).dot(a - b)
scaled_distance = -distance / (2 * (sigma) ** 2)
return math.exp(scaled_... | 8e50c92dede84ce8201ff15e9d7c375e222cb891 | 651,197 |
def four(data):
"""
>>> four(SAMPLE)
'eafb'
"""
return list(filter(lambda d: len(d) == 4, data[0]))[0] | 517813bc0e00ad8f2f259cb3c0ec0e8ffdd3607c | 651,198 |
def _arraylen(seq):
"""If seq is None, return 0, else len(seq).
CPLEX often requires a count argument to specify the length of
subsequent array arguments. This function allows us to return a
length of 0 for None (i.e., NULL) arrays.
"""
if seq is None:
return 0
return len(seq) | 72315f9356dc90dc103c544c95f37853764bf96b | 651,199 |
def user_unicode(self):
"""Use email address for string representation of user."""
return self.email | 3b3f8de3a48643dccbc585099a59e3e55fb284e2 | 651,201 |
import argparse
def make_parser():
"""
Creates and argv parser object.
:return: ArgumentParser. with defaults if not specified.
"""
parser = argparse.ArgumentParser(description='Upload csv files to yourls database')
parser.add_argument('path', type=str, nargs='+',
hel... | 182f609d6653bd2d35e7779203d06590275d5c2a | 651,202 |
def safe_cast(type, value, safe=None):
"""try and cast the value to the type
return safe value if any exceptions occur
"""
try:
return type(value)
except Exception:
return safe | 611f60211d7980a15bc50e5525d42219311e5e15 | 651,203 |
import string
def term_frequency(term: str, document: str) -> int:
"""
Return the number of times a term occurs within
a given document.
@params: term, the term to search a document for, and document,
the document to search within
@returns: an integer representing the number of times a... | fd3650360e2f1177c5e0514c10ba908767c2daf0 | 651,204 |
import pickle
def data_pickle_load(city, year, month):
"""
Load data from a Data class object pickle. See Data.pickle_dump
Parameters
----------
city : str
The identification of the city. For a list of supported cities, see
the documentation for the Data class.
year : int
... | 4577f104526e5564dbe587dcf616b4b08a9b10ad | 651,205 |
import os
import tarfile
def extract_criteo(size, compressed_file, path=None):
"""Extract Criteo dataset tar.
Args:
size (str): Size of Criteo dataset. It can be "full" or "sample".
compressed_file (str): Path to compressed file.
path (str): Path to extract the file.
Returns:... | 5832bba8ca573bd1650220b4064d03bd6146acaf | 651,206 |
import requests
def load_with_rest_api(url):
"""
returns objects in response to get requests
:param url: address api
:return: json object
"""
# setting host/port with config.ini
try:
response = requests.get(url, timeout=(40, 40)).json()
except requests.exceptions.ReadTimeout:
... | 2fe15a9c4dafe6cbb69c521e6e69e56470e699f4 | 651,207 |
import typing
import os
def detect_periodic_tasks(root_dirpath: str) -> typing.Dict:
"""
Detect Celery periodic tasks from a root directory
"""
tasks = {}
file_path = os.path.join(root_dirpath)
for root, dirs, files in os.walk(file_path):
for filename in files:
if os.path.b... | d1e4650956b39d83567a6a6161813c2e4d5c7e1e | 651,208 |
import numpy
def hydrographOFProb(observedDischarge, modelledDischarge):
"""Returns nash sutcliffe coefficient and mean square error, probabilistic, i.e. modelled is a MC sample
observedDischarge -- numpy array
modelledDischarge -- numpy array
"""
squares = numpy.square(observedDischarge - modelledDischarg... | a130d6144c440c76f44a4e06d8a3ceb498338f83 | 651,209 |
def clean_caesar(text):
"""Convert text to a form compatible with the preconditions imposed by Caesar cipher"""
return text.upper() | 80b3c79d00efaac29463ffc1e5352b73bf4f940e | 651,211 |
def poly_derivative(poly):
"""
args: polynomial
return: derivatoive
"""
if isinstance(poly, list) is False or len(poly) == 0:
return None
derivatives = []
for i in range(len(poly)):
if type(poly[i]) != int and type(poly[i]) != float:
return
if i != 0:
... | 896c7fbcdd602749c9c1aff6ba0821116f3ee161 | 651,212 |
def overlap_view_pediatrics(
obs_df, subjid, param, include_carry_forward, include_percentiles, wt_df, ht_df
):
"""
Creates a chart showing the trajectory for an individual with all values present. All values will
be plotted with a blue line. Excluded values will be represented by a red x. A yellow dash... | ba74b06acc368c72707b084915a49c3ec9dbf8fb | 651,213 |
def make_wheel(run_setup_file):
"""
Make a wheel distribution from a given package dir.
"""
def _make_wheel(package_dir, dist_dir, *args):
return run_setup_file(
package_dir, "bdist_wheel", "--dist-dir", str(dist_dir), *args
)
return _make_wheel | fa3f8aa8d012be3ab2eb1e3788abed85ffa4bbf2 | 651,214 |
def kin2dyn(kin, density):
"""
Convert from kinematic to dynamic viscosity.
Parameters
----------
kin: ndarray, scalar
The kinematic viscosity of the lubricant.
density: ndarray, scalar
The density of the lubricant.
Returns
-------
dyn: ndarray, scalar
The ... | 0a205710ef343c2bd82afa79952a40707135e4bb | 651,215 |
import math
def get_orp(integer):
"""Get Optimal Reading Position (ORP) given ``integer``.
ORP is slightly left of center.
:param integer: length of string object to calculate ORP
:type integer: ``integer``
:returns: value of ORP
:rytpe: ``integer``
"""
percentage = 0.35
orp = int... | 81fa9bef53e643981f6929986340051f39bc4b9d | 651,217 |
def get_states_by_substrings_all(states, substrings):
"""Get state names that contain all substrings.
Parameters
----------
states : list of strings
Names of all species in the model.
substrings : list of strings
Substrings that occur in the name of the species that should be
... | bd954de5e7e4756ca02ddc7ee0507b964e0d2ddf | 651,218 |
def convert_to_bool(data):
"""
convert_to_bool converts input to bool type in python.
The following values are converted to True:
1. 'true'
2. 'yes'
3. '1'
4. 'y'
5. 1
The following values are converted to False:
1. 'false'
2. 'no'
3. '0'
4. 'n'
5. 0
:par... | 64aa3bf70cb40a436fb6e92d835c27602c824175 | 651,219 |
def is_int(obj, int_like=False):
"""
Checks for int types including the native Python type and NumPy-like objects
Args:
obj: Object to check for integer type
int_like (boolean): Check for float types with integer value
Returns:
Boolean indicating whether the supplied value is o... | faa3403e061963749032923bb3311bab9522b5d1 | 651,220 |
def format_filename(string):
"""
Converts a string to an acceptable filename
e.g. "Go! series - F1" into "Go_series_-_F1"
Parameters:
string (str): raw filename
Returns:
formatted_filename (str): formatted filename
Raises:
"""
# NOTE: Periods (.) and dashes (-) are a... | ab48073064b396d2260138b39c33c5f24ec636ce | 651,221 |
def get_ion_state(line):
"""
Get the ionization state of a `VoigtFit.Line` instance or of `line_tag` string:
ex: Line<'FeII_2374'> --> II
ex: Line<'CIa_1656'> --> I
ex: 'CIV_1550' --> IV
"""
if isinstance(line, str):
ion = line.split('_')[0]
else:
ion = line.ion
... | 403867d4b05ae3d4a42a73daa5cdfb43adea03f1 | 651,222 |
def extract_content(last_metadata_line, raw_content):
"""Extract the content without the metadata."""
lines = raw_content.split("\n")
content = "\n".join(lines[last_metadata_line + 1 :])
return content | a14514753fb7a36a01972b3c6147ccd95a507bfb | 651,224 |
def _restrict_reject_flat(reject, flat, raw):
"""Restrict a reject and flat dict based on channel presence"""
use_reject, use_flat = dict(), dict()
for in_, out in zip([reject, flat], [use_reject, use_flat]):
use_keys = [key for key in in_.keys() if key in raw]
for key in use_keys:
... | 2f9bd8dbab031150e7ca9bc78759b06e43bea1e8 | 651,225 |
import difflib
import re
def fuzzy_find(value, options):
"""Given a value and a list of options, find the one option that should
be the closest match. We first use Python's ``difflib`` to find
potential typos in exact matches, then we do a word-match using regular
expressions.
:param value: User-... | 78729fdfaca1803f9fa33d0fd25bf3f84da890d1 | 651,226 |
import binascii
def get_tflite_data(tflite_path: str) -> list:
"""
Reads a binary file and returns a C style array as a
list of strings.
Argument:
tflite_path: path to the tflite model.
Returns:
list of strings
"""
with open(tflite_path, 'rb') as tflite_model:
... | 84dbe3b0fa9dbcac777cfb585498559fb40922f4 | 651,227 |
import csv
def read_sleepasandroid_file(saa_filename):
"""
read in a SleepAsAndroid backup file and return it as a parsed list
"""
with open(saa_filename) as file:
file_as_list = list(csv.reader(file, delimiter=','))
return file_as_list | 22011c2ba784747c65c3dc47063fb486d3130785 | 651,228 |
def snake_to_pascal_case(s: str) -> str:
"""Convert a string from snake_case to PascalCase"""
if not s:
return s
return "".join(
map(
lambda segment: (segment[0].upper() + segment[1:]) if segment else segment,
s.split("_"),
),
) | c8f462ae5ebc58f520509f21913a50c0631b1cb9 | 651,229 |
import functools
def check_list_integer(func):
"""Check a list if it consists only out of integers."""
@functools.wraps
def wrap(*args, **kwargs):
checked_list = [int(i) for i in func(*args, **kwargs)]
return checked_list
return wrap | 91a41ce99fe4510204aa3f6fda56aabf51ced487 | 651,230 |
def who_create(user_id, ticket = None):
"""
Create a TTBD user descriptor from a user id name and a ticket
:params str user_id: user's name / ID
:params str ticket: (optional) ticket for the reservation
:returns: (str) user id descriptor
"""
if ticket != None and ticket != "":
retu... | 8ba325d58d8c32d5e40fcf84cebedf4270597510 | 651,231 |
import pandas
from typing import OrderedDict
def make_groups_table(analysis_results):
"""Return a Pandas dataframe indicating which elements belong to each group.
"""
return pandas.DataFrame.from_records(
[
OrderedDict(
[
("Group", group),
... | 7295f536e86bd16bd47783900391e742a73abc06 | 651,232 |
import subprocess
def check_if_already_running():
"""Return whether we're already running: that indicates huge problems."""
command = "ps ax"
sub = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
... | c0855e2ee25fc073ba39f6ea2073b54ac99d48be | 651,233 |
def skin_myo():
"""Create a test fixture for skin myopithelioma"""
return {
"id": "normalize.disease:Skin Myoepithelioma",
"type": "DiseaseDescriptor",
"disease_id": "ncit:C167370",
"label": "Skin Myoepithelioma",
"alternate_labels": ["Cutaneous Myoepithelioma"],
} | 7b6833909c283603d90222202c424bf3bd090b05 | 651,234 |
def get_loc_offset(box_gt, box_anchor):
"""Computes the offset of a groundtruth box and an anchor box.
Args:
box_gt (array): groundtruth box.
box_anchor (array): anchor box.
Returns:
float: offset between x1 coordinate of the two boxes.
float: offset between y1 coordinate o... | 9e9d6c25d35d02c93594791e412c3ac058cacdcd | 651,235 |
def vfs_construct_path(base_path, *path_components):
"""Mimics behavior of os.path.join on Posix machines."""
path = base_path
for component in path_components:
if component.startswith('/'):
path = component
elif path == '' or path.endswith('/'):
path += component
... | 6e99c3596eaf94beea58ac79d5b8f861617bc918 | 651,236 |
from typing import Tuple
from typing import Optional
from typing import List
import subprocess
import sys
import json
def load_python_module_info(module: str, interpreter: str) -> Tuple[str, Optional[List[str]]]:
"""Return tuple (module path, module __all__) for a Python 2 module.
The path refers to the .py/... | 4a426c40644c7a490535d9a7e0a913fd89d44f51 | 651,237 |
def sum_scores(scores, query):
"""Sums all the scores"""
return sum(scores.values()) | d55367d029cf7e5e83cb268a5db229694ea705f3 | 651,238 |
def deep_getattr(obj, attr_string, default=None):
"""
Returns the attribute of `obj` at the dotted path given by `attr_string`
If no such attribute is reachable, returns `default`
>>> deep_getattr(cass, "cluster")
<cassandra.cluster.Cluster object at 0xa20c350
>>> deep_getattr(cass, "cluster.m... | a4450d5441f6a67bab7aa6c13977b4921dfceacd | 651,239 |
def start_time_offset(df):
"""
Return the offset to start a tumbling window from the first timestamp of the DataFrame.
:param df:
Spark DataFrame object with timestamp data
:return:
number of seconds
"""
## notice: the resulting offset must be smaller than the tumbling window
... | cc3fbfa5900983449f10993f2591dd762cbcaa68 | 651,240 |
from typing import List
def funkcia2(cisla: List[int]) -> List[int]:
"""Vyfiltruj iba čísla delitelné 3 alebo 5.
>>> funkcia2([7, 12, 35, 15, 45, 16, 18])
[12, 35, 15, 45, 18]
"""
# 1. riešenie
vysledok = []
for i in range(0,len(cisla)):
if(cisla[i] % 3 == 0) or (cisla[i] % 5 == 0)... | ea84724461e88a5b3cdab45058ae721f289479af | 651,241 |
def evaluate(model, val_loader):
"""
Evaluate the val loss of the model we trained.
Parameters
----------
model : LR model we trained
val_loader : DataLoader
Results
-------
dictionary
"""
outputs = [model.validation_step(batch) for batch in val_loader]
ret... | 34929780b131bdbfe70d6ade0231c995b4ba1d6a | 651,242 |
import requests
def get_activity_streams_json(activity_id, access_token, types=None):
"""Get streams (time series) for a particular activity.
https://developers.strava.com/docs/reference/#api-Streams-getActivityStreams
`stravalib` implementation for reference:
`streams = client.get_activity_streams(id)`
... | 1da3ad64f274d86b42ea367575f64ac126ddf710 | 651,243 |
def get_duplicate_value(sequence):
"""
O(n) - time
O(n) - space
"""
# keep track of visited numbers
visited = set()
for number in sequence:
# if you encounter a number that has already been visited, then that's the repeated number
if number in visited:
return n... | 8a417cc319fe7125d87268165b764c2e8a5ce14a | 651,244 |
import os
def get_output_file(args, input_file, stations):
"""
Retrieve the output file.
If the file isn't specified explicitly via command line arguments,
construct the output file based on the input file.
"""
if args.output_file:
return args.output_file
if args.fl_out:
r... | 9aabf9e513e4280bc641ca9dc0f30397ff46f973 | 651,245 |
from typing import List
def __has_term_from_list__(text: str, string_list: List[str]) -> bool:
"""
Check if a string contains an item in a list
"""
for item in string_list:
if item in text:
return True
return False | 90d3996989b3e19f046cca8d4835a1bcb6ee963c | 651,247 |
def currency_postprocess(txt):
"""Modify wrong predictions for '.'&',' in currency.
params:
- txt (str): predict text
return:
- txt_copy (str): modified text
"""
txt_len = len(txt)
if txt_len > 4 and txt.isdigit():
is_negative = False
if txt[0] == '-':
txt... | dff008fadfa83b93c650d8c152c7fbbd9e2e48ee | 651,248 |
import re
def extract_udf_name(udf_path):
"""
Parse out the name of the UDF from the SQL DDL
:param udf_path: Path to the UDF DDL .sql file
:return: Name of the UDF
"""
with open(udf_path) as udf_file:
udf_sql = udf_file.read()
udf_sql = udf_sql.replace('\n', ' ')
pattern = re... | 5acb393386e7a9ed3d9b9e7fcca9810ac50344a7 | 651,250 |
import json
def lerArquivoJSON(caminho_arquivo):
"""
Retorna conteúdo de um arquivo JSON de comandos SQL, delegando tratamento para bloco de função reservado
:param caminho_arquivo:
:return: data (JSON)
"""
with open(caminho_arquivo, "r") as read_file:
data = json.load(read_file)
... | 2cfdd872295a244fb2a83f6b287a954e806da829 | 651,251 |
def unit_to_pc_sparse(tensor):
""" From b[0,1] to b[-1,1] or [0,1] to r[-1,1] """
tensor[tensor == 0] = -1
return tensor | e4d3974036517c3ca2ddca01cfa6b36305601e61 | 651,252 |
import tempfile
def dirname():
"""Return temporary log file directory name.
"""
return tempfile.gettempdir() | e5ba65050a01cda3ff67c9e7787f89170efb3e4a | 651,253 |
def split_thousands(s, tSep='\'', dSep='.'):
"""
Splits a number on thousands.
http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/
>>> split_thousands(1000012)
"1'000'012"
"""
# Check input #
if s is None: return 0
# Check for int #
if ... | f513d2e02a8c9db255c1dbb5f127b4ffeb19a8f9 | 651,254 |
import calendar
def days_in_year(year: int) -> int:
"""Returns the number of days in the year
Args:
year (int): The year.
Returns:
int: The number of days in the year.
"""
return 366 if calendar.isleap(year) else 365 | b8a03d7bca79c3513ac4d278028b6c65b4fc3329 | 651,255 |
def extract_output(out):
"""
Extracts output for one filing unit in out and
returns extracted output as a dictionary.
Parameters
----------
out: pandas DataFrame row containing tc --dump output for one filing unit
Returns
-------
ovar: dictionary of output variables indexed from 1 ... | 1e4ebbfb096c4d76eaad20457075dbf49d4fe0bf | 651,256 |
def _get_subclasses(cls):
"""Get subclasses of passed in class and return a dictionary of them"""
return {subclass.__name__: subclass for subclass in cls.__subclasses__()} | 876e9e88d1eb0a3717e72f7ed4d4c11c90d07365 | 651,257 |
def help(command=""):
"""
Return a help manual to slack, which helps the user understand how to use a command.
@params:
input -> A specific command that the user want to look for. Default is "",
which would lead to an explanation of all command.
"""
command = command.lower()... | 87551fdde53b045343143f9116ec4d9c239d3e9c | 651,258 |
import os
import sys
import time
def open_logfile(filename, mode='a'):
"""Open the named log file in append mode.
If the file already exists, a separator will also be printed to
the file to separate past activity from current activity.
"""
filename = os.path.expanduser(filename)
filename = os... | 62ca68aec30ed89d5dea75961a311756fffc57e4 | 651,259 |
def _filter_metadata(metadata, **kwargs):
"""Filter metadata before return it to api.
Some metadata fields are not json compatible or
only used in db/api internally.
We should strip these fields out before return to api.
"""
if not isinstance(metadata, dict):
return metadata
filtere... | 2718c9dd85d042ea751e6b47a79613d699b59f9a | 651,261 |
from typing import Dict
def set_type_sex_effect(d_ : Dict[str,float], tp: str, sex: str,
t_M: float, mu_X0: float, mu_Y0: float
) -> Dict[str,float]:
"""Set type effect.
Returns:
alpha_X, alpha_Y and beta was added.
"""
d = d_.copy()
d["alph... | 9ba030f5df670c5da842d356746fd22e20e2d838 | 651,262 |
from typing import Tuple
from typing import Dict
def load_k8s_secrets() -> Tuple[Dict[str, str], str]:
"""
Loads secrets needed to access K8s resources.
Returns:
headers (dict): Headers with K8s access token
verify (str): Path to certificate
"""
with open("/var/run/secrets/kuberne... | 8a69b7ee8089cb6affe94a6ca84cd9a4064db388 | 651,263 |
import os
def loadcorrlist(corrlistfile):
"""
load corr file list to distinguish male and female
1 is female, 2 is male
"""
sexdict = {}
with open(corrlistfile) as f:
for line in f:
line = line.strip()
basename = os.path.basename(line)
sex = basename... | 3556b54032fb5c5e2d24faefe9d8cf421afc79b4 | 651,264 |
import random
def char_mlm_mask_random_words(tokens, max_predictions_per_seq=38, masked_lm_prob=0.20):
"""
Masks tokens using a algorithm designed for character level masking. The idea is to ensure groups and dense clusters of characters as masked so that the task won't be too easy.
:param tokens: tokeni... | 530224620806ed1ded43bd2b586d4cc8b3fdfc59 | 651,265 |
def delimit(delimiters, content):
"""
Surround `content` with the first and last characters of `delimiters`.
>>> delimit('[]', "foo")
[foo]
>>> delimit('""', "foo")
'"foo"'
"""
if len(delimiters) != 2:
raise ValueError(
"`delimiters` must be of length 2. Got %r" % de... | a393e2a8330c05d29855505fe679bfda4665500f | 651,266 |
import os
def save_apk(raw_dir, package, apk):
"""Save apk bytecode to filesystem
:param raw_dir: path to class raw directory
:param apk: APK package bytes
:returns: filename of APK
"""
apk_fn = os.path.join(raw_dir, f'{package}.apk')
apk_fp = open(apk_fn, 'wb')
apk_fp.write(apk)
... | 0dec56f111d74a82845bc54eaa1f76cf4deaff61 | 651,267 |
import time
def convert_timestamp(s):
"""
convert the N1MM+ timestamp into a python time object.
"""
return time.strptime(s, '%Y-%m-%d %H:%M:%S') | 6a1ebb40324a672c2d37fb612ed77c29e47e959c | 651,269 |
def check_coord_types(ds_processed, expected_types):
"""
Checks that processed dataset consists of coordinates
of expected data types.
"""
[exp_type_dim, exp_type_dim_value, exp_type_latlon, exp_type_time] = expected_types
time_types_pass = (isinstance(ds_processed['time'].values[0], exp_type_t... | 2f52360241cc8d035a18770e027bdd4db9757bf8 | 651,271 |
def annotation_filter(annotations, condition):
"""
Filter annotations.
`annotations`: the annotations to filter
`condition`: the filter callback
return: the filtered annotations
"""
filtered = dict()
for (key, value) in annotations.items():
if condition(key, value):
f... | 517e19ab9888964d77326a8bec8f4d469e22bc10 | 651,272 |
def adjacency_to_edges(nodes, adjacency, node_source):
"""
Construct edges for nodes based on adjacency.
Edges are created for every node in `nodes` based on the neighbors of
the node in adjacency if the neighbor node is also in `node_source`.
The source of adjacency information would normally ... | d593b4acd2b6f7553d6b9677209422ee665bc2d0 | 651,274 |
import requests
def follow_shortlinks(shortlinks):
"""Follow redirects in list of shortlinks, return dict of resulting URLs"""
links_followed = {}
for shortlink in shortlinks:
url = shortlink
request_result = requests.get(url)
redirect_history = request_result.history
# his... | a186b8690074128f037c0f38e9b239c755f6bc7c | 651,275 |
def list_all():
"""Returns list of all available pets."""
return ['dog', 'cat'] | a0b1660a3ab96e226b21ab3199d4e1d8b834f4cb | 651,276 |
from typing import Union
from pathlib import Path
from typing import Tuple
import shlex
def get_emittances_from_madx_output(madx_output_file: Union[str, Path], to_meters: bool = False) -> Tuple[float, float, float]:
"""
Parse MAD-X output file and return the X, Y and Z emittances from the output of the last c... | 412f4933c1d2190c397d124e6026ddd3d946fb72 | 651,277 |
def parse_by_integration(sensors):
"""Returns a list of devices that can be integrated."""
can_integrate = []
for sensor in sensors.values():
if sensor.get('integrate'):
can_integrate.append(sensor)
return can_integrate | 7aa6abd786949dc293668ef17d149f752fb716de | 651,278 |
import configparser
def get_config(config_path):
"""
Get config data
:param config_path: filepath of config ini file
:return: instance of ini config file
"""
config = configparser.ConfigParser()
config.read(config_path)
return config | 25de6636666097e501a6c6f51e68b4cab10cb3aa | 651,279 |
def as_int(attribute):
"""
Treat attribute as int if it looks like one.
"""
try:
return int(attribute)
except ValueError:
return attribute | 454eca7803a17c95415ffef3ce19c714c85fb976 | 651,280 |
def getCellByPath(rc,output,outerr,parseParamList,Logger):
"""
Returns the cell to which a file or directory belongs
"""
cellname=""
return cellname | a8168e4cfd813d555e98d1c122bd32763535c750 | 651,282 |
import subprocess
def interpreter_version(interpreter):
"""
Get the version from the python interpreter
"""
version = subprocess.check_output([interpreter, '--version'], stderr=subprocess.STDOUT).decode(errors='ignore').strip().split()[-1] # nosec
return version | 22fe49c251811672619b2b82ffcb88b0a6aeee7a | 651,283 |
def cubic_rbf(r, kappa):
"""
Computes the Cubic Radial Basis Function between two points with distance `r`.
Parameters
----------
r : float
Distance between point `x1` and `x2`.
kappa : float
Shape parameter.
Returns
-------
phi : float
Radial basis function... | 0c5192d2108834a0e82dcbe8a038d9fc720eb318 | 651,284 |
def _WX(s, wx):
"""Returns TRUE if s contains string wx"""
if wx == '':
return False
# special case for blowing/drifting snow
ix = s.find(wx)
if wx == 'SN' and ix > 1:
if s[ix-2:ix] in ('BL', 'DR'):
return False
return ix >= 0 | e1f236ec64d339e917402dc3511831015b0ca334 | 651,286 |
def add_payments(row):
"""Add payment method."""
payments = row['payment_gateway_names']
for i in range(len(payments)):
row['payment_method_' + str(i)] = payments[i]
return row | c0faa34ffd6af7ab7ef2cce912f6bb1d16e21b51 | 651,287 |
def div(a:int, b:int)->float:
"""
This function is used to multiply two numbers
# params
a: int , Number 1
b: int , Number 2
"""
if b == 0:
raise ValueError("Zero se divide karega.. bhagwan h??")
return a/b | 73e23049794daa8607946b20f4722a242d280c44 | 651,288 |
def suggestDType(x):
"""Return a suitable dtype for x"""
if isinstance(x, list) or isinstance(x, tuple):
if len(x) == 0:
raise Exception('can not determine dtype for empty list')
x = x[0]
if hasattr(x, 'dtype'):
return x.dtype
elif isinstance(x, float):
... | 3a854800589fbfa60bd044b3221400e35e59bdbf | 651,289 |
def ndbpprint(model, level=1):
"""
Pretty prints an `ndb.Model`.
"""
body = ['<', type(model).__name__, ':']
values = model.to_dict()
for key, field in model._properties.iteritems():
value = values.get(key)
if value is not None:
body.append('\n%s%s: %s' % (
' '.join([' ' for idx in range... | 5b1a5c06cc22bb9886e4e45da872dfd2bd02f359 | 651,290 |
from typing import Any
from typing import List
def wrap(item: Any) -> List[Any]:
"""Ensures that the input is either a list, or wrapped in a list. Returns []
for None.
"""
if item is None:
return []
if isinstance(item, list):
return item
return [item] | 9e1bc807e1b235b0f24e2a93787c11f704d954f5 | 651,291 |
def polynomial_hash(string, a, m):
"""
Написать функцию, вычисляющую хеш строки s.
В данной задаче необходимо использовать в качестве значений
отдельных символов их коды в таблице ASCII.
Полиномиальный хеш.
"""
n = len(string)
current_hash = {}
if n < 100:
result = 0
... | 55637b9dad81012009a9825b8ec6b8bb4cb8dd3c | 651,292 |
import os
def disable_cudnn_autotune(func):
"""Disable autotuning during the call to this function.
Some tests want to base assertions on a graph being isomorphic with a copy.
To ensure this, this decorator disables autotuning.
Args:
func: Function to run with CuDNN autotuning turned off.
Returns:
... | 229b6d714b302dcda52530f9335e44d6043959fb | 651,295 |
def _histplot_mpl_op(values, values2, rotated, ax, hist_kwargs):
"""Add a histogram for the data to the axes."""
if values2 is not None:
raise NotImplementedError("Insert hexbin plot here")
bins = hist_kwargs.pop("bins")
ax.hist(values, bins=bins, **hist_kwargs)
if rotated:
ax.set_... | 98d8a73f913583f55fbc5cfe9b0830d5e8790f8f | 651,296 |
def series_sum(n):
"""Sum of first nth term in series and return float value."""
total_series = 0.00
for x in range(n):
total_series += float(1) / (1 + (x * 3))
total_series_decimal = ('{0:.2f}'.format(total_series))
return total_series_decimal | d383b32638ef113d581cac6e30e619956e181961 | 651,297 |
def data_paper_all(list_data):
"""
:param list_data: list - 需处理数据列表
:return: list - 元胞数组列表
:describe: 对数据列表处理, 生成返回元胞数组列表
"""
author = {}
source = {}
time = {}
title = {}
collaborators = {}
abstract = {}
num = 1
sql_list = []
for item in list_data:
if it... | 68687303666a3a81f81160aaec3ffd0dd87f41a1 | 651,298 |
def test_well_plot(well):
"""
Tests mpl image of well.
"""
plot = well.plot(tracks=['MD', 'GR', 'DT'], extents='curves')
return plot.get_figure() | d8460a949dbaaefb1d817695a1e9b282f3839829 | 651,299 |
def split_dataset(data, split_factor):
"""Separates data while not separating data from different articles."""
num_articles = len(set([d['article_id'] for d in data]))
num_train_articles = int(split_factor * num_articles)
data_split1 = list(filter(lambda d: d['article_id'] <= num_train_article... | db93c9fe1c6bef6598167ee480f52d49dab72362 | 651,301 |
def mass_kmv(kinetic_energy,velocity):
"""Usage: Find mass from kinetic energy and velocity"""
result = (2*kinetic_energy)/velocity**2
return result | 19995c38093b25448307c6dce9d468d8967166ce | 651,302 |
def my_tst_function2(a, b):
"""
Returns *a+b*.
@param a (float) float
@param b (float) float
@return a+b
"""
return a + b | f34fb28d14d80ca9e34dc8feef8feb226fc24a25 | 651,303 |
import socket
import binascii
def fmt_ipv6_addr(v):
"""Given a 128-bit integer representing an ipv6 address, return a
string for that ipv6 address."""
return socket.inet_ntop(socket.AF_INET6, binascii.unhexlify("%032x"%v)) | 782996a2ffbf814b464cf041cf8543654fe60a49 | 651,304 |
def replaceItemObj(obj, keystart, newval, exclude_list=[]):
"""
Function for/to <short description of `netpyne.sim.utils.replaceItemObj`>
Parameters
----------
obj : <type>
<Short description of obj>
**Default:** *required*
keystart : <type>
<Short description of keysta... | 3d160ceaaf99930f43e1ffe730a906c022293ea8 | 651,306 |
import platform
import subprocess
def Name():
"""\nReturns The System/OS Name, E.g. 'Android', 'Linux', 'Windows' or 'Java' , Etc .\n
Special Thing In This Module It Can Be Detect Android OS\n"""
check = platform.system()
check1 = check.upper()
if "LINUX" in check1:
try:
path = su... | d8253b5eaa1b77c29d4772e8b3ebceb335047cf3 | 651,307 |
def even_fib_numbers(number: int = 0) -> list:
"""Ищет положительные числа в заданном интервале
Если аргумент number не задан, в качестве значения по умолчанию
используется ноль
Parameters
----------
number : int, positive
порядковый номер последнего числа интервала
even_elements :... | 1334867327e6381a64fe30520870acd4b3d84099 | 651,308 |
def args_to_cmds(args):
"""Convert args dictionary to command line arguments. For example:
>>> args_to_cmds({ 'foo': 'bar', 'qux': 'baz' })
'--foo=bar --qux=baz'
"""
result = ''
for key, val in args.items():
result += '--%s=%s ' % (key, val)
return result | 46b8e94c7b500fc3e71eccb1e39c5370f0586a5c | 651,309 |
def verbatim(f):
"""Read a line of text from file 'f'."""
line = f.readline()
return line | 8c9bd6f6c5d9f3f3d1d8ec45e62cfc8098d66af2 | 651,310 |
from pathlib import Path
def test2solution(filename: str, source_path: str) -> Path:
"""
Build a solution filename from a corresponding test filename.
"""
tokens = filename.split("/")
collection = tokens[-3]
dataset = tokens[-2]
filename = tokens[-1].replace("test-", "solutions-")
# ... | 03fe396162ec09163e8413252643cd84f462f375 | 651,311 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.