content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def bsi_calc(swir, red, nir, blue):
"""
Bare soil index
"""
return ((swir + red)-(nir + blue))/((swir + red)+(nir + blue)) | d290c904ac7656b9892901dc6f56e5729614d775 | 666,556 |
def number_of_fish(days, value=8):
"""
>>> number_of_fish(1)
1
>>> number_of_fish(8)
1
>>> number_of_fish(9)
2
>>> number_of_fish(15)
2
>>> number_of_fish(16)
3
>>> number_of_fish(18)
4
>>> number_of_fish(25)
7
>>> number_of_fish(47)
38
>>> number_... | 1754e6d426b5073713b96083bfc48f93c9b1f66c | 666,558 |
def box_area(boxes):
""" compute area of a set of boxes in (x1, y1, x2, y2) format
Args:
boxes: paddle.Tensor, shape = Nx4, must in (x1, y1, x2, y2) format
Return:
areas: paddle.Tensor, N, areas of each box
"""
return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) | 590426521d1e99548c4c2b4e3ea2e23f09bef53a | 666,559 |
from typing import Callable
from typing import Any
from functools import reduce
def and_then(*args: Callable[[Any], Any]) -> Callable[[Any], Any]:
"""和compose采用不同的fold方向的函数
"""
return reduce(lambda f, g: lambda x: g(f(x)), args) | d1f9e7bfb2e666a3c5badc157b35f7348e61273b | 666,561 |
def clean_spaces(txt):
"""
Removes multiple spaces from a given string.
Args:
txt (str): given string.
Returns:
str: updated string.
"""
return " ".join(txt.split()) | d6b354550ce0aadcf96d3e5131163bd10f27fce7 | 666,562 |
import os
def get_mongo_version():
"""
Parse MongoDB version from environment as numbers. Returns a dictionary of "major" version as a float and
"minor" version as an integer.
"""
parts = list(map(lambda v: int(v), os.environ["MONGO_VERSION"].split('.')))
return {
"major": float("%i.%i... | 33bb5d983dc4f1f398e34eb4413805b4c6571c1d | 666,563 |
def process_z_slice_list(img_obj_list, config):
"""Make sure all members of z_slices are part of io_obj.
If z_slices = 'all', replace with actual list of z_slices
Parameters
----------
img_obj_list: list
list of mManagerReader instances
config: obj
ConfigReader instance
Ret... | d4142f3c32fffff4cd733bc9f7a912526c36d993 | 666,564 |
def f(fstr):
"""f-strings for older versions of Python
i.e 2.7, 3.5 and eariler.
Uses globals(), which is somewhat hacky.
"""
if type(fstr) is str:
return fstr.format(**globals())
else:
return None | c424554f020bda132b4545cf1b9e3142a86e1095 | 666,565 |
def blur_augment(is_training=True, **kwargs):
"""Applies random blur augmentation."""
if is_training:
prob = kwargs['prob'] if 'prob' in kwargs else 0.5
return [('blur', {'prob': prob})]
return [] | bb4254ba956109ea9b2aa52a785d75b810a1b524 | 666,566 |
import torch
def masked_softmax(x, m=None, dim=-1):
"""
Softmax with mask.
:param x: the Tensor to be softmaxed.
:param m: mask.
:param dim:
:return:
"""
if m is not None:
m = m.float()
x = x * m
e_x = torch.exp(x - torch.max(x, dim=dim, keepdim=True)[0])
if m i... | c527bfd3102d0c69976fe4ea4e0cddfcd791eb06 | 666,567 |
import numpy
def L1d1d1(x):
"""
Second derivative for the linear lagrange basis function.
:param x: points to interpolate
:type x: numpy array (npoints)
:return: basis weights
:rtype: numpy array (npoints, 2)
"""
return numpy.zeros((x.shape[0], 2)) | 7fd90d3fcda872b7763e34c40c6669541e8f422a | 666,568 |
import pandas
def codelist_table_from_csv():
"""Returns a codelist table the could have been read from a CSV file."""
return pandas.DataFrame(
{
"code": pandas.Series([1, 2]),
"term": pandas.Series(["Code 1", "Code 2"]),
}
) | a3d7653956ee130e90ab2a9559d3b3db04ec402e | 666,569 |
def getCoord(percentX, percentY, image_size):
"""
Returns the width and height coordinates given the percentage of
the image size you want
percentX - percentage along x axis
percentY - percentage along y axis
image_size - tuple (width, height) of the total size of the image
@return - tuple f... | 7d88b9561d2f758df078e31022ad075120e7d2e5 | 666,571 |
def annotate_metadata_dependencies(repo):
"""
Collect information from the dependent repo's
"""
options = repo.options
if 'dependencies' not in options:
print("No dependencies")
return []
repos = []
dependent_repos = options['dependencies']
for d in dependent_repos:
... | d72e7292d088ef566335580f30df95e48a2366d3 | 666,573 |
import requests
from bs4 import BeautifulSoup
def scrape_reviews(isbn):
"""
Scrape reviews from book's Goodreads webpage using BeautifulSoup 4.
Return a list of tuples (names,rating,reviews)
"""
book_page_url = f"https://www.goodreads.com/api/reviews_widget_iframe?did=0&format=html&hide_last_page... | cf387e368c7c97cee1f8bced4551e40d5fa9a3ee | 666,574 |
import re
import json
def parse_output(s):
"""Parse a string of standard output text for the "OUTPUT: <JSON>"
line and return the parsed JSON object.
"""
m = re.search(r'^###OUTPUT: (.*)', s, re.MULTILINE)
if m is None:
return None
return json.loads(m.group(1)) | 2c59a214bca9884b940ea66eb19b372fc2850430 | 666,575 |
def _recurse_subprocesses(run, index):
"""Recursively get actual steps (not ``WorkflowRun``) for execution."""
if not run.subprocesses:
return [(index, run)], index + 1
processes = []
for s in sorted(run.subprocesses, key=lambda x: x.index):
result, index = _recurse_subprocesses(s.proce... | 2aec4674314f86457699e736f9b709ac7027fd4b | 666,576 |
def get_last_conv_layer(keras_model):
"""
Get last convolution layer name of keras model
input: Keras model
output: string of the name of the last convolution layer
Make sure last convolution layer has "conv" in the name!
"""
layer_names=[layer.name for layer in keras_model.layers]
layer_names.revers... | b53eb42b9b9f83f790b3b194026ae3f8571db070 | 666,577 |
def build_completed_questions_feedback(actor_name, quiz_name, course_name, score, feedback):
"""
Build the feedback when an user has completed the quiz and has failed the quiz.
:param actor_name: Name of the user that has completed the quiz.
:type actor_name: str
:param quiz_name: Name of the quiz.... | b447fb45c742e9f13b0b67b149cd65f5ccb354c2 | 666,578 |
def parse_fastq_description(description):
"""
Parse the description found in a fastq reads header
Parameters
----------
description: str
A string of the fastq reads description header
Returns
-------
description_dict: dict
A dictionary containing the keys and values fou... | d7d224e587f8053960d7cc235b78317309009ca2 | 666,579 |
def convert_alpha_exponent(alpha):
"""Convert a DFA alpha value to the expected powerlaw exponent.
Parameters
----------
alpha : float
Alpha value from a detrended fluctuation analysis.
Returns
-------
exponent : float
Predicted aperiodic exponent value, representing a 1/f ... | 940ed732f033d1d97d1e7ebfbe8e66df3899963b | 666,580 |
from numpy import cumsum,sqrt,zeros,uint16,absolute,median
def integrate(Zmask_flat,I_flat,V_flat,q_dict,sigma=5):
"""Returns the weighted mean (S) and standard deviation of the mean (sigS)
for each bin defined by q, qbin1, and qbin2. Requires as input Zmask_flat
(boolean), I_flat (counts), V_flat (varian... | 47ac559ae05680024e88ac745260f4c524528a97 | 666,581 |
def has_bad_first_or_last_char(val: str) -> bool:
"""Returns true if a string starts with any of: {," ; or ends with any of: },".
Args:
val: The string to be tested.
Returns:
Whether or not the string starts or ends with bad characters.
"""
return val is not None and (val.startswit... | 78cb04442cac2779049ad4e1b4a86969c7b57b43 | 666,582 |
def longest_increasing_array(arr):
"""
longest sub array in increasing order
:param arr:
:return: maximum length of sub array
"""
if not arr:
return 0
if len(arr) == 1:
return 1
end =1
start = 0
max_len = 1
while end < len(arr):
if arr[end] > arr[end -... | 48fde98e7ea031bc29b5b440f08cd92ad786893d | 666,583 |
def is_own_piece(v, h, turn, grid):
"""Check if the player is using the correct piece
:param v: Vertical position of man
:param h: Horizontal position of man
:param turn: "X" or "O"
:param grid: A 2-dimensional 7x7 list
:return: True, if the player is using their own piece, False if otherwise.
... | d3685e226554c9a67f4bef9a388ebbf968c9e5a6 | 666,584 |
def der_numerical(f, h=1e-5):
"""Provides numerical integrals for argument functions."""
return lambda x: ((f(x + h) - f(x - h)) / (2 * h)) | 4ae76dec336c752ffec0ae0fa61c4cc211621a15 | 666,585 |
def linear_interpolation(tbounds, fbounds):
"""Linear interpolation between the specified bounds"""
interp = []
for t in range(tbounds[0], tbounds[1]):
interp.append(fbounds[0] + (t - tbounds[0]) * ((fbounds[1] - fbounds[0]) /
(tbounds[1] - tbou... | be6bafbefde612859883abd93b562333435f0229 | 666,586 |
def is_valid_glob_path(glob_and_path):
"""Check config file is valid format."""
if 'path' not in glob_and_path:
return False
if 'glob' not in glob_and_path:
return False
return True | 5c189803fa2354ecae8b21ac4cb5f9df68b90996 | 666,587 |
import datetime
def getdate():
"""Functions to get the present date & time """
return datetime.datetime.now() | 8a26598c92bf835abf6c1672b59709672bfcd4a5 | 666,588 |
def load_txt(file):
"""读取文本文件。
Args:
file: 文件路径。
Returns:
返回list。
"""
with open(file, 'r', encoding='utf-8') as txt_file:
return list(txt_file.read()) | 430c37f4fe81febbe6a72ae103c79df79df356d0 | 666,589 |
def round_robin(teams, rounds=None):
"""
Based on recipe found at http://code.activestate.com/recipes/65200/
"""
# ensure we have a list so we can perform appends and inserts
if not isinstance(teams, list):
teams = [t for t in teams]
# ensure we have an even number of teams
if len(t... | d24261a54d753e6ae0ac31b5d6068f2c1e477b27 | 666,590 |
import time
def make_expr_sig(args = None):
"""create experiment signature string from args and timestamp"""
# print ("make_expr_sig", args)
# infile = args.infile.replace("/", "_").replace(".wav", "")
# expr_sig = "MN%s_MS%d_IF%s_IS%d_NE%d_EL%d_TS%s" % (args.mode, args.modelsize, infile, args.sample... | 2da20398ac7fc0e15b713ecabda46e7273958bec | 666,591 |
import os
import fnmatch
def _list_conda_packages(local_dir):
"""List the conda packages (*.tar.bz2 files) in `local_dir`
Parameters
----------
local_dir : str
Some local directory with (hopefully) some conda packages in it
Returns
-------
list
List of conda packages in `... | ded121eac41740598dae586a4fca489b3a319402 | 666,592 |
def title_score(title):
"""
check if python is in the title
"""
score = 0
if 'python' in title:
score += 2
if title in {'Senior', 'Sr.', 'senior', 'sr.'}:
score -= 2
return score | 6959ce81182defc4ab77073810eedd5b35023ce4 | 666,593 |
def add_pseudocounts_to_frequencies(df, pseudocount, timepoint_column="timepoint"):
"""Add pseudocounts to the frequencies in the given data frame.
Parameters
----------
df : pandas.DataFrame
table of samples including annotations for `timepoint`,
`clade_membership`, and `frequency` unl... | a2aa08a102860a2fe891535501cf2c478ae63fda | 666,594 |
def filter_nc_files(path_list):
"""Given a list of paths, return only those that end in '.nc'"""
return [p for p in path_list if p.suffix == '.nc'] | ed4c3e3eb2f8bb323aaf7ce24b331ec4c9f7bfe9 | 666,595 |
def _indent_for_list(text, prefix=' '):
"""Indent some text to make it work as a list entry.
Indent all lines except the first with the prefix.
"""
lines = text.splitlines()
return '\n'.join([lines[0]] + [
prefix + l
for l in lines[1:]
]) + '\n' | 98da37331f46f50e775bf4676d9d45c8274ffa03 | 666,596 |
def add_args(parser):
"""
parser : argparse.ArgumentParser
return a parser added with args required by fit
"""
# Training settings
parser.add_argument('--case_name', type=str, default='knn',
help='connective functions ("distance","knn","pcc","plv")')
parser.add_argu... | b6781446c48dd37b694dc5ae0afb294d1931e44a | 666,597 |
def transform_results(results, keys_of_interest):
"""
Take a list of results and convert them to a multi valued dictionary. The
real world use case is to take values from a list of collections and pass
them to a granule search.
[{key1:value1},{key1:value2},...] -> {"key1": [value1,value2]} ->
... | 3158ee9f64110f6d2db052419c22c6ac71f51d10 | 666,598 |
def calc_iou(bbox_a, bbox_b):
"""
Calculate intersection over union (IoU) between two bounding boxes with a (x, y, w, h) format.
:param bbox_a: Bounding box A. 4-tuple/list.
:param bbox_b: Bounding box B. 4-tuple/list.
:return: Intersection over union (IoU) between bbox_a and bbox_b, between 0 and 1... | 36bc304ffe72a3f4a9d575cdd081e11b6425aa14 | 666,600 |
def make_target(objtype, targetid):
"""Create a target to an object of type objtype and id targetid"""
return "coq:{}.{}".format(objtype, targetid) | 37a5af1b49ac507127289728d0d386d1f376e8b7 | 666,601 |
def is_valid_string(string):
""" Method returns true if contains valid parentheses
:param string: string
:return: False if open bracket otherwise 0 when valid parentheses
"""
cnt = 0
for i in range(len(string)):
if string[i] == '(':
cnt += ... | 48e9640b1ecab60f54400dad54d2ae14499a6d15 | 666,602 |
def get_search_params(url_path):
"""
From the full url path, this prunes it to just the query section,
that starts with 'q=' and ends either at the end of the line of the
next found '&'.
Parameters
----------
url_path : str
The full url of the request to chop up
Returns
-... | fccc2ecc6606e9d46246b1080bd3a7da6a441906 | 666,603 |
def _first_multiple_of(num: int, above: int) -> int:
"""
Returns first multiple of num >= above
"""
return above + ((num-(above%num)) % num) | 937cfcea1d663998afc730db844ad1c2e9c26ecd | 666,604 |
def from_num_to_id(df, row_num, column = 'track_id'):
""" df must have a 'track_id' column """
return df.iloc[row_num][column] | e36551fbaf3875620ffdb56b5e5aab78cea21ccc | 666,606 |
def linear_cb(valve):
"""
Linear opening valve function callback.
"""
@valve.Expression(valve.flowsheet().time)
def valve_function(b, t):
return b.valve_opening[t] | 79693d42fc2a56ea710eee7dba9dddd294f049a8 | 666,608 |
def _publications_urls(request, analyses):
"""Return set of publication URLS for given analyses.
Parameters
----------
request
HTTPRequest
analyses
seq of Analysis instances
Returns
-------
Set of absolute URLs (strings)
"""
# Collect publication links, if any
... | f60efb37c9603d614f8cf0fa9c53657235d0a156 | 666,609 |
import typing
def preservation_copy(row: typing.Mapping[str, str]) -> typing.Optional[str]:
"""A path to the original digital asset in the 'Masters/' netapp mount.
If the File Name starts with "Masters/", it will be used as is. Otherwise,
it will be prepended with "Masters/dlmasters/", in order to match ... | 79a2ee85e695d737c1e4042cf8000887ffe5c5df | 666,610 |
def _test_int_pickling_compare(int_1, int_2):
"""Add the two given ints."""
return int_1 + int_2 | db0c37f6c4a764fc3c46221fca8877e747417af1 | 666,611 |
def _GetComponentNumber(component):
"""Gets component number from component CloudUrl.
Used during parallel composite upload.
Args:
component: CloudUrl representing component.
Returns:
component number
"""
return int(component.object_name[component.object_name.rfind('_') + 1:]) | d9884b68e069798f2ace8a1cbcfdcffb336d9d0e | 666,612 |
def execute_rpc(rpc):
"""Execute a Google RPC request with retries."""
return rpc.execute() | 8d05cb202b7d46a7b58259800579c74230362d94 | 666,613 |
def _append_results(group, step_results, results, step=None):
"""
Adds results from each simulation steps to temporary results dictionary
"""
results_keys = results.keys()
for key in results_keys:
var = key.split('_',1)[-1]
if var in step_results and key.split('_',1)[0] == group:
... | 88cdaac52a6901c697eb540dd53fd523b00be635 | 666,614 |
from typing import Optional
import argparse
import pathlib
def parse_args(args: Optional[list[str]] = None) -> argparse.Namespace:
"""
:param args: command line arguments
:type args: `list[str]`
:return: parsed arguments
:rtype: `argparse.Namespace`
"""
parser = argparse.ArgumentParser()
... | 887352f53328f15c4cc95e1fb634b785e383d749 | 666,616 |
from networkx import get_edge_attributes
def uninformative_prediction(G, required_links):
"""
Function to predict links in an uninformative manner, i.e., the majority
parity. So, if there are more positive links that negative links, then a
positive link is predicted and vice-versa
Args:
G... | 6f89b6703f8df7c42c3b03c85efea6b2d4318d81 | 666,617 |
import os
import fnmatch
def find_directories(root, pattern):
"""Find all directories matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of dir paths relative to root
"""
results = []
for base, dirs, files in os.walk(root):
matched = fnm... | 0c21e062c0a9ccf4f60276f13e90f97f08bf6d60 | 666,618 |
import sys
def load_module(self, fullname):
"""
Iterate over the search path to locate and load fullname.
"""
root, base, target = fullname.partition(self.root_name + '.')
for prefix in self.search_path:
try:
extant = prefix + target
__import__(extant)
m... | 2ed3346192c0a17d33083ffaf1f007092fde651e | 666,619 |
def flatten(lst, out=None):
"""
@return: a flat list containing the leaves of the given nested
list.
@param lst: The nested list that should be flattened.
"""
if out is None: out = []
for elt in lst:
if isinstance(elt, (list, tuple)):
flatten(elt, out)
else:
... | 272f2b51f9f394fcccac3f94ed89c4e8ed6f1dcd | 666,620 |
import random
def get_permutation_traffic_dict(hosts):
"""
Returns a dictionary that specifies what host
should send traffic to what host:
hx --> hy
"""
hosts_ = hosts[:]
send_dict = {}
for h in hosts:
send_idx = random.choice(range(len(hosts_)))
# We should not ... | e56977b1b5d80e2b65a9eca03822924791bab2eb | 666,621 |
def get_configurations_by_qscheme(fq_to_hw_confs, qscheme):
""" Choose fake quantize configuration by qscheme
:param fq_to_hw_confs: dictionary with fake quantize names as keys and
list of its configurations as values (read_all_fake_quantize_configurations(..) return value)
:param qscheme: The quantiza... | 372133c2371af2b8fea578579c909d7fb87b442a | 666,622 |
def update_transaction_values(merged_data, consumer_transactions, transactions, consumer_id, offers):
"""
For all transactions with monetary value, determine whether
or not it falls within the offer window (between when the offer
was received and when it was either completed or expired). An... | b858276496b25e7ecc8b7c12029f9faca6cad1a8 | 666,623 |
import re
def int_pair(s, default=(0, None)):
"""Return the digits to either side of a single non-digit character as a 2-tuple of integers
>>> int_pair('90210-007')
(90210, 7)
>>> int_pair('04321.0123')
(4321, 123)
"""
s = re.split(r'[^0-9]+', str(s).strip())
if len(s) and len(s[0]):
... | 8238633843e7e3d2dfa2a23b8a3b7e7744b5c70f | 666,624 |
def find_match_brackets(search, opening='<', closing='>'):
"""Returns the index of the closing bracket that matches the first opening bracket.
Returns -1 if no last matching bracket is found, i.e. not a template.
Example:
'Foo<T>::iterator<U>''
returns 5
"""
index = search.f... | e044cdf5e6c760b995d0e4d26d35e5beebb5cb77 | 666,625 |
import math
def estimate_pi():
"""Computes pi using Ramananujan's infinite series"""
epsilon = 1e-15
sum = 0
k = 0
factor = 2 * math.sqrt(2) / 9801
while True:
term = factor * (math.factorial(4 * k) * (1103 + 26390 * k)) / ((math.pow(math.factorial(k), 4)) * math.pow(396... | 83fae4f84be22a62fbc51e1bec76e0edf08c06e8 | 666,626 |
def __path_exists__(source, target, predicates, arg_predicates, max_path_length):
"""
predicates : pred_id -> predicate map
arg_predicates : argument -> list of predicate where this arg appears
"""
visited = set()
source_arg = source.args[1] if (source.pos == "nn" or source.pos == "n") else... | 8d7b1540e84524baee917a3b4c161bb72d5f9197 | 666,627 |
def get_synapse_from_layer(cur,layer):
"""
Returns synapses in given layer list of tuples:
(mid_object,x-pos,y-pos)
Parameters
----------
cur : MySQLdb cursor
layer : str
Name of layer
"""
sql = ("select synapsecombined.mid,"
"object.OBJ_X,"
"ob... | 5daf84eeea34cf059409033d36759c55c041bb74 | 666,628 |
def rus_fold_json(rus_player_json):
"""Expected JSON for rus_fold model-fixture"""
return {"type": "fold", "player": rus_player_json} | afe181e863235d2f2d805c450aa314a8830ea8d4 | 666,629 |
def obfuscate_vars(inventory):
"""
Remove sensitive variables when dumping inventory out to stdout or file
"""
stars = "*"*14
splunkVars = inventory.get("all", {}).get("vars", {}).get("splunk", {})
if splunkVars.get("password"):
splunkVars["password"] = stars
if splunkVars.get("pass4... | c6cfca1f35c76cfaf878e8446ec56749338452c2 | 666,630 |
def flatten(seqs):
"""flatten(seqs)
Flattens objects in
"""
return sum(seqs, []) | 3b142a636df255bd1478c0002c4e79c1b950cadb | 666,631 |
import base64
def ecr_docker_login(client, docker_client):
"""
Logs logs into Docker using the ECR client registry
:param client: boto3.client the ECR client
:param docker_client: docker.APIClient the docker client to log into
"""
token = client.get_authorization_token()
username, password... | 74bf63bec9b1c170351c148fb24c4eeab05f62d1 | 666,632 |
def get_fieldnames(records):
"""
Extract fieldnames for CSV headers from list of results
:param records: list
:return: list
"""
fieldnames = []
ordered_fieldname = (
"time_last",
"time_first",
"source",
"count",
"bailiwick",
"rrname",
... | f8258e03397ee04da91e42cb4d54ba346ad7352d | 666,633 |
import base64
def get_stage1_command(stage1_file):
"""
The format of a PowerShell encoded command is a base64 encoded UTF-16LE string.
This function reads the stage 1 file (UTF-8) into a string, converts it into UTF-16LE encoding, and then base64 encodes that.
In Python, Base64 conversion requires Bytes objects, ... | 479c4c3f032ff476754982e45a5f99339f5aff92 | 666,635 |
def is_int(object):
"""Check if the given object is an integer"""
return isinstance(object, int) | 99aeb97e23db5ac6d83776b9e9c1172d7215972c | 666,636 |
def isCardinallyEnvyFree(prefProfile, allocation):
"""
INPUT:
prefProfile: a PrefProfile with cardinal utilities.
allocation: a dictionary that maps agents to their bundles.
OUTPUT:
True iff the given allocation is envy-free according to the agents' cardinal value function
>>> prefProfile ... | 5d19d2fd4be6f34d84ddfa209d248fed5e6b0260 | 666,637 |
def parse_ports(ports_text):
"""Parse ports text
e.g. ports_text = "12345,13000-15000,20000-30000"
"""
ports_set = set()
for bit in ports_text.split(','):
if '-' in bit:
low, high = bit.split('-', 1)
ports_set = ports_set.union(range(int(low), int(high) + 1))
... | 3e1017754773810fdf67ac61197dffa0373db255 | 666,639 |
import html
def _xml_to_kwargs(xml):
"""
This is to save time.
Args:
xml: BeautifulSoap Object
Returns: dict of kwargs that was after covert xml to dict
"""
data = {}
for x in xml: # it will run each tag and pass down those tag as key then pass value.
if x.name == "synop... | d35d25ddd98da087fbfded090c2a365510e161de | 666,640 |
import tarfile
def _create_pax_generic_header(cls, pax_headers, type=tarfile.XHDTYPE):
"""Return a POSIX.1-2001 extended or global header sequence
that contains a list of keyword, value pairs. The values
must be unicode objects.
"""
records = []
for keyword, value in pax_headers.iteritem... | b25b42a5632c454fbde43479fd7f3aaad5358a2c | 666,641 |
def get_bam2zmws(movie2zmws, movie2bams):
"""
movie2zmws --> {movie: zmws}
movie2bams --> {movie: bam_files} # allow *.1.subreads.bam, *.2.subreads.bam
return bam2zmws{bam: zmws}
e.g.,
movie2zmws {'movie': [20,21,31]},
movie2bams {'movie': ['movie.1.subreads.bam', 'movie.2.subreads.bam']}
... | 1cda817b2c70389c1d306f8985abd7504cad6624 | 666,642 |
import re
def normalize_middle_high_german(text, to_lower_all = True, to_lower_beginning = False, alpha_conv = True, punct = True):
"""
to_lower_all: convert whole text to lowercase
alpha_conv: convert alphabet to canonical form
punct: remove punctuation
"""
if to_lower_all:
... | 707a95097a7176a8b63cc8661c1ffb642106ce23 | 666,643 |
from datetime import datetime
def utcnow():
"""Returns datetime.utcnow(), used for testing.
Use this function so it can be mocked everywhere.
"""
return datetime.utcnow() | 46143dfe535c4fb46dc69a6ddd99ac9152e922a2 | 666,644 |
import math
def area(flow, c_thr, theta=2*math.pi):
"""Calculate area at i-section.
area(flow, c_thr):
area at throat section
area(flow, c_thr, theta):
area at any section located by the angle theta
:param flow (float): flow rate [m^3/s]
:param c_thr (float): absolute velocity [m... | 688ed7af2e4f52832f3591d3fc5b672d13c4426a | 666,645 |
import itertools
def tiles_info(panoid, zoom=5):
"""
Generate a list of a panorama's tiles and their position.
The format is (x, y, filename, fileurl)
"""
# image_url = 'http://maps.google.com/cbk?output=tile&panoid={}&zoom={}&x={}&y={}'
image_url = "http://cbk0.google.com/cbk?output=tile&pan... | dc5d08deff7e6b6922efb6296b19a5ed23a022e9 | 666,646 |
import time
def timecode(time_now, interval):
""" make integer and divide by time interval of valid OTP """
i = time.mktime(time_now.timetuple())
return int(i / interval) | d2525745d761adbe7ec38cc534efafafb088ad2b | 666,647 |
def extend(s, var, val):
"""
Returns a new dict with var:val added.
"""
s2 = {a: s[a] for a in s}
s2[var] = val
return s2 | 5efbb43fbcc2c46a0479c3fd9323d25e3e04e4d0 | 666,648 |
def escape_str(*, string: str) -> str:
"""
Escape special characters (e.g. line breaks of `\n`).
Parameters
----------
string : str
String to escape.
Returns
-------
string : str
Escaped string.
"""
string = repr(string)[1:-1]
return string | a29cc3fb3118c03c4a5e088a8c6973d059910873 | 666,649 |
import re
def get_words(text):
"""
:param text: words without any special characters
:return: a list of words
"""
list_of_words = list()
words = re.split(r'\s+', text)
for word in words:
list_of_words.append(word.upper())
return list_of_words | 2f41f2f4acbc21dd4098215d63f42c8f03d7c258 | 666,650 |
import os
def resolve_mongo_conn_string() -> str:
"""
returns the mongo connection string for the currently deployed environment.
"""
return os.environ["MONGO_CONN_STRING"] | d1c80e06c93af765e416d2ff43e0d7c941a5ac93 | 666,652 |
import math
import numpy
def pxyz_to_equ(p_coord):
"""
This function translates 3D point p on sphere to Equirectangular projection 2d point.
Args:
p_coord: A 3d vector, that is on sphere.
Returns:
lon: longitude of the point p. Range from[-1,1]
lat: latitude of the point p. ... | 7d94f3be0b13ad59b484335afe14182e280e010a | 666,653 |
import requests
def get_page(url):
"""发起请求 获得源码"""
r = requests.get(url)
r.encoding = 'utf8'
html = r.text
return html | 584cfd29df7b71ca860b9e1a4ff730e4ecfe6355 | 666,654 |
def collect_vowels(s):
""" (str) -> str
Return the vowels (a, e, i, o, and u) from s.
>>> collect_vowels('Happy Anniversary!')
'aAiea'
>>> collect_vowels('xyz')
''
"""
vowels = ''
for char in s:
if char in 'aeiouAEIOU':
vowels = vowels + char
return vowel... | 0fef4866e7ba78a9dd8209c580330b7874cfe146 | 666,655 |
def DUMMYPROF_FUNC(func):
"""dummy profiling func. does nothing"""
return func | 3367352f8e4a53bb4e7d2574b9f4d7ae3bb60406 | 666,657 |
def reward_scaling(r, scale=1):
"""
Scale immediate rewards by a factor of ``scale``.
Can be used as a reward shaping function passed to an algorithm
(e.g. ``ActorCriticAlgorithm``).
"""
return r * scale | 3afbfd0114f5e1af7328f8cc1b5da5ed9990a005 | 666,658 |
def get_raw_url_bitbucket(url_data, name, subdirectory):
"""returns raw url from bitbucket url data"""
return ("%s%s/raw/master/%s%s" % (url_data.netloc, url_data.path.split('.')[0], subdirectory, name)) | f25c8de5974698c8274c0efd292ebc2410fb26bb | 666,659 |
def nguHanh(tenHanh):
"""
Args:
tenHanh (string): Tên Hành trong ngũ hành, Kim hoặc K, Moc hoặc M,
Thuy hoặc T, Hoa hoặc H, Tho hoặc O
Returns:
Dictionary: ID của Hành, tên đầy đủ của Hành, số Cục của Hành
Raises:
Exception: Description
"""
if tenHanh in ["Kim",... | 9d46def34bee39bb0593f2620baeeb36aec1b022 | 666,660 |
from typing import Dict
from typing import List
import math
def get_mean(data: Dict[int, List[float]]) -> Dict[int, float]:
"""
Turns a dictionary with float lists into a dict with mean values of all non-NaN list entries.
:param data: Input dictionary with float lists
:return: Output... | 4ebb1faf754f6ceab714aa045ac86bb719096a8b | 666,661 |
def clear_bgp_neighbor_soft(device, command='clear bgp neighbor soft all', alternative_command='clear bgp neighbor soft',
fail_regex=None):
""" Clear bgp neighbor soft using one of two commands
Args:
device ('obj'): Device object
command ('str'): Command with a... | c3b372bbb74bde33066cd46c722b6eca7847e307 | 666,662 |
def is_custom_session(session):
"""Return if a ClientSession was created by pyatv."""
return hasattr(session, '_pyatv') | 741057221f80f0285b8b744e635d419dd9a0a38b | 666,663 |
import argparse
def parse():
"""
Parse arguments
"""
parser = argparse.ArgumentParser(description=
"""
Training multiple models on the same dataset for error analysis.
Here we assume that t... | 0117303f52d170822b13181fe63cf845dbe0da81 | 666,664 |
from typing import List
def resize(seq: List, n: int, default=None) -> List:
""" resize seq to exactly have n members """
seq = seq[:n]
seq = seq + [default] * (n - len(seq))
return seq | 16d61664aba5f7ac1ab38e4ec36266b1f1964e1b | 666,665 |
from typing import OrderedDict
def getabbrevs(text):
"""Get book abbreviations from toc2 and toc3 usfm tags."""
abbrevs = OrderedDict()
abbrevs2 = OrderedDict()
book = ""
lines = text.split("\n")
num = 0
for i in [_ for _ in lines if 'type="book"' in _]:
num += 1
bkline = l... | be07a7f281587b18a2c4d39047d77414f00722f7 | 666,666 |
from typing import Iterable
from typing import Callable
from typing import List
def remove(items: Iterable, predicate: Callable) -> List:
"""Return a new list without the items that match the predicate."""
return [x for x in items if not predicate(x)] | 540a3b0334ff756bc6d81df302f3543997044238 | 666,667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.