content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_list_of_allowed_websites():
"""Fetches list of all the websites the application is allowed to access."""
with open("../tools/tinyproxy/filter", "r") as filter_file:
websites = filter_file.read().split("\n")
return str(websites[:-1]) | 0638a1c85f11f082a4e64ba42d2a14d1443fad4d | 680,138 |
def none_wrapper(value, default=""):
"""
Pure laziness! Sometimes this ends up being nice syntactic sugar for code readability.
"""
return value if value is not None else default | adef96c85042b080c9acac6a261216d35e8b0bd9 | 680,139 |
import re
def GetBIOSAttrDefaultValues(attr_val_table_data):
"""
From pldmtool GetBIOSTable of type AttributeValueTable get the dict of
attribute handle and its default attribute values.
Description of argument(s):
attr_val_table_data pldmtool output from GetBIOSTable table type AttributeVal... | 6e822a99ce2664ddfd980f133bb69dd4553d26e5 | 680,140 |
import torch
def sqdist(X):
"""Euclidean distance of coordinates.
:param X: sample-coordinates matrix.
:type X: torch.FloatTensor
:return: Euclidean distance.
:rtype: torch.FloatTensor
"""
x = (X ** 2).sum(dim=1, keepdim=True)
sqd = x - 2 * X @ X.t() + x.t()
ind = torch.arange(X.s... | bd413b236547634c6913f497c63ff18b46809bcb | 680,141 |
import logging
def normalize_bridge_id(bridge_id: str):
"""Normalize a bridge identifier."""
bridge_id = bridge_id.lower()
# zeroconf: properties['id'], field contains semicolons after each 2 char
if len(bridge_id) == 17 and bridge_id.count(":") == 5:
return bridge_id.replace(":", "")
# ... | f22022211cf2f534dc83f40ba44271854dad876f | 680,142 |
import numpy as np
def remove_nones(l, return_np_array=False):
""" This function removes "None" values from the given list. Importantly,
compared to other single-function tests, this uses "is" and avoids
strange behavior with data frames, lists of bools, etc.
Optionally, the filtered list... | 57eb578828b9d7cc4a5f269e8286985200e0c637 | 680,143 |
import itertools
def repeatcall(func, *args):
"""Repeatedly call func(*args) and yield the result.
Useful when func(*args) returns different results, esp. randomly.
"""
return itertools.starmap(func, itertools.repeat(args)) | d6af1f2cf4d3efad735656d7759460c4d74c016b | 680,144 |
import json
def parse_read_count_tuples(tuple_string):
"""Parse the string value of one of the CountsOf* ExpansionHunter output fields
(CountsOfSpanningReads, CountsOfFlankingReads, or CountsOfInrepeatReads). For example:
"CountsOfSpanningReads": "(6, 1), (17, 10), (19, 16)"
Return: a list of 2-... | b482bb0e6d74e9cd85c9041131c803bc73bb382c | 680,145 |
from io import StringIO
def _join(args):
"""
Join the arguments with spaces, except newlines which don't
need to be padded.
"""
result = StringIO()
skipSpace = True
for arg in args:
if skipSpace:
skipSpace = False
else:
result.write(' ')
if a... | 950a8e7ae23072ad8693609d73fff5c5a0508752 | 680,146 |
def keep_only_digits(input_string: str) -> str:
"""This function takes as input a string and returns the same string but only containing digits
Args:
input_string (str): the input string from which we want to remove non-digit characters
Returns:
output_string (str): the output string that on... | 00feca8a43fd673ff6f650761dfa6861e29be88c | 680,147 |
def create_files_dict(file_name, metadata_content, bitstream_content):
"""Create dict of files to upload to S3."""
package_files = [
{
"file_name": f"{file_name}.json",
"file_content": metadata_content,
},
{
"file_name": f"{file_name}.pdf",
... | 5792f05076657163fb51d60fc8c1b2b4641fb5c4 | 680,148 |
import pathlib
import os
def get_name_ext(pathname):
"""from a complete file name return the last part composed of one or more ext"""
#ext_list=path.splitext(pathname)[1:] # work only if not more than 1 .ext
ext_list=[]
for ext in pathlib.Path(pathname).suffixes :
ext_list.append( ext.strip(os.extsep) )
return... | 3fbac459a5e5d9d6e59d9e4353babf5a1ebbb87b | 680,149 |
def fake_get_all_cluster_hosts(*args, **kwargs):
""" 返回测试用的集群节点信息 """
return [
{"cluster_id": "BCS-K8S-1001", "inner_ip": "127.0.0.1", "status": "normal"},
{"cluster_id": "BCS-K8S-1001", "inner_ip": "127.0.0.16", "status": "normal"},
] | a1ee9588deb7c80c2cae7959532aaa6cb2ad9bc0 | 680,150 |
import os
def get_filename_from_path(path):
"""
Returns the filename for a full path.
"""
return os.path.split(path)[1] | 711b752799ffdfa7d56b0caa641eaa2419666533 | 680,151 |
def supra_adjacency_matrix(net,includeCouplings=True):
"""Returns the supra-adjacency matrix and a list of node-layer pairs.
Parameters
----------
includeCoupings : bool
If True, the inter-layer edges are included, if False, only intra-layer
edges are included.
Returns
-------
... | cc418073cf34530eee9745d9429c549cb78dd229 | 680,152 |
import argparse
def parse_args():
""" Parse command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'-q','--queries', required = True,
help='Input list of query names with column header "query".')
parser.add_argument(
'-f','--fasta', required = True,
... | a0de128b70d7476201b86a451359f75a16fadec4 | 680,153 |
from typing import Union
from pathlib import Path
def expand_wildcards(paths: Union[str, Path]) -> list:
"""Expand the wildcards that may be present in Paths."""
path = Path(paths).expanduser()
parts = path.parts[1:] if path.is_absolute() else path.parts
return [f for f in Path(path.root).glob(str(Pat... | a326abe415b6f970ad53a8aef5c900c10dce048a | 680,154 |
import re
import os
def get_version(verbose=0):
""" Extract version information from source code """
matcher = re.compile('[\t ]*#define[\t ]+OPENQL_VERSION_STRING[\t ]+"(.*)"')
with open(os.path.join('..', 'include', 'ql', 'version.h'), 'r') as f:
for ln in f:
m = matcher.match(ln)
... | 0a5c43fd7e77e39608e7468232cfacbae1e0e4ea | 680,155 |
def test_arg_index_attrs() -> None:
"""Accessing argument index and attributes."""
assert "{0.real}, {0.imag}".format(3 - 5j) == "3.0, -5.0"
class Point:
"""Point with x-y coordinates."""
def __init__(self, x: int, y: int) -> None:
self.x = x
self.y = y
def... | e5fdf367b5fa1f073e0491ae12451d1b663f17f8 | 680,156 |
import torch
def validate(model, testloader, criterion):
"""Validate the model
Arguments:
model -- The network to validate
testloader -- Test data
criterion -- Loss function to use
"""
test_loss = 0
accuracy = 0
for images, targets in testloader:
images.resize_... | 9efd8746ded637b6e2564a830e7ddccb00d1f71d | 680,157 |
def add_integers(*args: int) -> int:
"""Sum integers.
Arguments:
*args: One or more integers.
Returns:
Sum of integers.
Raises:
TypeError: No argument was passed or a passed argument is not of type
`int`.
Example:
>>> add_integers(3, 4)
7
"... | 924c8bb13b9a5fc2387ee05b177d389853f2cddc | 680,158 |
def print_dict(data, indent_level=0):
"""Pretty-print a dict full of key-value metadata pairs"""
indent = ' ' * indent_level
def _format_key(k):
return '{}{}{: <40}{}'.format(
indent, '\x1b[36m', k + ':', '\x1b[0m'
)
for k, v in sorted(data.items()):
if not isinsta... | 97da5eb89440de9ebc185e30e86a3d40f57409b7 | 680,159 |
def is_valid(s: str) -> bool:
"""
Time: O(n)
Space: O(n) due to the stack we maintain
"""
stack = []
mapping = {"}": "{", ")": "(", "]": "["}
for c in s:
if c in mapping:
last_elm = stack.pop()
if mapping[c] != last_elm:
return False
el... | 7fa65305a9602b1a580144f32b858362ddd106a5 | 680,160 |
def select_by_year(year, D):
"""Select year from specification given in dictionary or list of ranges.
Examples:
>>> spec = {(..., 1990): 'foo',
... 1991: 'bar',
... (1992, 2000): 'foobar',
... (2001, ...): 'blah'}
>>> select_by_year(1990, sp... | 0c3eca376e4f06bf3d3f85308bf02c35ded21e9e | 680,161 |
import re
def md(MD_tag):
"""
Given MD tag and a sequence, find the number of matched, deletion, and substitution bps
Return: 1-level dictionary
"""
#matchLens = re.sub("\D"," ",MD_tag).split() #replace non-digit chars by blanks
#matchLens = map(int, matchLens) #length of the matches before... | 18e11d7749f7ee362bcb8cbede42848839276830 | 680,162 |
import mmap
def matchFilesLine(path, file_name, line, inverted=False):
"""
This method takes a file system path and a filename and a string to search for, it also takes an option boolean keyword 'inverted', if set it
will return True if the string is NOT found.
"""
file_path = path + '/' + file... | 54acd540733334374d577d95e4b178fe386b3ea2 | 680,163 |
import hashlib
def sqlite_md5(text):
"""
md5 - Returns the md5 of the text
"""
if (text!=None):
hash = hashlib.md5()
hash.update(text.encode("utf-8"))
return hash.hexdigest()
return None | 41875a9043923472b3b628cb3e727a574c66966f | 680,164 |
def response_error(response, message):
""" return a 500: Internal server error message """
if response != message:
return "500: Internal server error" | e281713c24bbe0a9fee8cb72c6acc310cb1cd7af | 680,165 |
import random
def MERB_config(BIM):
"""
Rules to identify a HAZUS MERB configuration based on BIM data
Parameters
----------
BIM: dictionary
Information about the building characteristics.
Returns
-------
config: str
A string that identifies a specific configration wi... | 53ab72ed19ebeb3e55f83fcccb80bff665de955e | 680,166 |
import torch
def hippo_skew_evals(N):
""" eigenvalues of (Hippo - Hippo.t()) / 2 (largest imag part first) """
i = torch.arange(N, dtype=torch.float)
x = 2*i + 1
Hippo = (x.view(-1,1) * x.view(1,-1)).sqrt().tril(diagonal=-1) # [N N]
Skew = (Hippo - Hippo.t()) / 2 ... | 4275e7c8f07fc7198d8e8774cc7e09b13d8e0af9 | 680,167 |
import torch
def compute_accuracy(logits, ys_ref, pad):
"""Compute teacher-forcing accuracy.
Args:
logits (FloatTensor): `[B, T, vocab]`
ys_ref (LongTensor): `[B, T]`
pad (int): index for padding
Returns:
acc (float): teacher-forcing accuracy
"""
pad_pred = logits... | 3f1af7d1fae95afd3b5c6567c345185b5ceeaa70 | 680,169 |
import re
def bracketify(**kwargs):
"""
Convert underscores to brackets.
"""
kw = {}
for par in kwargs:
m = re.search(r"\_([0-9])\_", par)
if m is None:
kw[par] = kwargs[par]
continue
prefix = par.split(m.group(0))[0]
... | 73f004f6dcc983c62b1952d05ffb5d2ce488ab10 | 680,170 |
def length(iterable):
"""
Return number of items in the iterable.
Attention: this function consumes the whole iterable and
can never return if iterable has infinite number of items.
:Example:
>>> length(iter([0, 1]))
2
>>> length([0, 1, 2])
3
"""
try:
return len(itera... | 1c2963290d22b9076d3f8f51dd84e586de711b11 | 680,171 |
def mergeSort(l):
"""
Algoritem urejanja z zlivanjem seznama l z n elementi.
Časovna zahtevnost: O(n log n)
"""
n = len(l)
if n <= 1:
return l
l1 = mergeSort(l[:n//2])
l2 = mergeSort(l[n//2:])
l = []
i, j = 0, 0
n1, n2 = len(l1), len(l2)
while i < n1 and j < n2:
... | d6b58f7432d6ea858bc6c2ae2576bb2ac1e7de39 | 680,172 |
def split_kv(text_pair, sep):
"""Helper."""
try:
key, value = text_pair.split(sep, 1)
except TypeError:
return None, text_pair
except ValueError:
return None, text_pair
if not key:
return None, None
return key, value | a8c5779f8e661e42ead85835823cfc3107fab2dc | 680,173 |
def process_dsn(dsn):
"""
Take a standard DSN-dict and return the args and
kwargs that will be passed to the pgdb Connection
constructor.
"""
dsn['password'] = dsn['passwd']
del dsn['passwd']
dsn['database'] = dsn['db']
del dsn['db']
return [], dsn | 12e577848fa6f063a9bcc2264f02d2d4ff0ab4e0 | 680,174 |
import requests
def get_request(url: str, headers: dict, path: str)->dict:
"""
Perform an HTTP GET request
:param url: the url to request
:param headers: a dict containing the ZT Auth header
:param path: the path at the url to request
:return: a dict representing the returned JSON object.
... | c597251cfa7477fdc9f9fb92313b4b14fff5dd43 | 680,175 |
from typing import Any
def maybestr(value: Any) -> str:
"""
A "maybified" version of the str() function.
"""
return str(value) | 920f74ead1c5d0ff3b98cb140bac0e6b5e15f22b | 680,176 |
def datetime_to_iso_8601(dt):
"""Format a datetime as an iso 8601 string - YYYY-MM-DDTHH:MM:SS with optional timezone +HH:MM."""
if dt:
return dt.replace(microsecond=0).isoformat()
else:
return None | 1f1610b6d34409a00f4a1b0d8d47caa5ec8e8ad8 | 680,177 |
def is_rss_data(data):
"""
This methods gets html data and check if it is content from a rss feed
:param data: html object data
:return: True if it is content from a rss feed, False otherwise
"""
data = data.lower()
if data.count("<html"):
return False
return data.count("<rss") ... | 312b852b8ea58f25cbde24925b3a17c60fa75a47 | 680,178 |
def count_unique_data_points_groupby_point_forall_traffic(reader):
"""
Process 5-min traffic flow data and execute a breakdown of the data to each different ingress/egress member ASN.
Files format:
".avro.point=egress.ipv=4.svln=all.txt.gz"
".avro.point=ingress.ipv=4.svln=all.txt.gz"
ingre... | ab38b8737ae3a2b26eb47bab26946a0d07039f5f | 680,179 |
def format_competition_round_headline(selected_match):
""" formats the competition round details
match is the match used to create the headline
returns the competition round details
"""
if len(selected_match.competition_round) > 0:
round_prefix = (" " if selected_match.competition_r... | f1d8f28b94e9dca4e5067dea819476c80577b76b | 680,180 |
def filtra_lista_request_vars(requestvars,clave):
"""Sirve para limpiar listas que se forman en request.vars con algunas variables que se ponen en el GEt y en el POST
devuelve
"""
if clave in requestvars:
if isinstance(requestvars[clave],(list,tuple)):
requestvars[clave]=requestvars... | 5f844b3644fc15c96e05602549ee204041577cbb | 680,181 |
def Pa2inH2O(x):
"""Pa -> inH2O"""
return x/249.1 | 83173ed9647b0667b2c831abd28b00d6781c89c9 | 680,182 |
from typing import Dict
from typing import Any
from typing import List
def get_key_mapping(inverse_mapping: Dict[Any, List[str]]) -> Dict[str, Any]:
"""Returns the key mapping from the inverse mapping.
Args:
inverse_mapping: A mapping from the mapped input to the list of keys.
Returns:
a mapping from ... | 213e5373953bab72682a41981d287c1b1bbb6e35 | 680,183 |
def _qt_list(secondary_dict_ptr, secondary_key_list_ptr, cols, key):
"""
This sub-function is called by view_utils.qt to add keys to the secondary_key_list and
is NOT meant to be called directly.
"""
if cols[key]:
if cols[key] not in secondary_key_list_ptr:
secondary_key_list_pt... | 8cb65f6b449acb54b87a4152b93d32b7b775b869 | 680,184 |
import itertools
def combos(indices):
""" Return all combinations of indices in a list of index sublists.
Arguments:
indices: list of int lists
List of index lists.
"""
return list(itertools.product(*indices)) | ad2bf7f98ee13496764c4fb3654071d8c4e40445 | 680,185 |
def setDefaults(configObj={}):
""" Return a dictionary of the default parameters
which also been updated with the user overrides.
"""
gain = 7 # Detector gain, e-/ADU
grow = 1 # Radius around CR pixel to mask [default=1 for 3x3 for non-NICMOS]
ctegrow = 0... | 6d852af3db241345ace2a8f4fcaa066304492bef | 680,186 |
import subprocess
import difflib
def get_diffs(files):
"""
Run clang-format on all `files` and report if it changed anything.
Returns a mapping of filename => diff generator
"""
name_to_diffs = {}
for f in files:
formatted_text = subprocess.check_output(["clang-format", f]).decode()
... | e5e7c3abedc420494fed0c4786c8f2dcd5de338a | 680,187 |
def init_comm(base_comm, grid_shape):
"""Create an MPI communicator with a cartesian topology."""
return base_comm.Create_cart(grid_shape, len(grid_shape) * (False,),
reorder=False) | c44beadaaeacbcadd634515a8c6c7041fdc5f8e4 | 680,188 |
import re
def preprocess(renderer, page):
"""
Yassg Markdown preprocessor.
"""
def sub_ref(m):
if m.group().startswith('\\'):
return m.group()[1:]
text, ref = m.groups()
if not ref:
text, ref = None, text
page = renderer.find_page(ref)
if not page:
return m.group()
i... | bf72f092f3c05b8903c247fdb7c5c7764f74931c | 680,189 |
def arithmetic_simplify_07(x):
""" arithmetic_simplify_07 """
return (x + 1) * 2 * 5 | 1b8d138cc9a7f411fa6a99163200a75c93f5c609 | 680,190 |
def create_new_features(df):
"""
Creates features for price differences:
high-low
close-open
"""
df['close-open'] = df['Adj_Close'] - df['Adj_Open']
df['high-low'] = df['Adj_High'] - df['Adj_Low']
# create pct features
df['close-open_pct'] = df['close-open'] / df['Adj_Close'] * 100
... | 3265d96d14c1ff79b8900f6d27cecc016a3bbd2e | 680,191 |
def is_test(obj) -> bool:
"""Is the object a test, i.e. test_func()?"""
assert hasattr(obj, "__name__")
obj_name = obj.__name__.lower()
patterns = ("test", "_test", "__test")
return any(obj_name.startswith(pattern) for pattern in patterns) | 7fa240b79833ba79bf0150c97a0c9081bc7c4cf7 | 680,192 |
import os
import fnmatch
def dofolderlist(filename, folderlist, envvariable, searchsubfolders, searchpt):
"""Search for filename in folderlist and return location or ""
filename is the file to find. It may be a wildcard expression.
folderlist is a possibly empty list of folders to search
envvari... | 77cc1244ce2bd99301508dcb75e3b529bda3330d | 680,193 |
def keep_aa(attentions):
""" Last minute change: transfer over the network is very slow. Need to drop keys from the JSON to make rendering faster """
aa = attentions['aa']
out = {'aa': aa}
return out | c6531964e9f032a038f92112c37c615aa4e63617 | 680,194 |
def has_shape(data, shape):
"""Check if the data structure has the given shape."""
# Dict pattern
if isinstance(shape, dict):
return isinstance(data, dict) and all(has_shape(data.get(key), value) for key, value in shape.items())
# List with known order
elif isinstance(shape, list):
r... | 889ccd915418dac8a412609c4cd99045dd0cddcd | 680,195 |
import os
from subprocess import Popen, PIPE, STDOUT
def gitversion():
"""Returns `git describe --tags --dirty --always`,
or 'unknown' if not a git repo"""
origdir = os.getcwd()
os.chdir(os.path.dirname(__file__))
try:
p = Popen(['git', "describe", "--tags", "--dirty", "--always"], stdout=... | cea632b7cb2fa3dc4261295086109fc88f272a8f | 680,198 |
import argparse
def parse_arguments(args):
"""
Parse the arguments from the user
"""
parser = argparse.ArgumentParser(
description= "HUMAnN Databases\n",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
"--available",
action="store_true",
... | 799042a650e30238177a04264b7c6a2bd305e4a2 | 680,200 |
def harm(x,y):
"""Harmonic mean of x and y"""
return x*y/(x+y) | 7054a8a05e6d20fa39efd31ac62a5d5c4c51f061 | 680,201 |
import webbrowser
def _open_profile_pic(profile_id):
"""
Input : Profile Id
Output : Opens a new tab with profile picture of the username
"""
try:
new_url = "https://graph.facebook.com/" + profile_id + "/picture?width=800"
webbrowser.open_new_tab(new_url)
return 1
exce... | dab7604b048c38a82b847b98a7ba3506c4822c6b | 680,202 |
def load_stsb_data(filename):
"""加载数据
单条格式:(文本1, 文本2, 标签)
"""
D = []
with open(filename, encoding='utf-8') as f:
for i, l in enumerate(f):
if i > 0:
l = l.strip().split('\t')
D.append((l[5], l[6], float(l[4])))
return D | 61ae585f1f5c488ed37d7919449f7d01909ac6b8 | 680,203 |
def find_sequencial_nodes(model, Node2nextEntity, Entity2nextNode, search_target=['Conv', 'Add', 'Relu', 'MaxPool'], if_print = False):
"""
Search Where is Subgroup
"""
found_nodes = []
for i, node in enumerate(model.graph.node):
if if_print: print("\nnode[{}] ...".format(i))
n_idx... | 55bb103031f9dbee082594551fa50fc0e4284420 | 680,205 |
def qiime_to_maaslin(in_datafile, outfile):
"""Converts a tsv file from qiime to a maaslin format
:param in_datafile: String; file of the qiime tsv format (from
biom_to_tsv)
:param outfile: String; file of the tsv format for input to maaslin
External dependencies
- QiimeToMaaslin: https://b... | 0a006c2a1e9ba7e6e1eb3c66b0e5cb2a79c15821 | 680,206 |
import copy
def make_state_space():
"""Quick and dirty way to generate the state space reference list for v6 agent.
Total states: 516097
"""
a = []
for i in range(6):
for j in range(6):
for k in range(6):
for l in range(6):
for m in rang... | 40448f6cb99e182ed2ba3505e7d10d36cd0fe59b | 680,207 |
from pathlib import Path
import os
def _get_filenames_from_folder(folder):
"""get the `folder` str, checks and returns children as list of Path
instances."""
folder_path = Path(folder)
if not folder_path.is_dir():
raise ValueError("'{path}' is not a valid directory".format(path=folder))
f... | a987459909157598861f672b6ed3d392b7f611f8 | 680,208 |
from pandas import concat
def concatenate_populations(populations, extra_labels={}):
"""
Write a file containing the set of the populations we want to serialized
Args:
populations (dict): dictionary of the populations, labeled by the key
extra_labels (dict): dictionary of the feature_la... | af852323d8765f279c66f275f1740251ad0b1a1c | 680,210 |
def voxel_hash(x, y, z):
"""
Computes a hash given the int coordinates of a 3D voxel
Args:
x (np.int64): the x coordinate of a voxel
y (np.int64): the y coordinate of a voxel
z (np.int64): the z coordinate of a voxel
"""
return 73856093 * x + 19349669 * y + 83492791 * z | 1e7de79814f3ef232ad1e62a457ddea08575ed01 | 680,211 |
def remove_dups(lst):
"""
Inputs:
lst - A list object
Outputs:
Returns a new list with the same elements in lst,
in the same order, but without duplicates. Only
the first element of each replicated element will
appear in the output.
"""
result = []
dups = set()
... | 21d0158e977847812d6ae944e5a39da5ef77951b | 680,212 |
import tempfile
import os
def get_temp_name(suffix='', prefix='tmp', dir=None, unlink=False):
"""Return temporary file name"""
fdesc, fname = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
os.close(fdesc)
if unlink:
os.unlink(fname)
return fname | a0e0e78ea84357ba5b626fbb3a3eff222a2c1a5f | 680,213 |
def compute_nodes_overlap_max( graph_1, graph_2, node_match):
""" computes a nodes in graph_2 matching with nodes in graph_1 according
to node_match
Returns - a dictionary of nodes """
nodes_2 = [ filter( lambda n2: node_match( graph_1.node[n1], graph_2.node[n2]), graph_2.nodes()) for n1 in gra... | 660f226566bc540769eb431b0c4519eba1f42f8b | 680,215 |
def generate_text_using_trigrams(language_model, N_output_words):
"""
Generate N words using probabilistic language model.
Trigrams are used to generate text.
"""
cprob_2grams, cprob_3grams = language_model
# Starting from the end-of-sentence token, generating 2nd token using bigrams, and the re... | 568206b78e2276087fa9e27cb64278f0638f8900 | 680,216 |
def _WrapAccumulatorCellGradFn(accumulator_layer, cell_grad):
"""Wrap a cell grad function to disable accumulators."""
def WrappedCellGradFn(theta, state0, inputs, extras, dstate1):
"""cell_grad wrapped to disable accumulators."""
# Compute the cell grad function with accumulators disabled.
accumulator... | 65edefc702ef3287c363ef1df0614821273d47ae | 680,217 |
from typing import Dict
def get_env_name__value_map(environ_sh_path: str) -> Dict[str, str]:
"""
获取environ.sh文件中的k-v值
:param environ_sh_path:
:return:
"""
with open(file=environ_sh_path, mode="r", encoding="utf-8") as environ_sh_reader:
lines = environ_sh_reader.readlines()
env_n... | f153b5548132b04850016a485336d270947e85a5 | 680,219 |
def normalize_service_argument(argument):
"""
normalize service name and set type: $object, $variable$
Examples:
>>> normalize_service_argument('$Mongodb')
['Mongodb', 'object']
>>> normalize_service_argument('%batch_size%')
['batch_size', 'variable']
"""
if isinstanc... | be2b1ed59f636c2aa2596877782e686ced045057 | 680,220 |
import re
def camel_to_snake(camel):
"""
make a camelcase from a snakecase
with a few things thrown in - we had a case where
we were parsing a spreadsheet and using the headings as keys in an object
one of the headings was "Who Uploads?"
"""
camel = camel.strip()
camel = re.sub(' ', ''... | 9d96a3597fcf9fd73248c315e224e55d5fd1f96c | 680,221 |
from typing import List
def format_board(board: List[str]) -> str:
"""Return the board formatted for output"""
out_board = ''
for i in range(0, len(board)):
if i == 0 or i % 3 == 0:
out_board += '\n' + '-------------' + '\n|'
tic = board[i] if board[i] in 'XO' else i + 1
... | f8450e2ba4f65beca9acc9811b9d3f8139430e34 | 680,222 |
import re
def get_bvalue(df):
"""Return image b-value. Default to 0 if not found.
It may also be stored as frame second.
Some Siemens scanners have it like this:
(0018,0024) SH [*ep_b0] # 6, 1 SequenceName
(0018,0024) SH [*ep_b1500t] # 10, 1 SequenceName
"""
r = None
if 'Dif... | 6975851390c882b7d9ba8296d62d9c40c193183e | 680,223 |
import re
def _include_exclude(
dictionary: dict,
include_pattern: str,
exclude_pattern: str,
) -> bool:
"""
Filters the items of a dictionary based on a include / exclude regexp pair.
Returns `True` if the size of the dictionary changed.
"""
incl, excl = re.compile(include_pattern), r... | c7b06f84463c7d003a6516d5fc943da12ac4968e | 680,224 |
def fruity_file(models_path):
"""Return fruity sample data file as a Path object."""
return models_path.joinpath("fruity.txt") | 3b32e5f52963b7d24ace1d4ad4745eeb00d3d49b | 680,225 |
from typing import Sequence
from typing import Mapping
def _safe_get_any(root, *keys):
"""
Helper method for getting value from nested dict, special for Gremlin valueMap things where properties can be lists
of one or 0.
:param root:
:param keys:
:return:
"""
current = root
for key ... | 9fb46399275be23d6808629cf149926a760c78a7 | 680,226 |
def get_cut_edge(image, l, r, t, b):
"""deletes pixels from some sided of an image"""
return 0, image[t : image.shape[0] - b, l : image.shape[1] - r] | 01f487827f3ca04e62a691fdf0663dd8d612d83a | 680,227 |
def time_offset(ttest, t0):
"""
Return a string time delta between two datetime objects in seconds formatted
to six significant decimal places.
:param ttest:
:param t0:
:return:
"""
delta = ttest - t0
t = float(delta.seconds) + float(delta.microseconds) / 1000000.0
return "%0.06f... | e10e4c57e1552da0b96cf01967298e55c18d3b0d | 680,228 |
from pathlib import Path
def _modified_date(f: Path) -> str:
"""Get the modified date of the file"""
return str(f.stat().st_mtime) | 2d4b6fcf19f2ecb3bf360b302a6a6a1c90acd831 | 680,229 |
def separate_gradients(gradients, weight_vars, input_vars):
"""
split the gradient dictionary up into one for input and one for weights.
Parameters
----------
gradients: dict:
dictionary of gradients. Should be str, list[Objective] key/value pairs.
input_vars: list:
the input va... | dd73c8f4860e5c7e2c98972c56c024959aba034f | 680,230 |
def insert_sort(unsorted_list):
"""[Takes in an unsorted list and returns a sorted list]
Args:
unsorted_list ([list]): [an unsorted list of ints]
"""
pace = 1
for pace in range(len(unsorted_list)):
pace_behind = pace - 1
temp = unsorted_list[pace]
while pace_behind >... | af07f67144b45b36a273b427e569cccc5193d9f8 | 680,231 |
import re
def subject_id_of(path) -> str:
"""
Returns the subject ID closest to the end of the input string or Path.
Inputs
------
path : str or Path
String or Path containing the subject ID.
Returns
-------
str
Subject ID found in the filename
Raises
------
... | e9dd8f93f6638a454d91d2aa719daec46c1ce9ac | 680,232 |
import logging
import inspect
def get_file_logger(
log_file=None,
log_filemode='a',
log_level=logging.INFO,
log_msg_fmt='%(asctime)s %(levelname)s %(message)s',
log_date_fmt='%a, %d %b %Y %H:%M:%S',
log_prefix=None
):
"""
Purpose:
Get Logger to file
Args:
log_level ... | f31321aef3bff1650f41957b2d3783168b440947 | 680,233 |
def class_name(obj):
""" Returns the class name of an object"""
return obj.__class__.__name__ | daa37085e28d2a7676f0eeacb8d65d74a6986934 | 680,234 |
def Split(string,n):
"""Split a string into lines of length n with \n in between them"""
N =len(string)//n
return '\n'.join([string[i*n:(i+1)*n] for i in range(N)]+[string[N*n:]]) | 06902b208fe1118c4a36edfa57f614238436dc22 | 680,235 |
def molm2_to_molec_cm2(spc_array):
"""
Convert moles/m2 to molec/cm2
"""
avo_num = 6.0221409e23
molec_per_m2 = spc_array * avo_num
molec_per_cm2 = molec_per_m2 * 1e4
return molec_per_cm2 | 9a22c2b79f1de4cfce04f2a41e422ad2421adc2a | 680,236 |
def get_sample_questions():
"""
Return a sample of questions.
"""
questions = {
'CIGOVX1': [
'1',
['SQ001', 'SQ002'],
['SQ001', 'SQ002abc'],
],
'CIGOVX2': [
'1',
['SQ001', 'SQ002'],
['SQ001', 'SQ002'],
... | a972454820757e73b0ca118a36ebe715def0be0a | 680,237 |
def dms2dd(dms):
"""
DMS to decimal degrees.
Args:
dms (list). d must be negative for S and W.
Return:
float.
"""
d, m, s = dms
return d + m/60. + s/3600. | 26ce439d9a4acc8b8d384ccb88e5142581ddcc99 | 680,238 |
def br(value):
""" Replaces newlines with HTML-style <br>'s """
return value.replace("\n", "<br>") | 919daa33a479293a112692aa6e3548a1ed71d6c3 | 680,240 |
def list_count(l):
"""
count the occurrences of all items in a list and return a dictionary
that is of the form {nb_occurence:list_item}, which is the opposite of
standard implementation usually found on the web
-----------------------------------------------------------------
in python >= 2.7, ... | 78d037e5ffd707db875327ee80c949bc57a12b31 | 680,241 |
import math
def binary_entropy(p):
"""
Uses the binary entropy function denoted H(p) in information theory/statistics
Computes the entropy of a Bernoulli process with probability of success p
When p = .5, entropy is at its max value (unbiased bit, most common unit of information entropy)
@param ... | 671eb431c152970546993ecdc6b9de06a7451e99 | 680,242 |
import argparse
def parse_args(args):
"""
Parse script arguments.
:return: Parsed args for assignment
"""
parser = argparse.ArgumentParser()
parser.add_argument('--build-directory',
required=True,
help="A directory where box files laid in",
... | 294944bb6df4ab5ca33c6cc0d43d936b58b3160b | 680,243 |
def chat_words_conversion(text, chat_words_list, chat_words_map_dict):
"""Function to convert the chat words"""
new_text = []
for w in text.split():
if w.upper() in chat_words_list:
new_text.append(chat_words_map_dict[w.upper()])
else:
new_text.append(w)
return " ... | 15a8e8ff31bccbb48f155e35cc8b19d6e558aeed | 680,244 |
def isosurface(da, coord, target):
"""
Returns the values of a coordinate in the input array where the input array values equals \
a prescribed target. E.g. returns the depth of the 20 degC isotherm. Returns nans for all \
points in input array where isosurface is not defined... | 87528aefb258e455fee653a61cef0ac39cfbdea1 | 680,245 |
def _process_ix(i, idx):
"""
:param i:
:param idx:
:return:
"""
if idx is None:
return set(i)
if len(idx) > 1:
return set( zip([i.get_level_values(l) for l in idx]) )
else:
return set( i.get_level_values(idx[0]) ) | e89cb65435ef9d94fcda49ecce1f0bfd9c98e317 | 680,246 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.