content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def convert_size_string_to_bytes(size):
"""
Convert the given size string to bytes.
"""
units = [item.lower() for item in SIZE_UNITS]
parts = size.strip().replace(' ', ' ').split(' ')
amount = float(parts[0])
unit = parts[1]
factor = units.index(unit.lower())
if not factor:
... | 52,600 |
def dumps(data, expires):
"""加密"""
# 创建对象
serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires)
# 加密
token = serializer.dumps(data).decode()
return token | 52,601 |
def align_data(data):
"""Given dict with lists, creates aligned strings
Args:
data: (dict) data["x"] = ["I", "love", "you"]
(dict) data["y"] = ["O", "O", "O"]
Returns:
data_aligned: (dict) data_align["x"] = "I love you"
data_align["y"] = "O O O "
"""
spac... | 52,602 |
def average_surface_distance(mflo, mref):
""" average on points so not reliable if the sampling is unhomogeneous """
pd = polydata_distance(mflo, mref, do_signed=False)
xv = pd.GetPointData().GetArray("Distance")
xn = nps.vtk_to_numpy(xv)
return xn.mean() | 52,603 |
def CleanUserUrl(user_url: str) -> str:
"""清理 user_url,去除其中的空格和无用参数
"""
user_url = user_url.strip()
return user_url.split("?")[0] | 52,604 |
def get_aqi_pb_24h(pb_24h: float) -> (int, str, str):
"""
Calculates Pb (24h) India AQI
:param pb_24h: Pb average (24h), ppm
:return: Pb India AQI, Effect message, Caution message
"""
cp = __round_down(pb_24h * 1000, 3)
return __get_aqi_general_formula_texts(cp, IN_PB_24H, IN_AQI_EFFECTS, I... | 52,605 |
def check_integrity(hdpgroup: list,
verbose: bool = False,
enforce: bool = False) -> Union[list, bool]:
"""Check integrity (comprare checksums) non-proposital data corruption
Args:
hdpgroup (list): [description]
verbose (bool, optional): [description]. De... | 52,606 |
def id_to_ec2_snap_id(snapshot_id):
"""Get or create an ec2 volume ID (vol-[base 16 number]) from uuid."""
if uuidutils.is_uuid_like(snapshot_id):
ctxt = context.get_admin_context()
int_id = get_int_id_from_snapshot_uuid(ctxt, snapshot_id)
return id_to_ec2_id(int_id, 'snap-%08x')
els... | 52,607 |
def delete_nonestimator_parameters(parameters):
"""Delete non-estimator parameters.
Delete all parameters in a parameter dictionary that are not used for the
actual estimator.
"""
if 'Number' in parameters.keys():
del parameters['Number']
if 'UsePCA' in parameters.keys():
del p... | 52,608 |
def get_gene_sequence(gene_name: Path) -> str:
"""Okay, I don't understand how this is suppose to work.
\f
Parameters
----------
gene_name :
Return
------
seq : `str`
"""
try:
with open(gene_name, "r") as f:
seq = f.read()
seq = seq.replace("\r\n... | 52,609 |
def set_max_price(sender, instance, *args, **kwargs):
"""Set max price automatically"""
"""Because of pre_save singal it will be called every time before
Car object updated or created and here instance is the
Car instance that is going to be created or updated"""
if(instance.price == 0):
... | 52,610 |
def get_service(credentials):
"""Get the service object corresponding to GMail."""
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
user = service.users().getProfile(userId="me").execute()
print("Authenticated user: {0}".format(user["emailAddress"]))
... | 52,611 |
def get_private_application_packages(display_name: Optional[str] = None,
filters: Optional[Sequence[pulumi.InputType['GetPrivateApplicationPackagesFilterArgs']]] = None,
package_types: Optional[Sequence[str]] = None,
... | 52,612 |
def load_data():
"""
:return: Data frame
"""
# load data
engine = create_engine('sqlite:///data/disaster_response.db')
df = pd.read_sql_table('disaster_response', engine)
return df | 52,613 |
def _modify_array_from_index_coef_dict(arr, index_coef_dict):
"""
Note: inplace
"""
for index, coef in index_coef_dict.items():
arr[index] = coef | 52,614 |
def start_child_span(
operation_name: str, tracer=None, parent=None, span_tag=None
):
"""
Start a new span as a child of parent_span. If parent_span is None,
start a new root span.
:param operation_name: operation name
:param tracer: Tracer or None (defaults to opentracing.tracer)
:param par... | 52,615 |
def demslv08old():
"""Nonlinear complementarity problem methods
Solve nonlinear complementarity problem on R^2 using semismooth and minmax methods
"""
''' function to be solved'''
def f(z):
x, y = z
fval = np.array([200 * x * (y - x ** 2) + 1 - x,
100 * (x ... | 52,616 |
def test_bool(spec, minval, maxval, expected_values):
"""
Test casting to boolean.
IntegerSetSpecifier which contains no values should evaluate as
False in boolean context.
"""
instance = IntegerSetSpecifier(spec, minval, maxval)
expected_bool = True if expected_values else False
resul... | 52,617 |
def from_mercator(x, y):
"""Convert x,y coordinate from Spherical Mercator to lon, lat
Ported from mercantile.
Parameters
----------
x : float
y : float
Returns
-------
(longitude, latitude)
"""
return (x * R2D / A, ((math.pi * 0.5) - 2.0 * math.atan(math.exp(-y / A))) * ... | 52,618 |
def test_projectgather_get_site_data_site2(
mock_project_site, mock_spec_reader_metadata_only
):
"""Test combining data for site2"""
# get required data
proj = get_test_project(TEST_PROJECT_PATH)
site_name = "site2"
selection = get_selection()
# now test gatherer._get_indices
gatherer = ... | 52,619 |
def GetMaxIndex(tree):
"""get maximum node number."""
return tree.id | 52,620 |
def audit_name_starts_with(prefixes):
"""
Given a list of prefixes, returns a function that takes a folder and prints the folder path if the folder name does not start with one of the prefixes.
"""
def action(folder):
if any(folder.name.startswith(prefix) for prefix in prefixes) == False:
... | 52,621 |
def error_handler(error):
"""
Handle errors in views.
"""
return render('error.html'), 500 | 52,622 |
def save_work(work_id):
"""Save a work"""
if not auth.session_user().can_manage_works:
return Response('User not logged in or not authorized to manage works.',
401)
if int(work_id) == -1:
# New work
work = Work()
else:
# Existing work
work = Work.f... | 52,623 |
def get_feedback_expertise_levels(): # noqa: E501
"""Request a list of allowable expertise levels
# noqa: E501
:rtype: ExpertiseLevels
"""
rtxFeedback = RTXFeedback()
return rtxFeedback.getExpertiseLevels() | 52,624 |
def get_coord_limits(coord):
"""get cooordinate limits"""
lower_limit = float('.'.join([str(coord).split('.')[0], str(coord).split('.')[1][:2]]))
if lower_limit > 0:
upper_limit = lower_limit + 0.01
else:
tmp = lower_limit - 0.01
upper_limit = lower_limit
lower_limit = t... | 52,625 |
def test_load_parent_config():
"""Test a parent config file can pull in children configs"""
cfg_full_path = config_path('files/config.json')
config = cfg.from_json(cfg_full_path)
assert(config['config_path'] == cfg_full_path)
assert('components' in config)
assert('networks' in config)
assert... | 52,626 |
def user_view_init_data(db_session):
"""Add a set of user with initial balances."""
# First user
db_session.add(User(id=1, name="John Doe", email="john@email.com"))
db_session.add(
TransactionLog(
user_id=1,
trans_type=TransactionType.DEPOSIT,
amount=Decimal("... | 52,627 |
def decode(loc, priors, use_yolo_regressors:bool=False):
"""
Decode predicted bbox coordinates using the same scheme
employed by Yolov2: https://arxiv.org/pdf/1612.08242.pdf
b_x = (sigmoid(pred_x) - .5) / conv_w + prior_x
b_y = (sigmoid(pred_y) - .5) / conv_h + prior_y
b_w = prior_w... | 52,628 |
def read_relative_file(filename):
"""Returns contents of the given file, whose path is supposed relative
to this module."""
with open(join(dirname(abspath(__file__)), filename)) as f:
return f.read() | 52,629 |
def get_activations(data_loader, model, device=None, batch_size=32, resize=False, n_samples=None):
"""Computes the activation of the given images
Args:
imgs: Torch dataset of (3xHxW) numpy images normalized in the
range [-1, 1]
cuda: whether or not to run on GPU
batch_size: batch size... | 52,630 |
def write(
# Basic setup
input_path,
# preset_nickname=None,
stream_name="",
stream_description="",
output_directory=None,
output_mode="video",
stream_name_file_output=False,
max_cpu_cores=0,
# Stream configuration
compression_ena... | 52,631 |
def entities(hass):
"""Initialize the test light."""
platform = getattr(hass.components, "test.light")
platform.init()
yield platform.ENTITIES[0:2] | 52,632 |
def shell_escape(string):
"""
Escape double quotes, backticks and dollar signs in given ``string``.
For example::
>>> _shell_escape('abc$')
'abc\\\\$'
>>> _shell_escape('"')
'\\\\"'
"""
for char in ('"', '$', '`'):
string = string.replace(char, '\\{}'.format... | 52,633 |
def boundary_and_obstacles(start, goal, top_vertex, bottom_vertex, obs_number):
"""
:param start: start coordinate
:param goal: goal coordinate
:param top_vertex: top right vertex coordinate of boundary
:param bottom_vertex: bottom left vertex coordinate of boundary
:param obs_number: number of ... | 52,634 |
def build_uncertain_table(args, scores, timestamp_list, image_path_list):
"""phase 3: build table from detection prediction"""
logging.info('phase 3 start.')
start = time.time()
uncertain_scores = build_uncertain_table_fast(scores)
save_uncertain_table(timestamp_list, uncertain_scores, image_path_l... | 52,635 |
def get_current_phase(path):
"""Returns the current phase of the current iteration"""
files = glob.glob(path + "/phase_*.sh")
phases = [0]
for file in files:
file = os.path.basename(file)
phase = file.split(".")[0] # -> phase_x
phase_num = int(phase.split("_")[-1]) # -> x
... | 52,636 |
def hashsum(data):
"""
Calculates the exfiltrated data MD5 hash sum
"""
global hash_sum
if data:
data_hash = int(md5(data).hexdigest(), 16)
hash_sum += data_hash | 52,637 |
def mvg_logpdf_fixedcov(x, mean, inv_cov):
"""
Log-pdf of the multivariate Gaussian where the determinant and inverse of the covariance matrix are precomputed
and fixed.
Note that this neglects the additive constant: -0.5 * (len(x) * log(2 * pi) + log_det_cov), because it is
irrelevant when comparin... | 52,638 |
def add_github_comment(result, message):
"""
Add a comment to a Pull Request in GitHub
:result: (int) exit code of tests, 0 is pass, 1 is fail
:message: (str) the content of the Pull Request comment
"""
travis_pull_request = os.environ.get('TRAVIS_PULL_REQUEST')
user = "YOUR GITHUB USERNAME"
repo = "YOUR GITH... | 52,639 |
def exec_flat_python_func(func, *args, **kwargs):
"""Execute a flat python function (defined with def funcname(args):...)"""
# Prepare a small piece of python code which calls the requested function
# To do this we need to prepare two things - a set of variables we can use to pass
# the values of argume... | 52,640 |
def robust_scale(df):
"""Return copy of `df` scaled by (df - df.median()) / MAD(df) where MAD is a function returning the median absolute deviation."""
median_subtracted = df - df.median()
mad = median_subtracted.abs().median()
return median_subtracted/mad | 52,641 |
def generate_context_menu_mainmenu(menu_id):
"""Generate context menu items for a listitem"""
items = []
if menu_id == 'myList':
items.append(_ctx_item('force_update_mylist', None))
return items | 52,642 |
def unroll_edges(domain, xgrid):
"""If necessary, "unroll" intervals that cross boundary of periodic domain.
"""
xA, xB = domain
assert all(np.diff(xgrid) >= 0)
assert xA < xB
assert xA <= xgrid[0]
assert xgrid[-1] <= xB
if xgrid[0] == xA and xgrid[-1] == xB:
return xgrid
... | 52,643 |
def create_correct_bias_pipe(params={}, name="correct_bias_pipe"):
"""
Description: Correct bias using T1 and T2 images
Same as bash_regis.T1xT2BiasFieldCorrection
Params:
- smooth (see `MathsCommand <https://nipype.readthedocs.io/en/0.12.1/\
interfaces/generated/nipype.interfaces.... | 52,644 |
def infer_gaps_in_tree(df_seq, tree, id_col='id', sequence_col='sequence'):
"""Adds a character matrix to DendroPy tree and infers gaps using
Fitch's algorithm.
Infer gaps in sequences at ancestral nodes.
"""
taxa = tree.taxon_namespace
# Get alignment as fasta
alignment = df_seq.phylo.to_... | 52,645 |
def _sklearn_booster_to_model(booster: GradientBoostingClassifier):
"""
Load a scikit-learn gradient boosting classifier as a Model instance. A multiclass booster gets turned into a one-vs-all representation inside the JSON.
.
Parameters
----------
booster : sklearn.ensemble.Grad... | 52,646 |
def encode_utf8_with_error_log(arg):
"""Return byte string encoded with UTF-8, but log and replace on error.
The text is encoded, but if that fails, an error is logged, and the
offending characters are replaced with "?".
Parameters
----------
arg : str
Text to be encoded.
Returns
... | 52,647 |
def gearys_c(adata, vals):
"""
Compute Geary's C statistics for an AnnData.
Adopted from https://github.com/ivirshup/scanpy/blob/metrics/scanpy/metrics/_gearys_c.py
:math:`C=\\frac{(N - 1)\\sum_{i,j} w_{i,j} (x_i - x_j)^2}{2W \\sum_i (x_i - \\bar{x})^2}`
Parameters
----------
... | 52,648 |
def run_blackbird_script(args):
"""Run a blackbird script.
Related arguments:
* input: the input blackbird script to be run
* output: the output file to store the results in (optional)
Args:
args (ArgumentParser): arguments that were specified on the command
line stored as attr... | 52,649 |
def eq_kinematic_src():
"""
Factory associated with EqKinSrc.
"""
return EqKinSrc() | 52,650 |
def test_check_config_01():
"""Check for check_config."""
folder_path = f"{os.getenv('HOME')}/.mybookingservices"
shutil.rmtree(folder_path)
assert config.check_config() is None | 52,651 |
def test_rpath_args(mutable_database):
"""Test a package's rpath_args property."""
rec = mutable_database.get_record('mpich')
rpath_args = rec.spec.package.rpath_args
assert '-rpath' in rpath_args
assert 'mpich' in rpath_args | 52,652 |
def generate_materials_string(materials, mtlfilename, basename):
"""Generate final materials string.
"""
if not materials:
materials = { 'default': 0 }
mtl = create_materials(materials, mtlfilename, basename)
return generate_materials(mtl, materials) | 52,653 |
def _mktyperef(obj):
"""Return a typeref dictionary. Used for references.
>>> from jsonpickle import tags
>>> _mktyperef(AssertionError)[tags.TYPE].rsplit('.', 1)[0]
'exceptions'
>>> _mktyperef(AssertionError)[tags.TYPE].rsplit('.', 1)[-1]
'AssertionError'
"""
return {tags.TYPE: '%s.%... | 52,654 |
def colorize(img: np.ndarray, color: Tuple) -> np.ndarray:
"""colorize a single-channel (alpha) image into a 4-channel RGBA image"""
# ensure color to RGBA
if len(color) == 3:
color = (color[0], color[1], color[2], 255)
# created result image filled with solid "color"
res = np.zeros((img.s... | 52,655 |
def prepare_template_stream(stream, base_url):
"""Prepares the stream to be stored in the DB"""
document_tree = _get_document_tree(stream)
_make_links_absolute(document_tree, base_url)
return _serialize_stream(document_tree) | 52,656 |
def _jsarr(x):
"""Return a string that would work for a javascript array"""
return "[" + ", ".join(['"{}"'.format(i) for i in x]) + "]" | 52,657 |
def class_channels_to_rgb(input_batch, output_batch, label_batch):
""" Converts multichannel tensor to RGB image -- i.e. model output to final mask. """
# colors = get_color_encoding_CamVid()
colors = get_color_encoding_Elements()
rgb_batch_size = list(output_batch.size())
rgb_batch_size[1] =... | 52,658 |
def PyApp_SetMacPreferencesMenuItemId(*args, **kwargs):
"""PyApp_SetMacPreferencesMenuItemId(long val)"""
return _core_.PyApp_SetMacPreferencesMenuItemId(*args, **kwargs) | 52,659 |
def isnum(value):
"""
Check if a value is a type of number (decimal or integer)
value:
The value to check
"""
try:
return bool(isinstance(value, (float, int)))
except BaseException:
return False | 52,660 |
async def _async_json_object(api_call):
"""async function to make a request to the wiki api and return a json object with article information
Args:
api_call (text): link to the api call
Returns:
dict: json content from the api call
"""
async with httpx.AsyncClient()... | 52,661 |
def yices_model_set_bv_int64(model, var, val):
"""Assign an integer value to a bitvector uninterpreted term.
"""
return libyices.yices_model_set_bv_int64(model, var, val) | 52,662 |
def assemble_job_output(self, job_id, launch_id):
"""
This takes the just-completed job and validates that it is complete and ready to process.
Specifically, it:
- checks the crawl log is there, and that there is no crawl.log.lck file, and no other crawl.log files.
- parses the crawl log, generati... | 52,663 |
def plot_peak_and_final_size(
e: float,
p_sa: float = p_south_africa,
severity: float = 1,
relative_severity: float = (1 - omicron_hospital_evasion),
y_limit_peak: list = 1.,
y_limit_final: list = 1.,
save_this_figure: bool = False
) -> None:
"""
Plot ... | 52,664 |
def test_get_host_ports():
"""
Validates that host and port data is parsed from settings
"""
service_setting = ["localhost:9090"]
expected = [("localhost", 9090)]
actual = get_host_ports(service_setting)
assert actual == expected
service_setting = ["localhost"]
expected = [("localho... | 52,665 |
def generate_histograms(
num_users: int,
counts_iid_param: float,
avg_count: float,
ref_distribution: np.ndarray,
hist_iid_param: float,
rng=np.random.default_rng()) -> np.ndarray:
"""Generate histograms with different total counts and distributions.
Args:
num_users: An integer indicati... | 52,666 |
def editable_str(initial_str):# -> array
"""Exactly the same as array.array except that it switches types based on Python Version:
Python 2: character, one byte
Python 3: unicode, two to four bytes"""
array_type = 'u'
if sys.version_info < (3, 0):
array_type = 'c'
return array(array_type... | 52,667 |
def neo_create_bucket(**kwargs):
"""Create a bucket with headers.
:param auth: Tuple, consists of auth object and endpoint string
:param acl: Input for canned ACL, defaults to "private"
:param policy_id: String represent `x-gmt-policyid` or determines how data in the bucket will be distributed, default... | 52,668 |
def babi_handler(data_dir, task_number):
"""
Handle for bAbI task.
Args:
data_dir (string) : Path to bAbI data directory.
task_number (int) : The task ID from the bAbI dataset (1-20).
Returns:
BABI : Handler for bAbI task.
"""
task = task_list[task_number - 1]
retur... | 52,669 |
def copy_tree(xyzlist, base_dir, new_dir):
"""
Copies the directory structure from the base directory downwards, and then when the final
subdirectory has been created, files are copied over
"""
base = os.path.abspath(base_dir)
new = os.path.join(base, new_dir)
if not os.path.exists(new):
... | 52,670 |
def _full_ner(text_analyzer):
"""
Run complete NER.
This includes extraction of different entity types and geotagging.
:param class text_analyzer: the text_analyzer of nlp_components
:return dict: json with persons, geotagged locations and metadata,
readalbe by the viewer
"""
named... | 52,671 |
def frequency_impulse_response(magnitudes: tf.Tensor,
window_size: int = 0) -> tf.Tensor:
"""Get windowed impulse responses using the frequency sampling method.
Follows the approach in:
https://ccrma.stanford.edu/~jos/sasp/Windowing_Desired_Impulse_Response.html
Args:
magnit... | 52,672 |
def create_sample_vcf_hf_polar():
""" Create polar plots from sample_hf.vcf. """
plot_vcf(in_vcf=SAMPLE_HF_VCF, save=True, output=BASE_HF_IMG)
plot_vcf(in_vcf=SAMPLE_HF_VCF, save=True,
output=BASE_HF_IMG_LABELS, labels=True)
plot_vcf(in_vcf=SAMPLE_HF_VCF, save=True,
output=BASE... | 52,673 |
def parse_station_list_to_json(filepath_or_buffer) -> str:
""" Return JSON-formatted data """
return _parse_station_list(filepath_or_buffer).to_json(orient="records") | 52,674 |
def get_minimal_intactness_ls_centralities(
nodes: List[Node], definitions: Definitions,
get_ill_behaved_weight: Callable[[Set[Node]], float],
get_mu: Callable[[numpy.array], float]
) -> numpy.array:
"""Compute minimal intactness linear system centralities"""
M = get_minimal_inta... | 52,675 |
def test_unauthorized(client, user_factory):
"""test for not logged in, redirect and final login"""
password = PWS.generate()
user = user_factory.create(password=PWS.hash(password))
response = client.get(url_for('auth.profile_route'))
assert response.status_code == HTTPStatus.FOUND
assert '/au... | 52,676 |
def dict_merge(dct, merge_dct):
""" Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
updating only top-level keys, dict_merge recurses down into dicts nested
to an arbitrary depth, updating keys. The ``merge_dct`` is merged into
``dct``.
:param dct: dict onto which the merge is ... | 52,677 |
def cl_encode(lengths):
"""lengths is a list of (char, code) tuples. Return a list of lengths
encoded as specified in section 3.2.7"""
dic = {char: len(code) for (char, code) in lengths.items()}
items = [dic.get(i, 0) for i in range(max(dic) + 1)]
pos = 0
while pos < len(items):
if items... | 52,678 |
def inverse_sigmoid_numpy(x):
"""
.. todo::
WRITEME
"""
return np.log(x / (1. - x)) | 52,679 |
def check_pex_health(baseroot, flags):
"""Check to see if pants.pex has been modified since the version stored in the branch. If so,
then the workspace is cleaned up to remove old state and force BUILD files to be regenerated.
:param string baseroot: directory at the root of the repo
:param list<String> flags:... | 52,680 |
def join_kwargs(**kwargs) -> str:
"""
Joins keyword arguments and their values in parenthesis.
Example: key1{value1}_key2{value2}
"""
return "_".join(key + "{" + value + "}" for key, value in kwargs.items()) | 52,681 |
def zipped_lambda_function():
"""Return a simple test lambda function, zipped."""
func_str = """
def lambda_handler(event, context):
print("testing")
return event
"""
zip_output = BytesIO()
with ZipFile(zip_output, "w", ZIP_DEFLATED) as zip_file:
zip_file.writestr("lambda_function.py", f... | 52,682 |
def byte_builtin():
"""byte: Immutable bytes array."""
return bytes("\xd0\xd2NUT", "utf-8").decode() | 52,683 |
def predict_interaction(model, n0, n1, tensors, use_cuda):
"""
Predict whether a list of protein pairs will interact.
:param model: Model to be trained
:type model: dscript.models.interaction.ModelInteraction
:param n0: First protein names
:type n0: list[str]
:param n1: Second protein names... | 52,684 |
def hessian(f, varlist, constraints=[]):
"""Compute Hessian matrix for a function f wrt parameters in varlist
which may be given as a sequence or a row/column vector. A list of
constraints may optionally be given.
Examples
========
>>> from sympy import Function, hessian, pprint
>>> from s... | 52,685 |
def extract_column_names(row_list):
"""
Extract names of columns from row list obtained from table csv. The first row contains all row names
:param row_list: List of all rows in csv used for table creation
:return: List of names present in table csv
"""
return row_list[0] | 52,686 |
def index_to_point(index, origin, spacing):
"""Transform voxel indices to image data point coordinates."""
x = origin[0] + index[0] * spacing[0]
y = origin[1] + index[1] * spacing[1]
z = origin[2] + index[2] * spacing[2]
return (x, y, z) | 52,687 |
def calculate_metrics(ground_truth_file: str, prediction_files: Tuple[str, ...]) -> None:
"""Calculate metrics for predictions generated by one or several translation models"""
with open(ground_truth_file, 'rt') as f:
ground_truth = [s.strip() for s in f]
predictions = []
for prediction_file i... | 52,688 |
def MakeEmptyTable(in_table=[[]], row_count=0, column_count=0):
"""
1 Read in *in_table*
2 Create an empty table
of '' values,
which has with the same number of rows and columns as the table,
(where columns based on the first row).
3 If the user has specified *row_count* and/or ... | 52,689 |
def refine_trials():
"""
Remove Terminated trials
"""
ref_path = os.path.join( 'data', 'meta')
ref_file = os.path.join(ref_path, 'clinical' + 'All' + '.csv')
df = pd.read_csv(ref_file)
# drop duplicates using url
df = df.drop_duplicates(subset=['url'])
# remove termina... | 52,690 |
def choose_pseudo_gt(boxes, cls_prob, im_labels):
"""Get proposals with highest score.
inputs are all variables"""
num_images, num_classes = im_labels.size()
boxes = boxes[:,1:]
assert num_images == 1, 'batch size shoud be equal to 1'
im_labels_tmp = im_labels[0, :]
gt_boxes = []
g... | 52,691 |
def test_sequential():
"""Test sequential module."""
lin = Sequential(Linear(1,2), Squeeze())
test = torch.zeros((1,))
assert lin(test, training=True).shape == (2,) | 52,692 |
def test_ingest_single_empty_message(connection):
"""It is possible to ingest a completely empty Event. It serializes to {}"""
e = Event()
connection.server.log(e) | 52,693 |
def create_submission(args: argparse.Namespace, cfg: CfgNode) -> str:
"""inferece models and save prediction
Args:
args (argparse.Namespace): argparse namespace
cfg (CfgNode): cfg for parameters
Returns:
str: path to the saved prediction
"""
napi = NumerAPI()
if args.co... | 52,694 |
def transform_covariance_matrix(transformation, histogram):
"""
Compute the covariance matrix of a new histogram given by:
new_histogram = transformation * histogram
"""
A = transformation
V = compute_numpy_covariance_matrix(histogram)
return A * V * A.T | 52,695 |
def pretty_print(obj):
"""pretty print an attrs object"""
obj_dict = attr.asdict(obj)
fields = list(attr.fields(obj.__class__))
max_name_length = max([len(x.name) for x in fields])
for field in fields:
print(
field.name + ":" + (max_name_length - len(field.name)) * " ",
... | 52,696 |
def plot_indicators(df_indicators):
""" Plot indicators in df_indicators"""
# 8.1 Plot Price chart for comparison later
df_price = df_indicators[['prices']].copy()
df_price.rename(columns={'prices': 'JPM stock price'}, inplace=True)
plot_data(df_price, title="JPM stock price normalized", xlabel="Dat... | 52,697 |
def main(argv):
"""
Command line utility for extracting authenticated login cookies.
Params: username, password, url.
Proxy support not yet implemented.
"""
import pprint
if not FORMASAURUS:
logging.warning('Formasaurus is not installed. Install it here: https://github.com/TeamHG-Mem... | 52,698 |
def _candidategroups(revlog, textlen, p1, p2, cachedelta):
"""Provides group of revision to be tested as delta base
This top level function focus on emitting groups with unique and worthwhile
content. See _raw_candidate_groups for details about the group order.
"""
# should we try to build a delta?... | 52,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.