content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def normalize_cap(option, pron):
"""Normalize the capitalization of the option according to the pronoun."""
cap_tuples = [
("The", "the"), ("His", "his"), ("My", "my"),
("Her", "her"), ("Their", "their"), ("An", "an"), ("A", "a")]
uncap_dict = dict(cap_tuples)
cap_dict = dict([(t[1], t[0]) for t in ... | bc60c20fe7e5038349473fba31e9e48c30d33bab | 657,357 |
def field_occurrence_predicate(field, args):
"""Return a function that checks for the occurrence of a field."""
newfield = field.lower() if args.ignore_case else field
def _field_occurrence(entry):
return bool(getattr(entry, newfield, None))
return _field_occurrence | b7ee2b5f9357648879764444bd01f9a7e30e8ca6 | 657,358 |
import re
def _n(name):
"""Return valid PySB name."""
n = name.encode('ascii', errors='ignore').decode('ascii')
n = re.sub('[^A-Za-z0-9_]', '_', n)
n = re.sub(r'(^[0-9].*)', r'p\1', n)
return n | f1f75b9c6f391536f2eae7eedbbfce077f5b41e1 | 657,359 |
def _bit_is_set(bit_str: str, i: int) -> bool:
"""
Private helper function to check whether the i-th bit in the given bit
string is set.
:param bit_str: str
:param i: int
:return: bool
"""
return bit_str[i] == '1'
# Running time complexity: O(1) | 8410a90031fdbaa23f92e1873468aa34c13667fb | 657,361 |
def minus(a, b):
"""
:param a: first interger number
:param b: second integer number
:return: subtract of second number from first
"""
return a - b | edb46dd013f60bfccd87be23099180d85483183e | 657,362 |
def alpha_to_pie(input):
"""
Parameters
----------
input : str
Text input with syllables separated by dashes and words by spaces.
Returns
-------
output : str
Transliterated text in Avestan Script
"""
# print(input.translate(script))
output = input
output =... | dbba9aeeb99983de87cd504025647a6bb476b851 | 657,363 |
def S_ISDOOR(mode): # real signature unknown; restored from __doc__
"""
S_ISDOOR(mode) -> bool
Return True if mode is from a door.
"""
return False | 7f756331e9bd3538df5457fc4dfe35f5cd6d5331 | 657,364 |
import random
def comment_is_salty():
""" Randomize if comment is salty """
value = random.randint(0, 1)
return value | 4af689ca539eda99da447571bbba6db823bf2032 | 657,365 |
from typing import List
from typing import Any
def peek(array: List[Any]) -> Any:
"""
Returns the last element in the input array. Similar to the built-in
Array.pop method, except that it does not remove the last element.
This method is a convenient shorthand for array[array.length - 1].
"""
r... | 40e690da46ba4e7142fd0087a20cc553288e9b63 | 657,367 |
def _get_feat_lkp_tbl():
"""
This function embeds the knowledge of mapping what features to be
generated for what kind of attr. types.
"""
# Initialize a lookup table
lookup_table = dict()
# Features for type str_eq_1w
lookup_table['STR_EQ_1W'] = [('lev_dist'), ('lev_sim'), ('jaro'),
... | da5d72d78dacd8f76d539e500024c50a98e63c41 | 657,368 |
def f(integer):
"""
factorcalc.f(int > 0) -> list of int -- provides a list of all the factors of the first argument
"""
if type(integer)==int:
if integer>0:
possible_factors=[integer]
possible_factor=integer-1
for i in range(integer):
possibl... | 52c7552f7f0351d1606fb36a1361a3aa2522c7d8 | 657,371 |
import re
def find_line(inputlist, regex, start=None):
"""
returns the index number of the line where regex is found in the inputlist
if stop is true, stop searching with first line found
:param inputlist: list of strings
:type inputlist: list
:param regex: regular expression to search
:ty... | 51fcf52113245736458eabd14b82a9b64a47090c | 657,372 |
import configparser
def make_blank_config(config_file):
"""Generate blank config
Parameters:
ak: app key
sk: secret key
url: prefix
bucket: bucket in QiNiu
Example:
[qiniu]
ak=F9-lVHzO3KWKAAbJA_FYTL1l8WEx2fJuNubSJXRv
sk=wEg_xzmOCaYqzZQEEE87sfkJ2-wfYC... | 04b5cbc5fa692759ae98acd9efd9354b45797bdb | 657,373 |
def _to_python_str(s):
""" Convert to Python string """
if isinstance(s, bytes):
return s.decode('utf-8')
else:
return s | f4a1967f64a30792346640b0e145f0038d7bf50b | 657,374 |
import json
import time
def measure_hash(sensor_id, measure_value, measure_type):
"""Create measurement JSON"""
typeid = 100
unitid = 100
if measure_type == "voc":
typeid = 105
unitid = 105
elif measure_type == "temperature":
typeid = 100
unitid = 100
elif measu... | baa72221f410fe7e63e99748bda7400427395eaa | 657,376 |
from typing import Union
def read_token() -> Union[str, None]:
"""
Reads token from the saved config file
Returns:
token string from file (or None if missing/invalid)
"""
try:
with open("config/token", "r") as file:
return file.readline().rstrip()
except Exception ... | f548971b97cd06a0e86ab2152dc4452928da6b09 | 657,377 |
def CMYKtoRGBA(mesh):
"""converts a mesh back to RGBA, ready for export."""
for i in mesh.visual.vertex_colors:
c,m,y,k = i[:]
r = 255 * (1-c/100) * (1-k/100)
g = 255 * (1-m/100) * (1-k/100)
b = 255 * (1-y/100) * (1-k/100)
i[:] = r,g,b,255
return mesh | 9e2747bdb0f247c3781f47cab7f69d081c38c84f | 657,378 |
def add_user_to_groups(uname, grpstr, groups=["lsst_lcl", "jovyan"]):
"""Take a user name (a string) and a base group file (as a string) and
inject the user into the appropriate groups, given in the groups
parameter (defaults to 'lsst_lcl' and 'jovyan'). Returns a string."""
glines = grpstr.split("\n")... | ddf15d42fe57ba5dc96afea43a330d787fdbb909 | 657,379 |
import re
def _replace_version(package_str, new_version):
"""
replaces the version tag in contents if there is only one instance
:param package_str: str contents of package.xml
:param new_version: str version number
:returns: str new package.xml
:raises RuntimeError:
"""
# try to repl... | 913c844c9387b6fb1f91327fba7999a72e3b156f | 657,380 |
def tocreset(I, Ipickup, TD, curve="U1", CTR=1):
"""
Time OverCurrent Reset Time Function.
Function to calculate the time to reset for a TOC
(Time-OverCurrent, 51) element.
Parameters
----------
I: float
Measured Current in Amps
Ipickup: float
... | 8c26a3aebcb5f51fe884724e4d9460f44454b3d1 | 657,381 |
def wigner_d_transform_analysis_vectorized(f, wd_flat, idxs):
""" computes the wigner transform analysis in a vectorized way
returns the flattened blocks of f_hat as a single vector
f: the input signal, shape (2b, 2b, 2b) axes m, beta, n.
wd_flat: the flattened weighted wigner d functions, shape (num_s... | 7f1a32fea3a42f6bff7ae7295dfe0182c61c6a57 | 657,383 |
def add_make_abundance_io_arguments(arg_parser):
"""Add io arguments to parser."""
helpstr = "Input group file which associates collapsed isoforms with reads."
arg_parser.add_argument("group_filename", type=str, help=helpstr)
helpstr = "Input pickle file (e.g., hq_lq_pre_dict.pickle) which maps HQ " + ... | 78bddd16f60f9055c532a1958cb7dff1398ca994 | 657,384 |
def remove_quotes(arg):
"""
This function returns two values:
- The treated string (i.e., without surrounding quotes)
- A boolean value informing whether it removed any quotes or not
Note that it will only remove anything if the quotes at each end match.
Therefore, strings like "foo' will be returned as they are... | 94af94c99440dbc10f042210f4ae68feb2b68e0f | 657,385 |
import os
def has_qutip_rc():
"""
Checks to see if the qutiprc file exists in the default
location, i.e. HOME/.qutip/qutiprc
"""
qutip_conf_dir = os.path.join(os.path.expanduser("~"), '.qutip')
if os.path.exists(qutip_conf_dir):
qutip_rc_file = os.path.join(qutip_conf_dir, "qutiprc")
... | 1273856f810b1a31867c71c69bcfa0501af2ceef | 657,386 |
def is_video_file(filename):
""" Check if file is a video
:param filename: file name string
:return: Boolean toggle
"""
return any(filename.endswith(extension) for extension in ['.mp4', '.avi', '.mpg', '.mkv', '.wmv', '.flv']) | fb112b094d13449026486e5e112ed4b41f19acf9 | 657,387 |
import platform
import os
def get_user_config_path(appname: str) -> str:
"""
:return: user config path
"""
system = platform.system()
if system == 'Windows':
# C:\Users\<username>\AppData\Local\<AppName>
data_path = os.getenv('LOCALAPPDATA', os.path.expanduser('~/AppData/Local/'))
... | cbcf856959fd8c19ce56099e77c24d7bda1fd6dd | 657,388 |
import six
def convert_id36_to_numeric_id(id36):
"""Convert strings representing base36 numbers into an integer."""
if not isinstance(id36, six.string_types) or id36.count("_") > 0:
raise ValueError("must supply base36 string, not fullname (e.g. use "
"xxxxx, not t3_xxxxx)")
... | 5ccd3661f6985c73e38ebcb6bbf9d0e242cddbb6 | 657,389 |
def normalize_df(series):
"""convenience function to normalize a signal
(i.e., rescale to range from 0 to 1)
"""
series_norm = (series - series.min()) / (series.max() - series.min())
return series_norm | 137433edddad2ef8e36a3369f194ff56e1015a13 | 657,391 |
def O2_analysis_v2(f, k, iratio):
"""
:param f: mcerp.UncertainVariable contaning a normal distributed sample of values around the best value of the
fit parameter f and its covariance value as sigma
:param k: mcerp.UncertainVariable contaning a normal distributed sample of values around ... | a5b0921bba40c1ba2f7e726ca57ae1e9d1f1c7b0 | 657,393 |
def svid2gnssid(svid) -> int:
"""
Derive gnssId from svid numbering range.
:param int svid: space vehicle ID
:return: gnssId as integer
:rtype: int
"""
if 120 <= svid <= 158:
gnssId = 1 # SBAS
elif 211 <= svid <= 246:
gnssId = 2 # Galileo
elif (159 <= svid <= 163... | 10f8726577b7d973aaec0a04281bd6bdb8e30f8b | 657,394 |
def last_openapp_fillform_count(uid, action_grouped):
""" 最后一次点击APP开始填写表单量 """
action_df = action_grouped[uid]
action_df = action_df[action_df['actionType'] == 1]
if action_df.shape[0] == 0:
return 0
last_open_time = action_df['actionTime'].iat[-1]
action_df = action_df[action_df['actio... | e121b6e30558357e78a8ac4a487db76f145657a9 | 657,395 |
def test_container(container):
"""Returns function that tests safely if item in container.
Does not raise TypeError (e.g. for dict checks.)
"""
def result(item):
try:
return item in container
except TypeError:
return False
return result | a5573348c0d2c992cb51742f677b63ef43360058 | 657,396 |
import hashlib
def compute_hash(filename):
"""Returns the MD5 hash of the specified file"""
with open(filename, 'r') as f:
contents = f.read().encode('utf-8')
return hashlib.md5(contents).digest() | f73983580eace66d9fe82156ac6cddb1576da58d | 657,397 |
import json
import base64
def get_service_account_cred_from_key_response(key_response):
"""
Return the decoded private key given the response from
`create_service_account_key()`. This return from this function is the
JSON key file contents e.g. response can be placed directly in file
and be used a... | 4ff6da5a134be890726d88848fd05a7f8a0b1e9c | 657,398 |
def awg2mm(AWG):
"""
Convert AWG ( American Wire Gauge to mm diameter)
:param awg: Wire AWG
:return: Wire milimitter diameter
diameter [mm] = 0.127 * 92 ^ ((36-AWG)/39)
Reference: http://www.reuk.co.uk/AWG-to-Square-mm-Wire-Size-Converter.htm
"""
return round(0.127 * 92 ** ((36 - ... | e83b63d76739171ea06067a3895ad4b5803dfb39 | 657,399 |
import unicodedata
def clean_str(s):
""" Clean a string
"""
return unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode() | 23da45088e6ccd54b1488847877828a32c3015bd | 657,400 |
import os
def name_parts(name):
"""
Return folder, undecorated file name + ext, file root, ext, decorations.
If extension is not specified, ".grd" assumed
For example:
.. code::
>>> import geosoft.gxpy.grid as gxgrd
>>> namep = gxgrd.name_parts("f:/someFolder/name.grd(GRD;TYPE=... | 49cab7c6c6685ca17bef01c1aede1fb801d1e72c | 657,401 |
def identity_labels(dim):
"""
The identity-basis labels based on a matrix dimension.
Parameters
----------
dim : int
The matrix dimension.
"""
return ['I'] | d3fd53898a36809f02c395f8a7730c9bfcd0de90 | 657,402 |
def list_services(conn) -> list:
"""[summary]
Args:
conn ([type]): [description]
Returns:
list: [description]
"""
cursor = conn.cursor()
cursor.execute("SELECT * FROM KEYS;")
rows = cursor.fetchall()
return [row[1] for row in rows] | 2046a6cdff3346694949af76aebf090a0c7252be | 657,403 |
import math
def dropna(df):
"""Drop rows with "Nans" values
"""
df = df[df < math.exp(709)] # big number
df = df[df != 0.0]
df = df.dropna()
return df | 099faf996cbf4f8c33edbf689bc4bcf9654d9439 | 657,404 |
def list_wanted_windows(actual_windows, shared_pids):
"""
Lists every window in the desired order for z-index sorting.
:param actual_windows: The windows in their current order
:param shared_pids: The list of shared_pids from the spawned windows
:return: A sorted list of windows indexed by the desi... | 0f2cd129b1736782f31fba6e2b341aeb64a26a5a | 657,405 |
from typing import List
from typing import Tuple
def get_new_gatecharacterization_range(
current_valid_ranges: List[Tuple[float, float]],
safety_voltage_ranges: List[Tuple[float, float]],
range_update_directives: List[str],
) -> List[Tuple[float, float]]:
"""Determines new voltage range for a subseque... | a4e20fa9bda7f5be3f3ba054563a818ece8370d3 | 657,406 |
def prompt_independent() -> str:
"""Prompt the user for the independent variable to ue for calculation
>>> prompt_independent()
Would you like to use CO2 or forest cover as the independent variable?
>? precipitation
Please enter 'CO2' or 'forest cover'
>? forest cover
'Estimated Natural For... | c6210b86ebbcef2b82178f684139f13238314457 | 657,407 |
import torch
import math
def encode_μ_law(x: torch.Tensor, μ: int = 255, cast: bool = False)\
-> torch.Tensor:
"""
Encodes the input tensor element-wise with μ-law encoding
Args:
x: tensor
μ: the size of the encoding (number of possible classes)
cast: whether to cast to in... | b4bd30fcf9353b5895ca95309f60064deb0baa89 | 657,410 |
def to_minimal_df(df_in):
"""
Extracts a minimal df partof the given dataframe to be used with the
implemented machine learning workflow. Also ensures that the indices are
compareable
"""
df1 = df_in.copy().reset_index()
if "Modified sequence" in df_in.columns:
df2 = df_in[["Sequenc... | 0e4d63abcf82e23d981a0cf8ebd54b8de54d749f | 657,411 |
def make_pattern_of_length(l):
"""docstring for make_pattern_of_length"""
# repeats = max(1, l / 26)
# return make_pattern(4, repeats)[:l] # Guarantee it ends with a .
s = '. . . . .. .. ... ... .... .... ..... .....'[:l]
if len(s) < l:
s += '.' * (l-len(s))
return s | aa9f3c5c7d368f6ea813a6d7ade7f8f913ea13f6 | 657,412 |
def get_comment_text(submission):
"""Returns the respondent typed text from a submission. The qcode for this text will be different depending
on the survey
"""
if submission.data['survey_id'] == '009':
return submission.data['data'].get('146')
if submission.data['survey_id'] == '187':
... | a9864d9c3f956a6b7133324362ab75c9c07410a6 | 657,413 |
def _fnv_1a_24(data, _ord=lambda x: x):
"""FNV-1a 24 bit hash"""
# http://www.isthe.com/chongo/tech/comp/fnv/index.html#xor-fold
# Start with FNV-1a 32 bit.
hash_size = 2 ** 32
fnv_32_prime = 16777619
fnv_1a_hash = 2166136261 # 32-bit FNV-1 offset basis
for elt in data:
fnv_1a_hash = fnv_1a_hash ^ _ord(elt)
... | cd716bd195324f02b13cd62aa129c252ccd599d8 | 657,414 |
def authenticated():
"""Response when active beta."""
return {
"info": {"version": "9.98.9"},
"releases": {
"9.97.9b0": [],
"9.97.9": [],
"9.98.9b0": [],
"9.98.9": [],
"9.99.9b0": [],
},
} | d32062bb8fec5b399b67cd3bcb0f3ea8c462965f | 657,415 |
def re_usable_db_mocker(mocker):
"""
Fixtures can invoke mocker to yield "re-usable" mocks
"""
mock_db_service = mocker.patch("other_code.services.db_service", autospec=True)
mock_db_service.return_value = [(0, "fake row", 0.0)]
return mock_db_service | 4b3e81ca06ad2471a0b7357de21c171084a438eb | 657,416 |
def get_tick_time():
"""
dt
:return:
"""
return 1.0 / 30 | 98d5957ca26846f4e8426fdf504e3b7f874d1220 | 657,418 |
def get_FTPdetect_coordinates(FTPdetect_file_content, ff_bin, meteor_no = 1):
""" Returns a list of FF*.bin coordinates of a specific bin file and a meteor on that image as a list of tuples e.g. [(15, 20), (16, 21), (17, 22)] and the rotation angle of the meteor.
"""
if int(FTPdetect_file_content[0].split(... | 3a5adf21d545848ac8807d3bd03e0e2ef11eda77 | 657,419 |
def mirror(pt: float, delta: float):
"""Mirrors a value in a numberline
Args:
pt : real value in numberline
delta: value to mirror
Returns:
pt - delta, pt + delta
"""
return pt - delta, pt + delta | 5ec80a889422a961c0aa5906ed4990317876286f | 657,420 |
def cw310_params(
tags = [],
timeout = "moderate",
local = True,
args = [
"--exec=\"console -q -t0\"",
"--exec=\"bootstrap $(location {test_bin})\"",
"console",
"--exit-failure=FAIL",
"--exit-success=PASS",
"--timeou... | eb0147819c78584e8153bab8bafc9169a54f3278 | 657,422 |
import jinja2
import os.path as path
def render(template, **kwargs):
"""
Renders the HTML containing provided summaries.
The summary has to be an instance of summary.Summary,
or at least contain similar properties: title, image, url,
description and collections: titles, images, descriptions.
... | 5d429ca7d1abf39d11fa1e3609e54b2f8b7668d0 | 657,423 |
import importlib
def find_function(search_def):
"""
Dynamically load the function based on the search definition.
:param str search_def: A string to tell us the function to load, e.g.
module:funcname or module.path:class.staticmethod
:raises ValueError: In case configuratio... | dd44ca63cf214f928667a704f8686739833775e5 | 657,424 |
import textwrap
def windows_inventory(remotes):
"""
:type remotes: list[AnsibleCoreCI]
:rtype: str
"""
hosts = []
for remote in remotes:
options = dict(
ansible_host=remote.connection.hostname,
ansible_user=remote.connection.username,
ansible_passwo... | 5dd9f3a880bf4bee4de86e3c091ace391dcbc0bf | 657,425 |
def find_proposition_by_node(anchor_node, sentence_theory):
"""
http://e-gitlab.bbn.com/text-group/jserif/blob/master/serif/src/main/java/com/bbn/serif/theories/Propositions.java#L86
:param anchor_node: serifxml.SynNode
:param sentence_theory:serifxml.Sentence
:return:serifxml.Proposition
"""
... | d88805b41fb34b803bc2bcb0de24e0802a5354a9 | 657,426 |
def read_leasefile(interface):
""" read lease file for given interface and returns content
of option-212 as string from the last found lease
:param interface
:return: string
"""
new_6rd_config = False
try:
# Do something with the file
with open("/var/db/dhclient.leases." ... | fbec719f25b539676c417ff5a3330963530530f5 | 657,427 |
import numpy
def mask_op(mask_array, value_array):
"""Mask out value to 0 if mask array is not 1."""
result = numpy.copy(value_array)
result[mask_array != 1] = 0.0
return result | 9cb0f520d3b0aa6c83abc5b340f2caf8c5478b8d | 657,428 |
def check_poly_isomorphism(p1, p2):
"""
Performs all 8 symmetries on polycube2 (p2)
and checks if it's equal to polycube1 (p1)
8 symmetries come from dihedral group of order 8 (D8)
(treat the xy-plane as the square under symmetries)
Parameters
----------
p1 : ... | 597d5d4de4df3587d7a26974c0b5c611e5adb8e3 | 657,429 |
def is_in_simplex(x):
"""Checks if a distribution has exited the simplex."""
stop = True
for j in range(x.size):
if x[j] < 0:
stop = False
break
return stop | eda5129098d1147dbc671c4e68336f7aea15284b | 657,433 |
def get_delay_loaded_timestamp(pefile_object):
"""
Retrieves the timestamp from the Delay Load Import Table directory.
:param pefile.PE pefile_object: pefile object.
:return: Recovered timestamps from PE imports (if any) as a list
of tuples such that [(dllname, timestamp)].
:rtype: list
"""... | 5e1b50d349d0ac7689cc20f283eea54439fa790d | 657,434 |
def generate_matrix(dim):
"""Generate the matrix with enumarated elements.
Args:
dim: Dimension of the matrix.
Returns:
Generated matrix as a nested list.
"""
matr = []
for i in range(dim):
# Start by 1 and increase the number for each new element by one.
matr.a... | d4446ef3fc469050f6bd346182203c42cf6eefbd | 657,436 |
def pack(join, alist):
"""Interleave a list with a value
This function interleaves a list of values with the joining
element.
Params:
join -- The value to be interleaved within the list
alist -- The supplied list
Returns:
A new list
pack("a",[1,2,3,4]) ==> ["a",1... | 407c0f1133ecb42b466c54b41cdde56eea80bcb6 | 657,437 |
import re
def read_d1_letter(fin_txt):
"""Reads letter aliases from a text file created by GoDepth1LettersWr."""
go2letter = {}
re_goid = re.compile(r"(GO:\d{7})")
with open(fin_txt) as ifstrm:
for line in ifstrm:
mtch = re_goid.search(line)
if mtch and line[:1] != ' ':... | a05a944aa263c6682f3a2fed8a659f579bfcb950 | 657,438 |
def _has_numbers(text):
""" Checks if any characters in the input text contain numbers """
return any(char.isdigit() for char in text) | c8992cfe40c310f07d292aa376aad8d766a5242b | 657,440 |
def expect_lit(char, buf, pos):
"""Expect a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, len(buf)
return char, pos+1 | a90ab29f20bdc4733cfd331d2d58f7952c02ae62 | 657,441 |
def exactly(length:int) -> str:
""" Match the previous pattern exactly `length` times.
>>> import superexpressive as se
>>> se.exactly(4)
'{4}'
>>> import superexpressive as se
>>> se.DIGIT + se.exactly(6)
'\\\\d{6}'
"""
return f"{{{length}}}" | 01ba444356d213366b17d2d2d6aad832e054718e | 657,442 |
def extract_otp_url(data, is_v2):
"""Get the otpauth url from our decoded json as a string."""
assert isinstance(data, dict)
fields = data['fields']
assert isinstance(fields, list)
if is_v2:
assert len(fields) == 1
return fields[0]['data']
# For v3 records
for subdict in fiel... | a4953f3a2d5951b7927d7c73d3aae0b721bcbe7a | 657,443 |
from typing import OrderedDict
def extract_params_from_model(common_net):
""" Obtain the parameters of a model in an OrderedDict
Parameters
----------
common_net: instance of :class: `~blocks.model.Model`
the model from where the parameters are extracted
"""
params = OrderedDict()
... | 8d034b2a576a62f62703c19a34092704f12dd7b9 | 657,445 |
def sort_lines_by_page(pages_obj):
"""
Expects a Pages Object (LIST OF DICTS) with the following Keys:
- PAGE_NUMBER: int
- LINES: list of dicts from AWS Textract BlockType Line
"""
pages = pages_obj
pairs = []
for i in pages:
pairs_to_sort = {}
... | db2eea001f5daaad75a4f0d817ab1f585650aa4a | 657,446 |
def make_save_folder(hyps):
"""
Creates the save name for the model.
hyps: dict
keys:
exp_name: str
exp_num: int
search_keys: str
"""
save_folder = "{}/{}_{}".format(hyps['exp_name'],
hyps['exp_name'],
... | a13298979af2c615483432bb528cda6400e8c355 | 657,447 |
import textwrap
def format_helptext(text):
"""Format help text, including wrapping."""
return "\n".join(textwrap.wrap(text)) | a1e9baa8bd093802a76890c1e87876d751c280aa | 657,448 |
def _energy_test_statistic_coefficient(n, m):
"""Coefficient of the test statistic."""
return n * m / (n + m) | 0ce7d5d70ccd64fc6cf9343e673f8a8acf90fa97 | 657,449 |
def mul(c1, val):
"""Multiplies an encrypted counter by a public value"""
a1, b1 = c1
return (val*a1, val*b1) | f51d578543c530abad2a1bb3680066f48b31c754 | 657,450 |
def FormatSubversionPropertyChanges(filename, props):
"""Returns Subversion's 'Property changes on ...' strings using given filename
and properties.
Args:
filename: filename
props: A list whose element is a (svn_prop_key, svn_prop_value) pair.
Returns:
A string which can be used in the patch file ... | f1cb0c1630e8b015ea284c7244619aa4d5e14c80 | 657,451 |
def process_covid_csv_data(covid_csv_data: list) -> tuple[int, int, int]:
""""A function that takes in a list of strings separated by whitespace and returns some of the data"""
last_7_days_cases, total_deaths, current_hospital_cases = 0, "", ""
started_reading = False # a boolean value to check whether t... | 52b9aa40cbd7bffd94b64207968012fda0d029ca | 657,452 |
def rosenbrock(vector, a=1, b=100):
"""
The Rosenbrock function is a non-convex function used as a performance test
problem for optimization algorithms introduced by Howard H. Rosenbrock in
1960. It is also known as Rosenbrock's valley or Rosenbrock's banana
function.
The function is defined b... | 56d5d712d0865940958ad7316ee4c76f27fa0444 | 657,453 |
import os
import subprocess
def _get_git_tracked_files(rootdir='.'):
"""Parsing .gitignore rules is hard.
However, a way we can get around this problem by just listing all
currently tracked git files, and start our search from there.
After all, if it isn't in the git repo, we're not concerned about
... | 894f50ce4d8d35d9933475e957ef1c621ecc3baf | 657,454 |
def try_attrs(obj, *attrs, **kwargs):
"""Try to find an available attribute.
Args:
obj (object): Object to get the attribute value for.
*attrs (tuple/str): Tuple of different string attribute names to try (These names may include '.' attributes).
default (object)[None]: Default Value to... | 2dfb52432a5387c41e916c23d71c88f2536534d6 | 657,455 |
def groupby(iterable, key=None):
"""
Group items from iterable by key and return a dictionary where values are
the lists of items from the iterable having the same key.
:param key: function to apply to each element of the iterable.
If not specified or is None key defaults to identity function and... | dccd69a0ffdc30e6d8b3950f14e3e2649e4c4409 | 657,456 |
def make_broadcastable(v, X):
"""Returns a view of `v` that can be broadcast with `X`.
If `v` is a one-dimensional tensor [N] and `X` is a tensor of shape
`[N, ..., ]`, returns a view of v with singleton dimensions appended.
Example:
`v` is a tensor of shape `[10]` and `X` is a tensor of shape... | f5178fd81a0b38217e5c66ab116e1781bc8d8a92 | 657,457 |
import pickle
def pickle_loads(input_data):
"""
把 python bytes 数据类型 转为 原来的数据类型
:param input_data:
:return:
"""
return pickle.loads(input_data) | c72ae2e0688f107c02a01b6f00faa12d1bfa765e | 657,458 |
def point(value):
"""
Convert an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
return "{:20,.2f}".format(value) | 4570ae24cdb64ffce8b0aefdfd66684ed0db8f16 | 657,459 |
import itertools
def multiindex_iterator (shape, *, melt_1_tuple=False):
"""
Provides a tuple-valued iterator to iterate over all multi-indices with given shape.
For example, if shape is (2,3), then the iterated sequence is:
(0,0), (0,1), (0,2), (1,0), (1,1), (1,2).
If len(shape) is 1 and me... | 2bee9b8f4094ec7f97eda3c3ca6bf20e23a4e0a2 | 657,460 |
def is_server_error(code):
"""Return that the server is aware that it has erred or is incapable of performing the request."""
return 500 <= code <= 599 | b4300537f5a50a7c34a006c827a1c77f225fd3c0 | 657,461 |
def filter_and_sort(file_list):
""" Out of a list of file names, returns only the ones ending by
'.py', ordered with increasing file name length.
"""
file_list = [filename for filename in file_list
if filename.endswith('.py')]
def key(item):
return len(item)
... | b87edcb318b49b5fcbd68ccb2397701e3518963d | 657,462 |
def getComboIndex(combo_box, label, ignore_casing=False):
"""
This will return the index of the first matching label within a combo
box qwidget.
If no label is found 0 is returned
:param combo_box: Widget to iterate through
:type combo_box: QComboBox
:param label: The combo label to match... | c67a7159e5a3875c53aed26c6a0a9c9ad78790be | 657,463 |
import os
def help():
"""Get help message."""
path = os.path.join(os.path.dirname(__file__), 'templates/help.html')
lines = open(path, 'r').readlines()
text = ''.join(lines)
return text | 40ff85023291c16a54c81afaf1eb44355364a2df | 657,464 |
import sys
def skip_if_py3(f):
"""Unittest skip test if PY3 decorator."""
PY2 = sys.version_info < (3, 0)
return f if PY2 else lambda self: print('not run in PY3.') | 0092e54c0299deb2b9df4cd3cf3d398d0002a11c | 657,465 |
def read_table (lines):
"""Reads to the next divider line.
Read lines are returned, 'lines' is reduced to everything remaining.
"""
table_lines = []
while len(lines):
popline = lines[0]
lines = lines[1:]
if popline[:6] == "======":
break
table_lines +... | bbc4a87f3e4ec62eca601c6b375f1c90091a4885 | 657,466 |
def arch_handler(value, **kwargs):
"""
Return a Package URL qualifier for the arch.
"""
return {'qualifiers': 'arch={}'.format(value)} | 0e7ff319eb2f62a85dce90a13ce44325a548e163 | 657,467 |
import torch
def maskNLLLoss(inp, target, mask, device):
"""
This loss function calculates the average negative log likelihood of the elements that correspond to a 1 in the mask tensor.
:param inp:
:param target:
:param mask:
:param device:
:return:
"""
# loss_fn = nn.CrossEntropy... | 975d12c208d2776f3c6ace988fa978788a125533 | 657,468 |
def convert_tags(tags):
"""Will convert tags so the article can be uploaded to dev.to. This involves removing the `-` and making the tag
lowercase.
Args:
tags (list): The list of tags to convert.
Returns:
list: The list of converted tags
"""
new_tags = []
for tag in tags:
... | 70527344c1f19c2b2c96a3697e02262a14a3302d | 657,469 |
def shall_exclude_diagnostic_message(message):
"""Exclude certain diagnostics messages"""
exclusion_list = [
"-fno-canonical-system-headers",
"-Wunused-but-set-parameter",
"-Wno-free-nonheap-object",
"-Werror=init-list-lifetime",
"-Werror=class-conversion",
]
retu... | 68b9e005f08ddb41541bc4fafdcceecfbf8cfab4 | 657,470 |
def _gen_item_dt(items):
"""
生成试题字典,key为试题顺序,value为试题所在维度
:param items: list(int), 试题维度排列列表
:return: dict(int: int) 试题字典
"""
item_dt = {}
for i, item in enumerate(items):
item_dt[i] = item
return item_dt | beeaf46529034030ab613889de23574215b2bf29 | 657,471 |
def slurp(f):
"""
Returns file content as string
"""
fd = open(f)
buf = fd.readlines()
fd.close()
return ''.join(buf) | f99a67e49f6e91594f38f85e7b0372f243d92b6a | 657,472 |
def encode_fourcc(fourcc):
"""Encodes 4 bytes in reverse order"""
return ord(fourcc[0]) << 24 | ord(fourcc[1]) << 16 | ord(fourcc[2]) << 8 | ord(fourcc[3]) | 840a296340d6481f5c829d954777b89df7a75d28 | 657,473 |
def evaluate_velocity_at_bottom(layer, prop):
"""
Evaluate material properties at bottom of a velocity layer.
.. seealso:: :func:`evaluate_velocity_at_top`, :func:`evaluate_velocity_at`
:param layer: The velocity layer to use for evaluation.
:type layer: :class:`~numpy.ndarray`, dtype = :py:const:... | 3320c7a316cd9eb6539cf013be745b9e154dfdbe | 657,474 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.