content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
def get_str_from_list(in_list: List, val_type: str = '', n_per_line: int = 10) -> str:
"""
Pretty print of list of values.
Parameters
----------
in_list : List
List of values to print.
val_type : str
Print style of type. Possible values: "float", "int",... | 2cc9efc0599abf5a01e92d8c818e4c2d0ec3c3b3 | 39,881 |
def parse_dep(dep_name):
"""
解析依赖关系,xxx、xxx:9.70.0.1 及 xxx:9.70.0.1/c 三种形式
:param dep_name:
:return:
"""
ret = dep_name.split(":")
custom_link_name = None
if ret and len(ret) == 2:
dep_name = ret[0]
dep_version = ret[1]
# 如果指定了/自定义链接名字,则解析,主要出现在某个第三放的库中有多个子库的情况
... | 2748f72dce4960f3543ac7494f6bb19117e51cc2 | 39,882 |
import json
def jsonify(data):
"""
format the output data
:param data:
:return:
"""
return json.dumps(data, indent=2, ensure_ascii=False, default=str) | 6c43be06078d0b8755fe8d7f85376237de0dfcb6 | 39,883 |
def log_list(start, end, n):
"""
>>> log_list(1, 100, 7) #doctest: +NORMALIZE_WHITESPACE
[1.0, 2.154434690031884, 4.641588833612778, 10.0,
21.544346900318832, 46.4158883361278, 100.0]
>>> log_list(-1, -10, 11) #doctest: +NORMALIZE_WHITESPACE
[-1.0, -1.2589254117941673, -1.5848931924611136,... | 9385d86a59ed78130497f44fc1d5144739d1c5b4 | 39,884 |
def get_aminoacids(graph, path: list):
""" Returns the aminoacids attributes (nodes; in order) """
# return the aminoacids of the path
return "".join(graph.vs[path]["aminoacid"]) | ae903e6df9c330fb69288b28599a3e830be377af | 39,886 |
def count_fixed_points(p):
"""Return the number of fixed points of p as a permutation."""
return sum(1 for x in p if p[x] == x) | f64f845609f8624b2d05071e7f225a2c8f73cfb2 | 39,887 |
def get_symbols(wordslist):
"""
Collect the set of letters from a list of strings.
"""
symbols = []
for word in wordslist:
for x in word:
x = x.lower()
if not x.isalpha():
raise ValueError("Only a-z and A-Z are allowed.")
if x not in symbol... | 5d065aa910a86430758d36ec459ce46a548579f6 | 39,889 |
def format_headers(headers):
"""
Parameters
----------
headers Headers to be formatted (List of str)
Returns A list of dict, the right format for v.DataTable headers
-------
"""
out_headers = []
for header in headers:
header_dict = {'text': header, 'sortable': True, 'value'... | 481acfe39c66addb3a2b396e66d195b44346ffc6 | 39,890 |
import tempfile
import os
def csp_sign(thumbprint, password, data):
"""
Подписывает данные с использованием ГОСТ Р 34.10-2012 открепленной подписи.
В качестве бэкенда используется утилита cryptcp из ПО КриптоПРО CSP.
:param str thumbprint: SHA1 отпечаток сертификата, связанного
с зкарытым клю... | 029b1e6610cb9554952591553ab74aab0b4baa2c | 39,891 |
def k_fold_boundaries(values, folds):
"""Take a list of values and number of folds, return equally spaced boundaries as tuples"""
return [
(int((i / folds) * len(values)), int(((i + 1) / folds) * (len(values))))
for i in range(folds)
] | 8b8b3fe1e2b191e538fb5c96a58de01f59ef66a8 | 39,892 |
def echo_magic(rest):
"""
Echo the argument, for testing.
"""
return "print(%r)" % rest | c2d8a14c6ce7fbf9e41e548506bee3a667b7f1de | 39,893 |
def per_model_mean(runs_df):
"""Computes the grouped mean and std by model type
Args:
runs_df (pd.Dataframe): A list of all the runs
Returns:
A tuple of pandas Dataframes that represent the mean and std of each model
"""
overall = runs_df.drop(columns=['SEED', 'ID']).groupby(['TYPE... | fd8c2fd10438df8239272551e8c73d1927449c03 | 39,895 |
def index():
"""
Main page without specific funcion.
"""
return "BiosecLoggerServer is running!" | 4c1ce8d2bdc5a6191f1a257363a303723247894b | 39,896 |
import os
import re
def expandvars(path, environ=os.environ):
"""Expand shell variables of form $var and ${var}. Unknown variables
raise and error. Adapted from os.posixpath.expandvars"""
if not isinstance(path, str):
return path
if '$' not in path:
return path
_varprog = re.compi... | 29c57d076edcf695a3d2ef87f4ab6fb5e35968d0 | 39,898 |
def get_short_account_code(account_type, environment_type):
"""Return a three-character, uppercase code indicating the account type."""
if (account_type == "core"):
code = "COR"
elif (account_type == "developer"):
code = "DEV"
elif (account_type == "sandbox"):
code = "SBX"
e... | a8d04db44c1e69f048680a79c9227ba3c33e48fb | 39,900 |
def html_table_to_excel(table):
""" html_table_to_excel(table): Takes an HTML table of data and formats it so that it can be inserted into an Excel Spreadsheet.
"""
data = {}
table = table[table.index('<tr>'):table.index('</table>')]
rows = table.strip('\n').split('</tr>')[:-1]
for (x, row) ... | 822e87d13f3f24e07aadb61477b4d064c5a58583 | 39,903 |
def get_screen_size(window):
"""获取屏幕 宽、高"""
return window.winfo_screenwidth(), window.winfo_screenheight() | 5d979cb5c9f5cec970977396e47bf751041f452d | 39,906 |
def _measure(line):
"""
Parse a measure line.
Parse a measure line. Looks similar to the following: '# Measure BrainSeg, BrainSegVol, Brain Segmentation Volume, 1243340.000000, mm^3'
Parameters
----------
line: string
A stats line.
Returns
-------
list of strings
A... | 073696bf4b650e947174daa563ed9550686f5758 | 39,907 |
def zero_crossings(x, y):
"""Given x the abscissa and y the ordinate, return the values of x
for which y crosses zero.
"""
n = len(x)
x_zc = []
for i in range(n-1):
if y[i] == 0.0:
x_zc.append(x[i])
elif ( (y[i] > 0.0 and y[i+1] < 0.0)
or (y[i] < 0.0 and y... | 1af23b41867eba3bed649a79fd7effc85941ee95 | 39,908 |
def write_occurrence(eventid, ensemblecount, filename, df):
"""
returns the dataframe for mapping event id and event occurnace id
"""
description = filename.split(".")[3] + ' ensemble ' + str(ensemblecount)
df = df.append({'EVENT_ID': eventid, 'EVENT_OCCURANCE_ID': eventid, 'DESCRIPTION': descripti... | 573ee06de25504d426ccbc74e553c02024ea2a26 | 39,909 |
import re
def is_roberta_based_model(model_name: str) -> str:
"""Validate if the model to pre-train is of roberta architecture."""
r = re.compile('(.*)roberta(.*)')
matches = r.findall(model_name)
base_name = 'none'
if len(matches) > 0:
base_name = '-'.join(model_name.split('-')[:-1])
... | d342f2b32ac6e6e53025610e269b5ff0eaf50902 | 39,910 |
def source_metadata(calexp, src, **kwargs):
""" Metadata from source catalogue.
Args:
task_result (dict): The result of ProcessCcdTask.
Returns:
dict: The dictionary of results
"""
result = {}
# Count the number of sources
result["n_src_char"] = len(src)
return result | 914499ce23b586290ebc81f545d0e0aaf276ca40 | 39,911 |
def multi_mean(input, axes, keepdim=False):
"""
Performs `torch.mean` over multiple dimensions of `input`.
"""
axes = sorted(axes)
m = input
for axis in reversed(axes):
m = m.mean(axis, keepdim)
return m | c636ed33d8db3e61dc96e80e32b17bdacad6d3a8 | 39,912 |
from pathlib import Path
def resolve_open_in_colab(content, page_info):
"""
Replaces [[open-in-colab]] special markers by the proper svelte component.
Args:
content (`str`): The documentation to treat.
page_info (`Dict[str, str]`, *optional*): Some information about the page.
"""
... | 18ab284b6d750743c57fc7746d64a0a8c8ed3b17 | 39,913 |
def get_odd_numbers(num_list: list) -> list:
"""Returns a list of odd numbers from a list."""
return [num for num in num_list if num % 2 != 0] | e7ff779e18b478bf1717912a1ad5b7130eed9b42 | 39,914 |
import re
def filterCChar(string):
"""
过滤出字符串中的汉字
:param string: 待过滤字符串
:return: 汉字字符串
"""
hanzi = re.compile(u"[\u4e00-\u9fa5]+", re.U)
return "".join(re.findall(hanzi, string)) | 1b4ebfe6e9680c21cac4649d4a062cb5f23dc6ae | 39,916 |
def get_title_and_remove(soup):
"""Insert the collapse buttons on the code input field of the nb."""
input_area = soup.find_all(["h1"])[0]
title = input_area.text.strip()[:-1].strip()
input_area = soup.select('div.cell')[0]
input_area.decompose()
return title | 1f4b87f4728f90e3874965a1e8773fceacae6269 | 39,918 |
def union_spans(span_list_A, span_list_B):
"""give spans that are in both A and B."""
## math notes: very similar to A-B, but we return the bit that is removed.
## despite simularities to subtract above, it is symetric
good_spans = []
spans_to_test = span_list_A
next_spans_to_test = []... | 23b060e97514847a924430db654ff59f4febde61 | 39,919 |
def crop_img(img_array, x_left, x_right, y_bottom, y_top):
"""
Crop the image in the bounding box.
wow cropping is so easy didnt think so
just slice the img_array like a numpy img_array
"""
cropped = img_array[y_bottom:y_top, x_left:x_right]
return cropped | 65a8fe8b98a32a374d7c1bcc65250ea190c433f0 | 39,921 |
def find_subsequence_location(sequence, subsequence):
""" Finds the start and end index of the first occurance
of a given subsequence within a larger list. Returns
the two indices corresponding to the postition of
the first and last token of the subseqeunce.
Assumes subsequence is... | 3032fa525edc7bd7da718e50356e6aa4984c4f9a | 39,922 |
def to_bs():
"""Custom Pipeline Registry for dev hello world tasks"""
b1 = [('$entry:e_01', 'smrtflow.tasks.example_tool:0')]
return b1 | ec7c5364cdb4237e2f8224fabc9ffb6a8626d827 | 39,923 |
def repository_dirname(template):
""" Utility function getting repository name from the link
Example: for "https://github.com/user/SomeRepo" should return "SomeRepo"
"""
return template.split('/')[-1] | 8f2987762c93f041458aeccc58133ad6b50a1b96 | 39,924 |
def get_precision_recall(confusion_table):
"""
Get precision and recall for each class according to confusion table.
:param confusion_table:
:return: {class1: (precision, recall), class2, ...}
"""
precision_recall = {}
relations = confusion_table.keys()
for target_relation in relations:
... | 1e9ea2d14c2d42199a5ca630c9587696db3b8ad1 | 39,925 |
import math
def progressbar_formatter_factory(length, nb_steps=10, fill="=", blank=".",
format="[%(fill)s>%(blank)s] %(progress)s%%"):
"""
Formatter factory
Parameters
----------
length : int >= 0
The size of the iterator
nb_steps : int >= 0 (Default : 10)
The number of st... | da2e397d89d88f85342ba16e0828793580960fb0 | 39,927 |
def compute_bert_vectors(text, bc):
"""
Compute BERT embeddings for the input string
:param text: single string with input text to compute BERT embedding for
:param bc: BERT service object
:return: encoded sentence/token-level embeddings, rows correspond to sentences
:rtype: numpy.ndarray or lis... | 688ef432a54effb13dbc08174b27e7a9dbba1b59 | 39,928 |
def isInt(val):
""" Return (bool) whether the input is a integer """
return val == int(val) | 2531179606c2bfae1f50c187d20c7390dc8075d1 | 39,929 |
def get_argparse_parser_actions(parser):
"""introspect argparse object and return list of parameters/options/arguments"""
ret = {}
parser_actions = [(x.option_strings, x.choices, x.help) for x in parser._actions]
for parser_action in parser_actions:
if parser_action[1]:
for action i... | 6f00cefa9be7ba77dfb0cec510eb53eae86c61fc | 39,931 |
def check_colinear(point1, point2, point3):
""" Checks whether three points are colinear or not
point1(A) and point2(B) are endpoints, check point3(P) for colinearity
USING slope based approach, check slope of line AB == slope of line AP
"""
if((point2.y - point1.y) * (point3.x - point1.x) =... | 36c4f6732f21c9a24e7ead7071a07fa74db78b28 | 39,932 |
from PIL import Image
def blackMask(image, alpha=.5):
"""
Draw black mask on image.
:param image: PIL.Image - image to draw
:param alpha: float - black mask intensity (0 - 1)
"""
mask = Image.new('RGB', image.size)
im = Image.blend(image, mask, alpha)
return im | c595e98d062ddc63f4d0754be1514c2ded85b0dd | 39,933 |
import requests
def getHtmlText(url):
"""发出请求获得响应并解码为html
Args:
url (String): 目标页面URL
Returns:
String: 解码后的html内容
"""
response = requests.get(url)
return response.text | b9dc79ed546552b6ebd2c4f5a4384a67ebf9422f | 39,934 |
def nth_child_edge_types(max_child_count):
"""Constructs the edge types for nth-child edges.
Args:
max_child_count: Maximum number of children that get explicit nth-child
edges.
Returns:
Set of edge type names.
"""
return {f"CHILD_INDEX_{i}" for i in range(max_child_count)} | dda3400dbc372d848a65c1409c9a88115b6e74be | 39,935 |
import torch
def box1_in_box2(corners1: torch.Tensor, corners2: torch.Tensor):
"""check if corners of box1 lie in box2
Convention: if a corner is exactly on the edge of the other box, it's also a valid point
Args:
corners1 (torch.Tensor): (B, N, 4, 2)
corners2 (torch.Tensor): (B, N, 4, 2)
... | 6407b8bafea25ca7606c5d205004d219b22cbffc | 39,937 |
import platform
def get_os_arch():
"""Get the OS architecture.
:returns: The OS architecture.
:rtype: string
"""
return platform.machine() | 0ccf6ff211d790071ccd31d94fef7a2fb81e3fa7 | 39,938 |
def dispersion(vmin, dx, fc, coeff=2.0):
"""Compute maximum dt for a stable simulation.
Parameters
----------
vmin: float
Minimum velocity of the medium
dx: float
Grid discretization.
fc: float
Central (peak) frequency of the source wavelet.
coeff: float
Coef... | 1097d10c900c726ea10430ec4be905f428bdd1b3 | 39,939 |
def reverse_index(index, length):
"""
Reverse the passed in index as if the index direction was flipped.
Taking the string "hello" as an example the regular indexes for
each letter are::
01234
hello
Reversing the indexes yields::
43210
hello
This allows easil... | a47c2db2aeec9369593936a34885ee2b04722e95 | 39,940 |
import math
def roundup_int(x: int, num_digits: int) -> int:
"""
round up like excel roundup
向上取证方法,暂时只支持整数
**One**::
>>> num = roundup_int(123,-1)
>>> num
130
"""
if num_digits > 0:
raise TypeError(f'is over 0! digit:{num_digits}')
num_digits = abs(num_d... | 97f60f2c94bfbffeb884501943e1ac470a8edeae | 39,942 |
import time
import calendar
def adjust_time(t, delta):
"""
Adjust a (UTC) struct_time by delta seconds
:type t: struct_time
:type delta: int
:param delta: seconds
:rtype: struct_time
"""
return time.gmtime(calendar.timegm(t) + delta) | 4d2ff67523b05a6f0af02ebb3b230e8875a39ae4 | 39,943 |
from typing import List
from typing import Any
def remove_duplicates_in_order(list: List[Any]) -> List[Any]:
"""
Remove duplicates in a list, keeping the first occurrence and preserving order.
Parameters
----------
list: input list
Returns
-------
deduplicated list
"""
... | 4444aa8e4ca1fa08385b4114055d9bd9eaebcd03 | 39,944 |
def generate_comment(content: str, title_mode: bool=False) -> str:
"""Generate Comment.
Generates the C-style comment using the string provided.
"""
# Tokenize the input.
words = list(filter(
len,
(content.strip()
.replace("\n", " \n ") # Keeps new lines separate.
... | 77cb7fcd4929bc9aa813934203f6085c89a1911c | 39,946 |
def frame_number(frame, speed, particles):
"""
Creates the text for the animation, called every frame to get the
text to be displayed.
Can have your own text the function must have the same input and
output variables as this one.
The first line to be run is pos = frame*speed to get th... | dd91de071c826e1d9e0b46f4d7d6fcbcbb0f358c | 39,948 |
def comma_separated_list(x):
"""
Parse a restructured text option as a comma-separated list of strings.
"""
return x.split(',') | c75c80c5f19fe1843c8ed8e8cc64e4233533bf20 | 39,949 |
import os, sys,time
def sbatch():
"""
"""
ela = []
sblist = []
for root,dirs,files in os.walk(r"./"):
for dir in dirs:
ela.append(os.path.join(root,dir))
mine = os.getcwd()
cmd = mine +"/gpu_tesk.sh"
for i in ela:
os.chdir(mine)
#print(i)
... | 6e48930ac0aa049f6965c69c1ecbe0b30881ed34 | 39,950 |
def wrapList(item):
"""
wrapList(item: any)
implement:
if type(item) != list:
return [item]
return item
"""
if type(item) != list:
return [item]
return item | b3c9bfe269a8167a425189b7f439f5a8302473ef | 39,953 |
def get_words_from_tuples(examples):
"""
You may find this useful for testing on your development data.
params:
examples - a list of tuples in the format [[(token, label), (token, label)...], ....]
return:
a list of lists of tokens
"""
return [[t[0] for t in example] for example in examples] | fceca9e34d59338a4dd612a6b61826c328616643 | 39,955 |
import os
def get_matched_dir_path(path, project_dir_name):
"""
Maybe useless, used before with mixed source-and-unit-test.
"""
while True:
head, tail = os.path.split(path)
if tail == project_dir_name:
return path
elif head == path:
raise ValueError(path... | 5773afe7b1da2afc1e19c222e5092a98b2090411 | 39,956 |
import string
import random
def random_str(length=16):
"""生成字母和数组组成的随机字符串
:param int length: 字符串长度
"""
candidates = string.ascii_letters + string.digits
return ''.join(random.SystemRandom().choice(candidates) for _ in range(length)) | e6a7c012fad44b88546d92553ea4b3dcc6c2fd11 | 39,957 |
def predict_test_data(rf, test_features):
""" Predicts outcomes from test data
Parameters
----------
rf : model
Random forest model built from train data, returned from create_random_forest()
test_features : numpy array
List of fraction of "x variables" used to test the model, returned from split_train_t... | 86314bf6dcba87d1fb8fe47b2bbca2cc8091fb96 | 39,958 |
def _load_name_in_scope(func,name):
"""Get the value of variable 'name' as seen in scope of given function.
If no such variable is found in the function's scope, NameError is raised.
"""
try:
try:
idx = func.func_code.co_cellvars.index(name)
except ValueError:
tr... | a1c1083b92ff48fd5d7678fd19791567995006c1 | 39,959 |
def merge(raw_items_by_id, item):
"""
>>> item = {'_id': 3, 'url': 'matplotlib/basemap', 'description': 'description'}
>>> raw_items_by_id = {3: 0.9, 4: 0.8, 5: 0.7}
>>> merge(raw_items_by_id, item)
{
"url": "",
"description": "description",
"score": 0.9
}
"""
sco... | 13cc44a46adbf0d3e7582edeb0c3fc5c6f23d1fb | 39,960 |
def next_batch_for_narx(dataset, window_size, n_steps, batch_size):
"""Returns a batch in a narx format: x0, y, inputs.
Args:
dataset (TSDataset): time series dataset.
window_size (int): number of steps to include in x0.
n_steps (int): number of steps to include in y and u.
batch... | 724b3381b57a37d0f74a23f0dd624278968809a9 | 39,961 |
def get_sig(row,labels):
""" get the highest significance value """
i = row.index(max(row))
return(labels[i]) | 1da8e3040cf0361997b4f28e701d6b8ff004f3bc | 39,962 |
def _sourcenames(short=False):
"""Return a list with the source names.
:param short: True for shorter names, defaults to False
:type short: bool, optional
:return: Source names.
:rtype: dict [list [str]]
"""
if short is False:
sources = ["psicov", "ccmpred", "deepmetapsicov"]
e... | 94144f783e3e6de83e2522a0f4f070b53e69b913 | 39,963 |
import argparse
def get_parser() -> argparse.ArgumentParser:
"""Build an ArgumentParser to handle various command line arguments.
Returns:
argparse.ArgumentParser: an ArgumentParser to handle command line
arguments
"""
parser = argparse.ArgumentParser(
description='Use a devi... | 4dece28adb877b68af0b50d11b13248314da35c9 | 39,964 |
def set_up():
"""Build structures for the tests."""
args = {
'blast_db': 'blast_db_1',
'log_file': 'log_file_1',
'log_level': 'info',
'sra_files': 'sra_files_1',
'shard_count': 4,
'temp_dir': 'temp_dir_1',
'keep_temp_dir': False}
return 'cxn', args | 0635f96d7ff92482111e9436e434140cac2c2ac5 | 39,966 |
import time
def print_time(t0, s):
"""Print how much time has been spent
@param t0: previous timestamp
@param s: description of this step
"""
print("%.5f seconds to %s" % ((time.time() - t0), s))
return time.time() | 46785207e57f14ce9aca23ed72eb2f7ab0835bac | 39,967 |
def map_label_with_marker(labels):
"""
Map label with marker
:param labels:
:return:
"""
markers = ('o', '*', '^', '<', '>', '8', 's', 'p', 'v', 'h', 'H', 'D', 'd', 'P', 'X',
'.', ',', '1', '2', '3', '4', '+', 'x', '|', '_', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
return dict(z... | d4718e14ec36ef4f6fe19e3c091dbf38cc29e917 | 39,969 |
def replace_short_forms(note: str, long_forms: list, span: list) -> str:
"""
Given a list of long forms and the span of the short forms, replace
the short form by long form in note using the string indeces.
"""
note_replaced: str = note
# Iterates in reverse order, otherwise we would have to cha... | ae2f1855ecab940ea6ef265648d806a7b71acfe6 | 39,970 |
def get_box(request):
"""get one box"""
return request.param | 489cd852db71781949148d03f409fed218ddee18 | 39,971 |
import logging
def check_labels(indiv_labels_ids, selected_labels):
"""Check the consistency of the labels asked by the user."""
# convert strings to int
list_ids_of_labels_of_interest = list(map(int, indiv_labels_ids))
if selected_labels:
# Remove redundant values
list_ids_of_labels_... | 7f55bdbd91333ef48dd46d2d77b2493fe81a3577 | 39,972 |
def decode_image(layer_list):
"""
Takes list of image layer strings as input.
Produces an output by looking through each layer until the following:
If a digit is 0 that means that pixel is black.
If a digit is 1 that means the pixel is white.
If a digit is 2 that means the pixel is transpar... | c0c0ef4a4831f2399174957fa504496945008c91 | 39,973 |
import string
import random
def random_str(length: int = 20, has_num: bool = False) -> str:
"""
generate a random str and len == length
:param length: the random str`length, default=20
:param has_num: has int?
:return: str
"""
all_char = string.ascii_lowercase + string.ascii_uppercase
... | 6e7aff8f6a256652fd067124b6566c4f649008af | 39,974 |
def batch_list(inputlist, batch_size):
"""
Returns the inputlist split into batches of maximal length batch_size.
Each element in the returned list (i.e. each batch) is itself a list.
"""
list_of_batches = [inputlist[ii: ii+batch_size]
for ii in range(0, len(inputlist), batch_... | b1de33c663e8d17645eeabd190a6f17442795a8d | 39,975 |
def i18n_to_eng(string, mapping):
"""Convert i18n to English."""
return mapping.get(string, None) | 8f531cbfcfa44fa6e9c1f243b0597e1f243bae41 | 39,976 |
def make_03f7():
"""NPCメッセージのヘッダー"""
return "" | 2017001b1513816024dab38ce919baac0d6f143d | 39,977 |
def clear_all_none(args):
""" Strip all None from a key/value structure, including keys which nested them
Args:
args (dict): key/value pairs which may contain None values
Returns:
dict: structure with all None removed and no empty values
Example:
>>> clear_all_none({'a': 1, 'b... | 8416266e99a9e03158ab024140f93a1ec3597e9c | 39,979 |
import os
def get_config(env_var, default):
""" return a configuration variable with casting """
if env_var is not None:
value = os.environ.get(env_var, None)
if value is not None:
return value
return default | 9de13a5c2e11c9716fee2190e4f607a8ad44b72a | 39,980 |
def _to_bit(raw):
"""bytearrayを0,1のビットを表す文字列に変換する"""
return ''.join(map(lambda s: format(s, '08b'), raw)) | 663aa2e354001433e9b0f8139519a0c19ffb08e4 | 39,983 |
def dYdx(Ys, h):
"""
Return the first derivative of Ys w.r.t x
"""
first = 0.0 * Ys
# skip the end points
for i in range(1, len(Ys) - 1):
first[i] = (Ys[i + 1] - Ys[i - 1]) / (2.0 * h)
return first | 2fa4e0929ad5c254cd3a391aaebb8657ea5d4b78 | 39,984 |
def read_experiment_lines(readme_lines, start_marker_a="TGA",
start_marker_b="###", end_marker="###"):
"""
This function iterates over a list of strings and searches for information
about a desired experiment. The information is found by looking for
sub-strings (markers) that e... | e80cd6213ba703f970db8f9b6b42704c179c4fdd | 39,985 |
def create_square(lat, lon, radius=0.0001):
"""
Create the a geojson square polygon
Args:
lat: the center latitude for the polygon
lon: the center longitude for the polygon
radius (int): half of the length of the edge of the square
Returns:
list: a list of lat/lon point... | 5dac7311997ea812d59b7fce9c3ab21c92178f98 | 39,986 |
def filter_stream(streams, excludes):
"""
Uses a list of keywords to remove sensors or streams from the list returned by OOI Net.
:param streams: list of sensor or streams returned from OOI Net
:param excludes: list of keywords to use in pruning the list
:return: a cleaned, pruned list
"""
... | d7c7278714cb80541a2aa29ab1c111256ef6b618 | 39,987 |
import math
def angle_to_comp(n, deg=False):
"""Returns the complex number with a magnitude of 1 that forms an angle of n with the real axis
n: angle as float \\
deg: bool (if ```True```, n is taken to be in degrees, if ```False```, n is taken to be in radians)"""
if deg:
n = math.radians(n)
... | a6e873b7d3bf382d3ea7077bca0a89d436742336 | 39,988 |
import os
def get_include():
"""Returns the includes directory.
Returns
-------
out : str
Directory that contains header files.
"""
return os.path.abspath(os.path.dirname(__file__)) | d5fabf5d623d77648c17077ea99d0ff5c67ed259 | 39,990 |
def unicodetoascii(s, encoding='ascii', rplc=None):
"""A crude str encoder. Replaces '?' from s.encode with rplc (if not None). Bytes returned unchanged."""
# Another choice: encoding='latin-1'.
# ??? Is this sane: just to have a different replacement char than '?'?
if not isinstance(s, str):
... | afcddf5323e7bb9837f485677dc521763f9a5ef7 | 39,991 |
def error_j(Dj,Pap,Pdc,PolError,exp_loss_jt):
"""
Calculates the conditional probability for a pulse of intensity mu_j
to cause an error, after sifting, in the time slot t.
Defined as e_k in Sec. IV of [1].
Parameters
----------
Dj : float, array
Expected detection rate.
Pap : f... | b3a8059154ef6be339c833f4955b1f78d3a89f77 | 39,992 |
import random
def shuffled(seq):
"""Returns a list with the elements in seq, shuffled.
"""
lst = list(seq)
random.shuffle(lst)
return lst | 9e80483084b290aace080269d697accffb649755 | 39,993 |
def heartbeat():
"""Generate heartbeat message.
"""
return u'2::' | a96df4ef627303e345027cf9cb5d3e072ed0b59a | 39,994 |
def get_parameters_from_simbench_code(sb_code):
""" Converts a SimBench Code into flag parameters, describing a SimBench grid selection. """
sb_code_split = sb_code.split("-")
version = int(sb_code_split[0])
if sb_code_split[1] != "complete_data":
hv_level = sb_code_split[1].split("V")[0] + "V"
... | 3864a03e3e6d623e2dc01453f59511b677da358e | 39,995 |
import hashlib
def md5_hash(string):
""" Calculates the MD5 sum of a string
"""
m = hashlib.md5()
m.update(string.encode('utf-8'))
return m.hexdigest() | cf89d1c83e3fa1382c2f883627a774bfc51475e1 | 39,996 |
def df_to_dygraph(data_frame):
"""Helper function to convert a :mod:`pandas.DataFrame` to
dygraph data
:param data_frame: The DataFrame to be converted
:type data_frame: :mod:`pandas.DataFrame`
"""
values = data_frame.values.tolist()
data = [[x] for x in data_frame.index.tolist()]
for... | a47e8514cabffda7fc0a9eecdd967eb3dd4c242c | 39,998 |
import os
def using_os():
"""
:return:
"""
os.chdir('../files')
file_list = os.listdir()
if 'aaa' in file_list:
return 'aaa'
return None | c7940aed7ae83d70329c29e5e74407e3e06c9480 | 39,999 |
def _by_attr(xdom, attr):
"""
From `xdom` pick element with attributes defined by `attr`.
Args:
xdom (obj): DOM parsed by :mod:`xmltodict`.
attr (dict): Dictionary defining all the arguments.
Returns:
obj: List in case that multiple records were returned, or OrderedDict \
... | 2679769117371470ebb98d0315dd5dc85bfa13a4 | 40,000 |
import functools
def tile_flatten_sources(tile):
"""
Extract sources from tile as a flat list of Dataset objects,
this removes any grouping that might have been applied to tile sources
"""
return functools.reduce(list.__add__, [list(a.item()) for a in tile.sources]) | d598c6ffc4c6ed061f2093dd2c743cb7edd18da0 | 40,002 |
def _barriers_to_list(ws):
"""Returns filtered list of barriers
Arguments:
ws {openpyxl.worksheet} -- [description]
Returns:
[type] -- [description]
"""
barriers_ws = ws
bars = []
for row in barriers_ws.rows:
vals = [cell.value for cell in row]
bars.append(vals)
bars_no_he... | 43714e7b20b8673a011831f7cfee37d92c70f07e | 40,003 |
import os
def check_folder(directory):
"""
Checks if a folder exists, if not creates it
"""
result = not os.path.exists(directory)
if result:
os.makedirs(directory)
return result | 6c2af31b73da36b056133daa879545d50ee5b51b | 40,004 |
def get_contexts(app):
"""
:type: pydgeot.app.App
:rtype: callable[str, str]
"""
def get_contexts_(name, value):
"""
:type name: str
:type value: str
:rtype: list[dict[str, Any]]
"""
context_dicts = []
results = app.contexts.get_contexts(name, ... | 11b815d62d7c73c2778695b3325d4b90c1075ea4 | 40,005 |
def resolve_checks(names, all_checks):
"""Returns a set of resolved check names.
Resolving a check name involves expanding tag references (e.g., '@tag') with
all the checks that contain the given tag.
names should be a sequence of strings.
all_checks should be a sequence of check classes/instance... | f1e1e7a880c2626e8086a90fffce5aac88e38a74 | 40,006 |
import sys
def _running_in_virtualenv():
"""Returns True if scons is executed within a virtualenv"""
# see https://stackoverflow.com/a/42580137
return (hasattr(sys, 'real_prefix') or
(hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)) | c2e8447711faf9a28955c7f87f73f10fbd4d076e | 40,008 |
def parse_device_env(data):
"""
parse something like this:
{meo}=>env list
_SW_FLAG=E1
_ETHERNET=SWITCH
_COMPANY_NAME=THOMSON
_COMPANY_URL=http://www.thomson.net
_PROD_NAME=Thomson TG
_BRAND_NAME=Thom... | 9c5e3b89adf50944352273f12bfb0561f3ec6d43 | 40,009 |
def doflip(dec, inc):
"""
flips lower hemisphere data to upper hemisphere
"""
if inc < 0:
inc = -inc
dec = (dec + 180.) % 360.
return dec, inc | c1627cd74f85e50d8e9d614065af956b0008624c | 40,010 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.