content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def extract_pos(positions, cash):
"""Extract position values from backtest object as returned by
get_backtest() on the Quantopian research platform.
Parameters
----------
positions : pd.DataFrame
timeseries containing one row per symbol (and potentially
duplicate datetime indices) and columns for amount and
last_sale_price.
cash : pd.Series
timeseries containing cash in the portfolio.
Returns
-------
pd.DataFrame
Daily net position values.
- See full explanation in tears.create_full_tear_sheet.
"""
positions = positions.copy()
positions['values'] = positions.amount * positions.last_sale_price
cash.name = 'cash'
values = positions.reset_index().pivot_table(index='index',
columns='sid',
values='values')
values = values.join(cash).fillna(0)
return values
|
248ecd5054df0eed7126137f2b9145c11eeff2c4
| 74,366 |
def left_of_line(point, p1, p2):
""" True if the point self is left of the line p1 -> p2
"""
# check if a and b are on the same vertical line
if p1[0] == p2[0]:
# compute # on which site of the line self should be
should_be_left = p1[1] < p2[1]
if should_be_left:
return point[0] < p1[0]
else:
return point[0] > p1[0]
else:
# get pitch of line
pitch = (p2[1] - p1[1]) / (p2[0] - p1[0])
# get y-value at c's x-position
y = pitch * (point[0] - p1[0]) + p1[1]
# compute if point should be above or below the line
should_be_above = p1[0] < p2[0]
if should_be_above :
return point[1] > y
else:
return point[1] < y
|
5cb130fecd46fe7eb74cee5179f4705b8ee4760f
| 690,180 |
def resolve(impmod, nameparts):
"""
Resolve the given (potentially nested) object
from within a module.
"""
if not nameparts:
return None
m = impmod
for nname in nameparts:
m = getattr(m, nname, None)
if m == None:
break
return m
|
4a6a0af926b7dbf226075e986a6d3fd65225fa4f
| 518,275 |
from unittest.mock import Mock
def make_coroutine_returning(return_value):
"""
A utility function used to create coroutines that return a specific value.
:param return_value: The value that the coroutine should return when awaited.
:return: A mock coroutine
"""
async def mock_coroutine(*args, **kwargs):
return return_value
return Mock(wraps=mock_coroutine)
|
818331f569466c34c21b2760a12d1bd804d945bd
| 443,344 |
def getattrrec(object, name, *default):
"""Extract the underlying data from an onion of wrapper objects.
``r = object.name``, and then get ``r.name`` recursively, as long as
it exists. Return the final result.
The ``default`` parameter acts as in ``getattr``.
See also ``setattrrec``.
"""
o = getattr(object, name, *default)
while hasattr(o, name):
o = getattr(o, name, *default)
return o
|
a847b7f54d2a737ac31226807c2f28ca58d1ef72
| 70,536 |
def redirect(target):
"""
Returns a redirect map to the target provided
"""
return {
'status': '302',
'statusDescription': 'Found',
'headers': {
'location': [{
'key': 'Location',
'value': target
}]
}
}
|
787c485c63a05f761b7b89198c311f6f522e5d3b
| 313,976 |
def maxed_rect(max_width,max_height,aspect_ratio):
"""
Calculates maximized width and height for a rectangular area not exceding a maximum width and height.
:param max_width: Maximum width for the rectangle
:type max_width: float
:param max_height: Maximum height for the rectangle
:type max_height: float
:param aspect_ratio: Aspect ratio for the maxed rectangle
:type aspect_ratio: float
:returns: A tuple with width and height of the maxed rectangle
:rtype: Tuple
Examples:
>>> maxed_rect(800,600,aspect_ratio=4/3.)
(800.0, 600.0)
>>> maxed_rect(800,1600,aspect_ratio=800/600.)
(800.0, 600.0)
>>> maxed_rect(1600,600,aspect_ratio=800/600.)
(450.0, 600.0)
"""
mw=float(max_width)
mh=float(max_height)
ar=float(aspect_ratio)
# Do by width
w=mw
h=(mw/(aspect_ratio))
if h > mh:
# Do by height
h=mh
w=(mh/(aspect_ratio))
return(w,h)
|
886cda77c833c3614b05cb41c9eeb209ea90c149
| 84,247 |
def extract_subgraph(adj_matrix, groundtruth, nodes):
"""
Return the subgraph and the ground-truth communities induced by a list of nodes.
The ids of the nodes of the subgraph are mapped to 0,...,N' - 1 where N' is the length of the list of nodes.
:param adj_matrix: compressed sparse row matrix or numpy 2D array
Adjacency matrix of the graph.
:param groundtruth: list of list/set of int
List of ground-truth communities
:param nodes: numpy 1D array
List of nodes from which we want to extract a subgraph.
:return:
new_adj_matrix: compressed sparse row matrix
Adjacency matrix of the subgraph.
new_groundtruth: list of list of int
List of ground-truth communities using the node ids of the subgraph.
node_map: dictionary
Map from node ids of the original graph to the ids of the subgraph.
"""
#adj_matrix = convert_adj_matrix(adj_matrix)
node_map = {nodes[i]: i for i in range(nodes.shape[0])}
new_groundtruth = [[node_map[i] for i in community if i in node_map] for community in groundtruth]
new_adj_matrix = adj_matrix[nodes, :][:, nodes]
return new_adj_matrix, new_groundtruth, node_map
|
4272b7acb2c632d3200f6b105cbb7a582a8bf10d
| 409,581 |
import hashlib
def _hashdigest(message, salt):
""" Compute the hexadecimal digest of a message using the SHA256 algorithm."""
processor = hashlib.sha256()
processor.update(salt.encode("utf8"))
processor.update(message.encode("utf8"))
return processor.hexdigest()
|
2c9c5886d72700826da11a62f4cc9c82c2078090
| 27,757 |
def validate(raw):
""" Checks the content of the data provided by the user.
Users provide tickers to the application by writing them into a file
that is loaded through the console interface with the <load filename>
command.
We expect the file to be filled with coma separated tickers :class:`string`.
Parameters:
- `raw` : :class:`string` content of the user provided file.
The function strips the raw data from spaces, carrier returns and split the
content around comas. It will also check if there are trailing comas or if
the user mistakenly put two comas instead of one between tickers.
Returns a :class:`list` of sanitized tickers
"""
tickers = []
raw = raw.replace(' ', '') # remove spaces
raw = raw.replace('\n', '') # removes cr
for item in raw.split(','): # comma split
if item is not '':
tickers.append(str(item).upper())
return tickers
|
c69b5b4177e11fabc3f70c0388e3b50f56a201b7
| 18,620 |
def _tasklines_from_tasks(tasks):
"""
Parse a set of tasks (e.g. taskdict.tasks.values()) into tasklines
suitable to be written to a file.
"""
tasklines = []
for task in tasks:
metapairs = [metapair for metapair in task.items()
if metapair[0] != 'text']
meta_str = "; ".join("{}:{}".format(*metapair)
for metapair in metapairs)
tasklines.append('{} | {}\n'.format(task['text'], meta_str))
return tasklines
|
a4d4677f9005e3e4f82bd67eee9a4faba168f79c
| 561,711 |
def frame_rti(detectorrows, ampcolumns, colstart, colstop, rowstart, rowstop,
sampleskip, refpixsampleskip, samplesum, resetwidth,
resetoverhead, burst_mode):
"""
Helper function which calculates the number of clock cycles, or RTI,
needed to read out the detector with a given a list of FPGA parameters.
This function can be used to test the frame time calculation over a
wide range of scenarios.
:Reference:
JPL MIRI DFM 478 04.02, MIRI FPS Exposure Time Calculations,
M. E. Ressler, October 2014
:Parameters:
detectorrows:
Total number of detector rows.
ampcolumns
Total number of amplifier columns (including reference columns).
= Total number of detector columns / Number of amplifiers.
colstart: int
Amplifier column at which readout starts.
Derived from the subarray mode.
colstop: int
Amplifier column at which readout stops.
Derived from the subarray mode.
rowstart: int
Detector row at which readout starts.
Derived from the subarray mode.
rowstop: int
Detector row at which readout stops.
Derived from the subarray mode.
sampleskip: int
Number of clock cycles to dwell on a pixel before reading it.
Derived from the readout mode.
refpixsampleskip: int
Number of clock cycles to dwell on a reference pixel before reading it.
Derived from the readout mode.
samplesum: int
Number of clock cycles to sample a pixel during readout.
resetwidth: int
Width of the reset pulse in clock cycles.
Derived from the readout mode.
resetoverhead: int
The overhead, in clock cycles, associated with setting shift
registers back to zero.
burst_mode: boolean, optional, default is False
True if a subarray is being read out in burst mode,
which skips quickly over unwanted columns.
:Returns:
frame_rti: float
Number of clock cycles (RTI) for readout.
"""
# The time taken to skip a row not contained in a subarray is the
# row reset overhead, which is the reset pulse width plus the overhead
# to reset the shift registers.
row_reset = resetwidth + resetoverhead
rti_row_non_roi = row_reset
# The number of clock cycles needed to read a pixel is the
pix_clocks = sampleskip + samplesum
refpix_clocks = refpixsampleskip + samplesum
if (colstart == 1) or (not burst_mode):
# For a row within a subarray (if burst_mode is False or the subarray
# begins at column 1), we start with the row reset overheads, then add
# the reference pixel time, refpix_clocks, then add the science pixel
# time, n * pix_clocks.
rti_row_roi = row_reset
# strg = "rti_row_roi=%d " % row_reset
if colstart == 1:
rti_row_roi += refpix_clocks
# strg += " + %d " % refpix_clocks
else:
rti_row_roi += resetwidth
if colstop == ampcolumns:
rti_row_roi += (colstop-2) * pix_clocks
# strg += " + (%d * %d) " % ((colstop-2), pix_clocks)
rti_row_roi += refpix_clocks
# strg += " + %d " % refpix_clocks
else:
rti_row_roi += (colstop-1) * pix_clocks
# strg += " + (%d * %d) " % ((colstop-1), pix_clocks)
# print(strg)
else:
# In burst_mode, when a subarray does not touch the left hand edge,
# each row begins with the same reset overhead, then the left hand
# pixels are clocked at 5 times the normal rate until the subarray
# is reached. If the number of burst columns is not an even multiple
# of 5, the readout is paused until a normal clock boundary.
rti_row_roi = row_reset
# strg = "rti_row_roi=%d " % row_reset
if colstart == 1:
rti_row_roi += refpix_clocks
# strg += " + %d " % refpix_clocks
else:
rti_row_roi += refpix_clocks + ((colstart-2)*pix_clocks+4)//5
# strg += " + %d + %d " % (refpix_clocks,
# ((colstart-2)*pix_clocks+4)//5)
if colstop == ampcolumns:
rti_row_roi += ((colstop-2)-colstart+1) * pix_clocks
# strg += " + (%d * %d) " % (((colstop-2)-colstart+1), pix_clocks)
rti_row_roi += refpix_clocks
# strg += " + %d " % refpix_clocks
else:
rti_row_roi += (colstop-colstart+1) * pix_clocks
# strg += " + (%d * %d) " % ((colstop-colstart+1), pix_clocks)
# print(strg)
# The total number of clock cycles to read the frame is the sum
# of the portion before the ROI, after the ROI and during the ROI.
# print("rti_row_non_roi=", rti_row_non_roi, "rti_row_roi=", rti_row_roi)
frame_rti = (rowstart-1) * rti_row_non_roi + \
(rowstop-rowstart+1) * rti_row_roi + \
(detectorrows-rowstop) * rti_row_non_roi
return frame_rti
|
07388d58bc1a8ddc2bc7df79266df264e36d3bd2
| 93,700 |
def normalize_on_minute(dtstamp, minute):
"""
Change a datetime stamp to be rounded down to the nearest interval of `minute`.
This also truncates off the seconds and microseconds parameters by setting them to 0.
>>> normalize_on_minute(datetime(2012, 3, 19, 15, 9, 12, 41), 15)
datetime.datetime(2012, 3, 19, 15, 0)
>>> normalize_on_minute(datetime(2013,3, 19, 15, 24, 20, 19), 20)
datetime.datetime(2013, 3, 19, 15, 20)
"""
tsmin = dtstamp.minute
rounded_tsmin = tsmin - (tsmin % minute)
return dtstamp.replace(microsecond=0, second=0, minute=rounded_tsmin)
|
c11c611edf6e01bae941ef368b2b647532b9c7a8
| 258,246 |
from typing import List
from typing import Tuple
def run(code: List[Tuple[str, int]]) -> Tuple[str, int]:
"""
Runs a program, returning status and accumulator.
The status can be either "loop" or "halt".
"""
pc = 0
acc = 0
instructions_run = set()
while True:
if pc == len(code):
return "halt", acc
if pc in instructions_run:
return "loop", acc
instructions_run.add(pc)
op, n = code[pc]
if op == "acc":
acc += n
pc += 1
elif op == "nop":
pc += 1
elif op == "jmp":
pc += n
else:
raise Exception("bad op code: " + op)
|
7984bf1d9a57e129770b1d7701212ffcaa4278b4
| 457,302 |
import re
def _api_version(release: str, significant: int = 3) -> str:
"""Return API version removing any additional identifiers from the release version.
This is a simple lexicographical parsing, no semantics are applied, e.g. semver checking.
"""
items = re.split(r"\.|-|\+", release)
parts = items[0:significant]
return ".".join(parts)
|
07fe3bfdc1693ea8d6028a79149acc4fb0dd2b9e
| 136,340 |
import re
def extract_id(url):
"""Extract the tournament id of the tournament from its name or URL."""
match = re.search(r'(\w+)?\.?challonge.com/([^/]+)', url)
if match is None or match.group(2) is None:
raise ValueError(f'Invalid Challonge URL: {url}')
subdomain, tourney = match.groups()
if subdomain is None:
return tourney
return f'{subdomain}-{tourney}'
|
c16f28fc114b5439800713e02a06243cbd3b67d8
| 93,340 |
def _incs_list_to_string(incs):
"""Convert incs list to string.
Example:
['thirdparty', 'include'] -> "-I thirdparty -I include"
"""
return ' '.join(['-I ' + path for path in incs])
|
6b6dbfd687fdf87e2203381a512f65460438e1ae
| 202,575 |
def turn(fen):
"""
Return side to move of the given fen.
"""
side = fen.split()[1].strip()
if side == 'w':
return True
return False
|
1adbe7b325ee957348ad1ba591335f38c5835573
| 428,369 |
def get_composer_names(artist_database, composer_id):
"""
Return the list of names corresponding to an composer
"""
if str(composer_id) not in artist_database:
return []
alt_names = [artist_database[str(composer_id)]["name"]]
if artist_database[str(composer_id)]["alt_names"]:
for alt_name in artist_database[str(composer_id)]["alt_names"]:
alt_names.append(alt_name)
return alt_names
|
5ad465de92cbd0e08c668e887b3fe65fdd9edb7a
| 269,609 |
def centres_from_shape_pixel_scales_and_origin(shape, pixel_scales, origin):
"""Determine the (y,x) arc-second central coordinates of an array from its shape, pixel-scales and origin.
The coordinate system is defined such that the positive y axis is up and positive x axis is right.
Parameters
----------
shape : (int, int)
The (y,x) shape of the 2D array the arc-second centre is computed for.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the 2D array.
origin : (float, flloat)
The (y,x) origin of the 2D array, which the centre is shifted to.
Returns
--------
tuple (float, float)
The (y,x) arc-second central coordinates of the input array.
Examples
--------
centres_arcsec = centres_from_shape_pixel_scales_and_origin(shape=(5,5), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))
"""
y_centre_arcsec = float(shape[0] - 1) / 2 + (origin[0] / pixel_scales[0])
x_centre_arcsec = float(shape[1] - 1) / 2 - (origin[1] / pixel_scales[1])
return y_centre_arcsec, x_centre_arcsec
|
66c08c63fa3cf5c0907590660075bb49719589e8
| 227,481 |
def hlstr(string, color="white"):
"""
Return HTML highlighting text with given color.
Args:
string (string): The string to render
color (string): HTML color for background of the string
"""
return f"<mark style=background-color:{color}>{string} </mark>"
|
52e9d069d559feec2237d0847e667a1cb53326d8
| 27,343 |
from bs4 import BeautifulSoup
def get_job_title_indeed(card: BeautifulSoup) -> str:
"""
Extracts the jobs title from the portion of HTML containing an individual job card.
Args:
card (BeautifulSoup object): The individual job posting card being processed.
Returns:
str: The job title extracted, otherwise an empty string.
"""
title_text = card.find("h2", {"class": "title"})
if title_text:
return title_text.text.lower().strip()
return ""
|
882f91df7bb193823ca6c12a76f65eff91d865e9
| 619,812 |
def join(sep, s):
"""Return 's' joined with 'sep'. Coerces to str."""
return sep.join(str(x) for x in list(s))
|
e4e11b06629db19ed955ea0e7d5b956b6ea961b5
| 214,068 |
import string
import random
def get_random_str(size=13):
"""
generates the random string of given size
Args:
size (int): number of random characters to generate
Returns:
str : string of random characters of given size
"""
chars = string.ascii_lowercase + string.digits
return ''.join(random.choice(chars) for _ in range(size))
|
04688d425787f96de2d4a559191266db39b1c1c1
| 312,126 |
import fnmatch
def is_ignored(path, ignore_patterns):
"""
Helper function to check if the given path should be ignored or not.
"""
for pattern in ignore_patterns:
if fnmatch.fnmatchcase(path, pattern):
return True
return False
|
fbe6c7cf9daac52e7d57553ad10ed74a6e2fffba
| 444,412 |
def stats(index_and_true_and_retrieved):
""" Returns comma-separated list of accuracy stats
Included are (relevant instances, retrieved instances, overlap,
precision, recall, f-score)
index_and_true_and_retrieved is composed of:
index: used to track which sample is associated with the stats
true: set of true instances
retrieved: set of retrieved indexes
Return value: (index, tuple of stats)
"""
index, true, recovered = index_and_true_and_retrieved
relevant = len(true)
retrieved = len(recovered)
overlap = len(true.intersection(recovered))
try:
precision = float(overlap) / retrieved
except ZeroDivisionError:
precision = 1
try:
recall = float(overlap) / relevant
except ZeroDivisionError:
recall = 1
try:
fscore = 2 * precision * recall / (precision + recall)
except ZeroDivisionError:
fscore = 1
return (index, (relevant, retrieved, overlap, precision, recall, fscore))
|
e3edcc8e1a75f91eee869ceb275611365c22c23a
| 349,684 |
def bytes_from_str(s: str):
"""
Convert string to bytes
"""
return s.encode()
|
b888bdd8276d36197a1c27892b74e897d17dc6d0
| 470,420 |
def convert_to_base_unit(value, unit):
"""
Convert value from current unit to base unit
:param (int) value: Numerical value
:param (str) unit: unit, where empty string denotes base unit
:return: (int) the value in base unit
"""
POWERS_BY_UNIT = {'n': -3,
'u': -2,
'm': -1,
'': 0,
'K': 1, 'Ki': 1,
'M': 2, 'Mi': 2,
'G': 3, 'Gi': 3,
'T': 4, 'Ti': 4,
'P': 5, 'Pi': 5,
'E': 6, 'Ei': 6}
if unit in ['n','u','m','','K','M','G','T','P','E']: # normal si system prefixes
base = 1000
else: # iec system
base = 1024
return value * (base ** POWERS_BY_UNIT[unit])
|
bd76d50b8dceab5e28c1c582a061dd5a01bce3a0
| 236,483 |
import torch
def c2d(x):
"""
Transform Cartesian coordinates to polar degree (r=1).
Parameters
----------
x, y : floats or arrays
Cartesian coordinates
Returns
-------
theta : floats or arrays
Polar degree
"""
x0, x1 = x.select(-1,0), x.select(-1,1)
return torch.atan2(x1,x0)
|
9596858aa0720faf7798ac1f6b1745a8b4123d78
| 496,671 |
import re
def modify_vars(vars_orig, var_modifiers):
"""Return a copy of `vars_orig` modified according to `var_modifiers`.
Parameters
----------
vars_orig : list of str
A list of variable names.
var_modifiers : list of str or None, optional
A list of variable modifiers. Each variable modifier is a string
either "+var_name" or "-var_name".
If `var_modifiers` has "+var_name", then "var_name" will be added
to the result.
If `var_modifiers` has "-var_name", then "var_name" will be removed
from the result.
If `var_modifiers` is None, then a simple copy of `vars_orig` will be
returned.
Default: None.
Returns
-------
list of str
A copy of `vars_orig` modified according to `var_modifiers`.
"""
if var_modifiers is None:
return vars_orig
result = vars_orig[:]
regexp = re.compile(r'([+-])(.*)')
for vm in var_modifiers:
res = regexp.match(vm)
if not res:
raise ValueError('Failed to parse column modifier %s' % vm)
mod = res.group(1)
val = res.group(2)
if mod == '+':
if val not in result:
result.append(val)
else:
result.remove(val)
return result
|
58f27e60b650a219abad70501e4573ab818b8450
| 625,903 |
def land(*fns):
"""
Functionally logical ands the given functions.
>>> lor(starts_with('123'), ends_with('asd'))('123asd')
True
>>> land(starts_with('123'), ends_with('asd'))('asd')
False
>>> land(starts_with('123'), ends_with('asd'))('123')
False
:param fns: Functions to and
:return: True if all of the functions return a truthy value, otherwise the first falsey value
"""
def _f(*args, **kwargs):
for f in fns:
v = f(*args, **kwargs)
if not v:
return v
return True
return _f
|
8b48e5862704548515593d8183aa88b82392da51
| 637,624 |
import re
def camel_case_split(str):
"""
e.g. str = "mayaMatchmoveTools" >> ['maya', 'Matchmove', 'Tools']
e.g. str = "MayaMatchmoveTools" >> ['Maya', 'Matchmove', 'Tools']
"""
return re.findall(r'[a-zA-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))', str)
|
cfa85307755e586f4b03aa9dd90b830ceb85b10e
| 506,225 |
import re
def check_convert_input(user_inputs: list):
"""
Check input for erroneous formatting.
If input is clean, convert it to more useful format.
Args:
guesses (dict): {
'word1':'XXXXX',
'word2':'XXXXX',
etc.
}
Returns:
guesses (dict): {
'word1':[X,X,X,X,X],
'word2':[X,X,X,X,X],
etc.
}
bad_input (bool): True if input is incorrect format.
"""
guesses = {}
bad_input = False
for user_input in user_inputs:
if re.match(pattern='[A-Z]{5}[-][0-2]{5}', string=user_input):
guesses[user_input.split('-')[0]] = [int(x) for x in list(user_input.split('-')[1])]
else:
bad_input = True
return guesses, bad_input
|
cb378bbbf994d32a79fd385e17e568f380bc189c
| 376,498 |
def build_dict(arg):
"""
Helper function to the Evaluator.to_property_di_graph() method that
packages the dictionaries returned by the "associate" family of
functions and then supplies the master dict (one_dict) to the Vertex
obj as kwargs.
"""
# helper function to the Evaluator.to_property_di_graph() method that
# packages the dictionaries returned by the "associate_" family of
# functions and then supplies the master dict (one_dict) to the Vertex
# obj as **kwargs
one_dict = {}
for ar in arg:
one_dict.update(ar)
return one_dict
|
9f379b6f612e86dcc5e73cbcc479c186e95653b7
| 271,287 |
import base64
def toProtobufString(protoObject):
"""
Serialises a protobuf object as a base64-encoded protobuf string
"""
# the base64-encoding shouldn't be necessary, but otherwise
# currently the "string" with high-bit-set bytes gets helpfully
# re-coded into corresponding unicode string in transit.
# Should find and fix that rather than base64 encoding
return base64.b64encode(protoObject.SerializeToString())
|
2a3270432f9cd4070fd5d2167ee5db118fd4660e
| 382,672 |
import torch
def prepare_sequence(seq, to_ix):
"""return indexes sequence of input word sequence
Args:
seq (list): word sequence
to_ix (dict): word to index map
Returns:
Tensor: indexes in Tensor format
"""
idxs = [to_ix[w] for w in seq]
return torch.tensor(idxs, dtype=torch.long)
|
da8276a4d54e15fa2f5cd9964abfa5483b9b5fd8
| 416,348 |
def html_obfuscate_string(string):
"""Obfuscates a string by converting it to HTML entities
Useful for obfuscating an email address to prevent being crawled by spambots
"""
obfuscated = ''.join(['&#%s;' % str(ord(char)) for char in string])
return obfuscated
|
21ef043a000f013ca7c19dba993b451b31de6398
| 486,094 |
def get_job_kwargs(job):
"""Returns keyword arguments of a job.
:param Job job: An apscheduler.job.Job instance.
:return: keyword arguments
:rtype: dict
"""
return job.kwargs
|
407e20c48886b9ecac9ecaf9bfeef634fdbd5da4
| 288,284 |
def get_unique_rows(df, columns, sort_by):
"""De-dupe a Pandas DataFrame and return unique rows.
:param df: Pandas DataFrame.
:param columns: List of columns to return.
:param sort_by: Column to sort by.
:return: Pandas DataFrame de-duped to remove duplicate rows.
"""
df = df[columns]
df = df.drop_duplicates(subset=None, keep='last', inplace=False)
df = df.sort_values(sort_by, ascending=False)
return df
|
1d1950cf07b54b03ecd86fdd5d5a038e51323ef7
| 255,730 |
def _text_indent(text, indent):
# type: (str, str) -> str
"""
indent a block of text
:param str text: text to indent
:param str indent: string to indent with
:return: the rendered result (with no trailing indent)
"""
lines = [line.strip() for line in text.strip().split('\n')]
return indent + indent.join(lines)
|
00101ea91edf3207983b57aa0d9022c08a4956ba
| 77,626 |
def levenshtein_distance(w1, w2):
"""
Calculates the Levenshtein (minimum edit) distance between two words. This implementation is based on the one
provided by Stavros Korokithakis ( https://www.stavros.io/posts/finding-the-levenshtein-distance-in-python/ ),
licensed under BSD with Attribution. For questions concerning the original implementation, Stavros can be
contacted via email at [email protected] .
Levenshtein Distance summary: https://en.wikipedia.org/wiki/Levenshtein_distance
"""
if len(w1) > len(w2): w1, w2 = w2, w1
if len(w2) == 0: return len(w1)
len_w1 = len(w1) + 1
len_w2 = len(w2) + 1
dist_matrix = [[0] * len_w2 for x in range(len_w1)]
for i in range(len_w1): dist_matrix[i][0] = i
for j in range(len_w2): dist_matrix[0][j] = j
for i in range(1, len_w1):
for j in range(1, len_w2):
del_cost = dist_matrix[i-1][j] + 1
ins_cost = dist_matrix[i][j-1] + 1
sub_cost = dist_matrix[i-1][j-1]
if w1[i-1] != w2[j-1]: sub_cost += 1
dist_matrix[i][j] = min(ins_cost, del_cost, sub_cost)
return dist_matrix[len_w1-1][len_w2-1]
|
ffdd256eafffc2294b2750dc84b8ed53e272900d
| 148,755 |
def _is_variable_argument(argument_name):
"""Return True if the argument is a runtime variable, and False otherwise."""
return argument_name.startswith('$')
|
cf74d6dfd1c0ea1b560bf3766e2fac8af1dbafda
| 17,537 |
import requests
def SendJSON(address, parameters):
""" Send a JSON request given a URL address and JSON parameters
"""
r = requests.get(url = address, params = parameters)
return r.json()
|
a1a0260923aeb5ad00a7a63c22c5639fb6a544cd
| 245,827 |
def get_polygon_area(verts):
"""
Calculate the area of a closed polygon
Parameters
----------
verts : numpy.ndarray
polygon vertices
Returns
-------
area : float
area of polygon centroid
"""
nverts = verts.shape[0]
a = 0.
for iv in range(nverts - 1):
x = verts[iv, 0]
y = verts[iv, 1]
xp1 = verts[iv + 1, 0]
yp1 = verts[iv + 1, 1]
a += (x * yp1 - xp1 * y)
a = abs(a * 0.5)
return a
|
86165171c8f75b079ae554759db47bce9841b1fa
| 606,735 |
def default_if_none(value, arg):
"""If value is None, use given default."""
if value is None:
return arg
return value
|
bceed44594652d17ba9c4aab6eec6697e72032ab
| 534,884 |
def compact(iterable, generator=False):
""" Returns a list where all None values have been discarded. """
if generator:
return (val for val in iterable if val is not None)
else:
return [val for val in iterable if val is not None]
|
229b7a37bfa85ea4373fe54aabdb32dbae87e9ca
| 397,352 |
def depth_first_search(grid, start, target):
"""
Search a 2d grid for a given target starting at start.
Args:
grid: the input grid as a List[List]
start: the start grid in format (x,y) zero index
target: the target value to find in the grid
Returns:
Coordinate of the target. Or None if cannot be found.
"""
height = len(grid)
if not height:
return None
width = len(grid[0])
x_start = start[0]
y_start = start[1]
# short circuit the start lookup
if grid[y_start][x_start] == target:
return (x_start, y_start)
visited = set()
stack = [(x_start, y_start)]
visited.add((x_start, y_start))
while stack:
current = stack.pop()
for coor in [(current[0], current[1]-1),(current[0]-1, current[1]),(current[0]+1, current[1]),(current[0], current[1]+1)]:
if coor[0] < 0 or coor[0] > width-1 or coor[1] < 0 or coor[1] > height-1:
continue
if grid[coor[1]][coor[0]] == target:
return coor
else:
if coor not in visited:
stack.append(coor)
visited.add(current)
return None
|
1bd8c5c5c5a3b44df97e9ff899576bfab44ad4e4
| 618,917 |
def _ends_in_by(word):
"""
Returns True if word ends in .by, else False
Args:
word (str): Filename to check
Returns:
boolean: Whether 'word' ends with 'by' or not
"""
return word[-3:] == ".by"
|
d6a080f8d3dcd5cab6ad6134df3dd27b3c2ceeea
| 46,321 |
def split_role(r):
"""
Given a string R that may be suffixed with a number, returns a
tuple (ROLE, NUM) where ROLE+NUM == R and NUM is the maximal
suffix of R consisting only of digits.
"""
i = len(r)
while i > 1 and r[i - 1].isdigit():
i -= 1
return r[:i], r[i:]
|
fe79df1421eb7903ea7f898b4940ec8feb48cdb7
| 363,590 |
def read_chunk(stream):
"""Read at most a chunk from a stream"""
chunk_size = 16 * 1024
return stream.read(chunk_size)
|
7ae1bf00edb285f34137048d836d81575ddb7834
| 446,587 |
def __prompt_overwrite(filename: str) -> bool:
"""Prompt if the given file should be overwritten.
:param str filename: the filename
:return: `True` if answered `y`, `False` if answered `n` or nothing
:rtype: bool
"""
prompt = input(f"Should '{filename}' be overwritten? [y/N] ")
if prompt.lower() == "y":
return True
elif prompt.lower() in ("n", ""):
return False
else:
return __prompt_overwrite(filename)
|
7694c8babfe51a62f73497bb7235d00dcddfe8e8
| 430,237 |
def flatten(seq):
"""Flatten a list of lists (NOT recursive, only works for 2d lists)."""
return [x for subseq in seq for x in subseq]
|
9cf1df0818d1852006f45b6b2a20000458f69b9a
| 141,823 |
def get_std_opt_group(parser):
""" Returns the 'Standard Options (optional)' argument group from the
standard parser. """
for group in parser._action_groups:
if group.title=="Standard Options (optional)":
return(group)
return(None)
|
acb4fd58c59750a2f9836013dcc65849263c9593
| 258,222 |
def dictionary_filter(dictionary, cols) -> dict:
"""Can be used to filter certain keys from a dict
:param dictionary: The original dictionary
:param cols: The searched columns
:return: A filtered dictionary
"""
return {key:value for (key,value) in dictionary.items() if key in cols}
|
d7a67bad623dce18e29e643d4cd2c1a9f3151a2d
| 538,130 |
def optional_arguments(d):
"""
Decorate the input decorator d to accept optional arguments.
"""
def wrapped_decorator(*args):
if len(args) == 1 and callable(args[0]):
return d(args[0])
else:
def real_decorator(decoratee):
return d(decoratee, *args)
return real_decorator
return wrapped_decorator
|
433dbb2653fcec612cfeb5817fd3a37155741c78
| 124,425 |
from typing import Dict
from typing import List
def span_subwords(
word: str,
unk_token: str,
vocab: Dict[str, int],
max_input_chars_per_word: int,
) -> List[str]:
"""
Tokenize a word into several subwords.
This code is copied from Bert tokenization.py.
Requirement: The input word should not contain whitespaces and accent tokens.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
The default arguments in BERT are
unk_token = '[UNK]'
max_input_chars_per_word = 200
E.g.
>>> span_subwords(
word="unaffable",
vocab={"un": 0, "##aff": 1, "##able": 2},
max_input_chars_per_word=200,
)
["un", "##aff", "##able"]
"""
# length of word is more than expected -> return [unk_token]
if len(word) > max_input_chars_per_word:
return [unk_token]
# subword matching
chars = list(word)
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start: end])
if start > 0:
substr = "##" + substr
if substr in vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
# one of subwords is not in vocab
return [unk_token]
return sub_tokens
|
c0ea928e7c37f6f901a6c0424fd30e257b29f1f2
| 303,157 |
def has_train(args):
"""Returns if some kind of train data is given in args.
"""
return (args.training_set or args.source or args.dataset or
args.datasets or args.source_file or args.dataset_file or
args.train_stdin or args.source_file)
|
6412f38f364e3332f606227b5404836b4940424e
| 463,459 |
def GetCbsdRegistrationRequest(cbsd):
"""Returns a CBSD registration request from the |Cbsd| object.
"""
return {
'cbsdCategory': cbsd.category,
'installationParam': {
'latitude': cbsd.latitude,
'longitude': cbsd.longitude,
'height': cbsd.height_agl,
'heightType': 'AGL',
'indoorDeployment': cbsd.is_indoor,
'antennaBeamwidth': cbsd.antenna_beamwidth,
'antennaAzimuth': cbsd.antenna_azimuth,
'antennaGain': cbsd.antenna_gain,
}
}
|
2720960f20e9eb792f0cc4dc5564c85a5dd69743
| 635,041 |
import re
def match_email(text):
"""Given a string, tries to find a regex match for an email."""
email_regex = r'(.+\s+)*(<)*\s*(?P<email>\w+(?:.+\w+)*@\w+(?:.+\w+)' + \
r'(?:\.\w+)+)(>)*'
match = re.match(email_regex, text)
if match:
return match.group('email')
|
0e888af8366062f1af789b12b5e3792ba492fd92
| 596,096 |
def strip_prefix(string, prefix):
"""Strip the given prefix from the string if it's present
"""
return string[len(prefix):] if string.startswith(prefix) else string
|
f7deb89958f2eeee2f2cf904172a65f6e00a68b2
| 174,322 |
def modulus(x, y):
""" Modulus """
return x % y
|
ea2694f98133ddaf43da3f3eb702f5ba22dec597
| 73,576 |
def remove_suffix(s: str, suffix: str) -> str:
"""Remove the suffix from the string. I.e., str.removesuffix in Python 3.9."""
# suffix="" should not call s[:-0]
return s[: -len(suffix)] if suffix and s.endswith(suffix) else s
|
17474d37726249dc84aa89f0861fe43db43bf1e9
| 46,177 |
from typing import Collection
from typing import Callable
from typing import Tuple
def key_func_for_attribute_multi(
attributes: Collection[str],
) -> Callable[
...,
Tuple[Tuple[str, str], ...],
]:
""" Return a closure that given a slave, will return the value of a list of
attributes, compiled into a hashable tuple
:param attributes: the attribues to inspect in the slave
:returns: a closure, which takes a slave and returns the value of those attributes
"""
def get_attribute(slave, attribute):
if attribute == "hostname":
return slave["hostname"]
else:
return slave["attributes"].get(attribute, 'unknown')
def key_func(slave):
return tuple((a, get_attribute(slave, a)) for a in attributes)
return key_func
|
b6695436124187927b9ac36362271f6aaf102e0a
| 537,727 |
def versiontuple(v: str) -> tuple:
"""
Function to converts a version string into a tuple that can be compared, copied from
https://stackoverflow.com/questions/11887762/how-do-i-compare-version-numbers-in-python/21065570
"""
return tuple(map(int, (v.split("."))))
|
53a506e7c5eb6c7b1d601968487bbce88f8905d4
| 450,711 |
def _combine_prg_roles(user_prg_roles, startup_prg_roles):
"""
Collapse two dictionaries with list values into one by merging
lists having the same key
"""
for key, value in startup_prg_roles.items():
if user_prg_roles.get(key):
user_prg_roles[key] = user_prg_roles[key] + value
else:
user_prg_roles[key] = value
return user_prg_roles
|
d7864f6b087593eed7fe5872100a0cb261db54fc
| 388,560 |
import re
def extract_code(text):
""" Extracts the python code from the message
Return value: (success, code)
success: True if the code was found, False otherwise
code: the code if success is True, None otherwise
"""
regex = r"(?s)```(python)?(\n)?(.*?)```"
match = re.search(regex, text)
if match:
return (True, match.group(3))
else:
return (False, None)
|
a912c90973f1d5ebbc356f4a9310a45757928d63
| 674,485 |
def _get_percent(text):
"""If text is formatted like '33.2%', remove the percent and convert
to a float. Otherwise, just convert to a float.
"""
if not text:
return None
if text.endswith('%'):
text = text[:-1]
return float(text.strip())
|
2975f0a603a113bf7991753250a83be4da363070
| 697,388 |
def init_global_params(run_settings):
"""
initialize global parameters
:run_settings: run settings dict, must contain
- dims
- max_iterations
- num_centroids
- threshold
:returns: GlobalParams list
"""
global_params = []
global_params.append(run_settings['num_points'])
global_params.append(run_settings['dims'])
global_params.append(run_settings['num_centroids'])
global_params.append(run_settings['max_iterations'])
global_params.append(run_settings['threshold'])
return global_params
|
fda866c9870bad2eae4522a3aec86d8d490164e2
| 279,485 |
import socket
def get_ipv4(hostname):
"""Get list of ipv4 addresses for hostname
"""
addrinfo = socket.getaddrinfo(hostname, None, socket.AF_INET,
socket.SOCK_STREAM)
return [addrinfo[x][4][0] for x in range(len(addrinfo))]
|
134adec72e28809f364725904f78996755725e6f
| 308,263 |
import struct
def unpack(fmt, data):
"""
a more ergonnomic struct.unpack,If data is longer than the fmt spec it copes
remaining data returned as last data element
@param fmt: format string as per L{struct.unpack}
@type fmt: L{str}
@param data: data to be unpacked, optionally more
@type data: L{bytes}
@rtype: L{tuple}
"""
sz = struct.calcsize(fmt)
ret = struct.unpack(fmt, data[:sz])
ret = list(ret)
ret.append(data[sz:])
return tuple(ret)
|
14f6d3fc413c9c6145af975cb2ad5445c78acce7
| 349,507 |
def format_bytes(nbytes):
"""Format ``nbytes`` as a human-readable string with units"""
if nbytes > 2 ** 50:
return "%0.2f PiB" % (nbytes / 2 ** 50)
if nbytes > 2 ** 40:
return "%0.2f TiB" % (nbytes / 2 ** 40)
if nbytes > 2 ** 30:
return "%0.2f GiB" % (nbytes / 2 ** 30)
if nbytes > 2 ** 20:
return "%0.2f MiB" % (nbytes / 2 ** 20)
if nbytes > 2 ** 10:
return "%0.2f KiB" % (nbytes / 2 ** 10)
return "%d B" % nbytes
|
6996b7632dcd638edb9ae9ef1d3168e583bc87ff
| 594,818 |
def read_data_asc(f):
"""
Read the elevation data from
the file 'f'. This data will be returned as a
two-dimensional list to be interpreted as:
[
Y1:[X1, X2, ...Xn],
Y2:[X1, X2, ...Xn],
...
Yn:[X1, X2, ...Xn]
]
"""
data = list()
header = True
for line in f:
if not header:
line = line.strip() #strip all leading/trailing whitespace
line_list = line.split(" ")
float_list=[float(elem) for elem in line_list]
data.append(float_list)
elif "NODATA" in line: #indicates end of header
header = False
return data
|
4b495a0300ea9ea3a664706fce650d5c51bce643
| 166,710 |
def default_if_none(value, default):
"""Return given default if value is None"""
if value is None:
return default
return value
|
86c036ac86d8b6b6c3ae2f2800d4711b38d7c523
| 430,668 |
def _GetObjcName(attr):
"""Returns the Objective-C name for the given attribute."""
if attr.name.startswith('init'):
return 'getI' + attr.name[1:]
return attr.name
|
db8819567c5636ddd783330d84a92be8ba23fb77
| 598,929 |
def recommender_function(model, X, treatment_column):
"""
Calculate the recommender function for a set of patients based on a
previously fitted model. Implementation corresponds to the one
proposed in [1] (Eq. 6).
Parameters
----------
model:
Model that will be used to compute the log-hazards.
It needs to be fitted previously.
X: pandas DataFrame
Data. Rows correspond to instances (i.e, patients).
Columns correspond to features.
treatment_column: string
Which column in X corresponds to the treatment.
Currently, it only supports comparison of two treatments.
Returns
-------
rec_ij: NumPy array.
The recommender function of all patients. For each patient:
If rec_ij is positive, it means that treatment i lead to a higher
risk of death than treatment j.
If rec_ij is negative, it means that treatment j lead to a higher
risk of death than treatment i.
References
----------
[1] Katzman, Jared L., et al. "DeepSurv: personalized treatment recommender system using a Cox proportional hazards deep neural network." BMC medical research methodology 18.1 (2018): 24.
"""
# Validate number of treatments.
treatments = X[treatment_column].unique()
n_treatments = len(treatments)
if n_treatments == 1:
raise ValueError("It is not possible to give a treatment recommendation with only one treatment value.")
elif n_treatments > 2:
raise ValueError(f"{n_treatments} found. Currently, only two treatments are supported for comparison.")
# Create DataFrames to be used for prediction.
X_treatment0 = X.copy(deep=True)
X_treatment0[treatment_column] = treatments[0]
X_treatment1 = X.copy(deep=True)
X_treatment1[treatment_column] = treatments[1]
# Calculate the log-hazards.
h_i = model.predict(X_treatment0)
h_j = model.predict(X_treatment1)
# Calculate the recommender function (Eq. 6)
rec_ij = h_i - h_j
return rec_ij
|
f1bb817b3e2297ac0c66ae008d765db9a749544f
| 453,558 |
def resolve_underlying_function(thing):
"""Gets the underlying (real) function for functions, wrapped functions, methods, etc.
Returns the same object for things that are not functions
"""
while True:
wrapped = getattr(thing, "__func__", None) or getattr(thing, "__wrapped__", None) or getattr(thing, "__wraps__", None)
if wrapped is None:
break
thing = wrapped
return thing
|
08e9d0909acb803d4877cb8610aace8465266bb9
| 463,233 |
def clo32(val):
""" Count Leading Ones starting from bit 32. """
# pylint: disable=line-too-long
first_bit = val[31] ^ 0x0
ctr = (1 & val[31]) + \
(1 & val[30]) + \
(1 & val[29] & val[30]) + \
(1 & val[28] & val[30] & val[29]) + \
(1 & val[27] & val[30] & val[29] & val[28]) + \
(1 & val[26] & val[30] & val[29] & val[28] & val[27]) + \
(1 & val[25] & val[30] & val[29] & val[28] & val[27] & val[26]) + \
(1 & val[24] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25]) + \
(1 & val[23] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24]) + \
(1 & val[22] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23]) + \
(1 & val[21] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22]) + \
(1 & val[20] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21]) + \
(1 & val[19] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20]) + \
(1 & val[18] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19]) + \
(1 & val[17] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18]) + \
(1 & val[16] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17]) + \
(1 & val[15] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16]) + \
(1 & val[14] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15]) + \
(1 & val[13] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14]) + \
(1 & val[12] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13]) + \
(1 & val[11] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12]) + \
(1 & val[10] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11]) + \
(1 & val[9] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10]) + \
(1 & val[8] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10] & val[9]) + \
(1 & val[7] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10] & val[9] & val[8]) + \
(1 & val[6] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10] & val[9] & val[8] & val[7]) + \
(1 & val[5] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10] & val[9] & val[8] & val[7] & val[6]) + \
(1 & val[4] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10] & val[9] & val[8] & val[7] & val[6] & val[5]) + \
(1 & val[3] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10] & val[9] & val[8] & val[7] & val[6] & val[5] & val[4]) + \
(1 & val[2] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10] & val[9] & val[8] & val[7] & val[6] & val[5] & val[4] & val[3]) + \
(1 & val[1] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10] & val[9] & val[8] & val[7] & val[6] & val[5] & val[4] & val[3] & val[2]) + \
(1 & val[0] & val[30] & val[29] & val[28] & val[27] & val[26] & val[25] & val[24] & val[23] & val[22] & val[21] & val[20] & val[19] & val[18] & val[17] & val[16] & val[15] & val[14] & val[13] & val[12] & val[11] & val[10] & val[9] & val[8] & val[7] & val[6] & val[5] & val[4] & val[3] & val[2] & val[1])
return ctr * first_bit
|
8a94901a9ca30533c2124ef0f5331d6e405b427f
| 576,194 |
def fileNumber(filePath):
"""
Get the number of the file. foo.0080 would return 0080
"""
num = filePath.split('.')[-1]
return int(num)
|
731918660f0c145c15ba99c2f5eb8be9745e8576
| 10,404 |
def sequence_input_funcs(input_funcs):
""" Returns a function that
- is like (the first element of input_funcs) the first time that it's called
- is like (the second element of input_funcs) the second time that it's called, etc.
- just returns None (ignoring its arguments) when there are no more elements of input_funcs
"""
it = iter(input_funcs)
def choose(*args):
try:
input_func = next(it)
except StopIteration:
return None
return input_func(*args)
return choose
|
26cffdfaaceff694c9df6afa8b39f98a26d79474
| 539,706 |
def Format_Phone(Phone):
"""Function to Format a Phone Number into (999)-999 9999)"""
Phone = str(Phone)
return f"({Phone[0:3]}) {Phone[3:6]}-{Phone[6:10]}"
|
8e46c35bca9d302d86909457c84785ad5d366c15
| 708,876 |
def invert_image(image):
"""
Inverts a binary image
Args:
image: a binary image (black and white only)
Returns:
An inverted version of the image passed as argument
"""
return 255 - image
|
eb466971c77fae2a57ad86a3b555884865ed404a
| 18,574 |
import hashlib
def digest(binary_data: bytes) -> str:
""" Return a SHA256 message digest for the given bytes string
:param binary_data: The binary data to digest
:return: A length-64 hex digest of the binary data
"""
m = hashlib.sha256()
m.update(binary_data)
return m.hexdigest()
|
c37403e2e47cd49fbfddbc33c09444186e8b8a9e
| 385,960 |
def create_all_possible_moves(m, n):
"""Create all moves on a (m,n) board."""
moves = []
for i in range(m):
for j in range(n):
moves.append((i, j))
return list(set(moves))
|
355670f2d0ffb5e462ca2ed02f8b6c766122807b
| 245,140 |
from typing import List
from typing import Tuple
def replace_one(title: str, abstract: str,
concepts: List[Tuple[int, int, str]]) -> str:
"""
Replace concepts in one PubMed article's title and abstract.
:param title: title string
:param abstract: abstract string
:param concepts: list of (start, end, concept_id) tuples
:return: string of title+abstract after replacements
"""
all_text = ''.join([title, abstract])
new_text = []
current = 0
for (start, end, cid) in concepts:
new_text.append(all_text[current:start])
new_text.append(cid)
current = end
new_text.append(all_text[current:])
return ''.join(new_text)
|
9d3c3bae5e0118506ee9cc5d8cdcd8665de14f9e
| 154,585 |
from functools import reduce
def extend(*dicts):
"""
Returns a dictionary that combines all dictionaries passed as arguments
without mutating any of them.
"""
def fold(acc, curr):
acc.update(curr)
return acc
return reduce(fold, dicts, {})
|
5f99cba8446f0a8bbd4385c8c91e5e3261fc0367
| 528,056 |
def mblg_to_mw_johnston_96(mag):
"""
Convert magnitude value from Mblg to Mw using Johnston 1996 conversion
equation.
Implements equation as in line 1654 in hazgridXnga2.f
"""
return 1.14 + 0.24 * mag + 0.0933 * mag * mag
|
f23acde1063c9c0f4c13a5d3679bf7e894fd6a00
| 624,816 |
import time
def exec_remote_cmd(client, cmd, t_sleep=5, verbose=False):
"""A wrapper function around paramiko.client.exec_command that helps with
error handling and returns only once the command has been completed.
Parameters
----------
client : paramiko ssh client
the client to use
cmd : str
the command to execute
t_sleep : float, optional
the amount of time to wait between querying if a job is complete
verbose : str, optional
print information about the command
"""
if verbose:
print("Remotely executing '{0}'".format(cmd))
stdin, stdout, stderr = client.exec_command(cmd)
while not stdout.channel.exit_status_ready():
if verbose:
print('Command not complete, checking again in {0} seconds.'.format(
t_sleep))
time.sleep(t_sleep)
if stdout.channel.recv_exit_status() != 0:
raise IOError('Error with command {0}: {1}'.format(
cmd, " ".join(stderr)))
return stdin, stdout, stderr
|
e6a79b58925252284c5427895d41ce3eed77f58f
| 56,271 |
def find_in_map(map_name, key, value):
"""The intrinsic function Fn::FindInMap returns the value of a key from a \
mapping declared in the Mappings section.
Args:
map_name: The logical name of the mapping declared in the Mappings
section that contains the key-value pair.
key: The name of the mapping key whose value you want.
value: The value for the named mapping key.
Returns: The map value.
.. note:
find_in_map is represented here "just in case".
Most likely, using the python equivalent in a pyplate will be
easier to both look at and maintain.
"""
return {'Fn::FindInMap': [map_name, key, value]}
|
491168fb619334f8dac8857b96481d90d9f8675f
| 70,113 |
def get_displayname(id, context):
"""
This function gets the printable username of a user
"""
user = context.message.guild.get_member(id)
if user is None:
return f"User {id}"
else:
return user.display_name
|
0f284e67a56ed460eecabe02b10d9f9669f2246a
| 224,651 |
import struct
def get_flag(alignment: bytes) -> int:
"""
Extract the alignment flag from a BAM alignment
Parameters
----------
alignment : bytes
A byte string of a bam alignment entry in raw binary format
Returns
-------
int
The alignment flag
Notes
-----
Flag values can be tested on raw BAM alignment with pylazybam.bam.is_flag()
Common flag values are available from pylazybam.bam.FLAGS
>>> print(pylazybam.bam.FLAGS)
{"paired": 0x1,
"aligned": 0x2,
"unmapped": 0x4,
"pair_unmapped": 0x8,
"forward": 0x40,
"reverse": 0x80,
"secondary": 0x100,
"qc_fail": 0x200,
"duplicate": 0x400,
"supplementary": 0x800,}
See https://samtools.github.io/hts-specs/SAMv1.pdf for details.
"""
return struct.unpack("<H", alignment[18:20])[0]
|
8cd0e2678467de22bb7cf4a027be33529c21ca94
| 269,243 |
def is_in_graph(G, v):
""" Check whether a node is in the graph. """
assert isinstance(v, str) # v should be a label
return v in G.nodes()
|
7dce9b4042b0a780734e31a6703aa427853bbc50
| 290,021 |
from typing import Callable
from typing import Iterable
from typing import Any
def ifilter(
function: Callable, iterable: Iterable, false: bool = False
) -> Iterable[Any]:
"""
Filter out the elements from iterable in accordance to function.
Notes
-----
The Python builtin filter class implementation.
The `false` key makes ifilter to work like itertools.filterfalse class.
Parameters
----------
function : Callable
function to apply on an item of iterable.
iterable : Iterable
false : bool, optional
filter on the false condition. The default is False.
Raises
------
TypeError
if `function` is not callable or `iterable` is not iterable.
References
----------
https://docs.python.org/3/library/functions.html#filter
https://docs.python.org/3/library/itertools.html#itertools.filterfalse
Yields
------
Iterable[Any]
"""
def _falsify(func: Callable):
"""Negate the result of foo function."""
def _not(arg: Any):
"""Return the negated result of foo function."""
return not func(arg)
return _not
if function is None:
function = bool
if false:
func = _falsify(function) # pylint is satisfied
else:
func = function
return (item for item in iterable if func(item))
|
f0c2ac169b5ddf1863f0f6e364076e7e5795e19f
| 130,828 |
def from_base_alphabet(value: str, alphabet: str) -> int:
"""Returns value in base 10 using base len(alphabet)
[bijective base]"""
ret = 0
for digit in value:
ret = len(alphabet) * ret + alphabet.find(digit)
return ret
|
386a286b2ad0f894adef69d40b8522f47ccdf287
| 335,585 |
from pathlib import Path
def file_exists(file_path):
"""
Check if file exists
:param file_path: (str) path to file
:return: (bool) True if file exists, False otherwise
"""
return Path(file_path).is_file()
|
69a973f1c399477dff8b04381d5c7defa6f435c7
| 283,638 |
def get_es_worker(es_algorithm, logger, **kwargs):
"""Instantiate an evolution strategic algorithm worker.
Return an ES algorithm worker from the algorithms package.
Args:
es_algorithm: algorithms.*. ES algorithm.
logger: logging.Logger. Logger.
Returns:
algorithms.*Worker.
"""
return es_algorithm(logger=logger, **kwargs)
|
6a12d0f44c0edfe34235d145fdb38e5b64ac836f
| 579,350 |
def convertir_tiempo(segundos: int) -> str:
"""Convierte un tiempo en segundos a horas, minutos y segundos
:param segundos: tiempo en segundos
:type segundos: int
:return: tiempo en formato hh:mm:ss
:rtype: str
"""
horas = segundos // 3600
minutos = (segundos % 3600) // 60
segundos = segundos % 60
return f"{horas:02d}:{minutos:02d}:{segundos:02d}"
|
be37add8e4acfa4af3dd1273468bc8ae1a38c52a
| 177,984 |
def get_best_k(trials,
k=1,
status_whitelist=None,
optimization_goal='minimize'):
"""Returns the top k trials sorted by objective_value.
Args:
trials: The trials (Trail objects) to sort and return the top_k of.
k: The top k trials to return. If k=1 we don't return a list.
status_whitelist: list of statuses to whitelist. If None, we use all trials.
optimization_goal: string, minimize or maximize.
Returns:
The top k trials (list unless k=1) sorted by objective_value.
"""
trials_ = trials
valid_status = status_whitelist
if valid_status is not None:
trials_ = [
trial for trial in trials_
if trial.status in valid_status and not trial.trial_infeasible
]
if not trials_:
return None
maximizing = optimization_goal != 'minimize'
top = sorted(
trials_,
key=lambda t: t.final_measurement.objective_value,
reverse=maximizing)
return top[:k] if k > 1 else top[0]
|
626c9664f013ed37c435a466603372d6f615d4c8
| 69,921 |
def update_driver_standings(standings, race_result):
"""
This function updates the driver's standings to reflect the points earned from a race.
Parameters:
standings (list): A list of dictionaries that contains the current driver's championship standings.
race_result (list): A list of dictionaries that contains the results from a race.
Returns:
(list): The updated driver's standings list containing points earned from the given race.
"""
for driver in race_result:
for row in standings:
if row['driver'] == driver['name']:
row['points'] = driver['points'] + row['points']
return standings
|
60138ad12ab1b9738ccb52f44123d7c242726165
| 276,945 |
def clean_reg_name(reg, list):
"""
Clean the name of the registers by removing any characters contained in
the inputted list.
"""
for char in list:
reg = reg.replace(char, '')
return reg
|
70bcd35e498c61c4ab1d53896d85fcd4fb74b5ff
| 32,286 |
def isAlphanum(c):
"""return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character.
"""
return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or
(c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126));
|
c955f5f7417ebcb0ce391bbbe244c2938035de81
| 618,998 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.