content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import ast
def is_name_in_ptree(name, ptree):
"""
Return True if an ast.Name node with the given name as its id
appears anywhere in the ptree, False otherwise
"""
if not ptree:
return False
for node in ast.walk(ptree):
if isinstance(node, ast.Name) and (node.id == name):
return True
return False
|
c2d6d0001c3baf14c110ff351c8a1c5e97b256d8
| 690,251 |
def update_letter_view(puzzle: str, view: str, position: int, guess: str) -> str:
"""Return the updated view based on whether the guess matches position in puzzle
>>> update_letter_view('apple', 'a^^le', 2, 'p')
p
>>> update_letter_view('banana', 'ba^a^a', 0, 'b')
b
>>> update_letter_view('bitter', '^itter', 0, 'c')
^
"""
if guess == puzzle[position]:
return puzzle[position]
return view[position]
|
b7c534acdbc57c04e1f7ee6a83fc94ff2734948a
| 698,438 |
def remove_unnecessary(string):
"""Removes unnecessary symbols from a string and returns the string."""
string = string.replace('@?', '')
string = string.replace('?@', '')
return string
|
56965ef4b60d302e659bafd4874b8c72790c5ec3
| 59,827 |
import json
def load_json(filename):
"""
json loader to load Nematus vocabularies
Note that we use unicode representations (not str)
:param filename:
:return:
"""
with open(filename, mode='rb') as f:
return json.load(f)
|
6df9c234c37a7ed01cf00d24ed49578bc447e38e
| 599,445 |
def _compute_error(node, x, y=None):
"""Error between target and prediction."""
prediction = node.state()
error = prediction - y
return error, x.T
|
2d675073cf994864f8557fd3e401c1e543755e9c
| 163,307 |
from typing import Callable
from typing import Any
from typing import Iterable
from typing import Tuple
from typing import List
def group_by_pred(
pred: Callable[[Any], bool], iterable: Iterable[Any]
) -> Tuple[List[Any], List[Any]]:
"""Splits items in a sequence into two lists, one containing
items matching the predicate, and another containing those that
do not."""
is_true = [] # type: List[Any]
is_false = [] # type: List[Any]
for item in iterable:
if pred(item):
is_true.append(item)
else:
is_false.append(item)
return is_true, is_false
|
07af56c4e40bbef2055b2675353be14e04f991aa
| 289,629 |
def new_line(string: str):
"""
Append a new line at the end of the string
Args:
string: String to make a new line on
Returns: Same string with a new line character
"""
return string + "\n"
|
f4deeaa94a6980f95a3020fa54570fbe1f0a6e9e
| 701,112 |
import typing
import yaml
def get_targets(filename: str) -> typing.List[str]:
"""Load the configuration file.
The configuration file is expected to be a YAML file listing
the target urls as a list.
For more information, refer to the README.md or the example configuration.
"""
with open(filename) as config:
targets = yaml.safe_load(config)
return targets
|
66cc4be3d17040562e321bf5e3fb7e564aa77335
| 420,156 |
from typing import Tuple
import math
def euler_to_quaternion(roll: float = 0, pitch: float = 0, yaw: float = 0) -> Tuple[float, float, float, float]:
"""
Convert Euler to Quaternion
Args:
roll (float): roll angle in radian (x-axis)
pitch (float): pitch angle in radian (y-axis)
yaw (float): yaw angle in radian (z-axis)
Returns:
Tuple[float, float, float, float]: x, y, z, w
"""
# Abbreviations for the various angular functions
cy = math.cos(yaw * 0.5)
sy = math.sin(yaw * 0.5)
cp = math.cos(pitch * 0.5)
sp = math.sin(pitch * 0.5)
cr = math.cos(roll * 0.5)
sr = math.sin(roll * 0.5)
# Quaternion
w = cr * cp * cy + sr * sp * sy
x = sr * cp * cy - cr * sp * sy
y = cr * sp * cy + sr * cp * sy
z = cr * cp * sy - sr * sp * cy
return x, y, z, w
|
e8346172f07510c377e14827842eb18f1631402e
| 707,128 |
def get_network(network_arg, task_idx):
""" Get network file from list of arguments.
Parameters
----------
network_arg: list of space-separated network filenames
as parsed by argparse (--networks)
task_idx: int
index of the task/network
Returns
------
Path to the network for task task_idx.
"""
if (task_idx == 0 or len(network_arg) == 1):
return network_arg[0]
else:
return network_arg[task_idx]
|
eac76c0c70e5dec1dccf8e3c3adea8a199997c10
| 113,661 |
def single_line(value):
"""Returns the given string joined to a single line and trimmed."""
return " ".join(filter(None, map(str.strip, value.splitlines())))
|
2f51425a02f64d9b64be74ad8b78ecaba8d6b300
| 206,907 |
from typing import List
from typing import Set
def _extract_target_labels(targets_in_order: List[dict], target_name: str) -> Set[str]:
"""Collect a set of all the board names from the inherits field in each target in the hierarchy.
Args:
targets_in_order: list of targets in order of inheritance, starting with the target up to its highest ancestor
target_name: the name of the target to find the labels for
Returns:
A set of names of boards that make up the inheritance tree for the target
"""
labels = {target_name}
for target in targets_in_order:
for parent in target.get("inherits", []):
labels.add(parent)
return labels
|
f47dcd90427efd70b0ac965ea017852db68381e4
| 674,322 |
import hashlib
def convert_to_SHA256(x):
"""Convert a given string to SHA256-encoded string.
:param x: arbitrary string.
:type x: str
:return: SHA256 encoded string
:rtype: str
"""
result = hashlib.sha256(x.encode())
result = result.hexdigest()
return result
|
b199155459a7d36b9614678190d72aff167da13c
| 272,896 |
def get_index_groups(time_list):
"""Get index groups corresponding to the different time interval
tvals. An index group is a pair consisting of a time interval
time value and a list of indices corresponding to that time value. A
dictionary will map the time interval tvals to their corresponding
index lists.
Inputs:
time_list -- list of triples (tval, time_interval_time_val, ind)
Returns:
dictionary mapping time_interval_time_val to its index list
"""
index_groups = {}
for (tval, time_interval_time_val, ind) in time_list:
if time_interval_time_val in index_groups:
index_groups[time_interval_time_val].append(ind)
else:
index_groups[time_interval_time_val] = [ind]
return index_groups
|
bc38858d28e25b45ed4ee6753a88638a847a810b
| 248,345 |
def latex_float(f, precision=0.2, delimiter=r'\times'):
""" Convert a float value into a pretty printable latex format
makes 1.3123e-11 transformed into $1.31 x 10 ^ {-11}$
Parameters
----------
f: float
value to convert
precision: float, optional (default: 0.2)
the precision will be used as the formatting: {precision}g
default=0.2g
delimiter: str, optional (default=r'\times')
delimiter between the value and the exponent part
"""
float_str = ("{0:" + str(precision) + "g}").format(f)
if "e" in float_str:
base, exponent = float_str.split("e")
return (r"{0}" + delimiter + "10^{{{1}}}").format(base, int(exponent))
else:
return float_str
|
b3d31afcfbf8a564d85f5f5b099b0d63bc8d89f8
| 77,753 |
def celsius_to_fahrenheit(temp):
"""
Convert degrees Celsius to degrees Fahrenheit
:param float temp: The temperature in Celsius
:return: The temperature in Fahrenheit
:rtype: float
"""
return (temp * 1.8) + 32.0
|
ebb420e14c0b01b8ed91cd603b2e3bf34388f917
| 563,487 |
def FormatResources(resources):
"""Formats a list of resources for printing.
Args:
resources: a list of resources, given as (type, name) tuples.
"""
return '\n'.join(['%-12s %s' % (t, n) for t, n in sorted(resources)])
|
f88604a186115a7333de02d6c0ad31315ea22f12
| 486,397 |
def binary_search(input_array, value):
""" Algorithm: Here is how it could be done:
1. Get middle index of array with range (0...array-size)
2. Compare value of mid-element at that index with given value
2.1 If (value == mid-element)
then return the middle index [DONE]
2.2 Else If (value < mid-element)
then repeat step 1 with range (0...mid-element-index)
2.3 Else If (value > mid-element)
then repeat step 2 with range (mid-element-index + 1, size)
3. Since iteration completed without finding the elements, return -1"""
""" Step 1"""
start = 0
end = len(input_array)
""" Step 2"""
while end > start:
mid_index = (start + end) / 2
mid_value = input_array[mid_index]
if value == mid_value:
return mid_index
elif value < mid_value:
end = mid_index
else:
start = mid_index + 1
""" Step 3"""
return -1
|
6723316e9460efb5ce41ad8e94152deb13af0d94
| 192,086 |
def format_iter(body: list) -> str:
"""
Formats an iterable into a multi-line bulleted string of its values.
"""
return "\n".join(sorted([f" - {getattr(v, 'value', v)}" for v in body]))
|
0f55b06276c45ef652e89df3dfd24d1fe9a4e844
| 11,724 |
def classify_list_f(a_list, *filters):
"""Classfy a list like object. Multiple filters in one loop.
- collection: list like object
- filters: the filter functions to return True/False
Return multiple filter results.
Example:
data = [1, 2, 3]
m1 = lambda x: x > 1
m2 = lambda x: x > 2
classify(data, m1, m2) -> [2, 3], [3]
"""
results = tuple([] for i in range(len(filters)))
for item in a_list:
for filter_func, result in zip(filters, results):
if filter_func(item):
result.append(item)
return results
|
4bafa7a6b714387cfa2a6c896eece909e4171cdf
| 288,981 |
def _convert_from_F(temp: float) -> float:
"""
Convert F temp to C
param temp: temp in F to convert
return: float
"""
return round((temp - 32) * 5/9, 1)
|
0bff2139405161193b6212ab46ddf34d8ef984f2
| 255,295 |
def detector_substr(detector):
"""
change detector string to match file format
(e.g., "SCA01" -> "SCA_1")
"""
return f"{detector[:3]}_{str(int((detector[3:])))}"
|
878a75146b5bf03d020acfa2b6363c166a3b0e4d
| 93,165 |
def get_neighbours_from_grid(row, column, grid):
"""Get from the grid neighbours of square on given row and column."""
coordinates = []
if row > 0:
coordinates.append(('up', row - 1, column))
if row + 1 < len(grid):
coordinates.append(('down', row + 1, column))
if column > 0:
coordinates.append(('left', row, column - 1))
if column + 1 < len(grid):
coordinates.append(('right', row, column + 1))
return [
(neighbour, grid[square_row][square_col])
for neighbour, square_row, square_col in coordinates
]
|
b6df05d66d26af30de9f0ac7c2544bd8f5e9643f
| 365,638 |
from typing import Dict
from typing import Any
async def provider() -> Dict[str, Any]:
"""Define a basic example data provider function."""
return {
"title": "Example",
"link": "https://example.com",
"description": "An example rsserpent plugin.",
"items": [{"title": "Example Title", "description": "Example Description"}],
}
|
e952f40d360bf31e4a8710c3b5d531c1467ef660
| 422,373 |
def get_sequence_name(image_file):
"""Returns a sequence name like '20180227_185324'."""
return image_file.split('/')[-3]
|
8456faf80320f2f4fe85413c537edf79ec6d5afa
| 357,289 |
from bs4 import BeautifulSoup
import re
def get_links(html_page, base_url):
"""gets all links from html
Parameters
------
html_page (str): document html
base_url (str): the original URL supplied
Returns
------
list: list of all the links in the html document
these could be files or sub-directories
"""
# "lxml" supposed to be faster than "html.parser
soup = BeautifulSoup(html_page, "html.parser")
regex = ".|(/$)"
links = [f"{link.get('href')}"
for link
in soup.findAll('a', attrs={'href': re.compile(regex)})]
return links
|
f2e97ce2934e994787f3ef79d43558f3380c6722
| 665,409 |
import errno
def is_eintr(exc):
"""Returns True if an exception is an EINTR, False otherwise."""
if hasattr(exc, 'errno'):
return exc.errno == errno.EINTR
elif getattr(exc, 'args', None) and hasattr(exc, 'message'):
return exc.args[0] == errno.EINTR
return False
|
b6a7c280f87757492f3a4c1ee166577691ef8622
| 123,313 |
import collections
def build_dicts(reviewText):
"""
Build dictionaries mapping words to unique integer values.
"""
counts = collections.Counter(reviewText).most_common()
dictionary = {}
for word, _ in counts:
dictionary[word] = len(dictionary)
return dictionary
|
5a20752a044d63f1be433494c4c2ca83953bbe67
| 119,082 |
def simplify_person_name( name ):
"""
Simpify a name to a last name only. Titles such as Ph. D. will be removed first.
Arguments:
name -- The name to shorten
"""
if name is not None:
new_name = name.replace("Ph.D.", "").replace("Ph. D.", "").replace("M.A.", "").replace("LL.D.", "").replace("A.M.", "").replace("Esq.", "").replace(",", "").strip()
return new_name.split(" ")[-1]
else:
return name
|
c8e26c84f4c8e2ef0107ed14a13980259b1b306b
| 208,868 |
import re
import json
def get_interfaces_counters(module):
"""
@summary: Parse output of "show interfaces counters" command and convert it to the dictionary.
@param module: The AnsibleModule object
@return: Return dictionary of parsed counters
"""
cli_cmd = "portstat -j"
rc, stdout, stderr = module.run_command(cli_cmd)
if rc != 0:
module.fail_json(msg="Failed to run {}, rc={}, stdout={}, stderr={}".format(cli_cmd, rc, stdout, stderr))
match = re.search("Last cached time was.*\n", stdout)
if match:
stdout = re.sub("Last cached time was.*\n", "", stdout)
try:
return json.loads(stdout)
except Exception as e:
module.fail_json(msg="Failed to parse output of '{}', err={}".format(cli_cmd, str(e)))
|
5f68b977c2a934a84e37d059349f60261e151055
| 443,116 |
def wow_gen(length: int):
"""Generates a wow at a given length"""
if (length <= 1984 and length >= 0):
wow_thing = "***__~~w"
for _ in range(length):
wow_thing += "o"
wow_thing += "w~~__***"
return wow_thing
elif (length >= -1984 and length < 0):
new_length = -length
wow_thing = "***__~~ʍ"
for _ in range(new_length):
wow_thing += "o"
wow_thing += "ʍ~~__***"
return wow_thing
else:
return "Sorry bud, but your wow is too much for me to handle.\n" \
"Here's a doge for now: https://upload.wikimedia.org/wikipedia/en/5/5f/Original_Doge_meme.jpg **_: (_**"
|
8057befdc1f5513340e659c3bcd92bd86c13875f
| 525,529 |
from typing import Any
import gc
def _object_for_id(id_: int) -> Any:
""" Return an object, given its id. """
# Do a complete garbage collect, to avoid false positives in case the
# object was still in use recently. In the context of AppSingleLaunch,
# this would happen if an app was closed, then launched again immediately.
gc.collect()
for obj in gc.get_objects():
if id(obj) == id_:
return obj
return None
|
6a334eb9dd7cffbc95fd4671fe9883bd4238d064
| 143,003 |
def get_file_name(conanfile, find_module_mode=False):
"""Get the name of the file for the find_package(XXX)"""
# This is used by the CMakeToolchain to adjust the XXX_DIR variables and the CMakeDeps. Both
# to know the file name that will have the XXX-config.cmake files.
if find_module_mode:
ret = conanfile.cpp_info.get_property("cmake_module_file_name")
if ret:
return ret
ret = conanfile.cpp_info.get_property("cmake_file_name")
return ret or conanfile.ref.name
|
db8afd149df6efd8dc01c120ab85d77ca229d3e8
| 480,555 |
def default_inverse_transform_targets(current_state, delta):
"""
This is the default inverse transform targets function used, which reverses the preprocessing of the targets of
the dynamics function to obtain the real current_state not the relative one,
The default one is (current_state = target + current_state).
Parameters
---------
current_state: tf.float32
The current_state has a shape of (Batch X dim_S)
delta: tf.float32
The delta has a shape of (Batch X dim_S) which is equivilant to the target of the network.
"""
return delta + current_state
|
9d7031dded17a69e195017384b5bdc71751aeb27
| 475,991 |
def confirmable_div(confirm_field_id: str | None, prefix: str = 'form-group-') -> str:
"""Return an opening div tag linking this error div to a confirm field.
See `confirmable-error.ts`.
"""
attrs = ['', 'data-role="confirmable-error"',
f'data-confirmed-by-checkbox-id="{confirm_field_id}"'] \
if confirm_field_id else []
return f"<div{' '.join(attrs)}>"
|
f6c773bb04bed63d387c61616ff437be727244f9
| 503,233 |
def fixup_setup(setup):
"""Fill in any missing pieces from setup."""
if not hasattr(setup, 'PY_NAME'):
setup.PY_NAME = setup.NAME
if not hasattr(setup, 'PY_SRC'):
setup.PY_SRC = '%s.py' % setup.PY_NAME
if not hasattr(setup, 'DEB_NAME'):
setup.DEB_NAME = setup.NAME
if not hasattr(setup, 'AUTHOR_NAME'):
setup.AUTHOR_NAME = setup.SETUP['author']
if not hasattr(setup, 'GOOGLE_CODE_EMAIL'):
setup.GOOGLE_CODE_EMAIL = setup.SETUP['author_email']
return setup
|
de49f99d09f6c683392ea2f006970bfe48ad01da
| 234,364 |
import string
import torch
def translate(sentence, inp_word2id, trg_word2id, trg_id2word, encoder, decoder, trg_max_len, device='cpu'):
"""
Generate translation for input sentence.
Inputs:
- sentence: a sentence in string format
- inp_word2id: word2id from input training set
- trg_word2id: word2id from target training set
- trg_id2word: id2word from target training set
- encoder, decoder: Encoder, Decoder models
- trg_max_len: max length for target sentence
- device: 'cpu' or 'cuda'
Return a sentence
"""
exclude = list(string.punctuation) + list(string.digits)
sentence = '<START> ' + ''.join([char for char in sentence if char not in exclude]).strip().lower() + ' <END>'
sen_matrix = [inp_word2id[s] for s in sentence.split()]
sen_tensor = torch.Tensor(sen_matrix).to(device=device, dtype=torch.long).unsqueeze(0)
encoder.eval()
decoder.eval()
with torch.no_grad():
enc_out, enc_hidden = encoder(sen_tensor)
dec_hidden = enc_hidden
dec_input = torch.Tensor([trg_word2id['<START>']]).to(device='cuda', dtype=torch.long)
output_list = []
for t in range(1, trg_max_len):
out, dec_hidden = decoder(dec_input, dec_hidden, enc_out)
dec_input = torch.max(out, dim=-1)[1].squeeze(1)
next_id = dec_input.squeeze().clone().cpu().numpy()
next_word = trg_id2word[next_id]
if next_word == '<END>':
break
output_list.append(next_word)
return ' '.join(output_list)
|
7c66d1ce73600443da2326c1c61b337cb6388d32
| 511,872 |
def make_valid_mapping(package_leaflets):
"""
Make sure to have valid mappings from NER (input) to section_content (output)
In case either input or output - None or empty, make sure the corresponding pair is None
:param package_leaflets: list, collection of package leaflets
:return: package_leaflets with valid mappings
"""
for leaflet in package_leaflets:
current_leaflet_sections = [leaflet.section1, leaflet.section2,
leaflet.section3, leaflet.section4,
leaflet.section5, leaflet.section6]
for section_index, current_section in enumerate(current_leaflet_sections):
# if section_content is None, make sure entity_recognition is None too (can not map NER --> None)
if current_section.section_content is None:
current_section.entity_recognition = None
continue
# if entity_recognition is None, make sure section_content is None too (can not map from None --> text)
if current_section.entity_recognition is None:
current_section.section_content = None
continue
# set empty section_content to None, make sure entity_recognition is None too (can not map NER --> None)
if len(current_section.section_content) == 0:
current_section.section_content = None
current_section.entity_recognition = None
continue
# set empty NER outputs to None, make sure section_content is None too (can not map from None --> text)
if len(current_section.entity_recognition) == 0:
current_section.entity_recognition = None
current_section.section_content = None
continue
return package_leaflets
|
fee328e4d207cf0a4510f190ac47b9f7fa6736b0
| 425,946 |
def nextIter(it, default=None):
"""
Returns the next element of the iterator,
returning the default value if it's empty,
rather than throwing an error.
"""
try:
return next(iter(it))
except StopIteration:
return default
|
f7be7cf6fdf6cd77459453858f20121207220ec9
| 534,219 |
def plurality(l):
"""
Take the most common label from all labels with the same rev_id.
"""
s = l.groupby(l.index).apply(lambda x:x.value_counts().index[0])
s.name = 'y'
return s
|
4e363648e79b5e9049aca2de56fd343c1efe1b93
| 8,513 |
def unique_append(old_list, new_list):
"""
Add items from new_list to end of old_list if those items are not
already in old list -- returned list will have unique entries.
Preserve order (which is why we can't do this quicker with dicts).
"""
combined = old_list
for item in new_list:
if item not in combined:
combined.append(item)
return combined
|
96ecc3350300ef0b6ed3ff54b370fbc9189ec96f
| 532,965 |
def fuel_burn_by_ll_rule(mod, prj, tmp, s):
"""
If no fuel_burn_by_ll_rule is specified in an operational type module, the
default fuel burn needs to be greater than or equal to 0.
"""
return 0
|
7e5e2861b7d5114060b66a6c988896e476063da2
| 478,799 |
def get_packagetype(name: str) -> str:
"""Get package type out of a filename"""
if name.endswith(".tar.gz"):
return "sdist"
elif name.endswith(".egg"):
return "bdist_egg"
elif name.endswith(".whl"):
return "bdist_wheel"
else:
return ""
|
34ad89c3c118ee7da1a07396da0dd39a63ea7a8b
| 385,152 |
def binary_search(arr, val):
"""Takes in a sorted list and a value. Preforms the Binary Search algorythem to see if the value is in the lsit."""
# Set the values to the end of the list
left,right = 0,len(arr)
while not right <= left:
mid = (right + left) // 2
if val > arr[mid]:
left = mid+1
elif val < arr[mid]:
right = mid
else:
return mid
return -1
|
49e25dd5ba4e9e92d6b1225141efa74f48ee19b1
| 95,118 |
def percent_diff(value1: float, value2: float, frac: bool = False) -> float:
""" Return the percentage difference between two values. The denominator
is the average of value1 and value2.
value1: float, first value
value2: float, second value
frac: bool, Default is False. Set to True returns a fraction
instead of percentages. This is useful for performing
calculations on spreadsheets.
return: float, absolute value of the difference in percentages
Usage
-----
>>> percent_diff(5, 7)
33.33333333333333
>>> percent_diff(5, 7, frac=True)
0.3333333333333333
"""
assert value1 >= 0 and value2 >= 0, 'Values must not be negative'
perdiff = abs(value1 - value2)/((value1 + value2)/2.0)
if frac is False:
perdiff *= 100
return perdiff
|
cffe298fb4218adc60bf75ff659090c41ae86922
| 37,999 |
def getdifflist(inputlist):
"""returns a list of length-1 relative to the input list
list values are the differential of the inputlist [n+1]-[n]"""
difflist=[inputlist[i+1]-inputlist[i]
for i in range(len(inputlist)-1)]
return difflist
|
145f11f1f6af87a222f91a2b2cd2ee4c6a039df7
| 604,190 |
def _modname_to_cliname(parser_mod_name):
"""Return module's cli name (underscores converted to dashes)"""
return parser_mod_name.replace('_', '-')
|
a8dea162a38744c4eeb13f68acdf88a03338c3ef
| 384,162 |
def calc4travel(fuelprice: float, averagecons: float, km: float) -> float:
"""
Função para calcular o valor gasto em combustivel para uma viagem de X Km (ida e volta).
fuelprice: representa o preço do combustivel;
averagecons: consumo médio do veiculo;
km: distância em km.
Retorna o valor em reais da quantia aproximada que será gasta
em combustivel.
"""
return (km/averagecons*fuelprice)*2
|
c1a7f0e7c6d669463ec40e290a7bc60036df9fbf
| 488,672 |
import yaml
def safe_dump(data, stream=None, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
"""
return yaml.safe_dump(data, stream, **kwds)
|
02e8cba070e19842fc669d20a83837b9c5ff19b6
| 255,519 |
import math
def get_3rd_side(a, b):
"""
Returns hypotenuse of a right-angled triangle, given its other sides
"""
# return np.sqrt(np.sum(np.square(mags)))
return math.sqrt(a**2 + b**2)
|
5f5f6606e3a18f567bef157b43fe54771ffe90f4
| 206,719 |
def calc_3d_bbox(xs, ys, zs):
"""Calculates 3D bounding box of the given set of 3D points.
:param xs: 1D ndarray with x-coordinates of 3D points.
:param ys: 1D ndarray with y-coordinates of 3D points.
:param zs: 1D ndarray with z-coordinates of 3D points.
:return: 3D bounding box (x, y, z, w, h, d), where (x, y, z) is the top-left
corner and (w, h, d) is width, height and depth of the bounding box.
"""
bb_min = [xs.min(), ys.min(), zs.min()]
bb_max = [xs.max(), ys.max(), zs.max()]
# NOTE: this need to +1, do not use this !!!!!!!!!!!!!!!
return [
bb_min[0],
bb_min[1],
bb_min[2],
bb_max[0] - bb_min[0],
bb_max[1] - bb_min[1],
bb_max[2] - bb_min[2],
]
|
5e4f2c6197addae67816844f6764b16c031d3d29
| 625,506 |
def filter_deleted_items(items, flag):
"""Filter deleted items
:param items: target
:param flag: deleted flag name, always True means deleted
:return: list does not contain deleted items
"""
# just return if parameter is not a list
if not isinstance(items, list):
return items
result = filter(lambda x: not x[flag], items)
return [x for x in result]
|
0f494d3515f7bd78661b3e5bed00055eeea6f7d3
| 662,339 |
def snake_to_camel_case(value):
"""
Converts a string from snake_case to camelCase
"""
words = value.strip("_").split("_")
return words[0].lower() + "".join([word.capitalize() for word in words[1:]])
|
b78419dbdbe0cd88f6dd79e9174f4a26ae9640b5
| 607,712 |
def get_all_ann_index(self):
""" Retrieves all annotation ids """
return list(self.ann_infos.keys())
|
4375c9dbc14bf50575c8a5e42ce0ae8749820dfb
| 706,589 |
def get_clean_fips(fips):
"""
Given a FIPS code, ensure it is returned as a properly formatted FIPS code of length 5
Example:
get_clean_fips(123) = "00123"
get_clean_fips("0002") = "00002"
get_clean_fips("00001") = "00001
:param fips: The FIPS code to clean
:return: The 5-digit FIPS code as a string
"""
as_string = str(fips)
size = len(as_string)
fips_length = 5
difference = fips_length - size
if difference > 0:
as_string = "0" * difference + as_string
return as_string
|
e41c846a7db4f34329e8d2d6a9f960f4b3da99a5
| 408,341 |
import math
def deg2rad(deg):
"""
Convert unit from deg to rad.
"""
return deg * math.pi / 180.0
|
3b0b206519f8725a81e5f97b236eb04b9caa94c8
| 402,897 |
def calculate_progress(total_count, count, start_progress = 0.0):
"""Calculates the progress in a way that is guaranteed to be safe
from divizion by zero exceptions or any other exceptions. If there
is any problem with the calculation or incoming arguments, this
function will return 0.0"""
default = 0.0
progress = float(start_progress)
if not (0.0 <= progress <= 1.0):
return default
if not (0 <= count <= total_count):
return default
try:
progress += float(count) / float(total_count)
except:
pass
assert type(progress) == float
if not (0.0 <= progress <= 1.0):
return default
return progress
|
9219e7b6657fbc405c478ae3294dd422f5b7d618
| 145,419 |
def _popanykey(dct, *keys, strict=False):
"""
Returns the first of the listed keys to be found in the dict
:param dct: a dict
:param keys:
:param strict: [False] if True, raise KeyError if we get to the end of the list and nothing was found
:return:
"""
for key in keys:
if key.lower() in dct:
return dct.pop(key.lower())
if strict:
raise KeyError(keys)
return None
|
dc895b8a2f7b4c42b8f46557a48a0f1fb048eb96
| 492,293 |
def remove_xml(rid):
"""
Removes the .xml from a resource or spec id.
"""
if '.xml' in rid[-4:]:
return rid[:-4]
else:
return rid
|
e57c7ccfdfb130092ef0f2fd8412d4771fd716aa
| 47,855 |
def intseq(words, w2i, unk='.unk'):
"""
Convert a word sequence to an integer sequence based on the given codebook.
:param words:
:param w2i:
:param unk:
:return:
"""
res = [None] * len(words)
for j, word in enumerate(words):
if word in w2i:
res[j] = w2i[word]
else:
res[j] = w2i[unk]
return res
|
9716cbc3fad228802ba954e50df4d2f109eff3e6
| 87,079 |
def feature_normalization(X):
"""
Mean/standard deviation normalization.
:param np.ndarray X: Feature matrix to be normalized.
:return: np.ndarray of normalized feature matrix, np.ndarray of means and np.ndarray of standard deviation.
"""
mu = X.mean(axis=0)
sigma = X.std(axis=0, ddof=1)
return (X - mu) / sigma, mu, sigma
|
b9d8b45db8c05e7dd55e3b6339543401219262ce
| 493,445 |
def parse_job_line(line):
"""
>>> parse_job_line("* * * *,myquery,mycredentials\\n")
('* * * *', 'myquery', 'mycredentials', 'collect.py')
>>> parse_job_line("* * * *,myquery,mycredentials,scripts/foo.py\\n")
('* * * *', 'myquery', 'mycredentials', 'scripts/foo.py')
"""
parts = line.strip().split(',')
if len(parts) == 3:
parts.append('collect.py')
return tuple(parts)
|
8a83a3a5721e9e9b15cae7cd438bf505e776b38f
| 125,629 |
def hamming_distance(str1, str2):
"""calculate the hamming distance of two strings."""
# ensure length of str1 >= str2
if len(str2) > len(str1):
str1, str2 = str2, str1
# distance is difference in length + differing chars
distance = len(str1) - len(str2)
for index, value in enumerate(str2):
if value != str1[index]:
distance += 1
return distance
|
6ac874c65fec012c74866bb10713195586c90294
| 535,228 |
def hist_range(array, bins):
""" Compute the histogram range of the values in the array.*
Parameters
----------
array: array
the input data.
bins: int
the number of histogram bins.
Returns
-------
range: 2-uplet
the histogram range.
"""
s = 0.5 * (array.max() - array.min()) / float(bins - 1)
return (array.min() - s, array.max() + s)
|
937df240f2e2c91aa8eb4f4fe6d5075a30f0ff76
| 87,904 |
import yaml
def trun_from_file(fpath):
"""Returns trun from the given fpath"""
with open(fpath, 'r') as yml_file:
return yaml.safe_load(yml_file)
|
4cc2ea61f61607edd79f25c93e01f55fc7b5dbbd
| 435,604 |
def count_distinct_occurence(calls, texts):
"""Return the count of distinct occurence of number
Args:
calls: list of calls
texts: list of texts
Returns:
number of distinct number
"""
number_set = set()
for record in calls+texts:
number_set.add(record[0])
number_set.add(record[1])
return len(number_set)
|
4acf40c50bbd32b23735aaad2c581559829bb664
| 21,923 |
def extract_ingredient_counts(ingredients_dict, ingredient_labels):
"""
Extract ingredient counts from dict for plotting in chart.
:param ingredients_dict: dict mapping ingredient names to counts
:param ingredient_labels: list of strings containing ingredient names
:return: list of counts of ingredients
"""
return [ingredients_dict[ingredient] for ingredient in ingredient_labels]
|
852b299d31e8896ec047db9bbf296cdbc7a0a2b0
| 574,037 |
from typing import Optional
def filter_106_sum_lines(obj: dict) -> Optional[bool]:
"""Filter our unneeded lines in Form 106Sum
:param obj: Pdf line
:return: Whether to keep filtered lines
"""
if obj["width"] < 20:
return False
if obj["top"] < 60:
return False
if obj["x0"] < 360:
return False
return True
|
fc63f005bcdc8d057fdec74dca4b572767296be8
| 196,222 |
def readDictionary(input):
"""
Read file to a dictionary data structure:
Input file is a lexicon consisting lines of the word and the most frequent associated tag
"""
dictionary = {}
lines = open(input, "r").readlines()
for line in lines:
wordtag = line.strip().split()
dictionary[wordtag[0]] = wordtag[1]
return dictionary
|
543261fe7cbff53b4dc3082d56687aa3d2cef336
| 627,535 |
def http_ok_status() -> dict:
"""
Return an HTTP 200 ok status
"""
return {"statusCode":200, "body":""}
|
e88f3f4f2c7a4ac900d52f58f5601d3782ff4867
| 580,552 |
def _dash_escape(args):
"""Escape all elements of 'args' that need escaping.
'args' may be any sequence and is not modified by this function.
Return a new list where every element that needs escaping has
been escaped.
An element needs escaping when it starts with two ASCII hyphens
('--'). Escaping consists in prepending an element composed of
two ASCII hyphens, i.e., the string '--'.
"""
res = []
for arg in args:
if arg.startswith("--"):
res.extend(("--", arg))
else:
res.append(arg)
return res
|
94f1f19cf02c3b640480052f1f586d24dee135ec
| 347,996 |
import sympy
def field_linear(theta):
"""Jones vector for linear polarized light at angle theta from horizontal plane."""
return sympy.Matrix([sympy.cos(theta), sympy.sin(theta)])
|
4ae21f61e0263f5e51ef6a390004bcdf4b9d763d
| 590,084 |
import logging
def get_logger(name):
"""
Create new logger with the given name
:param name: Name of the logger
:return: Logger
"""
logger = logging.getLogger(name)
return logger
|
80a7e545be7badd71277d38dbb202e70643f6ecb
| 629,815 |
def function() -> str:
"""Return a value."""
return "value"
|
00e8446e17cd3b2fa436a429780a500abdfe1286
| 504,049 |
def is_trunk(output, port):
"""
Returns True port is trunk, False otherwise
:param output: String - Output of 'show int trunk'
:param port: String - The port e.g. Gi0/1
:return: Bool
"""
for lines in output.strip().splitlines():
if port in lines:
return True
return False
|
dd687f7a2c6536b634baa9594f0e9835176a8716
| 463,093 |
def str_to_pair_of_lists(_str1, _str2, _sep=','):
"""
Attempts to convert 2 strings containing tokens separated by some _sep to a pair of lists, e.g. "a1,a2,a3", "b1,b2,b3" -> [['a1','a2','a3'],['b1','b2','b3']]
:param _str1: input string #1
:param _str2: input string #2
:param _sep: token separator in the strings
:returns: list of pairs of the corresponding tokens
"""
if((_str1 is None) or (_str2 is None) or (_str1 == '') or (_str2 == '')): return None
lstTok1 = _str1.split(_sep)
lstTok2 = _str2.split(_sep)
return [lstTok1, lstTok2]
|
704d322ca9ab55fcb67683402c057a39d9386dd2
| 500,063 |
import re
def clen(string):
"""Return the length of a string, excluding ansi color sequences."""
return len(re.sub(r'\033[^m]*m', '', string))
|
042873da51a583cfa30fda0b999e7a2cba0d5ada
| 450,571 |
def hex_8bit(value):
"""Converts 8bit value into bytearray.
args:
8bit value
returns:
bytearray of size 1
"""
if value > 0xff or value < 0:
raise Exception('Sar file 8bit value %s out of range' % value)
return value.to_bytes(1, 'little')
|
597ecb6c9a499c7a5959f1f8ddd7300b78b06e9a
| 694,649 |
def clamp(value: float, lower: float, upper: float) -> float:
"""
Basic clamp function: if below the floor, return floor; if above the ceiling, return ceiling; else return unchanged.
:param value: float input
:param lower: float floor
:param upper: float ceiling
:return: float within range [lower-upper]
"""
return lower if value < lower else upper if value > upper else value
|
e9dbe198776dafe743bbea4d4959e6e857112509
| 198,447 |
async def leave_comment(gh, issue_comment_url: str, message: str, token: str):
"""
Leave comment in issue or pull request
:param gh: object with actions
:param issue_comment_url: api string
:param message: comment
:param token: GitHub token
:return: response
"""
data = {'body': message}
return await gh.post(
f'{issue_comment_url}',
data=data,
oauth_token=token
)
|
cdcddeaef04cf3667cc861d44bd69180a8e49b34
| 628,004 |
def fatorial(num, show=False):
"""
-> Função para calcular fatorial.
-> Paramêtros:
* num: Número a ser calculado o fatorial.
* show: True para mostrar calculo, False para mostrar apenas resultado.
* return: Resultado da somatória.
"""
soma = 1
for cont in range (num, 0, -1):
if show:
print(cont, end='')
if cont > 1:
print(' x ', end='')
else :
print(' = ', end='')
soma *= cont
return soma
|
e6f50f63af36e79ed952010c917090cd4cbc930b
| 151,212 |
def module_tracker(fwd_hook_func):
"""
Wrapper for tracking the layers throughout the forward pass.
Arguments
---------
fwd_hook_func : function
Forward hook function to be wrapped.
Returns
-------
function :
Wrapped hook function
"""
def hook_wrapper(layer, *args):
return fwd_hook_func(layer, *args)
return hook_wrapper
|
d0835227ba1f7dde27bcc0d0af22bef8d50b90c6
| 380,123 |
def last_consecutives(vals, step=1):
"""
Find the last consecutive group of numbers
:param vals: Array, store numbers
:param step: Step size for consecutive numberes, default 1
:return: The last group of consecutive numbers of the input vals
"""
group = []
expected = None
for val in reversed(vals):
if (val == expected) or (expected is None):
group.append(val)
else:
break
expected = val - step
return group
|
7e12990eb8ee1f44fd81d2dd66c24bf952316053
| 520,789 |
import hashlib
def get_md5(path):
"""
Utility function for generating the md5sum of a file
:param path: Path to file
"""
md5 = hashlib.md5()
block_size = 8192
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
md5.update(chunk)
return int(md5.hexdigest(), 16)
|
6ac19b40154d5a2acfd6ff251a2d63cbc5908e96
| 421,588 |
def _massage_groups_out(appstruct):
"""Opposite of '_massage_groups_in': remove 'groups:' prefix and
split 'groups' into 'roles' and 'groups'.
"""
d = appstruct
groups = [
g.split("group:")[1]
for g in d.get("groups", "")
if g and g.startswith("group:")
]
roles = [r for r in d.get("groups", "") if r and r.startswith("role:")]
d["groups"] = groups
d["roles"] = roles
return d
|
a447e50c551e16319c53101d646d93d8868cd3f0
| 444,332 |
def scale_bounding_boxes(bounding_boxes, orig_width, new_width):
"""
Scale a list of bounding boxes to reflect a change in image size.
Args:
bounding_boxes: List of lists of [x1, y1, x2, y2], where
(x1, y1) is the upper left corner of the box, x2 is the width
of the box, and y2 is the height of the box.
orig_width: Width of the images to which bounding_boxes apply
new_width: Width of the target images to which the bounding boxes
should be translated
Returns:
A new list of bounding boxes with the appropriate scaling factor
applied.
"""
scale_factor = new_width / orig_width
ret = []
# Use a for loop because OpenCV doesn't play well with generators
for bbox in bounding_boxes:
new_bbox = []
for elem in bbox:
new_elem = round(float(elem) * scale_factor)
new_bbox.append(new_elem)
ret.append(new_bbox)
return ret
|
f670e9d37853075f169e933ff5128edbd300aa9f
| 67,649 |
def get_collection_sizes(net, bus_size=1.0, ext_grid_size=1.0,
trafo_size=1.0, load_size=1.0, sgen_size=1.0,
switch_size=2.0, switch_distance=1.0):
"""
Calculates the size for most collection types according to the distance between min and max geocoord so that
the collections fit the plot nicely
# Comment: This is implemented because if you would choose a fixed values
# (e.g. bus_size = 0.2), the size
# could be to small for large networks and vice versa
INPUT
net - pp net
bus_size (float)
ext_grid_size (float)
trafo_size (float)
load_size (float)
sgen_size (float)
switch_size (float)
switch_distance (float)
Returns
sizes (dict) - containing all scaled sizes in a dict
"""
mean_distance_between_buses = sum((net['bus_geodata'].max() - net[
'bus_geodata'].min()).dropna() / 200)
sizes = {
"bus": bus_size * mean_distance_between_buses,
"ext_grid": ext_grid_size * mean_distance_between_buses * 1.5,
"switch": switch_size * mean_distance_between_buses * 1,
"switch_distance": switch_distance * mean_distance_between_buses * 2,
"load": load_size * mean_distance_between_buses,
"sgen": sgen_size * mean_distance_between_buses,
"trafo": trafo_size * mean_distance_between_buses
}
return sizes
|
c032eeb22e4aed9acb2c519b2b0bcb548bba576f
| 502,461 |
def merge_dicts(dict_a, dict_b):
"""Performs a recursive merge of two dicts dict_a and dict_b, wheras dict_b always overwrites the values of dict_a
:param dict_a: the first dictionary. This is the weak dictionary which will always be overwritten by dict_b (dict_a
therefore is a default dictionary type
:param dict_b: the second dictionary. This is the strong dictionary which will always overwrite vales of dict_a
:return:
"""
merge_result = dict_a.copy()
for key in dict_b:
if key in dict_a and isinstance(dict_a[key], dict) and isinstance(dict_b[key], dict):
merge_result[key] = merge_dicts(dict_a[key], dict_b[key])
else:
merge_result[key] = dict_b[key]
return merge_result
|
32e2823a7491f916fcdab8a28b94d5027c1f0306
| 656,141 |
def getLaggedReturns_fromReturns(x, lag):
"""
Get lagged log returns for an x pandas Serie.
Parameters
----------
x : pd.Series
Data serie
lag : int
Number of periods to be lagged
"""
weekly_price = x.rolling(lag).sum()
weekly_returns = weekly_price.diff(lag)
return weekly_returns
|
12e2f8ba1cdf7316d8003dc030c7f181e2c7b17c
| 489,925 |
def load(filename):
"""Load the labels and scores for Hits at K evaluation.
Loads labels and model predictions from files of the format:
Query \t Example \t Label \t Score
:param filename: Filename to load.
:return: list_of_list_of_labels, list_of_list_of_scores
"""
result_labels = []
result_scores = []
current_block_name = ""
current_block_scores = []
current_block_labels = []
with open(filename,'r') as fin:
for line in fin:
splt = line.strip().split("\t")
block_name = splt[0]
block_example = splt[1]
example_label = int(splt[2])
example_score = float(splt[3])
if block_name != current_block_name and current_block_name != "":
result_labels.append(current_block_labels)
result_scores.append(current_block_scores)
current_block_labels = []
current_block_scores = []
current_block_labels.append(example_label)
current_block_scores.append(example_score)
current_block_name = block_name
result_labels.append(current_block_labels)
result_scores.append(current_block_scores)
return result_labels,result_scores
|
273a4addc8b943469b22f7495291fee179e67e62
| 693,722 |
def suffix(d: int) -> str:
"""Convert an input date integer to a string with a suffix.
Example:
>>> suffix(10)
'th'
>>> suffix(2)
'nd'
>>> suffix(23)
'rd'
>>> suffix(4)
'th'
"""
return "th" if 11 <= d <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(d % 10, "th")
|
96c41def9519d08e37a72a0fb7bbc39ae309cbbb
| 332,656 |
def areaCuadrado(lado):
"""Esta función sirve para calcular el área de un cuadrado del lado especificado como parámetro."""
return "El área del cuadrado de lado {} es: ".format(lado) + str(lado*lado)
|
827bfaac1644f8d56e64d207fbf5da896884c2be
| 472,933 |
def isascii(s):
"""Returns True if str s is entirely ASCII characters.
(Compare to Python 3.7 `str.isascii()`.)
"""
try:
s.encode("ascii")
except UnicodeEncodeError:
return False
return True
|
ab0969a89ebdf23b8c6ec2d34ecd3f67b616b30a
| 73,812 |
def get_recommendations(mid, conn):
"""
Grab recommendations for a single mid.
Returns multiple recommendation types as a dictionary.
Example Return
--------------
{
'l2r': [mid1, mid2, mid3],
'wrmf': [mid5, mid6, mid7
}
"""
c = conn.cursor()
sql = """
SELECT
type,
recommended
FROM recommendations
WHERE
mid = '{}'
""".format(mid)
c.execute(sql)
results = c.fetchall()
if results:
out = []
for r in results:
out.append((r[0], [str(x) for x in r[1].split(',')]))
out = dict(out)
else:
out = None
return out
|
5794810f907eae4cc778b15611efa19e49f1b05d
| 184,157 |
from bs4 import BeautifulSoup
def get_tag_by_field(text_or_soup, tag_name, field, expr):
"""Returns HTML tag in text if expr is in its field.
If not found, returns None.
"""
if isinstance(text_or_soup, BeautifulSoup):
soup = text_or_soup
else:
soup = BeautifulSoup(text_or_soup)
for tag in soup.find_all(tag_name):
if expr in tag.get(field, ''):
return tag
return None
|
4d792c5da4bf4621142c5efa04a4e437a7d70619
| 94,586 |
def oracle_id(account_id):
"""
Compute the oracle id of a oracle registration
:parm account_id: the account registering the oracle
"""
return f"ok_{account_id[3:]}"
|
6589b0cde6ab7bfc25b40e9e78e08d6c324a781b
| 140,980 |
def deserialize_utf8(value, partition_key):
"""A deserializer accepting bytes arguments and returning utf-8 strings
Can be used as `pykafka.simpleconsumer.SimpleConsumer(deserializer=deserialize_utf8)`,
or similarly in other consumer classes
"""
# allow UnicodeError to be raised here if the decoding fails
if value is not None:
value = value.decode('utf-8')
if partition_key is not None:
partition_key = partition_key.decode('utf-8')
return value, partition_key
|
21cc61d6048b5f7d9333ceadb86d03666719f05f
| 25,860 |
def ReserveHospRsrvEnd(t):
"""Hospitalization reserve: End of period"""
return 0
|
adc01e22aee1bc14a114fb37f27b40abd73810d7
| 64,145 |
def add_load_data_args(parser):
"""Adds common data loader arguments to arg parser"""
platforms = ['telegram', 'whatsapp', 'messenger', 'hangouts']
parser.add_argument('-p', '--platforms', default=platforms, choices=platforms, nargs='+', help='Use data only from certain platforms')
parser.add_argument('--filter-conversation', dest='filter_conversation', nargs='+', default=[], help='Limit by conversations with this person/group')
parser.add_argument('--filter-sender', dest='filter_sender', nargs='+', default=[], help='Limit by messages by this sender')
parser.add_argument('--remove-conversation', dest='remove_conversation', nargs='+', default=[], help='Remove messages by these senders/groups')
parser.add_argument('--remove-sender', dest='remove_sender', nargs='+', default=[], help='Remove all messages by this sender')
parser.add_argument('--outgoing-only', dest='outgoing_only', action='store_true', help='Limit by outgoing messages')
parser.add_argument('--incoming-only', dest='incoming_only', action='store_true', help='Limit by incoming messages')
parser.add_argument('--lang', nargs='+', default=[], help='Limit by detected languages')
parser.add_argument('--contains-keyword', dest='contains_keyword', nargs='+', default=[],
help='Limit by messages which contain certain keywords (multiple keywords are used with OR logic)')
return parser
|
5a1bc118a06199222a9940f095fa0471b7f20c33
| 541,607 |
def str_to_color(s):
"""Convert hex string to color value."""
if len(s) == 3:
s = ''.join(c + c for c in s)
values = bytes.fromhex(s)
# Scale from [0-255] to [0-1]
return [c / 255.0 for c in values]
|
cedcad67ee8de5d5470bb60ae106eb52b459c7ff
| 223,212 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.