content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_comment(line):
"""Check if line is comment."""
return line.startswith("#") | 50d49f48c73750e3fa2b761e416a83ea1425bcbb | 592,260 |
def get_upc(book_detail_soup):
""" Get the book's upc from the book detail soup """
upc = ''
book_table = book_detail_soup.find('table', { 'class' : 'table table-striped' })
trs = book_table.find_all('tr')
#return trs
for tr in trs:
if tr.find('th').get_text(strip=True) == 'UPC':
... | 833939e225ed600d3f61c124613a9b2c3cc624b5 | 592,262 |
def source_extension(source):
"""Get file extension for source"""
extensions = {'gamry':'.DTA','zplot':'.z'}
return extensions[source] | 881df844a222e2bf94f86bbad03d4a7c85e87707 | 592,265 |
def flip(c):
"""
Flip a character's polarity, i.e. a maps to A, B maps to b, etc.
:param c: the single character
:return: the reversed character wrt case
>>> flip('a')
'A'
>>> flip('B')
'b'
"""
return c.upper() if c.islower() else c.lower() | f502de9ce2101480eecc045c95d5fbc412d915da | 592,266 |
import re
def is_valid_zone(zone):
"""True if string looks like a GCE zone name."""
return re.match(r'^[a-z0-9\-]+$', zone) | d6d5327e4ec7a173a52686c7f4e1f5f9324c68f2 | 592,270 |
def _extract_exception_details(request, response, exception):
"""Extracts exception information from a request-response and an exception.
"""
# Set some standard values to fall back to if nothing comes of parsing the
# request and exception details.
code = 500 # Internal server error
title = 'U... | 018c4b86a3df7dd0d53a2b558e27efb577450126 | 592,271 |
def _isobject(target):
"""Return true if target is a lavavu object"""
return target.__class__.__name__ == 'Object' | 93cce4dfa6a7f3c18422eb027933f40404d10d2a | 592,272 |
def get_connection_string(db_username, db_password, db_host, db_port, db_schema):
"""
Returns a connection string according to the given variables.
Format:
mysql://username:password@mysql.db_stack.env.epfl.ch:1234/db_schema
Example:
mysql://aa2ea71b:-CxMbtSVdPcY88MH3Vo7@mysql-78bc59f0.db.rsaas.e... | ae7292b2ca34fb5d3c4c352117f6592bbd61ec8b | 592,275 |
def some_fn(data):
"""Dummy fn that has form of np.array -> np.array"""
return data | 546a1014fc7b6d6b59c3e8305c8adbce819d3a20 | 592,277 |
def clean_response(result):
"""
Clean a response by removing unnecessary fields
"""
result = result["PET"]
try:
del result["BLOQ"]
except (KeyError, TypeError):
pass
return result | 3c658d4fea334f3a843de6c3af3e06bd669bfde9 | 592,279 |
def coincidents(list0, list1, indices):
"""Get coincident values from lists based on indices calculated.
Parameters
----------
list0 : list
List of values
list1 : list
List of values
indices : dict
Dictionary containing index mapping
Returns
-------
items : ... | 306dd259f25aef3d144fc6884a60368e9851bc8f | 592,281 |
def get_ragged_nested_index_lists(df, id_col_list):
"""
Gets the ragged nested lists of indices (= row numbers of `df`).
Hierarchy in the nesting is set up by the `df` columns with names
in `id_col_list`.
Inputs:
= df: Pandas Data Frame with the sample. It ias to contain columns
listed in ... | 3a9a98e2baab5cd12f76f019b9e6af292945f91a | 592,286 |
def manhattan_dist(pose1, pose2):
""" Returns manhattan distance between two poses """
return abs(pose1[0] - pose2[0]) + abs(pose1[1] - pose2[1]) | 9c4de9944febd48d6226e752f21dbdfb75555b81 | 592,287 |
def _extension_ok(filename):
""" Returns `True` if the file has a valid image extension. """
return '.' in filename and filename.rsplit('.', 1)[1] in ('png', 'jpg', 'jpeg', 'gif', 'bmp') | c780516eeaa5b70244ada47df2c34f2e65950575 | 592,291 |
def _union_all(iterables):
"""Union entries in ``iterables`` into a set.
"""
return set().union(*iterables) | b41af228e7c35d6825f01823ec84f73278f76ea1 | 592,296 |
def furthest_right_point(list_of_points):
"""Given a list of 2D points (represented as Point objects), uses "max" with
the "key" argument to return the point that is furthest to the right (that
is, the point with the largest X coordinate)."""
return max(list_of_points, key = lambda point:point.getX()) | 758c139804fa2215c62d2b014be076133143aa8f | 592,298 |
def _formatArraySplitWiden(arFmtSplit, blank, linecount):
"""Private func that gets iterated over as part of enjambing multiple formatted arrays side-by-side.
Adds spaces such that the mutable sequence arFmtSplit (if joined by `\n`) will print as a rectangle.
Optionally also extends the "height" of the rect... | d4176d890dea307e3426d1194bc01fd899176860 | 592,300 |
def isrange(a, b):
"""
Return True if the passed tuple `(a,b)` is a valid range
(that is, `a` may not be greater than `b`).
"""
#~ if r[0] is None or r[1] is None: return True
#~ if r[0] <= r[1]: return True
if a is None or b is None:
return True
if a <= b:
return True
... | b7c7b09d586b066d8d24e7877c62612e49731ded | 592,301 |
from typing import Union
from pathlib import Path
import json
def read_json(filename: Union[str, Path]) -> Union[dict, list]:
"""Read a dict or list from a JSON file"""
with Path(filename).open("r", encoding="utf-8") as f:
return json.load(f) | 227338e4ac11dc4323203a1478bbd02a0be19ce9 | 592,303 |
import copy
def FillSymmetricMatrix(matrix, N):#{{{
"""
Fill in the bottom left part of a symmetric matrix, give the upper right
corner filled. The input matrix is un-changed
------
|+++++
| ++++
| +++
| ++
| +
"""
mtx = copy.deepcopy(matrix)
for i in range(N):
... | 858cb4d09365192590f1dd48bce882d3e4779af0 | 592,304 |
def as_readable(dataset_name: str) -> str:
"""Convert name on disk to readable for the user"""
return dataset_name.replace('_', ' ') | 5607677cab152922a70ea2db133f72f7d36cddac | 592,309 |
def main(*, base, exponent):
"""entrypoint function for this component
Usage example:
>>> main(
... base = pd.Series(
... {
... "2019-08-01T15:20:12": 3.0,
... "2019-08-01T15:44:12": None,
... "2019-08-03T16:20:15": 0.3,
... "20... | 73a8853835093f1fc2d35f5456f04bb9460eca54 | 592,310 |
def get_cv_object(train):
"""
Return Time Based CV Object.
Time based CV scheme: {train month(s) - test month}
{1}-{2}
{1,2}-{3}
{1,2,3}-{4}
{1,2,3,4}-{5,6}
"""
tx_month = train['DayN... | e5ce051d292588d151d1487f70a8cd254479dfd2 | 592,313 |
def _copy(data):
"""Return a copy of each DataFrame in `data` if it is a tuple,
otherwise return a copy of `data`."""
if not isinstance(data, tuple):
return data.copy()
return tuple(df.copy() for df in data) | ef41673a81fa399d646efe4a50f11ec0e50b939b | 592,315 |
import operator
def get_columns(item, attr_map=None):
"""Return pair of resource attributes and corresponding display names.
Assume the following item and attr_map are passed.
item: {'id': 'myid', 'name': 'myname',
'foo': 'bar', 'tenant_id': 'mytenan'}
attr_map:
(('id', 'ID', LIST_BO... | c36ab327f6f0420d91081a9659e9d79e11521d75 | 592,316 |
def _wraps(wrapped):
"""Decorator to preserve some basic attributes
when wrapping a function or class"""
def decorator(wrapper):
for attr in ('__module__', '__name__', '__qualname__', '__doc__'):
setattr(wrapper, attr, getattr(wrapped, attr))
return wrapper
return decorator | 42ec86e340a5fb56f041b124ef6b0dc69c2f5a5a | 592,318 |
def get_sets(list_a, list_b):
"""
Returns a tuple of A^B, A | B, A - B, B - A
"""
set_a = set(list_a)
set_b = set(list_b)
return (
set_a.intersection(set_b),
set_a.union(set_b),
set_a.difference(set_b),
set_b.difference(set_a)
) | 93ab71e27a8783a15a382e38255a2aa720691221 | 592,319 |
import torch
from typing import Union
from typing import Tuple
def giou(bounding_box_1: torch.Tensor, bounding_box_2: torch.Tensor,
return_iou: bool = False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""
Function computes the general IoU for two given bounding boxes
:param boundi... | 34be2dc5cc4e57c5c7092dc2f5d5d6351a1f2de6 | 592,320 |
def copy_obj(proto_obj):
"""Make a copy of proto_obj so that later modifications of tmp_obj will have no impact on proto_obj.
Args:
proto_obj: a protobuf message
Return:
a copy of proto_obj
"""
tmp_obj = type(proto_obj)()
tmp_obj.CopyFrom(proto_obj)
return tmp_obj | 5640dfeff38685d7be9438f7d1282e3fe3b3fbbd | 592,321 |
import re
def format_url(url: str):
"""Add the default http scheme prefix to urls without one."""
if not re.match("^((?:http|ftp|https):)?//", url.lower()):
return "http://{0}".format(url)
return url | a0772f770116452d9760f625181dceeba1529418 | 592,322 |
def flow_in_tube_Dittus_boelter(Re, Pr, heating=True):
"""Nu of forced convection in tube, turblence, Dittus-Boelter formula"""
if heating is True:
n = 0.4
else:
n = 0.3
return 0.023*Re**0.8*Pr**n | cf364d02e8d553860713396d2e3e40f19c22d5f8 | 592,324 |
def find_select_idx_name(
central_idx: int, limit_idx: int, close_to_limit: bool
):
"""Returns a two-tuple which contains an int of value 0 or -1 in
the first position and a string of value 'min' or 'max' in the second.
The string is determined based on the relative values of
*central_idx* to *limi... | 6028fe642c42074f62691e693328c11c220a87ab | 592,325 |
def represent_seconds_in_milliseconds(seconds):
"""Converts seconds into human-readable milliseconds with 2 digits decimal precision"""
return round(seconds * 1000, 2) | 4706c47a40177625c161d73bf1cb79ac1b53ae6a | 592,326 |
def _difference_in_years(start, end):
"""
Calculate the number of years between two dates.
Parameters
----------
start : datetime.datetime
The start date.
end : datetime.datetime
The end date.
Returns
-------
float
The difference in years between start and e... | c6108c1df535eab936a12b0222a5336d0291fd98 | 592,332 |
def f(xx, uu, uuref, t, pp):
""" Right hand side of the vectorfield defining the system dynamics
:param xx: state
:param uu: input
:param uuref: reference input (not used)
:param t: time (not used)
:param pp: additionial free parameters (not used)
:return: ... | e5ca7c5952e5ce82cbc2b8899cce213351ee6f82 | 592,335 |
from typing import Sequence
from typing import List
def eliminate(ranks: Sequence[int]) -> List[int]:
"""
Pairwise eliminate contestants.
If there's odd number of ranks, the last one
is propagated as the first one in the result.
"""
n = len(ranks)
last = n if n % 2 == 0 else n - 1
r... | 3daa209ac5209ce82bcf01ab3e9f22ceb32bccbf | 592,336 |
def change_gates(gates, qubits):
"""
Modifies the gates outputted from decompose_state so that they
apply to the qubits in the list qubits
Specifically, a gate applied to (i, j) will now apply to
(qubits[i], qubits[j]
"""
return [(gate, qubits[i], qubits[j]) if j is not None else
... | 288b711c197ecd3a4dae3bf39b951465511bee26 | 592,337 |
def sum_of_middle_three(score1, score2, score3, score4, score5):
"""
Return sum of 3 middle scores
"""
min_score = min(score1, score2, score3, score4, score5)
max_score = max(score1, score2, score3, score4, score5)
sum_score = score1 + score2 + score3 + score4 + score5
return sum_score - min... | 545e9064df4e26367521504726369dba4504ee7c | 592,338 |
def is_class_dict(obj):
""" helper class that tests to see if the obj is a flattened object
>>> is_class_dict({'__class_module__':'__builtin__', '__class_name__':'int'})
True
>>> is_class_dict({'key':'value'})
False
>>> is_class_dict(25)
False
"""
if type(obj) is dict and \
... | 3e887695e292c3fc2975b5cc3d6fba369716648f | 592,339 |
def define_separator(filename):
""" Select separator for data values based on filename extension.
Returns separator.
"""
if filename.endswith(".tsv"):
separator = "\t"
else:
separator = ","
return separator | ac74cfdafe48d437b81ddd8a1a130f14586f250f | 592,340 |
def readtxt(ifile):
""" Simple function to read text file and remove clean ends of spaces and \n"""
with open(ifile, 'r') as f:
content = f.readlines()
# remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
return content | 8a6490a9e2a49bb0a9fc9c0ac44b03de6b7addbc | 592,344 |
import re
def squeeze_whitespace(text):
"""Squeeze multiple whitespace in text to single whitespace.
Args:
text: string, text to convert
Returns:
string, converted text.
"""
if text is None:
return
if not text:
return text
return re.sub(r'\s+', ' ', text) | 790e91661189a6e4a1b70fcec4a98d14d0f9b9e5 | 592,348 |
import math
def ObserverGravity(latitude, height):
"""Calculates the gravitational acceleration experienced by an observer on the Earth.
This function implements the WGS 84 Ellipsoidal Gravity Formula.
The result is a combination of inward gravitational acceleration
with outward centrifugal accelerat... | 664b082ad93afc26debef0ff502acae30942f38e | 592,350 |
import requests
import shutil
def _download_file(url, target_path, timeout=10):
"""Download a file and save it to a folder"""
with requests.get(url, stream=True, timeout=timeout) as response:
response.raise_for_status()
response.raw.decode_content = True
with open(target_path, 'wb') as... | 8a92bd9ca7c7d22944d71dfb41a16061e3c62670 | 592,352 |
def root_cause(binding, node, seen=()):
"""Tries to determine why a binding isn't possible at a node.
This tries to find the innermost source that's still impossible. It only works
if the failure isn't due to a combination of bindings.
Args:
binding: A binding, or a list of bindings.
node: The node at... | a17b4a928eaa696ac819c44ce234ead32f16b781 | 592,353 |
def reverse(seq):
"""
Recursively reverses a string
@param {string} sequence to reverse
@return {string}
"""
if seq == '':
return ''
last_index = len(seq) - 1
return seq[last_index] + reverse(seq[:last_index]) | 5395f8be64f48145e45612fb5b9635d6639dafed | 592,357 |
def count_tokens(tokens):
"""Count words into token lists
tokens: list of tokens (typically a sentence) to count
returns: dict of words with individual counts
"""
count = {}
for token in tokens:
if token in count:
count[token] += 1
else:
count[token] = 1... | 09e1a87ba8f3685e001c15448eae204fa78865f7 | 592,358 |
def air_indexEdlen53(l, t=15., p=760.):
"""Return the index of refraction of air at given temperature, pressure,
and wavelength in Angstroms.
The formula is from Edlen 1953, provided directly by ESO.
Parameters
----------
l : float
Vacuum wavelength in Angstroms
t : float
Tem... | 1d4a80cbf3a213e1cdb541b7624de3362666d4b4 | 592,360 |
def format_html_table(html):
""" Format a html table. """
html = html.replace("<table", "<table width=100%")
html = html.replace("<table", '<table style="text-align: right;"')
return html | 7b83d2d06b27911029bef964c87e7d2667166b35 | 592,362 |
def _score(cluster):
"""
score of the cluster, in this case, is the number of non-repetitive matches
"""
x, y = list(zip(*cluster))[:2]
return min(len(set(x)), len(set(y))) | c15be59764abcb73ae0aa6c1553f8827adb57a3d | 592,364 |
def _Backward3b_T_Ps(P, s):
"""Backward equation for region 3b, T=f(P,s)
Parameters
----------
P : float
Pressure [MPa]
s : float
Specific entropy [kJ/kgK]
Returns
-------
T : float
Temperature [K]
References
----------
IAPWS, Revised Supplementary ... | 6467fea6091b218d8b8f6c15d0488c1acc176845 | 592,365 |
from pathlib import Path
def csv_filename_renamer(csv_file):
"""
Converts the ING naming convention into naming convention
with date YYYYMMDD to YYYYMMDD first.
Expects a Path or filename (without folder)
"""
if isinstance(csv_file, Path):
csv_file = csv_file.name
account, fromdat... | 28886dd1d2a18f9631f3ce154a2744b9b433618b | 592,366 |
def inches_2_points(inches) -> float:
"""
Convert inches to points
"""
return inches * 72 | f1eb5d631d62ed87825038ced19a9a6c2a663435 | 592,369 |
def _is_replica_set_fixture(fixture):
"""Determine whether the passed in fixture is a ReplicaSetFixture."""
return hasattr(fixture, 'replset_name') | 7509d844ce302446feba9d57c937355a3ffb7ef5 | 592,370 |
def fliplr_joints(_joints, _joints_vis, width, matched_parts):
"""
flip coords
joints: numpy array, nJoints * dim, dim == 2 [x, y] or dim == 3 [x, y, z]
joints_vis: same as joints
width: image width
matched_parts: list of pairs
"""
joints = _joints.copy()
joints_vis = _joints_vis.co... | 05ec8003a90357b8fb0ad888d100f0b8ac50a0d7 | 592,372 |
def generate_pipeline_code(pipeline):
"""Generate recommended pipeline code.
Parameters
----------
pipeline: tuple
name and recommended pipeline configuration
Returns
-------
code: String
The Python code recommended pipeline
"""
code= """
# NOTE: Make sure ... | 47a8c8aca9dd9aa98b4285c819520cb3a7dd6fdd | 592,380 |
def _mean(listvalue):
"""
The mean value of the list data.
"""
return sum(listvalue) / len(listvalue) | 4630bbef493b88843f7e18b1644df025767d4dcc | 592,381 |
import operator
def binom(n, k):
"""
Binomial coefficient (n over k)
"""
n = operator.index(n)
k = operator.index(k)
if not 0 <= k <= n:
return 0
m = n + 1
num = 1
den = 1
for j in range(1, min(k, n - k) + 1):
num *= m - j
den *= j
return num // den | 91b711b24a9c582e41cf33e4b64595e7d097c02e | 592,384 |
def is_int(value) -> bool:
"""
Tests a value to check if it is an integer or not.
"value" can be of any type, as long as it can be converted to int.
Note: `is_int(None)` will raise TypeError.
"""
try:
int(value)
except ValueError:
return False
else:
return True | 12ddd58e07eb0ff638718a48febcca74a67d4d3d | 592,388 |
def is_atom_in_ring(molecule, atom):
"""
Given an atom and the molecule it belongs to
return a list of counts, each count shows
the occurances of the atom is involved in
3, 4, 5, 6, 7, 8-member rings
For instance, atom is in one 3-member ring and two
5-member rings, the returned list would ... | 43be06d2486738588abad89ba87001ad4ac056ea | 592,389 |
def part_d(f, x, h):
"""Second-order forward difference"""
return (-3*f(x) + 4*f(x+h) - f(x+2*h)) / (2*h) | 05d6166b3f6366ddc859fb8d83eb3b624201b07f | 592,394 |
from typing import Counter
def atom_to_vocab(mol, atom):
"""
Convert atom to vocabulary. The convention is based on atom type and bond type.
:param mol: the molecular.
:param atom: the target atom.
:return: the generated atom vocabulary with its contexts.
"""
nei = Counter()
for a in a... | 51959232f025cea886f507558c4e987dc86768d7 | 592,397 |
def _get_multiply_function(multiplier):
"""Returns function that multiplies by scalar.
:param multiplier: Function will multiply all inputs by this scalar.
:return: multiply_function: Function handle (see below).
"""
def multiply_function(input_array):
"""Multiplies input by scalar.
... | 4b50db54ae64ded7383916269b3f10d28c7d5fd6 | 592,403 |
def describe(img):
"""Return dict containing commonly referenced image metadata"""
return dict(
type=str(img.dtype),
shape=img.shape,
min=img.min(),
max=img.max(),
mean=img.mean(),
bytes=img.nbytes
) | 3e5d706dcfb293f5f96b1cb35ecb414ba4c3ef68 | 592,405 |
import time
def _init_step_result(step_object):
"""
Initializer for step_result structure.
"""
return {
'status': 'unknown',
'date': step_object.step_date,
'start_time': time.time(),
'end_time': None,
'type': step_object.step_type,
'error_info': {},
... | 94a95fed8e27a659e9dfcc88ff3a774274830faa | 592,406 |
def add_extension_if_needed(filepath, ext):
"""Add the extension ext to fpath if it doesn't have it.
Parameters
----------
filepath: str
File name or path
ext: str
File extension
Returns
-------
filepath: str
File name or path with extension added, if needed.
... | 24c673e9b96d663dc21d0de91cd54cbbc4b5fda4 | 592,411 |
import struct
def GetUnsignedByte(buf, offset):
"""Get an unsigned byte from a buffer at a supplied offset.
This returns the same value whether the input is a string or a bytes
object, coercing the return value of socket.recv to the same type whether
on python 2 or 3.
Args:
buf: A string or bytes obje... | 4ed491288e4d391b3d0b56801b01e9707098df6e | 592,417 |
def num_zero(n):
"""
Number of modes with nonzero horizontal wavenumber in the
system with n total modes of the HK hierarchy.
"""
shells = [4,10,18,28,40,54,70,88,108,130,154,180,208,238]
return min([i+1 for i in range(len(shells)) if shells[i] >= n]) | 875c2546eeb9dc0803db0711e71f3d28efe4d4b7 | 592,419 |
from typing import Iterable
from typing import List
from typing import Any
def get_max_size_of_arguments(*item_lists: Iterable[List[Any]]) -> int:
"""
Find the argument with most elements
e.g. [db, [arg1, arg2] -> 2
:param item_lists: arguments where some of the arguments is a list
:return: size o... | d11147569400d4c4c0dbd0626a8754bd3e376276 | 592,422 |
from pathlib import Path
def init_dir(home_dir) -> Path:
"""create a dir to save the downloaded files."""
home_dir.mkdir(parents=True, exist_ok=True)
return home_dir | e100c8988392c41f3d6e7aa29dfbeb7ecbb1512e | 592,423 |
def is_path_removed(patch, path):
"""Returns whether the patch includes removal of the path (or subpath of).
:param patch: HTTP PATCH request body.
:param path: the path to check.
:returns: True if path or subpath being removed, False otherwise.
"""
path = path.rstrip('/')
for p in patch:
... | f56796a82ae0a2b4091d5bc78ac0c2d5bd924ea2 | 592,427 |
def _ReadPassword(pwfilename):
"""Reads the coverity password in from a file where it was stashed"""
pwfile = open(pwfilename, 'r')
password = pwfile.readline()
pwfile.close()
return password.rstrip() | 014bed67bbe713135f2fa66158fcda1a4ec7b179 | 592,429 |
def differentiate_same_col_names(input_df):
"""
There might be multiple columns of the same name. This results in Combat function to raise an error. This function
makes sure that each column has a unique name.
Args:
input_df: pd DataFrame with repetitive column names
Returns:
pd Dat... | 5725930c96e5e587f4e382cb48dc87a419cacd35 | 592,434 |
def _predict_dcph(model, features, times):
"""Predict survival at specified time(s) using the Deep Cox PH model.
Parameters
-----------
model :
Trained instance of the Deep Cox PH model.
features : pd.DataFrame
A pandas dataframe with rows corresponding to individual samples and
columns as ... | 2a7c0719eba461ecf9ce3c7c6f8091f133493738 | 592,435 |
from typing import Dict
from typing import Any
def _update(value: Dict[str, Any], update: Dict[str, Any]):
"""Update entries in nested dictionaries (recursive)
Arguments:
value: Multi-level (nested) dictionary
update: Dictionary containing updates
"""
for key, val in update.items():
... | 8cd6730de56270b5fac3d357065650b3113679e2 | 592,436 |
from typing import List
def join_items_with_and(items: List[str]) -> str:
"""Join the list with commas and "and"."""
if len(items) <= 2:
return " and ".join(items)
return "{} and {}".format(", ".join(items[:-1]), items[-1]) | 4f495f07bc7e421c5be0e9c58785cc53984403a3 | 592,443 |
import mimetypes
def _GetContentType(filename):
"""Get the MIME type for content based on the given filename.
Args:
filename: A string representing the filename for the content.
Returns:
A string representing the best guess for the MIME type of the file
is returned.
"""
file_type = mimetypes.g... | 1f7789cab217981d6a56fb664c8daa5e1630e89b | 592,450 |
def parse_ids(ids_string):
"""
Parse a list of icon object IDs.
:param ids_string: extract command output string list of icon object IDs (e.g. `"1-3, 23, 99-123"`)
:return: list of icon object IDs as ints (e.g. `[1, 2, 3, 23, 99, 100, ...]`)
"""
ids = []
for id_string in ids_string.split(', ... | c412d76f531663fd07bb61be42a3265a64d5fb07 | 592,452 |
import requests
def get_images_ids(num_images, offset):
"""
:param num_images: The number of requested images to download from the archive
If None, will download the ids all the images in the archive
:param offset: The offset from which to start downloading the ids of the images
"""
# Specify... | f071d2cb88ec708057cce4a5b92e6437dccc25f4 | 592,453 |
def _listToPhrase(things, finalDelimiter, delimiter=', '):
"""
Produce a string containing each thing in C{things},
separated by a C{delimiter}, with the last couple being separated
by C{finalDelimiter}
@param things: The elements of the resulting phrase
@type things: L{list} or L{tuple}
@... | abf424c1a4939ccb6776c4824e61bf39cbe2cc9a | 592,454 |
def make_query_url(word):
"""Quickly turn a word into the appropriate Google Books url
Args:
word (str): Any word
Returns:
str: Google Books url for the word's popularity from 1970 to 2019
"""
return f"https://books.google.com/ngrams/json?content={word}&year_start=1970&year_end=201... | ff722a64fe2b932cf6f233dbf5cac8183ff2aed7 | 592,455 |
def read_file_as_binary( fPath ):
""" Open the file in binary mode and return its contents """
# URL , Pickle and Image: https://mail.python.org/pipermail/python-list/2005-April/313870.html
f = open( fPath , 'rb' )
f.seek(0)
rtnData = f.read()
f.close()
return rtnData | 37c8b0f6b8cf9ccc58c1bfdea7fb135cdc3da8df | 592,457 |
def cond_pu(cond, kv, length):
"""
Get per unit data for conductor
Args:
cond: conductor dictionary
kv: line voltage
lenght: length of line in miles
Returns: conductor dictionary
"""
kv = float(kv)
amps_to_mva = 3.0**0.5 * kv / 1000.0
Zbase = kv**2/100.0
Ybase... | d39846e5a971ac9f838adeaa7e9707d03e8eb46c | 592,461 |
import math
def lucas(n):
"""returns the nth Lucas number,
where the Lucas sequence is ```L0 = 2, L1 = 1, L2 = 3, L3 = 4, ...```
(sum of previous two terms)"""
phi = (1 + math.sqrt(5))/2
return phi**n + (1-phi)**n | 8df8c87e2ee44ab740977e27afd28f9e6ef9943e | 592,467 |
def is_strictly_increasing(L):
""" Returns True if the list contains strictly increasing values.
Examples:
is_strictly_increasing([0,1,2,3,4,5]) > True
is_strictly_increasing([0,1,2,2,4,5]) > False
is_strictly_increasing([0,1,2,1,4,5]) > False
"""
for x, y ... | 8af27b7af9f7942d622f2c73054e9e12a1f734ec | 592,471 |
import pickle
def loadData(file_path):
"""
Load a log file. (Use the built-in pickle module)
Parameters
----------
file_path: str
path of the log file
Returns
-------
- data: arbitrary object
arbitrary Python object which contains data
"""
with open(file_pa... | 6411e3d32f21c46e6d072006d9b3a1d08baf99b0 | 592,476 |
import itertools
import random
def pick_random_elements(iterable, k):
"""
Pick `k` random elements from `iterable`. Returns a list of length `k`.
If there weren't enough elements, `None` is stored at that index instead.
"""
# Algorithm R: https://en.wikipedia.org/wiki/Reservoir_sampling#Algorithm_R
# Changed to... | eeede011ccd857c00dd56c78d10927e7ae5a3132 | 592,479 |
def bytes_to_string(bytes):
"""
It generates a string with a proper format to represent bytes.
Parameters
----------
bytes : int
A quantity of bytes
Returns
-------
size_str : str
The string representing the number of bytes with a proper format
"""
kilobytes = b... | 3e3a2946e02d0c7f5ed347da265ee329bab0f577 | 592,481 |
def tuple_to_string(date_tuple):
"""
Create a yyyy-mm(-dd) string from a tuple containing (yyyy, m) (or one with the day too)
"""
if len(date_tuple) == 2:
# It's yyyy-mm
return str(date_tuple[0]).zfill(4) + '-' + str(date_tuple[1]).zfill(2)
# It's yyyy-mm-dd
return str(date_tuple... | 28d33949307ecd8fe7b5e70fa0d1103bf81acbfd | 592,483 |
from typing import Dict
from typing import Any
import json
def serializable_compact(record: Dict[str, Any]) -> str:
"""Loguru formatter to return a compact JSON string for JSONLines output.
`record` documentation: https://loguru.readthedocs.io/en/stable/api/logger.html#record
Based on the `_serialize_re... | 1e88cc4215f4ff7c1a8257caa335d5423655d6e0 | 592,484 |
import uuid
def create_uuid(prefix='uid'):
"""Create uuid4 specific UUID which uses pseudo random generators."""
return prefix+'-'+str(uuid.uuid4()) | 2b0196201fd33e829fddd65bdae25ada631242b8 | 592,492 |
def extract_boundaries_from_ffprobe_output(output):
"""
extracts the shot boundaries from the string output
producted by ffprobe
Args:
output (string): the full output of the ffprobe
shot detector as a single string
Returns:
List[(float, float)]: a list of tuples of flo... | 586d15c75e0243c2122e13067b3e17276eb2e9e5 | 592,495 |
import torch
def to_one_hot(indexes, output_dim):
"""
:param indexes: list of numbers in the range [0, output_dim)
:param output_dim: size of a single one-hot tensor
:return: tensor containing one_hot representation of indexes
"""
assert output_dim >= 2
assert output_dim > max(indexes)
... | bebf3a084459a95d7b7bf693691a6b0daf9c466d | 592,499 |
import random
import string
def fuzzy_generator(length):
"""
Returns a random printable string with the given length.
"""
return "".join([random.choice(string.printable) for i in range(length)]) | 7f82f1f17e7803e1abc266aa484c23008301be53 | 592,500 |
def Min(data):
"""Returns the minimum value of a time series"""
return data.min() | b156c30e56618895a07b3d0fe8d221208c6868f9 | 592,506 |
def lin_objective(x, m, b):
"""Linear objective function"""
return m*x + b | b3f57a1264161af07082a95836de925e39595b0d | 592,511 |
import six
def encode_string(text):
"""Encode text into an array of bytes in both Python 2 and 3 with UTF-8.
Parameters
----------
text : str or bytes
The text to be encoded
Returns
-------
encoded_text : bytes
The encoded text.
"""
if six.PY3:
return byte... | e9bc16c67d9343d2bd25de3afcec7167b11458de | 592,512 |
import re
def _image_name_from_url(url):
""" Create a nice image name from the url. """
find = r'https?://|[^\w]'
replace = '_'
return re.sub(find, replace, url).strip('_') | 47d064c2387d52e76554416db23861e4c00f4c1b | 592,513 |
import io
def get_line(filename, line_number):
"""Return the text of the line at the 1-based line number."""
with io.open(filename, mode='r', encoding="utf-8") as f:
return f.readlines()[line_number - 1] | 3854e85318c51068716569afc8230aa0859487b0 | 592,514 |
def aggregate(iterator, only_no_facts = False):
""" Aggregates the records of this iterator.
Returns a 3-tuple (dict, int, float) with predicate->time, count and total.
"""
predicates = dict()
count = 0
total = float(0)
for (pred, time, facts) in iterator:
if facts == 0 or not o... | a56e053607a30c96994aef57c7e7e66d132fc0f0 | 592,515 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.