content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def getMissingConfiguration(s) :
"""
Given a string, returns all the counts of concecutive missing values in the string, in the form of array.
We also include another value indicating if the edges are same or different
"""
# Initialize variables for computing and storing the values
missing_coun... | c7d6a07e2eafe4143220cf8b05648727a23e19a3 | 681,248 |
def check_knight_move(lhs, rhs):
"""check_knight_move checks whether a knight move is ok."""
col_diff = abs(ord(lhs[0]) - ord(rhs[0]))
row_diff = abs(int(lhs[1]) - int(rhs[1]))
return (col_diff == 2 and row_diff == 1) or (col_diff == 1 and row_diff == 2) | fb8aad86a278249da7fbdc5f341c5024b0cbfb82 | 681,249 |
def remove(self):
"""Remove this node.
@return: self
"""
self.parent.remove_creator(self)
return self | 96df3a910f6c6cef5f95723c94e5bde9070e2847 | 681,250 |
from datetime import datetime
def timestamp_ddmmyyyyhhmmss_to_ntp(timestamp_str):
"""
Converts a timestamp string, in the DD Mon YYYY HH:MM:SS format, to NTP time.
:param timestamp_str: a timestamp string in the format DD Mon YYYY HH:MM:SS
:return: Time (float64) in seconds from epoch 01-01-1900.
... | bf2239de21973ae537cee94022e9d2781f7cbd52 | 681,251 |
def read_file(file, delimiter):
"""Reads data from a file, separated via delimiter
Args:
file:
Path to file.
delimiter:
Data value separator, similar to using CSV.
Returns:
An array of dict records.
"""
f = open(file, 'r')
lines = f.readlines()
records = []
for line in lines:
... | d686ef236195638a3e1c6c71823c40ad3a72ccac | 681,252 |
import uuid
def makeUUID():
"""
_makeUUID_
Makes a UUID from the uuid class, returns it
"""
return str(uuid.uuid4()) | ad7b8c24e452ca2aa7c7c2dfb9151e8b87687a24 | 681,253 |
def get_phase_dir(self):
"""Return the Rotation direction of the stator phases
Parameters
----------
self : LUT
A LUT object
Returns
-------
phase_dir : int
Rotation direction of the stator phase
"""
return self.output_list[0].elec.phase_dir | 373bb34755a6cd3f7dd246484fecf7681b892549 | 681,254 |
import csv
def readAIAresponse(csvFile):
"""Obtains the SDO/AIA responses from a .csv file.
Parameters
----------
csvFile : str
The .csv file with the SDO/AIA responses in it. First line should be labels for each
column as a comma seperated string, e.g. row1=['logt, A94, A171'].
... | aa45e64ff945d3c2947012a0be1988a1c2c8d833 | 681,256 |
from typing import Set
def even_nodes(G) -> Set:
"""
:return: set of all even degree nodes in the graph
"""
return {x for x in G.nodes() if G.degree(x) % 2 == 0} | 8913e995089789ad9b61b24c29aeac598b0f91ea | 681,259 |
def get_pickle_file_path(file_name, target, folder):
"""
Returns a path to a saved file
Parameters
----------
file_name: str
name of the saved file
target: str
name of target column
folder: str
name of the folder file is saved in
Returns
-------
path to ... | e71925a50f8d637d83b620b202ad63e8e4ff7b0f | 681,260 |
def is_user_check(message, user_id):
"""Is is a user?"""
return message.author.id == user_id | 5e76d9734da0b2d05c301b57593a6c03ab008bfc | 681,261 |
import hashlib
def str_checksum(data):
"""Return the CRDS hexdigest for small strings. Likewise, must
match checksum() and copy_and_checksum() above.
>>> str_checksum("this is a test.")
'7728f8eb7bf75ec3cc49364861eec852fc814870'
"""
if not isinstance(data, bytes):
data = data.enco... | 72eaeb3725b6de7e8dac15cb5a06a222ddeb8f62 | 681,262 |
def model_zero(x, k, y0, y1):
"""
One-compartment first-order exponential decay model
:param x: float time
:param k: float rate constant
:param y0: float initial value
:param y1: float plateau value
:return: value at time point
"""
return y0 - (k * x) | 0a2a82d3531568ccc3ea1c3b4fb4c7897e56fcbd | 681,263 |
def is_owner(effect):
"""
User is the owner
"""
if 'user' in effect.options:
return effect.instance.activity.owner == effect.options['user']
return False | 463a4d058b9c344eb70ebfc59d8510f8fbc9d48f | 681,265 |
def concatenate_codelines(codelines):
""" Compresses a list of strings into one string. """
codeline = ""
for l in codelines:
codeline = codeline + l
return codeline | 4780c947aba149893d10cafc25c704596f9909e2 | 681,266 |
import os
def similarweb_short_extract(shortcut_path):
"""
extract the short of similar web chrome
"""
return_list = None
abo_path = shortcut_path
### retreive the ink file name
return_list = os.listdir(abo_path)
return_list = [list_dir for list_dir in return_list if 'lnk' in list... | 312bcb34be7bede36cf7044b80a64bb6dd65d5cf | 681,267 |
from typing import Any
def to_pipeline_params(params: dict[str, Any], step_prefix: str):
"""Rename estimator parameters to be usable an a pipeline.
See https://scikit-learn.org/stable/modules/compose.html#pipeline.
"""
return {"{0}__{1}".format(step_prefix, key): value for key, value in params.items(... | 4bd5fef01d23a2da79f8182ae30bebbef3ca2e88 | 681,268 |
def toutf8(ustr):
"""Return UTF-8 `str` from unicode @ustr
This is to use the same error handling etc everywhere
if ustr is `str`, just return it
"""
if isinstance(ustr, str):
return ustr
return ustr.encode("UTF-8") | e4fda18058cd34da13e7884761004082f95b3087 | 681,269 |
import re
def bpe_preprocess(text):
""" Use ▁ for blank among english words
Warning: it is "▁" symbol, not "_" symbol
"""
text = text.upper()
text = re.sub(r'([A-Z])[ ]([A-Z])', r'\1▁\2', text)
text = re.sub(r'([A-Z])[ ]([A-Z])', r'\1▁\2', text)
text = text.replace(' ', '')
text = ... | 57f66674334bc13e49ddab2853c6321cef7abb0f | 681,271 |
def RemoveUppercase(word):
"""Remove the uppercase letters from a word"""
return word.lower() | dddf1792f16e3dbcbb310ac9c6456031aefeb11f | 681,272 |
def plural(count=0):
"""Return plural extension for provided count."""
ret = 's'
if count == 1:
ret = ''
return ret | 45fcf037d4727483e09723367180c717efe526a4 | 681,273 |
def generate_freenas_volume_name(name, iqn_prefix):
"""Create FREENAS volume / iscsitarget name from Cinder name."""
backend_volume = 'volume-' + name.split('-')[1]
backend_target = 'target-' + name.split('-')[1]
backend_iqn = iqn_prefix + backend_target
return {'name': backend_volume, 'target': bac... | bd5c4851beee4d92cbcb8632200720b2a49bdd70 | 681,274 |
def degreeDays(dd0, T, Tbase, doy):
"""
Calculates degree-day sum from the current mean Tair.
INPUT:
dd0 - previous degree-day sum (degC)
T - daily mean temperature (degC)
Tbase - base temperature at which accumulation starts (degC)
doy - day of year 1...366 (integer)
OUT... | db7eb093656373b8f4f4cdba7cebdee1e5092e8d | 681,275 |
def obj_to_dict(obj, *args, _build=True, _module=None, _name=None,
_submodule=None, **kwargs):
"""Encodes an object in a dictionary for serialization.
Args:
obj: The object to encode in the dictionary.
Other parameters:
_build (bool): Whether the object is to be built on de... | a5881d0d65fb43c43109efb8c5313e04c791eb9e | 681,276 |
def get_create_relationships_query(
node1_label:str,
node1_id:str,
node1_col:str,
node2_label: str,
node2_id: str,
node2_col: str,
relationship:str,
rel_properties=[],
foreach=False,
foreach_property=''
):
"""
Build the query to create relationships.
:param node1_lab... | 016e03765242cbaba481a12125aac69472c37e3d | 681,278 |
def identity(x):
"""x -> x
As a predicate, this function is useless, but it provides a
useful/correct default.
>>> identity(('apple', 'banana', 'cherry'))
('apple', 'banana', 'cherry')
"""
return x | 041ae6204b56fbbe90df0cb974db1f277d2e854b | 681,280 |
import pathlib
import os
def get_program_list():
""" Return a list of programs by walking the repository directory. """
# Walk the programs directory.
programs = pathlib.Path(os.getcwd()) / ".." / "resources" / "views" / "programs"
programs_list = os.listdir(programs)
# # Walk the geosciences su... | 7a44f467a3ee225579ad953d934181aa03a67da4 | 681,281 |
def epoch2checkpoint(_epoch: int) -> str:
"""
Args:
_epoch: e.g. 2
Returns:
_checkpoint_name: e.g. 'epoch=2.ckpt'
"""
return f"epoch={_epoch}.ckpt" | 8111d952dac9a356cf14846a88d2c87721ff8b50 | 681,282 |
def create(properties, defaults=None):
"""Create objects from their associated property class.
E. g. a NettingChannelState from NettingChannelStateProperties. For any field in
properties set to EMPTY a default will be used. The default values can be changed
by giving another object of the same property... | 6d9aec67060b6cd2aa5d7b006e2f9305e61b961d | 681,283 |
def is_svn_path(path_):
"""Whether the path is to a subversion sub-directory
>>> is_svn_path('/path/to/.svn/file')
True
"""
return '/.svn' in path_ | d437be22689e328659ed45a920d056b8502f9936 | 681,284 |
def divide(arg1, arg2):
""" (float, float) -> float
Divides two numbers (arg1 / arg2)
Returns arg1 / arg2
"""
try:
return arg1 / arg2
except TypeError:
return 'Unsupported operation: {0} / {1} '.format(type(arg1), type(arg2))
except ZeroDivisionError as zero_... | eab4386c5b72457eb486be081f7af9ee16302eb3 | 681,285 |
def ED(first, second):
""" Returns the edit distance between the strings first and second."""
if first == '':
return len(second)
elif second == '':
return len(first)
elif first[0] == second[0]:
return ED(first[1:], second[1:])
else:
substitution = 1 + ED(first[1:], se... | e0b8e1c6538ab5cc96266c9638dd1da7f33a7a39 | 681,286 |
def filter_inPriceBorders(itineraries, minPrice, maxPrice):
"""
filter the input itineraries and select itineraries with price from minPrice to maxPrice
:param itineraries: input itineraries
:param minPrice: minimum price for itinerary
:param maxPrice: maximum price for itinerary
:return: tiner... | e458e26a09667edfd4f354b672f471e487722f30 | 681,287 |
def remove_repetition_from_changelog(
current_release_version_number, previous_release_version,
changelog_lines):
"""Removes information about current version from changelog before
generation of changelog again.
Args:
current_release_version_number: str. The current release version.... | 2b38056ad813e9ba4757e42241e3ffd64ebffa37 | 681,288 |
def remove_slash(path: str) -> str:
"""Remove slash in the end of path if present.
Args:
path (str): Path.
Returns:
str: Path without slash.
"""
if path[-1] == "/":
path = path[:-1]
return path | d714454d17d05ea842b6f1b88fe7e5d65bd1de15 | 681,289 |
def handle_positions_of_ships(data):
"""The function handle the data that the client send and return the positions of the ships and
the username of the client"""
list2 = data.split('$')
username = list2[1]
list1 = list2[0].split('*')
list_of_positions = []
for position in list1:
... | bd20928cad173a8458d2e9e831f418c1a929d9bf | 681,291 |
def chk_chng(src_flist,dst_flist):
""" Returns unchanged file list and changed file list
Accepts source file list and dsetination file list"""
uc_flist = []
c_flist = []
for files in src_flist:
if files in dst_flist:
uc_flist.append(files)
else:
c_flist.ap... | 99c21b204ea5145edd81dc88aadb279cdaa643c8 | 681,292 |
def cnn_estimate(inputs, network, est_fn):
"""
Estimated labelf by the trained cnn network
Inputs
======
inputs: np.ndarray
The test dataset
network: lasagne.layers
The trained cnn network
Output
======
label_est: np.ndarray
The estimated labels
"""
... | 0c1f66ed6746d216e7fe180fed660580b55b8db2 | 681,293 |
import csv
def getProModel():
"""
Gets and returns the three heatmaps for each ProModel image along with the location data and relevant labels.
Returns
-------
x : float
The X coordinate for the images to be displayed on the graph.
y : float
The Y coordinate for the images to ... | 6460849649b82feb5f0cd9526d95e34e422da380 | 681,294 |
def get_probs(input_file):
"""
get probs from input file.
"""
return [float(i.strip('\n')) for i in open(input_file)] | 1494767f4d34d0ffcbb530e08b6d9427569d973f | 681,295 |
def say_hello():
"""
Says hello!
:return: *string*
"""
print("Hello from Blender")
return "I said hello in Blender" | bc67301bf5ba132dfe61c7180dc3f0a6bc1edb54 | 681,296 |
import argparse
def get_args():
"""Gets parsed command-line arguments.
Returns:
Parsed command-line arguments.
"""
parser = argparse.ArgumentParser(description="avoids obstacles")
parser.add_argument("--obstacle-density", default=0.01, type=float,
help="area density... | 6d13563df767872b178e72aa039c9b2eea2dbe67 | 681,297 |
def parse_substitution_misc(consequence):
"""
Return fields for syn, non-syn or correlated
"""
elem = consequence.strip().split(' ')
#Default: ['gene', 'G=>A', 'GBS222_0094', 'base', '33']
correlated = False
locus_tag = elem[2]
# Handle: ['gene', 'C=>G', 'GBS222_t08', 'base', '64,... | 9de81a7cce143c85d69ee4bc2b7bf2a73df57261 | 681,298 |
def fill_clusters(clusters, element_i, element_j):
"""
Fill the list of clusters (sets) with two elements from the same cluster.
>>> clusters = []
>>> fill_clusters(clusters, 1, 10)
[{1, 10}]
>>> fill_clusters(clusters, 10, 100)
[{1, 10, 100}]
>>> fill_clusters(clusters, 20, 30)
[{1... | ba999b5d63104f20ddc6de1fc8da27e1c46cd9f2 | 681,299 |
def is_even(num):
"""
Returns True if a number is even
:param num:
:return:
"""
if num == 0:
raise NotImplementedError(
"Input number is 0. Evenness of 0 is not defined by this "
"function."
)
if num % 2:
return False
else:
return T... | 29f800e988f62ac6b03b377e6dd5e2e0e3e14607 | 681,300 |
import inspect
def is_iterable(value):
"""
Returns:
(bool): True if value is iterable (but NOT a string)
"""
return isinstance(value, (list, tuple, set)) or inspect.isgenerator(value) | 2fb0149df049a7e10e10a4db0c5b03e625cd1636 | 681,301 |
def _can_append_long_entry(e, f):
"""True if f is a FATDirEntry that can follow e. For f to follow e, f and e
must have the same checksum, and f's ordinal must be one less than e"""
return (
f.LDIR_Chksum == e.LDIR_Chksum and
f.long_name_ordinal() + 1 == e.long_name_ordinal()
) | caf73ddda8b7d4dff02e0fdf14d6a10c22098185 | 681,302 |
def get_declared_licenses(license_object):
"""
Return a list of declared licenses, either strings or dicts.
"""
if not license_object:
return []
if isinstance(license_object, str):
# current, up to date form
return [license_object]
declared_licenses = []
if isinstan... | bd466497097d55ef6348650683819b6432f8454e | 681,303 |
def predict(node, row):
"""This method makes a prediction with a decision tree"""
if row[node['index']] < node['value']:
if isinstance(node['left'], dict):
return predict(node['left'], row)
else:
return node['left']
else:
if isinstance(node['right'], dict):
... | 97afbd7b34f5899291ec05932da3ad31bcc80219 | 681,304 |
import math
def to_acres(km2):
""" square KM to acres """
if math.isnan(km2):
return 0
return round(km2 * 247.11) | cb59770998d88b95a98f02b6cd2a976c27513036 | 681,305 |
def get_created_action(card):
"""
Return the date when a card was created.
"""
if not card.actions:
return
for action in card.actions:
if action['type'] == 'createCard':
return action | d88b67cd542aaa2350cd446a827d64d3951e19b6 | 681,306 |
import math
def alpha(n):
"""Normalizing scale factor"""
return 1 / math.sqrt(2) if n == 0 else 1 | 7fcab0cc717c241303d40170f38b84b1101c32b9 | 681,307 |
def flttn(lst):
"""Just a quick way to flatten lists of lists"""
lst = [l for sl in lst for l in sl]
return lst | 04d131fc3f2b8113802b40aeed03a809d2af0476 | 681,308 |
import numbers
def make_struct_binding(
python_name: str,
cpp_name: str,
members_info: list,
*,
generate_repr=True,
indent_size=4,
module_var="m",
) -> str:
"""Generate pybind11 definitions for a simple struct.
`members_info` is a `list` of `MemberInfo` namedtuples.
"""
i... | 2bcac92f0c64be6b10aa8385211223e677561098 | 681,309 |
def extract_transcript_sequences(bed_dic, seq_dic,
ext_lr=False,
full_hits_only=False):
"""
Given a dictionary with bed regions (region ID -> BED row) and a
sequence dictionary (Sequence ID -> sequence), extract the BED region
sequences a... | bb81e0ff820ac4de762213358a783d1174152ee2 | 681,310 |
def _simplify_attr_list(attr_list):
"""
对attr_list进行简化,去掉没有用的字段。
"""
for attr in attr_list:
for key in attr.keys():
if key not in ("attr_id", "attr_name", "attr_type"):
attr.pop(key)
return attr_list | ffc7c2e3443a6c6f1baa1188b37d1fc2cf1945e3 | 681,311 |
from typing import List
import ast
def flatten_assign_targets(targets: List[ast.AST]) -> List[ast.AST]:
"""Extract assign targets from nested structures."""
unresolved = targets
resolved = []
i = 0
while i < len(unresolved):
target = unresolved[i]
if isinstance(target, (ast.List, ... | d6d083aef9d5ec1b746dd79f80fac7c29b00e263 | 681,312 |
import random
def getRandomColor(colorsList):
"""Returns a random color from <colorsList> or OFF"""
if len(colorsList) > 0:
return colorsList[random.randint(0, len(colorsList)-1)]
return 0, 0, 0 | 71ffb37f96281ee0978367ec983893dc9749d797 | 681,313 |
import os
def check_last_lines(filename,searchstr,lastbytes=10000,logger=None):
"""!Checks the last few bytes of a file to see if the specified
search string is present. Returns True if the string is present
or False if the file existed but the string was not present. Will
raise an exception if the ... | 4aaf6e6cf440289b956a4b4e3fba2b539fa03e52 | 681,315 |
from typing import Union
def uri_from_details(namespace: str, load_name: str,
version: Union[str, int],
delimiter='/') -> str:
""" Build a labware URI from its details.
A labware URI is a string that uniquely specifies a labware definition.
:returns str: The URI... | 5cf688704116d9f2d14cbe25fc455b4454fe96b8 | 681,316 |
def npm_download_url(namespace, name, version, registry='https://registry.npmjs.org'):
"""
Return an npm package tarball download URL given a namespace, name, version
and a base registry URL.
For example:
>>> expected = 'https://registry.npmjs.org/@invisionag/eslint-config-ivx/-/eslint-config-ivx-0... | 6adcf8728b37f59de7b03b8fa5d8de3bd3bc712b | 681,317 |
def format_all_args(args, kwds):
"""makes a nice string representation of all the arguments"""
allargs = []
for item in args:
allargs.append(str(item))
for key, item in kwds.items():
allargs.append(f"{key}={item}")
formattedArgs = ", ".join(allargs)
if len(formattedArgs) > 150:
... | 104c039bc1135fe9efd188a54ad376555a79898e | 681,318 |
def srepr(arg,glue = '\n'):
"""joins arguments as individual lines"""
if (not hasattr(arg, "strip") and
hasattr(arg, "__getitem__") or
hasattr(arg, "__iter__")):
return glue.join(srepr(x) for x in arg)
return arg if isinstance(arg,str) else repr(arg) | 850a0384ec69ea049f95954e0de71e998ca09726 | 681,320 |
def get_connected_nodes(n,nets):
"""
:param n:
:return:
"""
connected_nodes = []
for i in n.netIds:
net = nets[i]
for nd in net.nodeList:
if nd not in connected_nodes and nd != n:
connected_nodes.append(nd)
return connected_nodes | 0bcd2028683865d8a6ecf22681128ec73dbd161c | 681,321 |
import bisect
def find_le(a, x):
"""Find the rightmost value of A which is less than or equal to X."""
i = bisect.bisect_right(a, x)
if i: return a[i-1]
return None | 20a1b85908771d7eb2cb7398e22f899242b5c347 | 681,322 |
def pmid_15146165():
"""Create a test fixture for PMID 15146165."""
return {
"id": "pmid:15146165",
"label": "Lasota et al., 2004, Lab. Invest.",
"type": "Document",
"description": "A great majority of GISTs with PDGFRA mutations represent gastric tumors of low or no malignant po... | 808f2f3cdce8ce8417d9f552d4c07bd0736015d3 | 681,323 |
def is_singleton(obj):
"""Is string_like or not iterable."""
return hasattr(obj,"capitalize") or not hasattr(obj,"__iter__") | ded32e0124b417a6bd08fbae3548fb8ac7cba6a4 | 681,324 |
def _plot_procs_lad(ftr_key, lad_key):
"""return processors to add ladder feature of price sizes to back/lay feature"""
return [
{
'name': 'prc_ftrstodf',
'kwargs': {
'ftr_keys': {
'y': ftr_key,
'text': lad_key
... | e3c91ed5b578a414504f222889cfa9b20e8719b8 | 681,325 |
import os
def magic_write(ofile, Recs, file_type, dataframe=False,append=False):
"""
Parameters
_________
ofile : path to output file
Recs : list of dictionaries in MagIC format OR pandas dataframe
file_type : MagIC table type (e.g., specimens)
dataframe : boolean
if True, Recs is ... | fcc6ce84d22483d417a6077eb2a9ba78b84ba934 | 681,326 |
def get_cookie_domain(app):
"""Helpful helper method that returns the cookie domain that should
be used for the session cookie if session cookies are used.
"""
if app.config['SESSION_COOKIE_DOMAIN'] is not None:
return app.config['SESSION_COOKIE_DOMAIN']
if app.config['SERVER_NAME'] is not N... | 0c5be02b554c875e3dffdf0850c5421c9a410f37 | 681,327 |
import re
def _name_label(name_dict):
"""Create label for name dictionary.
Parameters
----------
name_dict : dict
name dictionary created by format_name method
Returns
-------
label : str
"""
esc = r"\\"[:-1]
if "mag" in name_dict["base"]:
base = "|" + re.su... | fa12fe3e87f16b10a7e49ff41c7111adbeb2f72d | 681,328 |
def get_status_color(status):
"""Return (markup) color for test result status."""
colormap = {"passed": {"green": True, "bold": True},
"failed": {"red": True, "bold": True},
"blocked": {"blue": True, "bold": True},
"skipped": {"yellow": True, "bold": True}}
r... | c0c23ab6c37202fd78c4ddfe66226077bbb9ad1e | 681,329 |
from typing import List
import re
def glob2re(glob: str) -> str: # pylint: disable=too-many-branches
"""
Translate a ``glob`` pattern to the equivalent ``re.Pattern`` (as a string).
This is subtly different from ``fnmatch.translate`` since we use it to match the result of a successful ``glob``
rathe... | b67c56232db2dc91336655fb84836576eb71c2bd | 681,330 |
def date_month(date):
"""Find the month from the given date."""
return date.month | 2473c70e38de923074a3534f8320b3df5689fc3d | 681,331 |
def packages(package_helper):
"""Return the list of specified packages (i.e. packages explicitely installed excluding dependencies)"""
return package_helper.specified_packages() | 7b6ed3eb4180dcd88d1ace52db3015571e58f623 | 681,332 |
def get_channel_clrs():
""" Simple dict to organize styles for channels
Returns:
channel_dict: dict
"""
return dict(b='blue', r='red', z='purple') | 0fffab140cc2e277e1aab1e900e1dcbcaf518df9 | 681,333 |
import random
def get_random_point():
"""Creates random x, y coordinates."""
x = random.randint(-100, 100)
y = random.randint(-100, 100)
return x, y | 0be10095ca9646f51be98c115a766a265746517a | 681,334 |
from typing import Dict
from typing import List
from typing import Set
def determine_alternatives(profile: Dict[str, List[Set[str]]]) -> Set[str]:
"""
:param profile:
:return:
"""
ret_set = set()
for _, ballot in profile.items():
for alternatives in ballot:
for alternative... | d655eef035535d00495cea6ccb537ccec40f762b | 681,335 |
def _kron(vec0,vec1):
"""
Calculates the tensor product of two vectors.
"""
new_vec = []
for amp0 in vec0:
for amp1 in vec1:
new_vec.append(amp0*amp1)
return new_vec | 491ec6539a5352c1a744b1b856b4e1412755f4fc | 681,336 |
import json
def to_msg(msg_data):
"""Serialize prebuild message
:param dict msg_data: message data dict
:return: pickled bytes
:rtype: bytes
"""
return json.dumps(msg_data) | f1f7cb101e572fe87670c387d452fcf36ec42ede | 681,337 |
def problem(keys, kt):
"""
return a function that return from kt
"""
def return_function(x):
table = dict(zip(keys, x))
acc, vacc, xacc = kt(table)
return [(vacc + xacc)/2]
return return_function | 6c7e7485ea7ec773bf9fe96b550d440d446e9642 | 681,338 |
def units(self):
"""
Function Description:
This function will...
1. Currently will be a dummy function that does nothing
2. Future it will take in the original units, convert them to MPa for calculations
then the units can be converted into whatever is needed after that
"""
"""---------... | cdc4d6c722ae3911fa7411b60fe6887851cfbbd0 | 681,339 |
def get_container_name(framework):
"""Translate the framework into the docker container name."""
return 'baseline-{}'.format({
'tensorflow': 'tf',
'pytorch': 'pyt',
'dynet': 'dy'
}[framework]) | 172dfb49d25646aa1253bc257db5bc712c1229e9 | 681,340 |
def _merge_temporal_interval(temporal_interval_list):
"""
Merge the temporal intervals in the input temporal interval list. This is for situations
when different actions have overlap temporal interval. e.g if the input temporal interval list
is [(1.0, 3.0), (2.0, 4.0)], then [(1.0, 4.0)] will be returne... | 1d7db003ed068b02f14fb9ef02b051044ab75d11 | 681,341 |
def datetimeToReadable(d, tz):
"""Returns datetime as string in format %H:%M %m/%d/%Y
%d datetime object
%returns string of object in readable format."""
return d.astimezone(tz).strftime("%H:%M %m/%d/%Y") | ad4d93d9d112703f7f8c3455dd9128e350c2be07 | 681,342 |
def GenerateNextInRange(range, prev=None):
"""Generates next value in range.
Args:
range: dict, A range descriptor:
{start: Value, stop: Value, opt step: Value}
prev: int or float or None, A previous value or None.
Returns:
int or float, Random value.
"""
start = range['start']
if prev is... | 3541c0fcf15945181b9f8b8fd7f071e15c64452d | 681,343 |
import re
def filter_runs(runs, function, device):
""" returns a list of runs that only contain runs matching with function and device """
function_re = re.compile(function) if function else re.compile(".*")
device_re = re.compile(device) if device else re.compile(".*")
return [r for r in runs if func... | 5a53265aba5093902a0a141f5de1ef11ebbd549f | 681,344 |
def _asym_transform_deriv_alpha(systematic_utilities,
alt_IDs,
rows_to_alts,
intercept_params,
output_array=None,
*args, **kwargs):
"""
Parameters
-... | 24df48d34f05299deab7a7b024a43301a585f677 | 681,345 |
def create_valid_worksheet_name(string):
"""Exclude invalid characters and names.
Data from http://www.accountingweb.com/technology/excel/seven-characters-you-cant-use-in-worksheet-names."""
excluded = {"\\", "/", "*", "[", "]", ":", "?"}
if string == "History":
return "History-worksheet"
... | 0944904893f5e1c0339aa381d83e1c9eef13e792 | 681,346 |
def _default_call_out_of_place(op, x, **kwargs):
"""Default out-of-place evaluation.
Parameters
----------
op : `Operator`
Operator to call
x : ``op.domain`` element
Point in which to call the operator.
kwargs:
Optional arguments to the operator.
Returns
-------... | 8aaec539ebaa2005cc2e8163a5ac4e20ae12b0c8 | 681,347 |
import hashlib
def encrypt(text):
"""
encrypts plain text to unreadable text by utilizing the
sha512 hashing algorithm.
"""
return hashlib.sha512(text.encode("utf-8")).hexdigest() | e084d9fcb0152790c18ef561a7f79fb62d034085 | 681,348 |
import numpy as np
def fix_task_env():
"""
Set up a testing environment for tasks.
"""
def input_task_example(parts_dict):
"""Simple example task. This is the first task in the chain.
:param dict parts_dict: Dictionary specifying the input parts. It should be of the form
{"pa... | ecbe9977dc9883cd780ea9d28d1fb5b151eaf9f7 | 681,349 |
import uuid
def gen_id() -> str:
"""Generate new Skybell IDs."""
return str(uuid.uuid4()) | 77cdcf546c95071f618119b5f493d7a46426c5bd | 681,350 |
def wrap_list(list_, idx):
"""Return value at index, wrapping if necessary.
Parameters
----------
list_ : :class:`list`
List to wrap around.
idx : :class:`int`
Index of item to return in list.
Returns
-------
:class:`list` element
Item at given index, index will... | 9875ccfa8c9885753bcbc6782e0b7926bb69bbf2 | 681,351 |
def ghostedDistArrayFactory(BaseClass):
"""
Returns a ghosted distributed array class that derives from BaseClass
@param BaseClass base class, e.g. DistArray or MaskedDistArray
@return ghosted dist array class
"""
class GhostedDistArrayAny(BaseClass):
"""
Ghosted distributed arr... | c735b09b50070e3e8f318e989e465887163dae5f | 681,353 |
from typing import Tuple
def get_tensor_dimensions(n_atom_types : int, n_formal_charge : int, n_num_h : int,
n_chirality : int, n_node_features : int, n_edge_features : int,
parameters : dict) -> Tuple[list, list, list, list, int]:
"""
Returns dimensions for... | 7c1da4fccf7e3d944a08e3be70751bd4f2422ed7 | 681,354 |
def djb2(s: str) -> int:
"""
Implementation of djb2 hash algorithm that
is popular because of it's magic constants.
>>> djb2('Algorithms')
3782405311
>>> djb2('scramble bits')
1609059040
"""
hash = 5381
for x in s:
hash = ((hash << 5) + hash) + ord(x)
return hash & ... | 52cc44035ec1cc20e6f635a6e2715f08e7ee9887 | 681,355 |
def create_keys(line):
"""Return list of unique words"""
bins = {}
for number in line.split():
if number != '|':
# sort digits in number
s = "".join(sorted(number))
bins[s] = bins.get(s, 0) + 1
return(list(bins.keys())) | 91260c821d0a660d02062389c01bfdb288c082f6 | 681,356 |
def meow() -> str:
"""Another sample method."""
return "meow!" | 93543778993e6ac367ae702d16fe21664e669eb7 | 681,358 |
import requests
import random
def get_image_content_and_comment() -> tuple:
"""It gets a random image from xkcd.com. and write it to a file."""
current_image_num = requests.get('https://xkcd.com/info.0.json').json()['num']
random_image_num = random.randint(0, current_image_num)
random_image_url = 'htt... | 344c80c38dc050cb030733e3f7a14189e038cb91 | 681,359 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.