content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def rivers_with_station(stations):
"""rivers_with_station(stations) returns a sorted list of the rivers stations are on without repeats"""
stationRivers = set()
for station in stations:
stationRivers.add(station.river)
stationRivers = sorted(stationRivers)
return stationRivers | d13044fef2a824d0d08e4419a13a2b22f1732175 | 12,322 |
def _format_media_type(endpoint, version, suffix):
"""
Formats a value for a cosmos Content-Type or Accept header key.
:param endpoint: a cosmos endpoint, of the form 'x/y',
for example 'package/repo/add', 'service/start', or 'package/error'
:type endpoint: str
:param version: The version of th... | 993e178fc2a91490544936e019342e6ab8f928ce | 12,325 |
def fill_result_from_objective_history(result, history):
"""
Overwrite function values in the result object with the values recorded in
the history.
"""
# counters
result.n_fval = history.n_fval
result.n_grad = history.n_grad
result.n_hess = history.n_hess
result.n_res = history.n_r... | a2f1388c5d71a06f45369098039a3fa623a25735 | 12,326 |
def Armijo_Rule(f_next,f_initial,c1,step_size,pg_initial):
"""
:param f_next: New value of the function to be optimized wrt/ step size
:param f_initial: Value of the function before line search for optimum step size
:param c1: 0<c1<c2<1
:param step_size: step size to be tested
:param pg: inner p... | 90462eda94244c10afdf34e1ad042118d793c4fd | 12,328 |
import socket
def connect(host, port):
"""Connect to remote host."""
# Create socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as msg:
return (None, msg)
# Get remote IP
try:
addr = socket.gethostbyname(host)
except socket.gaierr... | ab03e5551f0fbf92c6e2417635bc753d5b77eae2 | 12,332 |
import pprint
def pfomart(obj):
"""格式化输出某对象
:param obj: obj对象
:return: 格式化出处的字符串
"""
return pprint.pformat(obj) | 2f2c7d7df9de9bb65c72634e8ba9386365408445 | 12,335 |
import re
def rle2cells(rle_str: str) -> str:
"""Convert lifeform string in RLE encoding to PlainText
Args:
rle_str (str): single line of RLE commands
Returns:
str: valid PlainText-encoded lifeform
"""
# drop the last part
if "!" in rle_str:
rle_str = rle_str[: rle_st... | e48ea40bd9032445e1aabe4753b7fbdcc62191ed | 12,338 |
def pow_sq(x, y):
"""
Compute x^y, without calling its pow,
using exponentiation by squaring.
"""
r = 1
while y:
if y & 1:
r = r * x
x = x * x
y >>= 1
return r | f6d82257ff909d9c890360dcd9408db0d742b13d | 12,345 |
def get_point(values, pct):
"""
Pass in array values and return the point at the specified top percent
:param values: array: float
:param pct: float, top percent
:return: float
"""
assert 0 < pct < 1, "percentage should be lower than 1"
values = sorted(values)
return values[-int(len(... | 11474d804e0845284a864a5cb8de23299999a5e7 | 12,351 |
def check_columns(df):
"""
Checks wether dataframe contains the required columns.
:param df: the data frame with track data.
:return: whether or not df contains all the required columns.
required columns: refName, start, end, name, score (is optional)
:rtype: boolean
"""
require... | 3ddc53fc0e2caad74b3218f7f47134aed258cba9 | 12,354 |
def accuracy_inf_sol(inferred,cliques_solution):
"""
'inferred' should be a set of vertices
'cliques_solution' an iterable of all the solution cliques (as sets)
"""
assert len(cliques_solution)!=0, "No solution provided!"
max_overlap = 0
best_clique_sol = cliques_solution[0]
clique_size ... | d2d38d7f3470520058f90699dab6b7eb59cbd5cf | 12,355 |
def _ziprange(alist, ix):
"""
returns zip of the list, and the one with ix added at the end and first element dropped
Example
-------
::
alist = [2,4,7]
_ziprange (alist, 10)
-->
zip([2,4,7], [4,7,10]) -> (2,4), (4,7), (7,10)
"""
blist = alist.copy()
... | e816ad20e8c193487d8483cdfd3ee27d77fef814 | 12,356 |
import re
def title_output_replace(input_title_output, metadata_dict, data_dict, rel_channels_dict, is_title = False, custom_vars = None):
"""Substitute %VAR% variables with provided values and constants.
Given a title (or output path) string template, replace %VAR%
variables with the appropriate va... | 83102c1557643b67ce1c52f0c69154bcfac4ac72 | 12,358 |
def format_data(data, es_index):
"""
Format data for bulk indexing into elasticsearch
"""
unit = data["unit"]
rate_unit = data["rateUnit"]
egvs = data["egvs"]
docs = []
for record in egvs:
record["unit"] = unit
record["rate_unit"] = rate_unit
record["@timestamp"]... | 094af427daaf4922371e17fca70a2b8c8539d54c | 12,359 |
def paste_filename(search):
"""
Function that will create a name for the files to be saved to using the search
"""
# Removes any spaces
cleaned_keyword = search.replace(' ', '_')
# Adds 'videos.csv' at the end
filename = cleaned_keyword + "_videos.csv"
return filename | 3279ef21e039b7a63a728a6d02714086a61f3e0e | 12,361 |
import torch
def repeat_column(column: torch.Tensor, times: int) -> torch.Tensor:
"""
Repeats the given column the given number of times.
:param column: the column to repeat. Size [H].
:param times: the number of repetitions = W.
:return: the given column repeated the given number of times. Size [... | dfa955fbff0c4b87a7f5cef729a454eb99c93760 | 12,364 |
def parse_markers(f):
"""
Parse markers from mrk file f. Each marker determines a time point
and an according class-label of the movement that was imagined.
Args:
f (String) - an mrk file
Returns:
tuple of lists of ints - one list for the markers, one for
... | 670ce43529a7aae4f4ed4341938a90eb6e714fb3 | 12,367 |
def dp_key(relations):
"""
generates a unique key for the dptable dictionary
:param relations: set of relations
:return: str
"""
return '-'.join(sorted([r.name for r in relations])) | e415778193d5a5c90ba7574bccc7e82d0d95c2e8 | 12,369 |
def extract_sectors(pred_df, thres):
"""Extracts labels for sectors above a threshold
Args:
pred_df (df): predicted sector
thres (float): probability threshold
"""
long_df = (
pred_df.reset_index(drop=False)
.melt(id_vars="index", var_name="division", value_name="probabi... | a772e965685ca8ac8cd6a52861c36e9cf7faf887 | 12,377 |
import bisect
def find_closest(numeric_list, query_number):
"""
Given a list of numbers, and a single query number, find the number in the sorted list that is numerically
closest to the query number. Uses list bisection to do so, and so should be O(log n)
"""
sorted_numeric_list = sorted(numeric_l... | ae2dad58162f38f7c1e4d7149943488a96c3c8dc | 12,378 |
def count_features_type(types, include_binary=False):
""" Counts two or three different types of features
(binary (optional), categorical, continuous).
:param types: list of types from get_type
:returns a tuple (binary (optional), categorical, continuous)
"""
if include_binary:
return (
... | 4158122256c9a407f58987d278657e4a006e6a13 | 12,386 |
def is_pandas_module(fullname: str) -> bool:
"""Check if a fully qualified name is from the pandas module"""
return fullname.startswith("pandas.") | 0becdbfd7c1c4f5b7990cbc0466a6e45f25acb14 | 12,387 |
def squeeze_first(inputs):
"""Remove the first dimension in case it is singleton."""
if len(inputs) == 1:
inputs = inputs[0]
return inputs | c2c0cabc873baf88ce7673f2c8889fedce0f05da | 12,390 |
def is_part_of_word(word_fragment, wordlist):
"""Returns True if word_fragment is the beginning of a word in wordlist.
Returns False otherwise. Assumes word_fragment is a string."""
for word in wordlist:
is_part_of_list = word_fragment == word[:len(word_fragment)]
if is_part_of_list == True:... | 54f572655fe7bb383cb00d732b57d85156b5f528 | 12,395 |
def render_output(data):
"""Print the formatted output for the list
"""
output = ['[Dataduct]: ']
output.extend(data)
return '\n'.join(output) | 5e3bee31890f682eca6aa03128dbf8d51e2fe473 | 12,396 |
def get_parent_doc(__type: type, /) -> str | None:
"""Get the nearest parent documentation using the given :py:class:`type`'s mro.
:return The closest docstring for an object's class, None if not found.
"""
doc = None
for parent in __type.__mro__:
doc = parent.__doc__
if doc:
... | efe61d30a82e08ccdf5411ffc9feb4252fdb53e2 | 12,397 |
def drop_multiple_col(col_names_list, df):
"""AIM -> Drop multiple columns based on their column names.
INPUT -> List of column names, df.
OUTPUT -> updated df with dropped columns"""
df.drop(col_names_list, axis=1, inplace=True)
return df | 991144349d383b79e1510fa5c106226254f8329b | 12,398 |
def replstring(string, i, j, repl):
"""
Replace everything in string between and including indices i and j with repl
>>> replstring("abc", 0, 0, "c")
'cbc'
>>> replstring("abc def LOL jkl", 8, 10, "ghi")
'abc def ghi jkl'
"""
# Convert to list since strings are immutable
strlist = li... | 97eee8912a6c8fd9e29a5784af1f3853b714cf0b | 12,399 |
def cli(ctx, workflow_id):
"""Delete a workflow identified by `workflow_id`.
Output:
A message about the deletion
.. warning::
Deleting a workflow is irreversible - all workflow data
will be permanently deleted.
"""
return ctx.gi.workflows.delete_workflow(workflow_id) | 9ee3aa82a9577f9b20574f821f4a9e226665740d | 12,402 |
def int2bit(x, w=20):
"""
Generates a binary representation of an integer number (as a tuple)
>>> bits = int2bit(10, w=4)
>>> bits
(1, 0, 1, 0)
>>> bit2int( bits )
10
"""
bits = [ ]
while x:
bits.append(x%2)
x /= 2
# a bit of padding
bits = bits ... | b65cd8f7c6232896eb2aef9f9d69b6ac4fd97bc6 | 12,405 |
def to_tuple(x):
"""Converts lists to tuples.
For example::
>>> from networkx.utils import to_tuple
>>> a_list = [1, 2, [1, 4]]
>>> to_tuple(a_list)
(1, 2, (1, 4))
"""
if not isinstance(x, (tuple, list)):
return x
return tuple(map(to_tuple, x)) | 29586512b336ae5079e991bb13c1ac904e5eefe9 | 12,408 |
def mean_residue_ellipticity(phi, n, c, l):
"""
Calculate mean residue ellipticity (millideg cm2 / decimol) from
ellipticity (mdeg)
Args:
phi (float): a ellipticity (milli deg)
n (int): the number of residues
c (float): the molar concentration of the polymer (mol/L)
l (f... | a51a90e3a12b921b2e12fb75160929d60652dcca | 12,409 |
from typing import List
from typing import Tuple
import random
def generate_round_robin_matches(bots: List[str]) -> List[Tuple[str, str]]:
"""
Returns a list of pairs of bots that should play against each other for a round robin.
"""
# This makes the list of matches consistent over multiple calls. E.g... | 1d29e36613210d8d1198fe5943c035c0e435b8dc | 12,414 |
def bin2dec(string_num):
"""Turn binary into decimal."""
return str(int(string_num, 2)) | 5c8ba774f1a749947e64a00c86e6cb4054b44d97 | 12,415 |
def get_config_dict(robustness_tests, base_config_dict):
"""
Combines robustness_test and train_config_dict into a single config_dict.
Args:
robustness_tests (dict): robustness test config dict
base_config_dict (dict): train/data/eval/model/hyperparam config dict
Returns:
confi... | 593a2307849fa27b895f18d8b9eacd679eeab04a | 12,416 |
def distance_vector_between(point_1, point_2):
"""Compute and return the vector distance between two points."""
return [point_2[0] - point_1[0], point_2[1] - point_1[1]] | 397d3191cc4c214bb0d4b474db2efe7c63e8a10f | 12,417 |
def split_names(data, names, fosa_types, drop):
"""Separates facility type prefix from facility name
inputs
data: data frame containing source data from IASO
names: column name to split
fosa_types: list of facility types
drop: list of prefixes indicating row should be dropped fro... | 4842756abd8b332d22548382f56a7c03d43609c2 | 12,421 |
def _NamesNotIn(names, mapping):
"""Returns a list of the values in |names| that are not in |mapping|."""
return [name for name in names if name not in mapping] | ec91dcb6e29b0a9c1aa66f04e1b61d715ded3266 | 12,422 |
import re
def natural_sort(l):
"""
Takes in a list of strings and returns the list sorted in "natural" order.
(e.g. [test1, test10, test11, test2, test20] -> [test1, test2, test10, test11, test20])
Source: https://stackoverflow.com/questions/4836710/is-there-a-built-in-function-for-string-natural-sor... | 7db22ee5f75703f52b25eecd888847eb35590e65 | 12,423 |
def get_extensions(list_of_files):
"""Function take a list of Path file objects and adds the file extenstion/suffix to a set. The set of extensions
is returned"""
extensions = set()
for file in list_of_files:
if len(file.suffix) < 6:
extensions.add((file.suffix).lstrip('.'))
ret... | 654b893c148535a99dd112dc3711ea9005ae96b7 | 12,424 |
def org_rm_payload(org_default_payload):
"""Provide an organization payload for removing a member."""
rm_payload = org_default_payload
rm_payload["action"] = "member_removed"
return rm_payload | e976396f6fe5de1073f2235aac36b300f129867a | 12,427 |
def get_progress_rate(k, c_species, v_reactants):
"""Returns the progress rate for a reaction of the form: va*A+vb*B --> vc*C.
INPUTS
=======
k: float
Reaction rate coefficient
c_species: 1D list of floats
Concentration of all species
v_reactants: 1D list of floats
Stoi... | 6baaaa07fe0814dbc50516b29ba55087c4ec23fd | 12,431 |
import json
def get_key(filepath, key, default=None):
"""
Opens the file and fetches the value at said key
:param str filepath: The path to the file
:param str key: The key to fetch
:param default: The value to return if no key is found
:return: The value at the key (or the default value)
... | 9f720f33373ceec9a9a1a4b46c0e9257d3a55787 | 12,435 |
def commonprefix(l):
"""Return the common prefix of a list of strings."""
if not l:
return ''
prefix = l[0]
for s in l[1:]:
for i, c in enumerate(prefix):
if c != s[i]:
prefix = s[:i]
break
return prefix | 235636c207c89a7128295fb5aa5b0cba732f50a1 | 12,441 |
def get_qtypes(dataset_name, part):
"""Return list of question-types for a particular TriviaQA-CP dataset"""
if dataset_name not in {"location", "person"}:
raise ValueError("Unknown dataset %s" % dataset_name)
if part not in {"train", "dev", "test"}:
raise ValueError("Unknown part %s" % part)
is_biase... | 0aa1a186ebf4fcfe5820ecbb697d8cb166114310 | 12,443 |
import re
def get_numbers_from_file(path, skip_lines=2):
"""
Function to read a file line-wise and extract numbers.
Parameters
----------
path: str
Path to the file including the filename.
skip_lines: int
Number of lines to skipp at the beginning of the file.
Returns
... | 64026a6c5cf9aa16076a3c8872663ab7996c1add | 12,445 |
def describe_list_indices(full_list):
"""
Describe the indices of the given list.
Parameters
----------
full_list : list
The list of items to order.
Returns
-------
unique_elements : list
A list of the unique elements of the list, in the order in which
they firs... | 664bcfd63dd0d5d5114ce24a4c7b2850b61364c5 | 12,447 |
def load_metadata_txt(file_path):
"""
Load distortion coefficients from a text file.
Parameters
----------
file_path : str
Path to a file.
Returns
-------
tuple of floats and list
Tuple of (xcenter, ycenter, list_fact).
"""
if ("\\" in file_path):
... | d1220c39fd9e69b76b1aa6f3e73cd9eef708c451 | 12,448 |
from typing import OrderedDict
def gen_top(service_uri, no_pages, num_mem, label=None):
"""
Generate the top level collection page.
:param service_uri: base uri for the AS paged site.
:param no_pages:
:param num_mem:
:param label:
:return: dict
"""
top = OrderedDict()
top['@co... | 14b330e0ad57b08462b3854eba2771e859344df2 | 12,449 |
def a_simple_function(a: str) -> str:
"""
This is a basic module-level function.
For a more complex example, take a look at `a_complex_function`!
"""
return a.upper() | a511eb8577e0440d0026c4762628fdb6de9be643 | 12,454 |
def paginated_list(full_list, max_results, next_token):
"""
Returns a tuple containing a slice of the full list
starting at next_token and ending with at most the
max_results number of elements, and the new
next_token which can be passed back in for the next
segment of the full list.
"""
... | 99a20e3af4ff64d3de52eccbc00aea9fda735e00 | 12,455 |
def celsius_to_kelvin(deg_C):
"""Convert degree Celsius to Kelvin."""
return deg_C + 273.15 | 45eb2dd781adbab2db44f5a8ce5042b2834c7c00 | 12,456 |
def params_linear_and_squares(factors):
"""Index tuples for the linear_and_squares production function."""
names = factors + [f"{factor} ** 2" for factor in factors] + ["constant"]
return names | 8f7505cb2a07e08d3ad2686d52960d631cd7b458 | 12,461 |
def tuple_as_atom(atom:tuple) -> str:
"""Return readable version of given atom.
>>> tuple_as_atom(('a', (3,)))
'a(3)'
>>> tuple_as_atom(('bcd', ('bcd',12)))
'bcd(bcd,12)'
"""
assert len(atom) == 2
return '{}({})'.format(atom[0], ','.join(map(str, atom[1]))) | 5c18f34733d839865eef35509f95c2d4d198a903 | 12,465 |
import struct
def Fbytes(f):
"""
Return bytes representation of float
"""
return struct.pack("f", f) | 117fb86216ad6983851923ac9dbd0196cc29b92d | 12,466 |
def clamp(value, low, high):
"""Clamp the given value in the given range."""
return max(low, min(high, value)) | 48303b27d78f8d532b1e74db052457ae19b9f10d | 12,469 |
def fmt_n(large_number):
"""
Formats a large number with thousands separator, for printing and logging.
Param large_number (int) like 1_000_000_000
Returns (str) like '1,000,000,000'
"""
return f"{large_number:,.0f}" | 7b23e902a1c9600f1421b45b27623abaa1930f05 | 12,470 |
def inner_product(L1, L2):
"""
Take the inner product of the frequency maps.
"""
result = 0.
for word1, count1 in L1:
for word2, count2 in L2:
if word1 == word2:
result += count1 * count2
return result | 65ede8eddcf86d75a1b130a76381416c2a272f61 | 12,472 |
def x_point_wgt_av(df_agg, x_var):
"""
Set the x_point to be the weighted average of x_var within the bucket,
weighted by stat_wgt.
"""
if not (x_var + '_wgt_av') in df_agg.columns:
raise ValueError(
"\n\tx_point_wgt_av: This method can only be used when"
"\n\tthe wei... | 15d8515efceb67e1dc9062d7fd79250c5935b549 | 12,474 |
from typing import Mapping
from typing import Optional
def _rename_nodes_on_tree(
node: dict,
name_map: Mapping[str, str],
save_key: Optional[str] = None,
) -> dict:
"""Given a tree, a mapping of identifiers to their replacements, rename the nodes on
the tree. If `save_key` is provided, then the ... | b8d3df2f2247b27c614b767b28eda7b91e380524 | 12,478 |
def ignore(name):
"""
Files to ignore when diffing
These are packages that we're already diffing elsewhere,
or files that we expect to be different for every build,
or known problems.
"""
# We're looking at the files that make the images, so no need to search them
if name in ['IMAGES']:
return Tru... | d5f64616480fa14c03b420165d2c89040a8cc768 | 12,481 |
def power(work, time):
"""
Power is the rate at which the work is done.
Calculates the amountof work done divided by
the time it takes to do the work
Parameters
----------
work : float
time : float
Returns
-------
float
"""
... | 48eb476658fa19a6002b428993bfa58c81634638 | 12,482 |
def find(*patterns):
"""Decorate a function to be called for each time a pattern is found in a line.
:param str patterns: one or more regular expression(s)
Each argument is a regular expression which will trigger the function::
@find('hello', 'here')
# will trigger once on "hello you"... | 884005008791baba3a9949e9d2c02aee0f985552 | 12,484 |
import re
def validate_container_name(name):
"""Make sure a container name accordings to the naming convention
https://docs.openstack.org/developer/swift/api/object_api_v1_overview.html
https://lists.launchpad.net/openstack/msg06956.html
> Length of container names / Maximum value 256 bytes / Cannot c... | 5bef8b304c004dc3169b6984b49a0d669fc9b7b3 | 12,490 |
def function(values):
"""A simple fitness function, evaluating the sum of squared parameters."""
return sum([x ** 2 for x in values]) | ee96b0948e43eec1e86ffeeca681567d2a0afa53 | 12,491 |
def create_redis_compose_node(name):
"""
Args:
name(str): Name of the redis node
Returns:
dict: The service configuration for the redis node
"""
return {
"container_name": name,
"image": "redis:3.2.8",
"command": "redis-server --appendonly yes",
"deplo... | e6d01acc8b0c5c324ad3e0f6e5f527e2a6433705 | 12,493 |
def sun_rot_elements_at_epoch(T, d):
"""Calculate rotational elements for Sun.
Parameters
----------
T: float
Interval from the standard epoch, in Julian centuries i.e. 36525 days.
d: float
Interval in days from the standard epoch.
Returns
-------
ra, dec, W: tuple (flo... | 9a74edc686869eebd851200687fe4d10d38d550a | 12,497 |
def NameAndAttribute(line):
"""
Split name and attribute.
:param line: DOT file name
:return: name string and attribute string
"""
split_index = line.index("[")
name = line[:split_index]
attr = line[split_index:]
return name, attr | 7595f51d728c5527f76f3b67a99eccd82fb9e8b7 | 12,500 |
import torch
import copy
def clones(module: torch.nn.Module, n: int):
"""
Produce N identical copies of module in a ModuleList
:param module: The module to be copied.
The module itself is not part of the output module list
:param n: Number of copies
"""
return torch.nn.ModuleList([cop... | e4807cda87c90af415555606e3308f07ff9ddf49 | 12,504 |
def is_sorted(array):
""" Check if array of numbers is sorted
:param array: [list] of numbers
:return: [boolean] - True if array is sorted and False otherwise
"""
for i in range(len(array) - 1):
if array[i] > array[i + 1]:
return False
return True | 8542e162aa96f7035d33f1eb7b7159031a8a41b8 | 12,506 |
def FormatDescriptorToPython(i):
"""
Format a descriptor into a form which can be used as a python attribute
example::
>>> FormatDescriptorToPython('(Ljava/lang/Long; Ljava/lang/Long; Z Z)V')
'Ljava_lang_LongLjava_lang_LongZZV
:param i: name to transform
:rtype: str
"""
i... | 8d217883603ae9e9c8f282985b456aa97494beba | 12,507 |
def layer_severity(layers, layer):
"""Return severity of layer in layers."""
return layers[layer]['severity'] | e8a7a95268ddd2d4aa6b5f7fa66d5828016517eb | 12,509 |
def _parse_alt_title(html_chunk):
"""
Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title.
"""
title = html_chunk.find(
"input",
{"src": ... | bd5df0edfc174653731256d50e0a8f84a6f84880 | 12,512 |
def prompt_worker_amount(cpu_cores: int):
"""Prompt the user for the amount of Celery workers they want to run.
Start 2 less workers than amount of CPU cores by default."""
answer = 0
safe_cores_suggestion = cpu_cores - 2
def invalid_answer():
"""Restart prompt if answer invalid"""
... | 2f2e4d423eb94d0bf709feda09c5c45ca8cc481a | 12,513 |
def tab_delimited(list_to_write):
"""Format list of elements in to a tab-delimited line"""
list_to_write = [str(x) for x in list_to_write]
return '\t'.join(list_to_write) + '\n' | 921a3316f01aecaba1efb43c524b1ad5cca89546 | 12,523 |
def get_sorted_indices(some_list, reverse=False):
"""Get sorted indices of some_list
Parameters
----------
some_list : list
Any list compatible with sorted()
reverse : bool
Reverse sort if True
"""
return [
i[0]
for i in sorted(
enumerate(some_lis... | 6e207f4079cd3800fd26269725f5385250b76112 | 12,529 |
def excel_index(column):
""" Takes a string and returns what column it would be in Excel. """
# Not needed but will insure the right values. There are different
# ASCII values for uppercase and lowercase letters.
letters = list(column.upper())
# This works like this: LOL = 8514
# 26^2 * 12(L) + ... | 224d7f370468e232a68a8205cf101e8dcb959829 | 12,531 |
def gp_tuple_to_dict(gp_tuple):
"""Convert a groupings parameters (gp) tuple into a dict suitable
to pass to the ``grouping_parameters`` CompoundTemplate.__init__
kwarg.
"""
params = [{'min': 1}, {'max': 1}, {'name': None}, {'possible_types': None},
{'is_separator': False}, {'inner_sep... | 5db98d0530dc177685e0bcfefad94a1f6718aed9 | 12,537 |
from typing import Optional
def convert_int_or_none(val: Optional[int]) -> Optional[int]:
"""Convert to an int or None."""
return int(val) if val is not None else val | 1920243d7465df6f2f3f9e6fdbd2424bbad165b4 | 12,539 |
def parse_object(repo, objectish):
"""Parse a string referring to an object.
:param repo: A `Repo` object
:param objectish: A string referring to an object
:return: A git object
:raise KeyError: If the object can not be found
"""
return repo[objectish] | 6606eb58a1aab94a6071bf18221dbec63e2ef6da | 12,545 |
def elision_normalize(s):
"""Turn unicode characters which look similar to 2019 into 2019."""
return s.replace("\u02BC", "\u2019").replace("\u1FBF", "\u2019").replace("\u0027", "\u2019").\
replace("\u1FBD", "\u2019") | a7b0f2ba14d0fcbb2cd1cc97b8ce858051d35709 | 12,548 |
def constrain_to_range(s, min_val, max_val):
"""
Make sure that a value lies in the given (closed) range.
:param s: Value to check.
:param min_val: Lower boundary of the interval.
:param max_val: Upper boundary of the interval.
:return: Point closest to the input value which lies in the given r... | d2017580bab60ba444cbf40f570b16763de81969 | 12,550 |
def find_piece_size(total_size):
""" Determine the ideal piece size for a torrent based on the total
size of the data being shared.
:param total_size: Total torrent size
:type total_size: int
:return: Piece size (KB)
:rtype: int
"""
if total_size <= 2 ** 19:
return 512
elif ... | 532adc41448ce5dfb11f02699c987936e1abda0a | 12,555 |
def fake_file(filename, content="mock content"):
"""
For testing I sometimes want specific file request to return
specific content. This is to make creation easier
"""
return {"filename": filename, "content": content} | 5b342edf9dec65987223fbbc8b670402513ae4ed | 12,557 |
def flatten(sequence):
"""Given a sequence possibly containing nested lists or tuples,
flatten the sequence to a single non-nested list of primitives.
>>> flatten((('META.INSTRUMENT.DETECTOR', 'META.SUBARRAY.NAME'), ('META.OBSERVATION.DATE', 'META.OBSERVATION.TIME')))
['META.INSTRUMENT.DETECTOR', 'META... | 6ca3fe470757dc4081c4387d917d5e285c2a3f06 | 12,560 |
def relevant_rule(rule):
"""Returns true if a given rule is relevant when generating a podspec."""
return (
# cc_library only (ignore cc_test, cc_binary)
rule.type == "cc_library" and
# ignore empty rule
(rule.hdrs + rule.textual_hdrs + rule.srcs) and
# ignore test-only rule
not ... | 3e1a45d222128e0065eb585135806a0f8bb787d9 | 12,561 |
def _decrement_version(lambda_config):
"""Decrement the Lambda version, if possible.
Args:
lambda_config (dict): Lambda function config with 'current_version'
Returns:
True if the version was changed, False otherwise
"""
current_version = lambda_config['current_version']
if cur... | a06ed14e0abaa68a809bdb49c2d4f2cc59ce6db2 | 12,564 |
import collections
def rollout(env, agent, max_steps):
"""Collects a single rollout of experience.
Args:
env: The environment to interact with (adheres to gym interface).
agent: The agent acting in the environment.
max_steps: The max number of steps to take in the environment.
Re... | eb9a9f41b9c37e1c5f8ebdbbec13650dd7665622 | 12,566 |
def tms_mpsse(bits):
"""convert a tms bit sequence to an mpsee (len, bits) tuple"""
n = len(bits)
assert (n > 0) and (n <= 7)
x = 0
# tms is shifted lsb first
for i in range(n - 1, -1, -1):
x = (x << 1) + bits[i]
# only bits 0 thru 6 are shifted on tms - tdi is set to bit 7 (and is l... | 25d2dc3b1edd5494e82295fe50889565246c2ae5 | 12,567 |
def _aggregate(query, func, by=None):
"""
Wrap a query in an aggregation clause.
Use this convenience function if the aggregation parameters are coming from
user input so that they can be validated.
Args:
query (str): Query string to wrap.
func (str): Aggregation function of choice. Valid choices ar... | e26aa715fadc5a58f5f87cee297fc3e6500120e1 | 12,568 |
from typing import Any
def accept(message: Any) -> bool:
"""
Prompts the user to enter "yes" or "no". Returns True if the
response was "yes", otherwise False. Ctrl-c counts as "no".
"""
message = f"[pretf] {message} [yes/no]: "
response = ""
while response not in ("yes", "no"):
t... | 884bf321462ef37f02a69925ece012e108fad861 | 12,569 |
def format_seconds(total_seconds: int) -> str:
"""Format a count of seconds to get a [H:]M:SS string."""
prefix = '-' if total_seconds < 0 else ''
hours, rem = divmod(abs(round(total_seconds)), 3600)
minutes, seconds = divmod(rem, 60)
chunks = []
if hours:
chunks.append(str(hours))
... | c0f79b7f45c32589537b5dbf51a95b4811c50417 | 12,570 |
import six
def rev_comp( seq, molecule='dna' ):
""" DNA|RNA seq -> reverse complement
"""
if molecule == 'dna':
nuc_dict = { "A":"T", "B":"V", "C":"G", "D":"H", "G":"C", "H":"D", "K":"M", "M":"K", "N":"N", "R":"Y", "S":"S", "T":"A", "V":"B", "W":"W", "Y":"R" }
elif molecule == 'rna':
nuc_dict = { "A":"U", "... | 2e42ccf5f37992d0fbe3a25afd70a04e6fc0c225 | 12,572 |
def findall_deep(node, selector, ns, depth=0, maxDepth=-1):
"""
recursively find all nodes matching the xpath selector
:param node: the input etree node
:param selector: the xpath selector
:param ns: a dict of namespaces
:param depth: the current depth
:param maxDepth: the maximum number of... | f93d413dd205acf5be0e5f76dd6c599f54bfac57 | 12,577 |
from typing import Union
from typing import List
def table_insert(name: str, field_names: Union[str, List[str]]) -> str:
"""Return command to add a record into a PostgreSQL database.
:param str name: name of table to append
:param field_names: names of fields
:type: str or list
:return: command ... | a50aadebe655118c255ccb81c3c0852646057ff4 | 12,578 |
def __normalize(variable):
"""
Scale a variable to mean zero and standard deviation 1
Parameters
----------
variable : xarray.DataArray or np.ndarray
Returns
-------
xarray.DataArray or np.ndarray
"""
mean = variable.mean()
std = variable.std()
if std != 0:
resu... | 7d6329ef6454deb04b041a630a7f1f084f237b57 | 12,580 |
def get_proj(ds):
"""
Read projection information from the dataset.
"""
# Use geopandas to get the proj info
proj = {}
maybe_crs = ds.geometry.crs
if maybe_crs:
maybe_epsg = ds.geometry.crs.to_epsg()
if maybe_epsg:
proj["proj:epsg"] = maybe_epsg
else:
... | 4ed68d8733285cdea92c1b167a3d7f59024845db | 12,584 |
def nameFormat(name):
""" Edits the name of the column so that it is properly formatted with a space between the words, and each word capitalized."""
space = name.find("l") + 1
firsthalf = name[:space]
secondhalf = name[space:]
name = firsthalf.capitalize() + " " + secondhalf.capitalize()
return... | d93b54d6a18347aeb32657c1f8880965d01db7f2 | 12,585 |
def invert_cd_path(graph, path, c, d):
"""
Switch the colors of the edges on the cd-path: c to d and d to c.
:param graph: nx.Graph(); each edge should have an attribute "color"
:param path: nx.Graph() representing cd-path
:param c: integer smaller then the degree of "graph" or None; represents a co... | 53455f3e442a10ee403d499fe9c5b6f2e86a6e7f | 12,586 |
def _initialise_notable_eids(db):
"""Returns set of eids corresponding to "notable" entities."""
rows = db.query("""
SELECT eid FROM entity_flags
WHERE political_entity=TRUE;
""")
notable_eids = set(row["eid"] for row in rows)
print('[OK] Received %d notable eIDs.' % len(notable_eids))
... | c11306395937fc58dadbd3e9d129f7f6d7b4b576 | 12,589 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.