content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def find(bdd, i):
"""
returns a list of all the u numbers of variable i
"""
l = []
for q in bdd["t_table"]:
if bdd["t_table"][q][0]-1 == i:
l.append(q)
return l | 060d2a5941175eb19e7359847fd902e59b04b266 | 683,613 |
def format_import(names):
"""Format an import line"""
parts = []
for _, name, asname in names:
if asname is None:
parts.append(name)
else:
parts.append(name + " as " + asname)
line = "import " + ", ".join(parts) + "\n"
return line | ad712e39e9ccd63abf7a989e6474aaca054b84dc | 683,614 |
def count_leading_spaces(string: str) -> int:
"""
Count the number of spaces in a string before any other character.
:param string: input string
:return: number of spaces
"""
return len(string) - len(string.lstrip(" ")) | 06d9393f5226a101cd0a81d974b9f7d317f8390c | 683,616 |
def replace_special_quotes(html_str: str):
"""
replace special quotes with html entities
"""
# special quotes
html_str = html_str.replace('“', '“')
html_str = html_str.replace('”', '”')
html_str = html_str.replace('’', '’')
html_str = html_str.replace('‘', '‘')
... | 247a03d912c2cc545826dee774adbe63be6c8c31 | 683,617 |
def bash_array(lst):
"""Converts python array [a, b, c] to bash array (a b c)"""
contents = ' '.join(str(x) for x in lst)
return '({:s})'.format(contents) | 25bafcf5e8f7d0e65eb7268b377c3a64e7d7fba8 | 683,618 |
import re
def get_length(s):
""" Determine the length of the string from it's name which is
prepended as:
"foobar%d" % N
"""
x = re.search("[\d]+$", s)
# there can be only one or no match here
n = 0
if x :
n = int(x.group(0))
return n | 6621eba4fcfa0eeb59c65eaf794aa37a85a76493 | 683,619 |
def runningSum(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
c = 1
for i in range(len(nums)):
s = 0
for e in nums[:c]:
s += e
res.append(s)
c += 1
return res | bc0fc11ec389daea9f5d8bc36477d4ab103757ab | 683,620 |
def my_num_to_words(p, my_number):
"""
Front end to inflect's number_to_words
Get's rid of ands and commas in large numbers.
"""
number_string_list = p.number_to_words(my_number, wantlist=True, andword='')
number_string = number_string_list[0]
for i in range(1,len(number_... | 3dfa8beaac2545a3b3c879351aab2288948d1d99 | 683,621 |
def index():
""" Index Uri von Web API """
return "API is live!" | 95bb3cdef44696090a926b630790e2829e00be3f | 683,622 |
from typing import Optional
import re
def _try_parse_port(port_str: str) -> Optional[int]:
"""Tries to extract the port number from `port_str`."""
if port_str and re.match(r"^[0-9]{1,5}$", port_str):
return int(port_str)
return None | 0dac3e8a0979c8218526ded3b788d5877061c9d4 | 683,623 |
def chmin(dp, i, x):
"""chmin; same as:
dp[i] = min(dp[i], x)
ref: https://twitter.com/cs_c_r_5/status/1266610488210681857
Args:
dp (list): one dimensional list
i (int): index of dp
x (int): value to be compared with
Returns:
bool: True if update is done
ex:... | ec67fd854a34180dcbe047245aef7e5fa23f1a46 | 683,624 |
def singlestar(index, soup):
"""
Written by Yi
"""
stars = soup.find_all("div", {"class" : "foreground"})[index]
full_star = stars.find_all("i", {"class" : "icon icon-pink icon-beach icon-star"})
half_star= stars.find_all("i", {"class" : "icon icon-pink icon-beach icon-star-half"})
total_st... | ec571ab1149d2b9b5d3f8e514c8c45697a703a06 | 683,626 |
def sum(n):
"""
Returns the sum of integers between 1 and `n` (inclusive).
This implementation uses recursion.
"""
if n == 1:
return 1
elif n > 1:
return n + sum(n - 1) | 21a435096cc914a9b91fdef9058524c18e8a788c | 683,627 |
def islist(string):
"""
Checks if a string can be converted into a list.
Parameters
----------
value : str
Returns
-------
bool:
True/False if the string can/can not be converted into a list.
"""
return (list(string)[0] == "[") and (list(string)[-1] == "]") | fc2c32f6d034ccc81ab1ef84369554fd164dda81 | 683,628 |
import os
def backend_fname_formatter(fname):
"""Removes the extension of the given filename, then takes away the leading 'backend_'."""
return os.path.splitext(fname)[0][8:] | 50737a2b1c53345fe65f0a1af38ab9f39f2cc1d6 | 683,629 |
import os
def is_existing_tomb(ctx, tomb_name):
"""Checks if the tomb, specified by the given name, exists in the catacomb.
Arguments:
tomb_name (str): The name of the tomb.
Returns:
A `bool`, True if the specified name corresponds to an existing tomb,
False otherwise.
"""
... | b7b5d6218e197f8cf4982368505a9ea593594a39 | 683,630 |
from typing import Optional
import re
def read_commit(version_data: str) -> Optional[str]:
"""Parse commit string from version data
@param version_data: Contents of version file
@return: commit, or None if not found
"""
p = re.compile('.*Commit: ([^\n\r]*)', re.DOTALL)
match = p.match(version_... | fa3bbe463f133984a874bd18a442a7ed248fd540 | 683,632 |
def z2lin(array):
"""dB to linear values (for np.array or single number)"""
return 10 ** (array / 10.) | 9ec85927580709efaae322a72f6dec21ebcf0e6a | 683,633 |
def model_field_attr(model, model_field, attr):
"""
Returns the specified attribute for the specified field on the model class.
"""
fields = dict([(field.name, field) for field in model._meta.fields])
return getattr(fields[model_field], attr) | b6fdd6be26c9f5c49f3f5c8ad05331f547fe4559 | 683,635 |
def search_min(array):
"""查找列表中的最小数"""
min_index = 0
min_num = array[0]
for i in range(len(array)):
if array[i] < min_num:
min_index = i
min_num = array[i]
array.pop(min_index)
return min_num | 82e3d93c1f8d3df8155303f6bc83a529c0ff6eed | 683,636 |
import os
def get_file_extension(file, **options):
"""
gets the extension of given file.
:param str file: file path to get its extension.
:keyword bool remove_dot: specifies that the extension must not
include the `.` character.
defaults to... | c3191dd3a69a2e3faaeefcdfd06683a1592c6500 | 683,637 |
import os
def get_themes():
"""
获取主题
:return:
"""
directory = os.path.join(os.path.dirname(__file__), 'themes')
return os.listdir(directory) | 2d680aeceba84de5ec40b176e3066386bdb1f8ea | 683,638 |
def count_models(block):
"""Count models in structure file block.
:param block: PDBx data block
:type block: [str]
:return: number of models in block
:rtype: int
"""
atom_obj = block.get_object("atom_site")
model_num = []
for i in range(atom_obj.row_count):
tmp = atom_ob... | 94f20675a76edfc202994d27442f5bd920b7528b | 683,639 |
def baseconvert(number,fromdigits,todigits):
""" converts a "number" between two bases of arbitrary digits
The input number is assumed to be a string of digits from the
fromdigits string (which is in order of smallest to largest
digit). The return value is a string of elements from todigits
(ordere... | 4d6e427113efef69c0112b2db54e1d56518ba4a0 | 683,640 |
def consecutive_ducks1(n):
"""
Time complexity: O(n)
Space complexity: O(n).
"""
# Edge case.
if n == 2:
return False
# Create dict cusum_idx_d:cusum->idx.
# Check if cusum - n exists in cusum_idx_d.
cusums = [0]
cusum_idx_d = dict()
cusum_idx_d[0] = 0
for i in r... | 376f62c62d1b3bcdece5a2b50af4a23d08aad0ff | 683,641 |
def hex_to_bin(txt: str) -> str:
"""Convert hexadecimal string to binary string.Useful for preprocessing the key and plaintext in different settings."""
return bin(int(txt,16))[2:] | beffae4a0eb8bda8a56e0a23fb9aefcdbd41dd37 | 683,643 |
def clean_lemma(lemma: str, pos: str) -> str:
"""Cleans whitespace and special symbols
Args:
lemma: Raw token lemma.
pos: Lemma POS.
Returns:
Clean lemma.
"""
out_lemma = lemma.strip().replace(" ", "").replace("_", "").lower()
if pos != "PUNCT":
if out_... | b38f04dd27384d5baa339d39efad4cf8ca45d3fd | 683,644 |
def to_byte(val):
"""Cast an int to a byte value."""
return val.to_bytes(1, 'little') | 556c5e416566384013a1bfdce7b14b8621d40c90 | 683,646 |
import math
def vector_to_distance(v):
""" start of vector is at 0, 0 """
return math.sqrt(math.pow(v[0], 2) + math.pow(v[1], 2)) | 0d84a1660ecfe655a1cd105535ebb93cbd1290c9 | 683,647 |
import os
def path_leaf(path):
"""Return the leaf of a path."""
head, tail = os.path.split(path)
# Ensure the correct file name is returned if the file ends with a slash
return tail or os.path.basename(head) | 39ff6a45a807c5307274a589019ffecb190178b6 | 683,649 |
import os
import fnmatch
def find_g4():
"""
Find all g4 files and return a list of them.
The recursive search starts from the directory containing
this python file.
"""
file_path = os.path.realpath(__file__)
parent_folder = file_path[0:file_path.rindex("/") + 1]
res = []
for cur, _... | ffa4e8eebcd8c7eaac7d0bce0121946746f03274 | 683,650 |
import time
def getTerm():
"""
获取当前学期,按时间计算,2-7月为第一学期,8-1月为第二学期
:return: Number 学期数
"""
month = time.localtime(time.time())[1]
if (month > 1 and month < 8):
return 2
return 1 | d21ddfdeaa7ee129108083f6226a1bdb12390a90 | 683,653 |
import re
def clean_title(title):
"""
Clean title.
Parameters
----------
title : str
title of FTM dataset.
Returns
-------
title : str
cleaned title of FTM dataset.
"""
title = re.sub('^[0-9\\.]+_+[a-z A-Z]+_', '', title)
title = re.sub('[0-9\\-]+.pdf$', ... | ed2ce240c470797907843ea357c28b728a650436 | 683,654 |
def quick_sort(arr):
"""Returns the array arr sorted using the quick sort algorithm
>>> import random
>>> unordered = [i for i in range(5)]
>>> random.shuffle(unordered)
>>> quick_sort(unordered)
[0, 1, 2, 3, 4]
"""
less = []
equal = []
greater = []
if len(arr) < 1:
... | e045c8111083314d567fc118b5bff4f6b61169af | 683,656 |
from typing import Tuple
import re
def replace_code(
begin_delim: str, end_delim: str, content: str, new_code: str
) -> Tuple[str, int]:
"""Replaces text delimited by `begin_delim` and `end_delim` appearing in `content`, with `new_code`.
Returns new string and number of matches made."""
return re.subn... | ab7cfff3c3ae7b0356a1b3558b2fa36c1beb5401 | 683,657 |
import requests
def get_root_domains(url, filename):
""" Updates root domain file.
:param url: URL of the root domains list.
:param filename: File name to write the list.
"""
r = requests.get(url)
with open(filename, 'w') as f:
f.write(r.text)
return True | d5427f77e4eba72b9952ea7b6059d620a18d5520 | 683,658 |
def create_hf(geom):
"""Create header and footer for different types of geometries
Args:
geom (str): geometry type, e.g., polygone
"""
if geom == "polygone":
header = """
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
... | 28276e77ccaa2943dfe4bd2f65a19347f6b1cc1c | 683,660 |
import copy
def _extended(original):
"""
Create the extension to the `original` list to make the laminate symmetric.
The position of the comments is taken into account.
"""
if sum(1 for la in original if isinstance(la, str)) == 0:
return original[::-1]
layers = copy.deepcopy(original)
... | 063e9f62fff70540b6f5afd11568e296cf910e10 | 683,662 |
import math
def string_to_array(s):
"""Convert pipe separated string to array."""
if isinstance(s, str):
out = s.split("|")
elif math.isnan(s):
out = []
else:
raise ValueError("Value must be either string of nan")
return out | 9e8755a15a2e8da4571d94be50200a01201912d3 | 683,663 |
import math
import hashlib
def adventcoin_mine(salt, zeros, prob=0.99):
"""MD5-hashes salt + counter, increasing counter until hash begins with a given number of 0's in HEX,
or until maximum value is reached
:param salt: string to append before countes
:param zeros: number of zeros to search for
:... | 5bab24e24611fc81e07767c91f9c447e0c78afa7 | 683,664 |
def _format_cached_grains(cached_grains):
"""
Returns cached grains with fixed types, like tuples.
"""
if cached_grains.get("osrelease_info"):
osrelease_info = cached_grains["osrelease_info"]
if isinstance(osrelease_info, list):
cached_grains["osrelease_info"] = tuple(osrelea... | b916043859288ae13ebfbe6e14daa3846baf4321 | 683,667 |
def help():
"""
print an help message
"""
out = " --- wgalp: a pipeline for bacterial Whole Genome Assembly ---\n\n"
out += "This programs is an helper to run the sub procedures of wgalp\n"
out += "usage: wgalp <program> [args]\n\n"
out += "the following is a list of all the available progra... | f03fa9408905414d1c15d89b8c9ca35f207ce732 | 683,668 |
def unfold_fields(lines):
"""Unfold fields that were split over multiple lines.
Returns:
A list of strings. Each string represents one field (a name/value pair
separated by a colon).
>>> unfold_fields("foo \n bar \n baz \nbiz \nboz ")
['foo bar baz ', 'biz ', 'boz... | 6270fc9c67bc3ab37e2262e6c7d161bb4a3cc505 | 683,669 |
def analyzer(klass):
"""Return an instance of the CUT with some defaults."""
a = klass(
start_states=["In Progress", ],
commit_states=["Selected", "Created"],
end_states=["Done", ]
)
return a | bf58bce04b6d4ad50ac38760b9a942f50ea2f944 | 683,671 |
def sync_user_forumuser(apps, schema_editor):
"""
Synchronizes the unsynchronized users with their forum user.
"""
User = apps.get_model('users', 'User')
ForumUser = apps.get_model('forum_tools', 'ForumUser')
for user in User.objects.filter(forumuser_id__isnull=True):
# triggers lookup a... | 7fbb6ee602244c759671b5529d996efb8335f83c | 683,673 |
import torch
def pack_sequences(seqs, lens):
"""
doesnt need sequences to be sorted by length. handles this for us/you
sequences should be [M][N][E]
returns the inverse sequence mapping to unpack later
"""
lens = lens.view(-1)
N = lens.size(0)
lens_sorted, lens_sorted_idxes = lens.so... | 33c0721bad7f767e8bece4786377e6eec3d199fd | 683,674 |
def map_symbols_to_currencies(currencies):
"""
Create dictionary where key is symbol of currency and value is
currency itself
:param list currencies:
List of dictionaries with data about many currencies
:return: Dictionary with symbols and currencies
:rtype: dict
:raises KeyError: ... | 5cb0516af69e86621dbcca338a52e911a65bc429 | 683,675 |
def good_morning_world():
"""
This is a python Airflow callable that returns 'Good Morning World!'.
:return: String
"""
return 'Good Morning World!' | 6f68a14ee92edfc9ece35ee25580308a9533318b | 683,676 |
import glob
import re
def get_filenames(start_path, look_in_path, subdir, *args):
"""retrieval function for all the files (recursive) leveraging glob
Args:
start_path ([str]): [string value of the start directory (of the script running)]
look_in_path ([str]): [the subdirectory (1 level down c... | 12fe501c97f181db4245ffac35e99766ec2f94e5 | 683,677 |
import os
def get_checkpoint_options(checkpoint_directory):
"""
List of available checkpoint iterations
Parameters
----------
checkpoint_directory : str
Path to checkpoint folder
Returns
-------
list
List of checkpoint iterations sorted from high to low
"""
re... | c9a7ceed98ec83ae8332073c2d08ded2cf920cdb | 683,678 |
def _compute_per_channel_loss(c1, c2, img1, img2, conv):
"""computes ssim index between img1 and img2 per single channel"""
dot_img = img1 * img2
mu1 = conv(img1)
mu2 = conv(img2)
mu1_sq = mu1 * mu1
mu2_sq = mu2 * mu2
mu1_mu2 = mu1 * mu2
sigma1_tmp = conv(img1 * img1)
sigma1_sq = sig... | 8cf7562c34ca5c87ccc9184642bea83ed00534f9 | 683,679 |
import math
def to_dB(value):
"""
Wert in logarithmische Form umrechnen
:param value: float
:return: float
"""
return 10 * math.log(value, 10) | 63a10b715607bdf49702b61dd4e5337393990f71 | 683,680 |
def cal_percision(label_list, classify_res):
""" calculate the percision"""
assert(len(label_list) == len(classify_res))
true_positive_count = 0.0
false_positive_count = 0.0
for i in range(len(label_list)):
if classify_res[i] == True:
if label_list[i] == True:
tru... | 5458819539110e5aae2868325cbfc796e4823603 | 683,681 |
def parse_authors(authors_data: list) -> list:
"""Extract information about contributors."""
authors = []
for author in authors_data:
authors.append({
'author_id': author.get('authorId'),
'first_name': author.get('first'),
'last_name': author.get('last'),
... | 23c27b03a597e9de8cc11a426b0f6ff6bff79996 | 683,682 |
def show_toolbar(request):
"""we can write some logic for whether toolbar should appear or not"""
return True | 941aeab11fe578e08fad26a5e39767b4d2d9c9ef | 683,683 |
def evaluate_rule(when, answer_value):
"""
Determine whether a rule will be satisfied based on a given answer
:param when:
:param answer_value:
:return:
"""
match_value = when['value'] if 'value' in when else None
condition = when['condition']
answer_to_test = str(answer_value) if c... | ff01753f9eaeeab7a91baf219cfb145c9c251b14 | 683,684 |
def update_time(original, add):
"""
original: string representing the original time of format YYYYMMDDHHMMSS
add: positive int, amount of days to add
"""
og_year = int(original[:4])
og_month = int(original[4:6])
og_day = int(original[6:8])
new_year = og_year
new_month = og_month
... | a06d3c15c9220978d1ed51166dcc09759d118d80 | 683,685 |
import yaml
def load_configs(s: str) -> dict:
"""Load config from string."""
return yaml.load(s, Loader=yaml.FullLoader) | 766969cd684fae6d873e96ba8f6bc6875f8f98fd | 683,686 |
def get_length_of_missing_array(array_of_arrays):
"""
Sort the list in ascending order and extract the lengths of each list into another list
Loop through the list of lengths searching to the greatest distance between 2 elements
if the distance is greater than 1, add 1 to the previous element (or subtra... | ec5210840d90448238195d113168e46dccd0685b | 683,687 |
def update_parameter(osi, new_value):
"""
Once the parameters in FE model are defined, their value can be updated.
Parameters
----------
osi: o3seespy.OpenSeesInstance
new_value: float
The updated value to which the parameter needs to be set.
Examples
--------
>>> impor... | df86503f2b903809dcba817c20b1a2f3144a013b | 683,688 |
import argparse
from sys import path
def is_variable(var):
""" """
var = var.lower()
if var not in ["temperature", "pressure", "t", "p"]:
raise argparse.ArgumentTypeError("{} is an invalid variable type".format(path))
return var | 7736981f84a21501f9f98f0e62d0dc9cb48d16b5 | 683,689 |
def fold_arguments(pysig, args, kws, normal_handler, default_handler,
stararg_handler):
"""
Given the signature *pysig*, explicit *args* and *kws*, resolve
omitted arguments and keyword arguments. A tuple of positional
arguments is returned.
Various handlers allow to process argum... | f47b470eccbff02a47247ff952948c8575cc5252 | 683,690 |
def extract_text_body(parsed_email):
"""
Extract email message content of type "text/plain" from a parsed email
Parameters
----------
parsed_email: email.message.Message, required
The parsed email as returned by download_email
Returns
-------
string
string conta... | 20f35f18850fb6ca5718242c7ce8e8162ea6eb1a | 683,691 |
from typing import List
def demand_satisfied(people_after: List) -> List[bool]:
"""Verifies that each person gets the appropriate number of appointments.
We assume that scheduling occurs over a single week. Thus, people in the
`1x` cohort get one test, people in the `2x` cohort get two tests,
and peo... | bd1e2c8286bf3ee48fa2300cfb8f7331cfcf16aa | 683,693 |
def GetMSBIndex(n):
"""
Getting most significiant bit
"""
ndx = 0
while 1 < n:
n = (n >> 1)
ndx += 1
return ndx | 945c78a4091a430968ce10400bb7f171bb74bf36 | 683,694 |
def post_truststore(operation=None, new_password=None, re_password=None, key_store_type=None, remove_alias=None, certificate=None): # noqa: E501
"""post_truststore
# noqa: E501
:param operation:
:type operation: str
:param new_password:
:type new_password: str
:param re_password:
... | 7a208246fbbcf61bfba3afcb783e6dbb9d576161 | 683,695 |
import ast
def _dedupe_ast(tree):
"""Takes an AST that has multiple identical classes defined and dedupes them."""
###
# As an intermediate step in the typegen process we fully expand the schema, this will
# result in all referenced types being defined with their namespace - even if the same()
# o... | b4f965307fbe2f98fcaea9beb29bac192e8f7076 | 683,696 |
def get_preposition(inp, apos=True):
"""Return the given string with the Turkish preposition "de/da" appended.
Do not add an apostrophe if the optional arg. apos is False.
"""
# Some exceptional cases:
if inp == "abd":
return "abd'de" if apos else "abdde"
elif inp.endswith("lar... | a55b5ff65ac9f427af395978eea0bfacb2371083 | 683,697 |
def get_portal_licensed_summary(self) -> dict:
"""Retrieves summary of portal licensed appliances
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - license
- GET
- /license/portal/summary
:return: Returns summary of... | 9714f9ffe8e694b3b455c8585072967f72787755 | 683,698 |
def vector_add(vector1, vector2):
"""
Args:
vector1 (list): 3 value list
vector2 (list): 3 value list
Return:
list: 3 value list
"""
return [ vector1[0] + vector2[0], vector1[1] + vector2[1], vector1[2] + vector2[2] ] | 744311e6cb1a67c1388cea3d281b38b44cc93346 | 683,700 |
import sys
import shlex
import subprocess
def runpy(py_file, stdin=None):
"""Run python script and return output.
This is sort of like check_output, which was introduced in python 2.7.
"""
cmd = [sys.executable]
cmd += shlex.split(py_file)
stdin_val = subprocess.PIPE if stdin else None
... | b4eddc70e1de148ca8f77ed5698850ace29a4d94 | 683,701 |
import textwrap
def long_string(s: str) -> str:
"""left strip and dedent the string
Args:
s (str):
Returns:
left string and dedent the string
"""
return textwrap.dedent(s).lstrip() | 0c1ab3fa41dbfbd0b8561aa9fe89f2050ab4cb4b | 683,702 |
def progress_to_dict(path: str) -> dict:
"""
Converts a Delphin progress file into a dict.
:param path: path to folder
:return: converted progress dict
"""
file_obj = open(path + '/progress.txt', 'r')
lines = file_obj.readlines()
file_obj.close()
progress_dict = {'simulation_time'... | 879f655427307e88da5057574419a491188b93b7 | 683,703 |
import torch
def round(tensor, decimal_places):
"""
Round floats to the given number of decimal places.
:param tensor: input tensor
:type tensor: torch.Tensor
:param decimal_places: number of decimal places
:types decimal_places: int
:return: rounded tensor
:rtype: torch.Tensor
""... | dc6d6adeb4607fffb43d0442bcc5a24e38ed74d3 | 683,704 |
def split_parts(msg):
"""Splits a key=value pair into a tuple."""
index = msg.find("=")
return (msg[:index], msg[index+1:]) | 1e7392f3f24556a0bf69789f986a1470ce512cd8 | 683,706 |
import mimetypes
def guess_extension(mime):
"""Shortcut for getting extension to a given mime string.
The parameter mime can be None"""
return mimetypes.guess_extension(type=mime or "") | 6c38133bcf8378a8228c4e39e930794411666691 | 683,707 |
import random
import torch
def random_inpainting(image, cnt=5):
"""[summary]
masking images with random window blocks, where values are randomly draw.
code is adapted from Model Genesis: https://github.com/MrGiovanni/ModelsGenesis/blob/master/pytorch/utils.py
Args:
image ([ torch tensor]): a b... | 58ae97494ba5a52dc2f844ef5f7e5fc4c3a36de3 | 683,708 |
import re
def idify(utext):
"""Make a string ID-friendly (but more unicode-friendly)"""
utext = re.sub(r'[^\w\s-]', '', utext).strip().lower()
utext = re.sub(r'[\s-]+', '-', utext)
if not len(utext):
# Headers must be non-empty
return '_'
return utext | 9ec7b4d49e1cdf256d6362adf7b0a134843da054 | 683,710 |
import os
import pickle
import sys
def recover():
"""Recover running app from temp pickle file"""
if os.path.exists("tweets_crawler.py.tmp.pickle"):
with open("tweets_crawler.py.tmp.pickle", "rb") as inFile:
app = pickle.load(inFile)
return app
else:
print("No tmp pickl... | 1b43f8de5bd60d2b848c694ef1a31540a401606a | 683,711 |
def register_backend_funcs(func):
"""
Register the specific function in extension as backend methods
:param func: The instance function needed to register as backend
method
:type func: instancemethod
:return: None
"""
func.is_backendmethod = True
return func | d2a634dc9e4abcfc9257b763eba5a150366e68fe | 683,712 |
from typing import List
def join_output(input: List[List]) -> str:
"""Return string based on chunk data which is an List of lists.
Params
--------
input: List[List]
self.model output which is an list
of list in case of chunked data.
Returns
--------
results: str
... | ddb27e7bfcf7af69469a30f2596435a6effbc46c | 683,713 |
def my_func02(num01, num02):
"""
返回两个参数的和
:param num01: 数字1
:param num02: 数字2
:return: 两个数字的和
"""
return num01 + num02 | 4426ec968773ec10972565f70b08d1aa61537e6b | 683,715 |
def validate_parameters(value, ctx=None): # pylint: disable=unused-argument
"""Validate 'parameters' dict."""
parameters = value.get_dict()
try:
plot_num = parameters['INPUTPP']['plot_num']
except KeyError:
return 'parameter `INPUTPP.plot_num` must be explicitly set'
# Check that ... | fa8830f89ba2ee04adcf96cc6bce5bfa7ef5613a | 683,718 |
def read_prep_times():
""" This function manually reads T2-prep times (iBEAt study specific function) and returns it as a list."""
## hard coded as these are not available in the anonymised Siemens dicom tags
T2_prep_times = [0,30,40,50,60,70,80,90,100,110,120]
return T2_prep_times | 5247f4aa8095831ea2e1b188bb3d093ee4a972a6 | 683,721 |
def map_msa_names(df, msa_lookup):
""" Helper function to handle known MSA name changes/inconsistencies
:param df: A pandas dataframe, BLS OEWS data set
:param msa_lookup: a dictionary containing MSA code to peer type lookup
:return df: A pandas dataframe
"""
df['area_title'] = df['area'].map... | d7f07645903a44c4a2e44620778e825eedbae1a5 | 683,722 |
def possible_films(country, year):
"""
This function makes list of possible films using setted
year and country you entered.
"""
result = list()
with open("locations.list") as file:
for line in file:
if year in line:
line = line[:-1]
line = lin... | 5727ea7e374b1f3a5c756477fd3303ce2eb68bee | 683,723 |
def height(ep, m):
"""
Calculate and return the value of height using given values of the params
How to Use:
Give arguments for ep and m params
*USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE
IT'LL BE HARD TO UNDERSTAND AND USE.'
Parameters:
ep (int):... | 2e3523cc9ce6cc2f381ddd3307d1d502a825e31a | 683,724 |
def legend(is_legend_show=True,
legend_orient="horizontal",
legend_pos="center",
legend_top='top',
legend_selectedmode='multiple',
**kwargs):
""" Legend component.
Legend component shows symbol, color and name of different series.
You can click ... | e8110aa8e45ea210162a70fc5607c08e5af84a6a | 683,725 |
def get_average(numbers):
"""
Args:
numbers (list): A list of floats.
Returns:
float: The average of the floats in numbers list.
"""
total = 0.0
for number in numbers:
total += number
return total/ len(numbers) | 2370be5a43e459ef6a0daa586246860b3b6030ce | 683,726 |
def pixel(cube):
"""Testing pixel (ground and specular)."""
return cube[6, 32] | ee8deef9b5c465ae1b9af307c87882821b16b346 | 683,728 |
def set_hidden_measurement_lists_from_Ns_Nv(num_nodes, Ns, Nv, list_bus_id_power_hiding_priority=None, list_bus_id_voltage_hiding_priority=None):
"""
Returns the list of the hidden power bus ids and a list of hidden voltage ids
:param num_nodes: number of buses in the grid
:param Ns: Number ... | aefdf4e2a4179e732387169a8e0f96e581ee5052 | 683,730 |
def get_foo():
"""Get some foo.
Returns:
A string contaning a nice foo.
"""
return "foo" | a3e30f6250cb6aa6f057beed4258f74ca66544dd | 683,731 |
def scale_dict(all_perfs:dict, MODELS:list, ATTACKS:list, PERFS:list, TRIALS):
"""intialize a dictionary of performances
"""
for m in MODELS:
for a in ATTACKS:
for p in PERFS:
all_perfs[''.join([p, '_', m, '_', a])] /= TRIALS
return all_perfs | 29042475136419a777c551e4a3b12328e800be82 | 683,732 |
import os
import logging
def is_root():
"""If SPET has root access or not.
Example:
>>> is_root()
True
Returns:
Boolean: If root access or not.
"""
try:
return os.getuid() == 0
except IOError as err:
logging.error(err) | ff4e9cf97dd61a891029298448386f74a2e7e5e6 | 683,733 |
import os
def fixture_bak_cleanup():
"""Cleanup bak file which is created during migration."""
bak_fnames = []
def _fixture_back_cleanup(bak_fname):
bak_fnames.append(bak_fname)
return bak_fname
yield _fixture_back_cleanup
for bak_fname in bak_fnames:
print("teardown of ... | ca746e6903b66973ed5a463dd58e0cfc6b641f18 | 683,734 |
def denormalize_m11(x):
"""Inverse of normalize_m11."""
return (x + 1) * 127.5 | a7c6edd415cf80e2574051194e7276acbef562d0 | 683,735 |
def test_row(dataframe):
"""
test if dataframe contains at least one row
Parameters
----------
dataframe: pandas dataframe
Raises
------
ValueError
If number of row is smaller than 1, raise ValueError
Returns
-------
is_valid: boolean
True if greater than 1... | 84d73e21a662ae3eac749cee15815507178090a5 | 683,736 |
def _get_elem_at_rank(rank, data, n_negative, n_zeros):
"""Find the value in data augmented with n_zeros for the given rank"""
if rank < n_negative:
return data[rank]
if rank - n_negative < n_zeros:
return 0
return data[rank - n_zeros] | 6517ccc434e86640141278e049a8ff62b4faa8d2 | 683,737 |
def gc_content(sequence):
"""Return the proportion of G and C in the sequence (between 0 and 1).
This function is equivalent to `goldenhinges.biotools.gc_content()`.
**Parameters**
**sequence**
> An ATGC string (`str`).
"""
return 1.0 * len([c for c in sequence if c in "GC"]) / len(seque... | 9276eb77a6431b7c61b0b4944267761d83b69c6d | 683,738 |
import socket
import traceback
def read(HOST, PORT):
"""
Method that opens a TCP socket to the robot, receives data from the robot server and then closes socket
Returns:
data: Data broadcast by the robot. In bytes
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout... | 71888f5ca0203247784ad021aa039695252ecb00 | 683,739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.