content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def parse_arxiv_json(data):
""" Parses the response from the arxiv_metadata collection in Solr
for the exact search on arxiv_identifier. It returns the published date of
the first version of the paper (i.e. if there are multiple versions, it
ignores the revision dates)"""
docs = data['response'][... | c012ad6d0fb9c63d56413adc22321edbea3efa85 | 154,890 |
def get_protocol(url, default="http"):
"""
Extracts the protocol, or returns value of default param (defaults to http)
"""
double_slash = url.find("//")
if double_slash == -1:
protocol = default
else:
protocol = url[:url.find('//')]
if protocol.endswith(':'):
protocol = protocol[:-1]
if protocol == ... | d385ae97040744e2f2ffaea7d67c801d34098ae0 | 590,547 |
def _check_if_found(new_term: str, targets: list) -> bool:
"""
Checks if `new_term` matches `targets`.
:param new_term: string to check
:param targets: list of strings to match to `new_term`. Targets can be a list of specific targets, e.g.
['UBERON:123219', 'UBERON:1288990'] or of general ontol... | 05b4227c466e17942e3d1849a94af704c20880e7 | 495,967 |
def rotate(list, places):
"""Shift the elements in a list. A positive place will move the list
to the left, a negative place to the right."""
return list[places:] + list[:places] | d7c06f233d0f0946274f555b45b8ab0cb08fe62d | 88,989 |
def ip4_subnet_c(ip):
"""returns C subnet of ipv4 address e.g.: 1.2.3.4 -> 1.2.3.0"""
return ".".join(ip.split(".")[:-1]) + ".0" | c7f68e5a1d82ea179d9ffd61eb46665cbb95593d | 489,611 |
def has_value(value):
"""
We want values like 0 and False to be considered values, but values like
None or blank strings to not be considered values
"""
return value or value == 0 or value is False | 1ffabaed22b2a1b83b89eb4d551c6e776a8e13c0 | 676,224 |
def repeat_list_elements(a_list, rep):
""" Creates a list where each element is repeated rep times. """
return [element for _ in range(rep) for element in a_list] | c503ecef4e29fe334cfa565ea1dab5fa20406b5c | 447,769 |
def count_meme_entries(motif_path):
"""Count number of meme entries"""
with open(motif_path, "r") as f:
counter = 0
for line in f:
if line[:6] == "letter":
counter += 1
return counter | 90c0cc72b2693c18a2d7f91451044fc096f71b90 | 477,891 |
def get_domains(contents_list):
"""
Return list of domains without <br/>
"""
return [item for item in contents_list if str(item) != '<br/>'] | fcd90195dac03c486abdbb69504d3edb765d5437 | 326,610 |
from pathlib import Path
def broken_config(tmp_path):
"""
Writes a improperly formatted config.yml file into the directory
broken_config.
"""
# Create directory for the config (to avoid messing up the config
# in tmp_path used by other tests)
dir = Path(tmp_path, "broken_config")
dir.... | 02512fb3e38804420c5c969fb905b5d8cee716cd | 247,202 |
def _validate_prefix(prefix, avoid):
"""
Validate an install prefix.
"""
if prefix.startswith(avoid):
rest = prefix[0:len(avoid)]
return rest != "/" and rest != ""
return True | 6be541f65334a28ea09d6237f9e54cbfce9347f0 | 641,272 |
def cowsay(input_string):
"""Return ASCI art of a cow saying the input_string."""
output_string = " "
for letter in list(input_string):
output_string += "_"
output_string += "__\n< {} >\n ".format(input_string)
for letter in list(input_string):
output_string += "-"
output_strin... | e692b429f54b1d7de96360a90adfc66fe56d0346 | 216,902 |
def _coerce_to_list(obj):
"""Return [obj] if obj is not a list, otherwise obj."""
if not isinstance(obj, list):
return [obj]
else:
return obj | 0763f05cf6e781ca8847c61c45845351dc375691 | 470,012 |
def rgb2rgb01(r, g, b):
""" Convert between RGB [0-255] and RGB [0-1] """
return tuple([ float(i)/255. for i in [r,g,b] ]) | 4cd3d47c41de3927d8a0878130651cb714e44256 | 495,293 |
def global_flip_lr(boxes3d):
"""Flip y axis (y coordinate of the center position and yaw angle)"""
boxes3d['c'][:,1] *= -1
boxes3d['r'][:,2] *= -1
return boxes3d | 01cc62960740c47d16070b0b863f3731fcf10edc | 148,310 |
import shutil
def tempfiles(tmpdir, filespath):
"""Fixture for copying test files into a temporary directory"""
dest = tmpdir.join('testfiles')
shutil.copytree(filespath, str(dest))
return str(dest) | 88dafc571a6c4bc678ce18463122abe994cb6dd0 | 601,403 |
def strings_to_ints(lst):
"""transforms a list of strings to a list of ints
ARGS:
list of strings
RETURNS:
list of ints
RAISES:
ValueError: when the string in the list is not a number
"""
return [int(x.strip()) for x in lst] | bf81cdcc03fa7750391594f25e46fcb99a229a9c | 531,945 |
import hmac
def calculate_message_signature(key: str, msg: str):
"""
calculate a message signature using a SHA1 HMAC
:param key: the secret token
:param msg: the message
:return: the calculated HMAC
"""
return hmac.new(key.encode(), msg=msg.encode(), digestmod='sha1').hexdigest() | d38ca1d4c219cc3e3e47b87c0ad71e4921f63e93 | 624,413 |
from typing import List
def count_occupied_seats(layout: List[List[str]]) -> int:
"""
Count quantity of occupied seats in a given layout
:param layout: seat layout
:return: quantity of occupied seats
"""
occupied_seats = sum(sum(1 for seat in r if seat == '#') for r in layout)
return occ... | 64dd38f46ec8148d04dba5ee2bb2f8765ef8b6d0 | 356,220 |
def vb_scale(vb, p_a_r, doc_width, doc_height):
""""
Parse SVG viewbox and generate scaling parameters.
Reference documentation: https://www.w3.org/TR/SVG11/coords.html
Inputs:
vb: Contents of SVG viewbox attribute
p_a_r: Contents of SVG preserveAspectRatio attribute
... | fafd361fc29a49d30f3ee0092feca1ec91b99402 | 506,424 |
def swap(number, i1, i2):
"""
Swap given bits from number.
:param number: A number
:type number: int
:param i1: Bit index
:type i1: int
:param i2: Bit index
:type i2: int
:return: A number with given bits swapped.
:rtype: int
>>> swap(0b101011, 1, 4) == 0b111001
True
... | b02399ef5242a0e396a9e09e3dc807958d44faf4 | 404,698 |
def get_support(cluster):
"""
Returns support
>>> get_support({5: {'11111': ['ab', 'ac', 'df', 'bd', 'bc']},
... 4: {'11101': ['ef', 'eg', 'de', 'fg'], '11011': ['cd']},
... 3: {'11001': ['ad'], '10101': ['dg']},
... 2: {'10010': ['dh', 'bh'], '11000': ['be... | 33082e6e89a6c116f93a8aed0d64f0e1fa2e74bb | 451,488 |
def is_end_word(word):
"""
Determines if a word is at the end of a sentence.
"""
if word == 'Mr.' or word == 'Mrs.':
return False
punctuation = "!?."
return word[-1] in punctuation | 9165fede070654b3d0b10b2bb02855307f9ab0c5 | 67,187 |
import math
def lmoments_parameter_estimation_generalized_logistic(lambda1, lambda2, tau):
"""Return the location, scale and shape or the generalized logistic distribution
Based on SUBROUTINE PELGLO of the LMOMENTS Fortran package version 3.04, July 2005
:param lambda1: L-moment-1
:param lambda2: L-... | d25b5c5891cdc00779c7a20458bae0c5dd061510 | 252,470 |
def is_same_scanner_position(*images):
"""Check that all images have the same unique scanner position.
Parameters
----------
images : sequence[MRI]
Returns
-------
True if all elements of the input set have the same unique scanner
position (which is not `None`).
"""
uids = [im... | b75e9c790aefbf184675f8e29aebdcec4e12d21f | 480,174 |
def sizeof(bsObj):
""" Size of BotSense object in bytes. Size is contextual by object type. """
return bsObj.__sizeof__() | 70c55a9002e336d2d827ee21d04260dfc328d7fc | 689,127 |
from typing import Any
import torch
def is_singleton_tensor(x: Any) -> bool:
"""Is x a dimensionless tensor?"""
return torch.is_tensor(x) and x.dim() == 0 | 6da89e669928f43a1a87a848b6a512f0c2df2bf2 | 394,258 |
def convert_attr_name(s):
"""Convert all underline in string name to space and capitalize
"""
return " ".join(map(str.capitalize, s.strip().split("_"))) | 6ba56ccef5091ae33588c9a48a244bfefebd9d45 | 607,089 |
def kilometers_to_miles(input_km_value):
"""Convert kilometers to miles.
:param input_km_value: Kilometer value to convert to miles
:type input_km_value: float, int
:return: Miles
"""
return input_km_value * 0.621371 | 9b57983029fe48aec49d45d8bebc74abbb6983c7 | 440,423 |
def format_fuzzy_result(es_result):
"""
format the es search result to front end processable format
@param es_result: the es search result
@type es_result: dict
@return: the front end processable format, while will be like this::
[{'compound_id': id, 'name': name},...]
@rtype: list
... | d5ed35d0b11b60d1dfe4ef72b1c374584a8661b4 | 142,591 |
def get_element_tag(element):
"""Returns the tag name string without namespace of the passed element."""
return element.tag.rsplit('}')[1] | 6b5ace48209a711db1c1d33e5acc28f7e245ea3e | 634,263 |
def _convert_ITP_to_path_to_index(index_to_path):
"""convert index_to_path pandas series to path_to_index dict
----
index_to_path:(pandas.series)
returns
path_to_index:(dict) {path:[indices corresponding to that path]}
"""
path_to_index = dict()
for i in index_to_path.index:
index, path = i, index_to_path[i... | 84f816b8af4e9cfa56e1d6c8100428e39b746419 | 312,146 |
import json
def js_r(file_path: str) -> dict:
"""
Read a .json file into a dictionary
Parameters
----------
file_path: str
the path to the .json file
Returns
-------
the .json file in dictionary format
"""
with open(file_path) as f_in:
return json.load(f_in) | 5cfe7ce205f46c0de88357933a046e3317f68d68 | 371,777 |
def _get_action_profile(x, indptr):
"""
Obtain a tuple of mixed actions from a flattened action profile.
Parameters
----------
x : array_like(float, ndim=1)
Array of flattened mixed action profile of length equal to n_0 +
... + n_N-1, where `out[indptr[i]:indptr[i+1]]` contains play... | ffeb0a38f07d16079723beddf73ce090135af43c | 626,742 |
def _get_all_osc(centers, osc_low, osc_high):
"""Returns all the oscillations in a specified frequency band.
Parameters
----------
centers : 1d array
Vector of oscillation centers.
osc_low : int
Lower bound for frequency range.
osc_high : int
Upper bound for frequency ra... | 9199283080bd0111d8ca3cb74f4c0865de162027 | 13,903 |
def coin_snapshot(self, fsym, tsym):
"""
https://www.cryptocompare.com/api/#-api-data-coinsnapshot-
Keyword arguments:
fsym - The symbol of the currency you want to get that for
tsym - The symbol of the currency that data will be in.
"""
self._is_params_valid(fsym=fsym, tsym=tsym)
... | 087e76cc56d9246da3293aacaccc1e5a847e79f2 | 339,755 |
def vumps_params(checkpoint_every=500, gauge_via_svd=True, gradient_tol=1E-3,
max_iter=200):
"""
Bundles parameters for the vumps solver itself.
PARAMETERS
----------
gradient_tol (float) : Convergence is declared once the gradient norm is
at least th... | 9b5bd7f4f9f560a3991c1205ca1549d5eb12dabf | 143,703 |
def finite_diff_gradient_descent(f, begin, end, x0=None, niters=10, lr=1):
"""Find the local minima using gradient descent
Parameters:
f (function): Function to find the local minima
begin (int): beginning of the interval
end (int): end of interval
x0 (int): initial point
... | fa1738c0ccb82f353053a6654b0856900b8f0996 | 219,322 |
def _get_module_src_file(module):
"""
Return module.__file__, change extension to '.py' if __file__ is ending with '.pyc'
"""
return module.__file__[:-1] if module.__file__.endswith(".pyc") else module.__file__ | 8fe71809a1d3c1ff4efe01c740e9724c2dbf702a | 213,510 |
def find_index_list(inputlist, key):
"""get a list of index for key in inputlist"""
start = 0
indexlist = []
while 1:
try:
index = inputlist.index(key, start)
except:
break
indexlist.append(index)
start = index + 1
return indexlist | 453365cc45c927446f08b9d3f448fcd62c54f6da | 57,689 |
def parse_test_names(test_name_args):
"""Returns a dictionary mapping test case names to a list of test functions
:param test_name_args: The parsed value of the ``--test`` or ``--skip``
arguments
:return: None if ``test_name_args`` is None, otherwise return a dictionary
mapping test case n... | a1c5aed647f9b77289c1c23b16b3703b722cb432 | 600,554 |
def _ValidateRepoToDepPathConfig(repo_to_dep_path):
"""Checks that the repo_to_dep_path is properly formatted.
Args:
repo_to_dep_path (dict): A dictionary mapping repository url to its
chromium repo path.
For example:
{
"https://boringssl.googlesource.com/boringssl.git":
... | 1ac03d9c3aa20f2c988cf9990202cbe34ff3ed2a | 383,906 |
def _pad_with_nulls(data, len_):
""" Pad string with null bytes.
Parameters
----------
data : str/bytes
the string/bytes to pad
len_ : int
the final desired length
"""
return data + (b'\x00' * (len_ - len(data))) | 238cc6c7b883d087cfa09131eec2b463054f791e | 662,260 |
def ensure_keys(dict_obj, *keys):
"""
Ensure ``dict_obj`` has the hierarchy ``{keys[0]: {keys[1]: {...}}}``
The innermost key will have ``{}`` has value if didn't exist already.
"""
if len(keys) == 0:
return dict_obj
else:
first, rest = keys[0], keys[1:]
if first not in ... | e8d87444ed8961d8d650b49c8670dca1496623b1 | 29,550 |
import io
def read_file(file):
"""Open and read file input."""
f = io.open(file, 'r', encoding='utf-8')
text = f.read()
f.close()
return text | 8c5e65f59e0475473c29798a8aa10d038628a9b4 | 51,459 |
def fst(pair):
""" First of a pair."""
return pair[0] | 62f207e03b07a731bb9616c27d9393b2eb8ff2a1 | 485,813 |
def calculate_test_values(
total_words, ocr_recognized_words,
tp, tn, fn
):
"""
Calculates the model test values :
TP : True Positive (There are words and every word has been recognized)
TN : True Negative (There is no word and no word has been recognized)
FP : False Positive (There ... | e0de958ff308ac3c6a1425203ff3b92b1ecb5fca | 32,265 |
def get_message_ids(service):
"""
Returns all the message ids from the user
'INBOX'.
"""
msg_list = service.users().messages().list(userId='me',
labelIds='INBOX').execute()
message_ids = msg_list['messages']
return message_ids | 24c8a2ccbef25449487171895df8555db4b875e8 | 192,530 |
def get_square_color(box, x, y, side):
"""Gets the color of the square with its top left corner at (x, y) and with the sides being a length of side
Returns None if they are not all the same color or if side == 1"""
colors = set()
for i in range(side-1):
for j in range(side-1):
color... | 2841b25ce03046cda61f4af43ac14d7f14c0629a | 514,491 |
def consume_byte(content, offset, byte, length=1):
"""Consume length bytes from content, starting at offset. If they
are not all byte, raises a ValueError.
"""
for i in range(length-1):
if content[offset + i:offset + i+1] != byte:
raise ValueError(("Expected byte '0x%s' at offs... | 1ff372d2ae0766aedbddefae86c52851d6c172ce | 134,276 |
def merge_qs_maps(obj1, obj2):
"""
Merge queryset map in `obj2` on `obj1`.
"""
for model, [qs2, fields2] in obj2.items():
query_field = obj1.setdefault(model, [model.objects.none(), set()])
query_field[0] |= qs2 # or'ed querysets
query_field[1].update(fields2) # add ... | d8d669eea385c73ac0322519dde27227fc737772 | 526,310 |
def generate_factor_list(factor_list, df):
"""
Create a dictionary that contains the unique values of different
factors based on the input dataset for visualizations toggling.
Args:
factor_list(list): List containing
factors the user want to toggle when interacting with
... | a7311e8f000e324c33f49f2766192d2f88e74918 | 415,950 |
def forward_box(box):
"""Increase box level (max 4)
Parameters
----------
box: int
question box level
Returns
-------
int: updated box
"""
if box < 4:
box += 1
return box | ae0de5b0821e8bde81063471f1f3768022d1856e | 104,249 |
def _quadratic_bezier(y_points, t):
"""
Makes a single quadratic Bezier curve weighted by y-values.
Parameters
----------
y_points : Container
A container of the three y-values that define the y-values of the
Bezier curve.
t : numpy.ndarray, shape (N,)
The array of value... | 7c5cf27ce2fadb0843039729dc0f01473dfa946c | 696,382 |
def all_1_bits() -> int:
"""
Returns:
Examples:
>>> all_1_bits()
-1
>>> bin(all_1_bits())
'-0b1'
"""
return ~0 | 174bef7cd9315152b2bd4232352724bb6de32660 | 170,644 |
def ignore(name, *names):
"""
Function decorator used to ignore certain parameters of your function
when it is converted to command. You can specify one or more parameters
to ignore.
Parameters
----------
name : str
Name of the parameter.
names :
Specify more parameters ... | 72b14dd6cd7490c1b34b4fd12af6d3a963023c64 | 456,500 |
def checkBaseClassesMatch(bases, typename):
"""Recursively check if the name of the types in bases (or parents) are equal to typename
| *Args:*
| bases - A tuple of types
| typename : str - A name of a type
| *Returns:*
| True if any of the names of types in bases or any of... | f71a26fa9dd1af65aff54c5b850624177636c679 | 191,294 |
def get_equipped_in_slot(actor, slot):
"""
Returns Equipment in a slot, or None.
"""
if hasattr(actor, 'inventory'):
for obj in actor.inventory:
if obj.equipment and obj.equipment.slot == slot and obj.equipment.is_equipped:
return obj.equipment
return None | 68afd2af8fe7418756ba3b40cb40918be0559cd7 | 575,804 |
def my_reverse(L):
"""
Accepts a list `L` and reverses its elements. Solves problems 1 & 2.
Parameters
----------
L : list
The list to be reversed.
Returns
-------
revL : list
The reversed list.
"""
# Initialisations
revL = list() # The empty list to be app... | 8bb582c4bd41923120899b17cd34f3302a3fdec2 | 387,011 |
def GetExamples(node):
"""Returns the examples (if any) for some Unit node."""
return node.examples | 592a6bcd01469ab02c8a3a761d18c50408274405 | 217,780 |
def get_Id_Iq(self):
"""Return Id and Iq
Parameters
----------
self : OPdq
An OPdq object
Returns
-------
I_dict : dict
Dict with key "Id", "Iq"
"""
return {"Id": self.Id_ref, "Iq": self.Iq_ref} | cba09701c3cd1fb9dda0a560c14819560a38b48e | 598,639 |
from typing import Tuple
def split_str_date_dt_sc(str_date: str) -> Tuple:
"""Split string date to date and time.
:param str_date: String date in the format YYYY-MM-DD
:return: Tuple with date and time
"""
if ' ' not in str_date:
dt = str_date
sc = '00:00:00'
else:
dt,... | 67854369cbac20370d658bcfd2c2356049606236 | 153,712 |
def bubble_sort(array):
"""
Sort array in ascending order by bubble sort
Bubble sort, sometimes referred to as sinking sort,
is a simple sorting algorithm that repeatedly steps
through the list, compares adjacent pairs and swaps
them if they are in the wrong order.
- Best-case time perform... | 6947d7a3fb646f6cb44b11359fbf4bcede35e584 | 352,088 |
def get_strip_square(image, idx):
"""gets the idxth square from a horizontal strip of images"""
square_size = image.size[1]
x_start = square_size * idx
result = image.crop((x_start, 0, x_start + square_size, square_size))
result.load()
return result | 6640f79b38b56b80ea6ae38a404d4fb136424dd0 | 170,169 |
def create_cmd(parts):
"""Join together a command line represented as list"""
sane_parts = []
for part in parts:
if not isinstance(part, str):
# note: python subprocess module raises a TypeError instead
# of converting everything to string
part = str(part)
... | c7fe6e58d32c96fe4d70a3cc1290638170351b88 | 636,123 |
def get_login_url(client_id: str, redirect_uri: str) -> str:
"""
Returns the url to the website on which the user logs in
"""
return f"https://login.live.com/oauth20_authorize.srf?client_id={client_id}&response_type=code&redirect_uri={redirect_uri}&scope=XboxLive.signin%20offline_access&state=<optional;... | 924732c531287d592607f8cb8741b5e620fec8d9 | 441,058 |
def eval_input(variable, table):
"""
Requests user input for given variable and assigns it to a copy of the
table
"""
copy_table = table.copy()
input_val = int(input("Enter value for " + variable + ": "))
copy_table[variable] = input_val
return copy_table | bfd0be3a599a81218462ccabe3b0c8f127fc19e2 | 363,981 |
import torch
def from_onehot(onehot, dim=-1, dtype=None):
"""Argmax over trailing dimension of tensor ``onehot``. Optional return
dtype specification."""
indexes = torch.argmax(onehot, dim=dim)
if dtype is not None:
indexes = indexes.type(dtype)
return indexes | c011060789ec4eeb46a3aae29be4691ba215f313 | 215,830 |
from typing import Any
import io
def is_file_like(value: Any) -> bool:
"""Check if a value represents a file like object"""
return isinstance(value, io.IOBase) | 291d72b0ef930951872928a769b7126e35576cdd | 647,994 |
def to_secs(x: str) -> int:
"""Convert time from hh:mm:ss (str) format to seconds (int).
"""
h, m, s = x.split(':')
return int(h) * 3600 + int(m) * 60 + int(s) | 56ea0efb12ddb287c4cb218e1625d497d1f1a8a0 | 532,928 |
def create_mae_rescaled(scale_factor):
"""Create a callback function which tracks mae rescaled
Arguments:
scale_factor: Scaling factor with which the labels were scaled initially
"""
def mae_rescaled(y_true, y_pred):
difference = abs(y_pred - y_true)
return difference / scale_fa... | 70380a2845f58e4ddb80252819c0e5aaa8521e43 | 247,728 |
def filter_arglist(args, defaults, bound_argnames):
"""
Filters a list of function argument nodes (``ast.arg``)
and corresponding defaults to exclude all arguments with the names
present in ``bound_arguments``.
Returns a pair of new arguments and defaults.
"""
new_args = []
new_defaults ... | d6346cfdc7a8579411223f11fcfc946dc4ac4a10 | 689,991 |
def only_sig(row):
"""Returns only significant events"""
if row[-1] == 'yes':
return row | 12ff2d7b5cea4a01f3ecbba81dc1f4f982f7bd5a | 109,229 |
def rowmul(matlist, index, k, K):
"""
Multiplies index row with k
"""
for i in range(len(matlist[index])):
matlist[index][i] = k * matlist[index][i]
return matlist | aa365da33d80e2cb90c14e2b1af1a19cbfacb947 | 147,612 |
from typing import List
from typing import Any
def _partition(items: List[Any], left: int, right: int) -> int:
"""Partitions the array around the pivot value.
Picks a pivot value and sorts everything to the left <= pivot,
and everything greater than pivot to the right.
At the end, the pivot will be ... | 4d28a10efc8034be97bc693956686c0f5d2db537 | 277,043 |
def sorted_equality(v1, v2, read):
"""
Equality for fields where the values must be sorted before equality tested.
"""
return sorted(v1) == sorted(v2) | ff9a4cfd917b04dda5655ef2c28489f9fa46626c | 567,501 |
def get_model(dataset, model_hparams):
"""Return the dataset class with the given name
Args:
dataset (str): name of the dataset
model_hparams (dict): model hyperparameters
"""
if model_hparams['model'] not in globals():
raise NotImplementedError("Dataset not found: {}".form... | 106413e5874a90322da047062a822c027905b138 | 289,151 |
import json
import requests
def metadata_post_request(file_name, metadata, auth_parameter, url):
"""
Used to structure and make the post request for metadata to Zenodo.
Parameters
----------
file_name : str
The name of the file to be created.
metadata : dict
The PresQT metadat... | 150d342257cdd9ee7a3576878a17aced2be9faa3 | 515,318 |
import re
def uncamel(s):
"""Convert CamelCase to underscore_case."""
return re.sub('(?!^)([A-Z])(?=[^A-Z])', r'_\1', s).lower() | 4192de6b8cdf5c2b7cd380e40e662bb3f7892152 | 344,052 |
import re
def _GenerateSensitiveWordsRe(words):
"""Returns the regexp for matching sensitive words.
Args:
words: A sequence of strings.
Returns:
A pattern object, matching any of the given words. If words is empty,
returns None.
"""
if not words:
return None
union = []
for word in word... | 4ee004d96b57480d307a1f9a450600d30ed12741 | 223,360 |
def get_bill_to_address(user):
"""
Create an address appropriate to pass to billTo on the CyberSource API
Args:
user (User): the user whose address to use
Returns:
dict:
User's legal_address in the appropriate data structure
"""
legal_address = user.legal_address
... | 8558a4e2185d4f634695bf4d8248b744c17cc557 | 57,360 |
def fold_whoopsies(whoopsies1, whoopsies2):
""" Merge whoopsies2 into whoopsies1
sorted on query, then descending on magnitude
of the whoops (so biggest whoops for queries come first)"""
whoopsies1.extend(whoopsies2)
whoopsies1.sort(key=lambda x: (x.qid, 1000-x.magnitude()))
return whoop... | 078532ce2ec15c2e2c27fb935b7b7e634adce636 | 344,635 |
def set_ipu_model_options(opts, compile_ipu_code=True):
"""Set the IPU Model options.
Args:
compile_ipu_code: Whether or not to actually compile real IPU code for
modelling.
Returns:
The IpuOptions configuration protobuf, with IPU model options set.
"""
opts.ipu_model_config.compile_ipu_code =... | d5e9577fb9ebad81b6fedb1988561197dbd3028e | 697,255 |
def _ta_append(tensor_array, value):
"""Append a value to the end of a tf.TensorArray."""
return tensor_array.write(tensor_array.size(), value) | 1bad0472a2c1e51c7563608c8d2439c18026f9b6 | 190,958 |
def build_cmd(*args, **kwargs):
"""
>>> build_cmd('script.py', 'train', model_pickle='tmp.pkl', shuffle=True)
'script.py train --model_pickle "tmp.pkl" --shuffle'
"""
options = []
for key, value in kwargs.items():
if isinstance(value, bool):
if value:
options.... | c6adf3618b4541d54c0c005e6fcab99288c1f1b2 | 244,552 |
def StripSo(name):
"""Strip trailing hexidecimal characters from the name of a shared object.
It strips everything after the last '.' in the name, and checks that the new
name ends with .so.
e.g.
libc.so.ad6acbfa => libc.so
foo.bar.baz => foo.bar.baz
"""
stripped_name = '.'.join(name.split('.')[:-1])... | ac7914867388e0a84f0252be5c29a8ceecc7b9b6 | 312,706 |
def any_ga(geoawi):
"""
GEOAWI: GA W/I GRID
0=None
1=Quest
2=<I2
3=<O2
4=<1/2 DA
5=<1DA
6=<2DA
7=>2DA
8=CG
Returns:
0, 1, 88
"""
if geoawi == 0:
return 0
elif 1 <= geoawi <= 7:
return 1
elif geo... | 1db941f44a23f8ec99fb27efd395cc12c8902544 | 669,299 |
def transpose(table):
"""
Returns a copy of table with rows and columns swapped
Example:
1 2 1 3 5
3 4 => 2 4 6
5 6
Parameter table: the table to transpose
Precondition: table is a rectangular 2d List of numbers
"""
result = []... | fe84714d3e09deb22058fd75ac3333c2206f77c3 | 704,561 |
def shake_drop_eval(x, mask_prob, alpha_min, alpha_max):
"""ShakeDrop eval pass.
See https://arxiv.org/abs/1802.02375
Args:
x: input to apply ShakeDrop to
mask_prob: mask probability
alpha_min: alpha range lower
alpha_max: alpha range upper
Returns:
"""
expected_alpha = (alpha_max + alpha... | ee19a07eaf42d4be3fcccf2850109044eea1c826 | 457,431 |
def measure(obj, depth=0):
"""
Returns the number of nodes, properties and the depth of an inspect tree.
`obj` is a dict read from JSON that represents inspect data
"""
nodes = 0
properties = 0
max_depth = depth
for (_, child) in obj.items():
# ensure this is a node that is not a... | cd7a4d7a7d2a2fea41a09b1edd5b1cb1a4403bea | 124,640 |
def shrink_sides(image, ts=0, bs=0, ls=0, rs=0):
"""Shrinks/crops the image through shrinking each side of the image.
params:
image: A numpy ndarray, which has 2 or 3 dimensions
ts: An integer, which is the amount to shrink the top side
of the image
bs: An integer, which is t... | 6858a75516626affb3d65b9c8aad8bd207cfe495 | 54,186 |
import re
def opensearch_clean(f):
"""
Some opensearch clients send along optional parameters from the opensearch
description when they're not needed. For example:
state={openoni:state?}
These can cause search results not to come back, and even can cause Solr's
query parsing to thro... | 862bf8cbb9a2629949746a92b78b3b23bdfd7c49 | 38,273 |
def GetLoans(sliver_name):
"""Return the list of loans made by the specified sliver"""
rec = sliver_name
return rec.get('_loans', [])[:] | 4736034a729a7135e851110b1f57c996367b7232 | 577,154 |
def humanize_seconds(seconds):
"""
Returns a humanized string representing time difference
between now() and the input timestamp.
The output rounds up to days, hours, minutes, or seconds.
4 days 5 hours returns '4 days'
0 days 4 hours 3 minutes returns '4 hours', etc...
"""
minutes, seconds = divmo... | 22051f1467ebffa89d061cb5301b789338f69eb5 | 521,479 |
import types
def is_object_module(obj):
"""
Test if the argument is a module object.
:param obj: Object
:type obj: any
:rtype: boolean
"""
return isinstance(obj, types.ModuleType) | b9dc22543b19be02f0cd2ac396370affcd0e3aeb | 643,223 |
def convert_to_list(obj):
""" receives an object and if type tuple or list, return list. Else
return a list containing the one object
"""
if type(obj) is None: return [] # None implies empty list...
if type(obj) is list: return obj
if type(obj) is tuple:
return [x for x in obj]
... | aa78ea08f06ffab91feead5898a4433807966c02 | 622,964 |
def fibi(n: int) -> int:
"""Fibonacci numbers saving just two previous values
>>> fibi(20)
6765
>>> fibi(1)
1
>>> fibi(2)
1
>>> fibi(3)
2
"""
if n == 0:
return 0
if n == 1:
return 1
f_n2, f_n1 = 1, 1
for _ in range(3, n+1):
f_n2, f_n1 = f_... | 1e7d331e5572c5a1886c31e7d51d0d3d9710c37f | 390,711 |
def interval_overlap_length(i1,i2):
"""Compute the length of overlap of two intervals.
Parameters
----------
i1, i2 : pairs of two floats
The two intervals.
Returns
-------
l : float
The length of the overlap between the two intervals.
"""
(a,b) = i1
(c... | a22fdd3cf76a503700055bc4077ef9584b6b394b | 640,149 |
def create_mock_resource_resp(dm):
"""Given an instance of Deployment, transforms into resource info as API response."""
return {
"name": dm.name,
"insertTime": dm.insert_time,
"properties": "zone: " + dm.zone,
} | 6c140a2389b220b26f231c066e2d7fe108f7b117 | 599,368 |
from typing import List
def get_characters_from_file(file_path: str) -> List[str]:
"""
Opens the specified file and retrieves a list of characters.
Assuming each character is in one line.
Characters can have special characters including a space character.
Args:
file_path (str): path to th... | 50fda9d3e4b2e1dd5724174549967165879dcc14 | 687,413 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.