content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def gen_endpoint_config(
endpoint_config_name,
model_name,
initial_instance_count,
instance_type,
data_capture_sample_percent,
data_capture_s3_prefix,
enable_data_capture=False,
):
"""
Generates the endpoint_config for the Sagemaker Endpoint. We can specify all the
production var... | 25d74a53c3ffc715bdd1bcdb831e303ec55f52d3 | 607,680 |
def get_criteria() -> dict:
"""Return standard analysis criteria."""
criteria = {
'structure': ['VISp'],
'depth': [175],
'cre_line': ['Slc17a7-IRES2-Cre'],
'exp_idx': 1
}
return criteria | d926f1a75f55e4c7a50a07b5fb8d1ff6348ebe4f | 607,682 |
def getPeriod(n):
"""
Returns period of 1/n
Parameters
----------
n : int
denotes positive integer
return : int
returns an integer denoting period of 1/n
"""
if(n!=int(n) or n<1):
raise ValueError(
"n must be positive integer"
)
rem = 1
... | 1dccc4dd763c9d11337d02f1943fbb7272c18967 | 607,685 |
def highest_port(service, base_port, *kinds):
"""Find the first port >= base_port not in use by any input in kinds."""
highest_port = base_port
for input in service.inputs.list(*kinds):
port = int(input.name.split(':')[-1])
highest_port = max(port, highest_port)
return highest_port | 52753089cc7cd03b847b68808680c832108b8cf1 | 607,686 |
def compute_precision(true_positives, false_positives):
"""Compute precision
>>> compute_precision(0, 10)
0.0
>>> compute_precision(446579, 13932)
0.969747
"""
return true_positives / (true_positives + false_positives) | 9aa7292695b7dd039dda87326b0bca37df3afa1b | 607,687 |
def create_range_as_list(rng, as_type=str):
"""
Parameters
----------
range : str
The range to create as a list.
e.g.
range="1-4" --> [1, 2, 3, 4]
range="1-3,5,7-9,1001" --> [1, 2, 3, 5, 7, 8, 9, 1001]
as_type : type
map list to as_type. default = str... | ca17a57a60f59e30a021fbbd50ad95405827c0a3 | 607,689 |
def _get_valid_owner(owner):
""" Try to find an owner that supports the required functionality. """
while owner is not None:
if hasattr(owner, 'check_path') and \
hasattr(owner, 'get_abs_directory'):
return owner
if hasattr(owner, 'parent'):
owner = owner.paren... | 03a452a01345457fa403fa583f8373df72e28268 | 607,693 |
import re
def str_contains_numbers(str):
"""
Check if a string contains at least one number.
:param str: the string to check.
:return: true if the string contains at least one number, false else.
"""
return bool(re.search(r'\d', str)) | aaaeb38f3a40db4610ce27db1bed8e0966b88d37 | 607,696 |
from typing import Dict
def prefix_url(url: str, namespaces: Dict[str, str]) -> str:
"""Expand short forms into full URLs using the given namespace dictionary."""
for k, v in namespaces.items():
if url.startswith(v):
return k + ":" + url[len(v) :]
return url | 3114f3929f51201d77dbb3722306d56034d0a6d7 | 607,701 |
def _dupper(ev, state_args=None, **kwargs):
"""Duplicates every input event."""
return [ev, ev] | fad5b67465a8747313fb2d049d97dbfba5a3f96f | 607,705 |
def shoot(vx: int, vy: int, right: int, bottom: int) -> tuple[int, int]:
"""Simulate a shot and get the last position that's not out of bounds.
Args:
vx: The horizontal speed.
vy: The vertical speed.
right: The right bound.
bottom: The bottom bound.
Returns:
The (x,... | 268858a65f3aa44b33a46a0a93c955be4dbe6929 | 607,707 |
import torch
def threshold(data:torch.Tensor, min_value:torch.Tensor, max_value:torch.Tensor) -> torch.Tensor:
"""
Generate mask using min & max values.
Note, data in (max_value, min_value) interval have True values.
Parameters
----------
data: torch.Tensor
input 1D data
min_valu... | face801acaa5b3bbcc83e3152f3820c998d12a60 | 607,708 |
def flattenByComprehension(lista):
""" Flattens a list of lists by comprehension.
Args:
lista (list): a nested list.
Returns:
(list): flattened list.
"""
return [val for sublist in lista for val in sublist] | 004ef4127e3ed2dd2da803cd789ceb0d2e78b0b2 | 607,709 |
import random
def random_from_pdf(pdf, seed=None):
"""Return a random value according to a given probability density function.
Parameters
----------
pdf : dict
Dictionary mapping values of the random variable and probability of
occurrence. The sum of all dictionary values must be 1.
... | 1b0977c9576f85fda8930bf8b2c77455f4c8c355 | 607,710 |
def snake_to_camel_case(value):
"""
Converts a string from snake_case to camelCase
"""
words = value.strip("_").split("_")
return words[0].lower() + "".join([word.capitalize() for word in words[1:]]) | b78419dbdbe0cd88f6dd79e9174f4a26ae9640b5 | 607,712 |
def entry_keywords(value):
"""Build the bibtex keywords field."""
keywords = []
for word in value.split(';'):
word = word.strip()
keywords.append(word)
return ', '.join(keywords) | 0dba0347f9a4dc94f28e76c67d49541779b2665c | 607,713 |
import shutil
import textwrap
import pprint
def fit_to_console(obj, initial_indent='', subsequent_indent='', width=None,):
"""Return a string formatted to fit nicely in the console
This is essentially a wrapper around textwrap and pprint; it pretty-prints the input object,
then wraps it to the width of t... | 7568f36ebe6daeb3a06d81e154ff930908098e3f | 607,718 |
def qrGetRequiredGuides( skeletonParameters ):
"""
This method returns a list of the guides corresponding to the given skeleton parameters.
It should be in sync with the output of:
- qrGetGuidesFromEmbedding( )
"""
guides = [
'Reference' ,
'Hips' ,
'Head' ,
... | 08465db5b7ce289b674b35dfd3efbdd654c91a92 | 607,720 |
def mean(lst):
"""Calculates the mean of a numeric list"""
return sum([float(x) for x in lst])/len(lst) | 54933a2facf7f8cbf1374efb12a3d66e6fc55188 | 607,725 |
import copy
def flip_y(img):
"""Flips a given image along y axis."""
flipped_img = copy.deepcopy(img)
center = int(len(img[0]) / 2)
for i, row in enumerate(img):
for j in range(center):
flipped_img[i][j] = img[i][(len(img[0]) - 1) - j]
flipped_img[i][(len(img[0]) - 1) -... | 601b4072fbbd170b6ffde55372a55c90b8ecdfb1 | 607,726 |
def is_config_file(filename, extensions=['.yml', '.yaml', '.json']):
"""Return True if file has a valid config file type.
Parameters
----------
filename : str
filename to check (e.g. ``mysession.json``).
extensions : list or str
filetypes to check (e.g. ``['.yaml', '.json']``).
... | 0d86fb39a2a91e749ab48b96c386b73f146e7bf6 | 607,728 |
def dirn_is_ok(dirn):
"""Ensure that the TM head direction is OK.
"""
return dirn in set({'L','R','S'}) | f26c30fa008b0cd133a0060f794487589c6a440a | 607,730 |
from pathlib import Path
def tempdir(tmpdir):
"""Fixture that wraps pytest fixture to return Path object"""
return Path(str(tmpdir)) | 6fde898ff0ff870578bb5072a060d60e556aaf84 | 607,731 |
def _get_product_id(device_dict):
"""Converts 0x1234 to 1234."""
return device_dict['product_id'].split('x')[-1] | 8719d7022991a4fa53658330b01221a4e886e6a3 | 607,732 |
from unittest.mock import call
def _lcall(command, job_id):
"""
Call an executable and return a tuple of exitcode, stdout&stderr
"""
# Write output to a file so we can see what's going on while it's running
f = "/tmp/%s.out" % job_id
with open(f, "w", buffering=1) as log: # Max buffer 1 lin... | 181019526999e5c4d95d8545af6a0b723ce7f83f | 607,738 |
from typing import Dict
from typing import Any
def get_expected_length(elem: Dict[str, Any], unit: str = 'bytes') -> int:
"""Return the expected length (in terms of bytes or pixels) of the *Overlay
Data*.
.. versionadded:: 1.4
+------------------------------------------------+-------------+
| El... | 20dcb0cd7146d4ba2ebfe6ce3544126d20d4e43d | 607,739 |
from typing import Dict
import json
def __load_text_json(file_path: str) -> Dict[str, str]:
"""Load quotes from a JSON file, i.e., load a JSON objects that maps titles to quotes/lyrics.
Parameters
----------
file_path : str
Path to the .json file with lyrics/quotes.
Returns
-------
... | 4d1ec15ea2d406b4f7800800b25f3ecb216b931f | 607,740 |
import requests
import json
def get_groups(platform, key, client_id):
"""
Retrieve a list of all of the groups associated with the
specified client ID.
:param platform: URL of the RiskSense platform to be queried.
:type platform: str
:param key: API Key.
:type key: ... | bdcb8f4eb51c84155a0b327ea6bc1b1b5917a7c1 | 607,741 |
from typing import Any
def container_logs(container: Any) -> str:
"""Get logs for a container
Args:
container (any): Container to get logs for
Returns:
str: Logs from container
"""
return container.logs().decode() | f17be6841c784dbe199ad2647df64d22603f4970 | 607,743 |
def get_dict_differences(ref_json, test_json, ref_file, test_file):
"""
Identify differences between the two JSON dictionaries.
Parameters
----------
ref_json : dict
Refernce JSON configuration dictionary.
test_json : dict
Test JSON configuration dictionary.
ref_file : str
... | b55f57bbbf2b9ce620b5373ef2b8ac9304401020 | 607,753 |
from typing import Dict
from typing import Any
import yaml
import json
def load_configuration(config_path: str) -> Dict[str, Any]:
"""
Load a configuration file
Parameters
----------
config_path: str
Path to yaml or json configuration file
Returns
-------
dict[str, Any]
... | 90b66b7537dcd0d63756de84cc21f9220f8ebe2b | 607,755 |
def box_range(number):
"""
:param number: input the row or column number
:return: a list of row or column number within the same box
"""
if number in (1, 2, 3):
return [1, 2, 3]
elif number in (4, 5, 6):
return [4, 5, 6]
elif number in (7, 8, 9):
return [7, 8, 9] | 51f63d621224e13f0526b3ad7e3bff4db5b064af | 607,756 |
def target_selection(data) :
""" Separates features from target
:param: Dataframe
:return: Features pandas.Dataframe
:return: Target pandas.Series
"""
data = data[['Sintoma','Tipificacao_Nivel_1','Tipificacao_Nivel_2','Tipificacao_Nivel_3','Equipamento_Tipo','Servico','Tarifario','Contexto_Said... | 92882cb70451af56b0560fb34e9bdee44f70fc56 | 607,757 |
def remove_keys(road):
"""
:param road: A road segment as a dict
:return: The same road segment without "felt" and "kvalitet".
"""
road.pop("felt", None)
road["geometri"].pop("kvalitet", None)
return road | 633f5934f2e41bbf9a0a83b55ada2400ec9b3ddf | 607,759 |
def is_json_response(response):
"""Returns ``True`` if response ``Content-Type`` is JSON.
:param response: :class:~`requests.Response` object to check
:type response: :class:~`requests.Response`
:returns: ``True`` if ``response`` is JSON, ``False`` otherwise
:rtype bool:
"""
content_type = ... | 113bc6e1dcb45d4294287454b2a7519f05bad4cb | 607,762 |
def _get_next(iter_f):
"""
Get function than get next of iterable in each call
:param iter_f: iterable to wrap in next function
:return: function to get next of iterable
"""
def f_next():
try:
return next(iter_f)
except RuntimeError:
return None
e... | c7e59d07c32ac22ff510a6d749cc2b114fa58ea5 | 607,763 |
def get_selfcontrol_out_pattern(content_pattern):
"""Returns a RegEx pattern that matches SelfControl's output with the provided content_pattern"""
return r'^.*org\.eyebeam\.SelfControl[^ ]+\s*' + content_pattern + r'\s*$' | e8bf556cbf14ef7c4ad20a60d84f049057bc4ffe | 607,776 |
from typing import Union
def all_keys(d: Union[dict, list]) -> list:
"""
Returns a list of all the keys of a dictionary (duplicates included)
d -- a dictionary to iterate through
"""
if not d:
return []
if d is None or not isinstance(d, dict) and not isinstance(d, list):
retu... | 7edb785cb27fcfdbe60631fe1442549c1eeaf563 | 607,778 |
def format_small_box(message, ws_offset=6, box_width=40):
"""
Formats the message into a one line string offset by # and white space
symbols.
:param message: self-explanatory.
:param ws_offset: two sided white space offset wrapping the message.
:param box_width: the total width of the box.
... | cad8e95ae73cf1901cf2ebf8323896da2089796f | 607,781 |
def typeOf(value):
"""
Get the type of value.
:param value: What to get the type of.
:type value: anything
:returns: str
"""
return str(type(value)) | 081500ca6554f71b0a87439be16bd3fb067bdc2a | 607,782 |
def short_form_one_format(jupytext_format):
"""Represent one jupytext format as a string"""
if not isinstance(jupytext_format, dict):
return jupytext_format
fmt = jupytext_format['extension']
if 'suffix' in jupytext_format:
fmt = jupytext_format['suffix'] + fmt
elif fmt.startswith('.... | aef23bb9644724225987529a28ebbfc34f826210 | 607,783 |
def taxid_flag(config, tool):
"""Set taxid flag for running blast searches."""
taxid = config["taxon"].get("taxid", None)
if taxid is None:
return ""
flags = {
"blastn": "-negative_taxids",
"diamond_blastp": "--taxon-exclude",
"diamond_blastx": "--taxon-exclude"
}
... | 3a9afe37aba8feaa9a3d9aa0151a077613ae1057 | 607,784 |
def miles_to_km(miles):
"""
convert from miles to km
"""
return 1.609344*miles | c5e189d1a7f49732d64a13658a0a91c49baaebfc | 607,787 |
def format_pylist_to_mathematica_legend(labelname_syntax, pylabel_list):
"""
Helper funciton. convert python list to be mathematica list for the legend
Parameters
-------------
labelname_syntax : str
label type syntax in the Wolfram Mathematica .
pylabel_list : list
the lis... | 26d42e5330c89dac5351507ca3a37e4d2f8e03c8 | 607,790 |
import re
def extract_swagger_path(path):
"""
Extracts a swagger type path from the given flask style path.
This /path/<parameter> turns into this /path/{parameter}
And this /<string(length=2):lang_code>/<string:id>/<float:probability>
to this: /{lang_code}/{id}/{probability}
"""
return re.sub('<(?:[^:]... | 8563f028d4736d4032492a6d7a166aa5c3d97e36 | 607,791 |
def sample_filter_smooth(lds_model, key):
"""
Sample from a linear dynamical system, apply the kalman filter
(forward pass), and performs smoothing.
Parameters
----------
lds: LinearDynamicalSystem
Instance of a linear dynamical system with known parameters
Returns
-------
... | 5de935eca574feb34216baee6e59f21bd06eead5 | 607,792 |
from pathlib import Path
def with_stem(path: Path, stem: str) -> Path:
"""Replacement for pathlib.PurePath.with_stem() which is new Python 3.9."""
return path.with_name(stem + path.suffix) | 33f9f51ebc5b4fa69469efe14b4c4df4c0b060eb | 607,794 |
def extract_table_data(row_list, n):
"""
Extract table tows from all row as a list of tuples for persisting.
First :param n rows of csv are metadata, header rows. Thus, returns rows n and onwards
:param row_list: List of all rows in csv used for table creation
:param n: Represents how any rows in th... | 59cfa4b8406eafbe385c602f8956cbb2d21ed701 | 607,795 |
def calc_dist_to_center(img_width, left_fitx, right_fitx):
"""Calculate the distance to the center of the street."""
center = img_width / 2.
left_bottom_x = left_fitx[-1]
right_bottom_x = right_fitx[-1]
lane_width = right_bottom_x - left_bottom_x
center_lane = (lane_width / 2.0) + left_bottom_x... | a0ae973ae2973280e2bdd661455298576499470e | 607,796 |
def _determineLinked(componentA, componentB):
"""determine axial component linkage for two components
Parameters
----------
componentA : :py:class:`Component <armi.reactor.components.component.Component>`
component of interest
componentB : :py:class:`Component <armi.reactor.components.compo... | 29c2307c665c42f8849ee6d17a30d0cdcf79ada7 | 607,797 |
def longitude_set_meridian(longitude):
"""Sets longitude to be between -180 and 180 degrees"""
return (longitude + 180.0) % 360.0 - 180.0 | 232856f5148370bea245c544e4d2fdad46fe5a47 | 607,799 |
def ValueToString(descriptor, field_desc, value):
"""For a non-repeated field, renders the value as a Javascript literal.
Args:
descriptor: The descriptor module from the protobuf package, e.g.
google.protobuf.descriptor.
field_desc: The type descriptor for the field value to be rendered.
value... | a3bda2d14080081b6d625891d0d394e95e5499f0 | 607,800 |
def expose(func):
"""Decorator that exposes the function to the xmlrpc server"""
func.exposed = True
return func | 63eb532b6472e4a8e8a28c49d9fb41208f019106 | 607,806 |
def process_data(employee_list):
"""
Process employee data.
Receive the list, employee_list, as a parameter and return a dictionary of
department:amount.
"""
department_list = []
for employee_data in employee_list:
department_list.append(employee_data['Department'])
department_... | 9bf7d5ac624337441410e2b94eabea5a04645463 | 607,808 |
def _singlethread_iteration(selection_iterator, scoring_fn):
"""Handles a single pass of the abstract variable importance algorithm,
assuming a single worker thread
:param selection_iterator: an iterator which yields triples
``(variable, training_data, scoring_data)``. Typically a
:class:... | 58ab64e4d4ece0c7629caf3d2c1582f2cc8b4133 | 607,812 |
def dummy_coordinates() -> tuple:
"""Regresa coordenadas de prueba.
Returns:
tuple: latitud, logintud.
"""
latitude = 25.669287203700236
longitude = -100.30994076079043
return latitude, longitude | 0920df974d912f2546a82025115accd2249edff4 | 607,813 |
def test_statistic_difference(data1, data2, mct) -> float:
"""Test function for test statistic: Difference between MCT"""
return mct(data1) - mct(data2) | 7c52cbdc713e98791d9eed385467f5c0d49516cc | 607,814 |
def move_point(point):
"""Move point by it velocity."""
for index, change in enumerate(point['velocity']):
point['position'][index] += change
return point | f36b78b397611d0deb83eb9198730b92f802b27f | 607,816 |
def format_result(fit):
"""
Formats a pyDDM fit object into something more useful
by extracting parameter estimates and the loss function value.
"""
parameter_names = fit.get_model_parameter_names()
estimates = [fitted.real for fitted in fit.get_model_parameters()]
estimate_dict = {
... | 010cf203ef041fdee5d5499c9c46585f6c0914aa | 607,818 |
def pp_Age(df):
"""
imputes missing values of age through a groupby([Pclass,Title,isFemale])
returns df with new column named Age_nonull appended to it
"""
transformed_Age = df.groupby(["Title", 'Pclass', "Sex"])['Age'].transform(lambda x: x.fillna(x.median()))
df['Age_nonull'] = transformed_Age... | 17a2ebbefe742fe594224cf5b6742b7562c8029b | 607,821 |
import sympy
def generate_monomials(order):
"""
Generate trivariate monomials up to given order.
"""
monoms = []
x, y, z = sympy.symbols('x y z')
for i in range(0, order + 1):
for j in range(0, order + 1):
for k in range(0, order + 1):
if i + j + k <= order:... | 7bed7ef37c9d4c48201283d84ecdb1932808771d | 607,822 |
from datetime import datetime
from typing import Union
import pytz
def datetime_to_str(date: datetime, format_str: str) -> Union[str, None]:
"""Get date string from datetime, based on `format_str` provided.
If `date` is already a string, return it. Make the date aware."""
if isinstance(date, str):
... | 076d0c87d3a425de50d1060cf3093028d947a20b | 607,823 |
def _qdwh_coefs(lk):
"""
Computes a, b, c, l for the QDWH iterations.
"""
d = (4. * (1. - lk**2) / (lk**4))**(1 / 3)
f = 8. * (2. - lk**2) / (lk**2 * (1. + d)**(1 / 2))
a = (1. + d)**(1 / 2) + 0.5 * (8. - 4. * d + f)**0.5
b = (a - 1.)**2 / 4
c = a + b - 1.
lk = lk * (a + b * lk**2) / (1 + c * lk**2)
... | 1bb2d7eedf5fef673d647f0ee7d3116d2cd77663 | 607,835 |
from typing import Counter
def hapax_legomena(text):
"""Return words that occur only once within a text.
:param text: str list or Counter
"""
cnt = Counter(text) if type(text) == list else text
return [w for w, c in cnt.most_common() if c == 1] | 0b44fc30ab421e1e573eece848a2f610e1bfa24d | 607,836 |
import json
def _is_pesummary_json_file(path, check_function):
"""Determine if the result file is a pesummary json file
Parameters
----------
path: str
path to the results file
check_function: func
function used to check the result file
"""
with open(path, "r") as f:
... | e999ad9e0db1a21a089c756c6dd7db69e9765138 | 607,844 |
from datetime import datetime
def to_mins(timestamp: datetime):
"""
Calculates n minutes from midnight.
"""
delta = timestamp - datetime(timestamp.year, timestamp.month, timestamp.day)
return delta.seconds // 60 | 6dade89f1729ae6d3c171c9c6486ee79b8bbb957 | 607,849 |
def intersect_dicts(checkpoint_state_dict, model_state_dict):
"""
Dictionary intersection of matching keys and shapes using checkpoint_state_dict values
:param checkpoint_state_dict: checkpoint state dict
:param model_state_dict: model state dict
:return: intersect dicts
"""
return {key: va... | 3a30eab7eab7013eea474d13bd0d1dffba993cdf | 607,850 |
import re
def get_songs(description):
"""
Extracts the songs located in the description
:param BeautifulSoup description: video description as bs4 object
:return list: song names
"""
# pattern for a youtube video time (e.g. 34:87, 2:38:56)
yt_time_regex = re.compile(r'(\d{1,2}:)?([0-5]?[0-... | b2aee35a93cb2b62c6c6d9cb98575bf0dc77f1d8 | 607,853 |
def Group(items, key):
"""Groups items by given key function.
Args:
items: An iterable or an iterator of items.
key: A function which given each item will return the key.
Returns:
A dict with keys being each unique key and values being a list of items of
that key.
"""
result = {}
for item... | 368cd2356adf6dc5f90a1478f46d0e61e667eb2d | 607,857 |
def tolist(value=None, sep=',', empty_strings=False):
"""Convert a string to a list.
The input string is split on the separator character. The default separator
is ','. An alternative separator may be passed as the 'sep' keyword. If no
string value is provided a function is returned that splits a strin... | 93a1d3e45736fc57a4a85f9e481bfd32c32843f7 | 607,859 |
import re
def is_numerical_spec(input_string):
""" Match all strings containing a positive integer without leading zeros. """
regex = re.compile('[1-9][0-9]*')
match = regex.fullmatch(str(input_string))
return bool(match) | d1217c444bd457d97d6a60acc898d86638c70554 | 607,862 |
import string
def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers and spaces.
shift: 0 <= int < 26
returns: dict
"""
# Check constrain on shift
asser... | 04b9a6db54f1e085e25c8af53b83a4dc777bd6c3 | 607,863 |
import math
def to_radians(degrees):
"""Converts a list of floats representing degrees to a list of radians.
Parameters
----------
degrees : list of :obj:`float`
List of degrees.
Returns
-------
list of :obj:`float`
List of radians.
"""
return [math.radians(d) for... | c733d5e6fa92e1df4086a31e98cf22b7c853cc34 | 607,864 |
from typing import List
from typing import Tuple
import re
def expand_string(string: str, to_replace: List[Tuple[str, str]]) -> str:
"""
Within string replace a character in the first value of a pair to the second value of a pair.
If the string contains the character in the second value, the character wil... | 1028ca8453caac521c05f77b3d6253242f64f9ca | 607,866 |
import csv
def get_rate_area_rates(file_path):
"""
reads plans.csv file and returns the content as a dictionary
Args:
file_path: the path to plans.csv file
Returns:
a dictionary mapping each rate area for Silver plans into a set of
rates
"""
rate_area_rates = dict()
... | 28b73106ef592335e162e95d56ab6b5759dbbeed | 607,871 |
def get_drifter_ids_from_ascii(filename):
"""
Returns a list of all drifter ids that are available in the GLAD
dataset
Parameters
----------
filename : string
Path to GLAD ascii data file.
Returns
-------
ids : list
A list of integers that represent all drifter ids ... | 850d423ee01dd993f28f4d93c123c29b54227558 | 607,873 |
def is_square(mat):
"""Ensure that an array is a 2-D square matrix."""
return (mat.ndim == 2) and (mat.shape[0] == mat.shape[1]) | 6b26692ab57b2419190ccac951d2453dda6923f6 | 607,874 |
import torch
def group_same_class_object(obj_classes, one_hot=True, num_classes=-1):
"""
Given a list of class results, group the object with the same class into a list.
Returns a list with the length of num_classes, where each bucket has the objects with the same class.
:param
obj_classes: (t... | cc9fb8fceb9ec74693dc75ea1ce1ebc97dfa4828 | 607,875 |
def format_grant(grant):
""" Convert a dict describing mysql grants into a GRANT command
Args:
grant - dict with keys string privileges, username, source_host, password
and a bool grant_option
Returns:
sql - A GRANT command in string format
"""
if grant['grant_option']:
... | a3863a4f5a7a7aa6b9d42d8251aa9e7453bd44a9 | 607,877 |
def clean_int_value_from_dict_object(dict_object, dict_name, dict_key, post_errors, none_allowed=False, no_key_allowed=False):
"""
This function takes a target dictionary and returns the integer value given by the given key.
Returns None if key if not found and appends any error messages to the post_errors ... | 15c61a8defcd28b0f609131e34fe8e328c00163b | 607,878 |
import sqlite3
def open_sqlite_db(fname: str):
"""Open sqlite database and return connection to the database"""
try:
conn = sqlite3.connect(f"{fname}")
c = conn.cursor()
except sqlite3.Error as e:
raise OSError(f"Error opening {fname}: {e}")
return (conn, c) | 5ea95d5eac5c769215e92978cfc44372a6f07b4d | 607,883 |
def downsample_im(image, rate=10):
"""Takes a numpy matrix of an image and returns a smaller version
Args:
image (ndarray) 2D array of an image
rate (int) the reduction rate to downsample
"""
return image[::rate, ::rate] | f8bb9a5b1db975ccd696e2e98cb99f5895c2d375 | 607,885 |
def addVectors(lst1, lst2):
"""Add two lists together like a vector."""
return list(map(int.__add__, lst1, lst2)) | 2c67927b6836a31addc14723e0e0f13e54f242f2 | 607,890 |
import struct
def _decode_int(s):
"""
Decodes the 4-byte strings representing a 4 byte big endian integer
into an int.
:param s: A 4 byte string representing an integer
:return: The integer the string passed represents
"""
return struct.unpack('>i', s)[0] | f98d1d1fa2365c74307fd68f3ddec273c68b012b | 607,893 |
def require_user(controller):
"""
Requires that a user is logged in
"""
if not controller.user:
return (False, "You must be logged in")
return True | 752b2619ebd8341fa50d1176662959ce1d3443de | 607,894 |
import hashlib
def md5triple(s:str,p:str,o:str) -> str:
"""create a md5 from a triple
Args:
* s: Subject of the triple pattern.
* p: Predicate of the triple pattern.
* o: Object of the triple pattern.
Returns:
the md5 of s+p+o.
"""
#print("md5:{},{}... | 8b9a0c7a386caeab5dc45738ad50d5efe1811d1f | 607,895 |
from typing import Iterable
from typing import Optional
def argmax(iterable: Iterable) -> Optional[int]:
"""
Find the first index of the biggest value in the iterable.
Parameters
----------
iterable : Iterable
Returns
-------
argmax : Optional[int]
Examples
--------
>>> ... | 2ab12ddad93b1e96058f2c3de834b206f99d1bcc | 607,898 |
def hamming_distance(target, test):
"""
Calculate the hamming distance between two tuples.
Arguments:
target (tuple): the target tuple.
test (tuple): the test tuple. Must have same length as target
Returns:
int: the hamming distance
"""
dist = 0
assert len(target) =... | 4d85a677cf04302a31a9c2f32e1e3a4fd634591a | 607,900 |
def get_data(filename):
"""
From data file, reads, formats and saves data as a list.
Args:
filename: the name of a data file such as data.txt.
Returns:
lines: a list of formatted and relevant data items extracted from the data file.
"""
f = open(filename, 'r')
lines = f.rea... | f9e17c7b9629e65fc6c89770f7e47ba0bcd9017f | 607,901 |
def get_column_width(column, table):
"""
Get the character width of a column in a table
Parameters
----------
column : int
The column index analyze
table : list of lists of str
The table of rows of strings. For this to be accurate, each
string must only be 1 line long.
... | ce6b0b010cbd997bc537b6aec5523d0f0d186075 | 607,907 |
def _GetShivasCIPD(api):
"""Install shivas CIPD package and return path to the binary."""
packages_dir = api.path['cleanup'].join('packages')
ensure_file = api.cipd.EnsureFile()
ensure_file.add_package('infra/shivas/${platform}', 'prod')
api.cipd.ensure(packages_dir, ensure_file)
return packages_dir.join('s... | 0b21ac484c22839a3acfd2f56075d3eb1f72106c | 607,908 |
def clean_route_list(route_stack: list, goal_node_id: int):
"""
Creates an ordered route list from start to finish
with all node ids needed to traverse to the goal.
:param route_stack: All routes found until goal
:param goal_node: int ID of the goal node
:return: list A ordered list from start to... | c66feb9efe3dadb72779852478c25c545fdec7c2 | 607,909 |
def Renormalize(similarity,
metric = "carbo",
customrange = None,
):
"""
Renormalizes a similarity metric to the range [0:1]
:param similarity: Similarity score.
:param mode: (optional) Mode of similarity score
:param customrange: (optional) Custom range of similarity... | 52a771341b678ffde953b088712d69b40355fc29 | 607,912 |
def chunk_it(token_list):
"""
Compute noun chunks from Spacy docs
Parameters
----------
token_list: list of spacy docs
Returns
-------
chunks: list of lists
a list containing lists of noun chunks
"""
chunks = [comment.noun_chunks for comment in token_list]
return ... | 872b4d7ae27a6bba64dc19897ef4fed97e0ae31a | 607,918 |
import re
def is_sha(rev):
"""Heuristically determine whether a revision corresponds to a commit SHA.
Any sequence of 7 to 40 hexadecimal digits will be recognized as a
commit SHA. The minimum of 7 digits is not an arbitrary choice, it
is the default length for short SHAs in Git.
"""
return r... | 084b54069ca86e3fecfff7bf2aaebff6cce67136 | 607,919 |
def _GuessCharset(text):
"""Guess the charset of a text.
Args:
text: a string (str) that is either a us-ascii string or a unicode that was
encoded in utf-8.
Returns:
Charset needed by the string, either 'us-ascii' or 'utf-8'.
"""
try:
text.decode('us-ascii')
return 'us-ascii'
except... | 0b334ba933c8586e787bf364e402c4d6181a5658 | 607,926 |
def select_stitched_contig_count(cxn, ref_name, taxon_name, iteration=0):
"""Select stitched contigs for a reference taxon pair."""
result = cxn.execute(
"""SELECT COUNT(*) AS hits
FROM stitched
WHERE ref_name = ?
AND taxon_name = ?
AND iteration =... | f6d8c1b12f1d93a48f566d7c121b9c8aa02938d8 | 607,927 |
def percentile(n: int):
"""Percentile function that can be passed to pandas agg() function
AND changes column name.
"""
def percentile_(x):
return x.quantile(n)
percentile_.__name__ = 'q%s' % n
return percentile_ | b84cf47a61765a9554b10f0945b7e34ac81b3979 | 607,928 |
import json
def create_push_notification(package, repository):
# type: (str, str) -> str
"""Create notification about new push event encoded into JSON string."""
notification_dict = {
"repository": repository,
"package": package,
"event": "push",
}
return json.dumps(notific... | dc3a81d59bd6c6ba4a4ca7a90fdcf116622f80b9 | 607,934 |
from typing import Set
import re
def get_changed_lines(diff: str) -> Set[int]:
"""Parse changed lines from git diff -U0 output.
- Change data according to git diff output:
- @@ -old0,old1 +new0,new1 @@
- old0 to old0 + old1 are now new0 to new0 + new1
- changed lines = old0 to old0 + old1 (last no... | c979d45da1aa785c70d3bc75f4ac02a752543623 | 607,937 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.