content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def tokenizer_parser(x):
"""
remove_flag e.g. In article
remove extra space in the middle
remove special symbol
"""
x = re.sub("(?:In article)?.*writes:", "", x, flags=re.S)
# x = re.sub(" {2,}", " ", x) # compress space
# x = " ".join(word_tokenize(x, preserve_line=True)).s... | 694715b5b7a10cec67c08ab45aa1c78630df39e1 | 635,709 |
import pandas as pd
def LoadCsv(path):
"""
CSVファイルのロードを行う
戻り値:値配列
"""
csv_frame = pd.read_csv(path)
data = csv_frame.values
return data | 02141aa47adbca3d3d304f18d774bec198e6ad23 | 635,711 |
def convert_string(*, start='|', newlines=True):
"""Return a function that can be used as a converter.
The default converter ``str`` handles multiline values like
:class:`~configparser.ConfigParser`, i.e. preserving newlines but
ignoring indentations (because nothing gets realy converted).
A conve... | c1c29aca537f5669deafa15eae3608a21d0f3859 | 635,712 |
def _parse_string(s):
"""Parse a string representation of a tree structure (implementation)
Nodes are separated by whitespace, while child lists are enclosed in
balanced parentheses.
Return value is a tuple of (tree_structure, length_in_characters)"""
if '(' not in s:
s, _, _ = s.p... | d347f090c60c0c663ff3d6d778c7977cc2cd84e8 | 635,714 |
def db_consistent(dict_in_dict):
"""
Returns True iff every inner dictionary has the same keys.
>>>db_consistent(x)
False
"""
listofsets = []
for k in dict_in_dict:
for d in dict_in_dict[k]:
setofk = set()
for dk in d:
setofk.add(dk)
... | 1f2a5cb65eabbf2bb3ebb7029f835713890aff59 | 635,715 |
from io import StringIO
import tokenize
import token
def _get_indentword(source):
"""Return indentation type."""
sio = StringIO(source)
indent_word = ' ' # Default in case source has no indentation
try:
for t in tokenize.generate_tokens(sio.readline):
if t[0] == token.INDENT:
... | 26eed1ce4b78f841ab640a5c63c1a844ead8e99c | 635,716 |
def reformatExampleBlock(lines, name):
"""Turn an example block into a verbatim text.
"""
out = [u'::', u'']
out += lines
# safety line
out.append(u'')
return out | 908ed6bbbafa622f7ca62700a016c5fe3d246014 | 635,717 |
def chr_less(chr_left, chr_right, sorted_lex):
"""
Returns true if the left chromosome comes before the right or is the same.
Args:
chr_left = (string) the left chromsome being compared
chr_right = (string) the right chromosome being compared
sorted_lex = true if file sorted lexicog... | 8db132ffcdbfdc585dc8efadd3e2ddc0b8f83dd7 | 635,718 |
from typing import Optional
import re
def get_package_version(
package_xml_path: str,
) -> Optional[str]:
"""
Get a package's version from its package.xml file.
:param package_xml_path: the path to the package's package.xml file
:return: the version, or None if it failed
"""
version = Non... | 2b8bc740232f077601258ff0acca8d91112a28f7 | 635,719 |
def find_subnet_nat_instance(subnet_id, ec2_conn, vpc_conn):
"""
Find the NAT instance for the given subnet
:param subnet_id: The desired subnet
:param ec2_conn: A boto.ec2.connect_to_region() object
:param vpc_conn: A boto.vpc.connect_to_region() object
:return: The NAT instance public IP
"... | 2f071a2962832d1793d45589100835025e69a6e7 | 635,721 |
def get_edit_icon():
""" Should return None or some other icon from `templates/_bytesize_icons.html` if the fork is not on GitHub.
"""
return "github" | cbf446be3968d54758bcbd5b60d32f0adc921f0b | 635,722 |
def copy_config(conf, repeat):
"""
make 'repeat' copies of the config files.
"""
res = []
for x in range(repeat):
res.extend([conf])
return res | 166cc4626c010ca1d30def4320f15244d50dc592 | 635,723 |
from typing import Dict
def append_qsa(uri: str, qsas: Dict[str, str]) -> str:
"""Appends QSAs to a URL & sorts according to an order"""
def qsa_sort(key: str) -> int:
if key == "uri":
return 0
elif key == "_profile":
return 1
elif key == "_mediatype":
... | 03686f2090a2b470719f1ee7ec8d2e1884251d37 | 635,724 |
import os
def is_valid_mapdata(parser, path_to_mapdata):
"""Check if path_to_mapdata is a valid path."""
if os.path.isfile(path_to_mapdata):
return path_to_mapdata
else:
if path_to_mapdata == "":
parser.error(
"You have to specify the path to the mapdata file " ... | 4eb7f6f9edc15ae68981bab0f9c9227fbf2d2670 | 635,725 |
import json
def eval_functions_dumps(obj):
"""
This is a replacement for json.dumps that
does not quote strings that start with 'function', so that
these functions are evaluated in the HTML code.
"""
if isinstance(obj, str):
if obj.lstrip().startswith("function"):
return ob... | b0ecdb178e401c04753df6a04ec490682e046f68 | 635,726 |
def edge(geom):
"""
return a polygon representing the edge of `geom`
"""
h = 1e-8
try:
geomext = geom.exterior
except:
try:
geomext = geom.buffer(h).exterior
except:
geomext = geom
return geomext | d65d80910e7fe4b2b4b81fe566c705900cdb48d9 | 635,728 |
from sys import exc_info
def excinst():
""" Exception instance inside try/except block. """
return exc_info()[1] | e5860586c400e398b87d9ea73d96a5b0d6087913 | 635,729 |
def health():
"""
:return: 200 with message health
"""
return 'Health!' | 1c7748f12810a08a6e46929db04baa87eea3bb11 | 635,730 |
def prime_sieve(num: int) -> list[int]:
"""
Returns a list with all prime numbers up to n.
>>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> prime_sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> prime_sieve(10)
[2, 3, 5, 7]
>>> prime_sieve(9)
[2, 3,... | aec8a9f257f069668f1dda2eaa447dbedb0f85d8 | 635,731 |
def lca(u, v):
"""
Computes least common ancestor of 2 nodes (ExtNode) using log_parents and depth
:type u: lca of the nodes
"""
if u.depth < v.depth:
u, v = v, u
for i in range(len(u.log_parents), -1, -1):
if len(u.log_parents) > i and u.log_parents[i].depth >= v.depth:
... | 48cd667d4c5c42cf8669309364d09d05806630d1 | 635,732 |
from typing import Tuple
from pathlib import Path
def get_relative_and_absolute_paths(path: str) -> Tuple[str, str]:
"""Get relative (if possible) and absolute versions of path."""
absolute_path = Path(path).resolve()
try:
relative_path = absolute_path.relative_to(Path.cwd())
except ValueError... | e4cb546594a425997427cf607a561f78184b0152 | 635,733 |
def getRequestRedirectForRole(entity, role_name):
"""Returns the redirect to create a request for a specific role.
"""
result ='/%s/request/%s' % (
role_name, entity.key().id_or_name())
return result | 62012503b90ed14658c931d83943d896673eb44f | 635,734 |
def get_total_fuel(fuel_list):
"""Get the fuel that the submarine would spent."""
total = 0
for fuel_i in fuel_list:
total += fuel_i
return total | dd759d1d574dba3857e1c0230740ab661bf7c170 | 635,735 |
def run_log_retention_in_days() -> int:
"""How many days to keep node run times, output logs and system statistics"""
return 30 | 33f2e782f50413e56db8e9d977b9fecdd639a118 | 635,736 |
import warnings
def WrapMod(mod, deprecated):
"""Return a wrapped object that warns about deprecated accesses"""
deprecated = set(deprecated)
class Wrapper(object):
def __getattr__(self, attr):
name_map = [item for item in deprecated if item[0] == attr]
if name_map:
warnings.warn(f'Property {name_map[0... | 17a21e0890faaf1df5f4fb14cbb7f37e0da66770 | 635,737 |
import shutil
def get_ncnn2int8_path() -> str:
"""Get onnx2int8 path.
Returns:
str: A path of ncnn2int8 tool.
"""
ncnn2int8_path = shutil.which('ncnn2int8')
if ncnn2int8_path is None:
raise Exception(
'Cannot find ncnn2int8, try `export PATH=/path/to/ncnn2int8`')
r... | c94a53a20250e27e707a007de20f748edde196a8 | 635,738 |
import uuid
def get_schema_config_data(db_user):
"""This function is used to get advance config test data for schema"""
data = {
"deffuncacl": [],
"defseqacl": [],
"deftblacl": [],
"deftypeacl": [],
"name": "test_schema_{0}".format(str(uuid.uuid4())[1:8]),
"name... | 5c916c7c00cf1d635a789f5a587f71439a0c91a3 | 635,740 |
import re
def filter_list(items, ignores, search=False):
"""
IF SEARCH IS NOT TRUE, IGNORES MUST BE AN EXACT MATCH
take a list of items
take a list of itmes to ignore
return a new list of items based on first, original, with ignores removed
"""
for i in ignores:
if i in items:
... | 407c8c64928267267314927ba5eb6ebecb189025 | 635,741 |
import os
def get_data_folders(project_path, conf_file):
"""Get data folders and associated type (*markers and/or emg and/or emg*).
:param project_path: path to the project
:type project_path: str
:param conf_file: json conf file load as dict
:type conf_file: dict
:return: output: dict contai... | 923a21008d1f86f6e2acbf35759ba06160316390 | 635,742 |
import hashlib
def get_hashed_string(s):
"""Given a string s return a sha1 hashed version"""
return hashlib.sha1(s.encode('utf-8')).hexdigest() | 29be25216bb9c4e74000abdcb94d8dbd3e3b9761 | 635,744 |
def mapear (funcao, lista):
"""
aplica função em cada elemento de lista;
retorna lista com resutlados
"""
return list (funcao(elemento) for elemento in lista) | a9258e05d04e56533dc4a75eb68b7b71ec2a75bb | 635,745 |
def hosts_contain_id(hosts_data, host_id):
"""
True if host_id is id of a host.
:param hosts_data: list of hosts
:param host_id: id of a host
:return: True or False
"""
for host in hosts_data:
if host_id == host['id']:
return True
return False | 23d6cd7da2a0c508564d19135d024700b40ce8c6 | 635,746 |
def _above_threshold(flatstat, threshold):
"""Returns true of the CC of flatstat is
equal to or above self.threshold."""
return flatstat[2] >= threshold | 915fa680a31d2608133f125a7c98395a54d4cd75 | 635,747 |
import os
def skip_test_in_production_env():
""" skip this test in production environment
"""
return os.environ["TEST_ENV"] == "PRODUCTION" | 47634f477e45b3f6ab3b57096d25699f2c3f5aec | 635,748 |
import json
def load_dict_from(filename):
"""
:param filename: The local path where the asn2asn.json file is stored
:return: a dictionary of the given .json file
"""
with open(filename) as json_file:
data = json.load(json_file)
return data | bcab4d6a3f691f2ae6b12ec020c3119143fcbf90 | 635,749 |
def unique_values(rows, idx):
"""Checking for unique values in table.
rows : [{ }, { }, ...]
idx : dict key (column name)
"""
# counting occurances of the values (value for "idx" key)
cnt = {}
for i,x in enumerate(rows):
try:
value = x[idx]
except KeyError:
... | b728b9781786018e22ef2e57ae295caa5ce6d7ce | 635,751 |
import re
def validate_gene_sets(genesets, var_names, context=None):
"""
Check validity of gene sets, return if correct, else raise error.
May also modify the gene set for conditions that should be resolved,
but which do not warrant a hard error.
Argument gene sets may be either the REST OTA form... | 0c47b6c5f8674c6d29bfd191af4af4adcbfb7366 | 635,752 |
def _get_placeholder_fields_map(client, customer_id, feed_resource_name):
"""Get mapping of placeholder fields to feed attributes.
Note that this is only intended to produce a mapping for real estate feeds.
Args:
client: An initialized GoogleAds client.
customer_id: The Google Ads customer... | dc825c653633f26d6e08e04982198ac599936b3d | 635,753 |
from typing import Set
def all_subclasses(cls) -> Set:
"""Return all (transitive) subclasses of cls."""
res = set(cls.__subclasses__())
for sub in res.copy():
res |= all_subclasses(sub)
return res | c5bcc25fe4ae6be39f1a458f97f086f88d6b3415 | 635,754 |
def controler_types(*a_args, **a_kwargs):
"""On attend en paramètres du décorateur les types souhaités. On accepte
une liste de paramètres indéterminés, étant donné que notre fonction
définie pourra être appelée avec un nombre variable de paramètres et que
chacun doit être contrôlé"""
def decor... | e93094860fc5e5455c546e2fdbed27109988b0e2 | 635,755 |
import hashlib
def string_to_md5(content):
"""Calculate the md5 hash of a string.
This 'string' can be the binary content of a file too."""
content = content.encode("utf8")
return hashlib.md5(content).hexdigest() | 5a0fe4a35a9c067708439574c6ece1c42746e80a | 635,757 |
def with_request(method):
"""
Decorator to enable the request to be passed as the first argument.
"""
method.with_request = True
return method | 05433aaa34018603a7392094132ef6c8b3c62ddf | 635,758 |
def _GetHoles(i, n, cont, assigned):
"""Find holes for path i: i.e., unassigned paths directly inside it.
Directly inside means there is not some other unassigned path k
such that path such that path i contains k and path k contains j.
(If such a k is already assigned, then its islands have been assign... | b058c077527fb184ef700a7b1104679083074ef8 | 635,759 |
def parse_arguments(*args):
"""
Parse arguments into a dictionary.
Returns
-------
tuple
First element with codes and second element
with names.
Examples
>>> utils.collect_args({"A": 1, "B": 2}, 100)
{"A": 1, "B": 2, 100: 100}
"""
d = {}
for arg in args:
... | 197e14a67f97e306047b9316f9ba9896eca4efed | 635,760 |
def _get_score(rectangle):
"""
Get count of locations above vs below or left vs right in order to do
symetry checks.
"""
def _get_row(xrow):
return xrow // len(rectangle)
def _get_rot_row(xrow):
return xrow % len(rectangle)
def _local_op(indx):
return [_get_rot_row,... | 30cc1c5d43ca56d2a5c2353050f26228d5d12e6d | 635,761 |
def get_unique_office_name(element=None):
"""Provide an autogenerated unique <office:name> for the document.
"""
if element is not None:
body = element.document_body
else:
body = None
if body:
used = body.get_office_names()
else:
used = []
# unplugged current ... | 0e7cf51241cc3b3be77b15c11fcb8c96f3a20e57 | 635,762 |
def key(row, key_attributes):
"""Return a key for identifying equivalent rows.
Return a key consisting of a tuple of the key attributes for the
row, which should be a dict-like object.
Parameters
----------
row : dict-like
The row for which to create a key.
key_attributes : List[st... | 1a4ce8d1818f48c7e21442e21b07eac0edf43920 | 635,763 |
import sys
def convert_relative_time(time_string):
"""Takes a single +XXXX[smhdw] string and converts to seconds"""
last_char = time_string[-1]
user_value = time_string[0:-1]
if last_char == 's':
seconds = int(user_value)
elif last_char == 'm':
seconds = (int(user_value) * 60)
... | 5846bf307e52b889210fb0326f4977cfb630a4d1 | 635,764 |
def get_cluster_status(els):
"""Function: get_cluster_status
Description: Return status of the Elasticsearch cluster.
Arguments:
(input) els -> ElasticSearch instance.
(output) Status of the Elasticsearch cluster.
"""
return els.cluster.health()["status"] | b8f129f3f6f8687b363835492b1420881f96a9b1 | 635,765 |
import subprocess
def git_available():
"""
Indicates whether ``git`` is available on the system.
Result is cached by functools.lru_cache
"""
return (
subprocess.call(
["git", "--version"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
== 0
) | af501e8f08584cee52fd21225fdf59777d4ec5f5 | 635,767 |
import os
def tail_logfile(logfile=''):
"""Read 50 lines of the logfile"""
result = "Can't read logfile."
try:
bufsize = 8192
lines = 50
logfsize = os.stat(logfile).st_size
iter = 0
with open(logfile) as f:
if bufsize > logfsize:
bufsiz... | 17941c305cd5a1ee01e411b4d80bcd0a89b78c08 | 635,768 |
def stop_word_filter(tokens):
"""
удаление общеупотребительных слов (таких например как a, I, the, таким образом заводим список стоп-слов)
:param tokens:
:return: возвраащает список токенов без стоп слов
"""
result_tokens = tokens
return result_tokens | d26d7c6dba87eca39ce1b46a1d4bf58c73e0be1b | 635,769 |
def _datastore2string(data, padbyte=None, padtosize=None):
""" A helper function for packing the whole data store into
a string.
See DataFormatterBinary.write() for the explanation of
parameters.
"""
str = ''
if data.num_records() == 0:
return str
# If the first re... | 078f48adabe1634c29f6f71b86f11e72b40e665e | 635,770 |
def path(start, end):
"""
>>> path((1,1), (1,1))
[]
>>> path((0,0), (2,2))
[(1, 1)]
>>> path((1,2), (7,5))
[(3, 3), (5, 4)]
>>> path((9, 10), (6, 10))
[(8, 10), (7, 10)]
>>> path((10, 9), (10, 6))
[(10, 8), (10, 7)]
>>> path((1,1), (3,8))
[]
>>> path((4, 2), (4, 4... | bc6e6d0787afdb1fb9a80fce84c65ec40937adb2 | 635,771 |
def convert_words_to_id(corpus, word2id):
"""Convert list of words to list of corresponding id.
Args:
corpus: a list of str words.
word2id: a dictionary that maps word to id.
Returns:
converted corpus, i.e., list of word ids.
"""
new_corpus = [-1] * len(corpus)
for i, wo... | df0e3211a53936a641b3d41dcac01f2e613465fe | 635,772 |
def endfInterpolationLine( interpolation ) :
"""Makes one ENDF interpolation line."""
s = ''
for d in interpolation : s += "%11d" % d
for i1 in range( len( interpolation ), 6 ) : s += "%11d" % 0
return( s ) | d627b4001885ec06dce913aca1b47ee112a9bc17 | 635,773 |
def glob_to_regex(pattern):
"""Given a glob pattern, return an equivalent regex expression.
:param string glob: The glob pattern. "**" matches 0 or more dirs recursively.
"*" only matches patterns in a single dir.
:returns: A regex string that matches same paths as the input glob does.
"""... | 9118549123e298bcf47664e53c13291824083e2c | 635,774 |
def create_global_ctu_function_map(func_map_lines):
""" Takes iterator of individual function maps and creates a global map
keeping only unique names. We leave conflicting names out of CTU.
A function map contains the id of a function (mangled name) and the
originating source (the corresponding AST file... | 7656a2c039f925c9443e903b9da08e59d0295217 | 635,775 |
def temp2():
""" This is weird, but correct """
if True:
return (1, 2)
if True:
return (2, 3)
return (4, 5) | 7b2ece10d876848905bf533a91fcb6b7040ccf8a | 635,776 |
import uuid
def test_run_identifier(skin):
""" Return a session based random prefixed UUID used for
identifying data created in this test run.
"""
return "QA-{0}-{1}".format(str(uuid.uuid1()), skin) | 5c7596a890f793317d17a7b2d4d1ddc368182492 | 635,777 |
def isNodeNotEmpty(parent_node):
"""
params:
- parent_node:
return:
- (bool):
"""
lenNode = parent_node.__len__()
for i in range(lenNode):
child = parent_node.__getitem__(i)
if child.tag == 'isNotEmpty':
if child.text == 'True':
return True... | d3b3ca33404f727641fa1c6de231ba33f9640983 | 635,778 |
def Y(fck):
""" Determina lamba en funcion del fck e Mpa o N/mm2"""
if fck <= 50:
Y = 0.8
elif fck > 50 and fck <= 90:
Y = 0.8 - (fck - 50)/400
else:
Y = None
return Y | e2f136dbcb3eb9ba6ae8a7e77614cdb2e53cd099 | 635,779 |
def suma(a, b):
"""
Devuelve la suma de <a> y <b>.
"""
return a + b | 6f481ffa6657b78a080a4ec6c3c20eb34686e62e | 635,780 |
def determine_nnz(X, rowCount):
"""
Uses close to no memory at all when computing how many non
zeros are in the matrix. Notice the difference with Scipy
is HyperLearn does NOT use nonzero(). This reduces memory
usage dramatically.
"""
nnz = 0
n,p = X.shape
for i in range(n):
currNNZ = 0
Xi = X[i]
for j... | b680af7a9e675f556add7fc6cacd4bbd3272ccb6 | 635,781 |
def _to_cli_args(opts:dict):
"""
convert dict to cli options for HM & VTM softwares
"""
args = []
for k, v in opts.items():
if k.startswith('--'):
args.append(f'{k}={v}')
else:
args += [k, str(v)]
return args | c176b86bbcbcd4af69f7be3c7b6a55f1e18ea906 | 635,782 |
import itertools
def by_attributes(entities):
"""
entities: list of DXF entities
attributes: thickness and width occurring in curve types; subdivision_levels occurring in MESH dxf types
"""
def attributes(entity):
width = [(0, 0)]
subd = -1
extrusion = entity.extrusion
... | 9c578d9cd58ebb99384255fe558fdf02c1458278 | 635,783 |
def endf_float_str(value):
"""
Return the ENDF format string of a floating point number
Parameters
----------
value : float
A single floating point value
Returns
-------
valstring : str
An ENDF format string of input par `value`
"""
if(abs(value) < 1e-9 or abs(v... | 502c7e777cc15da0ec0a9c033a536cea03306d40 | 635,784 |
def toXml(dbo, parent=None, baseuri='', view=''):
"""Convert a BQObject to an etree object suitable for XML
generation
"""
node = dbo
return node; | c0a4d5f9f3ff08c4f803454a011cfd45ea5af8c1 | 635,785 |
def is_derivative_symbol(expr, t_symbol=None):
"""
Returns whether expr is a derivative symbol (w.r.t. t)
:param expr:
:param t_symbol:
:return: True or False
"""
if t_symbol is not None:
# we currently do not distinguish between different independent variables
raise NotImp... | 1bdf369dfe9bc74872bd5097e9f018cc5d5b2c52 | 635,787 |
def next_permutation(seq):
"""Emulation of C++ std::next_permutation:
Treats all permutations of seq as a set of "dictionary" sorted
sequences. Permutes the current sequence into the next one of this set.
Returns true if there are more sequences to generate. If the sequence
is the largest of the set, the smal... | 3f68b53bb1076d02683e7b0a06aab8cb6a15b2bf | 635,788 |
def agave_job_id():
"""Returns an Agave Job identifier
"""
return '6583653933928541720-242ac11b-0001-007' | 9ea5d1edbfbd4acd8338603e359512f59732356d | 635,789 |
def condense_into_single_line(text):
"""
Remove all the newlines from a block of text, compressing multiple
lines of HTML onto a single line. Used as a Jinja2 filter.
"""
lines = [line.lstrip() for line in text.split('\n')]
return ''.join(lines) | 17fce92fc19985b4bdb470810d8dcd5df3e2240f | 635,790 |
import random
def split_posint_rand(i, n):
""" Split a positive integer i into four random numbers that add up
to itself. Returns a list of positive integers. Specify the number
of numbers as n.
"""
# Reject non-positive integers and zero.
if i <= 0 or n <= 0:
return None
# Short-cut codepath when n is just ... | 389fe78de5c217928d83bac358671fd6f6e1efbb | 635,791 |
import os
def is_gmt_script(fname):
"""
Check if a given file is a GMT script.
"""
return os.path.splitext(fname)[-1] == '.sh' | 08fbd7384cc0d516ddb0b9fabff238441dd8286f | 635,792 |
def gen_class_name(underline_name):
"""
由下划线的名称变为驼峰的名称
Args:
underline_name
Returns:
"""
return "".join([name.capitalize() for name in underline_name.split("_")]) | c9f3a088a06e53ecfe85e66fe2007d396f68eced | 635,793 |
import sys
import argparse
def get_args():
"""Command-line parser for this script"""
if sys.version_info<(3,5,0):
sys.stderr.write("You need python 3.5 or later to run this script\n")
sys.exit(1)
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescript... | 6ce993e06b6040a68fea9eb4bd5799fb0b90a919 | 635,794 |
def get_table_count(connection, table):
"""
Return the number of table entries.
:param connection: A database connection instance
:param str table: Name of the database table
:return: The number of table entries
:rtype: int
"""
sql = 'SELECT COUNT(*) FROM {table};'.format(table=table)
... | 718fb234d8d4869112b3faac2826a6520887d92f | 635,795 |
def _clear_entity_type_registry(entity, **kwargs):
"""Clear the given database/collection object's type registry."""
codecopts = entity.codec_options.with_options(type_registry=None)
return entity.with_options(codec_options=codecopts, **kwargs) | e8901dba01bdebae3415673568cf85c7134a6161 | 635,796 |
def filter_calls(filter_file):
"""create a filter in order to exclude traces wrapped at
calls not belonging to a specific group """
if not filter_file:
return []
temp = []
f = open(filter_file, "r")
for line in f:
temp.append(line.split('\n')[0] + ':' + 'libc.so')
return t... | 3acb0b5e10361541d488a20b91fced1ee343e341 | 635,797 |
from typing import IO
from sys import stdout
def puts(s: str, fd: IO = stdout, newline: str = "\n") -> None:
"""puts a string into the file descriptor"""
line = "{s}{newline}".format(s=s, newline=newline)
return print(line, end=newline, file=fd) | 80aa7ed57201223cb9352f1b8991d35408525198 | 635,798 |
def init_device():
"""
initialize device and return device object
"""
return None | 393e895799f70fb10297d1acfbf3d8cbb99fb8e7 | 635,800 |
def register_words_fixture():
"""Set default for register_words."""
return [0x00, 0x00] | 3adf07a88afca19f48cf264acf697157e01e7045 | 635,801 |
def fibonacci2(number: int) -> int:
"""
Generate the fibonacci number for n
Utilizes caching to mimic literal memoization, has lower recursive limit...
0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc
:param number: iteration of the Fibonacci sequence
:return: Fibonacci number
"""
... | ba32daf9b9b56faecda305f50d9e8f5cb7e4c1cb | 635,802 |
def format_perfdata(features):
"""Format the output of performance data"""
perfdata = " | "
for feature in features:
if feature["status"] == "OK":
perfdata += "'%s'=%s;;;0;%s " % (feature["name"], feature["in_use"], feature["total"])
return perfdata.rstrip() | c151dfaf2d8782373c77c7c97d3535b4b577dfcd | 635,803 |
def get_tasks_args(parser):
"""Provide extra arguments required for tasks."""
group = parser.add_argument_group(title='tasks')
# parameters for the knowledgeable dialogue generation
group.add_argument('--task', type=str, required=True,
help='Task name.')
group.add_argument("-... | 17f5623c82341e75bf974b295692f6c5c4fbdb9e | 635,806 |
def get_cep(uf, city, place, re_format):
"""
:param UF: state abbreviation.
:param city: city's name.
:param place: place to be found.
"""
path = f"{uf}/{city}/{place}/{re_format}/"
return path | dbd570e9a473b9974da15633397a83b52223b218 | 635,807 |
def clean_process_parameters(params):
"""
Removes any null valued parameters before passing them to the extension scripts
:param dict params:
:return: cleaned parameters
:rtype: dict
"""
for key, value in params.items():
if value is None:
del params[key]
return param... | 7c22be0723b46ec5df30ace716459413e3f4b8ee | 635,809 |
def generate_stored_procedure_search_failed_simulations():
""" Generates an SQL statement to create a stored procedure used to search for failed simulations. If failed
simulations are found, they are reset provided that they meet the corresponding requirements. It returns
True in case any simulation... | 8f0d78021e08d56035298d1696784e2c9f44ba17 | 635,810 |
def calculate_difference(time1,time2):
"""
Function to calculate difference in times.
ARGS: two times in datetime format
OUTPUT: Returns a value based on the difference in minutes. As the problem is trying to maximize -
i have given differences that are small large values, and differences... | 2956530219ca6d6c9698233cb8eed8851cacd73d | 635,812 |
def extract_fragment_features_librosa(time_series, start_time, end_time, description, PID, EXP):
"""
Extracts / aggregates features in a certain time period within the time series data
Parameters
----------
time_series: pandas.core.frame.DataFrame
A pandas data.frame for which there is a co... | 5c3b1685dac38ec404f38041eaeb7810a8915675 | 635,813 |
def customer(make_customer):
"""A `Customer` object."""
return make_customer() | 17bd75f54412ee40bfc71237e993d69c1a73cbae | 635,814 |
import random
def dice():
"""Number of points in dice"""
return random.randint(1,6) | b83bba3f7e108b3a131b2ca1b89f9e804b52bdbd | 635,815 |
def pingallHosts( main, hostList ):
"""
Ping all host in the hosts list variable
"""
main.log.info( "Pinging: " + str( hostList ) )
return main.Mininet1.pingallHosts( hostList ) | 87e398b49ceb907e618065a3333bf10cd64118ea | 635,816 |
def remove_indentation(str_list):
"""
Remove a indentação do objeto JavaScript de modo que ele
possa ser decodificado normalmente
"""
return ''.join([i.strip() for i in str_list]) | 75fdb2ab6cac7a0dffbc7e0878b77594a207002a | 635,817 |
def get_rate():
"""Get and validate the rate value as float."""
while True:
try:
print()
amount = float(input("Enter the amount of data transfer rate: "))
break
except ValueError:
print("> Wrong format, type numbers instead.")
print("> ... | 7ea8e3347b8e043670ffa6663a90e71cf1c07367 | 635,818 |
def b64d(n):
"""Return decoded values from a base64 string."""
b64 = n.decode("base64")
return b64 | 3adef2be0e9eeb81b6e6d97625fe2a5e6e142b3c | 635,819 |
def get_writetoinput_filenames(writetofile):
"""
Extract the writeToFile file name(s).
writeToFile='tmpin_mc16_13TeV.blah:AOD.15760866._000002.pool.root.1'
-> return 'tmpin_mc16_13TeV.blah'
:param writetofile: string containing file name information.
:return: list of file names
"""
fil... | 62a7fd2bdb25011204561b63232c48ae550a98f1 | 635,820 |
import torch
def interleave(x: torch.Tensor, bt: int):
"""Rearrange a tensor of the form [1..1;2..2;...;bt..bt] into [12..bt;12..bt;...]."""
s = list(x.shape)
return torch.reshape(torch.transpose(x.reshape([-1, bt] + s[1:]), 1, 0), [-1] + s[1:]) | adcf0d834e9531cb6ba9abd8e005588ce865a27d | 635,822 |
def shuffle_function(dt):
""" Randomly shuffle the deck, this should help with the matching process.
:param dt: a data of archive values that will be used in the matching process.
:return: a randomly ordered data frame.
"""
nrow = dt.shape[0]
out = dt.sample(nrow... | b914024ce8e8ec2e66da27e08390fefc17c94ba3 | 635,823 |
def to_int(s):
"""Return integer from this string
"""
return int('0' + ''.join(c for c in s if c.isdigit())) | bbe5029152fcf2ed50de7961a25008b62a4dbbfa | 635,824 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.