content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def chocaPared(p,l_pared,l_destructibles,direccion,dx,dy):
"""
True si esta chocando una pared
:param p: Player or Enemy
:param l_pared: List (listas de paredes)
:param direccion: str
:param dx: float
:param dy: float
:return: boolean
"""
(x,y)=p.getcenter()
epsilon=20
if... | 28f6eace7a4d277865c5da94b1f8e26dd3db27ea | 653,958 |
def _get_lut_id(lut, label, use_lut):
"""Convert a label to a LUT ID number."""
if not use_lut:
return 1
assert isinstance(label, str)
mask = (lut['name'] == label)
assert mask.sum() == 1
return lut['id'][mask] | 62df204e0cab53085611c0626b77b6d6bd9d4b5b | 653,959 |
import os
def mkdir(scope, dirname, mode=None):
"""
Creates the given directory (or directories). The optional access
permissions are set to the given mode, and default to whatever
is the umask on your system defined.
:type dirname: string
:param dirname: A filename, or a list of dirnames.
... | 0d01ea2c080eec9f4adc30f51c9232743f70c226 | 653,960 |
def get_queue_arn(sqs_client, queue_url: str) -> str:
"""
Returns the given Queue's ARN. Expects the Queue to exist.
:param sqs_client: the boto3 client
:param queue_url: the queue URL
:return: the QueueARN
"""
response = sqs_client.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["... | 58d980cce90861922c7f02d210ecca27dd8d82dc | 653,961 |
def compute_scaling_dnu(numax, numax_threshold=300, numax_coeff_low=0.267, numax_coeff_high=0.22, numax_exponent_low=0.76, numax_exponent_high=0.797):
"""
Compute the large frequency separation (`dnu`).
This function computes a value of `dnu` from an input `numax` as based on
literature scaling relati... | b8fb922c16c29750e04585dfdad7357773125843 | 653,962 |
def word_doc_freq_map(doc):
"""emit words
Args:
doc (list[string]): one document
Returns:
zip(string, int): emitted words
"""
words = set(doc)
return zip(words, [1] * len(words)) | ffae86353019cc269f3eae670037d88c8448bf51 | 653,963 |
from typing import Counter
def verify_specs_to_include_in_project_generation(ctx, option_name, value):
""" Configure all Specs which should be included in Visual Studio """
if not value:
error = ' [ERROR] - Empty spec list not supported'
return (False, "", error)
spec_list = ... | d69cbf9ed617d720286039350b934113448e5a12 | 653,964 |
import os
import sys
def get_layout(install_root):
"""Returns a dictionary representing the layout of an SDK installation.
For example, the 'bin' key points to the directory which contains the executables under the
given installation root.
Additionally, the installation root is checked to make sure ... | 70dddc069a7278c47a53b9d5986ed579d986eab6 | 653,965 |
def paraxial_focus(separation, z0, focal_length):
"""
Calculates the paraxial focus of a lens given its position, separation
between its two surfaces and the required focal length.
"""
focus = z0 + separation/2 + focal_length
return focus | 99f9367f2bdf388fe872d012df2f8d113d020602 | 653,966 |
import argparse
def parse_args():
"""Parse the command-line arguments and return an argument object."""
parser = argparse.ArgumentParser(description='Dashboard to evaluate the cost of different ML models')
parser.add_argument('-d', '--dataset', help='filepath to dataset, uses Iris dataset if none given')
... | 0cd4feeb4017d6d99b4ed92dfd4470ee4a25f250 | 653,967 |
from typing import Set
def _keep_line(line: str, seqnames: Set[str]) -> bool:
"""Function to decide which lines to keep."""
if not line.strip():
return True
if line.strip() == '//': # End tag
return True
if line.startswith('# STOCKHOLM'): # Start tag
return True
if line.startswith('#=GC RF'): ... | a73adb5e969f9f27061296f4c396bdb9a53ecbfe | 653,968 |
def create_rec_lvl_range(rec_lvl):
"""
gui values:
'Level 1 - blank, I, 4',
'Level 2 & up - M, K, 7, 1, 2',
'Level 3 & up - 3, 8'
"""
default = [" ", "I", "4"]
try:
lvl = rec_lvl[6]
if lvl == "1":
return default
elif lvl == "2":
... | 8b45a1b8acb9cf3d2d53ea58bcd46fce0f343573 | 653,970 |
def filter_by_length(genes, transcripts, min_length):
""" Given a minimum transcript length, this function
- Iterates over transcripts and keeps the ones with length >= min_length
- Removes genes not represented in the transcript set
"""
filtered_transcripts = {}
filtered_genes = {}
... | 534398a957a846adbe7ffde4d472881746b863eb | 653,971 |
def find_review_comment(user_gitee, group, repo_name, pull_id):
"""
Find the review comment for PR
"""
review_key = "以下为 openEuler-Advisor 的 review_tool 生成审视要求清单"
data = user_gitee.get_pr_comments_all(group, repo_name, pull_id)
for comment in data[::-1]:
if review_key in comment['body']:... | 2e351054350743ca00ec968ce6493dc6d620c79a | 653,972 |
from typing import Any
from typing import Awaitable
def make_awaitable(result: Any) -> Awaitable[Any]:
"""
Makes an awaitable, suitable for mocking an `async` function.
This uses Futures as they can be awaited multiple times so can be returned
to multiple callers.
"""
future = Future() # type... | b0d81d56a3d7b6d3dd02d142be096603e16c0fc8 | 653,973 |
def predict(model, data):
"""
Predicts and prepares the answer for the API-caller
:param model: Loaded object from load_model function
:param data: Data from process function
:return: Response to API-caller
:rtype: dict
"""
# return a dictionary that will be parsed to JSON and sent bac... | 2d45bdbecfcb17155cff2f31ff331cf0c1eacb85 | 653,974 |
import re
def get_fig_name(title, tag, legends=[]):
"""Get the name of the figure with the title and tag."""
fig_name = "_".join(re.split("/|-|_|,", title) + legends).replace(" ", "")
return f"{fig_name}_generalization_{tag}.pdf" | a1bb5c3d91eba412ffaca7354b5d663c37de0a46 | 653,975 |
async def command_permissions(ctx):
"""Check | Global Permission Manager
This is attached to all commands.
When a comand is used this function will use the permissions imported
from Permissions.yml to verify that a user is/is not allowed
to use a command.
"""
# Administrators are always al... | fcbc7595b9e493c98168ccb72700c2404827c3af | 653,976 |
import requests
def is_already_blocked(ip, firewall_ip_and_port):
""" This function checks if {ip} is already blocked in the firewall.
:param ip: IP to check.
:param firewall_ip_and_port: URL of firewall wrapper.
:return: True if IP if already blocked on the firewall, False otherwise.
"""
ret... | d698720a1287b27e87d3aacd9fb63defda09e4c3 | 653,977 |
import uuid
def random_container_name():
"""Generate a unique name for the container."""
return uuid.uuid4().hex | 0b2a5c69d199cd1611782f4131d55325b9a5ecb7 | 653,978 |
import tempfile
def make_temp_file(content):
"""Make a temporary file containing C{content} and return a path to it."""
_, fpath = tempfile.mkstemp()
if not hasattr(content, 'decode'):
content = content.encode('ascii')
fd = open(fpath, 'wb')
fd.write(content)
fd.close()
return fpat... | 4bb41256773f9971b6b37224d73013a753d9b287 | 653,979 |
def getFeatureId(feature):
"""
Return the ID of a feature
params:
feature -> a feature
"""
return feature["id"] | 8bdccc4166c67d9076f702d03414cb4f3e4e8a48 | 653,980 |
import sys
def getVersions(obj):
"""Return Revision info for all modules where one of the object's
class and base classes are in.
"""
versions = []
modules = set()
def _add(cls):
try:
if cls.__module__ not in modules:
ver = sys.modules[cls.__module__].__ver... | a7c6031b884e511bdd0445f54a45ac1794a7af11 | 653,981 |
def text_file(tmpdir, random_lines, request):
"""Fixture to produce a random text file."""
encoding = request.param
filename = tmpdir.join('text.{}.txt'.format(encoding)).ensure().strpath
with open(filename, 'wb') as output_file:
output_file.write((u'\n'.join(random_lines) + u'\n').encode(encodi... | deafa8d67c02c74aee00fd2ecb5e5ef13c47408c | 653,982 |
def srwl_uti_proc_is_master():
"""
Check if process is Master (in parallel processing sense)
"""
try:
#resImpMPI4Py = __import__('mpi4py', globals(), locals(), ['MPI'], -1) #MPI module dynamic load
resImpMPI4Py = __import__('mpi4py', globals(), locals(), ['MPI'], 0) #MPI module dynamic l... | 5d813042c1f976f4269aedd2ef4b93ae94e90aee | 653,983 |
def field_name(field):
"""
Produce a clean version of a field's name.
The
:class:`zope.schema.fieldproperty.FieldPropertyStoredThroughField`
class mangles the field name, making it difficult to trace fields
back to their intended attribute name. This undoes that mangling
if possible.
T... | 2f93760c16a605502d0273c1462588b79252c96e | 653,984 |
def remap(degreeinput,degreemin,degreemax,dmxmin=0,dmxmax=65536):
"""
Convert the degree value to a 16 bit dmx number.
"""
DMXvalue = ((degreeinput - degreemin) * (dmxmax-dmxmin) / (degreemax - degreemin) + dmxmin)
return DMXvalue | 31f3d26342f7c5cc08964f2ff0430d51dd5c5672 | 653,985 |
import copy
def bgr2rgb(im):
"""BGR -> RGB.
Input/Return: (..., C).
"""
nc = im.shape[-1]
assert (nc == 1 or nc == 3), 'EXPECTED INPUT FORMAT: (..., C)!'
im = copy.deepcopy(im)
im = im[..., ::-1]
return im | fbdbe235b5dfeb189fb46ab63cdf09bf1f5e4df9 | 653,986 |
import torch
def img2tensor(img, device):
""" Convert numpy.ndarry to torch.Tensor """
img_tensor = torch.from_numpy(img.transpose((2, 0, 1))).float().to(device)
img_tensor = img_tensor.unsqueeze(0)
return img_tensor | b17e9845d51f0c6e1fdade596d035e152ec3cc00 | 653,987 |
import re
def event_item(regex):
"""
Add inner regex grouping for repeating expressions within the event expression result.
"""
def wrap(function):
function.sub_pattern = re.compile(regex, re.IGNORECASE)
return function
return wrap | 15c0695395165864d4487ba8e6458143395895c6 | 653,988 |
def request_x()->int:
"""asks user to provide an integer representing the number of hypernyms to return from controller"""
while True:
try:
x = int(input("Please enter an integer, x, representing how many high order hypernyms\nto return per word: ").strip().lower())
break
... | 16f0032cdc77fe2a98414c2fcfecf2693eb96d9d | 653,989 |
def getObjectTuple(obj1, obj2, obj3, obj4):
"""
@function: getObjectTuple
@description: returns a collection of objects
@param obj1 - first object to be returned
@param obj2 - second object to be returned
@param obj3 - third object to be returned
@param obj4 - fourth object to be returned
... | 2007844c7e7e3c9013e5291b4d379749a370a0b5 | 653,990 |
def chunk_result(future):
"""Returns the results of a processed chunk."""
try:
return future.result()
except Exception as error:
return (error, ) | 13ffd3181bca38c73e87859ed770b00f9ddd0460 | 653,991 |
def string_slice(input_str, search_str):
"""
slices the input string so that the search_str is the beginning of the
returned string. So if you pass in 'hello world' as the first string
and then 'lo' as the second string, this function will return "lo
world'. If you pass in 'foo" as the second strin... | 3d413b899b7b7f4217906e7c700f6e5cc46d8ce9 | 653,992 |
def get_month_delta(date1, date2):
"""
Return the difference between to dates in months.
It does only work on calendars with 12 months per year, and where the months
are consecutive and non-negative numbers.
"""
return date2.month - date1.month + (date2.year - date1.year) * 12 | 0ec1216530dd8172174245156af72ecf620d12f0 | 653,995 |
def notas(*n, sit=False):
"""
-> Função para analisar notas e situações de vários alunos.
:param n: uma ou mais notas dos alunos.
:param sit: valor opcional, para mostrar a situação do aluno.
:return: dicionário com várias informações sobre a situação da turma.
"""
nota = dict()
nota['to... | e19c2ca417770e4ed72ffc087b39a625585a41b1 | 653,996 |
def months_between(date1, date2):
"""
Compare two dates and return the number of months beetween them.
**Parameters**
``date1``
First date for the comparison
``date2``
Second date for the comparison
"""
if date1 > date2:
date1, date2 = date2, date1
m1 = date1.ye... | acc7ad02f2f04dda451853a9dce6402408189e04 | 653,997 |
import re
def is_palindrome(usr_ip):
"""
Checks if string is a palindrome
ValueError: if string is invalid
Returns True if palindrome, False otherwise
"""
# remove punctuations & whitespace and change to all lowercase
ip_str = re.sub(r'[\s.;:,\'"!?-]', r'', usr_ip).lower()
if re.se... | 651330893b24e49f2a0409e7ab0984f7c3f1de7f | 653,998 |
import os
def config_files_to_try(config_file):
"""What config files should we try to read?
Returns a list of tuples:
(filename, is_our_file, was_file_specified)
"""
# Some API users were specifying ".coveragerc" to mean the same as
# True, so make it so.
if config_file == ".coverage... | b4cc2b4334368029e5f740d83d9f9e6556dc2f3b | 653,999 |
import random
def picker(weight=0.75):
"""
weight: the larger the weight, the chances higher elements got picked up.
if weight < 0.5, the lower elements got more chances to be picked up
than higher elements.
"""
def weighted_pick(items):
"""
items: ordered seq... | 1b503e64f46b27a5242d9f0876d8ce871ad2077f | 654,000 |
def dddd(u):
"""Fourth derivative (if available)."""
return u.grad4 | 15c73c160952439e73f1cc89dd3cdfc146f499b8 | 654,001 |
import math
def perturb_coordinates(old_coords, negative_freq_vecs, molecule_perturb_scale, reversed_direction):
"""
Perturbs a structure along the imaginary mode vibrational frequency vectors
old_coords (np.ndarray): Initial molecule coordinates
negative_freq_vecs (list of np.ndarray): Vibrational f... | f7a084aa54f8ddc9ba8f71581f349065566ab702 | 654,002 |
def api_private(_marker_liveapi, _marker_apiprivate, _api_private):
"""BasicKrakenExAPI instance for private API requests and shared call rate limiting.
Guarded against missing markers. Wraps session-scoped `_api_private`.
"""
return _api_private | a50cd752cc01577e24dc6a11ea0d2ff9b9a46ab1 | 654,003 |
import argparse
def _parse_input_arguments():
"""Parse input arguments.
"""
parser = argparse.ArgumentParser(description="Visualize Newton residuals.")
parser.add_argument("filename", metavar="FILE", type=str, help="Newton data file")
parser.add_argument(
"--imgfile",
"-i",
... | e983c14c1edc2cac397d178f2232ddc5f407bc4d | 654,004 |
def _get_deps(meta, section=None):
"""
meta : dict-like
Parsed meta.yaml file.
section : str, list, or None
If None, returns all dependencies. Otherwise can be a string or list of
options [build, host, run, test] to return section-specific dependencies.
"""
def get_name(dep)... | 4b34a88172e806a0682732843e8f14bbb8bf6889 | 654,005 |
def parse_rows(rows):
""" Get data from rows """
results = []
for row in rows:
if row.find('td'):
row_second_column = row.find_all('td')[1]
if row_second_column.get_text():
results.append(row_second_column.get_text().replace("*", ""))
return results | 3eb8437d4a4958c86e2f0ec87d277760ad8afa6c | 654,006 |
def _kwargs_to_props(**kwargs):
"""
Receives `kwargs` and returns them as dict to give easier manipulation
for different methods.
:param kwargs: kwargs
:return: kwargs dict
"""
props = {k: v for k, v in kwargs.items() if v}
return props | 67372e0f96055aeeedebf62203a5be9636e9613c | 654,007 |
def chip_converter(chip):
"""Converts a chip name to usable string."""
chip_map = {
"3xc": "TC",
"wildcard": "WC",
"bboost": "BB",
"freehit": "FH"
}
return chip_map[chip] | 37ad159e2946546717ebce5c0878331a2bede55a | 654,008 |
def baseline_calc_hmean ( SSP1, SSP2, BSL_range, TAT):
""" Calculates measured baseline lengths (harmonic mean sound speed).
It needs:
SSP1 ... sound speed at beacon 1 in metres per second
SSP2 ... sound speed at beacon 2 in metres per second
BSL_range ... measured traveltime in milliseconds
TA... | 2de458102142307993546c4d19cea7520aed5632 | 654,009 |
def spectral_penalty_d_optimal(svs,
already_abs=False,
already_normalized=False,
eps=1e-7):
"""
D-Optimal Regularizer as described in https://openreview.net/pdf?id=rJNH6sAqY7
"""
svs = list(svs.values())
... | 875312ec63fb56b8c27a46da53b22fcd95dbfe15 | 654,010 |
def code_h_format(what):
"""
Converts content of code/pictures history to an html form
Minor Tweak: You can change the html tags however you like.
Another Tweak: Can change the length of displayed history (100 currently)
"""
if len(what) == 0:
return ''
res = '<ul>'
# pick t... | 233fd56003fe0b609afc99bf9062c43682a4c8fa | 654,012 |
def make_content_field(doc):
"""
doc: dict containing clinical trial information
desc: transfers the content of the summary field to the new `contents`
field, if summary exists, otherwise contents field becomes emtpy string
"""
summary = doc['brief_summary/textblock']
doc['contents'] = su... | 76ea12ca4f2fec84ee48395ef29e3af15d5df91f | 654,013 |
def parse_values_in_lines(lines):
"""
Parses the lines for 'A = B' lines and returns a dictionary, as well as the
profile name
"""
values = {}
profile_name = None
for line in lines:
line = line.strip()
if len(line) > 2 and line[0] == '[':
profile_name = line[1:-1]... | 4e7ee62d226e1f052ebcab883b3bf44f98d6ae92 | 654,014 |
def convert_time(t):
"""
converts a time given in seconds to a time in
minutes
:param t: int
:return: string
"""
if type(t) == str:
return t
if int(t) < 60:
return str(t) + "s"
else:
minutes = str(t // 60)
seconds = str(t % 60)
if int(second... | 643e72fe6dc530ffe73aa729b7a96013bd8d27f6 | 654,015 |
def remove_empty_items(v: list) -> list:
"""Remove Falsy values from list.
Sees dicts with all Falsy values as Falsy.
This is used to allow people to submit list fields which are "empty" but are not really empty like:
`[{}, None, {name:"", email:""}]`
Example:
>>> remove_empty_items([{}, N... | 9a3b38b6def088de531160710d58330b024c5b36 | 654,017 |
def Switch(node):
"""
Root of switch/case branch
Args:
node (Switch): Current position in node-tree
Return:
str : Translation of current node.
Children:
Expression Case+ Otherwise?
Expression:
Test-expression
Case:
Case-block
Otherwise:
Otherwise-block
Examples:
... | 538658b3ac8e913a897722f18c3fcfd45cb486b4 | 654,018 |
import re
def trim_id(id, prefix):
"""Remove insignificant characters from the feature ID
If we know the species in a downstream context, in an ID like
"ENSMUSG00000102628", we can infer everything except the "102628".
So we trim the ID to only those significant characters, which yields
a smalle... | 7f773dad15914fdada6b7210f004742e75960e4f | 654,019 |
def command_result_processor_command_uninitialized(command_line_command):
"""
Command result message processor if a command line command is not initialized (should not happen).
Parameters
----------
command_line_command : ``CommandLineCommand``
Respective command.
Returns
-... | dba198925f99cb986eada3cc74050a6f13bfc292 | 654,020 |
import colorsys
def generate_colour(num, count, rotate):
"""Create an RGB colour value from an HSV colour wheel.
num - index from the rainbow
count - number of items in the rainbow
rotate - number between 0 and 1 to rotate the rainbow from its
usual red first, violet last.
"""
h = num / count
h = h + rotate
... | 8709eed4ceb93671cceaf126908dbd2aaf01c374 | 654,021 |
def match_condition(exc_type):
"""Return a function that matches subclasses of ``exc_type``"""
return lambda _exc_type: issubclass(exc_type, _exc_type) | e6899d66fd81c484f9f073141d69fa3acce569c2 | 654,023 |
def rename_file(name: str):
"""
Rename file if concentration is not followed with a space
:param name:
:return: rename
"""
reached_number = False
for i in range(len(name)):
if name[i].isdigit():
reached_number = True
if reached_number:
if name[i] == ' ... | ff06be9cf0ef42475c51a143ac016dddcf78de97 | 654,026 |
import traceback
def create_books_table(cur):
"""creates books table
Returns boolean"""
pass_status = False
sql = """CREATE TABLE books(bookId int,
title varchar(1000),
authors varchar(1000),
average_rating real,
isbn varchar(100),
isbn_1... | 34f1a59efaec1a2fc036503a0708a78d5213954c | 654,027 |
import requests
def get_from_nist(url,destinationfile):
""" copy the file from NIST NVD site
"""
print('Downloading %s' % destinationfile)
data = requests.get(url)
with open(destinationfile, 'wb') as f:
f.write(data.content)
return True | cf1c574f43d5d49faf3091252b26a1bb0b3ee48b | 654,029 |
from typing import Any
def create_property(attr: str, default: Any, type_annotation: type) -> property:
"""Return a property descriptor given config attribute."""
def fget(self) -> Any:
if attr in self._env_overrides:
return self._env_overrides[attr]
if attr in self._config:
... | d7359b49a666e8826797d297e6642bd0736a0191 | 654,030 |
def wrapGrowthRatioDiv(value, MoM, YoY):
"""
Wrap the growth ratio into grids
MoM: month on month growth ratio
YoY: year on year growth ratio
"""
return "<div style='width:50%'>"+value+\
"</div><div style='width:50%'><table><tr><td>"+MoM+ \
"</td></tr><tr><td>"+YoY+"</td>... | 6977d42d1475ae0deeea8a2ce2a32bc0c9acc456 | 654,031 |
import re
def _update_card_text(text, lang='English', skip_rules=False, # pylint: disable=R0915
fix_linebreaks=True):
""" Update card text for RingsDB, Hall of Beorn and Spanish DB.
"""
text = str(text)
if lang == 'Spanish' and not skip_rules:
text = re.sub(r'\b(Resoluci... | eff3ceeb62865e54feb3c1ce77d7e92c870897a6 | 654,033 |
import re
def check_symbols(value):
"""
Checks if an string has symbols
:param value: String to be checked
:type value: String
:returns: True if there are symbols in the string
:rtype: Boolean
Examples:
>>> check_symbols('Lorem ipsum')
True
>>> check_... | 364cf64c135c80c7e6a5b70ab8dd07aa2e368c8c | 654,034 |
import re
def snake2camelback(snake_dict: dict):
"""Convert the passed dictionary's keys from snake_case to camelBack case."""
converted_obj = {}
for key in snake_dict.keys():
converted_key = re.sub(r'_([a-z])', lambda x: x.group(1).upper(), key)
converted_obj[converted_key] = snake_dict[k... | 6da0cdb40712a2ea0539fe520bb8164254dc04a8 | 654,035 |
import tarfile
import os
def get_archive_top_dir(path):
"""Return first top level folder name in given archive or raises RuntimeError"""
with tarfile.open(path) as tar:
first = tar.next()
if not first is None:
result = os.path.dirname(first.path)
if len(result) == 0:
... | 8bebec9cbb5077e795d6c2174ddd42d805fe1f64 | 654,036 |
def get_type(mal, kitsu_attr):
"""
Get the type of the weeb media.
:param mal: The MAL search result.
:param kitsu_attr: The attributes of kitsu search result.
:return: the type of the weeb media
"""
mal_type = mal.get('type')
if mal_type:
return mal_type
show_type = kitsu_a... | b98d026d0b2b6de6daa5fb9e713bd640c43c1fd4 | 654,037 |
def get_dist_prob_suc(t1, t2, w1, w2, decay_factor):
"""
Get p_dist
"""
return 0.5 + 0.5 * w1 * w2 * decay_factor | cf43cc63cdf029b574ad3aa9a5d6d2ce0d1b1f2f | 654,038 |
def get_extension(filename: str, default_extension="py") -> str:
""" Get a file's extension (assumed to be after a period) """
if not filename:
return default_extension
return filename.lower().split(".")[-1] | 7336fac7c77cade12d79664b4088b4ecf0108e0a | 654,039 |
def char_to_info(kind):
"""
How to represent entry in gopher directory in control column.
"""
return {'i': " ",
'0': "TEXT ",
'1': " DIR "}.get(kind, "?[{}] ".format(kind)) | 2772386a8b9bfd42e8d2d68840fcb5e814db9123 | 654,041 |
def fix_tuple_length(t, n):
"""Extend tuple t to length n by adding None items at the end of the tuple. Return the new tuple."""
return t + ((None,) * (n - len(t))) if len(t) < n else t | f21316b5c87052407a0b8cc240231c5b129aa51c | 654,042 |
def url(context, link_url):
"""
Get the path for a page in the Cactus build.
We'll need this because paths can be rewritten with prettifying.
"""
site = context['__CACTUS_SITE__']
url = site.get_url_for_page(link_url)
if site.prettify_urls:
return url.rsplit('index.html', 1)[0]
... | 977303df8a977a5257f4f4eaec63decd42612c7e | 654,043 |
def parse_coords(coord_str):
"""Parse a line like <x=1, y=2, z=-3> into [1, 2, -3]"""
coords = coord_str.strip('<>\n').split(',')
return [int(coords[x].split('=')[1]) for x in range(0, 3)] | c13c887fffa24deba81a176ee12532a05ad23e5f | 654,044 |
def extract_opaque_struct(fd):
""" Extracts a list of opaque structures from a file. """
source = fd.readlines()
structs = []
while len(source) != 0:
line = source[0]
if line == '#ifdef OPAQUE\n':
end = source.index("#endif\n")
structs.append("\n")
st... | a3613eb201bbddbaa9fdd3b6f472be5807835030 | 654,045 |
def wave_dir(theta):
"""Wave direction failure function."""
if theta < 60.0:
return 1
else:
return 0 | 0ee1acbd5e299c99561d2b466ba9e62f3d2ac813 | 654,046 |
def replace(str,start,end,ss):
"""
将[start:end](包括start和end)替换为ss
:param str:
:param start: int
:param end: int
:param ss:
:return:
"""
return str[:start]+ss+str[end:] | 514add3551d822467741347f180658a6de900c9c | 654,047 |
def wrap_check_stop(l, stop):
"""Check that stop index falls in (-l, l] and wrap negative values to l + stop.
For convenience, stop == 0 is assumed to be shorthand for stop == l.
"""
if (stop <= -l) or (stop > l):
raise IndexError('stop index out of range')
elif stop <= 0:
... | e1d6fd412240c98ede2b6c421c2154f91e7c5678 | 654,048 |
def snake_to_camel_case(s):
"""
Converts strings from 'snake_case' (Python code convention)
to CamelCase
"""
new_string = s
leading_count = 0
while new_string.find('_') == 0:
new_string = new_string[1:]
leading_count += 1
trailing_count = 0
while new_string.rfind('_... | f4d11323af7d34d600a45231cbe72c76a7c33115 | 654,049 |
from datetime import datetime
import os
def get_salt_cloud_log_file(stack, suffix):
"""
suffix is a string (e.g, launch, overstate, highstate, error, etc)
"""
# Set up logging for this launch
root_dir = stack.get_root_directory()
log_dir = stack.get_log_directory()
now = datetime.now().st... | 1798f4bdba68672e98d4d5d4ccdde9ba56ba2adb | 654,050 |
def calculator(a, b, op):
""" Compute operation on passed values"""
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
return round( a / b, 3 )
elif op == "%":
return a % b
else:
print("Invalida... | c58f98fbf6d8944af66edd260eb8d60b69ff7cf9 | 654,051 |
def _hookitems(ui, _untrusted=False):
"""return all hooks items ready to be sorted"""
hooks = {}
for name, cmd in ui.configitems(b'hooks', untrusted=_untrusted):
if (
name.startswith(b'priority.')
or name.startswith(b'tonative.')
or b':' in name
):
... | 9cdbccecb9d148a019fcea511da2910ced77445d | 654,052 |
import struct
import re
import platform
def interpreterBits():
# type: () -> int
"""
Returns the number of bits of the architecture the interpreter was compiled on
(ie, 32 or 64).
Returns
-------
int
"""
# NOTE: platform.architecture()[0] returns '64bit' on OSX 10.6 (Snow Leopard)... | 086ddf70723a817f0f9caf45173ccb3d45226ce7 | 654,053 |
def eulers_richardson_method(f, dx, y, yp, range, return_yp = False):
""" The Eulers Richardson method for solving a differential equation of second
order. Works by taking the Euler method, but uses the average values instead.
This produces a better approximation to the solution faster (in theory) than
... | 587106bc19b116b6bed6c32565e3f5a0e56dfdd6 | 654,055 |
def url_is_secure(data):
"""
=> Check if the passed in url is a secure
url
=> based on whether the url starts with https or https://
"""
return data.startswith("https://") | 69187e9ac7717cf78e09190c563e202073d14750 | 654,057 |
import json
def get_key(path=".keys/AES.key"):
"""
Load key from .keys/AES.key file
:param path: file path
:type path: String
:return: key
:rtype: bytearray
"""
with open(path, 'r') as f:
k = json.load(f)
return bytearray.fromhex(k["key"]) | fb653d3447629c3b50974f3aad2170ea4af50e79 | 654,058 |
def age(age: float) -> str:
"""
Given a QuestionnaireResponse *item*, returns the first age value as a float
in years.
"""
return f"{age} years" | f3ea64a8141e98df0d29588183dcb1be6a128e42 | 654,059 |
def yearmonthplusoffset(year, month, offset):
""" calculate new year/month from year/month and offset """
month += offset
# handle offset and under/overflows - quick and dirty, yes!
while month < 1:
month += 12
year -= 1
while month > 12:
month -= 12
year += 1
ret... | c26ed20bf71777b3c2773a77384c49eb53577f02 | 654,060 |
import os
import zipfile
def GetMappingFromOffset(mapping, app_symboldir):
"""
If the input mapping is a zip file, translate the contained uncompressed files and add mapping
entries.
This is done to handle symbols for the uncompressed .so files inside APKs. With the replaced
mappings, the script looks up t... | 476dd67fd7644e99583f9f32701cc99fac4742b9 | 654,061 |
import math
def relevant(points, error=1e-3):
"""Remove irrelevant vertices of linear spline.
Parameters
----------
points : list of 2-tuple
Vertices of linear spline.
error : float, optional
Tolerated deviation from original spline.
Yields
------
2-tuple
Rele... | d0e852849103ac7ab008fd207b17e9788f7029d7 | 654,062 |
def to_one_liner(text: str, max_length: int = 75):
"""Truncates a string to a single line for logging"""
one_liner = " ".join(text.split("\n"))
if len(one_liner) > max_length:
one_liner = f"{one_liner[:max_length-1]}…"
if not one_liner:
one_liner = "<empty>"
return one_liner | 2ff16ea3de8ce053f734cc29e4ed1b6b7e8aaf8c | 654,063 |
def validateDir(value):
"""
Validate direction.
"""
msg = "Direction must be a 3 component vector (list)."
if not isinstance(value, list):
raise ValueError(msg)
if 3 != len(value):
raise ValueError(msg)
try:
nums = map(float, value)
except:
raise ValueError(msg)
return value | 214bc1f8c5833c8db8cb1a0cbe544b0d3330ccc5 | 654,064 |
def human_format(num, precision=2):
"""Return numbers rounded to given precision and with sensuous suffixes.
Parameters
==========
num : float
The number to humanify.
precision : int, default : 2
Number of decimal places.
Return
======
s : String
Human readable ... | 99888181e53021a674db5ed102526d5481941205 | 654,065 |
def load_cws_sentences():
"""测试分词效果的句子"""
texts = []
texts.append("守得云开见月明")
texts.append("乒乓球拍卖完了")
texts.append("无线电法国别研究")
texts.append("广东省长假成绩单")
texts.append("欢迎新老师生前来就餐")
texts.append("上海浦东开发与建设同步")
texts.append("独立自主和平等互利的原则")
texts.append("黑天鹅和灰犀牛是两个突发性事件")
texts.app... | 049f39afc468a49250979c219b56659036770a96 | 654,066 |
def total_slices(num_pizzas, slices_per_pizza):
""" (int, int) -> int
Return the total number of slices in num_pizzas pizzas that each have slices_per_pizza slices.
>>> total_slices(2, 30)
60
>>> total_slices(1, 8)
8
"""
return num_pizzas*slices_per_pizza | 21e09edf99e14539083b8506a844ec9ec2ce79c8 | 654,067 |
def _get_pgsql_command(name, host="localhost", password=None, port=5432, user="postgres"):
"""Get a postgres-related command using commonly required parameters.
:param name: The name of the command.
:type name: str
:param host: The host name.
:type host: str
:param password: The password to u... | b7e44bd38cd153051ea2f9c6e04690a95f8f2c6d | 654,068 |
import os
import json
def store(fakes, directory="fixtures/datagen/synthetic"):
"""
Save `fakes` dictionary to a new directory (create if not exists)
Each file should be the name of the fakerized uuid
Return the path
"""
if not os.path.exists(directory):
os.makedirs(directory)
for... | 9b04a0af67378a6a84a332e4b60c53f04cb7b8c7 | 654,069 |
def compute_predictions(input_ids,
model,
attention_masks=None,
# device="cuda"
):
"""
Compute the prediction for given input_ids, model and attention masks
This function returns numpy arrays of labels and probabilities associated with that label
:param input_ids:
:param model:
:param atte... | a1bd848858adde3af3bc38569ed5716a94464082 | 654,070 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.