content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def ignore_answer(answer):
"""
Should this answer be disregarded?
"""
return (answer == "<Invalid>") or \
answer.startswith("<Redundant with") | 4ef4e55bae942d4c33b5fe1f4e6f9b339c332e92 | 315,004 |
import logging
import time
def execute_trade(market, action):
"""
Makes a trade via the API and responds once completed.
May have multiple retrys before raising exception if it failed.
Likely steps:
1. Initialise the trading API
2. Post trade to the API
3. Confirm success in response or r... | 63bc6bf5d74fca5d242fd337c1cec8298d2a6626 | 445,946 |
def positive_negative(inputlist):
""" return true if all items in the input list having same sign (+ or -)"""
if ((all(item>0 for item in list(inputlist))) or (all(item<0 for item in list(inputlist)))):
return True # elements with same sign (+ or -)
else:
return False | 69ebde6129139f5212d50891b4b81c0a5a76d51f | 576,430 |
import time
def pretty_epoch(epoch, format_):
""" Convert timestamp to a pretty format. """
return time.strftime(format_, time.localtime(epoch)) | 7cb0fd5185020da7e3c59592e8a476ecc0ff7046 | 429,617 |
import time
async def bench_to_arrow(client):
"""Test how long it takes to create a view on the remote table and
retrieve an arrow."""
table = client.open_table("data_source_one")
view = await table.view()
start = time.time()
arrow = await view.to_arrow()
end = time.time() - start
asse... | dccf9efc0516dc2774d886ec64182b85de97e428 | 102,328 |
def _xlRange_from_corners(xlWorksheet, r1, c1, r2, c2):
"""Get excel Range for (row1,column1) to (row2, column2), inclusive."""
return xlWorksheet.Range(xlWorksheet.Cells(r1,c1), xlWorksheet.Cells(r2,c2)) | ced64e630adb07de1f4447a42afc08b3672efadb | 467,878 |
def _is_version_range(req):
"""Returns true if requirements specify a version range."""
assert len(req.specifier) > 0
specs = list(req.specifier)
if len(specs) == 1:
# "foo > 2.0" or "foo == 2.4.3"
return specs[0].operator != '=='
else:
# "foo > 2.0, < 3.0"
return Tr... | c0602a1b28d787d93897f8380e34ee683cc95ad0 | 640,911 |
import re
def valid_mac_address(addr):
"""Validate a physical Ethernet address"""
return re.match("[0-9a-f]{2}([-:][0-9a-f]{2}){5}$", addr.lower()) | 033ee7ccb4a2a4f5cca96f896a6c72ca26351377 | 539,428 |
import hashlib
def _file_hash(filename: str) -> str:
"""Compute the hash of a file.
Args:
filename: the filename to hash.
Returns:
The hash hex string of the file contents.
"""
sha256_hash = hashlib.sha256()
with open(filename, "rb") as f:
# Read and update hash string value in blocks of 4K
... | a3d1860701c5ea59807930929ccfcbccde6e6e18 | 454,247 |
def episode(sim, agent, params):
"""Builds an episode graph using a Simulator and an Agent
Args:
sim: a Simulator object
agent: an Agent object
params: application level constants
Returns:
(a_ts, q_ts)
a_ts: (batch_size, num_actions)[time_steps], tf.int32, the chosen actions
q_ts: (batch... | 85c29ec80830ad1863ac75286b12208c5819d96e | 159,448 |
def parse_distance(distance):
"""parse comma delimited string returning (latitude, longitude, meters)"""
latitude, longitude, meters = [float(n) for n in distance.split(',')]
return (latitude, longitude, meters) | 954ef035e5aa5fa7965285622b5916ac1d51ac99 | 677,698 |
import re
def escape(toencode):
"""URL-encode data."""
if toencode is None:
return None
return re.sub(r"[^a-zA-Z0-9_.-]", lambda m: "%%%02x" % ord(m.group()),
str(toencode)) | bc82512b9d5f23b8aa1a86d1db8c1278c5278738 | 497,701 |
def compress(traj, copy=True, **kwds):
"""Wrapper for :meth:`Trajectory.compress`.
Parameters
----------
copy : bool
Return compressed copy or in-place modified object.
**kwds : keywords
keywords to :meth:`Trajectory.compress`
Examples
--------
>>> trc = compress(tr, co... | 42ebefdddeaecd67f61dd884dab31a3ec7f864c9 | 26,823 |
def notfound(request):
"""Handle a request for an unknown/forbidden resource."""
request.response.status_int = 404
return {} | 13693e24ba677e5095e7de651f7e85950502699c | 159,223 |
import torch
def dual_complete(u, v, s, alpha, beta, eps):
"""
min_{u>=0, v<=0} d(u, v)
= E_xy [ u(x)alpha(x) + v(y)beta(y) + Softplus(1/eps)(s-u-v) ]
"""
u = torch.as_tensor(u, device=s.device).reshape((-1, 1))
v = torch.as_tensor(v, device=s.device).reshape((1, -1))
if eps > 0:
... | d0008182434509a7192495519373882f2c1f1e67 | 103,347 |
import uuid
def create_hook_name(name=""):
"""
Utility to create a unique hook name. Optionally takes in a name. The output string is the name prefixed with a
UUID. This is useful to prevent collision in hook names when one class with hooks inherits hooks from another class
Example:
>>> creat... | a7c72abc91cbe1395a5115388834d4cf7de40e8f | 314,673 |
def permutation_from_disjoint_cycles(cycles, offset=0):
"""Reconstruct a permutation image tuple from a list of disjoint cycles
:param cycles: sequence of disjoint cycles
:type cycles: list or tuple
:param offset: Offset to subtract from the resulting permutation image points
:type offset: int
:... | 3c992f3612340e94e569b81be9195f79de8f864e | 587,045 |
def _decode_mask(mask):
"""splits a mask into its bottom_any and empty parts"""
empty = []
bottom_any = []
for i in range(32):
if (mask >> i) & 1 == 1:
empty.append(i)
if (mask >> (i + 32)) & 1 == 1:
bottom_any.append(i)
return bottom_any, empty | 6b93a30881ed526e801b4ad55c4a04af5562d8b6 | 73,741 |
import logging
import requests
import json
def add_intersight_resource_group(AUTH, MOIDS, CLAIM_CONFIG):
""" Create an Intersight Resource Group for Claimed Devices """
request_body = {
"Name":CLAIM_CONFIG['partner_id'] + "-rg",
"Qualifier":"Allow-Selectors",
"Selectors":[
... | b8d7653886b9ee2468eba447a452d625b9c6db0b | 285,273 |
import json
def read_config_file(fpath):
"""Create a dictionary of settings based on the json config file."""
with open(fpath) as input_file:
cfg = json.load(input_file)
return cfg | 1ea6fd5ef952626adbef55cd85fd62c6aa191b5f | 287,255 |
def returner( argument ):
"""
A module function that returns what you give it
"""
return argument | 29384104d99d6cbc10fc10cc9b0b0a78a2c72b53 | 131,422 |
def get_first_aligned_bp_index(alignment_seq):
"""
Given an alignment string, return the index of the first aligned,
i.e. non-gap position (0-indexed!).
Args:
alignment_seq (string): String of aligned sequence, consisting of
gaps ('-') and non-gap characters, such as "HA-LO" or "---... | d16331cb0cf6e94cfcb8aa04730520aeec915480 | 682,367 |
import time
def wait_release(text_func, button_func, menu):
"""Calls button_func repeatedly waiting for it to return a false value
and goes through menu list as time passes.
The menu is a list of menu entries where each entry is a
two element list of time passed in seconds and text to displa... | 63ac22a0fd9ed4eb4fcabeb54b37f55755a79ad1 | 247,498 |
import math
def compute_air_distance(_src, _dst):
"""Compute Air Distance
based on latitude and longitude
input: a pair of (lat, lon)s
output: air distance as km
"""
distance = 0.0
if _src == _dst:
return distance
radius = 6371.0 # km
dlat = math.radians(_dst[0] - _src... | 856b1b1e8c720625daa73f511fe841429d9e47f7 | 148,177 |
import random
def sample_baselines(bls, seed=None):
"""
Sample a set of baselines with replacement (to be used to generate a
bootstrap sample).
Parameters
----------
bls : list of either tuples or lists of tuples
Set of unique baselines to be sampled from. If groups of baselines
... | e53c66141fa4a90b6d74d64d59ecfae112d93d67 | 577,109 |
def get_w_gen_d_t(w_gen_MR_d_t, w_gen_OR_d_t, w_gen_NR_d_t):
"""(65a)
Args:
w_gen_MR_d_t: 日付dの時刻tにおける主たる居室の内部発湿(W)
w_gen_OR_d_t: 日付dの時刻tにおけるその他の居室の内部発湿(W)
w_gen_NR_d_t: 日付dの時刻tにおける非居室の内部発湿(W)
Returns:
日付dの時刻tにおける内部発湿(W)
"""
return w_gen_MR_d_t + w_gen_OR_d_t + w_gen_NR_d_... | 8166ea84c0adca839397fac35ee74d809bfe4b95 | 94,306 |
def ne(x, y):
"""Not equal"""
return x != y | 9e8f60889705122d0a6f98febdc689983a9e4cbf | 640,071 |
import json
def get_manageiq_config_value(module, name):
""" Gets the current value for the given config option.
:param module: AnsibleModule making the call
:param name: ManageIQ config option name
:return: dict of value of the ManageIQ config option
"""
returncode, out, err = module.run_comm... | 9e8d6c4afb5e7d962925c2b568836a04637c2c4b | 299,955 |
def _start_lt_end(params):
"""Check that 'start' param is < 'end' param
if both params are found in the provided dict.
In-place edit of params.
Parameters
----------
params : dict
{param_ID:param_value}
"""
if ('start' in params) & ('end' in params):
try:
sta... | 23379d1fbc443bd453b9239c971cda15efa7c05a | 140,429 |
import requests
def _post_request(url, token, body=None):
"""
Send a requests.post request
:param url: URL
:param token: authorization token
:param body: body to be sent with request
:return: json of response
"""
headers = {
'Authorization': 'bearer ' + token
}
if body... | adb1923bb18f21b98356bc4bc7fd7e79b59e2dfb | 84,893 |
def maybe(string):
"""
A regex wrapper for an arbitrary string.
Allows a string to be present, but still matches if it is not present.
"""
return r'(?:{:s})?'.format(string) | ce86a3ef9c42df184954aabed43634370816b3ed | 451,189 |
def HasPackedMethodOrdinals(interface):
"""Returns whether all method ordinals are packed such that indexing into a
table would be efficient."""
max_ordinal = len(interface.methods) * 2
return all(method.ordinal < max_ordinal for method in interface.methods) | 6c52e6ca065664480f3f32ac79906f9a9906b57e | 636,564 |
import requests
def get_resource(url, params=None, timeout=20):
"""Initiates an HTTP GET request to the SWAPI service in order to return a
representation of a resource.
Parameters:
url (str): a url that specifies the resource.
params (dict): optional dictionary of querystring arguments.
... | 411070c6795cf47a1cf2cee418043ebca1a1bace | 452,299 |
import torch
def split_train_test(X, y, train_size=0.8, shuffle=True):
"""
Split data into training and testing sets
Parameters:
X (Tensor): The input data
y (Tensor): The labels
train_size (float): The fraction of data used for the training
shuffle (boolean): Whether to randomly shuffle ... | 699615ca3ea8adb932aef457db8c13724cb5e73a | 410,303 |
from typing import List
def orderings3() -> List[List[int]]:
"""Enumerates the storage orderings for an input with rank 3."""
return [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] | 6f67a43903c070fc0d650ca6826945dffee9ac96 | 162,801 |
def _IsOutsideTimeRange(timestamp,
time_range = None):
"""Returns a boolean indicating whether a timestamp is in a given range."""
return time_range is not None and (timestamp < time_range[0] or
timestamp > time_range[1]) | 05b72d28607b74f0b71517381583ca88dde0efc5 | 636,704 |
def sort_io_dict(performance_utilization: dict):
"""
Sorts io dict by max_io in descending order.
"""
sorted_io_dict = {
'io_all': dict(sorted(performance_utilization['io'].items(), key=lambda x: x[1], reverse=True))
}
performance_utilization.update({**sorted_io_dict})
del performanc... | 86e30398d810b23b46f598926a08da62b1d3260d | 376,696 |
import jinja2
def create_jinja2_template_env(searchpath: str = "./templates") -> jinja2.Environment:
"""
Creates a usable template environment for Jinja2.
"""
return jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=searchpath)) | 7c9f2354ab32798de73c5d8b45a7042efb0b15f3 | 353,064 |
def format_speak_tags(sentence: str, include_tags: bool = True) -> str:
"""
Cleans up SSML tags for speech synthesis and ensures the phrase is wrapped in 'speak' tags and any excluded text is
removed.
Args:
sentence: Input sentence to be spoken
include_tags: Flag to include <speak> tags ... | 354de2fb2b6cc6e4a688393135f179461b9cd417 | 131,457 |
from typing import List
def ls_double_quote_if_contains_blank(ls_elements: List[str]) -> List[str]:
"""double quote all elements in a list of string which contain a blank
>>> ls_double_quote_if_contains_blank([])
[]
>>> ls_double_quote_if_contains_blank([''])
['']
>>> ls_double_quote_if_conta... | 1f3759072101995eea9a5f5397c18cd402d5c5b0 | 214,978 |
def parseDBXrefs(xrefs):
"""Parse a DB xref string like HGNC:5|MIM:138670 to a dictionary"""
#Split by |, split results by :. Create a dict (python 2.6 compatible way).
if xrefs == "-": return {}
return dict([(xrefParts[0], xrefParts[2])
for xrefParts in (xref.partition(":")
... | 8c64efd14d9dfc1367552a4af541d0c67dd749dc | 237,038 |
def restapi_predict(model, X):
"""
Computes the prediction for model *clf*.
:param model: pipeline following :epkg:`scikit-learn` API
:param X: inputs
:return: output of *predict_proba*
"""
return model.predict_proba(X) | a9bbb797948b4e238a3800fb3a225c9773c6bba8 | 449,235 |
import re
def re_search(pattern, text, plural=False):
"""Regex helper to find strings in a body of text"""
match = [m.group(1) for m in re.finditer(pattern, text)]
if plural:
return match
else:
if match:
return match[0] | 66998eb3b29978260eb60603cf440f95a16eb532 | 48,252 |
def calculate_resistivity(T, L_wire, rho, alpha, **kwargs):
"""
Temperature dependent resistivity model.
Args:
T: Temperature of wire (K)
L_wire: Length of wire (cm)
rho: Resistivity (Ohms*cm)
alpha: Reference resistance coefficient
**kwargs: Catch unused arguments
... | d6f1e44dde91e051ad92c38a7a4e2f19d635ee1d | 123,192 |
import re
def parse_time(time_string: str) -> int:
""" Parse a time stamp in h/m/s(default)/ms or any combination of these units.
Args:
time_string (str): timestamp, e.g., "0.23s", "5.234" (implied s), "1234 ms",
"1h 10m 12.345s", "00h00m00.000". Supported units: h, m, s (default), ms
... | 387ca46ad12faa404d446b6dd28583779638a024 | 327,853 |
import operator
def equals(column, name='id', function=(lambda x: x)):
"""Make filter template for filtering column values equal to value
transformed by given function.
:param column: database model
:param string name: name used in the filter template
:param callable function: function for transf... | da35503e46c306cbcef64d89566d526dc14bd46d | 607,477 |
def fitness_fn(turns, energy, isDead):
"""Fitness function that scores based on turns and energy.
Provides a score to a creature, with 3 times the amount of turns
plus the energy, with a bonus for surviving.
Args:
turns: number of turns a creature survived.
energy: amount of energy lef... | 823d1295bf64c46cf0e4bb2a7b24b55c2024282d | 67,935 |
def prompt_confirm(prompt: str) -> bool:
"""Prompt user for confirmation
Args:
prompt (str): question to user
Returns:
bool: confirmation
"""
return len(confirm := input(f"{prompt} [y/N]: ")) > 0 and confirm.lower()[0] == "y" | 23e3c08466fa8272d8d26a47954696241645b2c4 | 554,761 |
def quote_join(values):
"""Join a set of strings, presumed to be file paths, surrounded by quotes, for CMake"""
surrounded = []
for value in values:
surrounded.append('\"' + value + '\"')
return ' '.join(surrounded) | fa2a6ee278e7518fc12d7eb486d4668443b9b3d0 | 373,813 |
import csv
def read_graph_history(file_path):
"""
Load graph history from file.
Args:
file_path (str): File path contains the graph execution order info.
Returns:
set[int], the executed iteration ids of each graph.
"""
with open(file_path, 'r') as handler:
csv_reader ... | 03c5f90894e6677d6d6fc942a1b19b6f65ef0dc2 | 358,143 |
def chop(n, xs):
"""
Create a list of lists sized with n from list elements in xs.
"""
if len(xs) == 0:
return []
return [xs[:n]] + chop(n, xs[n:]) | 57b2a79aef38d1cf1bed3c7f2aac3d4eedf1d0ea | 540,134 |
def format_time(date):
"""Print UTCDateTime in YYYY-MM-DD HH:MM:SS format
Parameters
----------
date: UTCDateTime
"""
return date.datetime.strftime("%Y-%m-%d %H:%M:%S") | cebd0218110af67746e39dd954bb069067b889bf | 387,255 |
def get_entity_at_location(x, y, entities):
""" Return all entities at the given x, y coordinates.
Return -1 if there is no entity at these coordinates."""
results = []
for entity in entities:
if entity.x == x and entity.y == y:
results.append(entity)
if not results:
... | 24b7ce7e828f1db9c2365c48b694a84f688652e6 | 391,673 |
import inspect
def get_channelmethods(obj):
"""
Returns a sorted list of the names of all channelmethods defined for an object.
"""
channelmethods = list()
# getmembers() returns a list of tuples already sorted by name
for name, method in inspect.getmembers(obj, inspect.ismethod):
# To... | 2443434f3b4141272cbf6266cfec2da5c57d1e90 | 679,727 |
def naive(pattern: str, text: str):
"""Naive pattern matching."""
res = []
n = len(text)
for i in range(n):
for j, c in enumerate(pattern):
if i + j == n or text[i + j] != c:
break
else:
res.append(i)
return res | 30030778f32ae1b8b56f02df21b2e5b07761a277 | 508,623 |
def get_account_username_split(username):
"""
Accepts the username for an unlinked InstitutionAccount
and return a tuple containing the following:
0: Account Type (e.g. 'cas')
1: Institution Slug
2: User ID for the institution
"""
username_split = username.split("-")
if len(use... | 65a429b025e307b3a07b8f27303b7b16239b2b5a | 136,065 |
def get_Theta_gsRW_d_ave_d(K_gsRW_H, Theta_ex_d_Ave_d, Theta_ex_H_Ave, Theta_ex_a_Ave, Delta_Theta_gsRW_H):
"""日付dにおける地中熱交換器からの戻り熱源水の日平均温度(℃) (17)
Args:
K_gsRW_H(float): K_gsRW_H: 地中熱交換器からの戻り熱源水温度を求める式の係数(-)
Theta_ex_d_Ave_d(ndarray): 日付dにおける日平均外気温度 (℃)
Theta_ex_H_Ave(float): 暖房期における期間平均外気温度(... | 99363e26c67e5e7e56176bd630c5beac39b38811 | 169,439 |
def getParent(path, num=1):
"""
Find parent directory of a file or subdirectory
@param path: filepath or subdirectory from which to find a parent
@type path: string
@param num: how many subdirectories to traverse before returning parent
@type num: int
@return: path to parent directory
... | d031c52b9cb7bcad0ce5277b54e436ec8a7daa97 | 321,607 |
def digit(decimal, digit, input_base=10):
"""
Find the value of an integer at a specific digit when represented in a
particular base.
Args:
decimal(int): A number represented in base 10 (positive integer).
digit(int): The digit to find where zero is the first, lowest, digit.
bas... | c350b844130de86bd1cc5ce06c7c175ab8d4727b | 386,794 |
import json
def load_json(path):
"""Opens a json file and returns the content as a python dictonary.
Parameters:
path(str): Path of json file
"""
if not path.lower().endswith('.json'):
raise ValueError("Wrong file format!")
with open(path) as f:
return json.load(f) | 3c9167a9816e1ad8cc1cab1d20baae2f012aea7b | 362,071 |
def div0(num, denom):
"""Divide operation that deals with a 0 value denominator.
num: numerator.
denom: denominator.
Returns 0.0 if the denominator is 0, otherwise returns a float."""
return 0.0 if denom == 0 else float(num) / denom | 49f62d40c5bd90459b8304249e69ae4c2d9523d9 | 315,623 |
def _length(stream):
"""Returns the size of the given file stream."""
original_offset = stream.tell()
stream.seek(0, 2) # go to the end of the stream
size = stream.tell()
stream.seek(original_offset)
return size | 8520dee110a8fbab37f9c296c6d73bda1c167f2b | 60,915 |
import torch
def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:
"""
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if... | c871c1e95e9b6918d14bf2c5d3dd8641cfeef645 | 311,994 |
import math
def temporary_magnitude_quantity_reverse(C, J, n):
"""
Returns the temporary magnitude quantity :math:`t`. for reverse *CIECAM02*
implementation.
Parameters
----------
C : numeric
*Chroma* correlate :math:`C`.
J : numeric
*Lightness* correlate :math:`J`.
n ... | c83034b95580dedd2dd39e62f89eea7185125c12 | 580,270 |
def Dup(x, **unused_kwargs):
"""Duplicates (copies) an element."""
return (x, x) | c068c7b4144e6e4f25ec6eb07a02d76ec2e80862 | 494,505 |
def transforms_are_applied(obj):
""" Check that the object is at 0,0,0 and has scale 1,1,1 """
if (
obj.location.x != 0 or
obj.location.y != 0 or
obj.location.z != 0
):
return False
if (
obj.rotation_euler.x != 0 or
obj.rotation_euler.y != 0 or
obj.rotation_euler.z != 0
):
retu... | 411a5c0211c6a0b6833352e8566814958a8adaab | 679,064 |
def longest_common_substring(s1, s2):
"""
returns the longest common substring of two strings
:param s1: a string
:type s1: str
:param s2: a second string
:type s2: str
>>> longest_common_substring('hello world how is foo bar?', 'hello daniel how is foo in the world?')
' how is foo '
... | 2378ef6e620f997f3140c4a941a7e4955b355b66 | 564,065 |
def decode(encoded_digits: list[str], mapping: dict) -> int:
"""decode a number.
Use the mapping to decode the encoded digits and combine them to a number.
Args:
encoded_digits (list[str]): encoded digits
mapping (dict): mapping that decodes each segment
Returns:
(int) decoded... | be4cbd2fbc8be31b1126676a3a115b345b598c8a | 16,984 |
def readf(fname):
"""Utility function to read a file."""
with open(fname, 'r') as f:
return f.read() | 924ec495f31303a3101f7a09bd651db927de8a9b | 225,810 |
from typing import Any
def function_sig_key(
name: str,
arguments_matter: bool,
skip_ignore_cache: bool,
*args: Any,
**kwargs: Any,
) -> int:
"""Return a unique int identifying a function's call signature
If arguments_matter is True then the function signature depends ... | bfec647db5d819fb87cf3a227927acd5cd6dda10 | 699,267 |
def parseLogfileToInstanceid(fname):
"""Parse a file name and return the integer instance id for the service."""
if not fname.endswith(".log.txt") or "-" not in fname:
return
try:
return int(fname[:-8].split("-")[-1])
except ValueError:
return | 528784ebe3dfebcafb33c30ccdbd771757ced1db | 426,964 |
def make_exposure_shares(exposure_levels, geography="geo_nm", variable="rank"):
"""Aggregate shares of activity at different levels of exposure
Args:
exposure_levels (df): employment by lad and sector and exposure ranking
geography (str): geography to aggregate over
variable (str): varia... | 02d990f2b08e3acb2a2b8ac01e44848770bdea71 | 3,734 |
def str_date(date):
"""
convert the datetime.date into string
:param date: <class 'datetime.date'>, 2016-06-10 02:03:46.788409+10:00
:return 20160603
"""
d = str(date).split('-')
string_date = ""
for i in range(len(d)):
string_date += d[i]
return string_date | c15850bbd9215a7fb35de75f954013794d2b05ad | 495,498 |
def split_words_by_underscore(function_name):
"""
get_my_bag -> ['get', 'my', 'bag']
"""
return [word for word in function_name.split('_')] | 64145aeec269a6a4c3994bc3deb0cf8a460f19df | 507,398 |
import re
def get_text_refs(url):
"""Return the parsed out text reference dict from an URL."""
text_refs = {'URL': url}
match = re.match(r'https://www.ncbi.nlm.nih.gov/pubmed/(\d+)', url)
if match:
text_refs['PMID'] = match.groups()[0]
match = re.match(r'https://www.ncbi.nlm.nih.gov/pmc/ar... | f24cdec70775d10e707aa8ae693dfe5a977fee93 | 82,013 |
def sort_freq(freqdict):
"""
sort_freq reads word:frequency key:val pairs from dict, and returns a list sorted from
highest to lowest frequency word
:param freqdict:
:return: list named aux
"""
aux: list = []
for k, v in freqdict.items():
aux.append((v, k))
aux.sort(reverse=T... | 287a06ceabfc946f822d0465d8b33eda044f22f4 | 153,659 |
from typing import Sequence
from typing import Tuple
import math
def quaternion_to_euler(quat: Sequence[float]) -> Tuple[float,float,float]:
"""
Convert WXYZ quaternion to XYZ euler angles, using the same method as MikuMikuDance.
Massive thanks and credit to "Isometric" for helping me discover the transformation m... | 6bbce0b502f42e63b181ea65b6fff66d7294210b | 687,404 |
def create_tree_from_list(dict_list, i):
"""creates binary tree
Node of tree is element of dict_list at index i.
Right child is element of list with index 2i + 2.
Left child is element of list with index 2i + 1.
Args:
dict_list (list): list of dictionaries
i (integer): index (i < le... | 1f32503814781c0713507b61a5852e793843094c | 138,854 |
def find_group_single_candidate(square: tuple, squares: list, grid: list) -> list:
"""
Checks for a single option a square can have based on no other square in a group having it as an option
:param square: A tuple (row, column) coordinate of the square
:param squares: A list of squares (tuples) to chec... | 1983720f4540b0bd964a2ba535455ca0510ef369 | 72,890 |
def osr_proj(input_osr):
"""Return the projection WKT of a spatial reference object
Args:
input_osr (:class:`osr.SpatialReference`): the input OSR
spatial reference
Returns:
WKT: :class:`osr.SpatialReference` in WKT format
"""
return input_osr.ExportToWkt() | fb4b9bdb33f724d9c414ce7969ac516db1e91a85 | 618,004 |
from typing import Callable
from typing import Any
import time
def set_timeout(function: Callable[[], Any], second: int) -> Any:
"""Runs a given function after a given number of seconds."""
time.sleep(second)
return function() | 95a0d4db16354774541f93e65bce3987b2a65029 | 455,762 |
import ipaddress
def broadcast(addr):
"""Return the broadcast address of the current network
"""
ip = ipaddress.ip_interface(addr)
return f"{ip.network.broadcast_address}/{ip.network.prefixlen}" | 3d757804e7f98c0dda56730ec76f120631e5106b | 449,496 |
def get_reservation_ports(session, reservation_id, model_name='Generic Traffic Generator Port'):
""" Get all Generic Traffic Generator Port in reservation.
:return: list of all Generic Traffic Generator Port resource objects in reservation
"""
reservation_ports = []
reservation = session.GetReserva... | 650f4962e327ab7dd1eeaa054743b5f096a9d3f2 | 477,815 |
import asyncio
def run(coro, forever=False):
"""Convenience function that makes an event loop and runs the async
function within it.
Args:
forever: If True then run the event loop forever, otherwise
return on completion of the coro
"""
loop = asyncio.get_event_loop()
t = N... | 6bdb898f7f79b3d9eb591dc62826ead02e2b3cbe | 425,771 |
def validate_list_deceased(gedcom):
"""
US29: List all deceased individuals in a GEDCOM file
"""
deceased = []
for individual in gedcom.individuals:
if individual.alive is False:
deceased.append(f'Deceased: US29: ({individual.id}) {individual.name} [DeathDate: {individual.d... | b8c475475226e59c03986c4634374be1627266f4 | 487,339 |
def dict_lookup(d, key):
"""
Return dictionary value for given key
"""
return d[key] | 9c703b88b57f641c57054e1fc692fa5695dc32b3 | 536,300 |
import torch
def vector_to_parameter_list(vec, parameters):
"""
Convert the vector `vec` to a parameter-list format matching `parameters`.
This function is the inverse of `parameters_to_vector` from the
pytorch module `torch.nn.utils.convert_parameters`.
Contrary to `vector_to_parameters`, which ... | 9c7e4f4a3768e4b715026a6b0610da856653e714 | 555,823 |
def categoria_escolhida(categorias):
"""
Função que retorna a categoria escolhida pelo usuário
:param categorias: lista com todas as categorias possíveis
:return: retorna a escolha do usuário
"""
while True:
print("Qual tipo de categoria deseja jogar? ")
for i in range(len(catego... | 2b04554f92ed39aed005398d0cf78383923310cd | 315,552 |
def is_dev_only(dockerfile_path=str) -> bool:
"""
Check the build.conf for "devonly" flag.
Args:
dockerfile_path (str): the dockerfile's path
Returns:
"""
path = f"{dockerfile_path}/build.conf"
try:
with open(path) as f:
content = f.read()
if "devonl... | d51668751d9577cd64a52fb85267cf4d18d3ef63 | 606,117 |
def starts_with(left: str, right: str) -> str:
"""Check if the `left` string starts with the `right` substring."""
return left + ' STARTS WITH ' + right | 393ed46680d13130eee846e2a7c656f3f989425b | 127,682 |
def adda(a, b, c=0, d=0, e=0):
"""Add number b to number a. Optionally also add
any of numbers c, d, e to the result.
"""
print(f"Function `adda` called with arguments a={a} b={b}", end="")
if c: print(f" c={c}", end="")
if d: print(f" d={d}", end="")
if e: print(f" e={e}", end="")
prin... | 50a1a923f2dd046114bf92caffe9ba770d062f43 | 27,249 |
def final_well(sample_number):
"""Determines well containing the final sample from sample number.
"""
letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
final_well_column = sample_number // 8 + \
(1 if sample_number % 8 > 0 else 0)
final_well_row = letter[sample_number - (final_well_colu... | e48f0cc13c7dd30851f22fe3f32b4bbd9b71a0ed | 194,378 |
def convert_temp(unit_in, unit_out, temp):
"""Convert farenheit <-> celsius and return results.
- unit_in: either "f" or "c"
- unit_out: either "f" or "c"
- temp: temperature (in f or c, depending on unit_in)
Return results of conversion, if any.
If unit_in or unit_out are invalid, return "I... | 59202152a54dbc33ecb35bb034af85ab3a897a18 | 241,669 |
def get_img_extension(path: str) -> str:
"""
Parse the path and return the image's extension (replacing jpg to jpeg with accordance with EPUB spec)
"""
path_list = path.rsplit(".", 1)
if len(path_list) == 2:
ext = path_list[1]
else:
ext = "jpeg"
if ext == "jpg":
ext =... | 50f6f72885c5ad9a3e12663af18282c1ca78fe3d | 209,488 |
import pickle
def load_clifford_table(picklefile='cliffords2.pickle'):
"""
Load pickled files of the tables of 1 and 2 qubit Clifford tables.
Args:
picklefile - pickle file name.
Returns:
A table of 1 and 2 qubit Clifford gates.
"""
with open(picklefile, "rb") as ... | 25382d151456b926a317e3c820d29d650e28e31c | 657,816 |
def ens_to_indx(ens_num, max_start=1000000):
"""
Get the index related to the ensemble number : e.g 101 => 0
:param ens_num: ensemble number, int
:param max_start: max number of ensembles, int
:return: index, int
"""
start = 100
while start < max_start:
ind = ens_num % start
... | a0af56431df994d1c01207aa2c8a9cf9fd76e258 | 622,185 |
import re
def FillForm(string_for_substitution, dictionary_of_vars):
"""
This function substitutes all matches of the command string //%% ... %%//
with the variable represented by ... .
"""
return_string = string_for_substitution
for i in re.findall("//%%(.*)%%//", string_for_substitution):
return_st... | 192a502cfff97d58aeaa8c2201c588acc916616c | 384,000 |
def get_class_name_no_json(i, soup):
"""Gets the name of a class for courses that do not use a JSON timetable
As of 2018-11-13 it\'s saved as the content of an <h3> tag with id equal to tab{index}"""
return soup.find("h3", id="tab{}".format(i)).find("a").contents[2].lstrip().rstrip() | 542ac6cf620aca3067150ab776778581e9de0326 | 255,749 |
def latex_float(f, fmt='{:.1e}', phantom=False):
"""Convert float to LaTex number with exponent.
Parameters
----------
f : float,int,double
fmt : str
Python format string. Default: '{:.1e}'
phantom : bool
Add phantom zeros to pad the number if it does not fill the format string.... | b075035786d0e5468a15f34379817b85636f2bf8 | 614,403 |
def one(iterable):
"""Return the single element in iterable.
Raise an error if there isn't exactly one element.
"""
item = None
iterator = iter(iterable)
try:
item = next(iterator)
except StopIteration:
raise ValueError('Iterable is empty, must contain one item')
try:
next(iterator)
except StopIteration... | 49cbb2e829bccaeb3ba5337b00c8bb19c2842b02 | 629,750 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.