content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def hash_key(key: int, size: int) -> int: """ Return an integer for the given key to be used as an index to a table of the given size. >>> hash_key(10, 7) 3 """ return key % size
212d1c74aa7882695fbe3cd15ca62301386344b6
672,117
def isWord(s): """ See if a passed-in value is an identifier. If the value passed in is not a string, False is returned. An identifier consists of alphanumerics or underscore characters. Examples:: isWord('a word') ->False isWord('award') -> True isWord(9) -> False ...
84df75643db356fb583e4bbc20fc887779dfdb74
672,119
def is_better_sol(best_f, best_K, sol_f, sol_K, minimize_K): """Compares a solution against the current best and returns True if the solution is actually better accordint to minimize_K, which sets the primary optimization target (True=number of vehicles, False=total cost).""" if sol_f is None or so...
15ab7dd0294226870e476731066130253ae2986a
672,121
def lineAtPos ( s, pos ): """ lineAtPos: return the line of a string containing the given index. s a string pos an index into s """ # find the start of the line containing the match if len(s) < 1: return "" if pos > len(s): pos = len(s)-1 while pos > 0: if s[pos] == '\n': pos = pos + 1 break ...
f78b52947573ebc4cb6dfb8b88bd75a4bac7fb62
672,123
import inspect def wants_args(f): """Check if the function wants any arguments """ argspec = inspect.getfullargspec(f) return bool(argspec.args or argspec.varargs or argspec.varkw)
bf34e92240e5580edd32cfec7f21e10b53851371
672,129
from typing import Tuple def split_templated_class_name(class_name: str) -> Tuple: """ Example: "OctreePointCloud<PointT, LeafContainerT, BranchContainerT>::Ptr" ("OctreePointCloud", (PointT, LeafContainerT, BranchContainerT), "::Ptr") """ template_types = tuple() pos = class_name....
a2f0ee818a1985ee943cc975928be4e18470882b
672,130
def validate_type(data_dict: dict, type_name: str) -> dict: """Ensure that dict has field 'type' with given value.""" data_dict_copy = data_dict.copy() if 'type' in data_dict_copy: if data_dict_copy['type'] != type_name: raise Exception( "Object type must be {}, but was i...
cbb492d3ed27beba5e24f78c5f526585d7b47585
672,134
from typing import List from typing import Any def all_same(list: List[Any]) -> bool: """Decide whether or not a list's values are all the same""" return len(set(list)) == 1
1a3f22c2b2d1a5b114712bcf39e9ef50a3e10555
672,138
import torch def linear_2_oklab(x): """Converts pytorch tensor 'x' from Linear to OkLAB colorspace, described here: https://bottosson.github.io/posts/oklab/ Inputs: x -- pytorch tensor of size B x 3 x H x W, assumed to be in linear srgb colorspace, scaled between 0. and 1. Re...
f732e2b268c8bd1ffae92197b100cfd265033baa
672,140
def point_in_polygon(S, q): """determine if a point is within a polygon The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu> (see URL below) with some minor modifications for integer. It returns true for strictly interior points, false for strictly exterior, and ub for points on the boun...
81f73ded677991552927914ef478b0ce308c2d35
672,141
def query(question, default_answer="", help=""): """Ask user a question :param question: question text to user :param default_answer: any default answering text string :param help: help text string :return: stripped answer string """ prompt_txt = "{question} [{default_answer}] ".format(que...
ecfc894091cc3a77d07712ee3d74fcc46ae8a9df
672,145
def path_to_major_minor(node_block_devices, ndt, device_path): """ Return device major minor for a given device path """ return node_block_devices.get(ndt.normalized_device_path(device_path))
a229ad002912678cfe7f54c484218069f2fbc6ae
672,146
def except_text(value): """ Creates messages that will appear if the task number is entered incorrectly :param value: 'список', 'задача', 'цифра'. Depends on what messages are needed :return: 2 messages that will appear if the task number is entered incorrectly """ if value == 'список': ...
8394ca2f2cb5b513069877d29d070adf79709ac3
672,147
def RemoveAllJetPtCuts(proc): """ Remove default pt cuts for all jets set in jets_cff.py """ proc.finalJets.cut = "" # 15 -> 10 proc.finalJetsAK8.cut = "" # 170 -> 170 proc.genJetTable.cut = "" # 10 -> 8 proc.genJetFlavourTable.cut = "" # 10 -> 8 proc.genJetAK8Table.c...
1f73ccfc1d81c6af449fe45990bc9097dbc91252
672,157
import importlib def validate_external_function(possible_function): """ Validate string representing external function is a callable Args: possible_function: string "pointing" to external function Returns: None/Callable: None or callable function Raises: N/A # noqa ...
47b1584fbca601a67ff495b45d8f634a3bd412cd
672,158
from pathlib import Path def get_mirror_path(path_from: Path, path_to: Path) -> Path: """Return the mirror path from a path to another one. The mirrored path is determined from the current working directory (cwd) and the path_from. The path_from shall be under the cwd. The mirrored relative path is t...
e617e58c426f91499ba6ec85e842513b19b98ce2
672,161
def htk_int_to_float(value): """ Converts an integer value (time in 100ns units) to floating point value (time in seconds)... """ return float(value) / 10000000.0
54546e9d980ad0bcc488d086daa50a8bfb51821d
672,170
def parse_name(name): """ Parse name of the form 'namespace_name.unit_name' into tuple ('namespace_name', 'unit_name'). """ if '.' not in name: raise ValueError('`func` parameter must be provided or name must be "namespace_name.unit_name"') name_components = name.split('.') if len(name_component...
97a81e27e9b9c5eaea1a13b1c9a28cddf549c7f6
672,172
def loglinear_rule_weight(feature_dict, feature_weights_dict): """ Compute log linear feature weight of a rule by summing the products of feature values and feature weights. :param feature_dict: Dictionary of features and their values :param feature_weights_dict: Dictionary of features and their weights...
5db1edec2a3218144972434f6a7512484a3b71cc
672,173
def folder_from_egtb_name(name: str) -> str: """ Determine EGTB folder (Xvy_pawn(less|ful)) from EGTB name :param name: EGTB name """ l, r = name.split('v') prefix = f'{len(l)}v{len(r)}' suffix = '_pawnful' if ('P' in l or 'P' in r) else '_pawnless' return prefix + suffix
4c4838bcbaa20ac422102526162d44bf1422fcf2
672,178
import torch def householder_matrix(v, size=None): """ householder_matrix(Tensor, size=None) -> Tensor Arguments v: Tensor of size [Any,] size: `int` or `None`. The size of the resulting matrix. size >= v.size(0) Output I - 2 v^T * v / v*v^T: Tensor of size [size, ...
8b00a552bed7f22b671a4e4fa0a6b6df67b3aadc
672,185
def count_first_word(str_list): """Count the first word of each string in the list. Args: str_list: List of strings Returns: {"word": count, ...} """ ret_count = dict() for phrase in str_list: words = phrase.split("-") ret_count[words[0]] = ret_count.get(words[...
3350441d38daec4bb9f659d780886efd4af7dd4f
672,188
def quantify(iterable, pred=bool): """Count the number of items in iterable for which pred is true.""" return sum(1 for item in iterable if pred(item))
f43fbd0459db90615bd019e3afd9417abf7d8e88
672,195
def windows_low_high_to_int(windows_int_low, windows_int_high): """Returns an int given the low and high integers""" return (windows_int_high << 32) + windows_int_low
ead6e4d19022f49e9bde7600f13399d3e236d10a
672,197
import time def filename_stamped(filename, number): """Create a time-stamped filename""" time_str = time.strftime("%Y%m%d-%H%M%S") return '{}_{}_{}'.format(filename, number, time_str)
cf97aad13edbc1657f328725f2351d2ca1481ce6
672,198
def say_hello() -> str: """Say hello function.""" return "Hello"
42c2de62056246c01f4e0072e073d1fa944c406c
672,199
def parse_hash_id(seq): """Return a list of protein numbers within the given string. Example ------- "#10,41,43,150#" -> ["10", "41", "43", "150"] """ ans = seq.strip("#").split(",") return ans
26e196be40c741dca9c09c79ec6e4352c48952e9
672,200
def shorten_dfs(dfs, plot_start=None, plot_end=None): """Shorten all incidence DataFrames. All DataFrames are shortened to the shortest. In addition, if plot_start is given all DataFrames start at or after plot_start. Args: dfs (dict): keys are the names of the scenarios, values are the incide...
a059d0a27ec521d816679aeba1e5bf355cb5dc16
672,201
def nt2over_gn_groupings(nt): """Return the number of grouping ``over'' a note. For beamings trees this is the number of beams over each note. Args: nt (NotationTree): A notation tree, either beaming tree or tuplet tree. Returns: list: A list of length [number_of_leaves], with integer...
7f2c2a281a55d8dd3b837b7510be4dcc93f74779
672,202
def center_crop(data, shape): """ Apply a center crop to the input real image or batch of real images. Args: data (torch.Tensor): The input tensor to be center cropped. It should have at least 2 dimensions and the cropping is applied along the last two dimensions. sh...
c1f220e555333d38a83271d5e9254c4b1178d3c1
672,205
def fetch_method(obj, method): """ fetch object attributes by name Args: obj: class object method: name of the method Returns: function """ try: return getattr(obj, method) except AttributeError: raise NotImplementedError(f"{obj.__class__} has not impl...
49f823c4f8fd2296f6fd17dcfd5fc72b8835b42a
672,208
def extend_dict(dict_1: dict, dict_2: dict) -> dict: """Assumes that dic_1 and dic_2 are both dictionaries. Returns the merged/combined dictionary of the two dictionaries.""" return {**dict_1, **dict_2}
88e2f1c613181046b388092677b8ee627c432d4d
672,211
import requests def download_zip(url:str, dest_path:str, chunk_size:int = 128)->bool: """Download zip file Downloads zip from the specified URL and saves it to the specified file path. see https://stackoverflow.com/questions/9419162/download-returned-zip-file-from-url Args: url (str): sl...
a4f6024695976f422bc6dc3979c8438cfff9c70e
672,212
def trash_file(drive_service, file_id): """ Move file to bin on google drive """ body = {"trashed": True} try: updated_file = drive_service.files().update(fileId=file_id, body=body).execute() print(f"Moved old backup file to bin.") return updated_file except Exception: ...
f9a2a331a74cdb4050dc6bb788fc398d7db90ec1
672,214
import inspect def extract_kwargs(docstring): """Extract keyword argument documentation from a function's docstring. Parameters ---------- docstring: str The docstring to extract keyword arguments from. Returns ------- list of (str, str, list str) str The name of the...
3ec2442fbe3ec3984d6c5462f1c0006c4b723f2f
672,215
def get_total_interconnector_violation(model): """Total interconnector violation""" # Total forward and reverse interconnector violation forward = sum(v.value for v in model.V_CV_INTERCONNECTOR_FORWARD.values()) reverse = sum(v.value for v in model.V_CV_INTERCONNECTOR_REVERSE.values()) return forw...
cbe6c1e3e1424623064e9d906d143e1ae728a141
672,216
import hashlib def Many_Hash(filename): """ calculate hashes for given filename """ with open(filename, "rb") as f: data = f.read() md5 = hashlib.md5(data).hexdigest() sha1 = hashlib.sha1(data).hexdigest() sha256 = hashlib.sha256(data).hexdigest() sha512 = hashlib.sha512(data).hexdiges...
7805ab4e72726026a4fb21f754964d02fba857a0
672,218
def grad_likelihood(*X, Y=0, W=1): """Gradient of the log-likelihood of NMF assuming Gaussian error model. Args: X: tuple of (A,S) matrix factors Y: target matrix W: (optional weight matrix MxN) Returns: grad_A f, grad_S f """ A, S = X D = W * (A.dot(S) - Y) ...
4a52389764b9d52cc5dd4dae9f72fbdd46dba174
672,219
from typing import Sequence from typing import List def chain(items: Sequence, cycle: bool = False) -> List: """Creates a chain between items Parameters ---------- items : Sequence items to join to chain cycle : bool, optional cycle to the start of the chain if True, default: Fals...
d47e834b152c061011ec6278220777a5c3d04146
672,220
def _ensure_list_of_lists(entries): """Transform input to being a list of lists.""" if not isinstance(entries, list): # user passed in single object # wrap in a list # (next transformation will make this a list of lists) entries = [entries] if not any(isinstance(element, list...
a1866fdd62861f40e7f5aa9ce491ba14fc5a6cc9
672,222
def get_daily_returns(df): """Compute and return the daily return values.""" daily_returns = df.copy() daily_returns[1:] = (df[1:] / df[:-1].values) - 1 daily_returns.iloc[0] = 0 # set daily returns for row 0 to 0 return daily_returns
8b72e3bb446f77d0ccdd63d664da4f9a48f45cf0
672,225
def bitarray2dec(in_bitarray): """ Converts an input NumPy array of bits (0 and 1) to a decimal integer. Parameters ---------- in_bitarray : 1D ndarray of ints Input NumPy array of bits. Returns ------- number : int Integer representation of input bit array. """ ...
ae4cbb907c13d92a5dde734e7bb9d11ab4aa6225
672,226
def set_state_dict(model, state_dict): """Load state dictionary whether or not distributed training was used""" if hasattr(model, "module"): return model.module.load_state_dict(state_dict) return model.load_state_dict(state_dict)
fab8c5e73d0efa3df480e692697c865977066804
672,229
import re def _parse_line(cpuid, match): """Search a line with the content <match>: <value> in the given StringIO instance and return <value> """ cpuid.seek(0) for l in cpuid.readlines(): m = re.match('^(%s.*):\s+(.+)' % match, l) if m: return (m.group(1), m.group(2).r...
d83fcc1e79b13e5ed11e79e3dad47eb99d0e2371
672,230
def other_options(options): """ Replaces None with an empty dict for plotting options. """ return dict() if options is None else options.copy()
b2f22bc681ed633445a7a984e3c9f3da9dc975ab
672,231
from typing import Any def make_safe(element: Any) -> str: """ Helper function to make an element a string Parameters ---------- element: Any Element to recursively turn into a string Returns ------- str All elements combined into a string """ if isinstance(el...
ea104f847323c8b56ec20df57f28c98fce784cd7
672,235
import re def demo_id(filename): """Get the demo_number from a test macro""" b1 = re.match('.*/test_demo\d{2}\.py', filename) found = re.findall('.*/test_demo(\d{2})\.py', filename) b2 = len(found) == 1 is_test_file = b1 and b2 assert is_test_file, 'Not a test file: "%s"' % filename return...
9402586f92ea9d95eee10c9047efc6b43c25abac
672,236
def read_classification_from_file(filename): """ Return { <filename> : <classification> } dict """ with open(filename, "rt") as f: classification = {} for line in f: key, value = line.split() classification[key] = value return classification
8e3d30e55efd289fa98d0d28acf0d8d857ace835
672,239
def truncate(message, limit=500): """ Truncates the message to the given limit length. The beginning and the end of the message are left untouched. """ if len(message) > limit: trc_msg = ''.join([message[:limit // 2 - 2], ' .. ', message[...
93d117c475e4a198b60a387f6911c9cbbc246e64
672,241
def findDataStart(lines, delin = ' '): """ Finds the line where the data starts input: lines = list of strings (probably from a data file) delin = optional string, tells how the data would be separated, default is a space (' ') output: i = integer where the data stops being...
b9e2aa79d9eae1616412491763cfdde3e6e37672
672,247
def pa_bbm_hash_mock(url, request): """ Mock for Android autoloader lookup, new site. """ thebody = "http://54.247.87.13/softwareupgrade/BBM/bbry_qc8953_autoloader_user-common-AAL093.sha512sum" return {'status_code': 200, 'content': thebody}
4d1909fef728aa2adec2b418796747a7b789add1
672,250
import itertools import random def generate_comparison_pairs(condition_datas): """ Generate all stimulus comparison pairs for a condition and return in a random order for a paired comparison test. Parameters ---------- condition_datas: list of dict List of dictionary of condition data as ...
f850da7cfd9edbecf22bdabe7dff1e1a325cc1fb
672,255
def alltrue(seq): """ Return *True* if all elements of *seq* evaluate to *True*. If *seq* is empty, return *False*. """ if not len(seq): return False for val in seq: if not val: return False return True
ecfc0a2a88d4bac16144e676e9c141624ec15c9e
672,256
def test(classifier, data, labels): """ Test a classifier. Parameters ---------- classifier : sklearn classifier The classifier to test. data : numpy array The data with which to test the classifier. labels : numpy array The labels with which to test the the classifier. Returns ...
ab26442225b9a97fea27ad7d86cd2c4251dd4a3f
672,258
def reverse_complement(s): """Return reverse complement sequence""" ret = '' complement = {"A": "T", "T": "A", "C": "G", "G": "C", "N": "N", "a": "t", "t": "a", "c": "g", "g": "c", "n": "n"} for base in s[::-1]: ret += complement[base] return ret
dff5b4597596be93973c143a0e3fc110d23f132f
672,262
def hex_to_rgb(col_hex): """Convert a hex colour to an RGB tuple.""" col_hex = col_hex.lstrip('#') return bytearray.fromhex(col_hex)
2a38fe4fbd9231231a0ddcc595d27d71b0718ba3
672,267
def page_query_with_skip(query, skip=0, limit=100, max_count=None, lazy_count=False): """Query data with skip, limit and count by `QuerySet` Args: query(mongoengine.queryset.QuerySet): A valid `QuerySet` object. skip(int): Skip N items. limit(int): Maximum number of items returned. ...
2aef61019b67f2d9262ad8f671a9991e0915ddcf
672,272
def nvt_cv(e1, e2, kt, volume = 1.0): """Compute (specific) heat capacity in NVT ensemble. C_V = 1/kT^2 . ( <E^2> - <E>^2 ) """ cv = (1.0/(volume*kt**2))*(e2 - e1*e1) return cv
12d8cee877ef2a6eee1807df705ba5f193c84f52
672,274
def rectangle_to_cv_bbox(rectangle_points): """ Convert the CVAT rectangle points (serverside) to a OpenCV rectangle. :param tuple rectangle_points: Tuple of form (x1,y1,x2,y2) :return: Form (x1, y1, width, height) """ # Dimensions must be ints, otherwise tracking throws a exception return (int(rectangle_points[...
47548d4098d057625ebfd846164946481222559d
672,275
def dijkstra(g, source): """Return distance where distance[v] is min distance from source to v. This will return a dictionary distance. g is a Graph object. source is a Vertex object in g. """ unvisited = set(g) distance = dict.fromkeys(g, float('inf')) distance[source] = 0 whi...
aa28bb28c581fc6f3651f1a7ae704b56ac3f1525
672,276
def calc_gross_profit_margin(revenue_time_series, cogs_time_series): # Profit and Cost of Goods Sold - i.e. cost of materials and director labour costs """ Gross Profit Margins Formula Notes ------------ Profit Margins = Total revenue - Cost of goods sold (COGS) / revenue ...
d7fe1352278423b048cc456adba3580647cff0f4
672,277
import asyncio def event_loop() -> asyncio.AbstractEventLoop: """Returns an event loop for the current thread""" return asyncio.get_event_loop_policy().get_event_loop()
19d1e4544eba04b2b8d99c7efa3427021d2d95e8
672,283
def set_discover_targets(discover: bool) -> dict: """Controls whether to discover available targets and notify via `targetCreated/targetInfoChanged/targetDestroyed` events. Parameters ---------- discover: bool Whether to discover available targets. """ return {"method": "Target....
31de0937b68af4b6492f4c49d67d5f4c481a5c6b
672,284
def notas(*nt, sit=False): """ -> Função para analisar notas e situação de vários alunos. :param nt: recebe uma ou mais notas dos alunos. :param sit: valor opcional, mostrando ou não a situação do aluno(True/False). :return: dicionário com várias informações sobre a situação da turma. """ pr...
4854c5941f57e5775a504fd9ad24b96886dd2bfd
672,286
def _get_binary(value, bits): """ Provides the given value as a binary string, padded with zeros to the given number of bits. :param int value: value to be converted :param int bits: number of bits to pad to """ # http://www.daniweb.com/code/snippet216539.html return ''.join([str((value >> y) & 1) for...
4b4312026cef9fbdca228b1db7205825c5353450
672,289
def count_null_values_for_each_column(spark_df): """Creates a dictionary of the number of nulls in each column Args: spark_df (pyspark.sql.dataframe.DataFrame): The spark dataframe for which the nulls need to be counted Returns: dict: A dictionary with column name as key and null count as ...
ff27c3bad5a0578bb51b0ef6d71659360ab5b11e
672,293
def __version_compare(v1, v2): """ Compare two Commander version versions and will return: 1 if version 1 is bigger 0 if equal -1 if version 2 is bigger """ # This will split both the versions by '.' arr1 = v1.split(".") arr2 = v2.split(".") n = len(arr1) m =...
fe1a563d26a5dabdae968c8502049fc1333acdd9
672,294
def create_vocab_item(vocab_class, row, row_key): """gets or create a vocab entry based on name and name_reverse""" try: name_reverse = row[row_key].split("|")[1] name = row[row_key].split("|")[0] except IndexError: name_reverse = row[row_key] name = row[row_key] temp_ite...
3f8fd941e02b857279f1a4961d35cfd36bf7cb5b
672,297
import json def _load_repo_configs(path): """ load repository configs from the specified json file :param path: :return: list of json objects """ with open(path) as f: return json.loads(f.read())
f96e2d78b2614d07b2b1b1edc71eb10a9c2709a3
672,301
def get_if_all_equal(data, default=None): """Get value of all are the same, else return default value. Arguments: data {TupleTree} -- TupleTree data. Keyword Arguments: default {any} -- Return if all are not equal (default: {None}) """ if data.all_equal(): return da...
30e7186ae835ba3ba9ac110c2f55b316346bdc1a
672,302
def convert_compartment_id(modelseed_id, format_type): """ Convert a compartment ID in ModelSEED source format to another format. No conversion is done for unknown format types. Parameters ---------- modelseed_id : str Compartment ID in ModelSEED source format format_type : {'modelseed...
8856858637b2f655ac790e026e7fe88c6e83e364
672,304
import torch def dirichlet_common_loss(alphas, y_one_hot, lam=0): """ Use Evidential Learning Dirichlet loss from Sensoy et al. This function follows after the classification and multiclass specific functions that reshape the alpha inputs and create one-hot targets. :param alphas: Predicted para...
c6c5749e9a24b8d5d2d9df8a3567f0c1d967f84e
672,306
def merge_dicts(base, updates): """ Given two dicts, merge them into a new dict as a shallow copy. Parameters ---------- base: dict The base dictionary. updates: dict Secondary dictionary whose values override the base. """ if not base: base = dict() if not u...
8f5cfc3805cd94809648a64311239b6bdc04adea
672,308
def get_hashes_from_file_manifest(file_manifest): """ Return a string that is a concatenation of the file hashes provided in the bundle manifest entry for a file: {sha1}{sha256}{s3_etag}{crc32c} """ sha1 = file_manifest.sha1 sha256 = file_manifest.sha256 s3_etag = file_manifest.s3_etag c...
d86d979fb5266f5a5b3027ddc6cf03548d4bf3a1
672,309
def lowerColumn(r, c): """ >>> lowerColumn(5, 4) [(5, 4), (6, 4), (7, 4), (8, 4)] """ x = range(r, 9) y = [c, ] * (9-r) return zip(x, y)
a51dcefed097f09315be21ec1aca958799f05d6b
672,311
def summarize_filetypes(dir_map): """ Given a directory map dataframe, this returns a simple summary of the filetypes contained therein and whether or not those are supported or not ---------- dir_map: pandas dictionary with columns path, extension, filetype, support; this is the ouput o...
b825402d123b48354607e8fd76319b45bc586e32
672,312
def staticTunnelTemplate(user, device, ip, aaa_server, group_policy): """ Template for static IP tunnel configuration for a user. This creates a unique address pool and tunnel group for a user. :param user: username id associated with static IP :type user: str :param device:...
0367205462157fe8b242095f19cf936a24b9afd8
672,315
from typing import Tuple def _build_label_attribute_names( should_include_handler: bool, should_include_method: bool, should_include_status: bool, ) -> Tuple[list, list]: """Builds up tuple with to be used label and attribute names. Args: should_include_handler (bool): Should the `handler...
52b704767b69a8a75e1824489c39e3b59c994a17
672,320
def constructQuery(column_lst, case_id): """ Construct the query to public dataset: aketari-covid19-public.covid19.ISMIR Args: column_lst: list - ["*"] or ["column_name1", "column_name2" ...] case_id: str - Optional e.g "case1" Returns: query object """ # Public dataset ...
e2107800565b10b3ee21ab15db04fadc8b167f42
672,321
def batch_unflatten(x, shape): """Revert `batch_flatten`.""" return x.reshape(*shape[:-1], -1)
0cbde13e3621336a6571d7a047eafcf20124e1b6
672,323
def prepend_batch_seq_axis(tensor): """ CNTK uses 2 dynamic axes (batch, sequence, input_shape...). To have a single sample with length 1 you need to pass (1, 1, input_shape...) This method reshapes a tensor to add to the batch and sequence axis equal to 1. :param tensor: The tensor to be reshaped ...
2433b8ddf2ed9f5854b8c527e7e39b869939360d
672,325
def dms2dd(d, m, s): """ Convert degrees minutes seconds to decimanl degrees :param d: degrees :param m: minutes :param s: seconds :return: decimal """ return d+((m+(s/60.0))/60.0)
e8285ada31a1b8316e1d9563992475a197fdb76a
672,327
def transpose_dataframe(df): # pragma: no cover """ Check if the input is a column-wise Pandas `DataFrame`. If `True`, return a transpose dataframe since stumpy assumes that each row represents data from a different dimension while each column represents data from the same dimension. If `False`, re...
9ef8f30337467fe256042389e03c4e052feb6a12
672,328
def write_data(f, grp, name, data, type_string, options): """ Writes a piece of data into an open HDF5 file. Low level function to store a Python type (`data`) into the specified Group. .. versionchanged:: 0.2 Added return value `obj`. Parameters ---------- f : h5py.File Th...
748dbc7d646ec33c31f9ef393ae998b76b317d41
672,330
def find_collection(client, dbid, id): """Find whether or not a CosmosDB collection exists. Args: client (obj): A pydocumentdb client object. dbid (str): Database ID. id (str): Collection ID. Returns: bool: True if the collection exists, False otherwise. """ ...
96f6bb66797b40daf137ed2d7920b6cd30697aa0
672,332
import json def load_dicefile(file): """ Load the dicewords file from disk. """ with open(file) as f: dicewords_dict = json.load(f) return dicewords_dict
42da982410dfc1ac39a1f40766ba6f7a2824d088
672,333
def get_soup_search(x, search): """Searches to see if search is in the soup content and returns true if it is (false o/w).""" if len(x.contents) == 0: return False return x.contents[0] == search
402a9cf0523c0022d86f8c7eb7d502acb45a9291
672,334
def EVLACalModel(Source, CalDataType=" ", CalFile=" ", CalName=" ", CalClass=" ", CalSeq=0, CalDisk=0, \ CalNfield=0, CalCCVer=1, CalBComp=[1], CalEComp=[0], CalCmethod=" ", CalCmode=" ", CalFlux=0.0, \ CalModelFlux=0.0, CalModelSI=0.0,CalModelPos=[0.,0.], CalModelPar...
0aa7ef72d7a379868b2edba1ffea6aa2eee8f559
672,335
def split(children): """Returns the field that is used by the node to make a decision. """ field = set([child.predicate.field for child in children]) if len(field) == 1: return field.pop()
798ae7e7e82cb62b9b71f2e7453a7ceb77c07fae
672,340
def reverse_str(input_str): """ Reverse a string """ return input_str[::-1]
df53f8e4ff65731865b3c9ef86fcb3a040c98677
672,346
def drop_suffix_from_str(item: str, suffix: str, divider: str = '') -> str: """Drops 'suffix' from 'item' with 'divider' in between. Args: item (str): item to be modified. suffix (str): suffix to be added to 'item'. Returns: str: modified str. """ suffix = ''.join([suf...
68ed4d44ef30243558b482964108bfe3a1f87552
672,349
def compute_reporting_interval(item_count): """ Computes for a given number of items that will be processed how often the progress should be reported """ if item_count > 100000: log_interval = item_count // 100 elif item_count > 30: log_interval = item_count // 10 else: ...
e82a1210e235afe9da1cd368900b7ac688488353
672,366
def _preprocess_graphql_string(graphql_string): """Apply any necessary preprocessing to the input GraphQL string, returning the new version.""" # HACK(predrag): Workaround for graphql-core issue, to avoid needless errors: # https://github.com/graphql-python/graphql-core/issues/98 return g...
df2ef81ef8fc5311686cbfcc644ce187dce8e02f
672,367
def get_yn_input(prompt): """ Get Yes/No prompt answer. :param prompt: string prompt :return: bool """ answer = None while answer not in ["y", "n", ""]: answer = (input(prompt + " (y/N): ") or "").lower() or "n" return answer == "y"
8957f6a77716fb7ad85063dddf5921e108827ab5
672,373
def form_clean_components(rmsynth_pixel, faraday_peak, rmclean_gain): """Extract a complex-valued clean component. Args: rmsynth_pixel (numpy array): the dirty RM data for a specific pixel. faraday_peak (int): the index of the peak of the clean component. rmclean_gain (float): loop gain for cle...
2bac5a50fff2e593e5aeab26a15f5dd814b61079
672,375
import re import json def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'): """Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_pat...
1339c0f900f1c6162866983f2a575dc30b4820cd
672,377
def get_axe_names(image, ext_info): """ Derive the name of all aXe products for a given image """ # make an empty dictionary axe_names = {} # get the root of the image name pos = image.rfind('.fits') root = image[:pos] # FILL the dictionary with names of aXe products # # th...
6c97970149d8eefa35eb3887fc3071f5160c6a53
672,382
from typing import List def arrayToFloatList(x_array) -> List[float]: """Convert array to list of float. Args: x_array: array[Any] -- Returns: List[float] """ return [float(x_item) for x_item in x_array]
617377ae4bf5e55db2882451d91d6839df0bec3d
672,391
def fetch_neighbours(matrix, y, x): """Find all neigbouring values and add them together""" neighbours = [] try: neighbours.append(matrix[y-1][x-1]) except IndexError: neighbours.append(0) try: neighbours.append(matrix[y-1][x]) except IndexError: neighb...
7ec775f44b3f12d3693e77e73283fa9783cb5f58
672,394
def maybe_unsorted(start, end): """Tells if a range is big enough to potentially be unsorted.""" return end - start > 1
5b7de3e159418a3aa4b3bf0e524e41e11b6455e2
672,395