content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _check_type(par,par_type):
"""function for checking if python parameter 'par' and DBASIC type 'par_type' are compatible"""
if par_type=='String':
if type(par)==str:
return True
else:
raise TypeError("Parameter of DBASIC type 'String' must be of python type 'str'")
... | 789b6d3a14f435ea0f6f5805f444356b8afd7d2f | 35,388 |
def add_to_bank_balance(balance):
"""
Determine if the player wants to increase the balance
Prompt for the balance to addition
If the player needs to increase the balance (boolean)
balance: Players have balance, each game will change (int)
add: The player needs to increase the balance (int)
Retu... | bfb991bdea7faf355507354b1fc20540cd5eb2ff | 35,390 |
def GetUnixErrorOutput(filename, error, new_error=False):
"""Get a output line for an error in UNIX format."""
line = ''
if error.token:
line = '%d' % error.token.line_number
error_code = '%04d' % error.code
if new_error:
error_code = 'New Error ' + error_code
return '%s:%s:(%s) %s' % (filename, ... | 5689b28ea0475f08802c72a48b733e4625e6d9d5 | 35,392 |
import sys
def split_args(all_args):
"""
Split argument list all_args into arguments specific to this script and
arguments relating to the moses server. An isolated double dash acts as
the separator between the two types of arguments.
"""
my_args = []
mo_args = []
arglist = mo_args
... | 65e91201ac9ff7bdcd55e57bd6b0bcf680a68ea4 | 35,393 |
def left_child_index(i):
"""
:param i: int
Index of node in array (that is organized as heap)
:return: int
Position in array of left child of node
"""
return 2 * (i + 1) - 1 | 323106fbc8aa1a12144bde5c6e43cd6870c6b1da | 35,394 |
import os
import json
from datetime import datetime
def load_logs(log_dir):
""" load all logs and convert their time-stamps to datetime format """
# local func used for parsing...
def parse_nan_inf(arg):
print("got:",arg)
c = {"-Infinity":-float("inf"), "Infinity":float("inf"), "NaN":float... | b18675da51c69469bd6cf2d8d0275c39383f92bf | 35,395 |
def add(bowl_a, bowl_b):
"""Return bowl_a and bowl_b added together"""
return bowl_a + bowl_b | e12bb4d5f4d21f4ae113f064d62d0db2ea6f8014 | 35,396 |
def process_fid_to_avg_gate_fid(F_pro: float, d:int):
"""
Converts
"""
F_avg_gate = (d*F_pro+1)/(d+1)
return F_avg_gate | a69b6c7e43bd88762d472a30fc55d0e13ae1aa36 | 35,398 |
from typing import Tuple
from typing import List
def _get_value_name_and_type_from_line(*, line: str) -> Tuple[str, str]:
"""
Get a parameter or return value and type from
a specified line.
Parameters
----------
line : str
Target docstring line.
Returns
-------
value_name... | d2095fa2bc34a7086f60b40373a351f7c984dc96 | 35,399 |
def exclude_from_weight_decay(p):
""" exclude_from_weight_decay """
name = p.name
if name.find("layernorm") > -1:
return True
bias_suffix = ["bias", "_b", ".b_0"]
for suffix in bias_suffix:
if name.endswith(suffix):
return True
return False | 25289dc1246f9d2c65a7a1f22238efbb1c67f8bd | 35,400 |
import json
def JSONParser(data):
"""call json.loads"""
return json.loads(data) | d9356667b7dbadaea5196a85617ace1aeb1b40eb | 35,401 |
from typing import Counter
def verify_enabled_game_projects(ctx, option_name, value):
""" Configure all Game Projects which should be included in Visual Studio """
if not value:
return True, "", "" # its okay to have no game project
if (len(value) == 0):
return True, "", ""
if (value... | fbd859affc1f5c3e3c8ae2c31e20c47610615f69 | 35,402 |
def cut_tag_preserve(tags, tag):
"""
Cuts a tag from a list of tags without altering the original.
"""
tag_list = tags[:]
tag_list.remove(tag)
return ",".join(tag_list) | 691412fc466498413c32edd30eaca2d677d7e35a | 35,405 |
def _default_error_handler(error_handler):
"""
Use it to customize error handler.
In aiohttp-apispec we use 400 as default client http error code.
"""
error_handler.set_status(400)
return error_handler | b80896bc365bfdbebcd07b43131b80c938bfadff | 35,408 |
def is_related(field):
"""
Test if a given field is a related field.
:param DjangoField field: A reference to the given field.
:rtype: boolean
:returns: A boolean value that is true only if the given field is related.
"""
return 'django.db.models.fields.related' in field.__module__ | fff8bbc5f945e7f0ee576e4b501b2c9ca808541d | 35,409 |
import torch
def attention_score(att, mel_lens, r=1):
"""
Returns a tuple of scores (loc_score, sharp_score), where loc_score measures monotonicity and
sharp_score measures the sharpness of attention peaks
"""
with torch.no_grad():
device = att.device
mel_lens = mel_lens.to(device... | ccdce864a91c9816143f414c2cde99b5f67c89c4 | 35,411 |
def sort_lists(reference, x):
"""
Sorts elements of lists `x` by sorting `reference`
Returns sorted zip of lists
"""
# sort zip of lists
# specify key for sorting the ith element of `reference` and `x` as the first element of the tuple of the sorted zip object, e.g. pair[0] = (reference[i]... | 581e01f21902a029570dc45e5c6401696b80ee15 | 35,412 |
def mjd_to_f(in_mjd):
"""
:param in_mjd:
:return:
"""
return 1 / in_mjd | 8980a6ed365aeee4b2408e503af1fa3b3f110b36 | 35,413 |
def update_from_db():
"""read DB and returns a dict with the data
The returned dict must have the following structure:
{
ssid1:{
channel11:[
url11_1,
...
url11_n
]
],
...
channel1n:{...}
... | 59ecb0e412431f6d4ee712c62149344c7046fe8e | 35,414 |
import subprocess
def runBrowser(profileDir=None, browserArgs=None):
"""
Run in browser
"""
args = ["cfx", "run"]
if profileDir is not None:
args.append("-p")
args.append(profileDir)
if browserArgs is not None:
args.append("--binary-args")
args.append(browserArgs)
return subprocess.call... | 96a299a9fd4c3f01218b0ecba59da7bacf0f3be5 | 35,415 |
def pos_of(values, method):
"""Find the position of a value that is calculated by the given method.
"""
result = method(values)
pos = [i for i, j in enumerate(values) if j == result]
if len(pos) > 1:
print('Warning: The %s of the list is not distinct.' % (method,))
return pos[0] | 5300511a1dd8f76de51f58021cf011a4aa5ca757 | 35,416 |
def get_weeks():
"""
列出所有星期
:return:
"""
return ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] | 82f14f54d571186f68035d8bd7c5b67ea404637d | 35,417 |
def crop_frame(img, width, height, x, y):
"""
Returns a crop of image (frame) based on specified parameters
Parameters
----------
img : array, required
Array representing an image (frame)
width : int, required
Width of the crop
height : int, required
Height of th... | 1cbc34aed421cf67cef57b8fb53b47015911f701 | 35,420 |
import math
def sigmoid(x):
"""
sigmoid function
Args:
x: number
Returns: sigmoid(number)
"""
return 1 / (1 + math.exp(-x)) | 3f4fc16c99af2cdf71aea9f108382e6464f50e6f | 35,421 |
def parse_releases(content):
"""
Parse latest releases of a manga
Parameters
----------
content : BeautifulSoup
BeautifulSoup object of the releases page content.
Returns
-------
releases : list of dicts
List of latest releases of a manga.
List is ordered latest... | 9f1e99cf0e6e96cb60c6764c68052e94d341d196 | 35,423 |
def percent_to_volts(percentage: float) -> float:
"""Converts a float between 0 and 1 into an equivalent 3.3v value."""
if percentage > 1:
raise ValueError("volts expects a percentage between 0 and 1.")
return percentage * 3.3 | 09ec72f63f41de7d7123589d0b79d98989311fb8 | 35,424 |
def get_attitude_data(db_connection, scanno):
"""get attitude data from level1 database"""
query = db_connection.query(
'''select stw, latitude, longitude,
sunzd, orbit
from ac_level1b
join attitude_level1 using (stw)
where calstw = {0}
order by stw'''.format(scan... | ea7b9905e2fff2fbc3af103da2964004e31c027c | 35,426 |
def get_central_longitude(lon_deg):
"""Get the central meridian for the zone corresponding to a longitude.
This function determines the zone that a longitude corresponds to, and the
central meridian for that zone, all in one step.
See also http://www.jaworski.ca/utmzones.htm.
Args:
lon_de... | 044fc4eebe3ca9ba93799003964c45a5db9da017 | 35,428 |
def extract_instance_name(url):
"""Given instance URL returns instance name."""
return url.rsplit('/', 1)[-1] | 333c6f12ae44b0a5de0ed80d9e01c87dffeb18d2 | 35,430 |
def stream_table_dataframe_to_string(stream_table, **kwargs):
"""
Method to print a stream table from a dataframe. Method takes any argument
understood by DataFrame.to_string
"""
# Set some default values for keyword arguments
na_rep = kwargs.pop("na_rep", "-")
justify = kwargs.pop("justify"... | 8028ef06d5535cdfca7feead2647883c15ac4c7f | 35,431 |
def cmyk_to_luminance(r, g, b, a):
"""
takes a RGB color and returns it grayscale value. See
http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/
for more information
"""
if (r, g, b) == (0, 0, 0):
return a
return (0.299 * r + 0.587 * g + 0.114 * b) * a / 255 | 91a5720fe2f966913ac81330642d1f48c7d67b3a | 35,432 |
import os
def java_executable(env_prefix):
"""Returns the name of the Java executable."""
java_home = os.getenv('JAVA_HOME')
if java_home:
java_home_bin = os.path.join(java_home, 'bin', 'java')
if os.access(java_home_bin, os.X_OK):
return java_home_bin
return os.path.join(e... | f1dcc44462acee62d7d9b264b66ca3034d18f79d | 35,433 |
def salt_run_cli(salt_master):
"""
Override salt_run_cli fixture to provide an increased default_timeout to the calls
"""
return salt_master.salt_run_cli(timeout=120) | 10d2d04d83ae747e0898a34823d3403a374381a9 | 35,434 |
def load(*args, **kwargs):
"""
Entry point for server side interface code
"""
return {} | 22904d2281b39379f8bb237856a6c8921c00ded1 | 35,435 |
def getDaySuffix(day):
"""Return st, nd, rd, or th for supplied day."""
if 4 <= day <= 20 or 24 <= day <= 30:
return 'th'
return ['st', 'nd', 'rd'][day % 10 - 1] | 4023b97164cbb7c73a1a3ddb2a3527fa2c297a1d | 35,439 |
import bisect
def find_le(array, x):
"""Find rightmost value less than or equal to x.
Example::
>>> find_le([0, 1, 2, 3], 2.0)
2
**中文文档**
寻找最大的小于等于x的数。
"""
i = bisect.bisect_right(array, x)
if i:
return array[i - 1]
raise ValueError | dfa67df6fadbdead10821c4aceb027b0c5f5d90a | 35,440 |
def flatten(array: list):
"""Flatten nested list to a single list"""
return [item for sublist in array for item in sublist] | 65692535197b946d5d5a39e657ff07c3424e7652 | 35,441 |
def range_not_tag(length, tag, name=None, start=1):
"""
返回一个范围字段,此时抓取的信息不能是tag字段
:param length:
:param tag:
:param name:
:param start:
:return:
"""
if name:
return '(?P<%s>(((?!%s).)*){%s,%s})' % (name, tag, start, length*3) | 330042d5a7c40844fd31e51eaef5e7e3478affec | 35,442 |
def get_actions(state):
""" Returns the set of legal moves in a state. """
move_list = list()
for i in range(3, -1, -1):
for row in range(2, -1, -1):
for column in range(2, -1, -1):
if state[i][row][column] == '.':
for board in range(1, 5, 1):
... | 8896d879a4229af26e5c39022f8fa05813b21589 | 35,443 |
def _transaction_sort_key(txn):
"""
If there are payments and invoices created on the same day
we want to make sure to process the payments first and then
the invoices. Otherwise the transaction history on an
invoice will look like a drunk cow licked it, that's bad.
:param txn:
:return: sort... | c6e74a6c87ec7c46dba0507bf144bfddac954e3c | 35,447 |
import os
import json
def read_json(file_dir, name, num_files):
"""reads the json output of clustering"""
meetings = {}
for i in range(1, num_files + 1):
file_path = os.path.join(file_dir, '%s.%d.json' % (name, i))
with open(file_path, 'rb') as _json_file:
inputjson = json.load... | 8ae183dcf97264c366461fe8347cc9c229135c36 | 35,448 |
def get_reordered_parameters(parameters):
"""get_reordered_parameters"""
# put the bias parameter to the end
non_bias_param = []
bias_param = []
for item in parameters:
if item.name.find("bias") >= 0:
bias_param.append(item)
else:
non_bias_param.append(item)
... | bceb663f0398ee5b5b122805f69b6cb814c8c529 | 35,449 |
import os
def recursive_scandir(top_dir, dir_first=True):
"""Recursively scan a path.
Args:
top_dir: The path to scan.
dir_first: If true, yield a directory before its contents.
Otherwise, yield a directory's contents before the
directory itself.
Returns:
A generator of t... | c4a31caf9fde2ffd1798ae0daed8e459e1dcbda9 | 35,450 |
def cleanup_column_names(df,rename_dict={},do_inplace=True):
"""This function renames columns of a pandas dataframe
It converts column names to snake case if rename_dict is not passed.
Args:
rename_dict (dict): keys represent old column names and values point to
newe... | 2ee32d7742c20b9eeeffb9481d940f1e4c036937 | 35,451 |
import math
def returnNewDelta(delta_old):
"""returns the side of the new polygonal approximation.
Arguments:
delta_old -- the side of the previous approximation
"""
return math.sqrt( 2. * (1. - math.sqrt(1. - 0.25 * delta_old**2) ) ) | 7ffececdc6affb3b7f9aa215415077bc14baa9e3 | 35,452 |
import os
def maybe_java_home(s):
"""
If JAVA_HOME is in the environ, return $JAVA_HOME/bin/s. Otherwise, return
s.
"""
if "JAVA_HOME" in os.environ:
return os.path.join(os.environ["JAVA_HOME"], "bin", s)
else:
return s | 4bd3a1b9cb3891de599638ebd467a3ca7673665b | 35,453 |
import os
def input_file(s_input: str) -> str:
"""
Used for parsing some inputs to this program, namely filenames given as input.
Whitespace is removed, but no case-changing occurs. Existence of the file is verified.
:param s_input: String passed in by argparse
:return str: The filename
"""... | 8b8268d049df78274a2deea54cc718696e2fc03a | 35,454 |
import sys
def NotecardExceptionInfo(exception):
"""Construct a formatted Exception string.
Args:
exception (Exception): An exception object.
Returns:
string: a summary of the exception with line number and details.
"""
name = exception.__class__.__name__
return sys.platform ... | 7249250ed384b02a26f96d6e26c02967d7111c32 | 35,456 |
def max_contig_sum(L):
""" L, a list of integers, at least one positive
Returns the maximum sum of a contiguous subsequence in L """
sizeL=len(L)
max_so_far,max_ending_here=0,0
for i in range(sizeL):
max_ending_here+=L[i]
if max_ending_here<0:
max_ending_here=0
el... | 356c87a66ff1071e729e3de379550a0a61a2f4f4 | 35,457 |
def cal_recom_result(user_click,user_sim):
"""
recom by usercf algo
:param user_click:dict,用户的点击序列 key userid, value [itemid1,itemid2]
:param user_sim:经过排序后的用户的相似度矩阵 key:userid value:list,[(useridj,score1),(useridk,score2)]
:return:dict,key userid value:dict,value_key:itemid1,value_value:recom_scor... | d4d7e0e0c0e112ecf9e48214a1f253f82a052818 | 35,460 |
def test_module(unifi_session):
"""
Test Module for Demisto
:param unifi_session: Unifi Session from Unifi class
:return: Return 'OK' if success
"""
result = False
if unifi_session.base_url:
result = "ok"
return result | e375b8f673499c093cdfb691e154e5f7ba9f1737 | 35,462 |
import argparse
from pydoc import locate
import yaml
def parse(arg_file, description=None):
"""
:param description: string
:param arg_file: string
:returns: dict
Example YAML file for arguments:
---
string:
help: Example string parameter.
type: str
default: 'default stri... | 544e4ceafdbdfa1a1cd3bd84e30e11b044d7115b | 35,463 |
def denormalize(column, startvalue, endvalue):
"""
converts [0:1] back with given start and endvalue
"""
normcol = []
if startvalue>0:
if endvalue < startvalue:
raise ValueError("start and endval must be given, endval must be larger")
else:
for elem in column:... | b10bb2de587db74fcc48e93567f44af900173dc7 | 35,464 |
import requests
import json
def post_request(url, json_payload, **kwargs):
"""
post_request function is used to send a POST request in order to interact
with remote services through rest apis
url: url to the remote service
json_payload: json object containing remote service input parameters
k... | 8c9de68163df2c056f317aafd6affc79e49ce2cc | 35,465 |
def tokenise_table_name(table_name):
"""Given a feature class or feature dataset name, returns the schema (optional) and simple name"""
dot_count = table_name.count(".")
if dot_count == 2:
dot_pos = [pos for pos, char in enumerate(table_name) if char == "."]
return {
"database... | 7664bd8099cea88c8d0313c62ce5d4da38fcf947 | 35,467 |
from typing import List
def get_indices_of_extra_letters(row: List[str], split: int, key_length: int) -> List[int]:
"""
Returns indices of all letters which don't belong in a row because they make its length bigger
than the given split.
"""
row_without_placeholder = ''.join(char for char in row i... | 1c275b43d3605ef7514c14d6f0f99994f4eb7c3e | 35,468 |
import subprocess
def test_specification(module) -> str:
"""テスト仕様
"""
return "<br/>".join(
subprocess.run(
f"pytest --collect-only --quiet {module.__file__}",
universal_newlines=True,
check=True,
shell=True,
stdout=subprocess.PIPE,
... | a499c19f5f95b260c582d373514bbd86b89981ff | 35,469 |
def to_index_tuple(idx):
"""Converts a numpy array to a tuple of integer indexes.
Converts a numpy array to a tuple of integer indexes.
Args:
idx: The numpy array containing the indexes.
Returns:
A tuple of indexes.
"""
return tuple(idx.astype(int).tolist()) | 4c7a3182625f48a54e07432960f68c58f0828070 | 35,470 |
def ConvertTokenToInteger(string, location, tokens):
"""Pyparsing parse action callback to convert a token into an integer value.
Args:
string (str): original string.
location (int): location in the string where the token was found.
tokens (list[str]): tokens.
Returns:
int: integer value or None... | f0332c672156bb95b0d14d0af94d197464ab70a0 | 35,472 |
def midpoint(imin, imax):
"""Returns middle point
>>> midpoint(0, 0)
0
>>> midpoint(0, 1)
0
>>> midpoint(0, 2)
1
>>> midpoint(1, 1)
1
>>> midpoint(1, 2)
1
>>> midpoint(1, 5)
3
"""
middle_point = (int(imin) + int(imax)) / 2
return middle_point | 389058bb50f0e1f3d31498edcac2469a97545a3f | 35,474 |
def get_num_image_channels(module_or_spec, signature=None, input_name=None):
"""Returns expected num_channels dimensions of an image input.
This is for advanced users only who expect to handle modules with
image inputs that might not have the 3 usual RGB channels.
Args:
module_or_spec: a Module or ModuleS... | ade88e40833749b48461d7f996ab8824258ad7df | 35,475 |
def normalize_information_coefficients(a, method, clip_min=None, clip_max=None):
"""
:param a: array; (n_rows, n_columns)
:param method:
:param clip_min:
:param clip_max:
:return array; (n_rows, n_columns); 0 <= array <= 1
"""
if method == '0-1':
return (a - a.min()) / (a.max()... | 121445cdfdfa01ef6498fad9f35baa1158f77c6f | 35,476 |
import warnings
def check_case(name):
"""
Check if the name given as parameter is in upper case and convert it to
upper cases.
"""
if name != name.upper():
warnings.warn("Mixed case names are not supported in database object names.", UserWarning)
return name.upper() | 8e973c6c087e3bb9b3abd076e2d97b3770f3589c | 35,477 |
import requests
def get_elevation_for_location(latitude: float, longitude: float):
"""
Function to get the elevation of a specific location given the latitude and
the longitude
"""
url = (
f"https://api.open-elevation.com/api/v1/lookup?"
f"locations={round(latitude, 4)},{round(long... | 35d317bc6d926f2c24bd4c5095ebb6513010a652 | 35,478 |
from typing import List
def listToCSV(lst: List) -> str:
"""
Changes a list to csv format
>>> listToCSV([1,2,3])
'1,2,3'
>>> listToCSV([1.0,2/4,.34])
'1.0,0.5,0.34'
"""
strings = ""
for a in lst:
strings += str(a) + ","
strings = strings[0:len(strings) - 1]
return s... | 89fc272c4b9fc0a3a406f67d7b655b2c72755d07 | 35,479 |
def fibonacci(n):
"""
This function prints the Nth Fibonacci number.
>>> fibonacci(3)
1
>>> fibonacci(10)
55
The input value can only be an integer, but integers lesser than or equal to 0 are invalid, since the series is not defined in these regions.
"""
if n<=0:
return "Incorrect input."
elif n==1:
ret... | 165a6bf1fc73d24e0b3c25599040c26a56afdcd9 | 35,480 |
def _CreatePatchInstanceFilter(messages, filter_all, filter_group_labels,
filter_zones, filter_names,
filter_name_prefixes):
"""Creates a PatchInstanceFilter message from its components."""
group_labels = []
for group_label in filter_group_labels:
... | 7692812fe66b8db42bd76550281c7751d7648b1c | 35,481 |
import re
def fix_dependent_sources(input_line):
""" Fix table syntax for dependent sources """
table_statement = re.match(r".*table.*", input_line, flags=re.IGNORECASE)
n_line = input_line
# If source values come from a table
if table_statement:
# If there is no equal sign, the followi... | cac896ab90bcf5554d4c95fd44ad49f178ffe5ff | 35,483 |
import math
def row_deco_2(in_array, num_chunks, ghost_zone_size, block):
"""
Returns:
---------
chunks: nested list
[[dataid, start_idx, end_idx], [dataid, start_idx, end_idx]]
the start_idx and end_idx that is returned accounts for the
"""
tot_rows = in_array.shape[1]
to... | 675a91f5d80849511f861c6acc1597bfdd25a6b9 | 35,486 |
import re
def _normalizeText(text):
"""Normalize text before transforming."""
text = text.lower()
text = re.sub(r'<br />', r' ', text).strip()
text = re.sub(r'^https?:\/\/.*[\r\n]*', ' L ', text, flags=re.MULTILINE)
text = re.sub(r'[\~\*\+\^`_#\[\]|]', r' ', text).strip()
text = re.sub(r'[0-9]... | 021007a7773902de7fd167803639650ccb6e5ba8 | 35,489 |
def sublista_gestos_compostos(gesto, m):
"""
Verifica se o gesto corresponde a um gesto composto.
:param gesto: Lista com os gestos compostos unidos.
:param m: gesto individual
:return: Lista com os gestos compostos divididos, caso o gesto em m pertença a um gesto composto. Caso contrário retorna a lista com o ges... | f00464bb0d820329b913b2ede6813f6ea4cf50da | 35,490 |
import subprocess
def should_gather_results(directory, min_threshold):
# type: (str, int) -> bool
"""Should results be gathered for `directory` based on `min_threshold`?
:param directory: directory to determine whether or not the results should
be gathered.
:param min_threshold:... | 8fb7d137f24d94d3a9cc9959b70338196367a77a | 35,491 |
def med_is_decimal(s):
"""Takes a string and returns whether all characters of the string are digits."""
return set(s) <= set('1234567890') | f9078d20fe5b8d70493f34e2e53e95713fd7d37f | 35,493 |
def filter_on_cdr3_length(df, max_len):
"""
Only take sequences that have a CDR3 of at most `max_len` length.
"""
return df[df['amino_acid'].apply(len) <= max_len] | abe853dd0a5baeb3a178c41de9b15b04912e2033 | 35,494 |
def calc_array_coverage(solid_angle, number_of_bars):
"""
Calculate the coverage for an entire array
:param solid_angle: The solid angle in sr
:param number_of_bars: The number of solids in the array.
:return:
"""
return number_of_bars * solid_angle | 1d071116dea5f6a9e91c37168681b5386df0ac76 | 35,495 |
import mmap
import pickle
def load(path):
"""Load serialized object with out-of-band data from path based on zero-copy shared memory.
Parameters
----------
path : pathlib.Path
Folder used to save serialized data with serialize(). Usually a folder /dev/shm
"""
num_buffers = len(list(p... | 6c0ccc1d4941a6073b9f005774f53e3428dfc276 | 35,496 |
import socket
def GetOpenPort():
"""Returns an open port on the host machine.
Return:
an open port number as an int
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 0))
return int(sock.getsockname()[1]) | c0a329da5be24bc878217b150dd89ee77e5229b0 | 35,497 |
import torch
def secondary_sequence_metrics(x, ss_num=7):
"""
Compute metrics associated with with secondary structure.
It counts how many times a secondary structure appears in the proteins, and the median length of a sequence of
secondary structure, e.g. H, H, ..., H.
Parameters
----------... | 8ddc8df86438e0dee3aec45c2e573f4b39cca114 | 35,499 |
import os
def get_export_arguments():
"""Convert environment values into arguments."""
env = os.environ
return (env['EXPORT_PARENT'], env['GCS_DESTINATION'],
[ct.strip() for ct in env['EXPORT_CONTENT_TYPES'].split(',')],
[at.strip() for at in env['EXPORT_ASSET_TYPES'].split(',')]) | 9ed9474833806cf0e03daa86ed62617593adb8f3 | 35,500 |
import sys
def getPythonVersion(verbose=False):
"""returns which version of python is this"""
python_version = str(
"Python {major}.{minor}"
).format(
major=str(sys.version_info[0]),
minor=str(sys.version_info[1])
)
if verbose:
python_version = str(
"Python: {version}\n{flags}\n{copyright}\nBackend Py... | 5c7e9d51687dc5f7e2bac28ba59cc37798d9f111 | 35,502 |
import re
def clean_text(text):
"""
Remove code blocks, urls, and html tags.
"""
text = re.sub(r'<code[^>]*>(.+?)</code\s*>', '', text, flags=re.DOTALL | re.MULTILINE)
text = re.sub(r'<div[^>]*>(.+?)</div\s*>', '', text, flags=re.DOTALL | re.MULTILINE)
text = re.sub(r'<blockquote[^>]*>(.+?)</block... | 91934ecd7e5d037be1198bc645da8e507b5955ce | 35,503 |
import csv
def parse_labels_months(file_path='data/ae_pseudonyms.csv') -> dict:
"""
Parse age in months from csv
using row shorter dir stub
"""
dict_ = dict()
with open(file_path, newline='') as file:
reader = csv.reader(file)
for row in reader:
key = row[1].split('... | 64e0347f0d8a9fe1b1b7dbae8564c4dbff3c5b20 | 35,504 |
def list_string_to_dict(string):
"""Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``."""
dictionary = {}
for idx, c in enumerate(string):
dictionary.update({c: idx})
return dictionary | 0d9e3516e32bc69ee24d6afb19a7babcdba528f9 | 35,506 |
import os
def check_op_libSVM(input_dir='.', delete_file=True):
"""Perform terminal operation to identify possible classification failures
on the basis of number of files.
This works only for libSVM classification with stored results, as it
relies on files stored in the persistency directories... | 6217ad4bf384841bd4da2765d5278e3a69819d35 | 35,507 |
def _consume_rule(string):
""" Usage:
>>> _consume_rule('one {ONE} other {OTHER}')
<<< ('one', '{ONE} other {OTHER}')
>>> _consume_rule('other {OTHER}')
<<< ('other', '{OTHER}')
"""
def _get_rule_num(rule):
return {
'zero': 0, 'one': 1, '... | 398e3f16884ac4f2fe567d9eaa0e14c0e8f7fa42 | 35,508 |
def bytes_leading(raw_bytes, needle=b'\x00'):
"""
Finds the number of prefixed byte occurrences in the haystack.
Useful when you want to deal with padding.
:param raw_bytes:
Raw bytes.
:param needle:
The byte to count. Default \x00.
:returns:
The number of leading needl... | f57a4eef0bbf28df31c5a1f49d3e681f056403a9 | 35,512 |
def tags_from_context(context):
"""Helper to extract meta values from a Celery Context"""
tag_keys = (
'compression', 'correlation_id', 'countdown', 'delivery_info', 'eta',
'exchange', 'expires', 'hostname', 'id', 'priority', 'queue', 'reply_to',
'retries', 'routing_key', 'serializer', '... | 55376b0711a919757dfb97a314cd6b1a4175c8ae | 35,513 |
import re
def check_email(email):
"""
Checks if an email is valid
:param password: password to check
:return: True if the password is valid, false otherwise
"""
return bool(re.fullmatch(r"[^@]+@[^@]+\.[^@]+", email)) | f176a34b4666964dc96a84f75ee0c3e5539e0f6a | 35,514 |
def jaccard(a, b):
"""Creates a ...
Args:
a (float):
b (float):
Returns:
``float``: ``jac``
"""
jac = 1 - (a * b) / (2 * abs(a) + 2 * abs(b) - a * b)
return jac | 26acf9b1d0e0bacb800db7ade109cba52f299066 | 35,515 |
from typing import Sequence
def partial_numerator(n: int, a0: int, block: Sequence[int]) -> int:
"""Computes the numerator of the partial quotient p_n/q_n for the continued
fraction expansion sqrt(D) = [a0; (block)].
Adapted from http://mathworld.wolfram.com/ContinuedFraction.html"""
# handle base c... | 1cc350f1ee769e2e7fc599e729c593e5d38c17d8 | 35,517 |
import glob
import os
def contains_results(path, min_num=1):
"""
determines whether a directory contains at least min_num results or not
"""
return len(glob.glob(os.path.join(path, '*-results.json'))) >= min_num | b2f30c94bab9de546a2f8c0d803b560bba32dbe5 | 35,518 |
def all_cnt_info():
"""
Returns a print of all constants needed
"""
all_cnt_info={}
all_cnt_info['area']='Catchment size in square km'
all_cnt_info['timestep']='Time step for the model relative to an hourly timestep'
return all_cnt_info | 6ec9b96cfcae9a7f6e564c865fffb84b5450dabe | 35,519 |
import sys
import getpass
def _ask_pass(prompt: str) -> str:
"""Pide un password por consola, ocultándolo si se puede"""
prompt = "%s: " % prompt
if sys.stdin.isatty():
return getpass.getpass(prompt)
return input(prompt) | cc6466fd09cafb2b8c84ec2faafdc34bf93c4306 | 35,521 |
def ir(x):
"""
Rounds floating point to thew nearest integer ans returns integer
:param x: {float} num to round
:return:
"""
return int(round(x)) | 3ef85ede1dd773e2b9f67138a9448e9b47fd9610 | 35,522 |
def get_pos_association_dict(volumestokeep, outfiles_partititon):
""" Converts 3d index to numeric index
"""
index = 0
_3d_to_numeric_pos_dict = dict()
for i in range(outfiles_partititon[0]):
for j in range(outfiles_partititon[1]):
for k in range(outfiles_partititon[2]):
... | 092c9d33a59f10166443767558d65ad0901b594a | 35,523 |
import os
def get_sql() -> str:
""" get content of ../../create_tables.sql as string """
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, '../../create_tables.sql')
with open(filename) as f:
return f.read() | 9f2c5ac9c31a133c576daa15cb35c63d7d1ce77a | 35,525 |
from typing import List
def longest_consecutive_subsequence(arr: List[int]) -> int:
"""
1. Put the array in a set
2. For each array element i:
i. check if i-1 exists in set.
ii. if not, it is the starting point of a new subsequence.
iii. Count consecutive.
3. return max
O(... | f0115c3298c805e7af09d7f3ae5fd17c333ab726 | 35,526 |
def get_longitude_positive_direction(Body, Naif_id, rotation):
"""Define the positive longitudes in ographic CRS based on the rotation sens.
The general rule is the following:
* Direct rotation has longitude positive to West
* Retrograde rotation has longitude positive to East
A special case is don... | ff153ac2bd96f11e0341676b4fc6b348d4b256be | 35,528 |
def get_Cm_NO():
"""非居室の照明区画iに設置された照明設備の多灯分散照明方式による補正係数
Args:
Returns:
float: Cm_NO 非居室の照明区画iに設置された照明設備の多灯分散照明方式による補正係数
"""
return 1.0 | 1c3eaad477fe5d1ce88b8721ae1268d1bfa6aefa | 35,529 |
def setup_with_context_manager(testcase, cm):
"""
Use a contextmanager in a test setUp that persists until teardown.
So instead of:
with ctxmgr(a, b, c) as v:
# do something with v that only persists for the `with` statement
use:
def setUp(self):
self.v = setup_with_context_ma... | e1996c9650f02c89e8516ca9ae030f1a50576eda | 35,530 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.