content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _dfs(node, paths):
"""use depth first search to find all path activation combination"""
if node == paths:
return [[0], [1]]
child = _dfs(node + 1, paths)
return [[0] + _ for _ in child] + [[1] + _ for _ in child] | 93499b642f427da248fa261e8efc70eeed310a87 | 675,441 |
def print_tree(ifaces):
"""
Prints a list of iface trees
"""
return " ".join(i.get_tree() for i in ifaces) | 10e5d974497151d11983821bdc8bd831031134e9 | 675,442 |
from typing import Optional
import os
def _create_dir_or_throw(path: Optional[str]) -> str:
"""Creates a directory if necessary and if defined. If not defined, throw an exception."""
if path is not None:
# Make the directory if necessary
if not os.path.exists(path):
os.makedirs(pat... | 51c99d00340982fcaa419d352997175f60696cac | 675,443 |
from numpy import ndarray
def custom_function(data):
"""
Custom function that takes in the array of swarms cvs at a after iteration and does some custom transformation on them preserving the shape of the array.
This allows for example to make linnear combinations of distances the cvs. This de facto c... | 0695f6db4ffeeabd249df00c87d69fadfe2e8f9b | 675,444 |
async def async_setup_entry(hass, entry):
"""Set up Hassio Info from a config entry."""
for component in "sensor", "switch":
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True | 71312184ee129e8819ed83d4334e295daa4980b4 | 675,445 |
def autocov(v, lx):
""" Compute a lag autocovariance.
"""
ch = 0
for i in range(v.shape[0]-lx):
for j in range(v.shape[1]):
ch += v[i][j]*v[i+lx][j]
return ch/((v.shape[0]-lx)*v.shape[1]) | 4d05c29171ab92fe353e55e2f63a21a635e87059 | 675,446 |
def compute_score(segment, ebsd):
"""
Compute Dice measure (or f1 score) on the segmented pixels
:param segment: segmented electron image (uint8 format)
:param ebsd: speckle segmented out of the ebsd file (uint8 format)
:return: Dice score
"""
segmented_ebsd = ebsd >= 128
segmented_se... | b9c2e2db9dcca67d79e46dc5bd489e077918c602 | 675,447 |
def send_message(text, broker):
"""Add a message to the queue via a remote broker.
The message is of type C{text-message}.
@param broker: A connected L{RemoteBroker} object to use to send
the message.
@return: A L{Deferred} which will fire with the result of the send.
"""
def got_sessi... | ab5beeb3e111455ce474c9de22aa478f4583f9e1 | 675,448 |
def get_graphlist(gg, l=None):
"""Traverse a graph with subgraphs and return them as a list"""
if not l:
l = []
outer = True
else:
outer = False
l.append(gg)
if gg.get_subgraphs():
for g in gg.get_subgraphs():
get_graphlist(g, l)
if outer:
retu... | 1ca173bb3bf526593e1d10360cfe12e913a28b28 | 675,449 |
def get_default_nic():
""" Function to get the default network interface in a Linux-based system. """
# Source: https://stackoverflow.com/a/20925510/12238188
route = '/proc/net/route'
with open(route, mode='r') as fd:
# Removing spaces and separating fields
lines = list(map(lambda x: x.... | 2b1fb19fa75b661f05155f79f153c0162fd63308 | 675,450 |
def ReadDependencies(manifest):
"""Read the manifest and return the list of dependencies.
:raises IOError: if the manifest could not be read.
"""
deps = []
with open(manifest) as f:
for line in f.readlines():
# Strip comments.
dep = line.partition('#')[0].strip()
# Ignore empty strings.
... | 025ec893525acea9783525932a00823b24476db2 | 675,451 |
def build_chain(chain, cert, intermediate_certs, roots):
"""
Function used to build the chain of certificates from the base cert all the way to the root.
"""
chain.append(cert)
issuer = cert.issuer.rfc4514_string()
subject = cert.subject.rfc4514_string()
if issuer == subject and subject in roots... | 9882c23927b9e07af365e5a2f0962737d58c5e9f | 675,452 |
def heads(l):
"""
Returns all prefixes of a list.
Examples
--------
>>> heads([0, 1, 2])
[[], [0], [0, 1], [0, 1, 2]]
"""
return map(lambda i: l[:i], range(len(l) + 1)) | a39394ff83edb2254660a58269419825ad8813c4 | 675,453 |
def list_subtract(a, b):
"""Return a list ``a`` without the elements of ``b``.
If a particular value is in ``a`` twice and ``b`` once then the returned
list then that value will appear once in the returned list.
"""
a_only = list(a)
for x in b:
if x in a_only:
a_only.remove(... | d0557dbf0467e00c909d143c464f4af76eb130c6 | 675,454 |
def _patsplit(pat, default):
"""Split a string into an optional pattern kind prefix and the
actual pattern."""
if ':' in pat:
kind, val = pat.split(':', 1)
if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre'):
return kind, val
return default, pat | 9ff9eb6a8ba24df3a66ff74bd4bc6feda20d5eda | 675,455 |
def indent_level(level:int):
"""Returns a string containing indentation to the given level, in spaces"""
return " " * level | 09532674504a54569130739a8ef92aa37cd93f0b | 675,456 |
def _merge_series(ensure_keys=None, *series_lists):
"""Merge all series in `series_lists` in `data`"""
data = {}
ensure_keys = ensure_keys or []
assert isinstance(ensure_keys, list)
# Group series per date.
for series_list in series_lists:
for series in series_list:
for valu... | 0c0a027b782b3288ca1b93fbaaca9654d09e832e | 675,457 |
import difflib
def diff(a, b):
"""A human readable differ."""
return '\n'.join(
list(
difflib.Differ().compare(
a.splitlines(),
b.splitlines()
)
)
) | ad683cd696af6b2fd3412fb8c2956213950f5edf | 675,458 |
def load_partition_from_file(file_path, start, chunk_size):
"""
:param file_path:
:param start:
:param chunk_size:
:return:
"""
fp = open(file_path)
fp.seek(start)
temp = fp.read(chunk_size)
fp.close()
return [temp] | 1065bf16ddc8a2fcf60560363163d09d66dd01d8 | 675,459 |
def delete_label(name,repos, session, origin):
"""
Deletes label
:param name: name of the label to delete
:param repos: name of the repository where is the label
:param session: session for communication
:param origin: from where the label came from
:return: message code 200 (int)
"""
... | 66953007fa31810a15163c9aea1674c80882efa2 | 675,460 |
def render_tables(switch, concrete_class, title, table_format):
"""
Will create a table and return it as a string
with the title
:param table_format: format for displaying table
:param switch:
:param title: Title string for table
:param concrete_class: Concrete class to build the table for... | 5b218f8c00c005565f55d5f5fc0e8886c624c8bc | 675,461 |
import requests
import json
def get_json(response):
"""
Gets the json content out of a requests.response object. This functionality
is highly dependant on the version of the requests library used.
"""
if requests.__version__ >= "1.0.0":
return response.json()
elif requests.__version__ == "0.14.2":
return ... | 75a23c47e5038124fc1657ea66a442c3a92ba5a7 | 675,462 |
def horizontal_conf(hfile):
"""Reads psipred output .horiz file.
@param hfile psipred .horiz file
@return secondary structure string.
"""
result = ''
for line in hfile:
line_arr = line.strip().split(' ')
if line_arr[0] == 'Conf:' and len(line_arr) > 1:
result... | 43e79a3045278bd23c4ad303c052ae81c10c0097 | 675,463 |
def getData (tup):
"""
argument: tuple with tuple of int[0] and string[1] inside
return: int for smallest int, largest int, number of unique strings
"""
numbers = ()
words = ()
for elem in tup:
if elem[0] not in numbers and (type(elem[0])==int):
numbers = numbers + (elem... | 2ab4b4df027bdc3d785b0d467fb2929970cd6754 | 675,464 |
def pose_orientation_to_quaternion(msg):
"""converts a geometry_msgs/Pose to a quaternion tuple/list
e.g. to be used by tf.transformations.euler_from_quaternion
"""
return [msg.x, msg.y, msg.z, msg.w] | 6777e6a0f2a4168ca515a6e00485feb25ad6d065 | 675,466 |
def convertSnake(j):
""" this is convert FROM snake to json(camel) """
out = {}
for k in j:
new_k = k.split('_')
out[new_k[0] + ''.join(x.title() for x in new_k[1:])] = j[k]
return out | add2315dcf0ced4cfd70f5ad06506d0d5d49b47a | 675,467 |
def _proto_path(proto):
"""
The proto path is not really a file path
It's the path to the proto that was seen when the descriptor file was generated.
"""
path = proto.path
root = proto.root.path
ws = proto.owner.workspace_root
if path.startswith(root): path = path[len(root):]
if path.startswith("/"): ... | 43ee459f337ce85d9342f15dc675b80ffa8d962d | 675,468 |
def day_terms_for_user(duration, list_of_terms, searching_start_time, searching_end_time):
"""Find day mask of available time for meeting of duration x.
Arguments:
duration {int} -- duration of meeting in minutes
list_of_terms {query_set<Plan>} -- set of user plans in this day
searchin... | 6583e661acf2b1f0db03920375d34127944e6ad6 | 675,469 |
import time
def CreatePastDate(secs):
"""
create a date shifted of 'secs'
seconds respect to 'now' compatible with mysql queries
Note that using positive 'secs' you'll get a 'future' time!
"""
T=time.time()+time.timezone+secs
tup=time.gmtime(T)
#when="%d-%d-%d %d:%d:%d"%(tup[0],tup[1],tup[2],tup[... | bad798fb9e7588d1bbdbca9a814cf44fdbadb733 | 675,470 |
def chains():
"""Share default chain count."""
return 2 | be54fcaa620bfd4e1ff07ecfd563ddd8bac7fc2f | 675,472 |
def decompose(field):
""" Function to decompose a string vector field like 'gyroscope_1' into a
tuple ('gyroscope', 1) """
field_split = field.split('_')
if len(field_split) > 1 and field_split[-1].isdigit():
return '_'.join(field_split[:-1]), int(field_split[-1])
return field, None | 83dc5f235ab39119b21f1f0e125f2292f812a74c | 675,473 |
def mape(actual, forecast):
"""
Calculate mean absolute percentage error (MAPE)
:param actual:
:param forecast:
:return:
"""
if actual.shape == forecast.shape:
return ((actual - forecast) / actual).abs().sum() / actual.shape[0] | b4a7b2a67e3b14af8f0027f2b873077c3585fda6 | 675,474 |
def upd_p_fd_helm_sommerfeld_bc(p, k, dx):
"""
Pressure update of the 2D Helmholtz equation with Sommerfeld boundary
condition, see [Eqs. (4), (5), hegedus_atj2010].
:param p: updated pressure at time n+1, (Pa).
:type p: 2D numpy array of floats.
:param k: wavenumber (rad.m-1).
:type k: flo... | 30176acae012cc9bd2fe172fc8462da1e660d7bc | 675,475 |
from typing import Dict
import json
import os
def _maximum_startup_time() -> Dict[str, int]:
"""
Retrieve the maximum time an instance is allowed to need for start up.
:return: Dictionary mapping maximum startup time in seconds to the appropriate label
"""
return json.loads(os.environ['MAXIMUM_STA... | efbb80d7f541b377ffee9ff806153de4416fa527 | 675,476 |
import textwrap
def typed_table(typ, name, arr):
"""A table with a given type."""
text = '\n '.join(textwrap.wrap(', '.join(arr), 74))
# if it's not a pointer, append a space
if typ[-1] != '*':
typ += ' '
return '%s %s[] = {\n %s\n};\n' % (typ, name, text) | 0531eeabba3fa7151398841cf9236d7c9593328e | 675,477 |
def build_path(tmp_path_factory):
"""Provides a temp directory with various files in it."""
magic = tmp_path_factory.mktemp('build_magic')
file1 = magic / 'file1.txt'
file2 = magic / 'file2.txt'
file1.write_text('hello')
file2.write_text('world')
return magic | 4b715f51ad22985cd9cc6d48f96c15e303ff45b4 | 675,478 |
def run_model(model, X_train, y_train, X_test, y_test, params): # pylint: disable=too-many-arguments
"""Train the given model on the training data, and return the score for the model's predictions on the test data.
Specify parameters of the model with the provided params.
Args:
model (callable): ... | 332bcfe0f9b59c370ac5df784e4b443b02ccb23e | 675,479 |
def user_agrees(prompt_message: str) -> bool:
"""Ask user a question and ask him/her for True/False answer (default answer is False).
:param prompt_message: message that will be prompted to user
:return: boolean information if user agrees or not
"""
answer = input(prompt_message + ' [y/N] ')
re... | 5a9e92ac073d1801a733d0bd1407cba4a6b5f927 | 675,481 |
def _q_regs_2q_qasm_gate(qasm_gate):
"""Obtains a a list of tuples *[(q_reg, q_arg), (q_reg, q_arg)]* from a two qubit gate QASM string,
where *q_reg* is a quantum register name and *q_arg* is the quantum register index.
Args:
qasm_gate (str): a two qubit gate QASM string
R... | 85c9b0f2913e206b8a873c5818901266240782c6 | 675,482 |
def get(yaml_config, key_path, default_value=None):
""" Get a value in a yaml_config, or return a default value.
:param yaml_config: the YAML config.
:param key: a key to look for. This can also be a list, looking at
more depth.
:param default_value: a default value to return in case th... | 6eaab8c580f34d58558478a730e1279ab4778fcd | 675,483 |
def _known_populations(row, pops):
"""Find variants present in substantial frequency in population databases.
"""
cutoff = 0.01
out = set([])
for pop, base in [("esp", "af_esp_all"), ("1000g", "af_1kg_all"),
("exac", "af_exac_all"), ("anypop", "max_aaf_all")]:
for key i... | 23f2e1f8cc777a267810a438e6a15c0d07616f4f | 675,484 |
def error_margin_approx(z_star, sigma, n):
"""
Get the approximate margin of error for a given critical score.
Parameters
----------
> z_star: the critical score of the confidence level
> sigma: the standard deviation of the population
> n: the size of the sample
Returns
-------
The approximate margin o... | 4d2f18e8ee4a80e6e7e565ecd23c8c7413d35dce | 675,485 |
from numpy.distutils.misc_util import Configuration
import os
def configuration(parent_package='', top_path=None):
"""Creates `configuration` parameter for setup function.
Parameters
----------
parent_package : str, optional
top_path : str or None, optional
Returns
-------
config
... | 5471cf3fa4ca4cf4a7f7a627524ca6778c371ba6 | 675,486 |
import numpy
def deterministic(vec, n_nonz):
"""Calculate the indices of the n_nonz largest-magnitude elementss in vec
Parameters
----------
vec : (numpy.ndarray)
vector to compress
n_nonz : (unsigned int)
desired number of nonzero entries
Returns
-------
... | 7d3c8dec9d99b185784f65cb2082def404468104 | 675,487 |
def bmi(mass, height):
"""BMI: Body Mass Index
Params:
------
mass: int/float : mass of the person in kg
height:int/float: height of the person in m
Usage:
-----
>>> from health_indices import bmi
>>> bmi(mass=65,height=1.70)
>>>
"""
bmi_formula = mass // height ** 2
... | 3268c55cfd60d68406f2d8de72368ec739d54371 | 675,488 |
def find_user(collection, elements, multiple=False):
""" Function to retrieve single or multiple user from a provided
Collection using a dictionary containing a user's elements.
"""
if multiple:
results = collection.find(elements)
return [r for r in results]
else:
return coll... | 4e91f45673545bee25d912edcb20edff3dd8d1cb | 675,489 |
def is_novo(smi, d_data):
"""
smi: (str) SMILES strings
d_data: (dict) training + fine-tuning data
used, where keys are the SMILES strings.
Note: we use a dict as it's faster to search
"""
if smi in d_data:
return False
else:
return True | c2931efadab8d207d57d8dd3d57a14d7d02eac67 | 675,490 |
import os
def config_path():
"""Returns the path to the config spreadsheet file."""
return os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.csv') | 9d248e98383d43f9a92bf4d73e01bc18c81d1ed3 | 675,492 |
def _conformal_iscore_interval(predictions, score):
""" Compute the inverse of the non-conformity score defined in conformal_score_quantile.
The goal is that conformal_iscore_quantile(predictions, conformal_score_quantile(predictions, labels))) = labels
Args:
predictions: array [batch_size, 2]... | cc16dfbb8e2e37fc15c7c9097c4bf16ada15aa2e | 675,494 |
def extract_name_and_id(user_input):
"""Determines if the string user_input is a name or an id.
:param user_input: (str): input string from user
:return: (name, id) pair
"""
name = id = None
if user_input.lower().startswith('id:'):
id = user_input[3:]
else:
name = user_input... | feb84b022e626bae091bb28e8d3f316bdbf1ba3d | 675,496 |
def selection_sort(integer_list):
"""
The selection sort improves on the bubble sort by making only one exchange for every pass
through the list. In order to do this, a selection sort looks for the largest value as it makes
a pass and, after completing the pass, places it in the proper location. As wi... | 5558fb9f754a1977ef6cd006022948e10e0438c0 | 675,497 |
def minsort(lst):
""" Sort list using the MinSort algorithm.
>>> minsort([24, 6, 12, 32, 18])
[6, 12, 18, 24, 32]
>>> minsort([])
[]
>>> minsort("hallo")
Traceback (most recent call last):
...
TypeError: lst must be a list
"""
# Check given parameter data type.
if... | 915c12c9a46e80c04ca04e209a99eea1a726af00 | 675,498 |
def lis_dp(array):
"""
Returns the length of the longest increasing sub-sequence in O(N^2) time.
This is not fast enough to pass with the HackerRank time constraints.
"""
n = len(array)
if n == 0:
return 0
dp = [1] * n
# Let F(i) be the LIS ending with array[i]. F[i] = max({1 +... | ffa1d60a12f0a5d6a6ebb2666260a0d62a5b9216 | 675,499 |
import logging
def possible_int(arg):
"""Attempts to parse arg as an int, returning the string otherwise"""
try:
return int(arg)
except ValueError:
logging.info(f'failed to parse {arg} as an int, treating it as a string')
return arg | 2d842ca29fa057f0601e44aaea91e7ef8d71738b | 675,500 |
import random
def __generate_2d_points(agents, mode, sigma):
"""Generates a list of 2d coordinates subject to
various distributions."""
points = {}
# normal distribution, 1/3 of agents centered on (-0.5,-0.5),
# 2/3 of agents on (0.5,0.5)
if mode == "twogroups":
f... | caa345b02d9b87cd3c57bd74a12a2bf7555da5e6 | 675,501 |
def find_two_sum(arr, target):
"""
Finds the two (not necessarily distinct) indices of the first two integers
in arr that sum to target, in sorted ascending order (or returns None if no
such pair exists).
"""
prev_map = {} # Maps (target - arr[i]) -> i.
for curr_idx, num in enumerate(arr):
... | dc444add33e01e1ca59f8e08977dffc54e433097 | 675,502 |
import ast
def read_data_from_txt(file_loc):
"""
Read and evaluate a python data structure saved as a txt file.
Args:
file_loc (str): location of file to read
Returns:
data structure contained in file
"""
with open(file_loc, 'r') as f:
s = f.read()
return ast.l... | e974b50c2a9f691cb365edf1adef7bbf1bf3b638 | 675,503 |
def correct_resnums(initial_pose, reslist, final_pose):
"""Get rosetta numbering for final_pose from a reslist for the
intial_pose"""
corrected_residues = []
for res in reslist:
pdbnum = initial_pose.pdb_info().pose2pdb(res)
pdbres = int(pdbnum.split(' ')[0])
pdbchain = pdbnum.sp... | c9b6a03de8904955c5e16a273a566ff119de9068 | 675,504 |
import math
def bounding_hues_from_renotation(hue, code):
"""
Returns for a given hue the two bounding hues from
*Munsell Renotation System* data.
Parameters
----------
hue : numeric
*Munsell* *Colorlab* specification hue.
code : numeric
*Munsell* *Colorlab* specification ... | 72d247c9418b1c6e51ec56e6e10f79203631ae78 | 675,505 |
def parse(sudoku_string : str):
"""
celem funkcji jest przyjecie wielolinijkowego sudoku w postaci 9 linijek postaci
123000789,
gdzie liczby oznaczaja konkretne wartosc a 0 wartosci puste
zwracana jest wewnetrzna reprezentacja takiego sudoku jako tablica 2 wymiarowa
"""
lines = sudoku_string... | ccfb576e57c8114e24e893640763d8f61e92327a | 675,506 |
def df_drop(styles, col, item):
"""
This function drops certain columns
input: styles, dataframe
col, the item we want to drop in this coloumn
item, which item we want to drop
"""
for i in item:
styles = styles.drop(styles[styles[col] == i].index)
return styles | 64ccc80736849662412ef4dc6107ef8faffbe8ed | 675,507 |
def get_div_winners(df_sim):
"""Calculate division winners with summarised simulation data
:param df_sim: data frame with simulated scores summarised by iteration
:return: data frame with division winners per iteration
"""
return (
df_sim
.sort_values(by=['tot_wins', 'tot_pts'], ascending=[False, Fal... | ddaa111ae73209fb8e6c369ce0cecda3a3dd625d | 675,508 |
import math
def calculateSaleReturn(S,R,F,T):
"""
E = R(1 - ((1 - T / S) ^ (1 / F))
"""
if (T > S):
return 0
if F == 100:
return R*T/S
return float(R) * ( 1.0 - math.pow(float(S-T)/float(S) , (100.0/float(F)))) | 240a1a3427268045617d493c76b4efc195b59d9b | 675,509 |
import typing
import os
def find_project_directory(subdirectory: str) -> typing.Union[str, None]:
"""
Finds the root project directory from a subdirectory within the project
folder.
:param subdirectory:
The subdirectory to use to search for the project directory. The
subdirectory may ... | 8e58cbc17d7dda0f8e874f8d93c7aa006406cb3b | 675,510 |
import argparse
def get_args():
"""
add and parse program arguments
"""
args_obj = None
parser = argparse.ArgumentParser(description='This tool is for installing mellanox-os')
parser.add_argument('-s', '--switch-name', help='Switch name to connect', required=True)
parser.add_argument('-u',... | d8e68e54abd97d77277e6cf6d4a57e4f88bb709f | 675,511 |
def swap_count(list1: list, list2: list) -> float:
"""count the number of swaps required to transform array1 into array2"""
L = list(list2)
swaps = 0
for element in list(list1):
ind = L.index(element)
L.pop(ind)
swaps += ind
return swaps | 8a9d1ce56b48821128730a20952c0ae2920ce029 | 675,512 |
import sys
def find_possible_velocities(
target: tuple[int, int, int, int],
search_space: int = 200,
max_expected_y: int = 10000,
) -> tuple[int, int]:
"""Find initial velocities that would end up in the target area
Args:
target (tuple[int,int,int,int]): target area (x_start, x_stop, y_st... | 1df8305c154f0d33226e6e6558764ca522fea43e | 675,513 |
import os
def get_filename (directory, post, keep_names=False):
"""
Returns the path where the downloaded image should be written.
"""
return os.sep.join ((
directory, post.board, str(post.thread),
(post.image.filename if keep_names else str(post.image.tim)) + \
post.image.... | 178338862bccbc886a78221375aa466790463000 | 675,514 |
def _construct_version(major, minor, patch, level, pre_identifier, dev_identifier, post_identifier):
"""Construct a PEP0440 compatible version number to be set to __version__"""
assert level in ["alpha", "beta", "candidate", "final"]
version = "{0}.{1}".format(major, minor)
if patch:
version +=... | 9cf26af2250a2fed80b6e63390abc883dcba232b | 675,515 |
def process_one_example(tokenizer, label2id, text, label, max_seq_len=128):
"""
convert the text and label to tensor, result:
text: [101 3946 3419 4638 4413 7339 5303 754 ...]
mask: [1 1 1 1 1 1 1 1 ...]
segment_ids: [0 0 0 0 0 0 0 0 0 0 0 0 ...]
label: [0 26 28 0 0 0 0 ...]
"""
text... | cdbd27f14d1fd35afdd717d3ee66bcbb1192a64c | 675,517 |
def _display_metadata(self):
"""Called when Contingency objects are printed"""
header = f"<xskillscore.{type(self).__name__}>\n"
summary = header + "\n".join(str(self.table).split("\n")[1:]) + "\n"
return summary | 6a675a23d0a4476664b95c1d9fee1f4b7fc90172 | 675,518 |
def channel_parser(channel):
"""Parse a channel returned from ipmitool's "sol info" command.
Channel format is: "%d (%x)" % (channel, channel)
"""
chan, xchan = channel.split(' (')
return int(chan) | d2a5cb20b9e44bbbc6c617706e952b333db5b2b4 | 675,519 |
def dict_generator(field1, field2, field3, field4, field5):
"""Generate dictionary
Generate the dictionaries from the given field information.
Args:
field1 (list): [first name, last name]
field2 (int): age of the patient_dict
field3 (str): Gender of the patient
... | 97a07e8093d654533e484e2b2e62144cef9b23b6 | 675,520 |
def find_col(table, col):
"""
Return column index with col header in table
or -1 if col is not in table
"""
return table[0].index(col) | b6fd7f6e9e3431d042b488ca737c4e7883cf7018 | 675,521 |
import torch
def loss_fn(outputs, labels):
"""
Compute the cross entropy loss given outputs from the model and labels for all tokens. Exclude loss terms
for PADding tokens.
Args:
outputs: (Variable) dimension batch_size*seq_len x num_tags - log softmax output of the model
labels: (Var... | 9f53f0879db5853e516358336081f144e51272d1 | 675,522 |
def get_taskToken(decision):
"""
Given a response from polling for decision from SWF via boto,
extract the taskToken from the json data, if present
"""
try:
return decision["taskToken"]
except KeyError:
# No taskToken returned
return None | 5af140b26eb8af1fa93fd53e83634ecdd232a33a | 675,523 |
from typing import OrderedDict
def broadcast_variables(*variables):
"""Given any number of variables, return variables with matching dimensions
and broadcast data.
The data on the returned variables will be a view of the data on the
corresponding original arrays, but dimensions will be reordered and
... | 00eda392c2ae791a34c02a613ab5b3d6a2a40624 | 675,524 |
def suma(a,b):
"""Esta función recibe dos numeros y devuelve la suma"""
return a+b | 2dda1fb821e1346ecd1ad689223eddaceb720243 | 675,525 |
def keys2str(D):
"""Keywords cannot be unicode.""" # unnecessary for Python 3?
E = {}
for k, v in D.items():
E[str(k)] = v
return E | 1828199f09e9acb5aa457e682f61d57d58450d1e | 675,527 |
def _get_excel_engines():
"""
Creates a dictionary of supported engines for pandas.read_excel.
Returns
-------
excel_engines : dict(str, str)
A dictionary of file extensions (as given by pathlib.Path().suffix),
and the corresponding engine to use in pandas.read_excel.
Notes
... | e7a9d8ee1f0f75d3ff9b355c826ecf3134841d79 | 675,528 |
def chunkFair(mylist, nchunks):
""" Split list into near-equal size chunks, but do it in an order like a draft pick; they all get high and low indices.
E.g. for mylist = [0,1,2,3,4,5,6], chunkFair(mylist,4) => [[0, 4], [1, 5], [2, 6], [3]]
"""
chunks = [None]*nchunks
for i in range(nchunks):
... | 901005a4b9de39efd09c685b0111f30f9eca9679 | 675,529 |
def unionRect(rect1, rect2):
"""Determine union of bounding rectangles.
Args:
rect1: First bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
rect2: Second bounding rectangle.
Returns:
The smallest rectangle in which both input rectangles are fully
... | 1c89439efb082159400acd25396cbf43d7ea1ddf | 675,530 |
def is_int(obj):
"""
True & False is not considered valid integers even if python considers them 1 & 0 in some versions
"""
return isinstance(obj, int) and not isinstance(obj, bool) | 05ba5857699a5d2925409f604db5310a7f080e1e | 675,531 |
import math
def inverse_sigmoid(y):
"""A Python function for the inverse of the Sigmoid function."""
return math.log(y / (1 - y)) | f2f851b23dfd6fddb2ecdfa83aead3b3f880472a | 675,533 |
import stat
import os
def filemode( path ):
"""
Returns the integer containing the file mode permissions for the
given pathname.
"""
return stat.S_IMODE( os.stat(path)[stat.ST_MODE] ) | ff34482eef5644808934c1d4d0e66e58a652740d | 675,534 |
def put_object_string(swift, container, object_name, contents):
"""Put the object contents as a string """
try:
contents = contents.decode('utf-8')
except AttributeError:
pass
return swift.put_object(container, object_name, contents) | f675134dc61a490b811ac1381cfb7b1529002958 | 675,535 |
import os
def project_dir(base):
"""Project dir."""
return os.path.abspath(
os.path.join(
os.path.dirname(__file__),
(os.path.join(*base) if isinstance(base, (list, tuple)) else base)
).replace('\\', '/')
) | d9ac5bc0b65725bc34c4374b5736cfc82db45539 | 675,536 |
import math
def image_entropy(img):
"""
calculate the entropy of an image
"""
hist = img.histogram()
hist_size = sum(hist)
hist = [float(h) / hist_size for h in hist]
return -sum([p * math.log(p, 2) for p in hist if p != 0]) | d5e4a6134eeb3d1fb65d19d60995ffa1f4c1c72c | 675,537 |
from typing import Sequence
def change_coin_naive(amount: int, denominations: Sequence[int], index: int) -> int:
"""
Time Complexity: Exponential
"""
if amount == 0:
return 1
if amount < 0 or index < 0:
return 0
count = 0
if amount >= denominations[index]:
count ... | 9a42cff2f5bcb51f6eb700fa5cf611345677f275 | 675,538 |
def _double_list_check(XX):
"""
If a list, return as list of lists
"""
if(not(any(isinstance(el, list) for el in XX))):
XX = [XX]
return XX | de2f297f5f9fe82de806429948ad5379217bc53c | 675,540 |
def admensionality(x, minv, maxv):
"""
Funcao para reducao da dimensionalidade de um valor
"""
out = (x-minv)/(maxv-minv)
return out | 064099983141af3f69b909c61dff9d0d41f086ae | 675,541 |
import os
def absjoin(*args):
"""Return the absolute path to the joined arguments."""
return os.path.abspath(os.path.join(*args)) | 00c7ca183bdb4fcdfe8de602a2c6f2bf674526b8 | 675,542 |
def strip_alias_prefix(alias):
"""
Splits `alias` on ':' to strip off any alias prefix. Aliases have a lab-specific prefix with
':' delimiting the lab name and the rest of the alias; this delimiter shouldn't appear
elsewhere in the alias.
Args:
alias: `str`. The alias.
Returns:
... | 2a38083ecbd313a2bdfea88cd2c613b5b3074cdc | 675,544 |
def check_permutation_2(string1, string2):
"""
Do not use Counter, use dictionary instead
"""
# First, check whether string lengths are equal (EARLY EXIT)
if len(string1) != len(string2):
return False
# Key: [string], Value: [Int] E.g. {"a":5, "b": 10, "c":4}
char_dictionary = {}
... | 693230029e4894959586223bf4ed53bac25821d2 | 675,546 |
import os
def ensure_dirs_exist(path):
"""
Simple helper that ensures that any directories specified in the path are
created prior to use.
Arguments:
path (str): the path (may be to a file or directory). Any intermediate
directories will be created.
Returns:
... | 8e0850bc4a65f2b0de4117ad8c1ee9fc84581471 | 675,547 |
from typing import Dict
import subprocess
import re
def _get_conda_list_package_versions() -> Dict[str, str]:
"""Returns the versions of any packages found while executing `conda list`."""
list_output = subprocess.check_output(["conda", "list"]).decode().split("\n")
package_versions = {}
for output... | 6f394e903837ae3316f3608c4bbb8b02bda89e70 | 675,548 |
def merge_results(result1, result2):
"""
Merge two dictionaries to one. It merges the values of the same tag.
The format of the dictionaries is:
{filename: {tag1: [..], tag2: [..],}
:param result1: A dictionary to merge.
:param result2: A dictionary to merge.
:return: The merged result d... | 769cb2a5f6686654de41272882c857d0fd32d38a | 675,549 |
def logout(api_client):
"""
remove JWT from cookie
"""
api_client.token = None
api_client.refresh_token = None
return True | 242c5b40911b10a367c4486b47bdb7e408d22315 | 675,550 |
def _ping(req):
"""view to test aliveness of apps."""
return {'status': 'ok'} | 560ded68a21e38b03f0c5f62e2935f374e636bcc | 675,552 |
import re
def get_msvc_runtime_library_re_pattern():
"""Regex pattern for identifying linked msvc runtime libraries
For efficiency, call this function once and use the compiled regex in any subsequent calls.
"""
return re.compile('.*/DEFAULTLIB:(\w*)') | d0ab3b5cbdbfef06c83aa86241bb98be38e0b2d1 | 675,553 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.