content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_regex_flags(raw_flags: str = 'gim'):
"""
parse flags user input and convert them to re flags.
Args:
raw_flags: string chars representing er flags
Returns:
(re flags, whether to return multiple matches)
"""
raw_flags = raw_flags.lstrip('-') # compatibility with origi... | 5,346,300 |
def create_parser():
""" Create argparse object for this CLI """
parser = argparse.ArgumentParser(
description="Remove doubled extensions from files")
parser.add_argument("filename", metavar="file",
help="File to process")
return parser | 5,346,301 |
def has_answer(answers, retrieved_text, match='string', tokenized: bool = False):
"""Check if retrieved_text contains an answer string.
If `match` is string, token matching is done between the text and answer.
If `match` is regex, we search the whole text with the regex.
"""
if not isinstance(answe... | 5,346,302 |
def get_utm_zone(srs):
"""
extracts the utm_zone from an osr.SpatialReference object (srs)
returns the utm_zone as an int, returns None if utm_zone not found
"""
if not isinstance(srs, osr.SpatialReference):
raise TypeError('srs is not a osr.SpatialReference instance')
if srs.IsProjec... | 5,346,303 |
def test_create_with_manager():
"""Test getting a created test user with manager"""
user, user_key, manager, manager_key = helper.user.create_with_manager()
assert isinstance(user, protobuf.user_state_pb2.User)
assert isinstance(manager, protobuf.user_state_pb2.User)
assert isinstance(user.next_id,... | 5,346,304 |
def launcher(cmd):
"""Start a new terminal instance with defined command"""
global thread_id
print() # Just for clean output
logging.info("Thread %s: Starting :- %s", thread_id, cmd)
os.system(cmd)
logging.info("Thread %s: Finished :- %s", thread_id, cmd)
thread_id -= 1 | 5,346,305 |
def get_documents_meta_url(project_id: int, limit: int = 10, host: str = KONFUZIO_HOST) -> str:
"""
Generate URL to load meta information about the Documents in the Project.
:param project_id: ID of the Project
:param host: Konfuzio host
:return: URL to get all the Documents details.
"""
re... | 5,346,306 |
def CalcUB(idx1, idx2, replace=False, reflist=None):
"""Calculate a UB matrix from the cell and two reflections
idx1 and idx2 in reflist. Replace the current UB matrix when
replace is True"""
sample, inst = getSampleInst()
if not sample:
return
rfl = sample.getRefList(reflist)
if rfl... | 5,346,307 |
def parse_params_from_string(paramStr: str) -> dict:
""" Create a dictionary representation of parameters in PBC format
"""
params = dict()
lines = paramStr.split('\n')
for line in lines:
if line:
name, value = parse_param_line(line)
add_param(params, name, value)
... | 5,346,308 |
def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False):
""" Horizontally concatenate gctoos.
Args:
gctoos (list of gctoo objects)
remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos
error_... | 5,346,309 |
def number_fixed_unused_variables(block):
"""
Method to return the number of fixed Var components which do not appear
within any activated Constraint in a model.
Args:
block : model to be studied
Returns:
Number of fixed Var components which do not appear within any activated
... | 5,346,310 |
def tunnelX11( node, display=None):
"""Create an X11 tunnel from node:6000 to the root host
display: display on root host (optional)
returns: node $DISPLAY, Popen object for tunnel"""
if display is None and 'DISPLAY' in environ:
display = environ[ 'DISPLAY' ]
if display is None:
... | 5,346,311 |
def static_docs(file_path):
"""Serve the 'docs' folder static files and redirect folders to index.html.
:param file_path: File path inside the 'docs' folder.
:return: Full HTTPResponse for the static file.
"""
if os.path.isdir(os.path.join(document_root, 'docs', file_path)):
return r... | 5,346,312 |
def get_aws_account_id_file_section_dict() -> collections.OrderedDict:
"""~/.aws_accounts_for_set_aws_mfa から Section 情報を取得する"""
# ~/.aws_accounts_for_set_aws_mfa の有無を確認し、なければ生成する
prepare_aws_account_id_file()
# 該当 ini ファイルのセクション dictionary を取得
return Config._sections | 5,346,313 |
def profile(request, session_key):
"""download_audio.html renderer.
:param request: rest API request object.
:type request: Request
:param session_key: string representing the session key for the user
:type session_key: str
:return: Just another django mambo.
:rtype: HttpResponse
... | 5,346,314 |
def genotype_vcf(
args,
input_vcf: str,
input_sim: str,
input_real: str,
output_file=sys.stdout,
remove_z=5.0,
samples=[],
):
"""Write new VCF with NPSV-determined genotypes
Args:
args (argparse.Namespace): Command arguments
input_vcf (str): Path to input VCF file
... | 5,346,315 |
def pipFetchLatestVersion(pkg_name: str) -> str:
"""
Fetches the latest version of a python package from pypi.org
:param pkg_name: package to search for
:return: latest version of the package or 'not found' if error was returned
"""
base_url = "https://pypi.org/pypi"
request = f"{base_url}/{... | 5,346,316 |
def _GetLastAuthor():
"""Returns a string with the author of the last commit."""
author = subprocess.check_output(['git', 'log',
'-1',
'--pretty=format:"%an"']).splitlines()
return author | 5,346,317 |
def PlotPolygons(Polygons, Map=None, Ax=None, OutlineColour='k', FillColour='w', ColourMap="None", alpha=0.5):
"""
Function to plot polygons from a shapely Polygon Dictionary
Modified from PlottingRaster.py code by FJC
Outline colour can be name, tuple or range of value to shade
MDH
"""
... | 5,346,318 |
def mock_datasource_http_oauth2(mock_datasource):
"""Mock DataSource object with http oauth2 credentials"""
mock_datasource.credentials = b"client_id: FOO\nclient_secret: oldisfjowe84uwosdijf"
mock_datasource.location = "http://foo.com"
return mock_datasource | 5,346,319 |
def test_050_person_image_file():
"""Test person_image_file method."""
# FORM is subordinate of OBJE
dialect = model.Dialect.MYHERITAGE
form = model.make_record(2, None, "FORM", "JPG",
[], 0, dialect, None).freeze()
file = model.make_record(
2, None, "FILE", "/p... | 5,346,320 |
def os_environ():
"""
clear os.environ, and restore it after the test runs
"""
# for use whenever you expect code to edit environment variables
old_env = os.environ.copy()
os.environ = {}
yield
os.environ = old_env | 5,346,321 |
async def test_if_fires_on_transmitter_event(hass, calls, entry, lcn_connection):
"""Test for transmitter event triggers firing."""
address = (0, 7, False)
device = get_device(hass, entry, address)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automa... | 5,346,322 |
def save_pred_vs_label_4tuple(
img_rgb: np.ndarray, label_img: np.ndarray, id_to_class_name_map: Mapping[int, str], save_fpath: str
) -> None:
"""7-tuple consists of
(1-3) rgb mask 3-sequence for label or predictions
(4) color palette
Args:
img_rgb
la... | 5,346,323 |
def find_certificate_name(file_name):
"""Search the CRT for the actual aggregator name."""
# This loop looks for the collaborator name in the key
with open(file_name, 'r') as f:
for line in f:
if 'Subject: CN=' in line:
col_name = line.split('=')[-1].strip()
... | 5,346,324 |
def _find_module(module):
"""Find module using imp.find_module.
While imp is deprecated, it provides a Python 2/3 compatible
interface for finding a module. We use the result later to load
the module with imp.load_module with the '__main__' name, causing
it to execute.
The non-deprecated metho... | 5,346,325 |
def update_counts(partno, quantity, batchname, message):
"""
Updates the given stock entry, creating it if necessary.
Raises an exception if the part number is not valid or if there is a database problem
"""
_check_bom(partno) # validation
_do_update_counts(partno, quantity, batchname, message) | 5,346,326 |
def drop_object():
"""Drop an object into the scene."""
global bodies, geom, counter, objcount
body, geom = create_box(world, space, 1000, 0.2,0.2,0.2)
body.setPosition( (random.gauss(0,0.1),3.0,random.gauss(0,0.1)) )
theta = random.uniform(0,2*pi)
ct = cos (theta)
st = sin (theta)
bod... | 5,346,327 |
def float2bin(p: float, min_bits: int = 10, max_bits: int = 20, relative_error_tol=1e-02) -> List[bool]:
""" Converts probability `p` into binary list `b`.
Args:
p: probability such that 0 < p < 1
min_bits: minimum number of bits before testing relative error.
max_bits: maximum number o... | 5,346,328 |
def bin_thresh(img: np.ndarray, thresh: Number) -> np.ndarray:
"""
Performs binary thresholding of an image
Parameters
----------
img : np.ndarray
Image to filter.
thresh : int
Pixel values >= thresh are set to 1, else 0.
Returns
-------
np.ndarray :
Binariz... | 5,346,329 |
def add_object_align_init(context, operator):
"""
Return a matrix using the operator settings and view context.
:arg context: The context to use.
:type context: :class:`bpy.types.Context`
:arg operator: The operator, checked for location and rotation properties.
:type operator: :class:`bpy.type... | 5,346,330 |
def _main() -> None:
"""実行用スクリプト."""
ut.init_root_logger()
config = utils.load_config_from_input_args(lambda x: Config(**x))
if config is None:
_logger.error("config error.")
return
filepath = download(config)
_logger.info(f"download path: {filepath}") | 5,346,331 |
def load_dataset():
"""
load dataset
:return: dataset in numpy style
"""
data_location = 'data.pk'
data = pickle.load(open(data_location, 'rb'))
return data | 5,346,332 |
def video_feed():
"""Return camera live feed."""
return Response(gen(Camera()),
mimetype='multipart/x-mixed-replace; boundary=frame') | 5,346,333 |
def run(flist):
"""
Iterate over a list of files and yields each line sequentially.
Parameters
----------
flist : list of file-like objects
Must handle `.close()` attribute.
Yields
------
str (line-by-line)
Lines from the concatenated PDB files.
"""
for fhandle... | 5,346,334 |
def allocatable_production(dataset):
"""Return generator of production exchanges for a dataset.
Production exchanges either:
* Have type ``reference product``, or
* Have type ``byproduct`` and ``classification`` is ``allocatable product``
Note that all types of reference products are returned: ``... | 5,346,335 |
def test_capture_and_release_default_warning_handler(loguru_logger: Logger):
"""Ensure the module can capture and release the default warnings handler."""
assert not isinstance(warnings.showwarning, partial)
assert warnings.showwarning == DEFAULT_SHOWARNING
assert python_warnings.capture(loguru_logger... | 5,346,336 |
def area_in_squaremeters(geodataframe):
"""Calculates the area sizes of a geo dataframe in square meters.
Following https://gis.stackexchange.com/a/20056/77760 I am choosing equal-area projections
to receive a most accurate determination of the size of polygons in the geo dataframe.
Instead of Gall-Pet... | 5,346,337 |
def main() -> None:
"""Compares the Alma records to the current WorldCat holdings.
Outputs the following files:
- records_with_no_action_needed.csv
The OCLC numbers found in both the alma_records_file and the
worldcat_records_directory
- records_to_set_in_worldcat.csv
The OCLC n... | 5,346,338 |
def add_eges_grayscale(image):
""" Edge detect.
Keep original image grayscale value where no edge.
"""
greyscale = rgb2gray(image)
laplacian = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
edges = scipy.ndimage.filters.correlate(greyscale, laplacian)
for index,value in np.ndenumerate(edges... | 5,346,339 |
def generateFromSitePaymentObject(signature: str, account_data: dict, data: dict)->dict:
"""[summary]
Creates object for from site chargment request
Args:
signature (str): signature hash string
account_data (dict): merchant_account: str
merchant_domain: str
... | 5,346,340 |
def deal_weights(node, data=None):
""" deal the weights of the custom layer
"""
layer_type = node.layer_type
weights_func = custom_layers[layer_type]['weights']
name = node.layer_name
return weights_func(name, data) | 5,346,341 |
def label_brand_generic(df):
""" Correct the formatting of the brand and generic drug names """
df = df.reset_index(drop=True)
df = df.drop(['drug_brand_name', 'drug_generic_name'], axis=1)
df['generic_compare'] = df['generic_name'].str.replace('-', ' ')
df['generic_compare'] = df['generic_compare']... | 5,346,342 |
def RMSRE(
image_true: np.ndarray,
image_test: np.ndarray,
mask: np.ndarray = None,
epsilon: float = 1e-9,
) -> float:
"""Root mean squared relative error (RMSRE) between two images within the
specified mask. If not mask is specified the entire image is used.
Parameters
----------
i... | 5,346,343 |
def test_ksic10_to_isic4_concordance(code: str, expected: str):
"""Test KSIC10 to ISIC4 sample concordances."""
assert KSIC10_to_ISIC4.concordant(code) == expected | 5,346,344 |
def getImage(imageData, flag):
"""
Returns the PIL image object from imageData based on the flag.
"""
image = None
try:
if flag == ENHANCED:
image = PIL.Image.open(imageData.enhancedImage.file)
elif flag == UNENHANCED:
image = PIL.Image.open(imageData.unenhan... | 5,346,345 |
def save_record(record_type,
record_source,
info,
indicator,
date=None):
"""
A convenience function that calls 'create_record' and also saves the resulting record.
:param record_type: The record type, which should be a value from the RecordTyp... | 5,346,346 |
def test_adding_existing_data_is_idempotent(learner_type, f, learner_kwargs):
"""Adding already existing data is an idempotent operation.
Either it is idempotent, or it is an error.
This is the only sane behaviour.
"""
f = generate_random_parametrization(f)
learner = learner_type(f, **learner_k... | 5,346,347 |
def update_product_price(pid: str, new_price: int):
""" Update product's price
Args:
pid (str): product id
new_price (int): new price
Returns:
dict: status(success, error)
"""
playload = {'status': ''}
try:
connection = create_connection()
with connectio... | 5,346,348 |
def select_n_products(lst, n):
"""Select the top N products (by number of reviews)
args:
lst: a list of lists that are (key,value) pairs for (ASIN, N-reviews)
sorted on the number of reviews in reverse order
n: a list of three numbers,
returns:
a list of... | 5,346,349 |
def load_vanHateren(params):
"""
Load van Hateren data and format as a Dataset object
Inputs:
params [obj] containing attributes:
data_dir [str] directory to van Hateren data
rand_state (optional) [obj] numpy random state object
num_images (optional) [int] how many images to extract. Default... | 5,346,350 |
def build_parser() -> argparse.ArgumentParser:
"""Builds and returns the CLI parser."""
# Help parser
help_parser = argparse.ArgumentParser(add_help=False)
group = help_parser.add_argument_group('Help and debug')
group.add_argument('--debug',
help='Enable debug output.',
... | 5,346,351 |
def parse_args():
"""Parse command-line args.
"""
parser = argparse.ArgumentParser(description = 'Upload (JSON-encoded) conformance resources from FHIR IGPack tar archive.', add_help = False)
parser.add_argument('-h', '--help', action = 'store_true', help = 'show this help message and exit')
parser... | 5,346,352 |
def wrap_to_pi(inp, mask=None):
"""Wraps to [-pi, pi)"""
if mask is None:
mask = torch.ones(1, inp.size(1))
if mask.dim() == 1:
mask = mask.unsqueeze(0)
mask = mask.to(dtype=inp.dtype)
val = torch.fmod((inp + pi) * mask, 2 * pi)
neg_mask = (val * mask) < 0
val = val + 2 * p... | 5,346,353 |
def if_pandas(func):
"""Test decorator that skips test if pandas not installed."""
@wraps(func)
def run_test(*args, **kwargs):
try:
import pandas
except ImportError:
pytest.skip('Pandas not available.')
else:
return func(*args, **kwargs)
return... | 5,346,354 |
def handle_front_pots(pots, next_pots):
"""Handle front, additional pots in pots."""
if next_pots[2] == PLANT:
first_pot = pots[0][1]
pots = [
[next_pots[2], first_pot - 1]] + pots
return pots, next_pots[2:]
return pots, next_pots[3:] | 5,346,355 |
def run_example_activity_tests():
"""Parses and validates example activity file."""
fname = os.path.join(
os.path.dirname(__file__), '../assets/js/activity-examples.js')
if not os.path.exists(fname):
raise Exception('Missing file: %s', fname)
verifier = Verifier()
verifier.echo_func... | 5,346,356 |
def environment(envdata):
"""
Class decorator that allows to run tests in sandbox against different Qubell environments.
Each test method in suite is converted to <test_name>_on_environemnt_<environment_name>
:param params: dict
"""
#assert isinstance(params, dict), "@environment decorator shoul... | 5,346,357 |
def convert_vcf(i_filename, sample_info, o_prefix, skip_haploid):
"""Reads a VCF and creates a TPED/TFAM from it.
:param i_filename: the name of the VCF file (might be gzip).
:param sample_info: information about the samples.
:param o_prefix: the prefix of the output files.
:param skip_haploid: whe... | 5,346,358 |
def get_domain_name(url):
""" Returns the domain name from a URL """
parsed_uri = urlparse(url)
return parsed_uri.netloc | 5,346,359 |
def get_answer_str(answers: list, scale: str):
"""
:param ans_type: span, multi-span, arithmetic, count
:param ans_list:
:param scale: "", thousand, million, billion, percent
:param mode:
:return:
"""
sorted_ans = sorted(answers)
ans_temp = []
for ans in sorted_ans:
ans... | 5,346,360 |
def user_0post(users):
"""
Fixture that returns a test user with 0 posts.
"""
return users['user2'] | 5,346,361 |
def initialize():
"""
Initialize some parameters, such as API key
"""
api_key = os.environ.get("api_key") # None when not exist
if api_key and len(api_key) == 64: # length of a key should be 64
return api_key
print("Please set a valid api_key in the environment variables.")
exit() | 5,346,362 |
def plot_tuning_curve_evo(data, epochs=None, ax=None, cmap='inferno_r',
linewidth=0.3, ylim='auto',
include_true=True,
xlabel='Bandwidths',
ylabel='Average Firing Rate'):
"""
Plot evolution of TC averaged ove... | 5,346,363 |
def transportinfo_decoder(obj):
"""Decode programme object from json."""
transportinfo = json.loads(obj)
if "__type__" in transportinfo and transportinfo["__type__"] == "__transportinfo__":
return TransportInfo(**transportinfo["attributes"])
return transportinfo | 5,346,364 |
def group_events_data(events):
"""
Group events according to the date.
"""
# e.timestamp is a datetime.datetime in UTC
# change from UTC timezone to current seahub timezone
def utc_to_local(dt):
tz = timezone.get_default_timezone()
utc = dt.replace(tzinfo=timezone.utc)
lo... | 5,346,365 |
def onesetup(places, numtwts, numtest, balance):
""" This setup considers the tweets from the places in the list and select
some number of tweets from those places as testing tweets, the query is just one tweet
@arg city the place_id of the city
@arg num the number of tweets generated
... | 5,346,366 |
def create_matrix(PBC=None):
"""
Used for calculating distances in lattices with periodic boundary conditions. When multiplied with a set of points, generates additional points in cells adjacent to and diagonal to the original cell
Args:
PBC: an axis which does not have periodic boundary condition.... | 5,346,367 |
def get_additive_seasonality_linear_trend() -> pd.Series:
"""Get example data for additive seasonality tutorial"""
dates = pd.date_range(start="2017-06-01", end="2021-06-01", freq="MS")
T = len(dates)
base_trend = 2
state = np.random.get_state()
np.random.seed(13)
observations = base_trend *... | 5,346,368 |
async def test_creating_entry_tries_discover(hass):
"""Test setting up does discovery."""
with MOCK_PYHS100, patch(
"homeassistant.components.tplink.async_setup_entry",
return_value=mock_coro(True),
) as mock_setup, patch(
"pyHS100.Discover.discover", return_value={"host": 1234}
... | 5,346,369 |
def is_client_trafic_trace(conf_list, text):
"""Determine if text is client trafic that should be included."""
for index in range(len(conf_list)):
if text.find(conf_list[index].ident_text) != -1:
return True
return False | 5,346,370 |
def convert_range(g, op, block):
"""Operator converter for range."""
start = g.get_node(op.input("Start")[0])
stop = g.get_node(op.input("End")[0])
step = g.get_node(op.input("Step")[0])
dtype = infer_type(start).checked_type.dtype
params = []
for param in (start, stop, step):
para... | 5,346,371 |
def isinf(x):
"""
For an ``mpf`` *x*, determines whether *x* is infinite::
>>> from sympy.mpmath import *
>>> isinf(inf), isinf(-inf), isinf(3)
(True, True, False)
"""
if not isinstance(x, mpf):
return False
return x._mpf_ in (finf, fninf) | 5,346,372 |
def do_run_comparison(source,
config_input,
suppress_warnings_for=[]):
"""
Run rsmcompre experiment automatically.
Use the given experiment configuration file located in the given
source directory.
Parameters
----------
source : str
Path ... | 5,346,373 |
def formalize_switches(switches):
"""
Create all entries for the switches in the topology.json
"""
switches_formal=dict()
for s, switch in enumerate(switches):
switches_formal["s_"+switch]=formalize_switch(switch, s)
return switches_formal | 5,346,374 |
def check_coords(X, x_lat_dim, x_lon_dim, x_sample_dim, x_feature_dim):
"""Checks that X has coordinates named as specified by x_lat_dim, x_lon_dim, x_sample_dim, and x_feature_dim"""
assert x_lat_dim in X.coords.keys(), 'XCast requires a dataset_lat_dim to be a coordinate on X'
assert x_lon_dim in X.coords.keys(), ... | 5,346,375 |
def arp_scores(run):
"""
This function computes the Average Retrieval Performance (ARP) scores according to the following paper:
Timo Breuer, Nicola Ferro, Norbert Fuhr, Maria Maistro, Tetsuya Sakai, Philipp Schaer, Ian Soboroff.
How to Measure the Reproducibility of System-oriented IR Experiments.
... | 5,346,376 |
def init_testlink():
"""Test link initialization"""
if not TLINK.enabled:
return
# connect to test link
TLINK.rpc = testlink.TestlinkAPIClient(server_url=TLINK.conf['xmlrpc_url'],
devKey=TLINK.conf['api_key'])
# assert test project exists
_test... | 5,346,377 |
def bayesian_proportion_test(
x:Tuple[int,int],
n:Tuple[int,int],
prior:Tuple[float,float]=(0.5,0.5),
prior2:Optional[Tuple[float,float]]=None,
num_samples:int=1000,
seed:int=8675309) -> Tuple[float,float,float]:
""" Perform a Bayesian test to identify significantly ... | 5,346,378 |
def _create_triangular_filterbank(
all_freqs: Tensor,
f_pts: Tensor,
) -> Tensor:
"""Create a triangular filter bank.
Args:
all_freqs (Tensor): STFT freq points of size (`n_freqs`).
f_pts (Tensor): Filter mid points of size (`n_filter`).
Returns:
fb (Tens... | 5,346,379 |
def convert_millis(track_dur_lst):
""" Convert milliseconds to 00:00:00 format """
converted_track_times = []
for track_dur in track_dur_lst:
seconds = (int(track_dur)/1000)%60
minutes = int(int(track_dur)/60000)
hours = int(int(track_dur)/(60000*60))
converted_time = '%... | 5,346,380 |
def start_server(use_sendfile, keep_sending=False):
"""A simple test server which sends a file once a client connects.
use_sendfile decides whether using sendfile() or plain send().
If keep_sending is True restart sending file when EOF is reached.
"""
sock = socket.socket()
sock.setsockopt(socke... | 5,346,381 |
def sync_xlims(*axes):
"""Synchronize the x-axis data limits for multiple axes. Uses the maximum
upper limit and minimum lower limit across all given axes.
Parameters
----------
*axes : axis objects
List of matplotlib axis objects to format
Returns
-------
out : yxin, xmax
... | 5,346,382 |
def algo_config_to_class(algo_config):
"""
Maps algo config to the IRIS algo class to instantiate, along with additional algo kwargs.
Args:
algo_config (Config instance): algo config
Returns:
algo_class: subclass of Algo
algo_kwargs (dict): dictionary of additional kwargs to pa... | 5,346,383 |
def group_by_key(dirnames, key):
"""Group a set of output directories according to a model parameter.
Parameters
----------
dirnames: list[str]
Output directories
key: various
A field of a :class:`Model` instance.
Returns
-------
groups: dict[various: list[str]]
... | 5,346,384 |
def test_transform():
"""2D and 3D"""
WGS84_crs = {'init': 'EPSG:4326'}
WGS84_points = ([12.492269], [41.890169], [48.])
ECEF_crs = {'init': 'EPSG:4978'}
ECEF_points = ([4642610.], [1028584.], [4236562.])
ECEF_result = transform(WGS84_crs, ECEF_crs, *WGS84_points)
assert numpy.allclose(numpy... | 5,346,385 |
def redistrict_grouped(df, kind, group_cols, district_col=None,
value_cols=None, **kwargs):
"""Redistrict dataframe by groups
Args:
df (pandas.DataFrame): input dataframe
kind (string): identifier of redistrict info (e.g. de/kreise)
group_cols (list): List of colu... | 5,346,386 |
def count_wraps_rand(
nr_parties: int, shape: Tuple[int]
) -> Tuple[List[ShareTensor], List[ShareTensor]]:
"""Count wraps random.
The Trusted Third Party (TTP) or Crypto provider should generate:
- a set of shares for a random number
- a set of shares for the number of wraparounds for that number
... | 5,346,387 |
def update_processing_with_collection_contents(updated_processing, new_processing=None, updated_collection=None,
updated_files=None, new_files=None,
coll_msg_content=None, file_msg_content=None, transform_updates=None,
... | 5,346,388 |
def text_sim(
sc1: Sequence,
sc2: Sequence,
) -> float:
"""Returns the Text_Sim similarity measure between two pitch class sets.
"""
sc1 = prime_form(sc1)
sc2 = prime_form(sc2)
corpus = [text_set_class(x) for x in sorted(allClasses)]
vectorizer = TfidfVectorizer()
trsfm = vecto... | 5,346,389 |
def _feature_properties(feature, layer_definition, whitelist=None, skip_empty_fields=False):
""" Returns a dictionary of feature properties for a feature in a layer.
Third argument is an optional list or dictionary of properties to
whitelist by case-sensitive name - leave it None to include eve... | 5,346,390 |
def reverse_search(view, what, start=0, end=-1, flags=0):
"""Do binary search to find `what` walking backwards in the buffer.
"""
if end == -1:
end = view.size()
end = find_eol(view, view.line(end).a)
last_match = None
lo, hi = start, end
while True:
middle = (lo + hi) / 2
... | 5,346,391 |
def formatLookupLigatureSubstitution(lookup, lookupList, makeName=makeName):
""" GSUB LookupType 4 """
# substitute <glyph sequence> by <glyph>;
# <glyph sequence> must contain two or more of <glyph|glyphclass>. For example:
# substitute [one one.oldstyle] [slash fraction] [two two.oldstyle] by onehalf;... | 5,346,392 |
def convert_raw2nc(path2rawfolder = '/nfs/grad/gradobs/raw/mlo/2020/', path2netcdf = '/mnt/telg/data/baseline/mlo/2020/',
# database = None,
start_date = '2020-02-06',
pattern = '*sp02.*',
sernos = [1032, 1046],
site = 'mlo'... | 5,346,393 |
def zenith_simple_env(_shared_simple_env: ZenithEnv) -> Iterator[ZenithEnv]:
"""
Simple Zenith environment, with no authentication and no safekeepers.
If TEST_SHARED_FIXTURES environment variable is set, we reuse the same
environment for all tests that use 'zenith_simple_env', keeping the
page serv... | 5,346,394 |
def get_curricula(course_url, year):
"""Encodes the available curricula for a given course in a given year in a vaguely sane format
Dictionary fields:
- constant.CODEFLD: curriculum code as used in JSON requests
- constant.NAMEFLD: human-readable curriculum name"""
curricula = []
curricula_... | 5,346,395 |
def conv3x3(in_planes, out_planes, stride=1, groups=1):
"""3x3 conv with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, groups=groups, bias=False) | 5,346,396 |
def extract_facility_data(inventory_dict):
"""
Returns df of facilities from each inventory in inventory_dict,
including FIPS code
:param inventory_dict: a dictionary of inventory types and years (e.g.,
{'NEI':'2017', 'TRI':'2017'})
:return: df
"""
import stewi
facility_m... | 5,346,397 |
def test_log_interp_units():
"""Test interpolating with log x-scale with units."""
x_log = np.array([1e3, 1e4, 1e5, 1e6]) * units.hPa
y_log = (np.log(x_log.m) * 2 + 3) * units.degC
x_interp = np.array([5e5, 5e6, 5e7]) * units.Pa
y_interp_truth = np.array([20.0343863828, 24.6395565688, 29.2447267548]... | 5,346,398 |
def post_five_days_weather_data(message, option, city_name):
"""
指定された都市に関する5日間の天気予報を表示する。
コマンド: "tenki [-5 cityname|--five cityname]"
"""
post_message = tenkibot_service.make_5_days_weather_message(city_name)
message.send('{}'.format(post_message)) | 5,346,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.