content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _field_index(header, field_names, index):
"""Determine a field index.
If the index passed is already a valid index, that index is returned.
Otherwise, the header is searched for a field name matching any of
the passed field names, and the index of the first one found is
returned.
If no mat... | 6a8797d5972fec4cdc0cf5030397a90545a66177 | 671,369 |
import torch
def _sigmoid_then_2d(x):
"""Transform 1-dim logits to valid y_proba
Sigmoid is applied to x to transform it to probabilities. Then
concatenate the probabilities with 1 - these probabilities to
return a correctly formed ``y_proba``. This is required for
sklearn, which expects probabil... | 5aced9f0d20e4167cc84f818c2e4b9274cb2ab49 | 671,370 |
import re
def parse_combined_float_list(float_string_list):
"""Parses a list of strings, where each element of the list is a single string which is a list of floats
to be parsed.
Assumes the data delimiter is whitespace or comma,
and removes any white space at the beginning and end of the string
a... | 4e985cc90dc35fc8adf4a04eac8a9117c07653a8 | 671,371 |
def create_value_dict(data_agg,
super_star_avg_prices_2_agents,
super_star_avg_prices_3_agents
):
"""
A function to create a comprehensive dictionary with all
values that we need to create the plot.
Args:
data_agg (DataFrame): Da... | fc7797ff939f25214c53d4fe359fe488a45bf233 | 671,373 |
def get_referenced_filenames(license_matches):
"""
Return a list of unique referenced filenames found in the rules of a list of
``license_matches``
"""
unique_filenames = []
for license_match in license_matches:
for filename in license_match['matched_rule']['referenced_filenames']:
... | 4340cc1bf9c00c206032743e98a86ececb42e2ff | 671,374 |
def section_break(qty: int=2) -> str:
"""Return multiple line break characters.
:param int qty: number of line break characters (default: 2)
:returns: multiple new line characters
:rtype: str
"""
return '\n' * int(qty) | 3ca9ba1f4c90c0e145d56ef7cb8d052f892fafcc | 671,377 |
import hashlib
def get_hash(text):
"""Return a hash of the given text for use as an id.
Currently SHA1 hashing is used. It should be plenty for our purposes.
"""
return hashlib.sha1(text.encode('utf-8')).hexdigest() | c95df6d389297b19aac49ca3a94ff8a44ac27620 | 671,383 |
def _select_class_label(top_k_rows, label_index):
""" Gets the class label based on majority voting
:param top_k_rows: a list in the form of [(dist, row),...]
:param label_index: the index in the rows where the label is located
:return: the most common label
"""
labels = []
for tuple in top... | 12d1f0ed1f6fe663e4e737243b85f02a4f0f124c | 671,385 |
def rotate3_inertia(RotMat,relInertia):
"""
Rotates an inertia tensor. A derivation of the formula in this function
can be found in Crandall 1968, Dynamics of mechanical and electromechanical
systems. This function only transforms an inertia tensor for rotations with
respect to a fixed point. To tra... | 1d12a001b42ad2054fa5f9a01c591091d36517d5 | 671,391 |
from typing import Union
from typing import Tuple
from typing import List
def increase_version_number(version_buffer: Union[Tuple[int, int, int], List[int]]) -> List[int]:
"""
Increases the number of the version with an increment of 0.0.1.
Args:
version_buffer: (Union[Tuple[int, int, int], List[i... | 15b6fca8a2652be39f6535206519486b55d64670 | 671,392 |
import math
def get_num_elements(n):
"""Return the number of elements from the number of possible pairwise combinations.
Essentially, the reverse of the previous function. We only consider the solution
for [-b + sqrt(b^2 - 4ac)] for practical reasons.
"""
return int(1 + math.sqrt(1 + (8 * n))) //... | d0cf6541798784773f2bf12003b9f26ece182813 | 671,394 |
def two_list_dictionary(keys, values):
"""Given keys and values, make dictionary of those.
>>> two_list_dictionary(['x', 'y', 'z'], [9, 8, 7])
{'x': 9, 'y': 8, 'z': 7}
If there are fewer values than keys, remaining keys should have value
of None:
>>> two_list_dicti... | af9a15e160036625a67f2086758951670a2e5771 | 671,396 |
def walk_to_s(tree, pos):
""" Takes the tree being searched and the position from which
the walk up is started. Returns the position of the first S
encountered and the path taken to get there from the
dominating NP. The path consists of a list of tree positions.
Args:
tree: the tree bein... | fd06eaa9594635c43e2b6319a8dd16631fe3db5b | 671,397 |
def digits(m) -> int:
"""Parses a phrase representing a digit sequence, returning it as an integer."""
return int(m.digit_string) | 297837223c0fd14c345246d58d50f23ef6354d09 | 671,398 |
def fedoralink_classes(obj):
"""
Get the original fedoralink classes of of a given object. They might be different to real classes (via getmro) because
fedoralink autogenerates types when deserializing from RDF metadata/Indexer data.
:param obj: an instance of FedoraObject
:return: list of class... | 9e280a4a15428e40c5973359c401f68159c84579 | 671,400 |
from datetime import datetime
def yearmonth(value):
""" Returns the input converted to a string in format YYYY-mm
Args:
value (datetime): date to convert
Returns:
output (str): formatted in YYYY-mm
"""
output = datetime.strftime(value, '%Y-%m')
return output | 9242c942f6843d6281f0d44fe9a3803005bb84df | 671,401 |
import requests
def url_check(url):
#Description
"""Boolean return - check to see if the site exists.
This function takes a url as input and then it requests the site
head - not the full html and then it checks the response to see if
it's less than 400. If it is less tha... | be058a1f3081bfda71c617e4a5b706ff2fc2bb40 | 671,403 |
def rule_separation(value: float, layer1: str, layer2: str):
"""Min space between different layers"""
error = f"min {layer1} {layer2} separation {value}um"
return f"{layer1}.separation({layer2}, {value})" f".output('{error}', '{error}')" | 6376ce117033c2269be5b74dfd6c083acd5f42b1 | 671,404 |
from textwrap import dedent
def txt(s: str) -> str:
"""
dedents a triple-quoted indented string, and strips the leading newline.
Converts this:
txt('''
hello
world
''')
into this:
"hello\nworld\n"
"""
return dedent(s.lstrip("\n")) | 6b5f78fd0b4bfb6e2fd57223d74f008f4ba83467 | 671,408 |
import re
def _clean_xml(xml_string):
"""Replace invalid characters with "?".
:type xml_string: str
:arg xml_string: XML string
:rtype: str
:returns: valid XML string
"""
invalid_chars = re.compile(r'[\000-\010\013\014\016-\037]')
return invalid_chars.sub('?', xml_string) | fec5b3735b1f51d98fd33faec42c2853eb73808e | 671,409 |
import functools
import warnings
def remove_parameters(removed_params,
reason,
end_version='future'):
"""Decorator to deprecate but not renamed parameters in the decorated
functions and methods.
Parameters
----------
removed_params : list[string]
... | 8eeff651359722af4894d6ea347b47cb1b7d2bd6 | 671,410 |
def degseq_to_data(degree_sequence):
"""
Takes a degree sequence list (of Integers) and converts to a sorted
(max-min) integer data type, as used for faster access in the
underlying database.
EXAMPLE::
sage: from sage.graphs.graph_database import degseq_to_data
sage: degseq_to_data... | 881ea34a958f0f4f4ec39957c1433d6aa3795424 | 671,412 |
def pivot_smooth_norm(df, smooth_value, rows_variable, cols_variable, values_variable):
"""
Turns the pandas dataframe into a data matrix.
Args:
df (dataframe): aggregated dataframe
smooth_value (float): value to add to the matrix to account for the priors
rows_variable (str): name o... | 15b0888b42600e41ab68927fb60430cb3a49cea8 | 671,414 |
def detect(code):
"""Detects if a scriptlet is urlencoded."""
# the fact that script doesn't contain any space, but has %20 instead
# should be sufficient check for now.
return ' ' not in code and ('%20' in code or code.count('%') > 3) | 2e7c932a65cf08a460a83c8f9f691142722cc241 | 671,418 |
def parse_voice_flags(flags):
"""Parses flags and returns a dict that represents voice playing state."""
# flags: [0-9]{8}
if flags[0] == '0':
return {'voice': 'stop'}
else:
return {'voice': {
'number': int(flags[1:3]),
'repeat': int(flags[4:6])
}} | dcbdab0108ea4d5950d16338ff369920195e4335 | 671,419 |
import warnings
def deprecated(replaced_by_func):
"""
This decorator is used to mark functions as deprecated. It also points
the user to the newer function that should be used instead.
"""
def wrap(f):
def new_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWa... | f37ed5bb1bfaf1a6dc4d4dc9f379315e0ae006de | 671,424 |
from pathlib import Path
def enterprise_1_11_artifact() -> Path:
"""
Return the path to a build artifact for DC/OS Enterprise 1.11.
"""
return Path('/tmp/dcos_generate_config_1_11.ee.sh') | 7a115360e94dc866b35b49df329b23547144fa05 | 671,427 |
def nocache(response):
"""Add Cache-Control headers to disable caching a response"""
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
return response | 4dff55d10245a51b131c2803f3cd109ab72d8bde | 671,430 |
from typing import List
def parse_pdv(text: str) -> List[List[str]]:
"""
Parse pipe delimited values.
"""
rows = []
lines = text.split('\n')
for line in lines:
row = []
cols = line.split('|')
for col in cols:
col2 = col.strip()
row.append(col2)... | e9dcf6a1cffcad1a4cbd8981fa3fcc105fa65103 | 671,431 |
def wall_dimensions(walls):
""" Given a list of walls, returns a tuple of (width, height)."""
width = max(walls)[0] + 1
height = max(walls)[1] + 1
return (width, height) | 8f11b07f6e50a04363caed8480f67383a322dce2 | 671,436 |
import math
def millify(n):
"""Abbreviate a number to nearest thousand, million, etc.
Adapted from: https://stackoverflow.com/a/3155023/10696164
Parameters
----------
n : int
The number to abbreviate
Returns
-------
millified : str
The number abbreviated to the neare... | f4b80ce0abb52e2f0985ced448d4d7daf686a6e8 | 671,437 |
def compile_create_table(qualified_name: str, column_statement: str,
primary_key_statement: str) -> str:
"""Postgresql Create Table statement formatter."""
statement = """
CREATE TABLE {table} ({columns} {primary_keys});
""".format(table=qualified_name,
... | 4828e65915e96d47149fdb2f83ce59976a3b5760 | 671,438 |
def insertionsort(list, descending=False):
"""
Takes in a list as an argument, and sorts it using an "Insertion Sort"-algorithm.
---
Args:
- list (list): The list to be sorted
- descending (bool): Set true if the list be sorted high-to-low. Default=False
Raises:
- T... | e6e995ba051a764845456ed02c63930fba662510 | 671,444 |
def GetArgsForMockCall(call_args_list, call_number):
"""Helper to more sanely get call args from a mocked method.
Args:
call_args_list: The call_args_list member from the mock in question.
call_number: The call number to pull args from, starting at 0 for the first
call to the method.
Returns:
... | 877c74760055484d64f4ca761316157498e82e23 | 671,445 |
def filter_transmission_events(selected_events, transmission_events):
"""Filter transmission_events for node-links of interest.
:param selected_events: Specified organism_group-organism_group
relationships inside nested dictionary.
:type selected_events: dict[str, dict[str, None]]
:param transmissi... | 89a1026a02b52ce5c457d58edf864321c2f73f43 | 671,453 |
async def raceclass() -> dict:
"""Create a mock raceclass object."""
return {
"id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"name": "G16",
"ageclass_name": "G 16 år",
"order": 1,
"event_id": "event_id_1",
"distance": "5km",
} | 1d2ec3921c5d20b6a13ad5945569e15e4950b272 | 671,454 |
import math
def mach_angle(M):
"""Calculate the Mach angle
:param <float> M: Mach #
:return <float> Mach angle, mu
"""
return math.asin(1 / M) | 7206357389cd24c5348f850ca3be335e1a3e93f0 | 671,460 |
def binarize_score(adata, score_label: str, threshold: float):
"""
Binarizes a provided key of an AnnData object by labeling values over a threshold as 'positive' or 'negative'.
Args:
adata: AnnData object to perform the binarization for
score_label: Label in adata.obs which will be used fo... | febaa211db11be45f859df3067b2034b1b651bb9 | 671,463 |
def _find_calframe(calframes, calpaths, values, calname, verbose=False):
""" Find the calibration frame and path from given dicts for dict values.
"""
if calframes is None:
calpath = None
calframe = None
else:
try:
calframe = calframes[values]
calpath = ca... | 0eedfa2d31a4e02a579841b13ad1fda872ade097 | 671,464 |
def recv_all(sock):
"""Receive data until connection is closed."""
data = b''
while True:
chunk = sock.recv(1024)
if not chunk:
break
data += chunk
return data | 9e412f2f0913311d82b0e31ed788f48fc77e45d2 | 671,466 |
def popis_pozici(pozice):
"""Popíše pozici pro lidi
např:
>>> popis_pozici(0, 0)
'a1'
"""
radek, sloupec = pozice
return "abcdefgh"[sloupec] + "12345678"[radek] | efb2df8715b30c04bfdeb82684084f2037ad5e7e | 671,470 |
def scale_data(Data,cscale,dscale,scaledown = True):
"""
Returns scaled data on both columns
Parameters
----------
Data: ndarray()
Array of data to be scaled
scaledown: bool
determines if data is scaled down or up
cscale: float
how much to multiply column 1 by
ds... | 34d24af1987a105564a6205c97288bf422d65cac | 671,473 |
def _normalize_input_name(input_name):
"""Remove :i suffix from input tensor names."""
return input_name.split(":")[0] | 3e75ae51a52a7c1ffe38dcf3483526af776d1b9c | 671,474 |
def rectangles_circum(n: int):
"""Return `n` fixed circumference rectangles, w + h = n"""
output = list()
for i in range(1, n + 1):
output.append((i, n - i + 1))
output.sort(key=lambda x: x[1], reverse=True)
return output | ba3eced573953e9cf4951ec91f29d28b5363bda9 | 671,478 |
def check_is_user_owner_of_plant(user, target_rich_plant):
"""Check if user is owner of Rich plant"""
if user.id == target_rich_plant.owner:
return True
else:
return False | 420308af7546c4a9fb22a7805ef5735b016fe99e | 671,485 |
def pullColumnAll(cursor, ticker, column_name):
"""
Retrieves specific column data for the given parameter (column_name)
Arguments:
cursor: cursor object for the database
ticker: ticker for which we are collecting data
column_name: specific column we want data from
Returns:
... | 9482d04e91198b651650c2263858d6134493f89a | 671,487 |
import re
def regex_search(regex, text):
"""
Do regular expression search for text.
:param regex: Regular expression for search, if none then disabled
:param text: Text where to search
:return: True if search finds something or regex is None
"""
if regex:
return re.search(regex, t... | b1a040fa6ecb6a0a8840ec0aad1d4ff6d2217c24 | 671,488 |
import re
def UpdateVerityTable(table, hash_offset):
"""Update the verity table with correct hash table offset.
Args:
table: the verity hash table content
hash_offset: the hash table offset in sector (each sector has 512 bytes)
Returns:
updated verity hash table content
"""
find_offset = re.c... | d45235dd0d201c269e299ba7fc2a0a60f8e84954 | 671,490 |
def read_lines(txt_name=""):
"""return the text in a file in lines as a list """
txt_name="./intermediate_file/detect_result/txt/"+txt_name
f = open(txt_name,'rU')
return f.readlines() | 2ec3a4f868775f0a682317405c4e10c9283ae5a3 | 671,491 |
def list_to_id_dict(base, attribute):
"""
Return a dict from an attribute in a list of dicts.
"""
ret = {}
for d in base:
ret[d[attribute]] = d
return ret | 4aa4686b273591984f08c91de6b8a9ec6fda9ffd | 671,505 |
def nth_replace(string, old, new, n=1, option='only nth'):
# https://stackoverflow.com/questions/35091557/replace-nth-occurrence-of-substring-in-string
"""
This function replaces occurrences of string 'old' with string 'new'.
There are three types of replacement of string 'old':
1) 'only nth' repla... | eedc655af4d2e10a1db755a5c8d0fbde2879ab64 | 671,507 |
def translate_inequality(param_name):
"""
Replace GT or LT at the end of a param name by '>' or '<' to
achieve Twilio-like inequalities.
"""
for suffix, replacement in (('GT', '>'), ('LT', '<')):
if param_name.endswith(suffix):
return param_name[:-len(suffix)] + replacement
... | 71594fedf9bd7e95607de61152ddd5cd931c3d25 | 671,508 |
def item_order(node):
"""
Extracts item order value from a project tree node.
:param Node node: project tree node.
:return: item order value or -1 if not present.
:rtype: int
"""
return node.item.order if node.item.order else -1 | d5094f505d1b69ec09a2279f86f3b0b382cff439 | 671,510 |
import math
def RayleighNumber(g, alpha, deltaT, nu, kappa, H):
"""
Calculate the Rayleigh number:
Ra = g alpha delta T H^3
-------------------
nu kappa
"""
return (g * alpha * deltaT * math.pow(H, 3.0)) / (nu * kappa) | d3e609b40ffdd8458dd3306f73b6d38c53f556a8 | 671,511 |
import typing
import warnings
def format_timestamp(ts: typing.Union[int, float]) -> str:
""" Function for formatting start/end timestamps. Somewhat more condensed
than the standard Pandas formatting.
:param ts: The timestamps in microseconds. Rendered as integers, since
`idelib` times... | 0b4ea26210b79a87cb49642f74a459961f761bbf | 671,513 |
def hex_to_int(color):
"""
:hex_to_int: converts a string hexadecimal rgb code to a tuple rgb code consisting or integer values for each
channel.
:param color: string | hex code for a color (does not include the hashtag)
:return: (r, g, b) | a tuple rgb code in integer form
... | f02ffca88cec926b530caa0fc20fc614dc4376a9 | 671,514 |
from typing import Any
from typing import Union
from typing import List
from typing import Dict
def get_level_lengths(
levels: Any, sentinel: Union[bool, object, str] = ""
) -> List[Dict[int, int]]:
"""For each index in each level the function returns lengths of indexes.
Parameters
----------
lev... | 0e19b8eea448fa75b5aefc0e892690b32c11c027 | 671,516 |
from typing import Dict
from typing import Any
def _generate_delete_response_with_errors(num_rows=1) -> Dict[str, Any]:
"""Generates a Content API delete response with errors.
Args:
num_rows: The number of rows to generate.
Returns:
A Content API response with errors (item not found).
"""
response... | 6f7a2d56a46abf06101bd5c094b2f874a8618e51 | 671,519 |
def two_sum(nums, target):
""" Given an array of integers, return indices of the two numbers such
that they add up to a specific target.
You may assume that each input would have exactly one solution, and you
may not use the same element twice."""
'''# Brute force O(n^2).
for i in range(len(nu... | 46fcccfd4cb56c0449fd9a6125e6dcfb1e725500 | 671,521 |
import re
def osFindValue(obj, searchTerm, searchMethod):
"""Internal helper method!
Generic search method to search a string or int for a searchTerm. Different search methods can be
provided for different ways of searching.
Args:
obj (str|int): The object that is being searched in
se... | 54a9008fdfcb78cc256c4d5c95cf097573e8ae36 | 671,522 |
def round_to_nearest_increment(x :float, tick_size : float = 0.25) -> float:
"""
rounds a price value to the nearest increment of `tick_size`
Parameters
-----------
x : float
the price value
tick_size: float
the size of the tick. E.G. for ES = 0.25, for CL = 0.01
"""
val = round(tick_size * r... | be4a51e5a8fa0d23fcce4f6b8d4f47494d0c9c07 | 671,524 |
def prob4(A):
"""Make a copy of 'A' and set all negative entries of the copy to 0.
Return the copy.
Example:
>>> A = np.array([-3,-1,3])
>>> prob4(A)
array([0, 0, 3])
"""
B = A.copy()
B[A < 0] = 0
return B | d4ae66b35d2061ab4c1981cc9d9e7fdd7cb14061 | 671,526 |
def calcSlope(y1, y2, x1, x2):
""" Calculate slope between two points """
if x2-x1 == 0:
slope = 0
else:
slope = (y2 - y1) / (x2 - x1)
return slope | e55b393512dcdd4fa193f0fc99fc1106d965a8b5 | 671,527 |
def generate_gcp_project_link(project_id: str) -> str:
"""Generates a Slack markdown GCP link from the given `project_id`.
Args:
project_id: The project ID of which to hyperlink.
Returns:
The generated hyperlink.
"""
return ('<https://console.cloud.google.com/home/' +
... | 756575347a1b69d9c230fd58a20cbbfc9c7cd3e2 | 671,531 |
import json
def load_json(fpath):
"""
Load a file from json
Args:
fpath (string or pathlib.Path object):
Path to a json file
Returns:
python object parsed from json
"""
with open(fpath, "r") as infile:
return json.load(infile) | 4b294be5bd76a0d47a792a90ee5c00d71de9e604 | 671,537 |
def to_string(text, encoding='utf8', errors='strict'):
"""Convert a string (bytestring in `encoding` or unicode), to unicode."""
if isinstance(text, str):
return text
return str(text, encoding, errors=errors) | af3937b434f7458086fd7734a45ef67b006c9e9f | 671,539 |
import struct
def parse_task_packet(packet, offset=0):
"""
Parse a result packet-
[2 bytes] - type
[2 bytes] - total # of packets
[2 bytes] - packet #
[2 bytes] - task/result ID
[4 bytes] - length
[X...] - result data
+------+--------------------+--... | 097e5975fdedfc2eefa3d33b66c15b51f3f82d21 | 671,540 |
def slope(first_point, second_point):
"""
Returns the slope between 2 points
:param first_point: first point (x,y)
:param second_point: second point (x,y)
:return: the slope
"""
return 0. if first_point[0] == second_point[0] else\
((float(first_point[1]) - float(second_point[1])) / ... | 8b8738af96279a112cc0cf01591d8d7bf5de429b | 671,541 |
def stateLabel(s, state_type):
"""Returns the short-hand label of the state.
Parameters:
s (State): a State object.
state_type (string): either 'e' or 'g' for excited state or ground state. The ground state is primed.
Returns:
string: "J=... | 30b65e12bcec505539f148b339e37a91a14222d0 | 671,547 |
def is_void(line):
"""Test if it is a void line"""
for i in line:
if i!=' ' and i!='\t' and i!='\n':
return False
return True | 839da53b6068dbcf2f082ae78a13045b74221bf0 | 671,551 |
def nested_lookup(n, idexs):
"""Function to fetch a nested sublist given its nested indices.
Parameters
----------
n: list,
the main list in which to look for the sublist
idexs: list,
the indices of the sublist
Returns
-------
list: sublist with given indices
"""... | ba4927e749be979fa297384fa9345db78243fa93 | 671,552 |
from typing import Any
from typing import TypeGuard
import numbers
def is_integer(x: Any) -> TypeGuard[int]:
"""Return true if x is an integer."""
return isinstance(x, numbers.Integral) and not isinstance(x, bool) | 98af5e48e0418605668159b3fdbd3dd45bbaaade | 671,554 |
from typing import List
def error_detail(error: Exception) -> List[str]:
"""Convert an Exception to API representation."""
return [type(error).__name__] + [str(a) for a in error.args] | c9b5e117ef7f6effc0f78b3f0f860f33f5ca9a34 | 671,564 |
def retrieve_pendulum_data(filename = "pendulum.dat"):
"""
Gets pendulum data from filename and outputs a 2d list of
output[0] = L and output[1] = T
"""
L_list = []
T_list = []
with open(filename, 'r') as infile:
for line in infile:
data = line.split()
try:
... | 8d8fdc0e7cb042881e6d1be5b2453985cf8a9481 | 671,565 |
def selection_sort(lst: list) -> list:
"""This is a selection sort algorithm implementation
Parameters
----------
lst: list
The unsorted list
Returns
-------
list
A sorted list in ascending order
References
----------
https://en.wikipedia.org/wiki/Selec... | 04875848f4dc412b8de2c2b703eef9e595262beb | 671,572 |
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
out = []
lens = (len(l) / n)
for i in range(0, lens):
out.append(l[i * n:i * n + n])
out.append(l[lens * n:])
return out[:-1] | e3d6c7e16c390de1692aa9cb1d128b3fa9ee7850 | 671,580 |
def find_cols(defline, header_char='='):
"""
return a sorted list of (start, end) indexes into defline that
are the beginning and ending indexes of column definitions
based on a reStructuredText table header line.
Note that this is a braindead simple version that only understands
header_chars an... | b0219b3465deb40251428493fb5a60a21d849667 | 671,581 |
def frompct(x):
"""
Convert Percent values to Decimal fraction
>>> frompct([1.0, 2.3, 80.0, -23.0, 100.0])
[0.01, 0.023, 0.8, -0.23, 1.0]
"""
return x / 100.0 | 29552d0f0fd1901ff28af0e6ea501f825d08935d | 671,582 |
def flatten(seq):
"""
>>> flatten([1 , [2, 2], [2, [3, 3, 3]]])
[1, 2, 2, 2, 3, 3, 3]
"""
# flatten fonction from C:\Python26\Lib\compiler\ast.py,
# compiler is deprecated in py2.6
l = []
for elt in seq:
t = type(elt)
if t is tuple or t is list or t is set:
... | a0db618aa2fca1077b13fa5d96314f327e91b56e | 671,583 |
def clean(angr_answer):
""" angr deals in byte strings, which are not always null-terminated, so
clean things up a bit. """
# angr can return non-ascii characters into stdout; we don't want to decode
# these, since we're assuming flags are ascii printable.
return angr_answer.decode("utf-8", errors="ignore") | 31ef1cef21bf381e6eecbb2857ca0d322c142b45 | 671,586 |
import math
def calculate_ratio(numerator_pair, denominator_pair):
"""
Computes a derived estimate and its MOE for the ratio between
the numerator and denominator arguments where the numerator
does not represent a subset of the denominator.
Args:
numerator (list): a two-item sequence with... | e8ee12f562baefb486f1cb10c4158dab90abff9f | 671,587 |
def json(path, _pod):
"""Retrieves a json file from the pod."""
return _pod.read_json(path) | d5d62b698fee0ed62400c6a40cbe76cd7319ec96 | 671,589 |
from typing import Callable
from typing import Tuple
from typing import Mapping
from typing import Union
def _find_one_tree(tree: dict,
func: Callable,
args: Tuple,
kwargs: Mapping,
) -> Union[dict, None]:
"""
Find one item in the spe... | a279176b6ec28ca3dc00c5a5b65c708e0dbd9bb6 | 671,591 |
from datetime import datetime
def str_date_to_date(date_from, date_to):
"""
Convert two dates in str format to date object
Format: YYYYMMDD
:param date_from: beginning of the interval
:param date_to: end of the interval
:return: from_date and to_date equivalent of given in date objects
""... | e4a8ae97e8af9fc3547f57b3671143c7da4a1de1 | 671,592 |
def percentage(part, total):
"""
Calculate percentage.
"""
return (part / total) * 100 | 308fb6cdadf531942a2ce9524d6721247214f016 | 671,596 |
def listget(lst, ind, default=None):
"""
Returns `lst[ind]` if it exists, `default` otherwise.
>>> listget(['a'], 0)
'a'
>>> listget(['a'], 1)
>>> listget(['a'], 1, 'b')
'b'
"""
if len(lst)-1 < ind:
return default
return lst[ind] | bfb88e6748b5a14e399783a7bf24777ec371b48d | 671,597 |
def unquoteNS(ns):
"""Un-quotes a namespace from a URL-secure version."""
ns = ns.replace('_sl_', '/')
ns = ns.replace('_co_', ':')
return ns | 9530cdc00baf54e6004202f893304b9b7c7cbaf2 | 671,598 |
def pre_process_data(linelist):
"""Empty Fields within ICD data point are changed from Null to 0"""
for index in range(len(linelist)):
if not linelist[index]:
linelist[index] = '0'
return linelist | 93ac3380d2c915639cfde0e8be06e756169c3956 | 671,601 |
def json_default(o):
"""
Defining the default behavior of conversion of a class to a JSON-able object.
Essentially makes a dictionary out of the class and returns it. Returns a list of
all its elements in case of a set.
:param o: The object to convert to JSON.
:return: JSON-able version of the c... | 40322266415905f88602f18d68412c84f1c97a46 | 671,603 |
import requests
def extra_metadata_helper(project_url, headers):
"""
Build extra metadata dict to help with other integrations.
Parameters
----------
project_url: str
The url to the project info
headers: dict
Figshare Authorization header
Returns
-------
Extra... | 6e8e01988bace721d277f1ac8689441b1a7abe1c | 671,605 |
def get_all_slots(cls):
"""Iterates through a class' (`cls`) mro to get all slots as a set."""
slots_iterator = (getattr(c, '__slots__', ()) for c in cls.__mro__)
# `__slots__` might only be a single string,
# so we need to put the strings into a tuple.
slots_converted = ((slots,) if isinstance(slot... | 97e4b78ea90f87f54ea86de8b2a8cab36952605f | 671,606 |
def min_peak(peak):
"""
Minimum peak criteria
Parameters
----------
peak : float
The minimum peak pixel value in a leaf
"""
def result(structure, index=None, value=None):
return structure.vmax >= peak
return result | ab2a168d689286f28ef767b99b99462bb75ccb69 | 671,612 |
def _exclude(term):
"""
Returns a query item excluding messages that match the given query term.
Args:
term (str): The query term to be excluded.
Returns:
The query string.
"""
return f"-{term}" | 7a52ea8fbebab1c4b1fc0c8e94f24ee43c9d5362 | 671,613 |
def make_QC_header(coverage, identity, length):
""" Create a header for the read QC file """
cols = "\t".join(["dataset", "read_ID", "passed_QC", "primary_mapped",
"read_length", "fraction_aligned", "identity"])
header = "\n".join(["# TALON run filtering settings:",
... | c9022bf60c3c6f10188fedef5a17d70ca0f1675a | 671,616 |
def is_float32(t):
"""
Return True if value is an instance of a float32 (single precision) type.
"""
return t.typecode == "f" | 5c5b2c06f1ce3b09d7a7006909a47bc24c67b6ee | 671,617 |
def join(left, right):
"""
Join two dag paths together
:param str left: A node dagpath or name.
:param str right: A node name.
:return: A dagpath combining the left and right operant.
:rtype:str
"""
dagpath = "%s|%s" % (left.strip("|"), right.strip("|"))
if left.startswith("|"):
... | 5397047bf78d15e40286922ea70a6d97680d33e9 | 671,618 |
def js_time(python_time: float) -> int:
"""Convert python time to js time, as the mephisto-task package expects"""
return int(python_time * 1000) | 74b2635c480b689523030970c98aa6df40f8fb75 | 671,621 |
def boxBasics(box):
"""basic statistics of box. Returns (mean,var)"""
mean=box.box_data.mean()
var=box.box_data.var()
return (mean,var) | 0e9493722637adef80e606225bd712546c998470 | 671,622 |
def generator_to_list(function):
"""
Wrap a generator function so that it returns a list when called.
For example:
# Define a generator
>>> def mygen(n):
... i = 0
... while i < n:
... yield i
... i += 1
# This is ... | cb4d6ad2af71347145f8483a506426bdbab9f9c0 | 671,623 |
from typing import Mapping
def strip_indexes(indexes):
"""Strip fields from indexes for comparison
Remove fields that may change between MongoDB versions and configurations
"""
# Indexes may be a list or a dict depending on DB driver
if isinstance(indexes, Mapping):
return {
k... | 37fd93c18c8201209794b6849fd3bc00175ab1d1 | 671,628 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.