content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import Any
import pickle
def load_pickle(fpath: str) -> Any:
"""Load an arbitrary object from a pickled format. Note that no safety checking is performed.
Args:
fpath (str): Path to the pickled object to load.
Returns:
Any: The object as hydrated from disk.
"""
with o... | 9e8430d9d37ef62a9e146832a53dedd2c80daed0 | 116,324 |
def _test_exception(exc, func, *data):
"""Validate that func(data) raises exc"""
try:
func(*data)
except exc:
return True
except:
pass
return False | 2ee6926ef9233a78dea7731fab4d05027e4dbdf6 | 259,509 |
def split_num(num, n):
"""
Divide num into m=min(n, num) elements x_1, ...., x_n, where x_1, ..., x_n >= 1 and max_{i,j} |x_i - x_j| <= 1
"""
n = min(num, n)
min_steps = num // n
splits = []
for i in range(n):
if i < num - min_steps * n:
splits.append(min_steps + 1)
... | bbe69833b829dea8ca62f1b7646ad53eb8cebc80 | 593,252 |
def fliplr_joints(joints_3d, joints_3d_visible, img_width, flip_pairs):
"""Flip human joints horizontally.
Note:
num_keypoints: K
Args:
joints_3d (np.ndarray([K, 3])): Coordinates of keypoints.
joints_3d_visible (np.ndarray([K, 1])): Visibility of keypoints.
img_width (int)... | c9c4586fd8aa26bd5cd88aaf6f052192b8ef43a9 | 196,712 |
import math
def vector_from_wind_dir(wind_dir_degree, wind_speed=1.0):
"""
Return vector given a wind direction and wind speed
Wind dir = 0.0 -> [0.0,-1.0,0.0]
Wind dir = 90.0 -> [-1.0,0.0,0.0]
Wind dir - Meteorological wind direction
(direction from which wind is blowing)
u -> Zone Velo... | 2d39d6ba5ee80c215c4cd4041a97f435a47289c9 | 518,137 |
def swapaxes(a, axis1, axis2):
"""
Interchange two axes of an array.
Parameters
----------
a : array_like
Input array.
axis1 : int
First axis.
axis2 : int
Second axis.
Returns
-------
a_swapped : ndarray
If `a` is an ndarray, then a view of `a` ... | bbf8e4688f0d2adac93213efd8a55476a0aeb8e3 | 239,332 |
def parse_parameters(val_type, val):
"""
Helper function to convert a Vasprun parameter into the proper type.
Boolean, int and float types are converted.
Args:
val_type: Value type parsed from vasprun.xml.
val: Actual string value parsed for vasprun.xml.
"""
if val_type == "logi... | 829432c5f70c2de3ccb9c9de51e49ad3a5f1261f | 531,954 |
import re
def convert_remote_git_to_https(source):
"""
Accepts a source git URL in ssh or https format and return it in a normalized
https format:
- https protocol
- no trailing /
:param source: Git remote
:return: Normalized https git URL
"""
url = re.sub(
pattern=... | 0086b69a3e25992247580b2b7b7004632dde22d2 | 133,347 |
from pathlib import Path
def root_module_path() -> Path:
"""Return absolute root module path.
Returns
-------
:class:`pathlib.Path`
Absolute root module path.
"""
return Path(__file__).resolve().parents[1] | 48986dfde811819ae037318e9f4e2b21300fda25 | 82,386 |
def GetLegacySitelinksForCampaign(campaign_extension_service, campaign_id):
"""Get legacy sitelinks for a campaign.
Args:
campaign_extension_service: The CampaignAdExtensionServiceInterface
instance.
campaign_id: ID of the campaign for which legacy sitelinks are retrieved.
... | eb64480ac29e1e9b6585bb39fc6095a2b7bd5802 | 366,713 |
def mean(s):
"""Returns the arithmetic mean of a sequence of numbers s.
>>> mean([-1, 3])
1.0
>>> mean([0, -3, 2, -1])
-0.5
"""
# BEGIN Question 1
assert len(s) > 0
return sum(s) / len(s)
# END Question 1 | 4ef993046891d480bbb40f1eef49dfa54440f774 | 242,096 |
import six
def validate_hatch(s):
"""
Validate a hatch pattern.
A hatch pattern string can have any sequence of the following
characters: ``\\ / | - + * . x o O``.
"""
if not isinstance(s, six.text_type):
raise ValueError("Hatch pattern must be a string")
unique_chars = set(s)
... | 4ddf056dab2681759a462005effc4ae5488a4461 | 707,950 |
def get_d_pct(a, b):
"""Percentage difference between two values."""
d = float(abs(a - b))
avg = float((a + b) / 2)
return round(d / avg * 100) | ab181dbd36bdb28ed7fd8643981e41d00c1902d6 | 296,287 |
def get_thumbnail_size(image_size, thumbnail_height):
"""
Computes the size of a thumbnail
:param image_size: original image size
:param thumbnail_height: thumbnail height
:return: thumbnail size tuple
"""
width = round((float(thumbnail_height) / image_size[1]) * image_size[0])
return wi... | 6bd516279677c247adbe673ca47f7bc8ee74e651 | 399,381 |
def list_materials(client, file_=None, material=None):
"""List materials on a part.
Args:
client (obj):
creopyson Client.
`file_` (str, optional):
File name. Defaults is currently active model.
material (str, optional):
Material name pattern.
... | bcd70f4003f4b7499bf939f1d3f9810558f6c719 | 634,104 |
def bool2str(x):
"""Return Fortran bool string for bool input."""
return '.true.' if x else '.false.' | a2c5e500e7321cfff7bc3ff7a6d87aea28362a99 | 370,582 |
from typing import Tuple
import math
def to_proper(numerator: int, denominator: int) -> Tuple[int, int]:
"""Converts `numerator` and `denominator` to their simplest ratio.
Examples:
>>> to_proper(7, 28)
(1, 4)
>>> to_proper(-36, 54)
(-2, 3)
>>> to_proper(3, 4)
... | edd0c3d670cef0ba9c2eb17b4e0920fb2e614d07 | 240,863 |
def optStrajAdvHelp(strajDists, strajCov, r, c3):
""" Computes subtrajectory of a trajectory with maximum coverage cost ratio
Args:
strajDists: list having subtraj-distance pairs of a trajectory.
strajCov: dict storing points of subtrajs.
r (float): guess coverage-cost ra... | 6083bfd008418540dc1d14de0883b9e96cc371c2 | 180,260 |
def analysis_nindex_usages(analysis):
"""
Returns a dictionary of namespace usages by name.
'nindex' stands for 'namespace index'.
"""
return analysis.get("nindex_usages", {}) | 55defbe685e793df3a8377f6c030a653626b75db | 410,601 |
def time_to_num(time):
"""
time: a string representing a time, with hour and minute separated by a colon (:)
Returns a number
e.g. time_to_num(9:00) -> 9
time_to_num(21:00) -> 21
time_to_num(12:30) -> 12.5
"""
time_comps = time.split(":")
if int(time_comps[1]) == 0:
... | 77512320480404d5ea0d3c9490edc41ad3ad114b | 405,601 |
from typing import Any
def isclass(obj: Any) -> bool:
"""Determine if an object is a `class` object
>>> isclass(type)
True
>>> isclass(object)
True
>>> isclass({})
False
"""
return issubclass(type(obj), type) | 69536bc72a03a4a15900279b00e58a2a7e306a34 | 384,243 |
def needs_binary_relocation(m_type, m_subtype):
"""
Check whether the given filetype is a binary that may need relocation.
"""
if m_type == 'application':
if (m_subtype == 'x-executable' or m_subtype == 'x-sharedlib' or
m_subtype == 'x-mach-binary'):
return True
r... | 3abf8ea69201b7fdaa4ab6a104f131ca8add4ea8 | 500,216 |
import re
def _is_edl_hostname(hostname: str) -> bool:
"""
Determine if a hostname matches an EDL hostname.
Args:
hostname: A fully-qualified domain name (FQDN).
Returns:
True if the hostname is an EDL hostname, else False.
"""
edl_hostname_pattern = r'.*urs\.earthdata\.nasa\... | 8251cc40964993fe81587774757da7fa773ba02c | 427,593 |
def split_by_3(x):
"""
Method to separate bits of a 32-bit integer
by 3 positions apart, using the magic bits
https://www.forceflow.be/2013/10/07/morton-encodingdecoding-through-bit-interleaving-implementations/
:param x: 32-bit integer
:return: x with bits separated
"""
# we only look ... | c00e614983df0851172087034267417c7928775c | 216,893 |
def rtiOutputFixture(rtiConnectorFixture):
"""
This `pytest fixture <https://pytest.org/latest/fixture.html>`_
creates a session-scoped :class:`rticonnextdds_connector.Output` object
which is returned everytime this fixture method is referred.
The initialized Output object is cleaned up at the end
of a test... | 5cc9f6447a0312021cb5e949c09924aefcda49ef | 559,063 |
from datetime import datetime
def now() -> str:
"""String ISO Timestamp of current date"""
return datetime.now().strftime("%Y-%m-%d") | cd506197a440a0ad7217ec71903d7c32c1f414fd | 321,361 |
def convert(number):
"""
Converts a number into string based on rain drops methodj
Pling = if 3 is a factor
Plang = if 5 is a factor
Plong = if 7 is a factor
the number itself if none of the above are factors.
"""
raindrops = ''
r_3 = divmod(number, 3)[1]
r_5 = divmod(number, 5)[... | d84685437f623ddbb5b776a5dd0bb92c56fe59d3 | 556,613 |
def easy_or(b1, b2):
"""Takes two booleans and returns their OR"""
return b1 or b2 | 0ebdc18c4431a6a3c5e60f5f373b258e18980f3f | 311,232 |
import io
import json
def load_json_file(json_file):
"""
Load json file
:param json_file: json file path
:return: file content
"""
with io.open(json_file, encoding='utf-8') as f:
json_content = json.load(f)
return json_content | d5eafad4fa5d636e31240a3503699f490cbea5fc | 611,565 |
def parse(entrypoint):
"""
Parse an entrypoint string
Args:
entrypoint (str): The entrypoint string to parse.
Returns:
name (str): The name of the entrypoint
package (str): The package path to access the entrypoint function
func (str): The name of the function
"""
... | adb22aa44b559dbc833772266b8c19baee86253a | 531,659 |
def around(number):
"""
Truncate a float to the third decimal
"""
if number is not None:
return int(number * 1000) / 1000.
else:
return None | 9f011cf7f7a0b0886aa4bd3a98674e9bb1326200 | 598,778 |
from typing import Callable
from typing import Optional
def inline_try(func: Callable) -> Optional[Exception]:
"""
Try to execute an inline function without throwing an error. Useful when the Exception thrown is trivial.
:param func: A function to call.
:return: None if no exception is thrown or the E... | 4e5205f822c4f3243efbdf877a1b652de22b2c8e | 394,064 |
def remove_duplicate_info(data):
"""Convert duplicates information that can be found in other columns, into 'No'.
Args:
data ([pd.DataFrame]): Dataframe to be wrangled.
"""
# replace 'No phone service'
data["MultipleLines"] = data["MultipleLines"].replace({"No phone service": "No"})
#... | ad4f72ebc3849e0553a65ffb8975052d4eea6828 | 466,322 |
def Sort_Points(x_values, y_values, error):
"""
Combine three arrays and sorts by ascending values of the first.
Args:
x_values (1darray):
Array of x-values. This array is the one which sorting will be based.
Each index of this array is related to the same index value of the... | 190c6303f5f9c91a7654e65f66795aeae32ffacb | 464,714 |
def format_percent(d, t):
"""
Format a value as a percent of a total.
"""
return '{:.1%}'.format(float(d) / t) | 9c3e871191e2757436c466c2560810b80a7880dc | 618,452 |
import importlib
def _json_convert_from_dict(obj_dict: dict) -> object:
"""
Takes in a dict and returns an object associated with the dict.
The function uses the "__module__" and "__class__" metadata in the dictionary to know which object to create.
Parameters
----------
obj_dict : dict
... | ddf368f14aaf8aca3f4a534c55d870df1393f3b6 | 541,525 |
import math
def is_prime(k: int) -> bool:
"""
Determine if a number is prime
>>> is_prime(10)
False
>>> is_prime(11)
True
"""
if k < 2 or k % 2 == 0:
return False
elif k == 2:
return True
else:
for x in range(3, int(math.sqrt(k) + 1), 2):
if ... | 3d3ee9a33ee4bf8ad85d9bb9f7afa32032f7218b | 372,705 |
def parse_var(s):
"""Returns (key, value) tuple from string with equals sign with the portion before the first equals sign as the key
and the rest as the value.
Args:
s: string to parse
Returns: Tuple of key and value
"""
items = s.split("=")
key = items[0].strip() # we remove bla... | 8e6d63fde980435e84bb1d316ced95fc7ea383bb | 453,273 |
def compare_and_get_name(a, b):
"""
If both a & b have name attribute, and they are
same return the common name.
Else, return either one of the name of a or b,
whichever is present.
Parameters
----------
a : object
b : object
Returns
-------
name : str or None
"""
... | d3c2da2a1554d83d9a2b0640a050d209d7919295 | 186,396 |
def forcedir(path):
"""Ensure the path ends with a trailing /
:param path: An FS path
>>> forcedir("foo/bar")
'foo/bar/'
>>> forcedir("foo/bar/")
'foo/bar/'
"""
if not path.endswith('/'):
return path + '/'
return path | 968db047d604eb63cdbd0955a7da20479c40fc6a | 592,183 |
def edge_count(adjList):
"""Compute number of edges in a graph from its adjacency list"""
edges = {}
for id, neigh in enumerate(adjList):
for n in neigh:
edges[max(n, id), min(n, id)] = id
return len(edges) | 760b12e3074d6447d1173e4ac61ef35e91af3d21 | 486,426 |
def is_function(var):
"""
Test if variable is function (has a __call__ attribute)
:return: True if var is function, False otherwise.
:rtype: bol
"""
return hasattr(var, '__call__') | 1cd3d4bb70b1568a60c4f51c04652df12a967292 | 58,362 |
def colon_based_id_to_vep_id(colon_id):
"""Converts a colon-based identifier to VEP compatible one. Example: '15:7237571:C:T' → '15 7237571 . C T'"""
id_fields = colon_id.split(':')
assert len(id_fields) == 4, 'Invalid colon-based identifier supplied (should contain exactly 4 fields)'
return '{} {} . {}... | 208b9690f77e015263eb207fce6d2db129a2fae5 | 127,171 |
def search_component(key, CACHET_IDS):
""" Searches the list of componets in cachet for the
component returned from alertmanager. If found it returns the component,
if not 9999 is returned.
"""
return CACHET_IDS.get(key, 9999) | 69eaa484cb4715fd891b43a00c027f3ea0deb3ef | 224,643 |
def transport_degree_factor(
temperature,
deadband_lower=15,
deadband_upper=20,
lower_degree_factor=0.5,
upper_degree_factor=1.6):
"""
Work out how much energy demand in vehicles increases due to heating and cooling.
There is a deadband where there is no increase.
Degree factors are ... | ea5d5128fa985ea566aefe8b0f7b5875878a9838 | 600,331 |
def quick_sort(arr):
"""Sort array of numbers with quicksort."""
if len(arr) == 1:
return arr
if len(arr) > 1:
pivot = arr[0]
left = 1
right = len(arr) - 1
while left <= right:
if arr[left] > pivot and arr[right] < pivot:
arr[left], arr[ri... | 9f40258588967247379d50532dd62ec0588365b1 | 18,753 |
def get_text(doc, tag_id, value=False):
"""
beautifulsoup get_text() wrapper
优雅地处理 doc.find() 为 None的情况
:param doc: beautifulsoup doc
:param tag_id: tag id
:param value: 是否取tag中value属性的值
:return:
"""
res = doc.find(id=tag_id)
if res is not None:
if value:
if ... | 774233ee3b2b53861659f5a22a00f864d9b2efdc | 521,356 |
def divide_lists(lst_numer, lst_denom):
"""
Divides each element of the nested list 'lst_numer' by 'lst_denom'.
The division is done by taking each element of 'lst_numer' and for each
index of that element, dividing the item at that index by the item at the
same index of 'lst_denom'. See example be... | d040c159ca79eedfe74b5067affd67d42d928879 | 155,318 |
def calculate_enrichment(coverage_values):
"""Calculate TSS enrichment value for a dataset
Parameters
----------
coverage_values
iterable of tuples (tss_center_depth, flank_depth) per TSS
Returns
-------
float
the TSS enrichment value
"""
tss_depth, flank_depth... | 673ee0208dca03e10f92463d5d53c1be73341f0d | 630,244 |
def get_variables_used(string, variable_dict):
"""Returns what variables are used in the given string as a list."""
used_variables = []
for key in variable_dict:
temp_string = string.replace(key, "")
if temp_string != string:
used_variables.append(key)
string = temp_s... | 0b242da05640617f8efca9521bbfe61ce17182dc | 110,012 |
from typing import List
from typing import Tuple
def get_range_directives_gatecharacterization(
fit_range_update_directives: List[str],
current_valid_ranges: List[Tuple[float, float]],
safety_voltage_ranges: List[Tuple[float, float]],
dV_stop: float = 0.1,
) -> Tuple[List[str], List[str]]:
"""Dete... | c7b91804140c6b36f1ffae22e633b6512e05957f | 156,589 |
def _get_photos_by_attribute(photos, attribute, values, ignore_case):
"""Search for photos based on values being in PhotoInfo.attribute
Args:
photos: a list of PhotoInfo objects
attribute: str, name of PhotoInfo attribute to search (e.g. keywords, persons, etc)
values: list of values to... | 84ac207ff9b5915f0404cf0701d5985e7df2af9b | 506,428 |
def embedded(classes):
"""get embedded property (e-*) names
"""
return [c.partition("-")[2] for c in classes if c.startswith("e-")] | 862c6bd4f9ccbb05330950fbf284760c962da9de | 534,208 |
from typing import Iterator
def second(itr: Iterator[float]) -> float:
"""Returns the second item in an iterator."""
next(itr)
return next(itr) | 74e85436ed9b763f262c94e3898455bd24d75028 | 686,837 |
def palette_name(name, length):
"""Create a palette name like CubeYF_8"""
return '{0}_{1}'.format(name, length) | 1c06b9e6169558c479e3e350c5f2151519cf3ab0 | 266,145 |
def item(self, drive=None, id_=None, path=None):
"""Gets an item given the specified (optional) drive,
(optional) id_, and (optional) path
Args:
drive (str): The drive that you want to use
id_ (str): The id_ of the item to request
path (str): The path of the item to request
Ret... | 55f82f55a0ead8557ee9a5b53884259a906d044e | 151,976 |
def minutes_readable(minutes):
"""
convert the duration in minutes to a more readable form
Args:
minutes (float | int): duration in minutes
Returns:
str: duration as a string
"""
if minutes <= 60:
return '{:0.0f} min'.format(minutes)
elif 60 < minutes < 60 * 24:
... | 9115070cb17786cbb866d7849ad2b261ad6652e6 | 571,031 |
def writeConfig(xyTuple):
"""Creates a config file (config.py) and writes 4 values into it
Arguments:
xyTuple: a tuple of structure (xMin, xMax, yMin, yMax)
"""
outfile = open("config.py","w")
outfile.write("X_MIN="+str(xyTuple[0])+"\n")
outfile.write("X_MAX="+str(xyTuple[1])+"\n")
outfile.write("Y_MIN="+s... | 1c792874e0e07575f37843e133d62b094c33c35f | 405,710 |
def GetArgTypeStr(_n):
"""Function to return the string representation of the PyTango.ArgType value from
its integer code."""
_list = ['Void', 'Boolean', 'Short', 'Long', 'Float', 'Double', 'UShort', 'ULong', 'String', \
'CharArray', 'ShortArray', 'LongArray', 'FloatArray', 'DoubleArray', 'USho... | 211c8e7013ec92c5758f67b87ff21c987531a1b7 | 130,173 |
def _gen_gce_as_policy(as_params):
"""
Take Autoscaler params and generate GCE-compatible policy.
:param as_params: Dictionary in Ansible-playbook format
containing policy arguments.
:type as_params: ``dict``
:return: GCE-compatible policy dictionary
:rtype: ``dict``
... | 0fba5afeae0967ea37a2077abdcc2d32341795cb | 462,906 |
def eliminate_suffix(v, w):
"""
Removes suffix w from the input word v
If v = uw (u=prefix, w=suffix),
u = v w-1
Parameters:
-----------------------------------
v: str
A (sub)word
w: str
The suffix to remove
Returns:
-----------------------------------
u: st... | 5ff4cbfb6e82e20dfe05ef26f4a3503f5d05ab3c | 169,734 |
from typing import Tuple
import re
def check_tvm_version(curr: str, min_req: str) -> bool:
"""Check if the current TVM version satisfies the minimum requirement.
Parameters
----------
curr: str
The current version.
min_req: str
The minimum requirement version.
Returns
--... | f99d7da7212a5c96b186681ceb4b03dc47f2cb26 | 102,432 |
def SLICE(array, n, position=None):
"""
Returns a subset of an array.
See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/
for more details
:param array: Any valid expression as long as it resolves to an array.
:param n: Any valid expression as long as it resolves to an inte... | 98feb51282923b1d4d637695579f2fe3f9654713 | 506,302 |
def decode(value):
"""
Decode UTF8.
:param bytes value: an encoded content
:return: the decoded content
:rtype: str
"""
return value.decode('utf-8') | a276f61138d02939cfc78fe808892b7d8ed3f87e | 583,091 |
def get_action_space(environment_spec):
"""Get action space associated with environment spec.
Args:
environment_spec: EnvironmentSpec object
Returns:
OpenAi Gym action space
"""
return environment_spec.env_lambda().action_space | fa2608782ca69e62cf68c055213f15e8e9da0cfd | 371,120 |
from typing import Tuple
def _calculate_division(
dividend: int,
divisor: int,
max_decimal_places: int = int(1e6)
) -> Tuple[str, str, str]:
"""For given integer `dividend` and `divisor`, calculate the division `dividend / divisor`.
The decimal fraction part is made up of a fixed start... | 6bffaf9291af22709d77f5658622a4c987df21f9 | 238,430 |
def addKwdArgsToSig(sigStr, kwArgsDict):
""" Alter the passed function signature string to add the given kewords """
retval = sigStr
if len(kwArgsDict) > 0:
retval = retval.strip(' ,)') # open up the r.h.s. for more args
for k in kwArgsDict:
if retval[-1] != '(': retval += ", "
... | e859c27c14caaf755aeaaa963d10eb75e99a89f6 | 421,073 |
def x12_270_oneline_message() -> str:
"""A x12 270 transaction in one line without carriage returns/new line characters"""
return '{"x12": "ISA*00* *00* *ZZ*890069730 *ZZ*154663145 *200929*1705*|*00501*000000001*0*T*:~GS*HS*890069730*154663145*20200929*1705*0001*X*005010X279A1~ST*270... | dbaedad04a7d7c888c1c235872f3285f4f830dfd | 405,373 |
def inline(s, fmt):
"""Wrap string with inline escape"""
return "`\u200B{}\u200B`".format(fmt.format(s)) | 3f07a4f55e60c763a10956c9ac52314b6958eca8 | 699,557 |
def nombre_aretes(matrice):
"""Renvoie le nombre d'arêtes dans le graphe"""
nb_aretes = 0
for i in range(len(matrice)):
for j in range(len(matrice)):
if matrice[i][j] == 1:
nb_aretes += 1
return nb_aretes // 2 | 13262de15fd2d5a8018a63e8dabb529169d5c35a | 118,156 |
from typing import Callable
def is_such_at(func: Callable[[str], bool], index: int, text: str) -> bool:
"""
Whether a character at a string is of a certain class.
:param func: a function
:param index: a number indicating which character in the text
:param text: a string
:return: whether it is true
"""
return ... | 41eb6b3fd9076ddfc1bb9a0da515aae1b3d1a905 | 137,890 |
def avg_ci_data(data, axis=0):
"""Average the data along the given dimension, and calculate the 95
percent confidence interval. Return the avg, ci arrays."""
data_avg = data.mean(axis=axis)
data_std = data.std(axis=axis, ddof=1)
data_ci = data_std / data.shape[axis]**0.5 * 1.96
return data_avg, ... | 3ebc541d14e7b300f5acde0ff1741e0675a0a103 | 398,426 |
def DeveloperAPI(obj):
"""Annotation for documenting developer APIs.
Developer APIs are lower-level methods explicitly exposed to advanced Ray
users and library developers. Their interfaces may change across minor
Ray releases.
Examples:
>>> @DeveloperAPI
>>> def func(x):
>... | e78bc7cecb46e607dec199a300962f8899ed1f3b | 378,608 |
def capitalize_word(word):
"""
Capitalize the first letter of the word.
:param word: a string input.
:return: the word in title form.
"""
return word.title() | 0f5b9dec962717bac2c867551b093f8204a61737 | 558,683 |
def _get_images(container_group):
"""Get all images of a container group. """
containers = container_group.get('containers')
if containers is not None and containers:
images = set([])
for container in containers:
images.add(container['image'])
return ','.join(images)
... | c7f3fb3ad26beaf543067b0e25b96888bc0412b7 | 142,376 |
import hashlib
def genSha256(file_content):
"""
Generates SHA256 hash of a specific files contents
:parameters:
file_content (str) : all the contents the file as a string
:returns:
SHA256 hash of files content
"""
# generating sha256 hash and returning it
return hashlib.sha256(file_content).hexdig... | ad5e94299f5bf62425b906fd6fef336dc6c7124d | 386,457 |
def print_verilog_literal(size, value):
"""Print a verilog literal with expicilt size"""
if(value >= 0):
return "%s'd%s" % (size, value)
else:
return "-%s'd%s" % (size, abs(value)) | dcf5cd21a05a19d786e27a9dcd5b29743eeb8dc8 | 125,245 |
def split_path(path, all_paths):
"""Split path into parent and current folder."""
idx = path.rfind('/', 0, -1)
if idx == -1:
return '', path
parent, label = path[0:idx + 1], path[idx+1:-1]
if parent not in all_paths:
return '', path
return parent, label | aff444665545748343108cc9cd47ca916d47e3e7 | 495,868 |
from typing import List
def sequence (lower:int, upper:int) -> List[int]:
"""
generate an integer sequence between two numbers.
"""
seq = [ ]
current = lower
while current <= upper:
seq.append(current)
current += 1
return seq | 6a54c3b1234f108abd0a95fbbf0ab7fcb3d3f7f4 | 661,982 |
def group_bases(dna_seq, step=2):
"""
Group the DNA base from a sequence into groups by length "step"
:return: a list of groups
"""
bases_groups = []
for i in range(0, len(dna_seq), step):
bases_groups.append(dna_seq[i:i + step])
return bases_groups | 579f440c7660cd5a8f1347e74848f4710fec745e | 114,292 |
def non_related_filter(questions_df, non_related_ids):
"""
Splits a questions dataframe between related and non-related discussions,
based on an Ids list of non-related discussions.
:param questions_df:
> A pandas dataframe of stackoverflow questions containing posts Ids;
:param non_... | b7e64287b2bdb6a8999bcd8e7efd8e2787b991dd | 701,954 |
import functools
def _deepgetattr(obj, name, default=None):
"""Recurses through an attribute chain to get the ultimate value."""
try:
return functools.reduce(getattr, name.split('.'), obj)
except AttributeError:
return default | b03887865b9594cb806bc6bc72c54eba010dcae8 | 71,843 |
def _prop_var(p, n):
"""
Calculate variance of proportion.
var(X/n) = 1/(n^2)var(X) = (npq)/(n^2) = pq/n
"""
return p * (1 - p) / n | f93594904db150c2102fa32cb2d6f9ccfe372e50 | 493,179 |
def square(number):
"""
this function returns a square of a number
"""
result = number ** 2
return result | 10a3dc80d5ab0f709bd393c8956bd67be3ec8746 | 259,861 |
def append(df, entry):
"""
This function adds a new entry in the DataFrame
if the entry timestamp does not exists
Parameters
----------
df: pandas.DataFrame
Fataframe to record
entry: pandas.DataFrame
entry dataframe
Returns
-------
A pandas with the updat... | bdfcf7f7741eec8fccc0680f82e3d516e297c1ed | 83,823 |
from pathlib import Path
def get_readable_header(first_file, second_file):
"""Get the readable names from input files.
We want our eventual final output to include headers so that people
can easily see what versions we're diffing between. This grabs the
files' relevant parts -- which here is /folder/... | 216cc4937e9b0e5749b5fd7bcdcbeeb8d108a914 | 432,823 |
import threading
import functools
def _memoize(f):
"""Memoizing decorator for f, which must have exactly 1 hashable
argument."""
nothing = object() # Unique "no value" sentinel object.
cache = {}
# Use a reentrant lock so that if f references the resulting wrapper we die
# with recursion dept... | a6f89477c8e2c5ac886f0ceb573e7edc9659f8fa | 363,458 |
import ctypes
def c_str(string):
"""
Create ctypes char* from a python string
Parameters:
---------
string : string type
python string
Returns:
---------
str: c_char_p
A char pointer that can be passed to C API
"""
return ctypes.c_char_p(string.encode('utf... | 51ecf57b20aa40e79364dad7cd574948d69248b4 | 553,047 |
import re
def strip_appendix(lines):
"""Remove all code in the appendix."""
p = re.compile(r"#\s*#*\s*Appendix")
for i in range(len(lines) - 1, 0, -1):
if p.match(lines[i], re.IGNORECASE):
return lines[0:i]
raise ValueError("Could not find Appendix") | 4e03d0a2063eb999cfb17679084bc8ec92ac1a13 | 431,243 |
import itertools
def flatten(list_of_iters):
"""flatten
Flattens a list of iterables into a single flat list.
Parameters
----------
list_of_iters : :obj:`iter` of :obj:`iter`
A list of iterables.
Returns
-------
:obj:`generator`
Generates flattened list.
... | cb9a290ecb26fa228872ae2a08889c1f03688e38 | 540,482 |
def issubdict(d1, d2):
"""All keys in `d1` are in `d2`, and corresponding values are equal."""
return all((k in d2 and d1[k] == d2[k]) for k in d1) | 3d61e0ac47cdf3040e9838be64eeb338d16612b9 | 530,272 |
from typing import Union
import ast
from typing import Container
from typing import Tuple
from typing import Set
import itertools
def get_signature_params(
node: Union[ast.FunctionDef, ast.AsyncFunctionDef],
ignore: Container[str] = ("self", "cls"),
) -> Tuple[Set[str], bool]:
"""Get parameters in a funct... | 6c9dc6071356ef02e29535c086e4722b67dd61b0 | 268,278 |
def get_cluster_range(hsp_list):
"""Take a list of SearchIO HSP objects an return a range from the furthest
5' hsp end to the furthest 3' hsp end.
"""
start = min([x.hit_range[0] for x in hsp_list])
end = max([x.hit_range[1] for x in hsp_list])
assert start < end
return [start, end] | 8aeaa29023433c7bf27bca1137cacc9eb712da7c | 356,685 |
def renumber(num_list,
start=1, step=1, padding=4,
preserve=True, autopad=True):
"""Renumber objects.
Return a new list of integers, plus a padding value, as a tuple.
Arguments:
num_list (list) -- input list of integers
Keyword arguments:
start (int) -- start number for renumbering
step (int) -- step / ... | 6c026cf881a7939e7447ef0722a9e37a86cc6a9f | 493,037 |
def moving(boxes, threshold=5e-25):
"""Checks to see if boxes have kinetic energy ie moving"""
for b in boxes:
if b.body.kinetic_energy >= threshold:
return True
return False | 46ee559926a00b7aa7ab5793e9807edca4db8ec8 | 410,648 |
def get_service_from_condition_key(condition_key):
"""Given a condition key, return the service prefix"""
elements = condition_key.split(":", 2)
return elements[0] | a666a784219fa6b260bc28a8f9ca0c465b161473 | 352,151 |
def rbo_score(ground_truth, simulation, p=0.95):
"""
Rank biased overlap (RBO) implementation
http://codalism.com/research/papers/wmz10_tois.pdf
A ranked list comparison metric which allows non-overlapping lists
Inputs:
ground_truth - ground truth data
simulation - simulation data
p - R... | eda1d9b678bfbbfff71d493113c09e360b945003 | 142,082 |
def read_a_list_file(input_file_name):
""" Read a text file into a python list.
Args:
input_file_name: full path name of a file containing a list
Returns:
a list that is contained in the file
"""
with open(input_file_name, 'r') as fh:
str_input = fh.read()
return li... | 1f06add8dd9075ff0ef30e1174de45f6d597e122 | 265,809 |
def clip(img, size, rect):
""" Clip the frame and return the face region
Args:
img: an instance of numpy.ndarray, the image
size: size of the image when performing detection
rect: an instance of dlib.rectangle, the face region
Returns:
numpy.ndarray, the face region
"""
... | dd7929502591827987cefdc4c7c060a1b14759bd | 395,723 |
def is_doc(comment):
"""Test if comment is a C documentation comment."""
return comment.startswith('/**') and comment != '/**/' | 8f08a8ca87e30fc1693558ddfde9707984ea6ad9 | 541,320 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.