content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def subset_on_taxonomy(dataframe, taxa_level, name):
"""
Return only rows of the datframe where the value in column taxa_level
matches the specified name.
:param dataframe: Pandas DataFrame with columns like 'Kingdom',
'Phylum', 'Class', ...
:param taxa_level: a taxagenetic label such as "Genus... | a1d72a96b277791d677e2bf81073ed7f4daa423f | 17,021 |
def translation_existed(target_lang, translations):
""" Checks if the translation for a given key existed """
if target_lang in translations:
return True
return False | dffc81fd875ba134a34b35c587a43ab9af019f01 | 497,129 |
def nii_to_json(nii_fname):
"""
Replace Nifti extension ('.nii.gz' or '.nii') with '.json'
:param nii_fname:
:return: json_fname
"""
if '.nii.gz' in nii_fname:
json_fname = nii_fname.replace('.nii.gz', '.json')
elif 'nii' in nii_fname:
json_fname = nii_fname.replace('.nii', ... | bcd5e6d6c24943fe1e32e05dc36e9011ce24ecfc | 592,095 |
from typing import Dict
from typing import Any
def get_test_data() -> Dict[str, Any]:
"""
Auxiliary method to return test data args.
:return: Test data.
"""
return {
"root": {
"branch1": {"number": 23, "string": "value"},
"branch2": {"object": object(), "boolean": ... | 78b162e8f6b2b1b8f82e73f55bf0bc5f3425e829 | 621,664 |
import random
def calc_pi(N):
""" Estimates pi using Monte-Carlo """
M = 0 # Initialize the counter
for i in range(N):
# Simulate impact coordinates
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
# True if impact happens inside the circle
if x**2 + y**2 < 1.0:... | cdd56bfa5544dcf9850b06ca33dc13de046723ea | 459,842 |
def _append(so_far, item):
""" Appends an item to all items in a list of lists. """
for sub_list in so_far:
sub_list.append(item)
return so_far | 19163d1c02a3a248100e5c49e09a71068ac10ce7 | 541,978 |
def deleteItemByName(folderID, itemName, token, communicator):
"""Delete an item from a folder based on its name
folderID -- ID of the folder.
itemName -- Name of the item to delete.
token -- Authentication token.
communicator -- Midas session communicator.
Returns a boolean indicating success or ... | 688a6c4eba13e13ab497afb07cb42f3fcff4eade | 540,044 |
def get_min_max_landmarks(feature: list):
"""
Get minimum and maximum landmarks from training set
:param feature: list of features
:return: min/max landmarks
"""
return feature[-6:-3], feature[-3:] | 604c9b947d67795fe9cfec25159b410b6a0f3453 | 128,674 |
def cutoff_depth(d: int):
"""A cutoff function that searches to depth d."""
return lambda game, state, depth: depth > d | af7396a92f1cd234263e8448a6d1d22b56f4a12c | 705,354 |
def optimal_tuning_ratio(mass_ratio):
"""
Returns optimal tuning ratio (TMD freq / Mode freq) per eqn (7) in
Warburton & Ayorinde (1980)
"""
return 1 / (1 + mass_ratio) | 0f6070465a7d2249bdc990f435848c4fc42cf87c | 129,628 |
def getPolygonBounds(polygon):
"""
:param polygon:多边形上经纬度列表,eg:[(127.23,39.12),(126.23,36.45)]
:return:多边形外切矩形四个点的经纬度坐标信息元组,eg:(max_lng,min_lng,max_lat, min_lat)
"""
# 边界上的坐标列表化
lng_lst = [x[0] for x in polygon]
lat_lst = [x[1] for x in polygon]
# 将坐标进行处理,获得四个角落的坐标,构造一个矩形网络
max_lng,... | d317abf703b03c7e23af853ccd40a49f192fdce2 | 427,375 |
def separate_pauli(sigma):
"""Function
Extract coefficient and pauli word from a single QubitOperator 'sigma'
Args:
sigma (QubitOperator):
Returns:
coef (complex): coefficient
pauli (str): pauli word
"""
tmp = str(sigma).replace("]", "").split("[")
return complex(tmp... | 3ef0f1f65a78c91d42f093e1a3ef3c2fea92ceb1 | 200,802 |
def fill_in_the_blanks(noun, verb, adjective):
"""Fill in the blanks and returns a completed story."""
story = "I never knew anyone that hadn't {1} at least once in their life, \
except for {2}, old Aunt Polly. She never {1}, not even when that {0} came to \
town.".format(noun, verb, adjective)
return story | 648b315f73493c95ded815acd676740f271e8476 | 465,699 |
def _GetGroupByKey(entity, property_names):
"""Computes a key value that uniquely identifies the 'group' of an entity.
Args:
entity: The entity_pb.EntityProto for which to create the group key.
property_names: The names of the properties in the group by clause.
Returns:
A hashable value that uniquel... | c886168258b18c5cfd57d9c596df8bfd7608532a | 275,410 |
def file_extension(path):
"""Get the file extension of a path/filename."""
return path.split('/')[-1].split('.')[-1] | fe43378040e752d81df7c6775bb66b2b2c650ccf | 381,004 |
def get_source(source, provider):
"""
Returns `source` if given, otherwise `provider`
"""
if not source:
source = provider
return source | d84f1543ae9f31cec8709c6b2fbdc4c2e18142d0 | 582,297 |
def reference_vector_argument(arg):
"""
Determines a reference argument, so as not to duplicate arrays of reals, vectors and row vectors,
which usually have the same implementation.
:param arg: argument
:return: reference argument
"""
if arg in ("array[] real", "row_vector"):
return ... | 693d96b305a892ddaf9f7f97fe6f5270e63a4c59 | 532,656 |
def _localize(dt, tzinfo):
"""
:return: A localized datetime
:paramd dt: Naive datetime
:param tzinfo: A pytz or python time zone object
Attempts to localize the datetime using pytz if possible. Falls back to the builtin
timezone handling otherwise.
"""
try:
return tzinfo.locali... | f68588195197b250d88a710f01196d6dd701c2d1 | 637,518 |
import collections
def group_locations_by(locations, attribute):
"""
Group locations into a dictionary of lists based on an attribute.
:param list locations: A list of locations.
:param str attribute: Attribute name.
"""
grouped = collections.defaultdict(list)
for location in locations:
... | 3734eb79af2252f5e8d06d8d9fcb7322ed32ab0e | 325,100 |
import types
def _type_repr(obj):
"""Return the repr() of an object, special-casing types (internal helper).
If obj is a type, we return a shorter version than the default
type.__repr__, based on the module and qualified name, which is
typically enough to uniquely identify a type. For everything
... | 1da7d3af3a2fa31e909c2c00f59e92af32dfbf4e | 583,234 |
import json
def validateInputParametersFile(filename):
"""
Validates an input (json) file to check if
it contains the required keys. It does not
validate the values of the keys.
:param filename: Is a "Path" object that
contains the input model parameters for
the simulation.
:return: ... | adfc97191c56f32d16f5723a3a905736e2337046 | 184,089 |
def split_song_header(song_header):
"""Split the song title in half, to retrieve its artist an name.
Examples::
>>> song_header = 'Daughter:Run Lyrics'
>>> split_song_header(song_header)
(Daughter, Run)
Args:
song_header (string): song header / title to split
Retu... | d6299960264e41c23d2ae107ed242a043dd01a57 | 509,294 |
import logging
def get_logger_name(mylogger) -> str:
"""Find the name of the logger provided.
This is useful when configuring logging.
"""
ld = logging.Logger.manager.loggerDict
# ld = logman.loggerDict
# print("loggernames {}".format(ld.keys()))
for k, v in ld.items():
if v == myl... | 757fdbd620d4707bf892adac4332dafd13420420 | 440,358 |
def char_size(c):
"""Get `UTF8` char size."""
value = ord(c)
if value <= 0xffff:
return 1
elif value <= 0x10ffff:
return 2
raise ValueError('Invalid code point') | dd14e4e340697ce74472eefa55700a74c7029dce | 219,615 |
def __build_variable_string(translation, variables) -> str:
"""
Takes two parameters.
- translation: the string that will be used as the format in the translation string.
- variables: a list of variables that are used as replacement strings in the translation string.
Returns the translation string ... | 3482b6a7f0e8f89ad610e4421de05847c07e2281 | 262,059 |
def transformToRGB(lst):
"""
Change representation from 0-255 to 0-1, for triples value corresponding to RGB.
"""
def normToOne(x): return float(x)/255.
return [(normToOne(x), normToOne(y), normToOne(z)) for x, y, z in lst] | ec83893155bfaca7cbbec8281bd84ccb8401a48f | 75,050 |
def find_error_line(view, after):
"""Returns the first error after the given point."""
error_linenumbers = view.find_by_selector("constant.numeric.linenumber.error")
if not error_linenumbers:
return None
for region in error_linenumbers:
if region.begin() > after:
return region
# Go back to the ... | 94ba3966c0355e4ca3cdb0d4636a70e4c0764d6c | 596,018 |
def user_enabled(client, username):
"""
Checks if user is enabled. Takes:
* keystone client object
* username
Returns bool
"""
return client.users.list(name=username)[0].enabled | d6f264a670e3ad21954e55354a8a8e49bf47d12d | 381,727 |
from datetime import datetime
def is_datetime(string):
"""
Check if a string can be converted to a datetime object.
:param string: the string
:return: True if the string can be converted to a datetime object, False otherwise
"""
try:
datetime.strptime(string, "%Y-%m-%d %H.%M.%S")
... | d1fa368d1b7ac45b85661bd4b72771d088c4ac6f | 38,309 |
def square_summation(limit):
"""
Returns the summation of all squared natural numbers from 0 to limit
Uses the short form summation formula for summation of squares
:param limit: {int}
:return: {int}
"""
return (limit * (limit + 1) * (2 * limit + 1)) // 6 if limit >= 0 else 0 | e12830d76c48b23e08a3fcbc4de89ebf4f8dba21 | 447,828 |
import re
import uuid
def extract_uuid(filename):
"""
Given a filename containing a kernel, extract the uuid in
the kernel name.
Parameters
----------
filename : str
The name of the kernel-...-json file with the connection info.
Returns
-------
uuid : str or None
... | eccad7b6eaef3e0f16b531baec6bf701db4a960d | 595,122 |
def write_lines(new_lines, lines, edit_index):
"""
Inserts new lines where specified
:param new_lines: the new lines to be added
:param lines: holds all the current lines of output html file
:param edit_index: the index to insert new lines
:return: new contents of output htm... | e89d374b22aed26e57401d2529733b352baf3b8e | 215,869 |
def get_ont_query(predicate):
"""Return an ontology query based on the linking predicate."""
ont_query = """
SELECT ?sub ?res WHERE {
?sub <""" + predicate + """> ?res .
}
"""
return ont_query | 11d377d4ac80af6cdafb09aebedbfeb16fbba8ab | 512,742 |
def one_hot_to_int(x):
"""
Parameters
----------
x: torch.tensor; (N samples X C classes)
Returns
-------
torch.tensor; (N samples)
"""
return x.argmax(dim=1) | 64315136e1db137bb7638b0125bffbb6f4e94185 | 325,756 |
def str_to_int(s):
"""Convert binary strings (starting with 0b), hex strings (starting with 0x), decimal strings to int"""
if s.startswith("0x"):
return int(s, 16)
elif s.startswith("0b"):
return int(s, 2)
else:
return int(s) | 47ac2e7755d9a4d10b1e0712ad23aabb2c0489f5 | 48,547 |
def indent_string (s):
"""Put two spaces before each line in s"""
lines = s.split ("\n")
lines = [" " + i for i in lines]
lines = [("" if i == " " else i) for i in lines]
return "\n".join (lines) | 3b8edef2d454aabb31afdeeab9417a6b487d3c0e | 310,302 |
def ordinal(n):
"""Return the ordinal for an int, eg 1st, 2nd, 3rd. From user Gareth on
codegolf.stackexchange.com """
suffixes = {1: "st", 2: "nd", 3: "rd"}
return str(n) + suffixes.get(n % 10 * (n % 100 not in [11, 12, 13]), "th") | daa87b1b43d7c89348a9034aff389feb3b0b14d5 | 286,500 |
def lower_first(string):
"""Return a new string with the first letter capitalized."""
if len(string) > 0:
return string[0].lower() + string[1:]
else:
return string | fc6fba78d15633f1ab21105fbd46883797444fb1 | 700,609 |
def bartz_sigma_sanchez(T_e, T_avg, w=0.6):
"""Correction factor for the Bartz equation.
Reference:
[1] M. Martinez-Sanchez, "Convective Heat Transfer: Reynolds Analogy,"
MIT 16.512 Lecture 7. https://ocw.mit.edu/courses/aeronautics-and-astronautics/16-512-rocket-propulsion-fall-2005/lecture-note... | 9230d56ae5b33836a39c9272ca4996aa89126792 | 424,639 |
def _generate_stack_status_path(stack_path):
"""
Given a path to the stack configuration template JSON file, generates a path to where the
deployment status JSON will be stored after successful deployment of the stack.
:param stack_path: Path to the stack config template JSON file
:return: The path... | b0573148565e8cf338d4bc6877151cbe4186ebf5 | 58,509 |
def is_color(im):
"""Returns True if the image is a color image (3 channels) and false if not."""
return len(im.shape) == 3 | d598571ea5315fff8912f1f08e8c469dc76f1b75 | 153,137 |
def mk_filter_by_unk_ratio(vocab, max_unk_ratio=0.0, is_tbptt=False):
"""Return a filter function that takes a sentence, and returns True if a sentence
meet a criterion (unk ratio is below max).
NOTE: each sentence contains a bos and an eos, which are excluded for calculating unk ratio.
If is_tbptt is ... | 113242f681c195819e3ccc827997a8ba1b92082f | 560,735 |
def _jinja2_filter_icon_style(value):
"""Formats the icon style for templates"""
return 'ok' if value else 'remove' | 11486e9f53bda2e340d3ae262abbed16fdc3fdb5 | 171,978 |
import typing
def convert_value(dtype: typing.Any, value: typing.Any, default: typing.Any = None) -> typing.Union[typing.Any, None]:
"""
Return the passed value in the specified value if it is not None and does not raise an Exception
while converting. Returns the passed default if the conversion failed
... | 3fd02525daf5db4b8761b3af3746004db9459429 | 58,451 |
def get_reddit_posts(subreddits, limit, score, num_comments):
"""Collect submissions related data, including title, link, current score, the number of comments, etc.
Params:
-------
subreddits: list
a list of praw.Reddit.subreddit instances
limit: int
maximum number of submissio... | 664720609116cdd4512cec225b18fbb51a1e7369 | 614,656 |
def get_label2id(labels):
"""
Get label2id mapping based on labels
Args:
labels: list of labels.
Return:
label2id map
"""
return {v: str(k) for k, v in enumerate(labels)} | 644b9ce55a3df43eb8c85ed8086b2d10dbcc6951 | 84,592 |
def select_text_color(r, g, b):
"""
Choose a suitable color for the inverse text style.
:param r: The amount of red (an integer between 0 and 255).
:param g: The amount of green (an integer between 0 and 255).
:param b: The amount of blue (an integer between 0 and 255).
:returns: A CSS color in... | a8663b261c0d6ae087d08e8ecb67a77d51935b10 | 678,960 |
import torch
def reduce_sign_any(input_tensor, dim=-1):
"""A logical or of the signs of a tensor along an axis.
Args:
input_tensor: Tensor<float> of any shape.
axis: the axis along which we want to compute a logical or of the signs of
the values.
Returns:
A Tensor<float>, which as th... | 72dde84d97a8744c880bd7bbc92cb020cbe0d156 | 575,253 |
def _transform_interval(
interval, first_domain_start, first_domain_end, second_domain_start, second_domain_end
):
"""
Transform an interval from one domain to another.
The interval should be within the first domain [first_domain_start, first_domain_end]
For example, _transform_interval((3, 5), ... | c1743f605ec7093ed3ceb42193251c12339c3bc6 | 454,726 |
def get_diff(df, column1, column2):
"""Get the difference between two column values.
Args:
df: Pandas DataFrame.
column1: First column.
column2: Second column.
Returns:
Value of summed columns.
Usage:
df['item_quantity_vs_mean'] ... | 1fc5ec361cfdd28775257980c28b4924fdab4eeb | 24,810 |
def mime_to_pltfrm(mime_string):
"""
Translates MIME types to platform names used
by tng-cat. Returns: 5gtango|osm|onap
"""
pattern = ["5gtango", "osm", "onap"]
for p in pattern:
if p in str(mime_string).lower():
return p
return None | 05d424fb1371466f3372bf8b052a0cb97b7852a8 | 437,904 |
import textwrap
def _format_doc(docstring, prefix):
"""Use textwrap to format a docstring for markdown."""
initial_indent = prefix
# subsequent_indent = " " * len(prefix)
subsequent_indent = " " * 2
block = docstring.split("\n")
fmt_block = []
for line in block:
line = textwrap.f... | 1bf2bf0ee35f9b6e345eb8c70355d0a86bf74290 | 636,567 |
def sum_bbox(bbox1, bbox2):
"""Summarizes two bounding boxes. The result will be bounding box which
contains both provided bboxes.
:type bbox1: list
:param bbox1: first bounding box
:type bbox2: list
:param bbox2: second bounding box
:rtype: list
:return: new bounding box
"""
if not bbox1 or not ... | 83c0eddfe03e66843cbbc6c7de21be6688905087 | 87,956 |
def convert_variable(datatype, variable):
"""
Convert variable to number (float/int)
Used for dataset metadata and for query string
:param datatype: type to convert to
:param variable: value of variable
:return: converted variable
:raises: ValueError
"""
try:
if variable and ... | adaf06dde50a3667ee72000f5e346e41415ca2e7 | 234,302 |
def is_ebx(line):
"""Determines whether the line of code is a part of the rolling
key update (EBX register).
Args:
line (AsmBlock): one asm instruction with its operands
"""
return (len(line.args) >= 1
and str(line.args[0]) in ["EBX", "BX", "BL"]
and not line.name ==... | 76301b0ae8a5d96de2e8794e62487325ebddadab | 469,773 |
def diff21(n: int) -> int:
"""Absolute difference between n and 21.
Returns abs(n-21) if n <= 21 and abs(n-21) * 2 if n > 21.
"""
diff = abs(n - 21)
if n > 21:
return diff * 2
return diff | 8b6638a586ff2bf14cce4781bf7da0b9ae20c527 | 391,702 |
def add_commas(number):
"""1234567890 ---> 1,234,567,890"""
return "{:,}".format(number) | 3db1b2c73b2a65367458155745ba9f27f3e88917 | 140,483 |
import pickle
def load_object(pathname):
"""Load an object from disk using pickle.
Parameters
----------
pathname : str
Full path of the file where the object is stored.
Returns
-------
obj : any type
Object loaded from disk.
"""
with open(pathname, 'rb') as fid:
... | 3780e8ba607c35253bc22fff158e8ef09ca6d66e | 203,808 |
def get_user_attribute_default(attribute, ctx):
"""Return the default value for the given attribute of the user passed in the context.
:param attribute: attribute for which to get the current value
:param ctx: click context which should contain the selected user
:return: user attribute default value if... | 1fd290a391f2a2fd2bccc8437ad6b355495cc576 | 351,450 |
def cgi2dict(form, linelist):
"""Convert the form from cgi.FieldStorage to a python dictionary"""
params = {'linelist': linelist.value}
for key in form.keys():
if key != 'linelist':
params[key] = form[key].value
return params | c935c8f3393439a6632cd4a70c7a684c3ce42a85 | 634,683 |
def apply_function_on_axis_dataframe(df, func, axis=0):
"""Apply a function on a row/column basis of a DataFrame.
Args:
df (pd.DataFrame): Dataframe.
func (function): The function to apply.
axis (int): The axis of application (0=columns, 1=rows).
Returns:
pd.DataFra... | 631a9e3e62f8fc382f26450a9d9399842a544bda | 596,522 |
import requests
def _prepare(*args, **kwargs):
""" Return a prepared Request. """
return requests.Request(*args, **kwargs).prepare() | 5762d24e340483516ca5aaad8911e43572274f05 | 219,225 |
def leapdays(y1, y2):
"""Return number of leap years in range [y1, y2).
Assume y1 <= y2."""
y1 -= 1
y2 -= 1
return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400) | d66a6ee4633bdcb3719805f404e60adfe2a7fa6d | 229,810 |
def rec_fact(num):
"""rec_fact(int) -> int
Recursive function which takes an integer and computes the factorial.
>>> rec_fact(4) # 4*3*2*1 = 24
24
"""
if not isinstance(num, int):
raise TypeError("Must be a positive int")
if num == 0:
return 1
return num * rec_fact(nu... | 636b81145ac424c1d680bb95470c91773d37e7bd | 592,776 |
def content_loss(P, X, layer):
"""
Defines the content loss contribution from two images at a specific layer. Reasoning: If the content of
two images is the same the response of a given layer for each image should be the same.
Note that additionally there is a 1 / image size factor which was not in the ... | 40acaf3b1f447a98e73eed17536a406b138c9b56 | 398,276 |
def tf_sched(cur_epoch,epochs,final_tf_ratio):
"""
modified teacher forcing ratio according to epoch counts
Args:
cur_epoch: (int) current epoch
epochs: (int) total epochs
final_tf_ration: (float) smallest teacher forcing ratio
Returns:
teacher forcing ratio for cur... | f24f5efb9f5d570d8d3f9abde4ca371b9ad24d5f | 513,306 |
import yaml
def load(stream, is_safe=True):
"""Converts a YAML document to a Python object.
:param stream: the YAML document to convert into a Python object. Accepts
a byte string, a Unicode string, an open binary file object,
or an open text file object.
:param is_s... | ddb6d38f637aa38b70e647ff0566ae765408da29 | 418,017 |
def result_to_dict(res):
"""
:param res: :any:`sqlalchemy.engine.ResultProxy`
:return: a list of dicts where each dict represents a row in the query where the key \
is the column name and the value is the value of that column.
"""
keys = list(res.keys())
return [dict(zip(keys, row)) for row... | 9c93c1e23db07cf14f4b3a3f9e353368bdb28e16 | 426,127 |
def gpib_control_ren(library, session, mode):
"""Controls the state of the GPIB Remote Enable (REN) interface line, and optionally the remote/local
state of the device.
Corresponds to viGpibControlREN function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session:... | 4d9fc21bb3bca7cbd98c94c064500d0ce319e5cc | 683,409 |
def read_minisat_result(result_path):
"""Read the output from minisat.
Returs one of:
None -- empty file
'UNSAT' -- unsatisfiable result
dict containing the assignment -- satisfiable result
"""
with open(result_path) as f:
s = f.read().rstrip()
head = s.split()[0]
if... | a0462fad0dcbdb18cad33df479cdc7336bf07fbf | 214,688 |
import calendar
def millis(input_dt):
"""Convert datetime to milliseconds since epoch
Parameters
----------
input_df : datetime
Returns
-------
int
"""
return 1000 * int(calendar.timegm(input_dt.timetuple())) | b395c419b78d7721f4d67acc7987491af447896b | 461,396 |
def filter_columns(data,column_names):
"""Keep selected columns in the dataframe."""
selected_columns = data[column_names]
return selected_columns | c6056aaff62201f6a6e666f82613aa5cd95de369 | 614,208 |
def str_to_bool(val):
"""
cast a string to a bool
Parameters:
val: the string to cast
Returns:
(casted_val, success)
casted val: the casted value if successful, or None
success: bool if casting was successful
"""
if val == 'True':
return (True, True)
... | fdcedf41a136f14e13584a191985f120b5a637a2 | 487,064 |
import random
def rand_int(start=1, end=10, seed=None):
"""
Returns a random integer number between the start and end number.
.. versionadded:: 2015.5.3
start : 1
Any valid integer number
end : 10
Any valid integer number
seed :
Optional hashable object
.. vers... | e7e56a2b3f6b7684fe75c26ac96b59215db953f0 | 641,172 |
def trim_keys(dict_):
"""remove dict keys with leading and trailing whitespace
>>> trim_keys({' name': 'value'}) == {'name': 'value'}
True
"""
return {k.strip(): v for k, v in dict_.items()} | 67662f9e4636118dacf8595c1f4e2b6ea85fb2fa | 498,469 |
def list_vm(client, resource_group_name=None):
"""
Returns a list of VMware virtual machines in the current subscription.
If resource group is specified, only the virtual machines
in that resource group would be listed.
"""
if resource_group_name is None:
return client.list_by_subscripti... | 12db2abd8ba4ffd7905a826ad5b56f7259cf6016 | 180,386 |
def restore_original_texture_name(filename: str) -> str:
"""Create original texture name from RSB filename"""
newfilename = filename
if filename.startswith("TGA"):
#Strip TGA from front of filename
newfilename = filename[3:]
newfilename = newfilename[:-4] + ".tga"
else:
n... | a295a682af551982cf5d46f61c42325ba7ea9181 | 169,854 |
def _clear_bits(basis_state, apply_qubits):
""" Set bits specified in apply_qubits to zero in the int basis_state.
Example:
basis_state = 6, apply_qubits = [0, 1]
6 == 0b0110 # number in binary representation
calling this method returns sets the two right-most bits to zero:
retu... | 97f27fc0843c76bb05d98f3c62a52d09cfd3e9cc | 302,626 |
def identity(image, *args, **kwargs):
"""Returns the first argument unmodified."""
return image | 9330f42fa6d18465d7a081d6da3bf38669fb5e57 | 191,313 |
def get_progress_rate(k, c_species, v_reactants):
"""Returns the progress rate for a reaction of the form: va*A+vb*B --> vc*C.
INPUTS
=======
k: float
Reaction rate coefficient
c_species: 1D list of floats
Concentration of all species
v_reactants: 1D list of floats
Stoi... | 6baaaa07fe0814dbc50516b29ba55087c4ec23fd | 12,431 |
def query(field, op, value, type=''):
"""Assemble a dict representing a query filter.
:param field: Field to query
:type field: String
:param op: Query operator
:type op: String
:param value: Value to query
:type value: String
:param type: Type of the value
:type type: String
:r... | 9fa98cbfefc062782e8aa1e89bcaabcac926a49a | 572,894 |
import json
def get_json(content):
"""Decode the JSON records from the response.
:param content: the content returned by the eBird API.
:type content: http.client.HTTPResponse:
:return: the records decoded from the JSON payload.
:rtype: list
"""
return json.loads(content.decode("utf-8")... | 3e2e88063ddc730170212e635e11e64aca474a47 | 650,737 |
def fuzzy_match_reference(fuzzy_matcher, reference):
"""
Args:
fuzzy_matcher: instance of FuzzyMatcher, with index of publications in place.
reference: reference
Returns:
matched reference (citations), including publication & doc id.
"""
return fuzzy_matcher.match(reference) | 13041f6a7de1cdc67728174a3168b198fa252b12 | 478,872 |
def encode_headers(headers):
"""Encodes HTTP headers.
Args:
headers: Dictionary of HTTP headers.
Returns:
String containing encoded HTTP headers.
"""
return '\n'.join(["%s: %s"%(k,headers[k]) for k in sorted(headers.keys())]) | 21ce28af5fa62cc5be12b6543a078c5ca9890093 | 181,337 |
import torch
def normalize(tensor, min=None, max=None):
"""
Normalize the tensor values between [0-1]
Parameters
----------
tensor : Tensor
the input tensor
min : int or float (optional)
the value to be considered zero. If None, min(tensor) will be used instead (default is Non... | 46f413ffc1aacde12ab6f8d95bba105fc58f86d3 | 663,868 |
import locale
def generate_sorted_sem_terms(sem_features):
"""
Generates 1, 2, 3, 4-grams of lexicographically sorted semantic terms
according to UTF-8 order.
Args:
sem_features: list of semantic features.
Returns:
List of semantic terms in lexicographic order.
"""
terms ... | 5cb53b977acfb7c5f79444f455bd6b829aea4774 | 165,644 |
import functools
def require_privilege(level, message=None):
"""Decorate a function to require at least the given channel permission.
`level` can be one of the privilege levels defined in this module. If the
user does not have the privilege, `message` will be said if given. If it is
a private message... | ec1e255f2c4bd91eed6d4f549c6f13baab7146e2 | 349,315 |
import hashlib
def HashToCurve(curve, hash_oid, hv):
"""
Hash the provided input data into a curve point. The data (hv) is
either raw unhashed data, or a hash value if the data was pre-hashed.
'hash_oid' identifies the hash function used for pre-hashing; use b''
(empty string) for raw unhashed dat... | feb30406604a6f466a57e2c1c1a5da0a1d65b63d | 217,531 |
def school2nation(id_num):
"""
Takes school id, returns nation id of the school.
"""
if id_num < 97100000:
return id_num // 100000 * 10000
if id_num < 97200000:
return 7240000
if id_num < 97400000:
return 8400000
return 320100 | 74e7eb74b2adf1cd2c8855a1bcc35eddf38586e3 | 633,639 |
def _undo_op(arg, string, strict=False):
"""
Undo symbolic op if string is in str(op).
Returns <arg> untouched if there was no symbolic op.
Parameters
----------
arg : any symbolic variable.
string : str
String that specifies op.
strict : bool
Whether to force op undo o... | c2cd121ae2ebce49c921fff0f63e0dfd844565d9 | 614,543 |
def underline_filter(text):
"""Jinja2 filter adding =-underline to row of text
>>> underline_filter("headline")
"headline\n========"
"""
return text + "\n" + "=" * len(text) | 417340cef3dce0348e197d7af9150b8407a8fa5e | 65,423 |
def wind_dir(degrees):
"""Provide a nice little unicode character of the wind direction"""
# Taken from jenni
if degrees == 'VRB':
degrees = '\u21BB' # ↻
elif (degrees <= 22.5) or (degrees > 337.5):
degrees = '\u2B06' # ⬆
elif (degrees > 22.5) and (degrees <= 67.5):
degrees... | 2ddc9445d9da8607ca32ab6536b6c254be8e1bf2 | 177,598 |
def get_paren_substring(string: str) -> str | None:
"""Get the contents enclosed by the first pair of parenthesis
Parameters
----------
string : str
A string
Returns
-------
str | None
The part of the string enclosed in parenthesis e.g. or None
Examples
--------
... | 20694128171cf17f9aa23f1cb049591424e0276f | 200,704 |
def mocked_elasticsearch(mocked_elasticsearch_module_patcher):
"""
Fixture that resets all of the patched ElasticSearch API functions
"""
for mock in mocked_elasticsearch_module_patcher.patcher_mocks:
mock.reset_mock()
return mocked_elasticsearch_module_patcher | 0dabc985d1dbcd7eda3d365447c1241f54143644 | 641,438 |
def xyz_to_zne(st):
"""
Convert channels in obspy stream from XYZ to ZNE.
"""
for tr in st:
chan = tr.stats.channel
if chan[-1] == 'X':
tr.stats.channel = chan[:-1] + 'E'
elif chan[-1] == 'Y':
tr.stats.channel = chan[:-1] + 'N'
return st | 37c7b28ea81d41abc606c9b3ec1e1ce7788ff7f6 | 172,785 |
import collections
def filter_dataframes(dfs, xs, ys, table_ys, args_list, valid_keys):
"""Process necessary information from dataframes in the Bokeh format.
In the following explanation, N is assumed to be the number of experiments.
For xs_dict and ys_dict:
These are dictionary of list of list.... | 903ce855378d174370117d9cb729f1052c682ac4 | 695,596 |
def one_level_dict(res):
""" Transforms nested dict to dictionary only one level deep """
configs = []
roots = []
iters = []
energies = []
waves = []
ints = []
for config in res:
for root in res[config]:
for iteration in res[config][root]["peaks"]:
dat... | a1657aff2e22eb9012a07f5a2bcb6ea1db264490 | 551,914 |
def get_lines(self):
"""The list returned contains all the Line of the SurRing
Parameters
----------
self : SurfRing
A SurfRing object
Returns
-------
line_list : list
list of lines delimiting the surface
"""
line_list = self.out_surf.get_lines()
line_list.ext... | 9a9966fa86ed8f4a5aebc996fa4252ad67d12ffb | 640,200 |
def create_filename(ticker, interval, mmyy):
"""
Create a filename based on a set of given parameter values.
:param ticker: the ticker symbol
:param interval: the time interval of the data
:param mmyy: the date (in mmyy format) for which data is being fetched
:return: filename string
"""
... | 8ed5f59dacfc381748b19be3bdea6f255308c6cb | 604,546 |
def collect_blocks(d_blocks, ayear, n):
"""
Collect a block of patents for a window of n years regarding a focus
year.
If n is possitive the patents are from the future.
If n is possitive the patents are from the past.
Parameters
----------
d_blocks : A dictionary of patent blocks, the... | ea7029092610a59e50c5ff9e59f06f16a43a3420 | 121,205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.