content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _smallest(x, a, m):
"""
Gives the smallest integer >= x that equals a (mod m)
Assumes x >= 0, m >= 1, and 0 <= a < m.
"""
n = ceiling(x - a, m)
return a + n*m | 54,200 |
def max_pool_layer(layer_id, inputs, kernel_size, stride):
"""Build a max-pooling layer.
Args:
layer_id: int. Integer ID for this layer's variables.
inputs: Tensor of shape [num_examples, width, height, in_channels]. Each row
corresponds to a single example.
kernel_size: int. Width and height to ... | 54,201 |
def get_args():
"""Expose different behaviors of the server to the user.
Raises:
AssertionError: If the combination of arguments are unsupported
Returns:
parsed arguments for the server, cached
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsH... | 54,202 |
def pandas_read_xlsb_file(filepath):
"""
https://stackoverflow.com/questions/45019778/read-xlsb-file-in-pandas-python
Accepts a filepath - pathlib.Path object
Reads an xlsb file into a dataframe
Returns the dataframe
"""
dfs = []
with open_xlsb(filepath) as wb:
with wb.get_sheet(... | 54,203 |
def join_batch_meshes_as_scene(
meshes: List[ParametricMeshes],
include_textures: bool = True) -> ParametricMeshes:
"""Join `meshes` as a scene each batch. For ParametricMeshes. The Meshes
must share the same batch size, and topology could be different. They must
all be on the same device. I... | 54,204 |
def read_1D(file_path):
"""
Transform the .1D file to .mat file
TODO: to other file type
Args:
file_path: .1D file path
Return:
data: .mat file
""" | 54,205 |
def load_dxf(dxf_filepath: pathlib.Path):
"""
Import any-old-shape in dxf format for analysis.
Code by aegis1980 and connorferster
"""
if not dxf_filepath.exists():
raise ValueError(f"The filepath does not exist: {dxf_filepath}")
my_dxf = c2s.dxf.DxfImporter(dxf_file... | 54,206 |
def validate_cv_implementation(impl, bootstrap=False):
"""Validate a back end for computing variables, returning it.
Raise an exception if it is invalid.
The second argument is for internal use only.
"""
# Note that the very first call to this with a non-None argument,
# and with bootstrap giv... | 54,207 |
def create_qp_par():
"""
Creates a qp.par file with default parameters
"""
qp_par = open('qp.par','w')
text = """# Feel free to remove items to have a shorter file, but do NOT
# remove the section headers (with [])!
# Remember to rename file if edited!
[contours]
#Linear contours (FOU, DEF)
use_lin... | 54,208 |
def set_os_environ(variables_mapping):
""" set variables mapping to os.environ
"""
for variable in variables_mapping:
os.environ[variable] = variables_mapping[variable]
logger.debug(f"Set OS environment variable: {variable}") | 54,209 |
def accuracy_op(predictions, targets):
""" accuracy_op.
An op that calculates mean accuracy.
Examples:
```python
input_data = placeholder(shape=[None, 784])
y_pred = my_network(input_data) # Apply some ops
y_true = placeholder(shape=[None, 10]) # Labels
acc_op = acc... | 54,210 |
def detect_image(image, yolo, all_classes):
"""Use yolo v3 to detect images.
# Argument:
image: original image.
yolo: YOLO, yolo model.
all_classes: all classes name.
# Returns:
image: processed image.
"""
pimage = process_image(image)
start = time... | 54,211 |
def list_entry_factory(db):
"""
Fixture to get the factory used to create list entries.
"""
return factories.ListEntryFactory | 54,212 |
def fractals_tholins(wvln, rm, Df, N, db=Database(), **kwargs):
"""Fractals cross-sections and phase function for tholin aggregate.
Use default tholins indexes and Tomasko et al. 2008.
Parameters
----------
wvln: float
Wavelength (m).
rm: float
Monomer radius (m).
Df: float... | 54,213 |
def _apply_quat(quat, pts, move=True):
"""Apply MaxFilter-formatted head position parameters to points."""
trans = np.concatenate(
(quat_to_rot(quat[:3]),
quat[3:][:, np.newaxis]), axis=1)
return(apply_trans(trans, pts, move=move)) | 54,214 |
def render_url_list(app_name, urls):
""" Render sitemap to URL list for use in prerendering
Args:
app_name (:obj:`str`): application name (e.g., `simulators`
urls (:obj:`list` of obj:`Url`): list of URLs
"""
# render sitemap to text file
with open(os.path.join(os.path.dirname(__fi... | 54,215 |
def spherical_to_vector(spherical):
"""
Convert a set of (n, 2) spherical vectors to (n, 3) vectors
Parameters
------------
spherical : (n , 2) float
Angles, in radians
Returns
-----------
vectors : (n, 3) float
Unit vectors
"""
spherical = np.asanyarray(spherical,... | 54,216 |
def split_config(config: Mapping[str, Any]) -> Tuple[dict, InternalConfig]:
"""
Break config map object into 2 instances: first is a dict with user defined
configuration and second is internal config that contains private keys for
acceptance test configuration.
:param
config - Dict object that ... | 54,217 |
def klatt_bridge(f0, ff, bw, av, avs, ah, af, fs, dur, inv_samp=50):
"""
Processes/interpolates input parameters for Klatt synth, runs synth.
Arguments:
f0 (Track object) -- fundamental frequency contour
ff (list, len n_form, Track objects) -- formant frequency contours, one
... | 54,218 |
def create_dict(data: list):
"""
Cria um dicionário onde a chave é o tempo de duração da palestra
e o valor é uma lista que contém as palestras com essa duração.
"""
data = lectures_ordered_by_duration(data)
new_set = {}
for item in data:
if item[0] not in new_set:
... | 54,219 |
def create_args_parser():
"""
Create the program argument parser.
Returns:
An argparse parser object.
"""
prog_name = os.path.basename(os.path.dirname(sys.argv[0]))
mesg = """
This script will (re)generate tests for recipes.
It will OVERWRITE existing tests.
"""
mesg = m... | 54,220 |
def main(splunk_config: str, index: str, start_time: str, end_time: str, n: int, verbose: bool):
"""Estimate compression of Splunk records achieved by Bolt's <product_name>
\b
Examples:
splat --splunk-config splunk.json --index firewall -n 5000 -v
splat --splunk-config splunk.json --index f... | 54,221 |
def adapt_environment() -> set[str]:
"""Update env vars and return CLI flags for compatibility with latest Semgrep."""
for old_var, new_var in ENV_TO_ENV.items():
if os.getenv(old_var):
os.environ[new_var] = os.environ.pop(old_var)
parser = argparse.ArgumentParser()
for flag in FLA... | 54,222 |
def _kernel_cdf_gamma(x, sample, bw):
"""Gamma kernel for cdf, without boundary corrected part.
drops `+ 1` in shape parameter
It should be possible to use this if probability in
neighborhood of zero boundary is small.
"""
return stats.gamma.sf(sample, x / bw, scale=bw) | 54,223 |
def infer_type(node):
"""A method to infer the type of an intermediate node in the relay graph."""
mod = node if isinstance(node, _module.Module) else _module.Module.from_expr(node)
mod = _transform.InferType()(mod)
entry = mod["main"]
return entry if isinstance(node, _expr.Function) else entry.body | 54,224 |
def palindrome_from(letters):
"""
Forms a palindrome by rearranging :letters: if possible,
throwing a :ValueError: otherwise.
:param letters: a suitable iterable, usually a string
:return: a string containing a palindrome
"""
counter = Counter(letters)
sides = []
center = deque()
... | 54,225 |
def plot_scores_by_year(author_pub, name, weighted=True):
"""
:param author_pub: the output of the publications_per_author()
:param name: the full name of the author (e.g., Jinho D. Choi)
:param weighted: if True, use weighted publication scores; otherwise,
:return:
"""
d = {}
for pub in... | 54,226 |
def get_cloud(session, cloud_name, return_type=None, **kwargs):
"""
Retrieves details for a given cloud name
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type cloud_name: str
:param cloud_name: Cloud Name: i.e: zadaraqa9
:typ... | 54,227 |
def insertOrUpdate(db: str, tableName: str, dataFile: str,
conReplaceRules=None, writeToNewFormat: bool = True):
"""
inserta o actualiza en contenido del fichero json dataFile en tableName de
la base de datos db
args:
...
conReplaceRules: connexión a una bas... | 54,228 |
def check_scopes(required_scopes, scopes):
"""Check that required_scope(s) are in scopes
Returns the subset of scopes matching required_scopes,
which is truthy if any scopes match any required scopes.
Correctly resolves scope filters *except* for groups -> user,
e.g. require: access:server!user=x,... | 54,229 |
def new_filter(filters=None):
"""
Returns the default lookup filters.
:param filters: dict - The defaults are updated with this dict before being returned.
:returns: dict
"""
out = dict(const.DEFAULT_FILTERS)
if filters is not None:
if not isinstance(filters, dict):
... | 54,230 |
def addAssignment2D(initAssignments=None, odID=1, objectID=None, modelFile=None, startLoc=None, endLoc=None, startTimeSec=0.0, expDurationSec=None, routeType='euclidean2D', speedMPS=None, leafletColor=config['VRV_DEFAULT_LEAFLETARCCOLOR'], leafletWeight=config['VRV_DEFAULT_LEAFLETARCWEIGHT'], leafletStyle=config['VRV_D... | 54,231 |
def load(filename):
"""load a 'TAMO'-formatted motif file"""
FID = open(filename,'r')
lines = FID.readlines()
FID.close()
motifs = []
seedD = {}
seedfile = ''
for i in range(len(lines)):
if lines[i][0:10] == 'Log-odds matrix'[0:10]:
w = len(lines[i+1].split())-1
... | 54,232 |
def test_archived_date_set_save_strategic_action():
"""Test archived_date is set when archived strategic action saved."""
sa = StrategicActionFactory(is_archived=True, archived_reason="A reason")
assert sa.archived_date == date.today() | 54,233 |
def _homogenize_linesep(line):
"""Enforce line separators to be the right one depending on platform."""
token = str(uuid.uuid4())
line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "")
return line.replace(token, os.linesep) | 54,234 |
def create_div_stats(Pi, a, b):
"""Return div element with text of distribution statistics."""
# Calculate mode and variance probability based on prior.
if a == 1 and b == 1:
mode_str = "any value"
else:
# str(round((a - 1.0) / (a + b - 2.0), 7))
mode_str = f"{(a - 1.0) / (a + b... | 54,235 |
def check_credentials(account):
"""
Function that check if a Credentials exists with that account name and return true or false
"""
return Credentials.if_credential_exist(account) | 54,236 |
def quicksort(args: List[T]) -> List[T]:
"""
>>> quicksort([4, 3, 2, 1])
[1, 2, 3, 4]
>>> quicksort([4, 2, 3, 1])
[1, 2, 3, 4]
>>> quicksort([1, 2, 4, 3])
[1, 2, 3, 4]
>>> data = list(range(100))
>>> random.shuffle(data)
>>> quicksort(data) == list(range(100))
True
"""
... | 54,237 |
def remove_attributes_with_empty_value(element):
"""
Removes all attributes with an empty value from all elements.
:param element: an XML element object.
"""
remove_attributes_with_value(element, '') | 54,238 |
def vect3_bisector(v1, v2):
"""
Gives the bisector vector of v1, v2
v1, v2 (3-tuple): 3d vectors
return (3-tuple): 3d vector
"""
return vect3_add(vect3_normalized(v1), vect3_normalized(v2)) | 54,239 |
def check_intra_node_overlap(node_a, node_b):
"""
check if alignments of the same read hit overlapping
parts of the same node (or node_a and _b are different)
"""
same_node = True
if node_a.name != node_b.name:
same_node = False
same_orientation = False
overlap_bp = 0
... | 54,240 |
def load_model(filepath, custom_objects=None, compile=True):
"""
Loads a model saved via `save_model`.
Arguments:
filepath: One of the following:
- String, path to the saved model
- `h5py.File` object from which to load the model
custom_objects: Optional dictionary m... | 54,241 |
def read_guess_word(row):
"""
Read the specified row's results.
"""
guess_result = [read_guess_letter(row, ordinal) for ordinal in range(word_len)]
return guess_result | 54,242 |
def teacher_data(num_train=100, num_test=300, num_feat=5, num_feat_teach=10,
width=1.0):
"""Generate two Gaussians and then split features
into normal features and teacher features
"""
(metadata, examples, labels) = cloudgen(num_train+num_test, num_feat+num_feat_teach,
... | 54,243 |
def _transformer_mask(x, triu, mask, lengths, left_aligned):
"""Helper function to determine attention masks for the transformer
Args:
x (:py:class:`dynet.Expression`): Input (dimensions
``input_dim x L``)
triu (bool): Upper triangular masking
mask (:py:class:`dynet.Expressi... | 54,244 |
def inverse_alr(Y: np.ndarray, ind=-1, null_col=False):
"""
Inverse Centred Log Ratio transformation.
Parameters
---------------
Y : :class:`numpy.ndarray`
Array on which to perform the inverse transformation, of shape :code:`(N, D-1)`.
ind : :class:`int`
Index of column used as... | 54,245 |
def save(
filename: str,
simulator: Simulator,
signal_processors: list = None,
params: Parameters = None,
with_units: bool = True,
):
"""Serialize the Simulator, list of SignalProcessor, and lmfit Parameters objects
to a .mrsim file.
Args:
str filename: The data is serialized to... | 54,246 |
def exec_potrace(filepath, line='', filename=None):
""" Executes a subprocess call that executes imagemagick's convert
:returns True if passed, False if failed
"""
if filename is None:
return '', False
line = line if line is True else ''
name = filename.split('\\')
name = name[len(... | 54,247 |
def content_insert_emotes(bot: Bot, string: str):
"""
Method that will attempt to turn the passed in string and replace emoji sequences with the appropriate emote
Parameters
----------
bot: Bot
pass in bot reference to find emotes
string: str
the string that may or may not conta... | 54,248 |
def square(root):
"""This function calculates the square of the argument value"""
# result = num * num
return root * root | 54,249 |
def quick_sort(seq: MutableSequence[Any]) -> MutableSequence[Any]:
"""Quicksort or Hoare's sort.
Algorithm in-place, complexity: O(n*log(n)) for a totally unsorted seq.
"""
def _quick_sort(
_seq: MutableSequence[Any],
_begin: int,
_end: int) -> MutableSequence[Any]:
... | 54,250 |
def letter_frequency(seq):
"""Returns a dictionary with the frequencies of letters in the sequence"""
freq = filter(lambda x: x in string.ascii_letters, seq.lower())
freq = dict(Counter(freq).most_common())
freq.update(dict((x, 0) for x in filter(lambda x: x not in freq, string.ascii_lowercase)))
r... | 54,251 |
def ns_template():
"""api.query.ns_template
获取[模板]命名空间中所有页面
Returns:
List Of Response(py.Dict)
Response:
{
'pageid': 页面id,
'ns': 10,
'title': 标题,
}
"""
return _abstract_ns_allpages(10) | 54,252 |
def custom_openMM_force_object(system, bond_list, bond_type_index_dict, bond_param_dict, angle_list=None,
angle_type_index_dict=None, angle_param_dict=None):
""" #todo: add argument allowing this custom function to be fed in as an input (more flexible used-designed ff)
:param bond... | 54,253 |
def test_collect_account_basic_account_metrics(target_datetime: Optional[datetime.datetime] = None) -> dict:
"""
Run the CostManager.collect_account_basic_account_metrics() function and retrieve the results.
"""
end, _, previous_month_start = _get_month_starts(target_datetime)
manager = CostManager... | 54,254 |
def shadow_model():
"""The architecture of the shadow model is same as target model, because the attack is white-box,
hence the attacker is assumed to know this architecture too.
:return: shadow model
"""
classifier = Sequential()
classifier.add(
Dense(1,
input_dim=featur... | 54,255 |
def get_codes(dikt, text):
"""
returns those elements in a dict where value contains the expressions listed in codes
todo: more complicated star notations: starts with, contains, endswith
alterative name: find_codes? get_codes?
example
get all codes that have "steroid" in the explanatory text
... | 54,256 |
def split_first_col (READ_PATH, header, preproc = lambda x: x):
"""
Ugly horrible hacky code to read in the .csv at READ_PATH, and, assuming the first column is of the format
"ID_episodeEPISODE_timeseries.csv", then splits ID and episode into 2 columns
:p
:param READ_PATH:
:param preproc:
:r... | 54,257 |
def is_kind_of_class(obj, a_class):
"""
Function that determine if a class is a specific class or an inherited
class.
Args:
obj (object any type): The object to analyze.
a_class (object any type): The reference object.
Returns:
Returns True if the obj is exactly an instanc... | 54,258 |
def get_candidate_type(candidate_tokens):
"""Returns the candidate's type: Table, Paragraph, List or Other."""
first_token = candidate_tokens[0]
if first_token == "<Table>":
return "Table"
elif first_token == "<P>":
return "Paragraph"
elif first_token in ("<Ul>", "<Dl>", "<Ol>"):
... | 54,259 |
def parse_file(input_file):
"""
Input: A file containing one binary-number string per line
Output: A list of binary number strings
Blank lines and lines starting with '#' are ignored
"""
strings = []
with open(input_file) as f:
for line in f.readlines():
line = line.strip... | 54,260 |
def reset_override_colors():
""" Reset override colors scss file if attack brand flag is enabled """
if site_config.args.attack_brand:
colors_scss_f = os.path.join(site_config.static_style_dir, "_colors.scss")
temp_file = ""
with open(colors_scss_f, "r", encoding='utf8') as colors_f:
... | 54,261 |
def from_numpy(x):
"""Creates a ComplexTensor from a numpy.ndarray.
"""
a = x.real.copy()
b = x.imag.copy()
return ComplexTensor(torch.from_numpy(a), torch.from_numpy(b)) | 54,262 |
def load_config_paths(*resource):
"""Iterator of configuration paths.
Return an iterator which gives each directory named 'resource' in
the configuration search path. Information provided by earlier
directories should take precedence over later ones (ie, the user's
config dir comes first).
"""
... | 54,263 |
def experimental_options(options):
"""Run inside contextmanager with special options."""
old_opts = tf.config.optimizer.get_experimental_options()
tf.config.optimizer.set_experimental_options(options)
try:
yield
finally:
tf.config.optimizer.set_experimental_options(old_opts) | 54,264 |
def classification_stats(ytrue, ypred, num_samples=1000):
""" construct a dataframe that summarizes classification """
# compute aucs, prec, rec, f1
auc = roc_auc_score(ytrue, ypred)
yp = ypred > .5
prec = precision_score(ytrue, yp)
rec = recall_score(ytrue, yp)
f1 = f1_score(ytrue, y... | 54,265 |
def process_map_input(input_lines):
"""
Find the dimensions of a map using the lines of input
:param input_lines: List of string representing the map
:return: (x: width, y: height) Tuple
"""
height = len(input_lines) - 1
width = len(input_lines[0])
return width, height | 54,266 |
def total_loss(c_layer, s_layers, generated):
"""
Computes the total loss of a given iteration
:param c_layer: The layer used to compute the content loss
:param s_layers: The layer(s) used to compute the style loss
:param generated: The generated image
:return: The total loss
"""
conten... | 54,267 |
def weighted_choice(lst):
"""Choose element in integer list according to its value.
E.g., in [1,10], the second element will be chosen 10 times as
often as the first one. Returns the index of the chosen element.
:ivar [int] lst: List of integers.
:rtype: int
"""
total = sum(c for c in l... | 54,268 |
def my_plot(losses=None, pearson_corr=None, spearman_corr=None):
"""
a plot with three sub plot, which is loss, pearsonr, spearmanr, respectively
"""
subplotcnt = 0
plt.figure(figsize=(21.3, 4))
if losses is not None:
subplotcnt += 1
plt.subplot(1,3,subplotcnt)
for loss i... | 54,269 |
def git_connect(github_username, github_password, github_repo):
"""
Logs in to github with our creds, returns gh,repo,branch objects.
"""
gh = github3.login(username=github_username, password=github_password) # we login and get a session.
repo = gh.repository(github_username,github_repo) # we create our... | 54,270 |
def get_course(doc):
"""Returns the course name for given document of type Course, Chapter, Lesson or Exercise.
"""
if doc.doctype == "LMS Course":
return doc.name
elif doc.doctype == "Course Chapter":
return doc.course
elif doc.doctype == "Exercise":
return doc.course
el... | 54,271 |
def _read_configuration():
"""Get and return application settings.
:return:
"""
parser = argparse.ArgumentParser(
description='Compute PaDEL descriptors for given'
'molecules/fragments.')
parser.add_argument('-i', type=str, dest='input',
help='inp... | 54,272 |
def hhblits(
project: str,
region: str,
msa_dbs: list,
reference_databases: Input[Dataset],
sequence: Input[Dataset],
msa: Output[Dataset],
cls_logging: Output[Artifact],
maxseq:int=1_000_000,
machine_type:str='c2-standard-16',
boot_disk_size:int=200,
n_cpu:int=12,
):
... | 54,273 |
def _run_server(
file_store_path,
default_artifact_root,
host,
port,
static_prefix=None,
workers=None,
gunicorn_opts=None,
waitress_opts=None,
expose_prometheus=None,
):
"""
Run the MLflow server, wrapping it in gunicorn or waitress on windows
:param static_prefix: If set... | 54,274 |
def v_vorticity(u, v, dx, dy, dim_order='xy'):
"""Wrap vorticity for deprecated v_vorticity function."""
return vorticity(u, v, dx, dy, dim_order=dim_order) | 54,275 |
def split_rgb(stack: Image, with_alpha=False) -> List[Image]:
"""Variant of stack_to_images that splits an RGB with predefined cmap."""
if not stack.rgb:
raise ValueError(
trans._('Image must be RGB to use split_rgb', deferred=True)
)
images = stack_to_images(stack, -1, colormap... | 54,276 |
def get_country(user):
"""
Returns the object the view is displaying.
"""
user_countries = ActivityUser.objects.all().filter(
user__id=user.id).values('countries')
get_countries = Country.objects.all().filter(id__in=user_countries)
return get_countries | 54,277 |
def test_request_post_body_not_camelcased():
"""test_request_post_body_camelcased function tests post request
with `camelize_response=False`.
"""
data = {"my_value": "test_value"}
request, response = main_options_app.test_client.post(
"/post", data=json.dumps(data)
)
assert response.... | 54,278 |
def isfirefox(session):
""" bool: Whether the session is using Firefox. """
return getattr(session.driver, "_firefox", False) | 54,279 |
def generate_readme(meta: Dict[str, Any]) -> str:
"""
Generate a Markdown-formatted README text from a model meta.json. Used
within the GitHub release notes and as content for README.md file added
to model packages.
"""
md = MarkdownRenderer()
lang = meta["lang"]
name = f"{lang}_{meta['n... | 54,280 |
def origin_tag(parser, token):
"""Create a node indicating the path to the current template"""
if hasattr(token, "source"):
origin, source = token.source
return OriginNode(origin)
else:
return OriginNode() | 54,281 |
def get_bucket_name(config, bucket_suffix=None):
"""
Return a bucket name of the form: ${account_id}-${project}-${suffix}
Args:
config: dictionary containing all variable settings required
to run terraform with.
bucket_suffix: string to add to the returned bucket name.
... | 54,282 |
def solve(
instance: CVRPInstance, params: Optional[LKHParams] = None
) -> CVRPSolution:
"""Solve a CVRP instance using LKH-3"""
params = params or LKHParams()
logger.info("Converting instance into a TSPLIB file")
convert_instance_file(instance, params)
logger.info("Calling LKH external solve... | 54,283 |
def break_track(xy,waypoints,radius_min=400,radius_max=800,min_samples=10):
"""
xy: coordinate sequence of trackline
waypoints: collection of waypoints
return pairs of indices giving start/end of transects, split by waypoints.
"""
breaks=[]
for waypt in waypoints:
dists = mag( xy[:... | 54,284 |
def parse_string(s):
"""
Parse string containing Snowball code.
Returns the corresponding AST.
"""
reset()
return PROGRAM.parseString(s)[0] | 54,285 |
def update_combobox(combo, labeldata, default_index=0):
"""
Redefine the items in a QComboBox
Parameters
----------
widget : QComboBox
The widget to update
labeldata : sequence of N (label, data) tuples
The combobox will contain N items with the appropriate
labels, and data... | 54,286 |
def main(d_sr, h_s, h_r, sigma, f_max_src):
"""
Pass the five main input parameters into each numerical method.
Each method (FDTD or TLM) is launched above a ground, then in free field. The analytic
solutions are calculated at the last step, in plot_spectrum.py, in which the FFTs are comp... | 54,287 |
def list_to_multipolygon_df(list_of_inds, discretizer=DefaultSystem, split=True):
"""
Parameters
----------
split : object
"""
unique_h3 = list(set(list_of_inds))
polys = [discretizer.ind_to_boundary(cod) for cod in unique_h3]
if split:
polys = [shp_help.split_polys(poly) for po... | 54,288 |
def test_leapfrog_float_two_steps_filtered(mock_prognostic_call):
"""Test that the Asselin filter is being correctly applied"""
mock_prognostic_call.return_value = ({'air_temperature': 0.}, {})
state = {'air_temperature': 273.}
timestep = timedelta(seconds=1.)
time_stepper = Leapfrog([MockPrognostic... | 54,289 |
def key_press_release(widget, key, modifier=Qt.NoModifier):
"""
Функция для отправления события нажатия кнопки.
# Имитация нажатия на пробел:
key_press_release(widget, Qt.Key_Space)
"""
key_press = QKeyEvent(QKeyEvent.KeyPress, key, modifier, None, False, 0)
QApplication.sendEvent(widget, ... | 54,290 |
def warn_deprecation(msg):
"""
Raise a warning and prints a deprecation message to stdout.
Parameters
----------
msg : str
Message that will be printed to stdout.
"""
# note, stack level 3 should take us back to original caller.
issue_warning(msg, stacklevel=3, category=OMDeprec... | 54,291 |
def Get_Data(filename, start, stop):
"""Takes output from txt file and converts to a np.array
Argument:
filename -- filename including end bit, enclosed in single inverted commas
start, stop -- integers, lines to read if there's a header etc
Returns:
array -- np.array of file c... | 54,292 |
def load_sample_weights(weights_dir, filename='.json', dtype=np.float):
"""Loads the sampled bnn weight sets from directory recursively into
memory.
"""
weights_sets = []
# loop through json files, get weights, concatenate them
# walk directory tree, grabbing all
#for filepath in glob.iglob... | 54,293 |
def get_es_index_name(project, meta):
"""
Get the name for the output ES index
:param project: seqr project identifier
:param meta: index metadata
:return: index name
"""
return '{project}__structural_variants__{sample_type}__grch{genome_version}__{datestamp}'.format(
project=projec... | 54,294 |
def triangle_coordinates(i, j, k):
"""
Computes coordinates of the constituent triangles of a triangulation for the
simplex. These triangles are parallel to the lower axis on the lower side.
Parameters
----------
i,j,k: enumeration of the desired triangle
Returns
-------
A numpy ar... | 54,295 |
def generate_lines(rects, room):
"""
Converts a list of rects each containing x, y, width, height, theta into a list of
lines (each rect has 4 lines)
room is (width, height) of surrounding room
returns list of lines, each line is 2 points
"""
# x, y, w, h, angle
rects.append([0, 0, room... | 54,296 |
def write_csv(filename, actions_and_observations):
"""Write simulation data to file.
Save actions and observed angles, angular velocities and torques for
data
analysis.
Args:
filename: The file to write. Can be locally or on CNS.
actions_and_observations: the interested simulation quantities to save... | 54,297 |
def init():
"""Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed.
For debugging and testing, this module may be accessed
through `Qt.__... | 54,298 |
def set_volume_count(credentials):
"""Search for and set the volume count for a manga on user's list
:param credentials: A tuple containing valid MAL account details in the format (username, password)
"""
# prompt the user to search their list for the entry
result = search_list(credentials[0], "man... | 54,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.