content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def query(db):
"""
This function specify the query for the select query
"""
query = db.org_organisation.organisation_type_id == db.org_organisation_type.id
return query | da14331926709a4bda616fbf30dc65b45f3cf089 | 44,075 |
import binascii
def _wrap_base64(data, wrap=64):
"""Break a Base64 value into multiple lines."""
data = binascii.b2a_base64(data)[:-1]
return b'\n'.join(data[i:i+wrap]
for i in range(0, len(data), wrap)) + b'\n' | 9d07d6c757d10212c0f11be67452f1779b07e19e | 44,076 |
def create_query_token_func(session, model_class):
"""Create an ``query_token`` function that can be used in
resource protector.
:param session: SQLAlchemy session
:param model_class: TokenCredential class
"""
def query_token(client_id, oauth_token):
q = session.query(model_class)
... | a25d876ef1dd5f7548741f27e584724f27447506 | 44,077 |
def check_parsed_args_compatible(imp, modules, contact, cc, parser):
"""
Check that the combination of arguments are compatible.
Args:
imp(str): CSV import specifier
modules(str): Modules argument
contact(str): Contact argument
cc(str): CC argument
parser(:class:`arg... | 36778436b4ed03c3de2e45e77f9e70021ac7b8f6 | 44,078 |
def mod(p):
"""
Compute modulus of 3D vector
p: array
Cartesian coordinates
"""
return (p[0]**2 + p[1]**2 + p[2]**2)**0.5 | a15755be4e49120fa323ece0e456ae947d826b6d | 44,081 |
def sum_diagonals(side_length):
"""Sums diagonals of a number spiral with given side length."""
total = 25
bottom_corner = 3
for s in range(5, side_length+2, 2):
bottom_corner += 4*s - 10
for c in range(4):
total += bottom_corner + (s-1)*c
return total | 7b202579e3b7f6105e04d1b8697adcd35788d3ea | 44,082 |
import numpy
def construct_VHS_incore(system, xshifted, sqrt_dt):
"""Construct the one body potential from the HS transformation
Parameters
----------
system :
system class
xshifted : numpy array
shifited auxiliary field
Returns
-------
VHS : numpy array
the HS ... | 58cd9fa10708ec285b6c5c6998695bb18dc137b9 | 44,083 |
def get_weight_of(level: int) -> int:
"""Return the weight of a given `level`. The ratio is 1:3:5 for
modules of L4:L5:L6 respectively."""
levels = {4: 1, 5: 3, 6: 5}
return levels[level] if isinstance(level, int) and level in levels else 0 | 3eefdffdf828df8f5d2454ea56da075281400cf7 | 44,084 |
def formatter(ms):
"""
formats the ms into seconds and ms
:param ms: the number of ms
:return: a string representing the same amount, but now represented in seconds and ms.
"""
sec = int(ms) // 1000
ms = int(ms) % 1000
if sec == 0:
return '{0}ms'.format(ms)
return '{0}.{1}s'.... | 3d66257672d4df906581ca6cf79c808fd9e8d3ef | 44,086 |
def form_binary_patterns(k: int) -> list:
"""
Return a list of strings containing all binary numbers of length not exceeding 'k' (with leading zeroes)
"""
result = []
format_string = '{{:0{}b}}'.format(k)
for n in range(2 ** k):
result.append(format_string.format(n))
return result | c13cb7e9cd831e85cc5fde6ef8497ec45289664d | 44,087 |
def containsZero(n):
"""
n: an int or a str
output: True if n contains '0'
"""
numStr = str(n)
for letter in numStr:
if letter is '0':
return True
return False | e8698f6ba935079ecdb37adbdeb88b61edf9d640 | 44,090 |
import calendar
import time
def timestamp():
"""Returns Unix Timestamp of curret UTC time"""
return calendar.timegm(time.gmtime()) | 9ba82ae0223130367196976b2b54430fa18762a1 | 44,091 |
def produit(a,b):
""" renvoie le résultat de la multiplication des nombres a et b"""
return a*b | 866d4561edd2b2168ca167ff7116241c0fff310c | 44,092 |
def extract_hairpin_name_and_sequence(file,sampleName):
"""
Reads one MIRNA cluster file
It returns the corresponding cluster name and hairpin sequence in a Python dictionary
Dictionary keys: cluster names
Dictionary values: cluster sequences
"""
with open(file,"r") as filin:
lines =... | ea6c189a2b38822c08097ce77088f644c7b0c489 | 44,093 |
def _max_len(choices):
"""Given a list of char field choices, return the field max length"""
lengths = [len(choice) for choice, _ in choices]
return max(lengths) | 2042ff1466554abc2cbfdb6fc0faff664759ac55 | 44,094 |
def load_keywords(kw_file, lex):
""" load keywords """
kwords = []
orig_kwords = []
with open(kw_file, "r", encoding="utf-8") as fpr:
for line in fpr:
parts = line.strip().split()
# check if its in two column format or single column
if len(parts) == 2:
... | cbcb099888c15fdd72745558fefa5b90321198a6 | 44,095 |
def CommandLine(command, args):
"""Convert an executable path and a sequence of arguments into a command
line that can be passed to CreateProcess"""
cmd = "\"" + command.replace("\"", "\"\"") + "\""
for arg in args:
cmd = cmd + " \"" + arg.replace("\"", "\"\"") + "\""
return cmd | dfb7de2d1a72a007c9d120a27de5078d407f947d | 44,096 |
import torch
def reflect(v: torch.Tensor, axis: torch.Tensor):
"""reflect vector a w.r.t. axis
Args:
`v`: tensor of shape `[...,3]`.
`axis`: tensor with the same shape or dim as `a`.
Returns:
the reflected vector
"""
axis = torch.broadcast_to(axis, v.shape)
h_vec = 2*ax... | 92dface741eb36a9c2b889091c1f3b1275fcdc68 | 44,097 |
def findPermutation(permMat):
"""
In so far as permMat is a permutation matrix, returns the permutation.
"""
maxs = [(vec.tolist().index(max(vec)), max(vec)) for vec in permMat]
mins = [(vec.tolist().index(min(vec)), min(vec)) for vec in permMat]
for ii in range(len(maxs)):
if maxs[ii][1... | 7367b178fb742f66a8a39d7e6bc2bd725a6d5f70 | 44,098 |
def _delete_enhancement_git_data(enhancement):
"""Deletes the base GitHub data fields form an enhancement dictionary.
Parameters:
enhancement - The enhancement dictionary from which the GitHub data
fields should be deleted. This dictionary must contain
th... | 16745d6cb1d001278feb7b72609d843b73319166 | 44,099 |
def comp_surface_magnet(self):
"""Compute the surface of the Hole
Parameters
----------
self : HoleMLSRPM
A HoleMLSRPM object
Returns
-------
S: float
Surface of the Magnet. [m**2]
"""
point_dict = self._comp_point_coordinate()
Z3 = point_dict["Z3"]
Z4 = p... | 963d104794fcee3bca3272e62f8c1ba9be4c0c57 | 44,100 |
def to_nested_dict(d, delim='.', copy=True):
"""TLDR;
flat: {"a.b.c":0}
# pop 'a.b.c' and value 0 and break key into parts
parts: ['a','b','c']:
# process 'a'
flat <- {'a':dict()}
# process 'b'
flat <- {'a': {'b': dict()}}
# process 'c' @ tmp[parts[-1]] = val
flat <- {'a': {'b... | 12fd3be0869567b7fc3fce7ca9f3d2933b08eacc | 44,102 |
import random
import string
def get_random_string(length=10):
"""Get a string with random content"""
return ''.join(random.choice(string.ascii_uppercase) for i in
range(length)) | 5befd55c6f1cfa3bea941acb5f25048e56fd79ed | 44,103 |
def _convert_line_to_tab_from_orifile(line):
"""
:param line:
:return:
>>> _convert_line_to_tab_from_orifile('''IMG_1468832894.185000000.jpg -75.622522 -40.654833 -172.350586 \
657739.197431 6860690.284637 53.534337''')
['IMG_1468832894.185000000.jpg', '... | 2e5343da7673c9897d97ae29003a8f4fa29c78a4 | 44,104 |
import torch
def get_ja(arr):
"""
calculates jaw aperture (euclidean distance between UL / J (LI)):
pertinent indexes:
Jx : 6, ULx: 10, Jy : 7, ULy : 11
"""
return torch.sqrt((arr[:,6]-arr[:,10])**2+(arr[:,7]-arr[:,11])**2) | 14b23e9e2eaead1a8a2ff4eb305107a909fbb419 | 44,105 |
def is_ranged_value(value, min_value=None, max_value=None,
min_inclusive: bool=True, max_inclusive: bool=True) -> bool:
"""
Parameters
----------
value : float
float : the value as a float
min_value / max_value : float / None
float : the constraint is active
... | 217400c434b04591ec4155d6a3408ad42f497104 | 44,107 |
def get_dynamic_edgelist(data):
""" Make an edge list for all of the sequential visits of one site to the next
in a day per user. Each edge is directed. There is a dummy start node to
indicate the transition from being home to the first site visited that day """
data['total_people'] = 1
... | 36502d125ba10cb25ea15873c4925ff17d0afa8a | 44,108 |
def linear_segment(x0, x1, y0, y1, t):
"""Return the linear function interpolating the given points."""
return y0 + (t - x0) / (x1 - x0) * (y1 - y0) | de8bb06a7b294e0f0eb62f471da553a58e65fc49 | 44,109 |
from datetime import datetime
def now() -> str:
"""Return string timestamp for current time, to the second."""
return datetime.utcnow().isoformat(timespec='seconds') | 7a4b10b224398ad532137807b320ad404a7873ff | 44,110 |
import os
import subprocess
def _command_exists(command_name: str) -> bool:
"""Checks if a command exists in the environment."""
check_cli = os.name == 'nt' and 'where' or 'which'
result = subprocess.run(
[check_cli, command_name],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNU... | 8dec4ba2b99844cac191a71f3b5bba2fc1fd97a1 | 44,111 |
from typing import Any
from typing import Union
from typing import List
from typing import Sequence
def _list_convert(x: Any) -> Union[Any, List[Any]]:
"""Converts argument to list if not already a sequence."""
return [x] if not isinstance(x, Sequence) else x | 79a913305a931378e2cb2b8f46a74f1381850ac4 | 44,112 |
def p_value_stars(p_value):
"""
Returns the appropriate number of stars for the p_value
:param p_value: p_value
:type p_value: int
:param output_path: path to output directory
:type output_path: str
"""
if p_value < 0.0001:
return "****"
elif (p_value < 0.001):
retur... | 06ca876bf28933749186f06b760a1518a24d483f | 44,113 |
def title(value):
""" Title cases a string, replacing hyphens with spaces """
return value.replace('-', ' ').title() | ce5276225e46adc7fbe6b3dda62c80dd5580cbfd | 44,115 |
from typing import Iterable
from typing import List
def make_error_col_names(qcols: Iterable) -> List:
"""helper func to make error column names of the form
<col_name>_low ... <col_name>_high
Args:
qcols (iterable): an iterable of column names used for matching
Returns:
list: list of e... | 9bee77236b4d381d69b4359bdf0a319b06ac8285 | 44,117 |
import os
def os_parityPath(path):
"""
Converts unix paths to correct windows equivalents.
Unix native paths remain unchanged (no effect)
"""
path = os.path.normpath(os.path.expanduser(path))
if path.startswith('\\'):
return 'C:' + path
return path | 4bb2aaebb2cb6806101360337599c01c85fc1d41 | 44,118 |
import copy
def add_node_to_path(node, path):
"""
Adds the name of the node to the copy of the list of strings inside the
safely copied version of the path.
Leave the other two items in path unchanged (total distance traveled and
total number of buildings).
Parameters:
path: li... | 9c7868a6a2c4df1161a1ed46f7f92bb887171269 | 44,119 |
def create_label_cleaner(metadata_raw):
"""Use metadata to Create dict that maps default column name
to human-readable column name."""
occupied_labels = {}
for label in metadata_raw.split("\n")[278:547]:
variable = label.replace("label variable ", "").split(" ")[0]
name = label.split('"... | 16e40dba50ce90915637c7269acb5427ec7cb727 | 44,120 |
def get_div(value, start):
"""Returns the maximum divider for `value` starting from `start` value"""
div = 1
for d in range(start, 0, -1):
if (value % d) == 0:
div = d
break
return div | f483a3fcdc31eba37b17ac7f106bcea28ea84511 | 44,121 |
def pack_str(var):
"""Convert a string to a list of bytes."""
return str(var).encode("utf-8") | ba620b2a82f99e9accf198a211c7b71406f391fe | 44,122 |
import os
def running_on_ci(): # no cov
# type: () -> bool
"""If the system is running on a CI platform."""
if os.environ.get('CI') or os.environ.get('TRAVIS') or os.environ.get('GITHUB_ACTIONS'):
return True
return False | 42ed338e1dd129bee011a7f21fadae96f828be35 | 44,123 |
def userInputToNumber():
"""returns a float, the product of the two user inputs"""
an_int = int(input("please input an integer: "))
a_float = float(input("please input a float: "))
return an_int * a_float | 5cb913bb2fcb5220e9fdb547bb6822692a0de885 | 44,126 |
def parse_rc_ns(rrset):
"""解析出域名的NS集合"""
ns = []
domain = ""
r = str(rrset.to_text())
for i in r.split('\n'):
i = i.split(' ')
rc_type, rc_ttl = i[3], i[1]
if rc_type == 'NS':
ns.append((i[4][:-1]).lower())
domain = i[0][:-1]
ns.sort()
return d... | 47c66bb2f65f24e84bcbaebcda070d326b444747 | 44,127 |
import operator
def hamming_distance(s1, s2, equality_function=operator.eq):
"""
Returns the hamming distance between two strings.
"""
if not len(s1) == len(s2):
raise ValueError("String lengths are not equal")
# Number of non-matching characters:
return sum(not equality_function(c1, ... | f5fd74d3eb6c33f0a51dc5b61158d4f6e51e6b9e | 44,128 |
import os
import json
def get_format_dict(cogs_dir):
"""Get a dict of numerical format ID -> the format dict."""
if (
os.path.exists(f"{cogs_dir}/formats.json")
and not os.stat(f"{cogs_dir}/formats.json").st_size == 0
):
with open(f"{cogs_dir}/formats.json", "r") as f:
... | d687da9f2f179bb2772b0811c80dc0744fbc66d6 | 44,129 |
import six
def iterable(obj, strok=False):
"""
Checks if the input implements the iterator interface. An exception is made
for strings, which return False unless `strok` is True
Args:
obj (object): a scalar or iterable input
strok (bool): if True allow strings to be interpreted as it... | 7a9e4a835eb1eb5034fba4a7083e38994a2535b3 | 44,130 |
import re
def remove_repeated_strings(text):
"""Removes strings that are identical and consecutive (repeated
more than 3 times).
Args:
text (string): markdown text that is going to be processed.
Returns:
string: text once it is processed.
"""
# Repeated strings
repeated_strings_regex = re.compile(r'([^#... | be64c413aefdc5ca104d9e7e27466f09094c9d47 | 44,132 |
def annotation2rgb(i,palette,arr):
"""Go from annotation of patch to color.
Parameters
----------
i:int
Annotation index.
palette:palette
Index to color mapping.
arr:array
Image array.
Returns
-------
array
Resulting image.
"""
col = palette[i]
for i in range(3):
arr[...,i] = int(col[i]*255)
r... | 7fa9de356f27fadf72a6fe71a3ad63c70d9f0a48 | 44,133 |
def fig_path(path, *specs, suffix='.png'):
"""Get output path for figure."""
stem = '-'.join((path.stem,) + specs)
return (path.parent / stem).with_suffix(suffix) | 64c7d2205f08b098d8eaeefa494fe5282cab01e6 | 44,135 |
def copy_candidates(from_alias, to_alias, alias2qids, max_candidates=30, qids_to_add=None):
"""This will copy the candidates from from_alias to to_alias. We assume to_alias does not exist and from_alias does exists.
qids_to_add will be added to the beginning of the candidate list to ensure they are among the to... | 23835e2e99d1c663d0be1504575abe588741355e | 44,136 |
import random
def _rnd():
"""
"""
return random.randint(0, (2**32)) | 4041329e9739844e9da04a06341edb9d7dd2e4e5 | 44,138 |
from typing import Callable
from typing import Optional
from typing import Tuple
def then_parser(
first_parser: Callable[[str], Optional[Tuple[str, str]]],
second_parser: Callable[[str], Optional[Tuple[str, str]]],
text: str,
) -> Optional[Tuple[str, str]]:
"""
Uses one parser on the text,
then uses the next pa... | 7604deaed51af9177661defe5e62a13766a77065 | 44,139 |
import pickle
def load_investment_results(iteration):
"""Load investment results"""
with open(f'output/investment_plan/investment-results_{iteration}.pickle', 'rb') as f:
results = pickle.load(f)
return results | 93700e58b9db2c36ff5da9203ba1eeae9c7e4d84 | 44,141 |
def _translate_backupjobrun_summary_view(context, backupjobrun):
"""Maps keys for backupjobruns summary view."""
d = {}
d['id'] = backupjobrun['id']
d['created_at'] = backupjobrun['created_at']
d['status'] = backupjobrun['status']
return d | 3cf0394aff3191ab2db69f29f4052411f90c572b | 44,142 |
def inbreeding_as_dispersion(inbreeding, unique_haplotypes):
"""Calculate dispersion parameter of a Dirichlet-multinomial
distribution assuming equal population frequency of each haplotype.
Parameters
----------
inbreeding : float
Expected inbreeding coefficient of the sample.
unique_ha... | 3d57f8a31a82ad0effa8c12b7b69f36729a02c64 | 44,143 |
def add_startxref(article, pos_index):
""" """
o_num, o_gen, o_ver = article['o_num'], article['o_gen'], article['o_ver']
xref = article['content']
ret = ''
ret += f'<div id="obj{o_num}.{o_gen}.{o_ver}">\n<pre>\n'
ret += f'startxref\n'
if xref == 0:
ret += f'0\n'
else:
re... | 5dc8cbf91dfd4095fae65b5d33566de8cb736779 | 44,144 |
def josephus(n, k):
""" Function that calculates the last person location
of the josephus problem
Args:
n(int): number of people in circle
k(int): step rate
Returns:
int: index value of the winner
"""
# special case, k = 1
if k == 1:
return n - 1
# ... | 1b4923b5168738e22d1cfe4820251f4a1a05e063 | 44,145 |
import six
import re
from datetime import datetime
def convert_to_python(data):
"""Convert raw data (e.g. from json conversion) into the appropriate
Python objects"""
if isinstance(data, six.string_types):
# Dates
if re.match(r'^\d{4}-\d{2}-\d{2}$', data):
return datetime.str... | e5a7f3e06fbcc056384d77b4731cfa0704a1d641 | 44,146 |
def _pitch2m(res):
"""Convert pitch string to meters.
Something like -600- is assumed to mean "six-hundreths of an inch".
>>> _pitch2m("-600-")
4.233333333333333e-05
>>> _pitch2m("-1200-")
2.1166666666666665e-05
"""
res = int(res[1:-1])
return 0.0254 / res | a7fa2acaf8bbbf647bda3a35acfd5aad370df7f3 | 44,147 |
async def qr():
"""
words:二维码内容,链接或者句子
version:二维码大小,范围为[1, 40]
level:二维码纠错级别,范围为{L, M, Q, H},H为最高级,默认。
picture:自定义二维码背景图,支持格式为.jpg,.png,.bmp,.gif,默认为黑白色
colorized:二维码背景颜色,默认为False,即黑白色
contrast:对比度,值越高对比度越高,默认为1.0
brightness:亮度,值越高亮度越高,默认为1.0,值常和对比度相同
save_name:二维码名称,默认为qrcode.png
... | 1c05750eadc2a2039e08a5df51436f61c390f75b | 44,148 |
def tmp_bdb_root(mocker, tmp_path):
"""Set a temporary root directory for the BerkeleyDB minter hierarchy.
By default, a BDB path resolved by the minter will reference a location in EZID's
minter hierarchy, as configured in the EZID settings. Currently, `ezid/db/minters`.
This fixture causes BDB paths ... | 36803584568992b2c68fb32eb810bb6ea2ede91d | 44,149 |
def parse_csv(columns, line):
"""
Parse a CSV line that has ',' as a separator.
Columns is a list of the column names, must match the number of
comma-separated values in the input line.
"""
data = {}
split = line.split(',')
for idx, name in enumerate(columns):
data[name] = split[... | ff42251c5be595cc749ccc91d419e2ef105b9b49 | 44,150 |
import os
def git_pip_link_parse(repo):
"""Return a tuple containing the parts of a git repository.
Example parsing a standard git repo:
>>> git_pip_link_parse('git+https://github.com/username/repo@tag')
('repo',
'tag',
None,
'https://github.com/username/repo',
'git+ht... | 41212113c677df3163c3c0a18064da2b73c84fd2 | 44,151 |
import torch
def remove_zeros_from_traj(traj):
"""
Remove the start of the trajectory, if it only contains zeroes, while always keeping the last instant. This is
especially useful for when the trajectory consists of relative displacements (or velocities), because it removes
'redundant' instants where ... | dd913becb0880fc29feda886d096f28cc6322cec | 44,152 |
def armstrong(some_int: int) -> bool:
"""
Accepts an int
Returns whether or not int is an armstrong number
:param some_int:
:return:
"""
string_rep = str(some_int)
sum_val = 0
for digit in string_rep:
sum_val += int(digit) ** 3
return some_int == sum_val | dd0c2b3533e77c29330d750826b328c2b33b2460 | 44,153 |
def _get_slash_or_null_from_proto(proto):
"""Potentially returns empty (if the file is in the root directory)"""
return proto.path.rpartition("/")[1] | d7a9cac8aa6cb6a3a109f5579b88d5c4f77644a8 | 44,155 |
def prepare_auth_params_json(bot, manifest):
"""Returns a dict to put into JSON file passed to task_runner.
This JSON file contains various tokens and configuration parameters that allow
task_runner to make HTTP calls authenticated by bot's own credentials.
The file is managed by bot_main.py (main Swarming bo... | 775540265b9739de40ae4497033311e4fbbcb273 | 44,156 |
import ast
def get_input(arg, valid_keys):
"""Convert the input to a dict and perform basic validation"""
json_string = arg.replace("\\n", "\n")
try:
input_dict = ast.literal_eval(json_string)
if not all(k in input_dict for k in valid_keys):
return None
except Exception:
... | 55f702725186cb74767546c8a3c4b068f0c03f2b | 44,157 |
import os
def partially_configured(build_directory: str) -> bool:
"""
Determine if project is not configured enough to begin the build process
@param build_directory: The full path to the build directory
@return: Whether or not this needs to be configured from scratch
"""
cmake_cache = os.path... | 9a77c88d7b531da181523fcde7eacb84a79fa6f4 | 44,161 |
def convert_length(length_from, length_to):
"""
Determines the length scale factor
We crate a gravity_scale_length for any non-standard unit (ft, m)
"""
xyz_scale = 1.0
gravity_scale_length = 1.0
#if length_from != length_to:
if length_from == 'in':
xyz_scale *= 0.0254
... | 33a6311c32932eb6fe55345c82c57e9f5730017f | 44,162 |
def get_pip_link(page_name):
"""
获取pip官方的包源地址 当下载不到的时候可以查看下
:param page_name: 包名称
:return:
"""
if page_name.find('==') > -1:
page_name = page_name[:page_name.rfind('==')]
return 'https://pypi.org/project/{0}/#files'.format(page_name) | 22a0fb391f04ef1adab7bfa0fae98e88d582d8a4 | 44,163 |
import requests
import json
import logging
def authenticate_with_ome(ip_address: str, user_name: str, password: str) -> tuple:
"""
Authenticates a session against an OME server
Args:
ip_address: IP address of the OME server
user_name: Username for OME
password: Password for the OM... | a952e445acde71ee0bfde1aedc70a976fc2c49cf | 44,164 |
def searchForInsert(sortedList:list, value:float)->int:
"""Search for where to insert the value for the list to remain sorted
Args:
sortedList (list): a sorted list
value (float): the value to insert into the sorted list
Returns:
int: the index where to insert the value
"""
... | 3974c8e7b58feb9d47aadb68f88a931ba3bd8048 | 44,165 |
def get_flash(tree):
"""Get the memory and control base addresses of the SPI flash to program"""
metal_entry = tree.chosen("metal,entry")
if metal_entry:
node = tree.get_by_reference(metal_entry[0])
if node:
compatible = node.get_field("compatible")
if compatible and ... | 88d3a96135cc1df82b1a63c2e243b873eb6c8033 | 44,166 |
def date_formatter(raw_string):
"""Return a well formatted date as string."""
date = raw_string[:8]
date = f'{date[:4]}-{date[4:6]}-{date[6:8]}'
time = raw_string[9:]
if len(raw_string) > 15:
time = f'{time[0:2]}:{time[2:4]}:{time[4:6]}.{time[6:]}'
else:
time = f'{time[0:2]}:{tim... | c4501690e378ab0c7d1a128c1df713a8c79c979a | 44,167 |
def deep_to(batch, device, dtype):
""" Static method to call :func:`to` on tensors or tuples. All items in tuple will have :func:`deep_to` called
Args:
batch (tuple / list / :class:`torch.Tensor`): The mini-batch which requires a :func:`to` call
device (:class:`torch.device`): The desired devic... | e754e687c4f998c24fd6bf81259fa2aaf44bb419 | 44,169 |
def prune_with_bound(decision_tree, bound):
"""
Prunes the tree as described by Algorithm 3 in Appendix E of the paper.
Only to the outside 'while' loop of the algorithm is implemented in here. The 'for' loop is implemented by the 'prune_tree' method of the decision tree classifier object (which is called ... | 54f999a60a06d1210b5c7162f7a4596e4ee49d48 | 44,171 |
def parse_listItems(lis):
""" Get data from lists """
results = []
for li in lis:
for item in li:
results.append(item.text[:item.text.index(',')])
return results | cb1b220a18ab2495800f36c3e07f6a3e3bd3845a | 44,172 |
def sum_two_smallest_numbers(numbers):
"""Find two lowest positive integers and add them."""
return sorted(numbers)[0] + sorted(numbers)[1] | 9e90f521dd56e8e5dce2a26ede7a66256f46f958 | 44,173 |
import re
def parse_log(line):
"""Parse logs with regex
Function that parse raw logs and extracts request_time and url
Args:
line: Decoded line
Returns:
reqest_time_data: float number or None if log can't be parsed
url_data: String or None if log can't be parsed
"""
... | 3c2a889fe3e2fc7e922628da0c447575cbfed6d9 | 44,176 |
import random
def somebells():
"""Returns some random amount of bells"""
return random.randint(100, 500) | 9472963e1c277c19c84b46e6e2f6a6bf28e90114 | 44,178 |
def gipsy_dashboard_widget(context, widget, index=None):
"""
Template tag that renders a given dashboard module
"""
context.update({
'template': widget.template,
'widget': widget,
'index': index,
})
return context | 53ac407be1ff55d0208712c7b1b26d7bb675f6e3 | 44,179 |
def deregister_sub(topics_to_subs, sub):
"""Deregister a Subscription from a mapping topics->subscriptions.
Args:
topics_to_subs (dict): dictionnary topic -> list of subscriptions
sub (Subscription): subscription to deregister
"""
key = str(sub.topics)
if key in topics_to_subs:
... | 099e7e3a0683e0e047ab55fa4ce1dd0b111d19ee | 44,182 |
def server_status_field(log, server_status, field_name):
"""
Return (0, result) for a field of BarreleServerStatusCache
"""
# pylint: disable=unused-argument
return server_status.bssc_field_result(log, field_name) | 634d19ad50311902d92390b2f1ac5a2b73ddf389 | 44,183 |
def binaryPlusOne(operand):
"""
Adds 1 to the binary string operand.
No safety,i.e.: operand is assumed to be a string, with only binary content 9i.e.: 0s or 1s),
however a string may be returened only if it has the same length as operand.
"""
#print(str(operand))
length = len(o... | e3624a67fb33ebfe7c2270e0a45575e28a1e6dfa | 44,185 |
import warnings
def normalize_df(
df,
method,
drop_degenerate_cols=True,
replace_zero_denom=False):
"""For a given dataframe with columns including numerical values,
it generates a function which can be applied to original data as well as
any future data to normalize using ... | 277353068155226894b0cdba9fcf56b24e58a891 | 44,186 |
def is_interesting_file(file_name):
# type: (str) -> bool
"""Return true if this file should be checked."""
file_blacklist = ["buildscripts/cpplint.py"]
directory_blacklist = ["src/third_party"]
if file_name in file_blacklist or file_name.startswith(tuple(directory_blacklist)):
return False
... | dbddc9dd7fd493b8a18f8c6d9cf04fd8a16638bc | 44,188 |
def _check_handle(handle):
"""Checks if provided file handle is valid."""
return handle is not None and handle.fileno() >= 0 | 7bce4bc10f4a7ee9c393a4e6a79eb3cdc22f4a12 | 44,189 |
def clear_data_for_origin(origin: str, storageTypes: str) -> dict:
"""Clears storage for origin.
Parameters
----------
origin: str
Security origin.
storageTypes: str
Comma separated list of StorageType to clear.
"""
return {
"method": "Storage.clearDataForOri... | 8c8bf90c4ac4f7dc0dc3459fe18999c127d12226 | 44,191 |
def get_one_item(CURSOR, BARCODE):
"""
Returns the specified item from the database, determined by the
primary key - in this case the barcode number.
Args:
CURSOR (object):
BARCODE (str): the barcode number
Returns:
ITEM (list): the item in the database
"""
ITEM = CURSOR.execute("""
SEL... | 013c4a86ba7ca8c41965a448370d5d6ef05874e0 | 44,194 |
def linear_search(L, v):
""" (list, object) -> int
Return the index of the first occurrence of v in L, or
return -1 if v is not in L.
>>> linear_search([2, 3, 5, 3], 2)
0
>>> linear_search([2, 3, 5, 3], 5)
2
>>> linear_search([2, 3, 5, 3], 8)
-1
"""
i = 0
while i != l... | 50a9ac2e720373d050deb29f31724d27a06e97d6 | 44,196 |
def closure(s):
"""
ε-closure(s),即集合 s 的ε闭包。也就是从集合 s 中的每个节点,加上从这个节点出发通过ε转换所能到达的所有状态。
:param s:
:return:
"""
# ret_list = []
# for state in s:
# ret_list.append(state)
#
# if isinstance(state.value, EBNFNode):
# if state.value.node_type != NodeType.RANGE:
#... | 7253c90215e01370086b01cd5330daac9429f3d3 | 44,198 |
def matrix_identity(n: int) -> list:
"""
Generate the n-sized identity matrix.
"""
if n == 0:
return [0]
identity: list = []
for col in range(n):
column: list = []
for row in range(n):
if col == row:
column.append(1)
else:
... | 6ac3945b90e4c8ae9bb0ca6f2b9c55379ab13cec | 44,199 |
def get_gcd(x, y):
"""Calculate the greatest common divisor of two numbers."""
if y > x:
x, y = y, x
r = x % y
if r == 0:
return y
else:
result = get_gcd(y, r)
return result | 1e17028c0595df01897504b3332a6032186cd4f5 | 44,200 |
import base64
def img_to_base64(img):
""" 把图片处理成 base64 编码的图片
:param img: 输入是图片 IO
:return: 返回的是 base64 编码的图片
"""
return base64.b64encode(img) | 97088304813082d59580f65e081a5aca17d13180 | 44,201 |
import requests
from bs4 import BeautifulSoup
def getPDFlink(extension_list):
"""
Scrapes each ICO profile page and collects the Whitepaper download links if available.
Indexes are recorded to keep track of ICO's without download links'
"""
website = "http://ico.coincheckup.com"
indexes ... | 848cfed414d045354eee105f74ee6ab47991b4bb | 44,204 |
def raise_failure_factory(message):
"""
Create a function that raises a failure message
:param str message: Message to raise in combination with standard out
:return func raise_failure:
"""
def raise_failure(process_output):
_, _, standard_error = process_output
raise RuntimeErro... | fefca7d9672f1b07402e56c4b41e1c880ff6ae7c | 44,206 |
import requests
def get_from_github_with_auth_raw(url, apikeys):
""" """
headers = {}
username = apikeys.get("github-user")
key = apikeys.get("github-key")
return requests.get(url, headers, auth=(username, key)) | cb9f6ea799054192100de16bd37300bb39feb91a | 44,207 |
def clean(text):
"""
clean text for creating a folder
"""
return "".join(c if c.isalnum() else "_" for c in text) | e5dbfd2733cdd4e2387b04161bfc06921fe1ba75 | 44,208 |
import math
def repeat_data(preload, num_simulation_steps):
"""Repeats the transformer preload data until there are as many values as there are
simulation steps.
Args:
preload: (list): Containing the data (floats) to be repeated.
num_simulation_steps: (int): Number of simulation steps and... | 1e2c172d40d13c10802fd7edadb68fdb29153836 | 44,209 |
def get_node_and_attribute(attribute):
"""
Split a name between its node and its attribute.
Args:
attribute (str): attribute name, node.attribute.
Returns:
list: [node_name, attribute]
"""
split_attribute = attribute.split('.')
if not split_att... | 8534366c4d7800681c1088a1446f828087d9ddea | 44,210 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.