content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def exist_in_list(word_list, lst, from_begin):
"""Return dictionary of count of words from word_list on lst
:param word_list - list of string
:param lst - list of char
:param from_begin - boolean
:return dictionary"""
result = {}
if not from_begin:
lst = lst[::-1]
substring_stri... | 5a6fb9a5f2732c57ed2928d4f64f1e50076a29b2 | 39,750 |
def predict_step(model, inputs):
"""A single predict step."""
logits = model(inputs, train=False)
return logits | 0ff4ec680bdd17eb11a88eee221c4d30a9f3e9a4 | 39,751 |
def _get_current_engagement(d, assignment):
""" helper for WTAP solver
Calculates the current engagement
:param d: device
:param assignment: class Graph.
:return:
"""
if d in assignment:
for d, t, v in assignment.edges(from_node=d):
return t
return None | 18c9f310080a9ffe0d072590f516018442440b87 | 39,753 |
def strip_chr(chr):
"""Removes the 'chr' prefix if present.
Args:
chr (str): The chromosome.
Returns:
str: The chromosome without a 'chr' prefix.
Examples:
>>> strip_chr('22')
'22'
>>> strip_chr('chr22')
'22'
"""
return chr[... | 39a833dda595140a38226ce5b52dd3b8fd97337d | 39,757 |
def recording_in_db(rec_id, con):
"""
Returns True if the recording with ID rec_id is already in the database
pointed to by "con"
Parameters
----------
rec_id : int
ID of th3 recording.
con : SQLite3 connection
Connection to open DB.
Returns
-------
Boo... | 8954ec39899e0d68483933cba66a2923c4b6d4f0 | 39,759 |
def centre_table(t):
"""Centre cells in a Markdown table."""
lines = t.split("\n")
return t.replace(lines[1], "|".join([":-:"] * (lines[0].count("|") - 1))) | e75daec6ba10bb7a361bb1fcd588673b6ad52336 | 39,760 |
def _format_names(name: str) -> str:
"""Format dictionary key names to be human friendly.
Args:
name (str): The Unicode type name.
Returns:
str: The formatted Unicode type name.
"""
return name[0].upper() + name[1:].replace("_", " ") | 5256bfad00079f658ea2a8a7d95f4fbea39cb6a1 | 39,762 |
import os
import subprocess
def default_branch(repository, remote='origin'):
""" Detect default branch from given local git repository """
head = os.path.join(repository, f'.git/refs/remotes/{remote}/HEAD')
# Make sure the HEAD reference is available
if not os.path.exists(head):
subprocess.run... | 643d0e71fda055c4ba711268989ed3de7f3be893 | 39,763 |
import torch
def check_torch_version_for_proj_in_lstm():
"""
proj_size parameter is supported in torch.nn.LSTM layer started from 1.8.0 torch version
"""
me = False
version = torch.__version__
major, minor, micro = version.split(".")
if int(major) > 1:
me = True
elif int(majo... | 5bd4e4742c1d6aae69ed580e046d717bc43b1574 | 39,764 |
import requests
def requests_patch(**kwargs):
"""Patch for any requests method."""
def req(url):
if not url.startswith('http'):
raise requests.exceptions.MissingSchema
class Response(object):
def __init__(self, **kwargs):
for key, value in kwargs.items(... | 0d84688ab10b01d7475351dc2518789dca04e33e | 39,766 |
import time
def yearMonthDay():
"""
:returns: the year-month-day as 20200403
"""
return time.strftime("%Y%m%d") | cdd80f2c358bc2e1064c15fbbdfd25c386980238 | 39,768 |
def map_lbls_id(skills, label, id, lookup):
"""Map the skills labels to the skills ids
Args:
skills (df): skills dataframe
label (str): col to create, either 'class_lbl' or 'subclass_lbl'
id (str): col to use for mapping, either 'class_id' or 'subclass_id'
lookup (dict): to use ... | 14751efb08aa0cbee4844a25c0119fb8e29ffe2e | 39,769 |
import math
def rad2deg(rad):
""" from radian to degree """
return rad * 180 / math.pi | ee576c3c424e77690e40dc3c21623701737a8327 | 39,770 |
def num_or_string(v, d=None):
"""Loads a value from MO into either an int or string value.
String is returned if we can't turn it into an int.
"""
try:
return int(str(v))#.replace(',', '')
except (ValueError, TypeError):
try:
_value = float(str(v).replace(',', '.'))
if _value == 0:
... | 5dff9592e81dcdaa59858407fe8426c8f606e338 | 39,771 |
import typing
import struct
def unpackMIMEFieldImplHeap(heap: bytes, start: int, unused_http: object) -> typing.List[int]:
"""
Unpacks a MIMEFieldImpl from the given raw byte heap.
Returns a list of the values of the data members of the stored object.
"""
fmt = "4xL4II4i?PIP"
fmt += "3PhH4s"*16
return list(st... | 61ec683ca5b112fb1028853adb0b8ecfcdd12f35 | 39,773 |
def unprefix(prefix, d, all=False):
"""
Returns a new dict by removing ``prefix`` from keys.
If ``all`` is ``False`` (default) then drops keys without the prefix,
otherwise keeping them.
"""
d1 = dict(d) if all else {}
d1.update((k[len(prefix):], v) for k, v in d.items() if k.startswith(pref... | 81fc47898f9bde8c42b107b5838a3af6bfe3d7f5 | 39,774 |
def test_collision(snake_box, snake_pixels):
"""Function to detect box or snake collision."""
height, width = snake_box.getmaxyx()
# If collision with wall, only head would collide.
head = snake_pixels[-1]
if (head[0] <= 0 or head[0] >= width):
return True
if (head[1] <= 0 or head[1] >= ... | f035b44b8ad4664bad977243ceab38ea058e6d3b | 39,775 |
from pathlib import Path
from datetime import datetime
def get_recording_start(fname):
"""parse the recording date from the emg filename"""
parts = Path(fname).stem.split(" ")
subject = parts[0][0:4]
recdate = datetime.strptime(parts[1], "%Y-%m-%d_%H-%M-%S")
return recdate | 598c76228496e6e5b46888ea30b42eb908194220 | 39,779 |
def max_simple_divider(simple_numbers, divs):
"""
Наибольший простой делитель
:param simple_numbers: list
:param divs: list
:return: int
"""
return max(list(filter(lambda x: x in simple_numbers, divs))) | fc09cf95e5f699377168732338f0a46b4e6b55ce | 39,780 |
import struct
def _convert_filetime_to_timestamp(filetime):
"""
Windows returns times as 64-bit unsigned longs that are the number
of hundreds of nanoseconds since Jan 1 1601. This converts it to
a datetime object.
:param filetime:
A FILETIME struct object
:return:
An integer... | 4e4f21b1f75ab367e66a136a58dc615c1d40cc5e | 39,781 |
from typing import Any
def is_list(input_: Any) -> bool:
"""
Check type of :code:`input`
:param input_: Any arbitrary input
:type input_: Any
:return: True if :code:`input` is a :code:`list` else False
:rtype: True
"""
return isinstance(input_, list) | 12665e2e8bdc6c001860daa7b2513d52c1564b9c | 39,782 |
async def redirect_to_project() -> str:
"""Redirects the root path to the project website"""
return 'https://ibm.github.io/arcade' | d318b5ecc4896a0ae1d990b354c1e11fa0c30a1e | 39,783 |
import re
def acquire_star_rating(soup):
"""
Take a BeautifulSoup content of a book page.
Return the rating of the book.
"""
review_rating = soup.find(
class_=re.compile("^star")
)['class'][1]
return review_rating | f25ab2515a8c96957eb6b5154295cdcb811eae4f | 39,784 |
def get_region(b):
"""Tries to get the bucket region from Location.LocationConstraint
Special cases:
LocationConstraint EU defaults to eu-west-1
LocationConstraint null defaults to us-east-1
Args:
b (object): A bucket object
Returns:
string: an aws region string
""... | 8a773d20348b3fc01f7bd426765546069f79f9d8 | 39,785 |
def safeFilename(filename):
"""Return a filename with only file safe characters"""
validChars = '-_.()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
return ''.join(c for c in filename if c in validChars) | 450f392a1222741782c2b9c4d63d5757b534d6ed | 39,786 |
def dist(graph, i, j):
"""
Returns the weight of edge from i -> j or vice-versa.
The graph is undirected.
Paramters
---------
i : int
j : int
graph : Dict
"""
try:
i, j = i % 8, j % 8
if i < j:
return graph[i][j-i-1]
elif j < i:
re... | 533ad111def2f0fcf8098e143ac4dd0976a82c08 | 39,787 |
def sorter(entries):
"""order a list of entries by descending date first and then by name
alphanumerically"""
return sorted(
sorted(entries, key=lambda x: x["name"]),
key=lambda x: x["date"],
reverse=True,
) | 697981b6b00f05e208fd2487c9ce56deef285d86 | 39,788 |
def tmpdirpath(tmpdir):
"""Convenience fixture to get the path to a temporary directory."""
return str(tmpdir.dirpath()) | 4adf46e970fcdd00250af4d03db1b6b632bb3260 | 39,790 |
def shapeFromHdr(hdr, verbose=0):
"""
return "smart" shape
considering numTimes, numWavelenth and hdr.ImgSequence
if verbose:
print somthing like: w,t,z,y,x ot z,y,x
"""
zOrder = hdr.ImgSequence # , 'Image sequence. 0=ZTW, 1=WZT, 2=ZWT. '),
nt, nw = hdr.NumTimes, hdr.NumWaves
n... | b3a446e48da6c72c48489c09299b8e8d2a01be59 | 39,791 |
import logging
def dict_msg_processor(logger: logging.Logger, name: str, event_dict: dict):
"""Позволяет переложить конвертацию данных в строку на Formatter библиотеки logging. Данная возможность полезна при
внедрении structlog в приложение, где часть логов уже пишется при помощи библиотеки logging.
P.S.... | 6050cb604e7289976d10a28869d26a18ff35709c | 39,792 |
def bytes_to_oid(data):
"""Convert bytes to OID str"""
values = [ord(x) for x in data]
first_val = values.pop(0)
res = []
res += divmod(first_val, 40)
while values:
val = values.pop(0)
if val > 0x7f:
huges = []
huges.append(val)
while True:
... | 252c5d2fba14f883cb3d1faf55fa993241b0b043 | 39,793 |
def _compute_pmf(gen_graph_distr):
"""
Compute the probability mass function (PMF) of graphs. It can be seen as a normalization between 0 and 1, where
each count is converted into a probability.
:gen_graph_distr: The distribution of generated graphs. It is a dictionary where, for each entry (key, value), the
key... | d2ec2e50387464782910e52e4ea464752c20b9f1 | 39,794 |
def remove_duplicate_QUBO(QUBO_storage):
"""
De-duplicates the QUBO storage list
Parameters
----------
QUBO_storage : list
List of QUBOs (each QUBO is a dictionary).
Returns
-------
unique : list
de-duplicated list.
"""
unique = []
for a in QUBO_storage:
... | 7c0ece71be1def18de60fb1d72f69379dc0cf3a8 | 39,795 |
import os
import textwrap
def qsub_prep(script_path, cpus, mem, smiles_idx, run_nr, smiles, s_factor,
time_ps, k_push, alp, random_seed, with_products=False):
"""
write qsub file for SLURM subsmissin
"""
pwd = os.getcwd()
qsub_file = """\
#!/bin/sh
#SBATCH --job-name={3}_{4}... | b22254d334a1671288d112fe8bbb128dbe33fc65 | 39,796 |
def drop_keys(task_run_df, keys):
"""Drop keys from the info fields of a task run dataframe."""
keyset = set()
for i in range(len(task_run_df)):
for k in task_run_df.iloc[i]['info'].keys():
keyset.add(k)
keys = [k for k in keyset if k not in keys]
return task_run_df[keys] | be1c07e8abbfbd36a22800a13b1a88d1af775275 | 39,797 |
import os
import re
def get_dir_files(path: str, mode='F', absolute=False, filter_re=""):
"""获取目录下所有文件
:param path: 获取路径
:arg mode
F 当前目录下所有文件
D 当前目录下所有文件夹
FD 当前目录下所有文件和目录
AD 当前目录和子目录
AF 当前文件和子目录文件
AFD 当前目录的子目录所有目录和文件
:arg absolute 是否全路径
:arg ... | dc20020a683b6acbb72415bd709c07686f83a060 | 39,798 |
def add_bins_col_to_rank_df(df_feature,
n_bins,
bin_no_col='bin_no',
item_rank_col='equity_rank',
max_rank_col='max_rank'
):
"""
Description: This function takes as input a... | 380bec79d66d66cb3acd1e42de0edada76cc4024 | 39,799 |
import re
import os
def _parse_kvp_file(file_path, parent_test=None):
"""Parse details.txt and return True if successful"""
test_info = None
kvp = {}
if parent_test is not None:
test_info = parent_test.create_subtest('parse_kvp_file')
line_format = re.compile("^([a-zA-Z0-9 ]+): +(.+)$")
... | 40675f6bd12f06e2d309ada7f4a2b4ebafb7a871 | 39,800 |
def order(lst):
""" Returns a new list with the original's data, sorted smallest to
largest. """
ordered = []
while len(lst) != 0:
smallest = lst[0]
for i in range(len(lst)):
if lst[i] < smallest:
smallest = lst[i]
ordered.append(smallest)
... | 10ff93076af242431dc0831b14fb68af5663b8a4 | 39,801 |
def get_concat_level_bits(i, n, mul):
"""Create a string combining the bits of the current mul.
Combine the bits of the multiplication of the current variable (at mul) by the
i-th index of the previous variable.
Args:
i: An integer, the index of the previous variable.
n: An integer, the number of bits... | 3e6516c570ea128a6c9d12bca82fb35d45a6686e | 39,803 |
from typing import List
import tokenize
def fix_name(tokens: List[tokenize.TokenInfo]) -> List[tokenize.TokenInfo]:
""" Fix the name tokens in the given list of tokens. """
ignorable_types = [tokenize.COMMENT]
i = 0
while i < len(tokens):
token = tokens[i]
if token.type in ignorable_types or token.type == 62:... | d880450869624b0d7526edd9562ab1fba7e0e87f | 39,804 |
import re
def remove_tag_and_contents(s, tag=None, tags=None):
"""
>>> remove_tag_and_contents('hi there')
'hi there'
>>> remove_tag_and_contents('<p>hi</p> <style>p {font-weight: 400;}</style><p>there</p>', tag='style')
'<p>hi</p> <p>there</p>'
>>> remove_tag_and_contents('<span class="foo"... | 9c6506b39ff6f926cf9b03f691bd1b4ecbed6c4a | 39,805 |
def sprint_cmd_list(cmd_list):
"""Returns column of click-able commands from list."""
try:
ret = ''
for cmd in cmd_list:
ret += '/' + cmd + '\n'
return ret
except Exception as E:
print(E) | 2d029ee4e25c538982108756b7e3202d2aa481a8 | 39,806 |
import logging
def encoder_helper(df, category_lst, response=None):
"""
helper function to turn each categorical column into a new column with
propotion of churn for each category - associated with cell 15 from the notebook
input:
df: pandas dataframe
category_lst: list of col... | d74f120356e926b2af03f1316fe860870b64a0f5 | 39,807 |
def version():
"""
Return server version
:return: server version
:retype: str
"""
return '1.0' | d029be1e1b212ca5e4ccb9bde915957a08c0dcea | 39,808 |
def not_empty(s):
"""过滤掉空字符串"""
return s and s.strip() | 044e0c86446beab808f649ffd4ae49f64c1ff63f | 39,809 |
import copy
def prune_maps(net, subsample_indices, output_name):
"""
In case not all the feature maps are used in feedforward connections, the unused ones
can optionally be omitted from a model, if the model is not to include feedback
or lateral connections.
:param net:
:param subsample_indic... | 67a0745a8d522c8ec157bfce906376d0edcc428e | 39,810 |
def populateScoreDictionary(scoreLines):
""" Cette fonction retourne un dictionnaire construit à partir de la matrice importé BLOSUM62 et qui contient la valeur des scores
pour chaque combinaison de paires d'acides aminées """
scoringDictionary = {}
seqList = scoreLines[0]
seqList = seqList.sp... | 357e8fa0d60f183603b2bced240a227eec5e7cdf | 39,811 |
def integrate_euler_explicit(x_t, dx_dt, dt):
"""
Explicit euler integration
x(t+1) = x(t) + dx/dt * dt
:param x_t: known value at timestep t
:param dx_dt: derivative dx/dt
:param dt: timestep
:return: x(t+1); solution for the time t+1
"""
x_tp1 =... | 862feb02512142da98929aedc97707853b41242a | 39,812 |
import argparse
def construct_argparser():
"""
Controls the retrieval of command line arguments using the argparse module.
"""
parser = argparse.ArgumentParser(description="Elimination ordering to tree decomposition")
parser.add_argument("eo_filename", type=str, help="Filename of input graph eo f... | c259ddaefd7801ee73a31433d890cdec87738322 | 39,813 |
def kafka_consumer(kafka_consumer_factory):
"""Return a KafkaConsumer fixture"""
return kafka_consumer_factory() | e54d1013dd5020cc1b4459ed3b968ce02cd5523e | 39,814 |
def has_attribute(t, key: str) -> bool:
"""
Check if a callable has an attribute
:param t: the callable
:param key: the key, the attributes name
:return: True if callable contains attribute, otherwise False
"""
return hasattr(t, key) | 09e39d98bfdd5b2d24a8b7b71c74383bf33eb5b1 | 39,815 |
def assert_errors(result, expected_errors):
"""Assert that result errors match expected errors
Uses substring matching to coorelate expected to actual errrors.
Raise if any expected error is not matched or if any actual
errors are found that were not matched by an expected error.
This function ha... | 6923c4edbc27c0c81ef884aabcaaad06ff4e317c | 39,817 |
def linear_search(list, value):
"""This function takes a list as input and a value to find.Then linearly it searches for that value"""
for i in range(len(list)):
if list[i] == value:
return i #Returning the index
return -1 | 39fdbbdaed7090275ac75e1df39592017494f5fb | 39,818 |
def reformat_line_files(line_upgrades_df, line_cost_database):
"""This function renames, reformats line upgrades dataframe to match cost database columns
Parameters
----------
line_upgrades_df
line_cost_database
Returns
-------
"""
line_upgrades_df.rename(columns={"normamps": "amp... | e24aeff35381c5b591df76af4c31bbd2632a8025 | 39,819 |
def _splitDataByRegex(string_data, regex) -> list:
"""
Function Description :
_splitDataByRegex : provide a collection of splitted string by regex
accept string_data as a string that would be split into several part.
And regex value as splitter
EXAMPLE ARGS : (string_data ... | 716344eb14a3e751bf0ee28fd76bacbc1f047562 | 39,820 |
def read_models(models_file):
"""
Read the models file to get a list of filenames.
:param models_file: models file path
:type models_file: str
:return: list of filenames
:rtype: [str]
"""
files = []
with open(models_file, 'r') as f:
lines = f.readlines()
lines = [li... | bb0dbbcef77af7d3f04608a5a40fd8a8e94cf5a5 | 39,823 |
def create_ascii_file(ascii_file_name, args):
"""Convenience function for creating an output ascii file. This method
writes the current state of the input_flags arguments to the header of the
file and returns an open Python file handle object. The method will over
write any file it is given so use with ... | b431dfe53c39bb025931eddc5e3a985cac581b55 | 39,825 |
def currencies():
"""
:rtype: set[str]
"""
return {"USD", "EUR", "CZK", "GBP"} | e6a3e6e122f80b646e0792dd7b90abc750441853 | 39,826 |
def fib_recurse(n):
"""采用递归的方式求值"""
if n < 2:
return n
return fib_recurse(n - 1) + fib_recurse(n - 2) | fda8576a0c1afb971d8f949fc2d14689bde185bd | 39,827 |
import os
import pickle
import sys
def load_data(data_dir):
""" Load word index dictionary """
word_idx_cache_path = os.path.join(
data_dir, 'word_idx.pkl'
)
idx_word_cache_path = os.path.join(
data_dir, 'idx_word.pkl'
)
word_idx_path_exists = os.path.exists(word_idx_cache_pat... | ed9173c09bb9b8eaf94f62f1e4dec5e61babd7a6 | 39,828 |
def unpad(data: bytes) -> bytes:
"""Unpad a previously padded string."""
return data[: -ord(data[len(data) - 1 :])] | 1fec7f3c08599b139e2e525b6c5af31e6f3681f3 | 39,829 |
def purge_duplicates(list_in):
"""Remove duplicates from list while preserving order.
Parameters
----------
list_in: Iterable
Returns
-------
list
List of first occurrences in order
"""
# Algorithm taken from Stack Overflow,
# https://stackoverflow.com/questions/480214.... | 349211a9ad9b949fb7061e2b4ad21cb1ec3354f7 | 39,832 |
def _prefix_callable(bot, msg):
"""
prefix
:param bot:
:param msg:
:return:
"""
user_id = bot.user.id
base = [f'<@!{user_id}> ', f'<@{user_id}> ']
if msg.guild is None:
base.append('!')
base.append('?')
else:
base.append('¥')
return base | c581176424de6addcb189a901b11f7af4786ebbf | 39,833 |
from typing import Dict
from typing import Any
def build_data_columns(hparams: Dict[str, Any]) -> Dict[str, Any]:
"""Build data columns from hyper-parameters.
Args:
hparams: hyper-parameters for the data columns.
Returns:
data columns.
"""
try:
input_columns = hparams["in... | 21bfe8166234b7ed69aae7a3d49a0848c268611d | 39,834 |
def normArray(data_array, maximum=1):
"""
Returns the normalized array and multiplies with the maximum.
"""
data_array = (data_array / data_array.max())*maximum
return data_array | df0f91078a1460c995436b3038ea6cc82e870051 | 39,835 |
def get_mrca(pi, x, y):
"""
Returns the most recent common ancestor of nodes x and y in the
oriented forest pi.
"""
x_parents = [x]
j = x
while j != 0:
j = pi[j]
x_parents.append(j)
y_parents = {y: None}
j = y
while j != 0:
j = pi[j]
y_parents[j] =... | faece8f1fabf09444f1d3f0d42c49ed6f510acd4 | 39,836 |
def stub_read(mote_id, chan_id, read_start_time):
"""
A stub to return nothing of interest; well, a value that is more
easily picked up as "invalid".
"""
return -1 | b3d94d002f9d112540d62ae1f985bf595b3f2558 | 39,837 |
def convert_str_to_int(data):
""" An example expansion.
"""
data['employees'] = int(data['employees'])
return data | b59bda9aac74c304f143f9fb5775216fc3c71e24 | 39,838 |
def status_str(status):
"""return status string from status code"""
status_map = {
0: 'MATCH',
10: 'OK',
15: 'SKIP',
20: 'FAIL',
30: 'CRASH'
}
return status_map.get(status, 'UNKNOWN') | 55fd5486a2c8360ceb13eb773dc957b799a8e831 | 39,839 |
import torch
def normalize_torch(img: torch.Tensor) -> torch.Tensor:
"""
Standardize image tensor per channel
Args:
-----------
img (torch.Tensor):
input image tensor. shape (C, H, W).
Returns:
-----------
torch.Tensor. Standardized image tensor. Shape (C, H, W).
... | f6459f8ff465cdb56ace492f4de114eee2321855 | 39,840 |
def format_string(string: str) -> str:
"""Replace specific unicode characters with ASCII ones.
Args:
string: Unicode string.
Returns:
ASCII string.
"""
string \
.replace("\u2013", "-") \
.replace("\u00a0", " ") \
.replace("\u2018", "'") \
.replace("\u2... | 2a7efea0816096c549642b00bee6f50a29ede0a2 | 39,842 |
def run_tf_graph(sess, input_data, input_node, output_node):
""" Generic function to execute tensorflow """
tensor = sess.graph.get_tensor_by_name(output_node)
if isinstance(input_data, list):
input_dict = {}
for i, e in enumerate(input_node):
input_dict[e] = input_data[i]
... | 843af35faba84808ad0a6e3428cb65f2685a346c | 39,843 |
import torch
def to_tensor(x):
"""Make x to Tensor."""
try:
return x.clone().detach().float()
except:
return torch.tensor(x).float() | 14df794b76b8d1d4b845e68b6af340522331dd82 | 39,844 |
def createNamespace(benchmarkInfo, benchmarkResult):
"""
Creates a dictionary representing a namespace containing the member
var/values on the benchmarkInfo and benchmarkResult passed in to eval/exec
expressions in. This is usually used in place of locals() in calls to eval()
or exec().
"""
... | 79ff65e69e874c7d83085a7e5cc4c0df82ca572c | 39,845 |
import torch
def npvec_to_tensorlist(vec, params):
""" Convert a numpy vector to a list of tensor with the same dimensions as params
Args:
vec: a 1D numpy vector
params: a list of parameters from net
Returns:
rval: a list of tensors with the same shape as para... | 3cbed80b3896d6f0610a057903f09728ccae0a30 | 39,846 |
import fnmatch
import os
def fnmatch_any(filename, pattern):
"""Test whether `filename` or any of its parent directories match
the glob pattern.
"""
while filename:
# Try the current filename.
if fnmatch.fnmatch(filename, pattern):
return True
# Try its parent dire... | e7008439f5fb5fa1f061e351943799d1cd3f7386 | 39,848 |
def list_certificate_issuer_admins(client, vault_base_url, issuer_name):
""" List admins for a specified certificate issuer. """
return client.get_certificate_issuer(
vault_base_url, issuer_name).organization_details.admin_details | 37c8411b69c7bd3967d4ffe22c8b039236379625 | 39,850 |
def telnet_8742(command):
""" Assemble raw commands for 8742
picomotor controller and iterface to telnet
server """
def wrapped(func):
def telnet_interface(self, *args, **kwargs):
try:
value = func(self, *args, **kwargs)
self.connect_to_telnet()
... | eb36b1b3698fd264f7cc5625e3471130e3bd80a5 | 39,851 |
def semiflatten(multi):
"""Convert a MutiDict into a regular dict. If there are more than one value
for a key, the result will have a list of values for the key. Otherwise it
will have the plain value."""
if multi:
result = multi.to_dict(flat=False)
for k, v in result.items():
... | 75e2ea0a5ee05d53390e9469eb2239ef8a9d6d84 | 39,852 |
def _set_antecedent(self, descendants):
"""
Set antecedent property of descendents to current branch.
Notes
-----
We want the clusters to know who they are related to. An antecedent is the
immediate parent of a cluster. So when branching set the antecedent property
of all descendants in th... | a69a21954ae44548ea62a4fc290ca6df857bc891 | 39,853 |
import os
def append_stem(filename, word, delim="."):
""" returns a filename with word appended to the stem
example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
dirname = os.path.dirname(filename)
filename = os.path.basename(filename)
fsplit = filename.split(delim)
fsplit.insert(... | cb18d68695613ab1cca691a26de163d08d8cc1b9 | 39,854 |
import sys
def humanize(num):
"""A utility function to help generate human readable number string"""
try:
num = int(num)
except:
sys.exit("Unalbe to humanize input value.")
for unit in ['', 'K', 'M']:
if num % 1000:
return '%d%s' % (num, unit)
else:
... | 9a01c4df0c2903525a26b458ecaf123c747fa7cb | 39,856 |
import collections
import math
def prior(training_data, label_list):
""" return the prior probability of the label in the training set
=> frequency of DOCUMENTS
"""
smooth = 1 # smoothing factor
logprob = {}
num_files_by_label = collections.defaultdict(lambda: 0)
for data_point in t... | 983912ce805ae42e212c1af5504d53560af19c1b | 39,857 |
def udfize_def_string(code: str) -> str:
"""Given an unindented code block that uses 'input' as a parameter, and output as a
return value, returns a function as a string."""
return """\
def udf(input):
{}
return output
""".format(
" ".join(line for line in code.splitlines(True))
) | 71084f68ff268eaaa2eec2f8f22394e963fdd894 | 39,858 |
def get_astronomical_twilight(times, events, value):
"""
value = 0 for end of astronomical twilight
value = 1 for the beginning of astronomical twilight (first occurrence)
"""
try:
zindex = events.tolist().index(value)
at_time = times[zindex]
except:
at_time = None
re... | ce8780a833e6356ad169430720f6b4bdb555e8ed | 39,859 |
import pkg_resources
import os
def list_gene_names(gene_information_file=None):
"""Create a list of all known gene names and their aliases as listed on SGD (or as provided as an optional input file)
Input is a standard file downloaded from https://www.uniprot.org/docs/yeast.
Output is list of all genes, w... | 437016f93a1e38851dbe0198921806981d1777be | 39,860 |
def make_filename(traj):
""" Function to create generic filenames based on what has been explored """
explored_parameters = traj.f_get_explored_parameters()
filename = ''
for param in explored_parameters.values():
short_name = param.v_name
val = param.f_get()
filename += '%s_%s__... | f118fb4c79356528773a2c054a8a0955b3e51242 | 39,861 |
import random
def run_quiz(population, num_questions, num_countries):
"""Run a quiz about the population of countries"""
num_correct = 0
for q_num in range(num_questions):
print(f"\n\nQuestion {q_num + 1}:")
countries = random.sample(population.keys(), num_countries)
print("\n".joi... | 3d02fb8036e50f7dbaf4d52f360129fb8cfb0fe1 | 39,863 |
import numpy
def _pfa_check_uvects(PFA, Position, Grid, SCP):
"""
Parameters
----------
PFA : sarpy.io.complex.sicd_elements.PFA.PFAType
Position : sarpy.io.complex.sicd_elements.Position.PositionType
Grid : sarpy.io.complex.sicd_elements.Grid.GridType
SCP : numpy.ndarray
Returns
... | 3f3d975824cb705aa8c5e534b4804adeab2260dd | 39,865 |
def relu_loop(x):
""" ReLu
out = reLu(dot(W, input) + b)
relu = max(x, 0)
dot product:
b1
( a1 a2 a3 ) x ( b2 ) = a1b1 + a2b2 + a3b3
b3
"""
assert len(x.shape) == 2 # assert it is 2D matrix
x = x.copy() # deep ... | a0f91be60bfec9a4d704a132f26108cd3a9d2c0d | 39,866 |
import os
def get_read_count(in_bam_dir):
"""
Extract read count from Log file.
Required for downstream analysis (JunctionSeq)
:param in_bam_dir:
Result directory produced by STAR containing Log.final.out
:return:
Number of mapped reads
"""
in_log = os.path.join(in_bam_dir,... | 36cedc575f4c71f666837219983ced29e5488a5c | 39,868 |
import six
def construct_mirror_name(volume):
"""Constructs MirrorView name for volume."""
return 'mirror_' + six.text_type(volume.id) | 75ec30c8e5cf204f525301ea0fd988222c1d1cf5 | 39,870 |
def check_for_empty_string(input_data):
"""
Checks if data presented by a user is empty.
"""
if input_data.strip() == "":
return 'All fields are required'
return None | dab37e5778d1746e3e3d5c0985d9b24c56184aa3 | 39,871 |
def _count_dollars_before_index(s, i):
"""Returns the number of '$' characters right in front of s[i]."""
dollar_count = 0
dollar_index = i - 1
while dollar_index > 0 and s[dollar_index] == '$':
dollar_count += 1
dollar_index -= 1
return dollar_count | 4d140e63253ca0aee28f8bd6bb24e5a23e00a0f5 | 39,872 |
import bz2
import gzip
def smart_open(filename, mode):
"""Unified front end for opening plain files and compressed files."""
if filename.endswith(".bz2"):
opener = bz2.BZ2File
elif filename.endswith(".gz"):
opener = gzip.open
else:
opener = open
return opener(filename, mo... | 8dc8119c3d27d87d1cc7febe0202f727d925d7c3 | 39,873 |
def eglass_gl_input():
"""Table C3.8.1 - generica material data"""
return {
"name": "e-glass",
"density": 2540,
"modulus_x": 73000000,
"modulus_y": 73000000,
"modulus_xy": 30000000,
"poisson": 0.18,
} | 3bf1d84fbf6bae127049ea7e7010ea458695b6a5 | 39,874 |
import math
def we_calc(xPLL,vd,Kp_PLL):
"""Calculate inverter frequency from PLL."""
return (Kp_PLL*(vd) + xPLL + 2*math.pi*60.0) | b958909ce7481a46ae0fb0176d33f96926e3f607 | 39,876 |
def f(x):
"""
A function for testing on.
"""
return -(x + 2.0)**2 + 1.0 | 52d2c4a4dec5acaa34371a5cead727d94a36a478 | 39,878 |
def detectsubstitutions(args):
"""Detect substitutions specified on the commandline.
This method will be called from the hooks within the applications.py
module. This is where the applications specific code should be placed so
that Longbow can handle substitutions.
"""
# Initialise variables.
... | eb8ff391948ee13bfa1e476a94ceb7b133b296c5 | 39,880 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.