content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def read_transformation_txt_file(transformation_file):
"""
Extracts transformation parameters from the transformation file
and packs them into an returns them as a dictionary.
:param transformation_string: the contents of the transformation file.
:type: transformation_string: string
:return: A... | 19320c2ac80b831b51121568a1903d4f8ae8d133 | 649,941 |
from typing import OrderedDict
def network_to_phenotype(net):
"""Converts a network instance to a phenotype representation,
i.e. a structure dictionary.
Arguments
----------
net: EvoNet instance
The network to convert.
Returns
----------
An ordered dictionary. Phenot... | 0fca2f85c670e8296818b3f9fec3641dc599f27d | 649,943 |
def list_valid_tags():
"""
List of tags permitted in book content.
Reference: https://kdp.amazon.com/en_US/help/topic/G200673180
"""
return ['a', 'b', 'big', 'blockquote', 'body', 'br', 'center', 'cite', 'dd', 'del', 'dfn', 'div', 'em', 'font', 'head', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'html... | 14a285ccea5d525527fc6041d3fa2f77baf7eb18 | 649,944 |
def join_neighs_OR_notrelpos(idxs0_ki, idxs1_ki):
"""Join neighs with OR.
Parameters
----------
idxs0_ki: list or np.ndarray
the indices of the neighs of neighbourhood0
idxs1_ki: list or np.ndarray
the indices of the neighs of neighbourhood1
Returns
-------
neighs: list... | 4b45f897fd1fd5955459a8a90fea769b7f84351e | 649,945 |
def power_digit_sum(base, power):
"""Return the sum of the digtis in base**power"""
return sum([int(x) for x in list(str(base**power))]) | b7edd0037387b0894276cdab9a21357a4d49f5d1 | 649,946 |
def upsert(manager, defaults=None, updates=None, **kwargs):
"""
Performs an update on an object or an insert if the object does not exist.
:type defaults: dict
:param defaults: These values are set when the object is inserted, but are irrelevant
when the object already exists. This field sh... | 8b103b051600ab1bf222b1c88353835732c7ceff | 649,947 |
def eval_callbacks(callbacks, record, logbook, estimator):
"""Evaluate list of callbacks on result.
Parameters
----------
callbacks : list of callables
Callbacks to evaluate.
record : logbook record
logbook:
Current stream logbook with the stats required
estimator: :class... | 49a1c46a4fa4475a97cf58d62d76ce7a097d03c2 | 649,948 |
def sizeStr(size):
"""Returns formatted string of a byte size
Args:
size (int): size in bytes
Returns:
string: Size with appropriate byte suffix
"""
prefixes = ["B", "KB", "MB", "GB", "TB"]
exponent = 0
while size > 1024:
size /= 1024
exponent += 1
pr... | d0698c5c8ef040d26621e656327b3f9e82f7bb1c | 649,949 |
import re
def separate_words(txt: str) -> dict[str, int]:
""" splits words by white space and count repetition """
# replace anything except words with whitespace:
txt = re.sub(r'[^\w]', ' ', txt)
words_repetition = dict[str, int]()
for word in txt.split():
if not words_repetition.get(wo... | 8ef48a0a81b537217dbf62e011d74c34c00084dd | 649,950 |
def ctz_naive(x, w=16):
"""
counting zeros starting at the LSB until a 1-bit is encountered
"""
if x == 0:
return w
t = 1
r = 0
while x & t == 0:
t <<= 1
r += 1
return r | 0a19e16b8e3e6d0340227779930464418b5bf76d | 649,951 |
import torch
def create_positive_map(tokenized, tokens_positive):
"""construct a map such that positive_map[i,j] = True iff box i is associated to token j"""
positive_map = torch.zeros((len(tokens_positive), 256), dtype=torch.float)
for j, tok_list in enumerate(tokens_positive):
for (beg, end) in... | c7f2006c3ff4d5cf9ffce646b15704e4d36dddee | 649,952 |
import re
def get_grammatical_function(attributes):
""" Compute the grammatical function of a mention in its sentence.
Args:
attributes (dict(str, object)): Attributes of the mention, must contain
a value for "parse_tree".
Returns:
str: The grammatical function of the mention... | f3105bd17d9f03a99d36af40f0d128816fe2156c | 649,953 |
def goodMatchGeneralized(matchlist,thresh=10):
"""This function looks through all the edit distances
presented in the list 'matchlist', and returns the smallest one, or -1
if they are all -1 or all above thresh"""
bestmatch = -1
minimatch = thresh+10
for match_index in range(len(matchlist)):
... | 7f1a8f368aa08a0dd7bf0c9399fc85265f9d3886 | 649,954 |
def cap_sentence(s):
"""
* Remove extra space
* Lower all letters if word.isupper() and len(word) > 3
* Capitalize the first letter of each word
"""
sentence = " ".join(
[c.lower() if c.isupper() and len(c) > 3 else c for c in s.split()]
)
return "".join(
c.upper() if i =... | 0edeb2274988561080f811b561fe743b011e7dbb | 649,955 |
def pca_test(new_data, mean_vecs, eig_vecs):
"""
输入:新样本new_data、均值向量mean_vec、和投影向量eig_vec
输出:投影后的数据
"""
# 数据中心化
centralized_data = new_data - mean_vecs
# 降维
return centralized_data.dot(eig_vecs) | c9372fbc35d39100324d68a38b8b5f49cf1c40eb | 649,956 |
def blanks(i):
"""
Return i number of blank spaces
Used in places where reading number of blanks is tough
"""
return ''.join(' ' * i) | 7b9ccc5bd88f79c77c83d483c169f149e07495ed | 649,957 |
def simplify_replacements(replacements):
"""
Simplify a list of replacement patterns to make sure there are no needless ones.
For instance in the sequence "Bert->BertNew, BertConfig->BertNewConfig, bert->bert_new", the replacement
"BertConfig->BertNewConfig" is implied by "Bert->BertNew" so not needed.... | ff702f72f0503de2451f5b95883f2952c69b9d78 | 649,958 |
def huffman_code_tree(node, left=True, binary_value=''):
"""This function takes in a list of titles and the final list that contains the final truth table. Depending on which integer was entered.
Args:
node = nodes in the tree
left = left direction boolean
binary_value = binary plac... | ea794a0a57a84255f0446b4b837205f4cd23ae64 | 649,959 |
from typing import Dict
def generate_disjoint_sets(categories: list, freq_table: Dict[str, Dict[str, int]]):
"""
Given a list of categories. The frequency table is a dictionary where the keys are categories, and the values are
the frequency tables (key: word, value: frequency). The function removes words ... | be3d297c30421b73f545db8e21057c16a53343c6 | 649,960 |
import os
def detect_symlinks(dir_path, link_name=None, symlink_as_file=True):
"""
Recursively walk the given directory looking for symlinks. Return
a list of tuples containing the symlinks and the link targets (e.g.,
(('/mnt/galaxyTools/tools/pass/default', '/mnt/galaxyTools/tools/pass/2.0'))).
I... | 31bd9113e48c5826533bf47ac7fd31aadc50602f | 649,961 |
import re
def _transform_file_name_to_migration_name(name):
"""extracts from filename migration name
:param name: filename
:type name: string
:returns: Transformed filename
:rtype: string
"""
return re.sub(r'\.(up|down)\.sql$', '', name) | aa15ffbe9effb8b6fc51df388dd994a47b4846fe | 649,962 |
def fluxv(self, **kwargs):
"""Calculates the flux passing through a closed contour.
APDL Command: FLUXV
Notes
-----
FLUXV invokes an ANSYS macro which calculates the flux passing through
a closed contour (path) predefined by PATH. The calculated flux is
stored in the parameter FLUX. In a... | 7d6f95332e459c715b3797ed0274e6f20f5660f6 | 649,963 |
import glob
import os
def list_files(directory):
"""Returns files in a given directory
Default only splits annotated images, if no annotations are found then all images are split.
"""
files = glob.glob(os.path.join(directory, '*.json'))
if len(files) == 0:
files = glob.glob(os.path.join(di... | 2555f1d8dbe33520e9e092aacc57588d2d2c3e7e | 649,964 |
import requests
def call_api(url):
"""Calls API and returns info from that"""
req = requests.get(url)
return req | 1b7f29b6e5984eab8b254bc793850956e357e3fb | 649,965 |
import uuid
import random
def make_ds_id() -> str:
"""Generate a dataset ID like DataLad would.
This is intended for lightweight tests that don't create
full-fledged datasets.
"""
return str(uuid.UUID(int=random.getrandbits(128))) | c85f4662f93df6dd7c3035170f806d50e3480c30 | 649,968 |
import torch
def combine_initial_dims_to_1d_or_2d(tensor: torch.Tensor) -> torch.Tensor:
"""Given a (possibly higher order) tensor of ids with shape
(d1, ..., dn, sequence_length)
Args:
tensor: torch.Tensor:
Returns:
If original tensor is 1-d or 2-d, return it as is.
"""
if ten... | 1993a54e6771579481accd8c0e48c0c10d779b26 | 649,969 |
def is_object_translated(verbose, object_id, strings_by_object):
""" Checks if there are any translations for the given file id """
if object_id in strings_by_object:
return True
if verbose:
print(f"No translations for {object_id} in dump file -- skipping")
return False | f7abc448c1346087f9f423ba68f664729236e93f | 649,970 |
def median_val(vals):
"""
:param vals: an iterable such as list
:return: the median of the values from the iterable
"""
n = len(vals)
sorted_vals = sorted(vals)
if n % 2 == 0:
return (sorted_vals[n // 2] + sorted_vals[n // 2 - 1]) / 2
else:
return sorted_vals[n // 2] | b0255bce064d72c7031f81ed6b7f0b5f7c2c4ca0 | 649,971 |
def extension(path_):
"""Returns extension from given path. Skips end slash if any."""
if path_.endswith('/'):
path_ = path_[:-1]
filename = path_.split('/')[-1]
if not '.' in filename:
return None
return '.'+filename.split('.')[1] | f588f609a26c944c483b94907c03ff40b9b84bd4 | 649,973 |
def column_dict_to_str(columns, add_select=True):
"""
Convert the dictionary of columns into a SQL search SQL.
"""
col_str = ', '.join(["{0} AS {1}".format(v, k) for k, v in columns.items()])
if add_select:
return 'SELECT ' + col_str
return col_str | 6b85dcd693182844888e56a35bdfaef8aeb0b0f4 | 649,974 |
def has_workflow_stage(artifact, workflow_step_name):
"""
Checks that the artifact's sample's root artifact has been through the given workflow.
:return True if it has False otherwise
"""
for w, status, name in artifact.samples[0].artifact.workflow_stages_and_statuses:
if name == workflow_st... | 13d9d4c2e79331bc5f8bec8ebadfca705439442e | 649,975 |
def check_all_edges_marked(
graph: dict[int, list[int]],
marked_edges: dict[int, list[int]],
) -> bool:
"""
>>> check_all_edges_marked(
... {0:[1], 1:[0]},
... {1:[0], 0:[1]}
... )
True
"""
for vertex, neighbours in graph.items():
for neighbour in neig... | 6b4553cb2d956d79c116e7f1fc14743a0120d7ce | 649,976 |
import collections
def build_vocab(data):
"""Build vocabulary.
Given the context in list format.
Return the vocabulary, which is a dictionary for word to id.
e.g. {'campbell': 2587, 'atlantic': 2247, 'aoun': 6746 .... }
Parameters
----------
data : a list of string
the context in ... | 04cb83cb50f8a611b55dea27bffe2e85adc5be93 | 649,978 |
def instrumented_stage(args, stage):
"""
Returns true if we are using PGO and on stage 2
:param args: The args variable generated by parse_parameters
:param stage: What stage we are at
:return: True if using PGO and on stage 2, false if not
"""
return args.pgo and stage == 2 | e4058f2f2c4a671d27057257bdafd34b2536493c | 649,981 |
def simple_1arg_default(hello: str = "default"):
"""This will print hello.
Args:
hello: Your name.
"""
return f"Hello {hello}" | 9eb6bce5ea4294097880e85b2450ad6d68945a3a | 649,982 |
def get_data_science_bookmarks(bookmarks):
"""Function to select the top level data science folder of bookmarks.
Returns the first element of bookmarks where 'Data Science' is one of the keys.
"""
for item in bookmarks:
if type(item) is dict:
if 'Data Science' in item.keys():... | ae8eb873e4775c030e67c49dd693fc9ee1fb902e | 649,983 |
from pathlib import Path
def project_path() -> Path:
"""Find project directory."""
current_dir = Path.cwd()
if (current_dir / 'pyproject.toml').exists():
return current_dir
raise ValueError('This is not a project dir!') | 130dbb516873309984355bf3dc14b5d21eabcf3d | 649,984 |
def _violate_descending(values, descending):
"""
Check if values violate descending restrictions.
"""
for i in descending:
if values[i - 1] < values[i]:
return True
return False | 0e2f71e39a4d20b83a2e9b4e6ef88d7a66e1b360 | 649,985 |
def multivariate_regression_predict(X, w_opt):
"""Predict with multivariate regression.
Arguments:
X {DataFrame} -- Independent variables.
w_opt {ndarray} -- Parameter values.
Returns:
ndarray -- Predicted values.
"""
X = X.values
y_pred = X.dot(w_opt)
return y_pre... | 34a9d70dfc2a4a647184255413a792f5270004d0 | 649,986 |
def _str_to_float(string, exception=None):
"""Convert string to float. Return `exception_value` if failed.
Args:
string (str): Input string.
exception (): Exceptional value returned if failed.
Returns:
int:
"""
try:
return float(string)
except:
return ex... | 49cb022ba5356d71b44b90dcbbf21ef97df13a74 | 649,987 |
import zlib
import pickle
def zdumps(obj):
"""
Pickle and compress
:param obj: a python object
:return: compressed string
"""
return zlib.compress(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL), 9) | 82eeca0e9589adab3bb0f51797fe5deee117b0a1 | 649,988 |
import os
def get_example_config( data_dir ):
"""
Patameters
----------
data_dir: path
path to input raster layers
Returns
-------
dict
example configs
"""
files = [ os.path.join(data_dir, f) for f in os.listdir( data_dir )]
config_ex = {
'Target_r... | afd767da505ad5552726c0a9307bed90bc8517a0 | 649,989 |
import tempfile, os, shutil
def createSampleAssembly(workdir, template_dir, sa_xml):
"""Create a sampleassembly folder in the workdir
using files in template directory and the given sampleassembly.xml file
return the path to the new directory
"""
d = tempfile.mkdtemp(dir=workdir)
for fn in os.... | 3ee793ba7f2b2173959d23719047ff7ebe5e74fa | 649,990 |
from typing import Tuple
from typing import Optional
def _parse_url(url : str) -> Tuple[str,int,Optional[str]]:
"""
Parses the url in the following format if authentication enabled:
tcp://<hostname/url>:<port>?token=<token>
If authentication is not enabled, the url is expected to be in the format:
... | 2a86725edaf017bd06de28452a5c2825de5285b0 | 649,991 |
def plur_simple(cardinality: int, word: str, suffix="s"):
"""Pluralises words that just have a suffix if pluralised."""
if cardinality - 1:
word += suffix
return f"{cardinality} {word}" | 687b25a6e18c929dbdde3f2a720daf6f041aed77 | 649,992 |
from typing import List
def get_model_names() -> List[str]:
"""
:return:
"""
model_names = ['baseline', 'no_label_smoothing', 'dry_run', 'slice_dev', 'slice_dev+optimize', 'domain_robustness']
noise_probabilities = "0.001 0.005 0.01 0.05 0.075 0.1 0.25 0.5".split(" ")
for noise_probability ... | a518d16bccde54936d143eb83fa513f27db8d202 | 649,996 |
import requests
def get_data(url: str):
"""Get the data from the url.
:param url: The link used to get the data.
:return: The raw response from requests.
"""
response = requests.get(url, stream=True)
return response.raw | 84bddf623e5340c6914347b532ca058a3f4cfd17 | 649,997 |
def escape_mongokey(key):
"""Escape keys when serializing database entries."""
return key.replace('$', u'\uff04').replace('.', u'\uff0e').replace(' ', '_') | c1344a4aa3699970070b371fcc9de239f246046c | 649,998 |
import math
def calculate_revised_bitrate (video_bitrate, video_target_size, video_actual_size):
"""This calculates a revised video bitrate given the video_bitrate used,
the actual size that resulted, and the video_target_size.
This can be used if you want to compress the video all over again in an
at... | ebebdee37343f898d93a292ed1e73f6b9b2aec17 | 649,999 |
def get_links(soup):
"""Gets the story links from the given hacker soup."""
links = soup.select(".storylink")
return links | def4637af3b223b03d5fb528ec47dde03f6c6589 | 650,000 |
def get_tg_formatted_text(text: str) -> str:
"""
Форматированный текст в телеграмме (html)
"""
return f"<pre>{text}</pre>" | bcc1784b63ef47258063010bc7ef165c6fed47c9 | 650,001 |
def print_tag_info(tag):
"""Print the information currently stored in the Tag object."""
info = ""
attributes = ['id', 'time', 'ant']
for a in attributes:
if hasattr(tag, a):
info += "%s=%s, " %(a,str(getattr(tag, a)))
info = '<RFID Tag: '+info[:-2]+'>'
return info
... | b42e1900a11cbe60e76bb642b6be59e838f6d82c | 650,002 |
def immutable_dict_2_dict(imm_dict):
""" Function to convert an Immutable Dictionary to a Mutable one
Convert multi valued and keys ending with [] to lists
"""
m_dict = {}
for key, val in imm_dict.to_dict(flat=False).items():
if len(val) > 1 or key.endswith('[]'):
m_dict[key.str... | b2a02fe745cdbb3c413b3e141c6a31efd71fa1b1 | 650,003 |
def mock(df, config, dataframes):
"""
Creates a column with only one value.
"mock": {
"mocked_column": True
}
"""
for column, value in config.mock.items():
df[column] = value
return df | 981b6c7b2f01a73b987c05720d22f481a34bc39c | 650,004 |
def fontInfoStyleMapStyleNameValidator(value):
"""
Version 2+.
"""
options = ["regular", "italic", "bold", "bold italic"]
return value in options | 2984336466c063d7f826ec6ae7ff5d0437118e79 | 650,005 |
def _cache(f):
"""Decorator to cache return value of a function."""
cached = {}
def cached_function():
"""Cache return value in closure before calling function."""
if 'value' not in cached:
cached['value'] = f()
return cached['value']
return cached_function | cf25a68f4ac7a5cb94e1db7c3ef36e36002fa422 | 650,007 |
def make_list(var):
"""
Convert a variable to a list with one item (the original variable) if it isn't a list already.
:param var: the variable to check. if it's already a list, do nothing. else, put it in a list.
:return: the variable in a one-item list if it wasnt already a list.
"""
if... | 5ffcd3ef5d436162dae62cb823dc43a9438fc0f3 | 650,008 |
import json
def get_info():
""" 获取所有图片组的信息 """
res = []
with open('data/info.txt', 'r') as f:
for line in f:
data = json.loads(line)
res.extend(data['data']['list'])
return res | 372661773b9d12006db446434a3f0b20b3853df6 | 650,009 |
def _all_slice(obj):
"""
Returns True if all the elements in the object are slices else return False
"""
result = False
if not isinstance(obj, (tuple, list)):
return result
result |= all(isinstance(o, slice) for o in obj)
return result | 880594160213bda622f1d6dc436990cad2ede07c | 650,010 |
import argparse
from pathlib import Path
def create_arg_parser():
""""
Creates and returns the ArgumentParser object.
"""
parser = argparse.ArgumentParser(description='Calculates image brightness on scale of 1 to 10.')
parser.add_argument("--input_path", type=Path, help="Input image path")
ret... | b7df1e78d6e0e531296096823722b8002aef94f0 | 650,011 |
def win_safe_name(trackname):
"""Edit the track name so as the resulting file name would be
allowed in Windows.
"""
# In order: strip the whitespace at both ends, replace a trailing
# full stop by an underscore. Replace any forbidden characters by
# underscores.
trackname = trackname.strip(... | 7ede4e9af12e6fd4249f47e2b2519819e8b439dd | 650,012 |
import re
def clean_path(dirty):
"""Convert a string of python subscript notation or mongo dot-notation to a
list of strings.
"""
# handle python dictionary subscription style, e.g. `"['key1']['key2']"`:
if re.match(r'^\[', dirty):
return re.split(r'\'\]\[\'', re.sub(r'^\[\'|\'\]$'... | 0c5cce0e5e6e6b89167622e627ef5e8ca2dd154e | 650,013 |
def is_primitive(pyobj):
"""Determine if pyobj is one of (what other languages would deem) a primitive"""
if type(pyobj) in (int, float, bool, str, bytes):
return True
else:
return False | 72f26ba3361bac67142e0022f22faea3cab0de94 | 650,014 |
def _next_significant(tokens):
"""Return the next significant (neither whitespace or comment) token.
:type tokens: :term:`iterator`
:param tokens: An iterator yielding :term:`component values`.
:returns: A :term:`component value`, or :obj:`None`.
"""
for token in tokens:
if token.type ... | 992d0d6a42e8815ebae9f0ae6d5bd696bb4818f3 | 650,015 |
import os
def printable_path(dirpath):
"""Replace $HOME with ~."""
return dirpath.replace(os.getenv('HOME'), '~') | 9af0bc3fa47ba31ea10c57c020f4d4abc6bd9529 | 650,016 |
def state2feature(key):
"""
@return: the feature string from the given key
@rtype: str
"""
index = key.find("'")
if index < 0:
return key
else:
return key[index+3:] | e1a352d88669220fa7fe87567ff29befae114d8c | 650,017 |
import itertools
def compact_batches(batches):
"""Pack down batches to lists of continuous batches."""
return [
[x[1] for x in g]
for k, g in itertools.groupby(enumerate(batches), lambda i_x: i_x[0] - i_x[1])
] | 292b7c5ca09f20cd0066ce81e5ad7db107a50005 | 650,018 |
from typing import Sequence
from typing import Tuple
from typing import Optional
def _shift_to_tensor_domain(
axis: int,
key: Sequence[slice],
tensor_domain: Sequence[slice],
) -> Tuple[slice, ...]:
"""Shift the slice to the tensor domain.
Args:
axis: The chunked axis.
key: The sl... | b0f25362bb0ddc3f92c0e35127c8b2cfabd5230f | 650,019 |
def validate_yes_no(value):
"""Validate yes-no question"""
if isinstance(value, bool):
return value
if value is None or value == "<ask>":
return value
check_value = value.strip().lower()
if check_value in ("", "y", "yes", "t", "true", "1"):
return True
if check_value in (... | 508edc2885c26306de12b3688cb21ca788a86963 | 650,020 |
def korean_year(cycle, year):
"""Return equivalent Korean year to Chinese cycle, cycle, and year, year."""
return (60 * cycle) + year - 364 | 50c5fac933820474c9c6cbd4c6abd8fe26c89edb | 650,021 |
def fmt_bytes(bytes: int) -> str:
"""
Prints out a human readable bytes amount for a given number of bytes
"""
if bytes > 1000000000:
return '{:.2f} GB'.format(bytes / 1000000000)
if bytes > 1000000:
return '{:.2f} MB'.format(bytes / 1000000)
if bytes > 1000:
return '{:.2... | 0652ee1d48133a3d59832ae8cd0cd3fbbf6dcc08 | 650,022 |
def juris_dependency_dictionary():
"""Certain fields in jurisdiction files refer to other jurisdiction files.
E.g., ElectionDistricts are ReportingUnits"""
d = {'ElectionDistrict':'ReportingUnit','Office':'Office','PrimaryParty':'Party','Party':'Party',
'Election':'Election'}
return d | ca6631c107d5018b5c8af93c744b7e5f12e0aeb3 | 650,023 |
def __k_chk(k):
"""
Ensures a kelvin value is not below absolute zero. If it is
not, we raise a ValueError instead. If it is valid, we return it.
"""
if k < 0:
if k % 1 == 0:
k = int(k)
raise ValueError(f'{k}K is below absolute zero, and is invalid.')
return k | af40cec948ff1df639737139dbcb00d9a553712d | 650,024 |
def rounded(n, base):
"""Round a number to the nearest number designated by base parameter."""
return int(round(n/base) * base) | 231cd9c9972ab422bcf478defeb98c1abc06c333 | 650,025 |
import os
import json
def _CreateSourcesJsonFile(source_dirs, input_path, sources_json_file,
src_root):
"""Adds all normalized source directories and input path to
|sources_json_file|.
Args:
source_dirs: List of source directories.
input_path: The input path to non-instrument... | 5aba30083c532ba048d94fc2b2c613bb7b379304 | 650,026 |
def to_decimal(num, base, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
"""Converts a number from some base to decimal.
alphabet: 'digits' that the base system uses"""
using = str(num)[::-1]
res = 0
for i in range(len(using)):
res += alphabet.find(using[i])*base**i
return res | d29eba70b29885994c98e2c1159978d81efe4ac1 | 650,027 |
import math
def coding_problem_40(numbers):
"""
Given an array of integers where every integer occurs three times except for one integer, which only
occurs once, find and return the non-duplicated integer. Do this in O(N) time and O(1) space.
Examples:
>>> coding_problem_40([6, 1, 3, 3, 3, 6, 6])... | 1bf09577a61cde56df4fdbe46b19691496b1575e | 650,028 |
def bits_to_array(num, output_size):
""" Converts a number from an integer to an array of bits
"""
##list(map(int,bin(mushroom)[2:].zfill(output_size)))
bit_array = []
for i in range(output_size - 1, -1, -1):
bit_array.append((num & (1 << i)) >> i)
return bit_array | 7df0bd8bf3e95770e4eee332df4514581704eef6 | 650,029 |
def get_vis_node_info(node, options):
"""calculate the dict that will represent a node."""
node_label = next(iter(node.labels()), "")
prop_key = options.get(node_label)
vis_label = node.get(prop_key, "")
return {"id": id(node), "label": vis_label, "group": node_label, "title": repr(node)} | 1c73ffe1f7e0693ae7361d07fa2baa04d593a213 | 650,030 |
def _swap_curly(string):
"""Swap single and double curly brackets"""
return (string
.replace('{{ ', '{{')
.replace('{{', '\x00')
.replace('{', '{{')
.replace('\x00', '{')
.replace(' }}', '}}')
.replace('}}', '\x00')
.replace('}'... | ce5b833856aec8e4b6b9629e01fa9dc0ac3b5ddd | 650,031 |
import re
def fix_format(to_process):
"""
Fixes weird formatting in the NIOSHTIC output.
@param to_process: string representing the file being cleaned
@return more consistently formatted string
"""
DIVIDER = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
cleaned_stri... | 5a5353700f171f22643b52e83212ca21784235a4 | 650,032 |
import copy
def build_common_config(config, model_config):
"""
Build a common run configuration for each model
:param config: A Plot Generation Config
:return: A common run config
"""
model_name, run_num, agent_ens, adversary_ens, voted = model_config
config_base = copy.deepcopy(config)
... | 952b083213804508dee1f0fab64a0ef8366418fc | 650,033 |
import pickle
def read_chains(in_dir):
"""Read chains file."""
pickle_in = open(in_dir, 'rb')
chains = pickle.load(pickle_in)
pickle_in.close()
return chains | 073d0c6743efd2cc09557371f9de59b156c65691 | 650,034 |
import numpy as np
def dfa(X):
"""
Use: Fn, N = dfa(X)
This function calculates the rescaled range R(n)/S(n) of X
by detrended fluctuation analysis.
Method found at
https://en.wikipedia.org/wiki/Detrended_fluctuation_analysis
Input:
X: Time series ..................................... | a8d0c164e976f0dacddf88304d2cea3a73cc7d3e | 650,035 |
def _convert_pandas_csv_options(pandas_options, columns):
""" Translate `pd.read_csv()` options into `pd.DataFrame()` especially for header.
Args:
pandas_options (dict):
pandas options like {'header': None}.
columns (list):
list of column name.
"""
_columns = pa... | 2e64ee3c503bc91b167030e8c967204d489d3657 | 650,036 |
def ask_player_for_location(player):
"""Ask the player where they would like to use their turn"""
move = None
while not move:
try:
move = int(input(f"{player} where would you like to go? "))
if move not in range(1, 10):
move = None
raise ValueE... | 3a35ce8ef135d8a849e7403c763b9bf6b98b1b0e | 650,037 |
import itertools
def add4bitSbox(sbox, variables):
"""
Adds the constraints for the S-box and the weight
for the differential transition.
sbox is a list representing the S-box.
variables should be a list containing the input and
output variables of the S-box and the weight variables.
S(... | a07ff098201d244271c0c1a7eafd3257923b0226 | 650,038 |
def get_data(base_url):
"""
This just inserts a hardcoded introspection string for the baseurl.
"""
return [
{
"api_version": "v1",
"available_api_versions": {
"v1": base_url+"v1/",
},
"formats": [
"json",
],
"entry_types_by_format": {
"js... | 494e497d0482330cb1d6c2aefd42ae80664cbfaf | 650,039 |
from numpy import random
def getsky(data):
"""
Determine the sky parameters for a FITS data extension.
data -- array holding the image data
"""
# maximum number of interations for mean,std loop
maxiter = 30
# maximum number of data points to sample
maxsample = 10000
# size of the array
ny,nx =... | 9eff11e3d13e6e61aa21519cf6197820ed817fee | 650,040 |
def get_subsql(colname, fullwidth, param):
"""Generate fancy sql subquery with some optimizations"""
if len(param) == fullwidth:
return " %s = %%s" % (colname,)
return " strpos(%s, %%s) > 0 " % (colname,) | ccb6a0d832f96b33f41517b45758567605cfa200 | 650,041 |
def get(db, provider):
"""
get the existing document
:param db:
:param provider:
:return:
"""
collection = list()
for row in db.posts.find({'provider': provider}):
collection.append(row)
return collection | e6808d8266f5445aa9fc0dfe7788088a11b36849 | 650,042 |
def age_restricted(content_limit, age_limit):
""" Returns True iff the content should be blocked """
if age_limit is None: # No limit set
return False
if content_limit is None:
return False # Content available for everyone
return age_limit < content_limit | fe61fe3ac8dedd77d3d77d7166125f12625ca906 | 650,043 |
import torch
def sparse_bmm(sparse_matrix, dense_matrix_batch):
"""
Perform torch.bmm on an unbatched sparse matrix and a batched dense matrix.
Args:
sparse_matrix (torch.sparse.FloatTensor): Shape = (m, n)
dense_matrix_batch (torch.FloatTensor): Shape = (b, n, p)
Returns:
(t... | c7146764e24043fb311118dd2db817a751c856a7 | 650,044 |
def T(parameters, theta_v, pi, r_v=None):
"""
Returns an expression for temperature T in K.
:arg parameters: a CompressibleParameters object.
:arg theta_v: the virtual potential temperature in K.
:arg pi: the Exner pressure.
:arg r_v: the mixing ratio of water vapour.
"""
R_d = paramet... | 152648b6a338b7ac92769b0228fb26223aa1d7f9 | 650,045 |
def rshift(x, n):
"""For an integer x, calculate x >> n with the fastest (floor)
rounding. Unlike the plain Python expression (x >> n), n is
allowed to be negative, in which case a left shift is performed."""
if n >= 0: return x >> n
else: return x << (-n) | dbf38eacccb59e64099054d32253d791ed9eb672 | 650,046 |
def phrase2seq(phrase, word2idx, vocab):
"""
This function turns a sequence of words into a sequence of indexed tokens according to a vocabulary and its word2idx mapping dictionary.
:param phrase: List of strings
:param word2idx: Dictionary
:param vocab: Set or list containing entire v... | dac991872df01b0c44959d559395fa64f30e6979 | 650,047 |
def is_json_validation_enabled(schema_keyword, configuration=None):
"""Returns true if JSON schema validation is enabled for the specified
validation keyword. This can be used to skip JSON schema structural validation
as requested in the configuration.
Args:
schema_keyword (string): the name of... | d028a5c27a947872f4ca850ea1bbafde58751279 | 650,048 |
import os
def load_clustered_images(images_dir):
"""
:param images_dir: images dir which is organized as below
├── Ariel_Sharon
│ ├── Ariel_Sharon_0006.png
│ ├── Ariel_Sharon_0007.png
│ ├── Ariel_Sharon_0008.png
... | 791cdb1b8f996d041d9f375ec297e9f3990637b5 | 650,049 |
def combine_runs(runsets):
"""
Combine the output results of many runs into a single dictionary.
Parameters
----------
runsets : list
Outputs of multiple calls to 'chnbase.MOSOSolver.solve'
Returns
-------
rundatdict : dict
"""
rundatdict = dict()
for i, st in enume... | 4d257cbc2640b2fe3def30e723792f18db204ddb | 650,050 |
import socket
def get_host_finger(protocol, ip, port, timeout=5):
"""
获取远程主机特定端口下服务的指纹
:param protocol: 协议,tcp / udp
:params ip: ip
:params port: 端口
:return: 服务器指纹
"""
client = None
msg = b"Hello, Server\r\n"
if protocol == 'tcp':
# tcp 协议
client = socket.socket... | 8d64e7d308f3e2e9fe6b7be73c7496531d257efc | 650,051 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.