content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def listBranchUsage(err=''):
""" Prints the usage stmt for listBranch """
m = ''
if len(err):
m += '%s\n\n' %err
m += 'List status information for a single branch.\n'
m += '\n'
m += 'Usage:\n'
m += ' lsbr -s <stream> -b <branch_Name>\n'
return m | 220ff8fc3f604bcc441c5ef2fd09b79ec8d4a5b1 | 651,147 |
import gzip
def get_handle(filen, rw):
""" Returns file handle using gzip if file ends in .gz
"""
if filen.split('.')[-1] == 'gz':
return gzip.open(filen, rw)
else:
return open(filen, rw) | 376856d8753c4660c39cacbe61a835cda3d09212 | 651,150 |
def has(i):
"""Returns the form of the verb 'avoir' based on the number i."""
# Note: this function is used only for the third person
if i == 1:
return 'a'
else:
return 'ont' | 60002d083050e443dfd52f9fb752387068a7bdb0 | 651,152 |
from typing import Union
def get_bool(value: str) -> Union[bool, None]:
"""When given a string, returns a boolean value based on the string
Parameters
----------
value : str
A string representing a user response
Returns
-------
Union[bool, None]
whether the string is true... | bfc25a4d1bfdf194c68141d9027e0d3543ffdc0d | 651,155 |
def magtoflux(marr, fzero):
"""Convert from magnitude to flux.
marr--input array in mags
fzero--zero point for the conversion
"""
return fzero * 10 ** (-0.4 * marr) | 9b554361099eb0c3e6c9178451ccf0a5e49c60c0 | 651,156 |
def partition(arr, left, right):
"""
*--------*----------*-----------*
left mid frontier right
left is the pivot, it has been moved to the beginning of the array.
frontier marks all the elements we've alreay looked at.
mid is the new index of the pivot, everything to the left i... | c411eaa2e9a1a50a20f45fcfd7d7d49a6fc592b6 | 651,159 |
from datetime import datetime
def _time_of_day(dt: datetime) -> float:
"""Convert a given datetime `dt` to a point on the unit circle, where the 'period' corresponds to one day.
:param datetime.datetime dt: input datetime UTC
:returns: `float` between 0 and 1 corresponding to the phase
"""
midnig... | cd82b312de706445ba00e391bb33e2b6e056d0bd | 651,162 |
import torch
def objtrack_collect(batch):
"""Collect the objtrack data for one batch.
"""
targets = []
imgs = []
frame_id = []
indexs = []
for sample in batch:
imgs.append(sample[0])
targets.append(sample[1])
frame_id.append(sample[2])
indexs.append(sample[3... | 7df24ca59496634ba7d40c0cfaea1e12564b681d | 651,164 |
def frequency(total: float, percentage: float, value: float, invert: bool = False) -> float:
"""Return frequency of a given value .
Freq = v*t/p
v-> value
t-> total
p-> percentage
Args:
total (float): total value
percentage (float): percentage value between 0 and 1
val... | 516e06044cfec14af166f3e8fc1b1db646f518ad | 651,167 |
def get_query_string(params) -> str:
"""
Gets the query string of a URL parameter dictionary.abs
:param params: URL params.
:return: Query string.
"""
if not params:
return ''
return '?' + '&'.join([str(k) + '=' + str(v) for k, v in params.items()]) | 7bc08e0f68333c2f42d31e8879d3978dd94850ac | 651,174 |
def flatt_on_level(it, d=-1, level=None):
"""
>>> list(flatt_on_level([[[['a']]]], level=3))
[['a']]
"""
if d == -1:
return list(flatt_on_level(it, d=d + 1, level=level))
if d == level:
return (i for i in [it])
res = []
for x in it:
res.extend( flatt_on_level(x... | 03b033f7ea7af03a3124e8cb4be61c3b3609d4ef | 651,175 |
import re
def format_string(prop_string):
"""
Formats a property string to remove spaces and go from CamelCase to pep8
from: http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case
"""
if prop_string is None:
return ''
st_r = re.sub... | 4e5ff40b02edd51e927bb30083102e388c76b4b5 | 651,177 |
def average_index(n1, n2, v1=None, v2=None, vr=None):
"""Compute volume weighted average refractive index
Args:
n1, n2 (float/ndarray): refractive index of material 1 and 2
v1, v2 (float): volume of materials 1 and 2
vr (float): volume ratio of v1/(v1+v2) used instead of v1 and v2
""... | 373146c0e5e55fa09dcfa2c90cc12f48a89fe674 | 651,180 |
def verify_name(prior_name, inferred_name):
"""Verfies that the given/prior name matches with the inferred name.
"""
if prior_name is None:
prior_name = inferred_name
else:
assert prior_name == inferred_name, f"""given name {prior_name} does not mach with
... | 02466d179e37ffab5271b7b06a74b07404aa574a | 651,186 |
import math
def dist(a0, a1, b0, b1):
"""Returns the Eucleadean distance between two points in 2D."""
da = a1-a0
db = b1-b0
return math.sqrt(da*da + db*db) | e2db45aed6912f1d0c38f1176f86a10c83f0fda0 | 651,191 |
def _create_interface(phase, graph, references):
"""Creates an interface instance using a dynamic type with graph and references as attributes.
"""
interface = {'graph': graph}
interface.update(references)
return type(phase + 'Interface', (object,), interface) | 8f8c6d6cf531dcec0dd4bb72d21547de66ef340c | 651,192 |
def emtpy_cols(cols, rows, plas, model):
"""
Helper function for shrink_dict.
Iterates over the given model and removes all numbers of the coordinates
from the items in the model. this way there will be remaining lists of
empty cols, rows and plas. Returns a list of the 3 lists.
"""
for (x_c... | 410b13b0b0d527237c794be04f708e31cf39293f | 651,196 |
import math
def rbf_kernel(a, b, sigma=1):
"""An implementation of the radial basis function kernel.
Args:
a: A vector
b: A vector
sigma: The radius of the kernel
"""
distance = (a - b).dot(a - b)
scaled_distance = -distance / (2 * (sigma) ** 2)
return math.exp(scaled_... | 8e50c92dede84ce8201ff15e9d7c375e222cb891 | 651,197 |
def user_unicode(self):
"""Use email address for string representation of user."""
return self.email | 3b3f8de3a48643dccbc585099a59e3e55fb284e2 | 651,201 |
import string
def term_frequency(term: str, document: str) -> int:
"""
Return the number of times a term occurs within
a given document.
@params: term, the term to search a document for, and document,
the document to search within
@returns: an integer representing the number of times a... | fd3650360e2f1177c5e0514c10ba908767c2daf0 | 651,204 |
import pickle
def data_pickle_load(city, year, month):
"""
Load data from a Data class object pickle. See Data.pickle_dump
Parameters
----------
city : str
The identification of the city. For a list of supported cities, see
the documentation for the Data class.
year : int
... | 4577f104526e5564dbe587dcf616b4b08a9b10ad | 651,205 |
def clean_caesar(text):
"""Convert text to a form compatible with the preconditions imposed by Caesar cipher"""
return text.upper() | 80b3c79d00efaac29463ffc1e5352b73bf4f940e | 651,211 |
def make_wheel(run_setup_file):
"""
Make a wheel distribution from a given package dir.
"""
def _make_wheel(package_dir, dist_dir, *args):
return run_setup_file(
package_dir, "bdist_wheel", "--dist-dir", str(dist_dir), *args
)
return _make_wheel | fa3f8aa8d012be3ab2eb1e3788abed85ffa4bbf2 | 651,214 |
def kin2dyn(kin, density):
"""
Convert from kinematic to dynamic viscosity.
Parameters
----------
kin: ndarray, scalar
The kinematic viscosity of the lubricant.
density: ndarray, scalar
The density of the lubricant.
Returns
-------
dyn: ndarray, scalar
The ... | 0a205710ef343c2bd82afa79952a40707135e4bb | 651,215 |
def convert_to_bool(data):
"""
convert_to_bool converts input to bool type in python.
The following values are converted to True:
1. 'true'
2. 'yes'
3. '1'
4. 'y'
5. 1
The following values are converted to False:
1. 'false'
2. 'no'
3. '0'
4. 'n'
5. 0
:par... | 64aa3bf70cb40a436fb6e92d835c27602c824175 | 651,219 |
def is_int(obj, int_like=False):
"""
Checks for int types including the native Python type and NumPy-like objects
Args:
obj: Object to check for integer type
int_like (boolean): Check for float types with integer value
Returns:
Boolean indicating whether the supplied value is o... | faa3403e061963749032923bb3311bab9522b5d1 | 651,220 |
def format_filename(string):
"""
Converts a string to an acceptable filename
e.g. "Go! series - F1" into "Go_series_-_F1"
Parameters:
string (str): raw filename
Returns:
formatted_filename (str): formatted filename
Raises:
"""
# NOTE: Periods (.) and dashes (-) are a... | ab48073064b396d2260138b39c33c5f24ec636ce | 651,221 |
def get_ion_state(line):
"""
Get the ionization state of a `VoigtFit.Line` instance or of `line_tag` string:
ex: Line<'FeII_2374'> --> II
ex: Line<'CIa_1656'> --> I
ex: 'CIV_1550' --> IV
"""
if isinstance(line, str):
ion = line.split('_')[0]
else:
ion = line.ion
... | 403867d4b05ae3d4a42a73daa5cdfb43adea03f1 | 651,222 |
def extract_content(last_metadata_line, raw_content):
"""Extract the content without the metadata."""
lines = raw_content.split("\n")
content = "\n".join(lines[last_metadata_line + 1 :])
return content | a14514753fb7a36a01972b3c6147ccd95a507bfb | 651,224 |
import binascii
def get_tflite_data(tflite_path: str) -> list:
"""
Reads a binary file and returns a C style array as a
list of strings.
Argument:
tflite_path: path to the tflite model.
Returns:
list of strings
"""
with open(tflite_path, 'rb') as tflite_model:
... | 84dbe3b0fa9dbcac777cfb585498559fb40922f4 | 651,227 |
import csv
def read_sleepasandroid_file(saa_filename):
"""
read in a SleepAsAndroid backup file and return it as a parsed list
"""
with open(saa_filename) as file:
file_as_list = list(csv.reader(file, delimiter=','))
return file_as_list | 22011c2ba784747c65c3dc47063fb486d3130785 | 651,228 |
def snake_to_pascal_case(s: str) -> str:
"""Convert a string from snake_case to PascalCase"""
if not s:
return s
return "".join(
map(
lambda segment: (segment[0].upper() + segment[1:]) if segment else segment,
s.split("_"),
),
) | c8f462ae5ebc58f520509f21913a50c0631b1cb9 | 651,229 |
def who_create(user_id, ticket = None):
"""
Create a TTBD user descriptor from a user id name and a ticket
:params str user_id: user's name / ID
:params str ticket: (optional) ticket for the reservation
:returns: (str) user id descriptor
"""
if ticket != None and ticket != "":
retu... | 8ba325d58d8c32d5e40fcf84cebedf4270597510 | 651,231 |
def get_loc_offset(box_gt, box_anchor):
"""Computes the offset of a groundtruth box and an anchor box.
Args:
box_gt (array): groundtruth box.
box_anchor (array): anchor box.
Returns:
float: offset between x1 coordinate of the two boxes.
float: offset between y1 coordinate o... | 9e9d6c25d35d02c93594791e412c3ac058cacdcd | 651,235 |
def deep_getattr(obj, attr_string, default=None):
"""
Returns the attribute of `obj` at the dotted path given by `attr_string`
If no such attribute is reachable, returns `default`
>>> deep_getattr(cass, "cluster")
<cassandra.cluster.Cluster object at 0xa20c350
>>> deep_getattr(cass, "cluster.m... | a4450d5441f6a67bab7aa6c13977b4921dfceacd | 651,239 |
from typing import List
def funkcia2(cisla: List[int]) -> List[int]:
"""Vyfiltruj iba čísla delitelné 3 alebo 5.
>>> funkcia2([7, 12, 35, 15, 45, 16, 18])
[12, 35, 15, 45, 18]
"""
# 1. riešenie
vysledok = []
for i in range(0,len(cisla)):
if(cisla[i] % 3 == 0) or (cisla[i] % 5 == 0)... | ea84724461e88a5b3cdab45058ae721f289479af | 651,241 |
import requests
def get_activity_streams_json(activity_id, access_token, types=None):
"""Get streams (time series) for a particular activity.
https://developers.strava.com/docs/reference/#api-Streams-getActivityStreams
`stravalib` implementation for reference:
`streams = client.get_activity_streams(id)`
... | 1da3ad64f274d86b42ea367575f64ac126ddf710 | 651,243 |
from typing import List
def __has_term_from_list__(text: str, string_list: List[str]) -> bool:
"""
Check if a string contains an item in a list
"""
for item in string_list:
if item in text:
return True
return False | 90d3996989b3e19f046cca8d4835a1bcb6ee963c | 651,247 |
import re
def extract_udf_name(udf_path):
"""
Parse out the name of the UDF from the SQL DDL
:param udf_path: Path to the UDF DDL .sql file
:return: Name of the UDF
"""
with open(udf_path) as udf_file:
udf_sql = udf_file.read()
udf_sql = udf_sql.replace('\n', ' ')
pattern = re... | 5acb393386e7a9ed3d9b9e7fcca9810ac50344a7 | 651,250 |
import json
def lerArquivoJSON(caminho_arquivo):
"""
Retorna conteúdo de um arquivo JSON de comandos SQL, delegando tratamento para bloco de função reservado
:param caminho_arquivo:
:return: data (JSON)
"""
with open(caminho_arquivo, "r") as read_file:
data = json.load(read_file)
... | 2cfdd872295a244fb2a83f6b287a954e806da829 | 651,251 |
import calendar
def days_in_year(year: int) -> int:
"""Returns the number of days in the year
Args:
year (int): The year.
Returns:
int: The number of days in the year.
"""
return 366 if calendar.isleap(year) else 365 | b8a03d7bca79c3513ac4d278028b6c65b4fc3329 | 651,255 |
def extract_output(out):
"""
Extracts output for one filing unit in out and
returns extracted output as a dictionary.
Parameters
----------
out: pandas DataFrame row containing tc --dump output for one filing unit
Returns
-------
ovar: dictionary of output variables indexed from 1 ... | 1e4ebbfb096c4d76eaad20457075dbf49d4fe0bf | 651,256 |
def _get_subclasses(cls):
"""Get subclasses of passed in class and return a dictionary of them"""
return {subclass.__name__: subclass for subclass in cls.__subclasses__()} | 876e9e88d1eb0a3717e72f7ed4d4c11c90d07365 | 651,257 |
from typing import Tuple
from typing import Dict
def load_k8s_secrets() -> Tuple[Dict[str, str], str]:
"""
Loads secrets needed to access K8s resources.
Returns:
headers (dict): Headers with K8s access token
verify (str): Path to certificate
"""
with open("/var/run/secrets/kuberne... | 8a69b7ee8089cb6affe94a6ca84cd9a4064db388 | 651,263 |
import random
def char_mlm_mask_random_words(tokens, max_predictions_per_seq=38, masked_lm_prob=0.20):
"""
Masks tokens using a algorithm designed for character level masking. The idea is to ensure groups and dense clusters of characters as masked so that the task won't be too easy.
:param tokens: tokeni... | 530224620806ed1ded43bd2b586d4cc8b3fdfc59 | 651,265 |
def delimit(delimiters, content):
"""
Surround `content` with the first and last characters of `delimiters`.
>>> delimit('[]', "foo")
[foo]
>>> delimit('""', "foo")
'"foo"'
"""
if len(delimiters) != 2:
raise ValueError(
"`delimiters` must be of length 2. Got %r" % de... | a393e2a8330c05d29855505fe679bfda4665500f | 651,266 |
import time
def convert_timestamp(s):
"""
convert the N1MM+ timestamp into a python time object.
"""
return time.strptime(s, '%Y-%m-%d %H:%M:%S') | 6a1ebb40324a672c2d37fb612ed77c29e47e959c | 651,269 |
def annotation_filter(annotations, condition):
"""
Filter annotations.
`annotations`: the annotations to filter
`condition`: the filter callback
return: the filtered annotations
"""
filtered = dict()
for (key, value) in annotations.items():
if condition(key, value):
f... | 517e19ab9888964d77326a8bec8f4d469e22bc10 | 651,272 |
def adjacency_to_edges(nodes, adjacency, node_source):
"""
Construct edges for nodes based on adjacency.
Edges are created for every node in `nodes` based on the neighbors of
the node in adjacency if the neighbor node is also in `node_source`.
The source of adjacency information would normally ... | d593b4acd2b6f7553d6b9677209422ee665bc2d0 | 651,274 |
import requests
def follow_shortlinks(shortlinks):
"""Follow redirects in list of shortlinks, return dict of resulting URLs"""
links_followed = {}
for shortlink in shortlinks:
url = shortlink
request_result = requests.get(url)
redirect_history = request_result.history
# his... | a186b8690074128f037c0f38e9b239c755f6bc7c | 651,275 |
from typing import Union
from pathlib import Path
from typing import Tuple
import shlex
def get_emittances_from_madx_output(madx_output_file: Union[str, Path], to_meters: bool = False) -> Tuple[float, float, float]:
"""
Parse MAD-X output file and return the X, Y and Z emittances from the output of the last c... | 412f4933c1d2190c397d124e6026ddd3d946fb72 | 651,277 |
def parse_by_integration(sensors):
"""Returns a list of devices that can be integrated."""
can_integrate = []
for sensor in sensors.values():
if sensor.get('integrate'):
can_integrate.append(sensor)
return can_integrate | 7aa6abd786949dc293668ef17d149f752fb716de | 651,278 |
import configparser
def get_config(config_path):
"""
Get config data
:param config_path: filepath of config ini file
:return: instance of ini config file
"""
config = configparser.ConfigParser()
config.read(config_path)
return config | 25de6636666097e501a6c6f51e68b4cab10cb3aa | 651,279 |
def as_int(attribute):
"""
Treat attribute as int if it looks like one.
"""
try:
return int(attribute)
except ValueError:
return attribute | 454eca7803a17c95415ffef3ce19c714c85fb976 | 651,280 |
def cubic_rbf(r, kappa):
"""
Computes the Cubic Radial Basis Function between two points with distance `r`.
Parameters
----------
r : float
Distance between point `x1` and `x2`.
kappa : float
Shape parameter.
Returns
-------
phi : float
Radial basis function... | 0c5192d2108834a0e82dcbe8a038d9fc720eb318 | 651,284 |
def _WX(s, wx):
"""Returns TRUE if s contains string wx"""
if wx == '':
return False
# special case for blowing/drifting snow
ix = s.find(wx)
if wx == 'SN' and ix > 1:
if s[ix-2:ix] in ('BL', 'DR'):
return False
return ix >= 0 | e1f236ec64d339e917402dc3511831015b0ca334 | 651,286 |
def ndbpprint(model, level=1):
"""
Pretty prints an `ndb.Model`.
"""
body = ['<', type(model).__name__, ':']
values = model.to_dict()
for key, field in model._properties.iteritems():
value = values.get(key)
if value is not None:
body.append('\n%s%s: %s' % (
' '.join([' ' for idx in range... | 5b1a5c06cc22bb9886e4e45da872dfd2bd02f359 | 651,290 |
from typing import Any
from typing import List
def wrap(item: Any) -> List[Any]:
"""Ensures that the input is either a list, or wrapped in a list. Returns []
for None.
"""
if item is None:
return []
if isinstance(item, list):
return item
return [item] | 9e1bc807e1b235b0f24e2a93787c11f704d954f5 | 651,291 |
def series_sum(n):
"""Sum of first nth term in series and return float value."""
total_series = 0.00
for x in range(n):
total_series += float(1) / (1 + (x * 3))
total_series_decimal = ('{0:.2f}'.format(total_series))
return total_series_decimal | d383b32638ef113d581cac6e30e619956e181961 | 651,297 |
def test_well_plot(well):
"""
Tests mpl image of well.
"""
plot = well.plot(tracks=['MD', 'GR', 'DT'], extents='curves')
return plot.get_figure() | d8460a949dbaaefb1d817695a1e9b282f3839829 | 651,299 |
import socket
import binascii
def fmt_ipv6_addr(v):
"""Given a 128-bit integer representing an ipv6 address, return a
string for that ipv6 address."""
return socket.inet_ntop(socket.AF_INET6, binascii.unhexlify("%032x"%v)) | 782996a2ffbf814b464cf041cf8543654fe60a49 | 651,304 |
def args_to_cmds(args):
"""Convert args dictionary to command line arguments. For example:
>>> args_to_cmds({ 'foo': 'bar', 'qux': 'baz' })
'--foo=bar --qux=baz'
"""
result = ''
for key, val in args.items():
result += '--%s=%s ' % (key, val)
return result | 46b8e94c7b500fc3e71eccb1e39c5370f0586a5c | 651,309 |
def verbatim(f):
"""Read a line of text from file 'f'."""
line = f.readline()
return line | 8c9bd6f6c5d9f3f3d1d8ec45e62cfc8098d66af2 | 651,310 |
from pathlib import Path
def test2solution(filename: str, source_path: str) -> Path:
"""
Build a solution filename from a corresponding test filename.
"""
tokens = filename.split("/")
collection = tokens[-3]
dataset = tokens[-2]
filename = tokens[-1].replace("test-", "solutions-")
# ... | 03fe396162ec09163e8413252643cd84f462f375 | 651,311 |
def resolve_status(code):
"""
Get a label and status for the status code
:param code: The status to resolve
:return: A tuple containing the label and new status
"""
# Default label
status_label = 'info'
if code == 'success':
status_nice = 'Build Succeeded'
status_label ... | 8fc1c77170973c19bd3bb50240a184524c2c06a0 | 651,312 |
import csv
def get_desikan(filepath):
"""Parse the desikan atlas ordering for the 68 cortical regions from the csv file,
or indeed any other csv dictionary.
Args:
filepath (type): full file path.
Returns:
regions: list of region names in order of the desikan atlas.
coords: th... | 10709caceced351634696a841c963f68e3c6fe2b | 651,313 |
def get_dataset(dashboard):
"""Retrieves the dataset
Parameters:
-----------
dashboard : plsexplain.dashboard.Dashboard
Returns
-------
Callable
The API handler for the dataset
"""
def get_dataset_internal(skip, take):
skip = int(skip)
take = int(take)
... | 144bd9d2168eff06c383f187a7dfcc7a98d00ac3 | 651,316 |
import re
def is_tag(token):
"""Determine if a token is a tag of the format like [i-10] or [o-7]"""
is_tag_re = re.compile('\[[io]-\d+\]', re.IGNORECASE)
return is_tag_re.match(token) | 6639973b4949021f88f3d24857d6af8c83c6595f | 651,317 |
def SHPowerL(c, l):
""" Calculate the power for degree l. c is the CILM array.
RETURNS:
scalar value for the power
"""
return (c[:,l,:]**2).sum() | eb5ac44a7f7a9f6fb4cbebb0c581a8b4057fb0b3 | 651,321 |
def strip_numbers(text: str):
"""Strip numbers from a piece of text"""
text = text.replace("0", "").replace("1", "").replace("2", "").replace("3", "").replace("4", "").replace("5", "")
text = text.replace("6", "").replace("7", "").replace("8", "").replace("9", "")
return text | ad8ec7a0e706f32e66ec09fffd9155880b039723 | 651,325 |
def _get_outside_corners(corners, board):
"""
Return the four corners of the board as a whole, as
(up_left, up_right, down_right, down_left).
"""
xdim = board.n_cols
ydim = board.n_rows
if corners.shape[1] * corners.shape[0] != xdim * ydim:
raise Exception(
"Invalid numb... | 647a5f42192a312c7a661880d1d2750ebf70e154 | 651,335 |
import random
import time
def call_with_retries(function, max_retries=10,
exception_types=(Exception),
_args=(), _kwargs={}):
"""
Call `function` with up to `max_retries` retries. A retry is only
performed if the exception thrown is in `exception_types`.
:p... | 798f9e01cea59df1176537738326a24358695ea1 | 651,338 |
def yper(p):
"""Calculates the y position for a given amount of peroxide."""
return 100 + (p - 12) * -10 | 3d949f34843d9b98a1a2e2cf1ef757eeafe65845 | 651,340 |
def in_by_id(element, collection):
"""Check if element is in collection, by comparing identity rather than equality."""
return any(element is item for item in collection) | 55a0e174493970d55174b38d6bad3f9643ba7068 | 651,341 |
def getRemoteParams(dbElem):
"""Get parameters to supply to ktremotemgr to connect to the right DB."""
host = dbElem.getDbHost() or 'localhost'
return ['-port', str(dbElem.getDbPort()),
'-host', host] | 28c8d3dc3b566231aa5e82d04d69d76c434fcf46 | 651,350 |
import torch
import math
def get_rotation_matrix(heading):
"""Get the rotation matrix for the given heading.
Arguments:
heading (float): Rotation in radians.
Returns:
torch.tensor: 2x2 rotation matrix
"""
return torch.tensor([[math.cos(heading), -math.sin(heading)],
... | c58518f40ae9c4483002d32691a3ac2060e35bdf | 651,353 |
def repr_calling(args, kwargs):
"""
Reconstruct function calling code.
"""
li = []
li.extend(repr(a) for a in args)
li.extend('%s=%r' % (k, v) for k, v in kwargs.items())
return ', '.join(li) | dac4771ea4df9a048c63b50ec6c7300f0c6bec6d | 651,356 |
def calc_neighbour_positions(_cell_coord: tuple) -> list:
""" Calculate neighbouring cell coordinates in all directions (cardinal + diagonal).
Returns list of tuples. """
"""Creates and returns coordinates of all cells around the current cell"""
neighbour: list = [
(_cell_coord[0] - 1, _cell_co... | 46b4326f7bfdba17c0c316afeb8c50d829c867e1 | 651,357 |
def tmpdir_repoparent(tmpdir_factory, scope='function'):
"""Return temporary directory for repository checkout guaranteed unique."""
fn = tmpdir_factory.mktemp("repo")
return fn | 90ab3cc6d5484da6cfb9c47de0caf128fa0d6a6a | 651,358 |
def format_includes(includes: list) -> str:
"""Format includes into the argument expected by GCC"""
return " ".join([f"-I{path}" for path in includes]) | eb55d0ed32ade058ce176127d1d695c00f7f373f | 651,359 |
def _get_keystores_object_type(output_type):
"""
Map config type to custom resource cert type
"""
return {
'p12': 'pkcs12',
'jks': 'jks',
}[output_type] | 0b145494321243f58e5264946c7ddc9c27fec984 | 651,362 |
def frame_msg(msg: str) -> str:
"""Frame a message with hashes so that it covers five lines."""
return f"\n###\n#\n# {msg}\n#\n###" | 0575810b1199066bb4e0af12d8bad2a3f536aaf3 | 651,365 |
import webbrowser
import asyncio
async def get_oauth_verifier(oauth_token):
"""
Open authorize page in a browser,
print the url if it didn't work
Arguments
---------
oauth_token : str
The oauth token received in :func:`get_oauth_token`
Returns
-------
str
The PIN ... | 1b1cb399e8ac2070bbf6ad73ed585a19b8cbce2c | 651,366 |
def get_timestamp(imu_dict):
"""The timestamp of a message does not necessarily equal
the timestamp in the message's header. The header timestamp
is more accurate and the timestamp of the message just corresponds
to whenever the bag received the message and saved it.
Args:
imu_dict (dict): ... | 871d9dcfba366c5b30c4261a555874e06de6fe9b | 651,368 |
from typing import Tuple
from typing import Dict
def get_calibrated_plot_fonts(fig_size: Tuple[int, int]) -> Dict[str, float]:
"""
Takes in figure-size (tuple), and returns dictionary containing fontsizes for all other aspects
of the plot (calculated and set appropriately, based on the figure-size).
T... | cf85c46f321e917b1dedd5e035541946d97c0ab3 | 651,373 |
import logging
def get_ctx_options(conf):
"""Gets the appropriate context options for storing test information.
These context options are passed as keyword arguments to methods including
ndb.Key.get(), ndb.Key.put(), ndb.get_multi(), and ndb.put_multi() to control
how various storage methods are used.
Arg... | 7234946a549b7a65f3baf2addf422563d1c86fba | 651,374 |
def is_a_equal_to_b(num1, num2):
"""Predicate function evaluating whether num1 is equal to num2."""
return num1 == num2 | 3bad0c31241821804348f9db44ce968041dabafe | 651,375 |
def stripMetadataFlags(metadataChunk):
"""Strip binary flags from the start of the metadata chunk.
Arguments:
metadataChunk {bytes} -- This refers only to the first metadata chunk. If there are additional ones they won't have any flags.
Returns:
bytes -- Number of metadata chunks, uint8.
bytes -- Rest of t... | 42ccf91fd3e618d0c40b9206c267e331f4e984ee | 651,376 |
import socket
def is_port_available(port: int, host="0.0.0.0"):
"""
Check if a port is available
"""
assert isinstance(port, int)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = True
try:
sock.bind((host, port))
except:
result = False
sock.close()... | 7ecac8160b1e25575e90037f38ae4bcd1213d01d | 651,378 |
def shift_point_by_markersize(axes, x, y, markersize):
"""
Shift overlapping points alonmg x axis by half of the markersize.
This allows to show better plots with errorbars.
"""
inv = axes.transData.inverted()
points = [(i,j) for i,j in zip(x,y)]
pixels = axes.transData.transform(points)
... | fd2e88eee038ef443384b5c520cb30018c9bda47 | 651,380 |
def find_dupes(facts):
"""Find hosts with duplicate SSH host keys from PuppetDB output"""
hosts_by_key = {}
for fact in facts:
hosts_by_key.setdefault(
fact['value'],
set(),
).add(fact['certname'])
return {
k: v
for k, v in hosts_by_key.items()
... | 720efe02ef8295f74d1cb409d93634400118e997 | 651,384 |
def encode_data(data, tokenizer, punctuation_enc):
"""
Converts words to (BERT) tokens and puntuation to given encoding.
Note that words can be composed of multiple tokens.
"""
X = []
Y = []
for line in data:
word, punc = line.split('\t')
punc = punc.strip()
tokens = ... | 7424d07166adeb5a3c8605a31edcd4d2e3e0a24c | 651,385 |
def num_strings(data: bytes) -> int:
"""
return the number of strings in the strings file
Args:
data: strings data from "Strings.txt" file
Returns:
Number of lines in strings output
"""
return data.count(b'\n') | 85c4484bb608567d9463d2e11eff921a9ff4af60 | 651,390 |
import random
def choose_duration(simple=False):
"""Returns a random duration in durk units
Args:
simple (bool, optional): Defaults at False. If True, only considers notes of duration 8 or 16 durks. Otherwise, considers durations in list: [1, 2, 3, 4, 6, 8, 12, 16]
Returns:
int... | 5fdfd3379ec4bb2eb79ea2ff560704e579a95d2c | 651,393 |
import torch
def onehot_coding(target, device, output_dim):
"""Convert the class labels into one-hot encoded vectors."""
target_onehot = torch.FloatTensor(target.size()[0], output_dim).to(device)
target_onehot.data.zero_()
target_onehot.scatter_(1, target.view(-1, 1), 1.0)
return target_onehot | f71a2ac1c6040b0a9d8a91d697a0b6b4c3840996 | 651,395 |
import logging
def init_basic_root_logger(level=logging.INFO):
"""
Initialize the root logger with basic configuration.
"""
logging.basicConfig()
logger = logging.getLogger() # get root logger as default
logger.setLevel(level)
return logger | a989b0e86a4cbccc79fbef73fa2ab968d4b3ca29 | 651,396 |
def _get_fontsize(size_name):
"""Return a fontsize based on matplotlib labels."""
font_sizes = {
"xx-small": 5.79,
"x-small": 6.94,
"small": 8.33,
"medium": 10.0,
"large": 12.0,
"x-large": 14.4,
"xx-large": 17.28,
"larger": 12.0,
"smaller":... | d55c8b5d0f90d360b85a7a5edaa4dd1a13390e49 | 651,399 |
def get_digits(number):
"""Get digits in number from left to right."""
digits = []
while number > 0:
digits.append(number % 10)
number = number // 10
return digits[::-1] | c996131f026c097c7d95e636922108faf8ba3fc4 | 651,400 |
from pathlib import Path
from typing import Optional
from typing import List
def ignore_file(path: Path, patterns: Optional[List[str]]) -> bool:
"""Check if path matches ignore patterns.
:param path: path to compar with ignore pattern
:param patterns: list of glob patterns specifying which paths to ignor... | eef7b9288bcc47e6ca1ca6ae421cf19a67353db7 | 651,401 |
import requests
from bs4 import BeautifulSoup
def umc_web_scraper(map_id):
"""Get static copy of HTML from given url and returns it as HTML soup."""
url = f"http://unfortunate-maps.jukejuice.com/show/{map_id}"
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
return soup | d3518f1986a1efc790bad360051c0d928505f2f0 | 651,402 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.