content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_palindromic_phrase(s):
""" (str) -> bool
Return True iff s is a palindrome, ignoring case and non-alphabetic
characters.
>>> is_palindromic_phrase('Appl05-#$elppa')
True
>>> is_palindromic_phrase('Mada123r')
False
"""
result = ''
for i in range(len(s)):
... | ec079e99518ba477228e8d0e39c8ce34ca4f7c89 | 628,456 |
import torch
def get_prediction_ids(predictions):
""" Get the label ids from the raw prediction outputs """
tensor = torch.tensor(predictions)
softmax = torch.nn.functional.softmax(tensor, dim=-1)
argmax = torch.argmax(softmax, dim=-1)
return argmax.tolist() | 51b93b23138c1d32cdba27d218ad01a87ebccb93 | 628,460 |
def semester(date, *, base=1):
"""
Returns the semester of the given date.
The first semester runs from 1 January to 30 June; the second
from 1 July to 31 December.
Parameters
----------
date : datetime.date
the date from which to determine the semester
base : int, optional
... | 6519ad39e31117d341345555de7753c2e1069d6f | 628,465 |
def jaccard_index_pair_counts(a, b, c):
"""
Compute the Jaccard index from pair counts; helper function.
Arguments:
a: number of pairs of elements that are clustered in both partitions
b: number of pairs of elements that are clustered in first but not second partition
c: number of pairs of elem... | c0da77d2195055c28c6fc2ec67d00aacfa1ac497 | 628,468 |
def create_lookup(stream, derived_fields, index_field):
"""
Build a lookup table from an indexed field to a set of derived fields.
Ensures that there is a unique relation, raises assertion if violated
:param stream: stream of records
:param derived_fields: list of derived fields assumed to be a func... | 4003e051fe1f816af7e7f7f2df7a438c3092a711 | 628,470 |
from typing import Counter
def fill_histogram(histograms, indices, hist_idx, normalize=True):
"""
Compute a histogram and fill in the designated entry in the array histograms.
:param histograms: Array that will contains histograms.
:param indices: Array with values from which a histogram should be co... | e4eb4c03c16aa01813526d83324dbf39082bbcb9 | 628,472 |
def isKtServerRunning(logPath):
"""Check if the server started running."""
success = False
with open(logPath) as f:
for line in f:
if line.lower().find("listening") >= 0:
success = True
return success | 71a2a67fee57c55e28238f00e5c37aa5287610b8 | 628,477 |
def split_numal(val):
"""Split, for example, '1a' into (1, 'a')
>>> split_numal("11a")
(11, 'a')
>>> split_numal("99")
(99, '')
>>> split_numal("a")
(0, 'a')
>>> split_numal("")
(0, '')
"""
if not val:
return 0, ''
for i in range(len(val)):
if not val[i].isdigit():
return int... | 7ba4b35d4727692770b9cd3764f5fdf10bfb6c7c | 628,480 |
import math
def hm(hours):
"""Convert hours to hour-minute
If hours is negative, only hour of the tuple is negative.
"""
if math.isinf(hours):
return None
minutes = int(math.ceil(hours * 60))
h, minutes = divmod(minutes, 60)
return (h, minutes) | 5b4473694ed40f0f5a1594f796e42bc92852217e | 628,482 |
def is_nfs_have_host_with_host_obj(nfs_details):
""" Check whether nfs host is already added using host obj
:param nfs_details: nfs details
:return: True if nfs have host already added with host obj else False
:rtype: bool
"""
host_obj_params = ('no_access_hosts', 'read_only_hosts',
... | 8beac82c761ca71456a627c5a34db241daf3059d | 628,483 |
from pathlib import Path
def pathlen(path):
"""Return folder level of the path string"""
return len(Path(path).parts) | 0819611deafe9beea2e608ab85f36edb69b35ac9 | 628,485 |
import re
def normalize_timestamp(ts):
"""Normalize a timestamp
For easier comparison
"""
if ts is None:
return
return re.sub(r'\d(\.\d+)?', '0', ts) | 58561922838381a2575df646d1892831f5b94b3b | 628,487 |
def esval(es, tlist):
"""
Evaluates an exponential series at the times listed in ``tlist``.
Parameters
----------
tlist : ndarray
Times at which to evaluate exponential series.
Returns
-------
val_list : ndarray
Values of exponential at times in ``tlist``.
"""
... | 4dd2d2287c0bdec8efc4740f69522ab08bda1103 | 628,490 |
def google_fixed_width_font(style):
"""check if the css of the current element defines a fixed width font"""
font_family = ''
if 'font-family' in style:
font_family = style['font-family']
if 'Courier New' == font_family or 'Consolas' == font_family:
return True
return False | 9067d72978db4b63244feb3255d80a8d48a37c09 | 628,492 |
import math
def avg(current, previous, bpp):
"""
To compute the Average filter, apply the following formula to each
byte of the scanline:
Average(x) = Raw(x) - floor((Raw(x-bpp)+Prior(x))/2)
:param current: byte array representing current scanline.
:param previous: byte array representing th... | d1034a5acc626922de33dc6f3b9c59b10c0ccbf1 | 628,499 |
from typing import List
from typing import Dict
def flatten_list_dict(lst: List[Dict[str, list]]) -> Dict[str, list]:
"""Flatten list of dicts to dict of lists
Parameters
----------
lst : List[Dict[str, list]]
list of dicts of lists
Returns
-------
Dict[str, list]
"""
ret... | 2ca88975b524fc7065e425ab79408095d600e7e4 | 628,502 |
def evaluate_f1(tp: int, fp: int, fn: int) -> float:
"""F1-score.
*F1-score* $=\dfrac{2TP}{2TP + FP + FN}$
Args:
tp: True Positives
fp: False Positives
fn: False Negatives
"""
try:
return 2 * tp / (2 * tp + fp + fn)
except ZeroDivisionError:
return 0.0 | 8ba6beeb0c8fe8c20e9d12fec462474c8d15de5b | 628,504 |
import re
def FindProperties(data):
"""Finds extra properties for a file.
Finds strings of the form '@PROPS[name name name]'.
Args:
data: The contents of the file being checked.
Returns:
A list of properties from the PROPS line in the file.
"""
match = re.search(r'@PROPS\[([^\]]*)\]', data)
if... | a7a3ae636fdcfb13d17977b9d36535fbd6adab6f | 628,505 |
def construct_version_string(major, minor, micro, dev=None):
"""
Construct version tag: "major.minor.micro" (or if 'dev' is specified: "major.minor.micro-dev").
"""
version_tag = f"{major}.{minor}.{micro}"
if dev is not None:
version_tag += f"-{dev}"
return version_tag | 4734dc4627dbeebb9562ebc800092f3368010af1 | 628,507 |
import torch
def get_valid_positive_mask(labels):
"""
To be a valid positive pair (a,p),
- a and p are different embeddings
- a and p have the same label
"""
indices_equal = torch.eye(labels.size(0)).byte()
indices_not_equal = ~indices_equal
label_equal = torch.eq(labels.unsqueeze(1), labels.unsqueeze(0))... | fb17b18129f85c2a33f7c7ddc571622cab52df7c | 628,509 |
def get_slicing_config(config):
"""Util function that generates config for visualization.
Args:
config: EvalConfig that contains example_weight_metric_key.
Returns:
A dictionary containing configuration of the slicing metrics evalaution.
"""
return {'weightedExamplesColumn': config.example_weight_me... | 43baae2073634a700fc42480fa13893e305c9eb7 | 628,511 |
from typing import Tuple
from typing import Optional
def sort_categories_key(category: str) -> Tuple[str, Optional[str], Optional[int]]:
"""A function which may be used as the key when sorting a list of categories.
This function assumes categories are based on chemical environments and
compositions (up to... | 7b25de52b6902458ccfbf2e62efce8c8e63be61f | 628,515 |
from datetime import datetime
def get_month_options(year):
"""
Get the month options for the given year.
For the previous year, there is data available for each individual month.
However, for previous years only the aggregate statistics is available.
Parameters:
year: (int): The year for... | dc68b71134e9628f61228215d0394ae189aee08f | 628,521 |
def binomial_coefficient_faster(n, r):
"""
A faster way to calculate binomial coefficients
>>> binomial_coefficient_faster(10,5)
252
"""
if 0 <= r <= n:
#initializing two variables as 1
ntok = 1
rtok = 1
#we use the formula nCr = n!/(n-r)!r!
for t in ran... | 1678b9295d68f5d4c49a14e048385a6af202e085 | 628,522 |
import math
def get_utm_zone_epsg(lon: float, lat: float) -> int:
"""
Calculates the suitable UTM crs epsg code for an input geometry point.
Args:
lon: Longitude of point
lat: Latitude of point
Returns:
EPSG code i.e. 32658
"""
zone_number = int((math.floor((lon + 180... | 68688609ad2f445bd808a07576137fa9763fb113 | 628,523 |
def getY(line, x):
"""
Get a y coordinate for a line
"""
m, c = line
y = int((m * x) + c)
return y | c98fe2c6c1b6fd6541008681dde0d6a669b50d0a | 628,526 |
def get(a, i):
"""Retrieve the i-th element or return None"""
return a[i] if len(a) > i else None | c8daf6e5d1cbf10d2e9d197e4c9b14e38740045b | 628,528 |
import torch
def GetLinear(w):
"""
Return the weights and bias of the Linear module 'w' as a flattened numpy array.
"""
return torch.cat([w.weight.data.flatten(), w.bias.data.flatten()],0).numpy() | e705795768dc7ae054143061b4aaf1ac63f8182a | 628,529 |
import re
def get_signature(source, start):
"""
Get function signature and process it
"""
match = re.search(r'c?p?def.+\(', source[start].strip())
if not match:
return
start_j = match.span()[1]
open_brackets = 1
new_sign = match.group()
for i in range(start, len(source)):
... | fbe542ec97e3b19e258833ac5c8262a42f6a31df | 628,531 |
def adjust_detector_position(final_detector_length,
requested_distance_to_tls,
lane_length):
""" Adjusts the detector's position. If the detector's length
and the requested distance to TLS together are longer than
the lane itself, the positio... | eb1cfaa3ec4bd6a5d981b61f971aeb80d3b71f3c | 628,534 |
def interpolatePercentCover(percentDatePrev, percentDateAfter, percentCoverPrev, percentCoverAfter, cutDate):
"""
inputs: percentDatePrev - date obj - date prior to cut date that recorded the percent cover
percentDateAfter - date obj - date after the cut date that recorded the percent cover
... | 485471021c15f2cdc10bc65e56591c9824ad5572 | 628,538 |
def filter_by_lines(units, lines):
"""Filter units by line(s)."""
return [i for i in units if i.line in lines] | d32103055115d078af1237b9d7d2c6fca57b187c | 628,539 |
def lower_case(s: str) -> str:
"""Transforms an input string into its lower case version.
Args:
s: Input string.
Returns:
(str): Lower case of 's'.
"""
return s.lower() | 73ebf662722ae5900f1f621dbf3ea09472f49be0 | 628,543 |
def read_text(filename):
"""
filename: string, name of file to read
Returns a string containing all file contents
"""
in_file = open(filename, 'r')
line = in_file.read()
return line | a8219008996a696f61f3fa35ccac3f68b272162e | 628,544 |
def open_input(input_path: str) -> list[str]:
"""Opens and sanitizes the `input.txt` file for the day reading in each line as an element of a list.
- Remove any extra lines at the end of the input files (if present, due to auto-formatting)
- Remove newline characters for individual element strings
- St... | 5b78f7d64d076bd1ed8b6ed1839aaaa45c48e001 | 628,547 |
import re
def match_pattern(pattern, value):
"""
Helper function to carry out pattern matching
"""
patt = re.compile(pattern)
match = patt.match(value)
return match is not None | 1e29ba068727bb73aa47ecb07f9766cd6fdb2a91 | 628,549 |
def match_id(dis_id):
"""Match a discord id depending on mention or raw ID"""
# ID is user mention or role mention
if any(x in dis_id for x in ["<@!", "<@&"]):
if len(dis_id) == 22:
return int(dis_id[3:-1])
# Simple mention
elif "<@" in dis_id:
if len(dis_id) == 21:
... | 476e36d4c9e5a6fbeff379fb8d290489fdda376b | 628,550 |
from typing import TextIO
from typing import Dict
from typing import OrderedDict
import yaml
def yaml_load(stream: TextIO) -> Dict[str, str]:
"""
Load a yaml from a file pointer in an ordered way.
:param stream: the file pointer
:return: the yaml
"""
# for pydocstyle
def ordered_load(stre... | 5523eb373c870820e6e2ca35f2083597be34a2c9 | 628,551 |
def BoringCallers(mangled, use_re_wildcards):
"""Return a list of 'boring' function names (optinally mangled)
with */? wildcards (optionally .*/.).
Boring = we drop off the bottom of stack traces below such functions.
"""
need_mangling = [
# Don't show our testing framework:
("testing::Test::Run", ... | 86715e6ae4f50fa3e295ac1f086861ffe994afc3 | 628,552 |
def get_completed_only(mxml_df):
"""
Filter only completed activities
"""
complete = mxml_df[mxml_df.EventType == "complete"].rename({
"Timestamp": "Timestamp_Complete"
}, axis=1).set_index(["TraceId", "WorkflowModelElement"])
return complete.drop(["Originator", "EventType"], e... | 8da852d6cbd1bb915581a53d05501b495e50faaf | 628,560 |
import random
def max_vote(votes):
"""Manual bilding of counts and selection randomly the max vote (count) in the case of a tie."""
counts = {}
for vote in votes:
if vote in counts.keys():
counts[vote] += 1
else:
counts[vote] = 1
# print(counts)
# Building t... | 993a52b4dd5a1c68d6c652a668b698acfcd4f22e | 628,564 |
from typing import Any
import requests
def api_call(method: str, endpoint: str, payload: Any = None):
"""Runs an API call to Transact API
Args:
method (str): HTTP method
endpoint (str): url endpoint (see documentation)
payload (Dict[str, Union[str, int, float]], optional): Data payloa... | a66038af2defe7cdd1fcc88a843d4a7b45175c1d | 628,566 |
def remove_file_prefix(file_path, prefix):
"""
Remove a file path prefix from a give path. leftover
directory separators at the beginning of a file
after the removal are also stripped.
Example:
'/remove/this/path/file.c'
with a prefix of:
'/remove/this/path'
becomes:
... | 11f1e4929ed94607c5f1aedfe2600e295b4b1e67 | 628,567 |
from typing import Iterable
from typing import Optional
from typing import List
from typing import Any
import json
def concatenate_json_lists(input_files: Iterable[str],
output_file: Optional[str] = None
) -> List[Any]:
"""
Given a list of JSON files that ... | a883678bd7cfa764b95f53f958e0efae34129218 | 628,568 |
from typing import List
def bands_union(*args: List[str]) -> List[str]:
"""Take union of given lists/sets of bands"""
bands = []
for arg in args:
for a in arg:
if a not in bands:
bands.append(a)
return bands | e65c14134311d044d996bd57e23cbb05b4c2f052 | 628,570 |
from typing import Optional
import importlib
def _get_optional_dependency_version(import_path: str) -> Optional[str]:
"""Attempts to retrieve the version of an optional dependency
Args:
import_path: The import path of the dependency.
Returns:
The version of the dependency if it can be im... | 8737d5b26bf9a75b500c7f0b6840715d3ee50069 | 628,571 |
def find_weather_emoji(weather_icon):
""" Given the `icon` description, finds a suitable emoji to represent weather
conditions, and returns it. Currently accepted values (more may be defined in
the future): clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy,
partly-cloudy-day, partly-cloudy-ni... | e26e54f35974019a654dc133f4568dadded6c91e | 628,572 |
import six
def urlpathjoin(*parts):
"""Join multiple paths into a single url
>>> urlpathjoin('https://storage.scrapinghub.com:8002/', 'jobs', '1/2/3')
'https://storage.scrapinghub.com:8002/jobs/1/2/3'
>>> urlpathjoin('https://storage.scrapinghub.com:8002', 'jobs', '1/2/3', None)
'https://storage.... | 9f4598de005b047479a6efe420b854460cf9c2fb | 628,576 |
def subtree_leaf_positions(subtree):
"""Return tree positions of all leaves of a subtree."""
relative_leaf_positions = subtree.treepositions('leaves')
subtree_root_pos = subtree.treeposition()
absolute_leaf_positions = []
for rel_leaf_pos in relative_leaf_positions:
absolute_leaf_positions.a... | e8cda95cf2be394418e144130612667acd37e1d5 | 628,580 |
def _get_file_as_string(path):
"""Get the contents of the file as a string."""
with open(path, 'r') as f:
data = f.read()
return data | 83864be3b24a5d21113aababe134fc86886bc083 | 628,581 |
def get_transceiver_description(sfp_type, if_alias):
"""
:param sfp_type: SFP type of transceiver
:param if_alias: Port alias name
:return: Transceiver decsription
"""
if not if_alias:
description = "{}".format(sfp_type)
else:
description = "{} for {}".format(sfp_type, if_ali... | 636844e09ffd591972fd067c6345c3aeb7da3da8 | 628,582 |
def seq_2_features(seq, indices):
"""converts a single sequence to a list of features
based on indices
"""
result = []
for idxs in indices:
feature = ''.join([seq[i] for i in idxs])
result.append(feature)
return result | 1eb30dad05c9e156634d2d466f6f7dcefeba57c0 | 628,583 |
import pathlib
from typing import Iterable
def is_covered(path: pathlib.Path, sources: Iterable[pathlib.Path]) -> bool:
"""
Checks if `path` is contained in any of the subdirectories in sources.
See the test cases for details.
"""
path = path.resolve()
abs_path = [source.resolve() for source i... | 72fdb6ff957f66d081cf7fc2a790780c14713e28 | 628,591 |
def solve(captcha):
"""Solve captcha.
:input: captcha string
:return: sum of all paired digits that match
>>> solve('1212')
6
>>> solve('1221')
0
>>> solve('123425')
4
>>> solve('123123')
12
>>> solve('12131415')
4
"""
a = len(captcha) // 2
return sum(i... | edd3b556db7bb22ea9180c93bb4e5043ce884283 | 628,596 |
def check_input(letter: str) -> bool:
"""
Author: Jeremy Trendoff
Returns the validity of an input.
Takes a str parameter representing the input.
>>> check_input('t')
True
>>> check_input('z')
False
"""
# A list representing the valid inputs
vaild_inputs = ['2', '3', 'x'... | 59876cddbd6871bdc1e3ceac2633b7e7d3a87809 | 628,598 |
import math
def theil_l_index(distribution):
"""Theil's L Index is sensitive to differences at the lower end of the
distribution (small incomes).
Args:
distribution (list): wealth distribution of the population
Returns:
(float): Theil's L Index (TL), inequality of wealth distribution... | 577a7bd9f264093f31f8b99cf1a5f9cc5c11e01b | 628,599 |
import functools
def require_privmsg(message=None):
"""Decorate a function to only be triggerable from a private message.
If it is triggered in a channel message, `message` will be said if given.
"""
def actual_decorator(function):
@functools.wraps(function)
def _nop(*args, **kwargs):... | 9477b91f74d651e7c4eccae8e17dafddc996316a | 628,601 |
def to_yy(year):
"""Returns the last 2 digits of the year."""
return str(year % 100).zfill(2) | 1b076d0dc9e1db711b59bc787d10bc833ab12868 | 628,603 |
def change(seq, start, end, change):
"""Return the sequence with ``seq[start:end]`` replaced by ``change``"""
return seq[:start] + change + seq[end:] | 56c7ed60ff36698cb27f62a5d85a3dc249ac9f33 | 628,610 |
def beta_word(beta: float) -> str:
"""Describe a beta
Parameters
----------
beta : float
The beta for a portfolio
Returns
----------
str
The description of the beta
"""
if abs(1 - beta) > 3:
part = "extremely "
elif abs(1 - beta) > 2:
part = "ver... | 5a1830e13bdaae27d4481e0414ede36f1406c992 | 628,612 |
from typing import List
import importlib
def instanciate_classes(modules: dict, module_root) -> List:
"""
Creates sources based on the config file where each key is a module and each subkey is a class
Each class can also have custom configurations when creating an instance
:param modules: dictionary w... | 9c0e249234b62556691a4e8b71387f67780ff1e5 | 628,613 |
def exp_points(df):
"""
Calculates expected points for home and away team
"""
df["H_Pts_Exp"] = 3 * df["H_prob_odds"] + 1 * df["D_prob_odds"]
df["A_Pts_Exp"] = 3 * df["A_prob_odds"] + 1 * df["D_prob_odds"]
return df | 2dc8fbd3c76442aacf91b0e9fd6cd9e96d2678ab | 628,617 |
import requests
from bs4 import BeautifulSoup
def get_soup_web(path):
""" Return the soup object of the url passed as argument."""
url = path
r = requests.get(url)
r_html = r.text
soup = BeautifulSoup(r_html, "html.parser")
return soup | 26b98b3aacf4ed4f0bba252614f222cfa1b83ab3 | 628,618 |
def split_sections(record):
"""Split record to LOCUS, VERSION, FEATURES and ORIGIN sections"""
ret = {'LOCUS': [], 'VERSION': [], 'FEATURES': [], 'ORIGIN': []}
keywords = ['LOCUS', 'DEFINITION', 'ACCESSION', 'VERSION', 'KEYWORDS', 'SOURCE', 'REFERENCE', 'FEATURES', 'ORIGIN']
key = ''
for line in re... | e5d1103ba9f2657f0e3c6557dd6aa9b5d18357aa | 628,620 |
def find_ultimate_dependency(cache, deps):
"""Find any one manually-installed package that ultimately caused at
least one of the given deps to be installed. Returns "" if none found.
"""
depchain = {dep: dep for dep in deps}
while depchain:
newchain = {}
for dep, path in depchain.items():
for parent in cach... | 4867de97d2e097793931063a5319762324875786 | 628,624 |
def get_conv_fname(fname: str, dest_ext: str, output_dir=None) -> str:
"""Returns the filename and path of the file after conversion
Arguments:
fname -- the original filename
dest_ext -- the extension of the destination file
output_dir -- the output directory of the operation
"""
if output... | 33e12ae11ec9f0e72f8ccefd0546fb3751b2bec9 | 628,625 |
def keffLineParse(keffLine):
"""
Parses through the anaKeff line in .res file.
@ In, keffLine, string, string from .res file listing IMPKEFF
@ Out, keffTuple, list, (mean IMPKEFF, sd of IMPKEFF)
"""
newKeffLine = keffLine[keffLine.find('='):]
start = newKeffLine.find('[')
end = newKeffLine.find(']... | 518adf5fe33d9c692d588ec0b9469872b39690aa | 628,627 |
def from_dataframe(df):
"""Turn a dataframe into a dictionary of columns, suitable writing."""
index = {}
for column in df.columns:
values = df[column].values
if(values.dtype == "object"):
index[column] = values.tolist()
else:
index[column] = values
retu... | 1335a641c86a77f034dc379f68cc8dd5e966cbdf | 628,630 |
def index_sites(structure, species=None, labels=None):
"""
Return a list of the site indices in a structure that are occupied by specie or label (or both)
Args:
- structure (Structure): pymatgen structure object
- species ({str}): site species to count
- label ({str}): sit... | 67d5bfb08775318b7d50e7c972f6a1ec34dd063e | 628,632 |
def getHttpStatusCode(v):
"""Return HTTP response code as integer, e.g. 204."""
if hasattr(v, "value"):
return int(v.value) # v is a DAVError
else:
return int(v) | 46baff7894765f252d1447611c6662cb388880db | 628,634 |
import json
def get_sns_msg(event):
"""Returns a message object extracted from AWS SNS event.
:param event: AWS event object
:type event: dict
:returns: JSON serialized SNS message object
:rtype: dict
"""
return json.loads(event['Records'][0]['Sns']['Message']) | 9263eb930ebec6b0cb0ee601ae1f23e03cf6780b | 628,638 |
def dfs_visited_re(node, graph, visited=[]):
"""DFS: Return visited nodes via recursion"""
for child in graph[node]:
if child not in visited:
visited.append(child)
dfs_visited_re(child, graph, visited)
return visited | 140c039be8eb59ee2334420fe07ba959f29f4088 | 628,639 |
import json
def convert_json_to_dict(filename):
""" Convert json file to python dictionary
"""
with open(filename, 'r') as JSON:
json_dict = json.load(JSON)
return json_dict | 11f8ea6d4999a204b9d239afde1aa7538d262208 | 628,640 |
import math
def distance(x1: float, y1: float, x2: float, y2: float):
"""
Return distance between two 2D points.
"""
dx = x2 - x1
dy = y2 - y1
return math.sqrt(dx * dx + dy * dy) | a956929ed37b224bc178d4755129f4b6d469a167 | 628,641 |
def get_last(s):
"""Get the last item in a Pandas Series"""
return s.iloc[-1] | 00088046fead8fac52156f5a97b432f1ef5c6e03 | 628,642 |
def excel_column_number(name):
"""Excel-style column name to number, e.g., A = 1, Z = 26, AA = 27, AAA = 703."""
n = 0
for c in name:
n = n * 26 + 1 + ord(c) - ord('A')
return n | ddd8b803cef027f7c04953247ce63a535662ae60 | 628,645 |
def set_val_or_default(in_dict, key, val):
"""Helper functions to either get and item from or add an item to a dictionary and return that item
Parameters
----------
in_dict : `dict`
input dictionary
key : `str`
key to search for
val : `dict` or `function`
item to add to ... | 4368d5a34a26f67c220adebe634f59ad5467a2c6 | 628,646 |
from warnings import warn
def read_and_check(file_handle, byte_sizes):
"""
Return data read from input file stream in segments of specified byte sizes
and check for complete reads.
Inputs:
file_handle - Handle to file to read from.
byte_sizes - List of byte sizes to read.
Outputs:
... | d585859d305b33c49abea94725e9bbaa65e67966 | 628,647 |
import textwrap
def mutations( seqID='A' ): # pragma: no cover
"""RosettaScript to execute a
`RESFILE <https://www.rosettacommons.org/docs/latest/rosetta_basics/file_types/resfiles>`_.
:param str seqID: |seqID_param|
:return: :class:`str`
.. seealso::
:func:`.DesignFrame.apply_resfile`... | 5b7a7feecd435abaf36e101eda9ce21e5efc52ca | 628,648 |
from typing import Dict
from typing import List
import re
def get_typos_in_string(s: str, known_typos: Dict[str, str]) -> List:
"""
>>> get_typos_in_string('foo buzz', {'foo': 'bar', 'bazz': 'buzz'})
['foo']
>>> get_typos_in_string('foo bazz', {'foo': 'bar', 'bazz': 'buzz'})
['bazz', 'foo']
"... | fbd96e8897fbcf403a9da8db04f5a2bf0916270b | 628,650 |
def valid_chunk_size(chunk_size):
# type: (int) -> bool
"""Checks whether chunk size is multiple of 256 KiB.
Args:
chunk_size (int): Input chunk_size to be validated.
Returns:
bool: True if chunk_size is multiple of 256 KiB, False otherwise.
"""
return not bool(chunk_size % 262... | 0ae4fe953186f970b80e7e28baeeb23b2a8e903a | 628,651 |
def calculate_range(histogram, words, index):
"""Return the difference between the high and low ends of a range for a
value in the modified histogram.
Param: histogram(dict): modified so each value is a tuple
words(list): a list of the keys in histogram
index(int): a way fo... | 456078de0bf526cb7620ab38f4a8fa7ecc0db0ec | 628,655 |
from typing import Any
import gzip
import pickle
def load_object(path: str, compressed: bool = True) -> Any:
"""Reads a python object into memory that's been saved to disk.
Args:
path: the file path of the object to load
compressed: flag to specify whether the file was compressed prior to sav... | cd3324e484b58d275ebef95f083c8aa8c576e78a | 628,656 |
from datetime import datetime
def datetime_to_epoch(datetime: datetime, ms: bool = True) -> int:
"""
Convert a python datetime to number of (milli-) seconds since epoch.
"""
if ms:
return int(datetime.timestamp() * 1000)
return int(datetime.timestamp()) | 73c5e41a8d24e0542c87db5910e9a6354e1f2f5c | 628,657 |
def colorize(text, color):
"""
Wrap `text` with ANSI `color` code. See
https://stackoverflow.com/questions/4842424/list-of-ansi-color-escape-sequences
"""
code = f"\033[{color}m"
restore = "\033[0m"
return "".join([code, text, restore]) | e1995a7973197c4a31ad655db92a88e47917e89a | 628,667 |
def number_of_edges(G):
"""Return the size of a graph = number of edges. """
return G.number_of_edges() | 3c46add55f9b8cef27d20183c80681a4e0cb6a9b | 628,670 |
from typing import List
def ligands_from_conformers(conformers: List[str]) -> List[str]:
"""
Extract the ligands from a list of conformers.
"""
return [conformer.split('_')[0] for conformer in conformers] | f218a27b3a91d7852c6896dc8f15e08ff4885503 | 628,672 |
def bit_on(num, bit):
"""Return the value of a number's bit position.
>>> [bit_on(42, i) for i in range(clog2(42))]
[0, 1, 0, 1, 0, 1]
"""
return (num >> bit) & 1 | ecfa4486cb076207bf4b9e7ec7d97f0c58c1eb2d | 628,676 |
def load_filepaths(filename):
"""Read in a list of file paths.
Args:
filename: A text file containing a list of file paths. Assume that
each line has one file path.
Returns:
filepaths: A list of strings where each is a file path.
"""
with open(filename) as f:
filepa... | 2475a28b2afaf8380502270d79bc2f756dd5a25e | 628,679 |
import requests
def _http_get(url, session=None, stream=True, **kwargs):
"""Make a GET request with the URL.
Any errors from the HTTP request (non 200 codes) will raise an HTTPError.
:param url: The URL to GET.
:type url: str
:param session: Optional :class:`~requests.Session` object to use to m... | 5ac2be88284ab53a465d33f8900e4590cb0c190a | 628,680 |
def SignToBool(inp):
"""Converts signed bits into boolean bits
-1 -> 0
1 -> 1"""
return (inp + 1) / 2 | e50c669670df2538a6bb98ebcafa25043e328538 | 628,683 |
import re
def trim_after(string, regex, include_pattern=False):
"""Trim a string after the first match of regex.
If fail to match any pattern, the original string is returned
The matched pattern is trimed as well.
Args:
string (str): the string to trim
regex (regex): the regex to ma... | e4c9dfdb2f688c984a0bb0c34ca389fdd26a5c9f | 628,684 |
def crowdsale(uncapped_flatprice, uncapped_flatprice_finalizer, team_multisig):
"""Set up a crowdsale with customer id require policy."""
uncapped_flatprice.transact({"from": team_multisig}).setRequireCustomerId(True)
return uncapped_flatprice | 77c430cacb13f7b0e1b132952760e1fd7c4980b2 | 628,686 |
def _return_arg(__arg: ..., /) -> ...:
"""Return the singular positional argument unchanged."""
return __arg | b4f8b9b8a7b7d344f15c99fdeaf71f938dca5892 | 628,689 |
def display_iscsi_device(iqn, sess):
"""
Print the data for iscsi device identified by iqn.
Parameters
----------
iqn: str
The iSCSI qualified name.
sess: OCISession
An oci sdk session.
Returns
-------
bool: True on success, False otherwise.
"""
this_compa... | efc77ddd813fb0ece6fe5cae24b4719dcff948d2 | 628,691 |
def get_fitness(traceIsFit, traceFitnessValue):
"""
Gets a dictionary expressing fitness in a synthetic way from the list of boolean values
saying if a trace in the log is fit, and the float values of fitness associated to each trace
Parameters
------------
traceIsFit
Boolean value that... | 4a160126c7b0574919b9d98e7eae0bf5cf705df5 | 628,692 |
import re
def make_key(word: str, sense: str) -> str:
"""Create a key from a word and sense, e.g. "usage_example|NOUN".
word (unicode): The word.
sense (unicode): The sense.
RETURNS (unicode): The key.
"""
text = re.sub(r"\s", "_", word)
return text + "|" + sense | a417c00c8a11961d4e33b9df59665cc50b02efbe | 628,696 |
def discard_unknown_labels(labels):
"""Function for discarding medial wall (unknown) labels from a list
of labels.
Input arguments:
================
labels : list
List of labels. Each label must be an instance of the MNE-Python
Label class.
Output arguments:
===============... | 55dfd39591c4979979eb2f06515b57c6236ca407 | 628,700 |
def org_default_payload(login: str, uid: int):
"""Provide the basic structure for an organization payload."""
return {
'action': 'member_added',
'membership': {
'url': '',
'state': 'pending',
'role': 'member',
'organization_url': '',
'u... | af542f5a9da78ff3b08e80cd49e84f828e9a8cbb | 628,702 |
def generate_brightness_string_from_brightness_barcode(brightness_barcode, num_interval=15):
"""
Helper function
Generate the string where each character represents the brightness interval of the brightness in the input
brightness barcode.
:param brightness_barcode: Input 1 dimensional brightness b... | 07c059778409ea349df2a5f2ad5f26754f1a3f31 | 628,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.