content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def line_value(line):
"""Return the value associated with a line (series of # and . chars)"""
val = 0
for char in line:
val <<= 1
val += char == "#"
return val | d48adf92b3ba92077377da8f14168c838ee10300 | 197,770 |
import importlib
def get_command(all_pkg, hook):
"""
Collect the command-line interface names by querying ``hook`` in ``all_pkg``
Parameters
----------
all_pkg: list
list of package files
hook: str
A variable where the command is stored. ``__cli__`` by default.
Returns
... | 921bc4d8d3829fa35ceacaec741cde172dda175a | 461,116 |
import re
def url_to_filename(url: str) -> str:
"""Converts url to a filename by removing invalid filename characters
Note that this will not always work since windows has very particular file
naming rules.
"""
# Replace "*", used as geography wildcard, with "all"
url = url.replace("*", "all... | 6abf9891786e493c97a0fc63ecfacf6477859298 | 358,631 |
def join_strings(lst):
"""Join a list to comma-separated values string."""
return ",".join(lst) | fbbc195a53d2d4b15012861251d676dbf9369cde | 35,688 |
def son1(ind1,ind2):
""" son1 : one half of the first and second half of the second
2 individual to create one child
:param ind1:
:param ind2:
:return: a new individual
"""
return ind1[:len(ind1)//2]+ind2[len(ind1)//2:] | aa7da58a9ca9d33783670eefd9d6066c4ab7db0a | 268,759 |
def sum_divisible_by(n: int, limit: int) -> int:
"""Computes the sum of all the multiples of n up to the given limit.
:param n: Multiples of this value will be summed.
:param limit: Limit of the values to sum (inclusive).
:return: Sum of all the multiples of n up to the given limit.
"""
p = lim... | 1a68e3d77a98f4c3a5f05dbee935c8791c316063 | 403,874 |
def collection_id(product: str, version: str) -> str:
"""Creates a collection id from a product and a version:
Args:
product (str): The MODIS product
version (str): The MODIS version
Returns:
str: The collection id, e.g. "modis-MCD12Q1-006"
"""
return f"modis-{product}-{ver... | d6a8df291210a2644904447a1687b75b2b614fc3 | 84,935 |
def _func_worker_ranks(workers):
"""
Builds a dictionary of { (worker_address, worker_port) : worker_rank }
"""
return dict(list(zip(workers, range(len(workers))))) | 2efff27857c573f0c68fe725b74c6f04e16b4ec4 | 456,801 |
import torch
def generate_sparse_one_hot(num_ents, dtype=torch.float32):
""" Creates a two-dimensional sparse tensor with ones along the diagnoal as one-hot encoding. """
diag_size = num_ents
diag_range = list(range(num_ents))
diag_range = torch.tensor(diag_range)
return torch.sparse_coo_tensor(
... | 3a71c72acfca4fe9fbfe1a6848519e9726fe72d9 | 46,237 |
def any_in_string(l, s):
"""
Check if any items in a list is in a string
:params l: dict
:params s: string
:return bool:
"""
return any([i in l for i in l if i in s]) | 413f26353595ad92bd6803043f7c926845c6a063 | 434,714 |
def _random_subset_weighted(seq, m, fitness_values, rng):
"""
Return m unique elements from seq weighted by fitness_values.
This differs from random.sample which can return repeated
elements if seq holds repeated elements.
Modified version of networkx.generators.random_graphs._random_subset
""... | 438b72a0d36e529ec554e33357b7ad6dc37aaea5 | 668,659 |
def engine_version(connection):
"""
Return string representation of oVirt engine version.
"""
engine_api = connection.system_service().get()
engine_version = engine_api.product_info.version
return '%s.%s' % (engine_version.major, engine_version.minor) | ac038ee0d812cde0d4d50e34510e0c8004562ecf | 586,340 |
import textwrap
def format_ordinary_line(source_line, line_offset):
"""Format a single C++ line with a diagnostic indicator"""
return textwrap.dedent(
f"""\
```cpp
{source_line}
{line_offset * " " + "^"}
```
"""
) | 504f23b9ac2026ff59cd3d1ab184d9ad236fca96 | 625,340 |
from typing import List
def is_func_name_to_ignore(
func_name: str,
ignore_func_name_prefix_list: List[str]) -> bool:
"""
Get boolean value of function name which should be ignored.
Parameters
----------
func_name : str
Target function name.
ignore_func_name_prefix_lis... | 7d4a6465f1d5220c5c7233a5b3af9e4c2692926c | 220,848 |
def role_vars(host):
"""Loading standard role variables."""
defaults_files = "file=./defaults/main.yml name=role_defaults"
vars_files = "file=./vars/main.yml name=role_vars"
ansible_vars = host.ansible("include_vars", defaults_files)["ansible_facts"]["role_defaults"]
ansible_vars.update(
ho... | 19a874a46ff75de0513c2539d45597aeab2e8941 | 50,640 |
def compile_toc(entries, section_marker='='):
"""Compiles a list of sections with objects into sphinx formatted
autosummary directives."""
toc = ''
for section, objs in entries:
toc += '\n\n%s\n%s\n\n' % (section, section_marker * len(section))
toc += '.. autosummary::\n\n'
for o... | 61c7df461c473a318e5ea08902535e2cc0a9ad8f | 532,491 |
import requests
def fetch_json_package(url, host, referer, encoding):
"""
JSON抓包函数
:param url: AJAX API地址
:param host: 目标服务器
:param referer: header的引用页
:param encoding: 编码
:return: 字典格式的JSON数据包
"""
kv = {'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ... | c8d21f955fb4a92bfdb466c72bb0dccf27090c27 | 622,902 |
def encode_datetime(dt):
"""Converts provided datetime object into ISO 8601/RFC3339-compliant string
:param datetime.datetime dt: datetime object
:return: string representation of dt
:rtype: str
"""
s = dt.isoformat()
if s.endswith('+00:00'):
s = s[:-6] + 'Z'
if dt.tzinfo is Non... | 609daac917cccd4f42b96852352d412e8bde34ca | 607,404 |
def is_student(user):
"""
Method to determine if user has a student role
:param user: User making the request
:return: True if user has a student role
"""
return user.role == "student" | 0aa9fc7724cf2e1d95e71e9ffd76e86ae2b77945 | 213,528 |
import random
def basic_rand_sampler(seq, sample_len):
"""
Basic random text sampler.
If sample_len is greater than the length of the seq, the seq is returned.
"""
seq_len = len(seq)
if seq_len > sample_len:
start_idx = random.randint(0, min(seq_len,seq_len - sample_len))
end... | edf37fd201f15f7ff10efb1253fa3d6258790f1a | 550,728 |
def chunker(df, size):
"""
Split dataframe *df* into chunks of size *size*
"""
return [df[pos:pos + size] for pos in range(0, len(df), size)] | ea96315f9963551f4870d6732570d0ae375bd3c3 | 29,418 |
def factor(n):
"""
分解质因数,非递归解法
:param n: 正整数
:return 质因数列表
"""
result = []
while n > 1:
for i in range(2, n + 1):
if n % i == 0:
n //= i
result.append(i)
break
return result | 41ceccfaf90dffa39c6ce25988165f9779e1a011 | 517,372 |
def comma(text):
"""Split a string into components by exploding on a comma"""
components = (el.strip() for el in text.split(','))
return tuple(filter(bool, components)) | ebfd1d0fe7be436a93973e4ee14f7565414cd5f3 | 24,084 |
def _fold_change(df, cond1, cond2):
"""Linear fold-change calculation. Assumes non-log-transformed values as input."""
return df[cond2] / df[cond1] | 12306f5019f86497ca86901078aba8b85e5215f8 | 361,114 |
def analyse_qa(stats_per_subjects, stats_across_subjects, column_names):
"""
Analyse the subjects and flag warning
Parameters
----------
stats_per_subjects : DataFrame
DataFrame containing the stats per subjects.
stats_across_subjects : DataFrame
DataFrame containing the stats a... | b46a8fd0c2ce753a73a2f525a2f4235226ceacac | 332,394 |
def ToCppStringLiteral(s):
"""Returns C-style string literal, or NULL if given s is None."""
if s is None:
return 'NULL'
if all(0x20 <= ord(c) <= 0x7E for c in s):
# All characters are in ascii code.
return '"%s"' % s.replace('\\', r'\\').replace('"', r'\"')
else:
# One or more characters are n... | c6c9cd3728b026f094c101480dd0e9d580b4f2da | 175,331 |
def asymptotic_relation_radial(enn,numax,param):
"""
Compute the asymptotic frequency for a radial mode.
Parameters
----------
enn : int
The radial order of the mode.
numax : float
The frequency of maximum oscillation power
param : array_like
Collection of the asypm... | 8575c62b3ff5a54fa831b033d1578dfa40cf018e | 672,089 |
def to_type_key(dictionary, convert_func):
"""Convert the keys of a dictionary to a different type.
# Arguments
dictionary: Dictionary. The dictionary to be converted.
convert_func: Function. The function to convert a key.
"""
return {convert_func(key): value
for key, value ... | 98f43eab980358644f9a631759bd2c70904bae91 | 246,972 |
import re
import string
def _sanitize_name(name):
"""Sanitize content of an H2 header to be used as a filename
"""
# replace all non-aplhanumeric with a dash
sanitized = re.sub('[^0-9a-zA-Z]+', '-', name.lower())
# argo does not allow names to start with a digit when using dependencies
if san... | 4e9b68e0cb1fb40de4285cff920bfb0475c41ce9 | 376,839 |
def parse_line(line, names, types):
"""
parse line with expected names and types
Example:
parse_line(line, ['dt', 'ntstep', 'nbunch'], [float, int,int])
"""
x = line.split()
values = [types[i](x[i]) for i in range(len(x))]
return dict(zip(names, values)) | 1fc900601e29b44938536d7d4ca9c1b6fb67ff1b | 391,866 |
import logging
def ReadLines(filename, dut=None):
"""Returns a file as list of lines.
It is used to facilitate unittest.
Args:
filename: file name.
Returns:
List of lines of the file content. None if IOError.
"""
try:
if dut is None:
with open(filename, encoding='utf-8') as f:
... | 719594b32a7bfb853375635873b08b33397e4833 | 328,649 |
def s2d_orthographic(sph):
"""Converts coordinates on the unit sphere to the disk, using
the orthographic projection.
"""
return sph[..., 0] + 1j*sph[..., 1] | 7f1c0373be8534d8d162cac9a64bd6197de583f2 | 287,553 |
def is_array_sequence(obj):
""" Return True if `obj` is an array sequence. """
try:
return obj.is_array_sequence
except AttributeError:
return False | 753cf959a9c3d18980b57bcc2477784e76400711 | 429,291 |
def set_to_bounds(i_s, i_e, j_s, j_e, low=0, high=1):
"""
Makes sure the given index values stay with the
bounds (low and high). This works only for 2 dimensional
square matrices where low and high are same in both
dimensions.
Arguments:
i_s : Starting value for row index
i_e : ... | 765fb315238159111bb2423444b9575ff04382af | 121,409 |
def draw_rectangle(image=None, coordinates=None,
size=None, color=None):
"""
Generate a rectangle on a given image canvas at the given coordinates
:param image: Pillow/PIL Image Canvas
:param coordinates: coordinate pair that will be the center of the rectangle
:param size: tuple with the x... | ff492e256594ef562d58a8d9fdce0c1b6b10e99b | 678,591 |
import math
def blen(n):
"""Length of n in bytes. Also handles non-numeric data."""
try:
return int(math.ceil(n.bit_length() / 8.0))
except AttributeError:
return len(n) | 0bc8e12b3b07be9290821091548edee4b9f015c0 | 346,222 |
def is_registered_path(tmod, pin, pout):
"""Checks if a i/o path is sequential. If that is the case
no combinational_sink_port is needed
Returns a boolean value
"""
for cell, ctype in tmod.all_cells:
if ctype != "$dff":
continue
if tmod.port_conns(pin) == tmod.cell_con... | c5c35a1f2928dc8b6862bc4ebbfdac69fcb3eba9 | 87,583 |
def delete_keys_from_dict(dict_del, the_keys):
"""
Delete the keys present in the lst_keys from the dictionary.
Loops recursively over nested dictionaries.
"""
# make sure the_keys is a set to get O(1) lookups
if type(the_keys) is not set:
the_keys = set(the_keys)
for k, v in dict_de... | 12ef9f75679a470ae2d33db550c05e50991c18de | 144,247 |
def add_branch(tree, vector, value):
"""Recursively update dictionary given a vector containing the path of
the branch. Useful for directly adding a value at a specified key path.
Source: https://stackoverflow.com/a/59634887/6654930
"""
key = vector[0]
if len(vector) == 1:
tree[key] = v... | 95f054cc69ea5786e21961c409575fd214dd26eb | 391,643 |
def _invert(d):
"""Invert a dictionary."""
return dict(zip(d.values(), d.keys())) | 43f8173e5c41aca480abf2710dd03a550e91ac6f | 517,211 |
import re
def is_valid_domain(domain):
"""Checks if a domain is syntactically valid and returns a bool"""
if domain[-1] == ".":
domain = domain[:-1]
if len(domain) > 253:
return False
fqdn_re = re.compile("(?=^.{1,63}$)(^(?:[a-z0-9_](?:-*[a-z0-9_])+)$|^[a-z0-9]$)", re.IGNORECASE)
r... | 2b533646a10160f2172e1a1e1cb51c39ead3c89a | 428,220 |
def islambda(func):
""" Test if the function func is a lambda ("anonymous" function) """
return getattr(func, 'func_name', False) == '<lambda>' | e76b699023b23909f7536e0b3513201ceaebef5c | 127,000 |
def __update_count(count, max_count):
"""
Updating count for next permutation. If all permutations are
done, return -1 as stoping criteria.
:param max_count: list
:param count: list
:return: list
"""
n = len(count)
for i in range(n):
if (count[n-i-1]) < max_count[n-i-1]:
... | d211665652084f3efd6aa9124330854581d0df2d | 453,078 |
import glob
def FindMaxVtuId(project, extensions = [".vtu", ".pvtu"]):
"""
Find the maximum Fluidity vtu ID for the supplied project name
"""
filenames = []
for ext in extensions:
filenames += glob.glob(project + "_?*" + ext)
maxId = None
for filename in filenames:
id = filename[len(projec... | 02b4c1e17e40e18c120bb803790191ff8be592b6 | 230,822 |
def traverse_table(time_step, beam_indx, back_pointers, elems_table,
format_func=None):
"""
Walks back to construct the full hypothesis by traversing the passed table.
:param time_step: the last time-step of the best candidate
:param beam_indx: the beam index of the best candidate in... | e91e38e26f94862e8e676b78c7a2c39876153dd3 | 424,094 |
def find_prepositions(chunked):
""" The input is a list of (token, tag, chunk)-tuples.
The output is a list of (token, tag, chunk, preposition)-tuples.
PP-chunks followed by NP-chunks make up a PNP-chunk.
"""
n = len(chunked) > 0 and len(chunked[0]) or 0
for i, chunk in enumerate(chunked... | 5c86abcceef92cf445b817e64d08a208bbff76c3 | 414,447 |
from typing import Dict
def lower_booleans(value: str, meta: Dict) -> str:
"""
Lower boolean string values to the format expected by the DBMS server.
e.g.
`True` -> `true`
`False` -> `false`
Arguments
---------
value : str
The DBMS server argument value
... | 0604fa1f45972086345c09eb488db8312aece7b6 | 456,268 |
import lzma
def decompress_lzma(lzma_data):
"""Decompresses LZMA data.
Args:
lzma_data: lzma compressed data as bytes.
Returns:
Decompressed data as bytes.
"""
return lzma.LZMADecompressor().decompress(lzma_data) | 52f0e2a5de419df5a29b9a429d2b8632d58a44ef | 139,757 |
def circle_line_intersection(center, radius, line_start, line_end):
"""
Determines whether or not a circle and line intersect
:param center: The center of the circle as a tuple (x,y)
:param radius: The radius of the circle
:param line_start: The start point of a line as a tuple (x,y)
:param line... | 5d641d30987a32347b4834dc2b46cb40c8a59dec | 187,866 |
import random
def _randomly_negate(v):
"""With 50% prob, negate the value"""
return -v if random.random() > 0.5 else v | dd08e186b97afac1b6eb617e90be383e83b749bd | 69,725 |
def is_bottom(module_index):
"""Returns True if module is in the bottom cap"""
return ( (module_index>=600)&(module_index<696) ) | 88b778141776190fecaaa813e6ffcfd418abfd5f | 79,117 |
def is_unknown_license(lic_key):
"""
Return True if a license key is for some lesser known or unknown license.
"""
return lic_key.startswith(('unknown', 'other-',)) or 'unknown' in lic_key | cb3a9446d556f85bc828a8dc24a4041ada7256af | 582,183 |
def residcomp(z1, z0, linelength=1):
"""
Residual Compensation Factor Function.
Evaluates the residual compensation factor based on the line's positive and
zero sequence impedance characteristics.
Parameters
----------
z1: complex
The positive-sequence impedance
... | 398cff9b5a65785ed574e94945cfc7461f5e7bb5 | 153,765 |
def get_attack_rate(df, location):
"""
Get the attack rate for the location.
Args:
df (pd.DataFrame) : pandas DataFrame with attack rates for this scenario
location (str) : name of the location
Returns:
float: Attack rate as a fraction from SIR model, values between 0 and 1.... | 05e27abfd3046a6b455d1a1606ad1591d637e50f | 658,281 |
def _pop_highest(lst):
""" pop the highest value from the list
return a tuple (new list, popped value)"""
highest = lst.pop(lst.index(max(lst)))
return highest | 2d52af7dcec5c499cf24ac9b5d7137cacb7cb402 | 167,614 |
import asyncio
import functools
async def run_blocking_func_in_executor(func, *args, **kwargs):
"""
Run a blocking function in a different executor so that it won't stop
the event loop
"""
return await asyncio.get_event_loop().run_in_executor(None, functools.partial(func, *args, **kwargs)) | 1b7bd8d0680eb1f81aa0fd03f39e20356522105a | 213,435 |
def get_ngrams(sent, n=2, bounds=False, as_string=False):
"""
Given a sentence (as a string or a list of words), return all ngrams
of order n in a list of tuples [(w1, w2), (w2, w3), ... ]
bounds=True includes <start> and <end> tags in the ngram list
"""
ngrams = []
words=sent.split()
if n==1:
return words
... | 9259a07f43a0d17fdddd2556004acf7317d517e8 | 487,163 |
def get_list_nodes_from_tree(tree, parameters=None):
"""
Gets the list of nodes from a process tree
Parameters
---------------
tree
Process tree
parameters
Parameters
Returns
---------------
list_nodes
List of nodes of the process tree
"""
if paramet... | 0d0178407d7675d3b245965606462c23ead232b7 | 662,342 |
def truncate(text, length=30, truncate_string='...'):
"""
Truncates ``text`` with replacement characters
``length``
The maximum length of ``text`` before replacement
``truncate_string``
If ``text`` exceeds the ``length``, this string will replace
the end of the string
""... | 5815cc0e77ace83d73c2714e59b60c6b7111a306 | 376,885 |
def docker_PIDS(container_id):
"""
Determines the number of processes within the docker container.
:param container_id: The full ID of the docker container.
:type container_id: ``str``
:return: Returns the number of PIDS within a dictionary.
:rtype: ``dict``
"""
with open('/sys/fs/cgrou... | efba710f37c4a241415a82f10bdd9d028ae7e38f | 222,907 |
def try_func(func):
"""
Sandbox to run a function and return its values or any produced error.
:param func: testing function
:return: results or Exception
"""
try:
return func()
except Exception as e:
return e | 5d25af78685d89747202e50f227e33b383a8d3d1 | 436,230 |
def compare_flavors(flavor_item):
"""
Helper function for sorting flavors.
Sorting order: Flavors with lower resources first.
Resource importance order: GPUs, CPUs, RAM, Disk, Ephemeral.
:param flavor_item:
:return:
"""
return (
flavor_item.get("Properties", {}).get("Accelerato... | a0e167ee1c7a4f93cc3533064a801b1a29211b7d | 646,658 |
def get_test_result_publish_data(args):
""" Get the data needed to publish the results, from the args. """
publish_env = args.get("publish_results")
publish_username = args.get("publish_username")
publish_password = args.get("publish_password")
return publish_env, publish_username, publish_password | ed93fd7667d829dca0bbfb51d204eb2b4b7abfb6 | 464,522 |
def validate_overlap(periods, datetime_range=False):
"""
Receives a list with DateRange or DateTimeRange and returns True
if periods overlap.
This method considers that the end of each period is not inclusive:
If a period ends in 15/5 and another starts in 15/5, they do not overlap.
This is the ... | bae96eb890063e4d27af0914e7fcd1348d1340a7 | 10,898 |
def compare_polys(poly_a, poly_b):
"""Compares two polygons via IoU.
Input:
poly_a: A Shapely polygon.
poly_b: Another Shapely polygon.
Returns:
The IoU between these two polygons.
"""
intersection = poly_a.intersection(poly_b).area
union = poly_a.union(poly_b).area
... | 86e50bee10291b5363838a29bdef86dad6605235 | 610,077 |
def channel_squeeze(x,
channels_per_group):
"""
Channel squeeze operation.
Parameters:
----------
x : NDArray
Input tensor.
channels_per_group : int
Number of channels per group.
Returns:
-------
NDArray
Resulted tensor.
"""
retur... | ffd1ae27925f4531b8fe61d48a7054d3f3b5f0ce | 444,202 |
def parse_version(vers_string):
"""Parse a version string into its component parts. Returns a list of ints representing the
version, or None on parse error."""
vers_string = vers_string.strip()
vers_parts = vers_string.split('.')
if len(vers_parts) != 4:
return None
try:
major =... | 46d96c48e03ab9e68362cfb850ba49ecf54ba49d | 631,301 |
def partition(list_, indices):
"""Partitions a list to several parts using indices.
:param list_: The target list.
:param indices: Indices to partition the target list.
"""
return [list_[i:j] for i, j in zip([0] + indices, indices + [None])] | 0718abf3da142eeb0ba2817422f1a25a2705bf3a | 271,195 |
import json
def read_json(file_path):
"""Convenience method for reading jsons"""
return json.load(open(file_path)) | 585aa6133e6901c9b62e97c700fd10c712a58f7a | 328,767 |
def ilen(iterator):
"""
Counts the number of elements in an iterator, consuming it and making it
unavailable for any other purpose.
"""
return sum(1 for _ in iterator) | 8111982f0eebcec475588105ab3edebf6ed8677d | 292,619 |
def parameter(name, **kwargs):
"""
Function decorator used to provide additional information for your
function's parameter when it is converted to command.
Parameters
----------
name : str
Name of the parameter.
kwargs :
Keyword arguments to pass to ArgumentParser's add_argu... | 374b6a5eab717bde2267937f7a5363ede548f454 | 270,883 |
def _encode_structure_parts(local_target):
"""
Encodes the design task, to distinguish between struture and wequence domains.
Args:
A sequence that may contain structure or sequence parts.
Returns:
A list representation of the sequence with all structure sites and None else.
"""
... | deb185b439f7b75b6081ca61e57547bdb87aa981 | 627,960 |
def gcd_r(x, y):
"""
求x和y的最大公约数,递归实现方式
欧几里得的辗转相除法:gcd(x,y)=gcd(y,x%y)
:param x: 正整数
:param y: 正整数
:returns: x和y的最大公约数
"""
return x if y == 0 else gcd_r(y, x % y) | bad82bb0d36e8151ffcbf5fe20ae27c288f7a925 | 119,280 |
import pickle
def read_ds(path):
"""Read the data structure from the path."""
with open(path, 'rb') as ds_file:
ds = pickle.load(ds_file)
return ds | 3f5f1d0c52855b2ad4bcca6c498997a5fcc91877 | 107,752 |
def _check_var(
var,
varname,
types=None,
default=None,
allowed=None,
excluded=None,
):
""" Check a variable, with options
- check is instance of any types
- check belongs to list of allowed values
- check does not belong to list of excluded values
if None:
- set to... | ff548db83107661e0fcc7cf25575ec7b107a7041 | 291,955 |
import re
def _parse_version_plus_build(v_plus_b):
"""This should reliably pull the build string out of a version + build string combo.
Examples:
>>> _parse_version_plus_build("=1.2.3 0")
('=1.2.3', '0')
>>> _parse_version_plus_build("1.2.3=0")
('1.2.3', '0')
>>> _parse... | 95d0bdcaa76364d22426cfe86957d64a6f9dfa8d | 464,935 |
import json
def get_string(data):
"""Convert data dict to valid json string."""
return ''.join(json.dumps(data).split()) | 591caf9dcf7e7375d9e347eeb13e50bcde28e0bc | 347,287 |
def rebase_path(from_root_path, to_root_path, path):
"""
Rebase the path to a new root path.
:type path: pathlib.Path
:type from_root_path: pathlib.Path
:type to_root_path: pathlib.Path
:rtype: pathlib.Path
>>> source = Path('/tmp/from/something')
>>> dest = Path('/tmp/to')
>>> rebas... | d143d3d72524523d709bea6e0e132b347ef1cdee | 255,037 |
import pytz
def _ToTimeZone(t, tzinfo):
"""Converts 't' to the time zone 'tzinfo'.
Arguments:
t: a datetime object. It may be in any pytz time zone, or it may be
timezone-naive (interpreted as UTC).
tzinfo: a pytz timezone object, or None (interpreted as UTC).
Returns:
a datetime object i... | b4c47b19a2fc2766565a97523f8a5781c6a69bbe | 427,789 |
def getNamesFromSEGResIDBase(dfSegsNodesNDataDpkt
,SEGResIDBase):
"""
Returns tuple (DIVPipelineName,SEGName) from SEGResIDBase
"""
df=dfSegsNodesNDataDpkt[dfSegsNodesNDataDpkt['SEGResIDBase']==SEGResIDBase]
if not df.empty:
return (df['DIVPipelineName'].iloc[... | bc8ecd69916af18b99ad6b8f2db8661ce09a4f4f | 297,674 |
def _normalize_block_name(block_name):
"""Implements Unicode name normalization for block names.
Removes white space, '-', '_' and forces lower case."""
block_name = ''.join(block_name.split())
block_name = block_name.replace('-', '')
return block_name.replace('_', '').lower() | eead462770a826e8d0c6f6c03a0da00cd94b7bf3 | 77,680 |
import sqlite3
def connect_to_db(db_name='rpg_db.sqlite3'):
"""
This is a function that takes in the file name and connect to the DB using sqlite3
:param db_name:takes in the name of the database
:return: connect object
"""
return sqlite3.connect(db_name) | 2293db12461980cd78f1b114b16d7ea4c233f256 | 54,207 |
import pathlib
def is_sub_path(path1: str, path2: str) -> bool:
"""Given two paths, return if path1 is a sub-path of path2."""
return pathlib.Path(path2) in pathlib.Path(path1).parents | cda13f48049a95b993083721f29b31d4e1a6a195 | 193,122 |
def _find_pkgs_with_dep(packages, search_dep):
""" Return a list of packages which have a given dependency """
pkgs_with_dep = []
for info in packages.values():
for dep in info.get('depends', []):
if dep.startswith(search_dep):
pkgs_with_dep.append(info)
return pkgs_w... | 41d9ae263f863303962b3caaa75d1f42851424ce | 269,854 |
def rpmul(a,b):
"""Russian peasant multiplication.
Simple multiplication on shifters, taken from "Ten Little Algorithms" by
Jason Sachs.
Args:
a (int): the first variable,
b (int): the second vairable.
Returns:
x (int): result of multiplication a*b.
"""
result... | b5df4c2d71df87207248f15384f67161be8fc5d7 | 261,291 |
def human_delta(tdelta):
"""
Takes a timedelta object and formats it for humans.
Usage:
# 149 day(s) 8 hr(s) 36 min 19 sec
print human_delta(datetime(2014, 3, 30) - datetime.now())
Example Results:
23 sec
12 min 45 sec
1 hr(s) 11 min 2 sec
3 day(s) 13 hr(s... | c15cdfcc8cc8594e10b08d6cc5180d08d8460053 | 61,900 |
import requests
import json
def get_pushshift_submissions(query, sub):
"""
Retrieves Reddit submissions matching query term over a given interval
Parameters
----------
query : str
Query term to match in the reddit submissions
sub : str
Submission match query
Returns
-------
... | 5f29854d90f0cd568cc525164ef25bbf6a2b2c50 | 655,765 |
import torch
def horners_method(coeffs,
x):
"""
Horner's method of evaluating a polynomial with coefficients given by coeffs and
input x.
z = arr[0] + arr[1]x + arr[2]x^2 + ... + arr[n]x^n
:param coeffs: List/Tensor of coefficients of polynomial (in standard form)
:param x: ... | ee850e3ae1c7452db56ded1938431e38f275b473 | 373,905 |
from typing import List
def remove_punc(sentences: List[List[str]]) -> List[List[str]]:
"""
Remove punctuation from sentences.
Parameters
----------
sentences:
List of tokenized sentences.
"""
return [
[
"".join([c for c in word if c.isalpha()])
for... | de574fea31b9e89909656c9255b6ed1f891abb07 | 98,227 |
import itertools
def perm_parity(input_list):
"""
Determines the parity of the permutation required to sort the list.
Outputs 0 (even) or 1 (odd).
"""
parity = 0
for i, j in itertools.combinations(range(len(input_list)), 2):
if input_list[i] > input_list[j]:
parity += ... | ae6a1feb170b26e0c5f1b580584889d2ecdea867 | 128,053 |
def search_for_vowels(phrase: str) -> set:
"""Returns set of vowels found in 'phrase'."""
return set('aeiou').intersection(set(phrase)) | b7006216d00b9ab0529c9b41c4fa9533cd9fb78a | 543,123 |
def merge(dicts):
"""Merge an iterable of dictionaries into one."""
d = {}
for d_ in dicts:
d.update(d_)
return d | f7b562549d91a4f451835ee126d9520842e75d89 | 467,004 |
def get_line_equation_coefficients(location1, location2):
"""
Get line equation coefficients for:
latitude * a + longitude * b + c = 0
This is a normal cartesian line (not spherical!)
"""
if location1.longitude == location2.longitude:
# Vertical line:
return float(0), float(... | e4ea043a2818ffa6ccb03c07737c0f7c14f5f4c6 | 456,715 |
def euc_2d(n1, n2):
"""
The euclidean distance for 2D cartesian nodes
:param n1: first node
:type n1: Node
:param n2: second node
:type n2: Node
:return: the euclidean distance between first node and second node in 2D space
:rtype: float
"""
return ((n1.x - n2.x)**2 + (n1.y - n2... | fc7370c09c6e000e7fe984aa1ea663f561fe59db | 449,638 |
def build_flags(flags):
"""Convert `flags` to a string of flag fields."""
return "\n".join([" flag: '" + flag + "'" for flag in flags]) | fdd8e6d2caee31ebe9956cf6248e9ef85e6cec6e | 621,557 |
def hwc2chw(hwc):
"""Change the format of `hwc` from `(height, width, channels)` to `(channels, height, width)`
Args:
hwc (furry.Tensor): An image tensor with format `(height, width, channels)`.
Returns:
furry.Tensor: An image tensor with format `(channels, height, width)`.
"""
... | 75ff29e2371d38535cd0333c96992c36cba72be2 | 245,907 |
def make_transcript_PET_dict(infile):
""" Given a bedtools intersect file, this function creates a dictionary
mapping each transcript_ID to a set containing the RNA-PET IDs that
it matched to. """
transcript_2_pet = {}
with open(infile, 'r') as f:
for line in f:
line... | 2f7cbb1157142235dbf757a41a2197063ecd2a20 | 381,731 |
import importlib
def class_from_dotted_path(dotted_path):
"""Loads a Python class from the supplied Python dot-separated class path.
The class must be visible according to the PYTHONPATH variable contents.
Example:
``"package.subpackage.module.MyClass" --> MyClass``
Args:
dotted_path... | 4888ea47ffe3395452550fe2109df53d500f75f9 | 639,057 |
def request_url(lat, lon, maxpoints=0):
"""
Convert lat and lon to a url query string.
Converts lat and lon to a query string using osrm router.
Parameters
----------
lat : list
ordered list of all latitudes
lon : list
ordered list of all longitudes
maxpoints: int
... | 491e990cc793bb771c9af3fdf50e8e7a78b245a4 | 427,100 |
def expose_header(header, response):
"""
Add a header name to Access-Control-Expose-Headers to allow client code to access that header's value
"""
exposedHeaders = response.get('Access-Control-Expose-Headers', '')
exposedHeaders += f', {header}' if exposedHeaders else header
response['Access-Con... | 049383730da4fbc5a6286ed072655c28ea647c1e | 48,768 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.