content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def gpu_mul_Ax(A, b, ngpu, splits, TYPE=torch.float64,model_gpus=1): """ multiplies matrix A (stored on multiple GPUs) with vector x * returns vector on GPU 0 """ # Step 1: make a copy of B on each GPU N = splits[-1] b_ = [] for i in range(model_gpus, ngpu): b_.ap...
138670b16b825107ec4ba4eb7a71ed4238f6ec11
656,685
import logging def parse_tsv(fp): """Parse the Paladin output (in TSV format).""" dat = [] with open(fp, "rt") as f: header = f.readline().rstrip("\n").split("\t") for line in f: line = line.rstrip("\n").split("\t") # Skip empty lines if len(line) == 1: ...
a3a4f305aa402b158e170549db3a9f40d20b8ce5
656,687
import os def _get_config_file_abspath(fname): """Get absolute path of configuration file using BAG_WORK_DIR environment variable.""" fname = os.path.basename(fname) if 'BAG_WORK_DIR' not in os.environ: raise ValueError('Environment variable BAG_WORK_DIR not defined') work_dir = os.environ['B...
d4a228309e556ca3ec1b6a2e797fded7e146a453
656,688
def readfile(name): """Leggi i contenuti di un file. :param name: Nome del file """ file = open(name, 'r') content = file.read() file.close() return content
8540b12aa22174e7112d079a633abf00313c16a5
656,689
import ast from typing import List from typing import Tuple def get_scr119(node: ast.ClassDef) -> List[Tuple[int, int, str]]: """ Get a list of all classes that should be dataclasses" ClassDef( name='Person', bases=[], keywords=[], body=[ ...
eef10160a580c4b09451e69dd3054499e1d6ab91
656,690
import subprocess def get_first_last_commit_date(path): """ Gets the first and repository commit as a timestamp. """ # %at specifies a UNIX time stamp process = subprocess.Popen(['git', 'log', '--format=%at'], cwd=path, stdout=subprocess.PIPE) stdout, _ = process.communicate() log = stdout.decode(...
deed5f48c5f95150b71eb8cacf0bb9ceb025f41e
656,691
import click def style_prompt(message): """Returns a unified style for click prompts.""" return click.style(message, fg="cyan")
f04246be8f5b6afd689c46eae5529d3565f8fb7d
656,692
import subprocess def extract_audio(): """ Extracts audio from video file Returns: Returns filename for future use """ filename = input("Enter filename: ") command = "ffmpeg -i " + filename + " -ab 160k -ac 2 -ar 44100 -vn cut.wav" subprocess.call(command, shell=True) return ...
0d84027c3939bd7ad8693b981fd56473a63c0564
656,693
def is_prime(n): """Return True if n is a prime.""" if (n % 2 == 0 and n > 2) or n == 1: return False return all(n % i for i in range(3, int(n**0.5) + 1, 2))
4c1518664a464275f62a214c26c4b21796155c29
656,695
def _cache_name(request): """ Name for a preset cache. """ return "cache_%s" % request.user.username
ef722856d763c7288da12abcaa579b92af5c0a23
656,697
def book_value_per_share(book_value, total_shares): """Computes book value per share. Parameters ---------- book_value : int or float Book value (equity) of an enterprice total_shares : int or float Total number of shares Returns ------- out : int or float Book ...
80abcbb505892f1e028c2f45d7c725c763c1d33e
656,698
def str_to_bool(str_val): """ Функция конвертирует строку в настоящий bool. Правила конвертации: ===================== True (bool) == True, true, T, t, yes, y, 1 False (bool) == False, false, F, f, no, n, 0 :param str_val: --------------- Должна быть строка, содержащая ...
5eb942dbf41694bc43f74f5051ca22f470868ecf
656,699
from typing import List import json def str_to_list_of_ints(val) -> List[int]: """Accepts a str or list, returns list of ints. Specifically useful when num_hidden_units of a set of layers is specified as a list of ints""" if type(val) == list: return val else: return [int(v) for v in...
d1a8c471f0eb6bad828fdb6eb5bb42febfb2b36d
656,700
import collections def analyze_words(word_set): """ Identify uncommon letters in a word set. Returns a list of 2-tuples, each containing the letter of the alphabet and how many words in the set have that letter. Useful for identifying under-represented letters so you can beef up your word se...
17c9615f3a5f46d64b2685d12c1ba2afccaa281f
656,701
def time_to_seconds(time): # type: (str) -> int """ Attempts convert a given time string to the number of seconds where the format is SS, MM:SS or HH:MM:SS """ return sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time.split(":"))))
3bb8478d4c1a6477b2c52f5b36f65d6cff0fcebd
656,702
def center_crop(image, crop_size=None): """Center crop image. Args: image: PIL image crop_size: if specified, size of square to center crop otherwise, fit largest square to center of image Returns: cropped PIL image """ width, height = image.size #...
8159de83517289c8997ba5507bc62871eea3144c
656,704
def _set_default_elements(n_elements: int, subcategory_id: int) -> float: """Set the default number of elements for resistors. :param resistance: the current number of elements. :param subcategory_id: the subcategory ID of the resistor with missing defaults. :return: _n_elements :rtype: int """...
161717f8abbb705501dd119c516286df9d787c80
656,705
def rename_test(name: str, lang: str) -> str: """Append path with language type""" return f"{name}_{lang}"
a01f6ebfd52172f8955c0be60c6555fa147eb590
656,706
import os def prepare_ayah_directory(directory_path, surah_num, ayah_num) -> str: """Prepare a directory structure for an ayah. Returns: ayah_directory_path The path to the directory. """ ayah_directory_path = os.path.join(directory_path, 's{}'.format(surah_num), 'a{}'.format(ayah_num)) o...
2d34871ef4852add1068daf621b1bb197faf1a7d
656,707
from typing import List from typing import Dict def get_syntax_coloring_dicts(self) -> List[List[Dict]]: """ Converts the text in the editor based on the line_string_list into a list of lists of dicts. Every line is one sublist which contains different dicts based on it's contents. We create a dict f...
250569c0a2079cb9de2b709cc7f069caab776279
656,708
def name_version_release(spec_fh): """ Take the name, version and release number from the given filehandle pointing at a sepc file. """ content = {} for line in spec_fh: if line.startswith('Name:') and 'name' not in content: content['name'] = line[5:].strip() elif line.st...
6599beaaf980c133c3748c6d8433e58be2fc20e2
656,709
def listConnections(attr): """List connections of `attr` Arguments: attr (Plug or Node): Example: >>> node1 = createNode("transform") >>> node2 = createNode("mesh", parent=node1) >>> node1["v"] >> node2["v"] >>> listConnections(node1) == [node2] True ...
f7b7be7de41c365a761802ccdba0f9b9f8eec657
656,710
import time def ler_tempo(em_turnos=False): """ Se o jogo for em turnos, passe 1 (rodada), senão se o jogo for continuo ou estratégico, precisa. """ return 1 if em_turnos else time.time()
ad454ae62fce04fe6c12a9214417961b1ab855e6
656,711
def get_soft_trgt_acc_func(): """Get the accuracy function that can deal with generated soft targets. Returns: (func): A function handle. """ def soft_trgt_acc_fct(config, X, Y_logits, T_soft_logits, data): # Only compute accuracy for last timestep. Y_logits = Y_logits[-1, :, :]...
8efdc17a148a837a3ce3ae79f3d8cc305e7087b9
656,712
def _recursive_min(jagged): """ Examples -------- from landlab.components.profiler.base_profiler import _recursive_min >>> struct = [[1, 2, 3, 4], ... [[2, 3, 4, 5], ... [3, 4, 5, 6]], ... [4, 5, 6, 7]] >>> _recursive_min(struct) 1 >>> _recursiv...
6e66545a41caf0172a683f36b519f98f37260148
656,713
import ast def children(node): """Children to recurse over.""" # Children to recurse into for each node type. node_children = { ast.Module: ["body"], ast.ClassDef: ["bases", "body"], ast.FunctionDef: ["body"], ast.Assign: ["targets", "value"], } ks = node_children.get(node.__class_...
6c3a2a9f059b7f5f138a555709742109ec2bc9f9
656,714
import pathlib import collections import logging def get_text(directory): """ Return a concatenated string of section texts from the specified directory. Text files should be UTF-8 encoded. """ section_dir = pathlib.Path(directory) paths = sorted(section_dir.glob('[0-9]*.md')) name_to_text...
81d8483ee3f5943b0b15923fd9d451e7849a7df7
656,715
def import_class(class_path): """ Imports a class having dynamic name/path. Args: class_path: str Path to class (exp: "model.MmdetDetectionModel") Returns: mod: class with given path """ components = class_path.split(".") mod = __import__(components[0]) for c...
7f7957a28b90c01509e0a4490ba03ef2cd0f7abb
656,716
import re def rmPunct(string) : """Remove punctuation""" return re.sub(r'[^\w\s]','',string)
5257273f2eda6d9746b05c26aca3172a63e1cdb8
656,717
def _node_size(node): """Return the `node` size.""" size = 0 if node: size += 1 if node.left: size += node.left.size if node.right: size += node.right.size return size return size
4b5d7d3f271fd9d36b175173684b1dca57dda222
656,718
def remove_min_count(df, min_count): """ Function remove_min_count: This function removes data that is all zeros in a column best used once merging has taken place to get rid of all features that are zero in both conditions :param df: @type pandas dataframe: The data to remove counts below min_count...
6d18de9fc5acbec2e5324daf4ce3c3d6f50bd713
656,719
def getBigrams(wordlist, bigrams = {}, count = 0): """Returns a table of bigrams and the count.""" if len(wordlist) == 0: return bigrams, count for i in range(len(wordlist) - 1): if bigrams.has_key(wordlist[i] + " " + wordlist[i + 1]): bigrams[wordlist[i] + " " + wordlist[i + 1]] += 1 else: bigrams[wor...
7aa141def8cba376b510167fd62b76c3744a6038
656,720
def sort_by_score(iterable): """Sorts a collection of objects by their score attribute, descending. Args: iterable: iterable collection of objects with a score attribute. Returns: The collection sorted by score descending. """ return sorted(iterable, key=lambda x: x.score, reverse=True)
3b79220b4605bd9ddf754f6ba2356f2df7e1485f
656,721
import sys def use(abs_packages_dir): """Make an entry that contains an installed pip package the preferred location to import the package from. Usage examples : axs byname numpy_1.16.4_pip , use , python_api 'import numpy\nprint(numpy.__version__)' axs np: byname numpy_1.16.4_pip...
9df7493d4e9fc1fa3d103fa872274ac182f27444
656,722
import math def next_power_of_two(x: int) -> int: """Return next highest power of 2, or self if a power of two or zero.""" if x == 0: return 0 assert x >= 1, f"x must be 1 or greater; was: {x}" result = int(2 ** math.ceil(math.log2(x))) assert result >= x return result
84b253d86cc4531362c7592d10a56d056519834f
656,723
import torch def count_correct_rationales(pred, gold): """ Given vectors of predicted and gold rationales, count the number of correct predictions. A prediction is only correct if the whole gold set is ID'd. This is used for sentence-level evaluation. For this, we count all the predicted rationale...
6d9e707e66691d8fc2d6c1998b72ffe14c9e9de3
656,724
def escape_filter_chars(assertion_value,escape_mode=0): """ Replace all special characters found in assertion_value by quoted notation. escape_mode If 0 only special chars mentioned in RFC 4515 are escaped. If 1 all NON-ASCII chars are escaped. If 2 all chars are escaped. """ if escape_mo...
62a01c646001b6ed996225e21bfe37af95252e08
656,725
def cheap_lambdify_curry(free_vars, expression): """ Translate sympy expression to an actual Python expression that can be evaluated quickly. This is roughly the same as sympy's lambdify, with a number of differences: 1. We only support a subset of functions. Note that sympy's list is incomp...
8aa6cef4b6fed6dedab02c884671700bb8a13ad7
656,727
def _index_to_sequence(i, dim_list): """ For a matrix entry with index i it returns state it corresponds to. In particular, for dim_list=[2]*n it returns i written as a binary number. Parameters ---------- i : int Index in a matrix. dim_list : list of int List of dimensions...
18b6a077db38efd0dad027d129737e7d60621d6f
656,729
import math def y_ticks(max_y): """ Computes aesthetically pleasing y-axis tick marks for specified max value Note:: will always include y=0 as the minimum value returns list of y values and scaling factor """ log_max = math.log10(max_y) m_log_y = math.floor(log_max) # log of ...
00e1716f6db86389db0b16a27c62d7fd24d5ef3f
656,730
import os import uuid def get_unique_filename_uuid1(dir: str, fileext: str)->str: """Generate a unique file name in specified dir. return the file path""" if not isinstance(dir, str) or dir == "": raise Exception("Specified dir is None") if not isinstance(fileext, str) or fileext is None: ...
05157a786f788fb7e4d7981325460f14cbfd2465
656,731
def all_slots_will_be_full(effect): """ no open slots left """ return effect.instance.activity.slots.exclude(id=effect.instance.id).filter(status__in=['open']).count() == 0
75426be62b06df0830b6e32e0cedbf3980fe4b8d
656,732
import torch def to_bitmask(M): """ Returns the bitmask sparse format of matrix 'M' :param M: original weight matrix M """ wmb = (M != 0).float() data = M[torch.nonzero(M, as_tuple=True)] return wmb, data
a9e44b91effe07fa3aa4b99bec97794dc5e9ec58
656,733
from math import log def distributed_dlog(h, delta, m, g, fi): """converts a multiplicative secret sharing of g^x to an additive secret sharing of the value x, with inverse polynomial probability of error. :param g: g from ElGamal. :param h: g^t, t is modulo q. :param delta: failure probability. ...
f009086499a02090199d6a58227cb9cfc624c926
656,734
def WaitForAcquisition(): """ WaitForAcquisition can be called after an acquisition is started using StartAcquisition to put the calling thread to sleep until an Acquisition Event occurs. This can be used as a simple alternative to the functionality provided by the SetDriverEvent function,...
cb636127879769bbac0965bdb1ac3770ec8f1b19
656,735
def vec_sum(a): """ Computes the inner sum of a vector Parameters ---------- a: list[] A vector of scalar values Returns ------- scalar The sum of the elements in the vector """ return sum(a)
9fe0d0bc36b08e38fc118f8af05cc7e1fc642fa4
656,736
import types import functools import inspect def _is_unbound_self_method(core_callable): """Inspects a given callable to determine if it's both unbound, and the first argument in it's signature is `self`""" if isinstance(core_callable, types.MethodType): return False if isinstance(core_callable, ...
b403dd8da2d26ce2870a30c51d92322ec3e79dff
656,737
def dummy(t): """ A dummy function of time """ return t**2
2dd257c45068d35fdfa6cec8771352aa79e8fde6
656,739
def extract_epoch(filename): """ Get the epoch from a model save string formatted as name_Epoch:{seed}.pt :param str: Model save name :return: epoch (int) """ if "epoch" not in filename.lower(): return 0 epoch = int(filename.lower().split("epoch_")[-1].replace(".pt", "")) retur...
23be1634bd2350c0b560cf1fb7b59198668b7e02
656,740
import inspect def _default_param(func, param): """ Get the default value from the call signature. """ return inspect.signature(func).parameters[param].default
579b285506c5df900c80fea426f7eb9d275aab5b
656,741
def backends_mapping(custom_backend, private_base_url): """ Create backend with a "/foo" path """ return {"/foo": custom_backend("foo", endpoint=private_base_url("httpbin"))}
02d765d7bc0a66dd2fc657578afa86fe0addb1b9
656,742
def get_loss(name): """Returns loss function by the name.""" try: return globals()[name] except: raise ValueError("Invalid metric function.")
57dcedd1e17e4a390835bdd1e1536e371e2aaf07
656,743
import codecs import numpy def load_word_vectors(file_destination): """ This method loads the word vectors from the supplied file destination. It loads the dictionary of word vectors and prints its size and the vector dimensionality. """ print("Loading pretrained word vectors from", file_destina...
7ba50ad83c82e2abda1e642e3bcd7b94b005b367
656,744
def hello(name): """ (aside) Getting resources from the path. This is good for querying databases: path parameters represent entities (tables in your DB, more or less). """ return "Hello {}".format(name)
c8651b3cc4c025fbddbae05acbb67d501386227e
656,745
import torch def th_accuracy(pad_outputs, pad_targets, ignore_label): """Calculate accuracy. Args: pad_outputs (Tensor): Prediction tensors (B * Lmax, D). pad_targets (LongTensor): Target label tensors (B, Lmax, D). ignore_label (int): Ignore label id. Returns: float: Acc...
7352cfc4300891cca442af265b71cf610e30dead
656,747
def class_survival_rate(passenger_class, titanic_data): """Returns the survival rate of a given passenger_class Your test case must test all the three passenger classes """ count_total = 0 count_survive = 0 for i in range(len(titanic_data)): if int(titanic_data[i]["class"]) == passenger...
2966ae2160d858940ca8077004610e9446acc180
656,748
import os def collect(base_dir): """Collect all files in base_dir.""" collected_dirs = [] collected_files = [] for root, _, files in os.walk(os.path.join(base_dir)): # Make sure directory path ends with '/', do not include './' if root != base_dir: collected_dirs.append(os....
0ef9748d6d7f83a28017d1ed0dfa25e8757148d9
656,749
def reverse(x): """ reverse :param x: :return: """ new_x = 0 if isinstance(x, int): try: new_x = int(str(abs(x))[::-1]) if x < 0: new_x = -new_x if new_x < pow(-2, 31) or new_x > pow(2, 31): new_x = 0 except...
76a38ed863c70e8eb16fed4a458c62b8dba5e752
656,750
def align_bitext_to_ds(bitext, ds): """ Return a subset of bitext that's aligned to ds. """ bitext_dict = dict([(src, (ind, tgt)) for ind, (src, tgt) in enumerate(bitext)]) new_bitext = [] for entry in ds: en_sent = entry[2] ind, tgt_sent = bitext_dict[en_sent] new_bitext...
1e534ac49d607966f72ee660f5b5677f08fa5833
656,751
def _safe_getattr(value, attr, default): """Returns whether this value has the given attribute, ignoring exceptions.""" try: return getattr(value, attr) except Exception: return default
9c520ce2d673f9432c8ed730e88a3c9b12fcc812
656,752
import calendar def get_month_name(month): """gets the month full name from the calendar.""" # print(calendar.month_abbr[month]) # to print the month appreviated name return calendar.month_name[month]
8c88b1c330efa7d278279f463ccb093b7448c5d5
656,753
def filter_sequences(df, lower_bound, upper_bound, grouping_col='hadm_id'): """ Filters sequences so that only those that are between lower_bound and upper_bound remain Parameters ---------- df: object data on which to operate on lower_bound: int lower bound to discard upper_...
72dad7d3b91863d49cddaedc1fe9c582cb0d417d
656,754
import struct def len_unpack(prefix): """network big-endian to int len""" return struct.unpack("!I", prefix)[0]
07e98ff8bad9b7b0f1d6b5cbe089e020138bc28f
656,755
def addRequestBody(target): """ Iterate through all paths and add the request body to post/put commands """ for path in target['paths']: for verb in {'post','put'}: if verb in target['paths'][path].keys(): # remove parameters flag if present target['pa...
d94d31438625ce4035990f5e64f3bfbcd2dd3efc
656,756
import re def lc_basic_calculator(string): """ From https://leetcode.com/problems/basic-calculator Examples: >>> lc_basic_calculator('1 + 1') 2 >>> lc_basic_calculator(' 2-1 + 2 ') 3 >>> lc_basic_calculator('(1+(4+5+2)-3)+(6+8)') 23 >>> lc_basic_calculator('2-(5-6)') 3 ...
ae4387897a99b1f0076a21f9ffbbd3639251e6b9
656,757
def supportScalar(location, support, ot=True): """Returns the scalar multiplier at location, for a master with support. If ot is True, then a peak value of zero for support of an axis means "axis does not participate". That is how OpenType Variation Font technology works. >>> supportScalar({}, {})...
66df5e8325c1e5f94ee745497cb7a3e9500bad5b
656,758
def get_history_score(history): """ Calculate the history score given a list of pass/fail booleans. Lower indices represent the most recent entries. """ if len(history) == 0: return 0.0 score = 1.0 for index, good in enumerate(history): if not good: score -= 0.5 /...
dadd1922251d8fe03191bdbb1a3b66630f52bd2f
656,759
def date_specificity(date_string): """Detect date specificity of Zotero date string. Returns 'ymd', 'ym', or 'y' string. """ length = len(date_string) if length == 10: return 'ymd' elif length == 7: return 'ym' elif length == 4: return 'y' return None
4828146d43b4d3447b0f9ca014722d4d7a9ff015
656,760
def ignore(path, ignores): """ If the full path of a file in pivt is equal to the full path of an element in the ignore list then we return True because we do not want that full path in the list created by walk_root. :param path: Full path to a file in the pivt directory :param ignores: A list ...
ac6b5584c25867759a5c67c267887fb2428ed2ec
656,761
def get_stream_info_string(stream): """ Returns (compact) string with stream information. """ name = stream.name() hostname = stream.hostname() source_id = stream.source_id() uid = stream.uid() return '{}@{}[{}][{}]'.format(name, hostname, source_id, uid)
bd33fe631834b38553a08e28a637c2d3a186d82d
656,762
def implements(implementor, implementee): """ Verifies that the implementor has the same methods and properties as the implementee. __XXX__ classes are excluded. For the purposes of method comparison, arguemtn order is importent. >>> class Implementor(object): ... foo = 1 ... def ...
cf8400d82e9e26d2cf93f5ef27edf789ff591771
656,763
def _clean_scale(scale): """Cleanup a 'scaling' string to be matplotlib compatible. """ scale = scale.lower() if scale.startswith('lin'): scale = 'linear' return scale
5e67783ae6f8b9df704c3b2e7f68dcd3b6c9e47d
656,764
def values(*getters): """Return func extracting values of mulitple getters as tuple. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]) """ return lambda x: tuple(n(x) for n in getters)
29f35080e77f6daece5b341df0cbd36c91e788ae
656,766
import string import random def random_pwd_generator(length, additional_str=''): """Generate random password. Args: length: length of the password additional_str: Optional. Input additonal string that is allowed in the password. Default to '' empty string. Returns:...
5d61022fe7b1a362f4d7a163997129d9c5a4e4bf
656,767
import pkg_resources from pathlib import Path def get_molecfit_config(): """ This is the central place where the location of the molecfit configuration file is defined. """ configpath=Path(pkg_resources.resource_filename('tayph',str(Path('data')/Path( 'molecfit_config.dat')))) return(confi...
91452e8e73bfd9506825817eb275ebb812c61b2c
656,768
def _check_schema_file_content_for_reference_to_json(fs): """ checks file contents fs for .json :param fs: :return: True/False """ """ :param fs: :return: """ seek = u".json" if fs.find(seek) != -1: return False return True
f47cf6e49e1a5203913abd7f6f979a9b21e0476c
656,769
def get_summary_html_name(prj): """ Get the name of the summary HTML file for provided project object :param peppy.Project prj: a project object to compose a summary HTML file name for :return str: name of the summary HTML file """ fname = prj.name if prj.subproject is not None: fna...
132cfa1ec06f0ce6b559ae82ddfb8676b123a0a5
656,770
import asyncio def call_soon_periodic(interval, callback, *args, **kwargs): """Arrange for the `callback` to be called as soon as possible and periodically every `interval` seconds (either an int or float). `interval` is the delay between the end of one invocation of the callback and the start of the...
8b9148b981b08400db27e779fc77850ea7d4a1a4
656,771
def calculate_metrics(array_sure, array_possible, array_hypothesis): """ Calculates precision, recall and alignment error rate as described in "A Systematic Comparison of Various Statistical Alignment Models" (https://www.aclweb.org/anthology/J/J03/J03-1002.pdf) in chapter 5 Args: array_sure: ...
ccbcb76a5d34d79c44cc665849fabaa2ed674fe5
656,772
def selection_sort(arr): """Сортировка выбором по возрастанию O(n^2).""" selected_arr = [] while True: curr_index = None # найти наименьший элемент for el_index in range(len(arr)): if curr_index is None: curr_index = el_index if arr[curr_index...
dea6c61791a2e8b7f822c1ba354d026ecce6c966
656,773
import torch def loss_creator(config): """Constructs the Torch Loss object. Note that optionally, you can pass in a Torch Loss constructor directly into the TorchTrainer (i.e., ``TorchTrainer(loss_creator=nn.BCELoss, ...)``). Args: config: Configuration dictionary passed into ``TorchTrainer`...
a3aa7f8d6b6ac295f6adc883ce86c894134a7366
656,774
def matscalarMul(mat, scalar): """Return matrix * scalar.""" dim = len(mat) return tuple( tuple( mat[i][j] * scalar for j in range(dim) ) for i in range(dim) )
55a64773b3cef94b5edd8237ea4e50a01226d150
656,775
import re def slice(text, length=100, offset = 0, last_word=True): """ Slice a string. """ text = text[offset:] if len(text) <= length or not last_word: return text[:length] return re.sub('(\s+\S+\s*)$', '', text[:length])
49702f1a5161c2865d088cd5d208b247e6943fde
656,776
def get_window(affine, x, y, height): """ Return small window for raster from WGS84 coordinates """ # window = ((y1, y2), (x1, x2)) because rows get read backwards (col, row) = ~affine * (x, y) col, row = int(col), int(row) return ((height - row, height - row + 1), (col, col + 1))
a2100ca0c1d448660a42b7897ce12b24b9935b98
656,777
from typing import OrderedDict def _get_metadata(station): """Helper to get the metadata for a specific station. Args: station (str): Station code. """ metadata_dict = OrderedDict() metadata_dict['station'] = station metadata_dict['time-units'] = 'seconds' metadata_dict['displacem...
4a271a741bd97c17c48b20ec22e266d9ea19d3a5
656,778
def pack_namedtuple_base_class(name: str, index: int) -> str: """Generate a name for a namedtuple proxy base class.""" return "namedtuple_%s_%d" % (name, index)
33950d4c318182247d160ded0849b8c6cdcac50a
656,779
def add_project(conn, project): """ Create a new project into the projects table :param conn: :param project: :return: project id """ sql = ''' INSERT INTO projects(name, begin_date, end_date) VALUES(?,?,?) ''' cur = conn.cursor() cur.execute(sql, project) ...
910ad085316498381f59df0a2004487196696ec0
656,780
def from_file(filename, level="(not set)"): """Load test cases from file, return as list of dicts. Puzzle should be formatted as a string on a single line. See puzzle.latinsquare.from_string. Trailing whitespace is stripped. Args: filename: File to read. One line per puzzle. level: Lab...
94b60fd8f7d99bf541c107b5d4f55118611ad58c
656,781
import os def get_imageId_from_fileName(filename, id_iter): """Get imageID from fileName if fileName is int, else return id_iter.""" filename = os.path.splitext(filename)[0] if filename.isdigit(): return int(filename) return id_iter
dfb6d485782d3a8902658206eb9cc3ceaabe823e
656,782
def get_type(array): """Return type of arrays contained within the dask array chunks.""" try: datatype = type(array._meta) # Check chunk type backing dask array except AttributeError: datatype = type(array) # For all non-dask arrays return datatype
d4ca1bf300bf5a322bc76a9bc1e2c1213d8dcd50
656,783
def extract_tensors(tf_graph): """ Get input, initial state, final state, and probabilities tensor from the graph :param loaded_graph: TensorFlow graph loaded from file :return: Tuple (tensor_input,tensor_initial_state,tensor_final_state, tensor_probs) """ tensor_input = tf_graph.get_tensor_by_n...
8c6974ad723317f758388de3a93584c254c23732
656,784
import argparse def parse_args(args): """ parse command line arguments """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--seed", type=int, help="Random number generator seed for replicability", default=12, ) parser.add_argument("--k-...
b363cb4f93d3ffb8c3c37a68bff4e0bf9d90cbfe
656,785
from typing import Dict from typing import List def get_spot_request_ids_from_response(response: Dict) -> List[str]: """ Return list of all spot request ids from AWS response object (DescribeInstances) """ spot_request_ids = [] for reservation in response['Reservations']: for inst in ...
a6810adaebc033f5dcf57d1a59d3ea7f181dba2b
656,786
from typing import Dict import inspect def get_available_class(module, class_name) -> Dict[str, type]: """Search specified subclasses of the given class in module. :param module: The module name :type module: module :param class_name: the parent class :type class_name: type :return: A dict ma...
4e7a901296a2b75dc9cced045b77cc887c00c627
656,787
def read_csv_file_label(namefile): """ Read csv file that is supposed to be with two columns, one the index, two the label""" label = [] with open(namefile, "r") as f: for line in f: lin = line.replace('\n' ,'') list_lab = lin.split(",") if list_lab[0] != "": ...
8c70634665f5e809e97bee94ab5a9fb7949e565a
656,788
from typing import Any def is_real_float(candidate: Any) -> bool: """ Checks if the given `candidate` is a real `float`. An `integer` will return `False`. Args: candidate (Any): The candidate to test. Returns: bool: Returns `True` if the `candidate` is a real float; otherwise `False....
e5a93a3f082bbdd1f0e386eb678948d8a254f103
656,789
def points_at_corner_index(contour,index): """ contour is array([[[108, 290]],[[111, 290]]], dtype=int32) shape=(number of points,1,dimension(2) ) #index n-2 because the curvature is n-2 (1st and last are not exsistent), this shifts the index (0 splits at first knot!) """ return [contour[i+1] for i ...
e9ffdc1d9f843f2575643c2d41abe8894b1319f8
656,790
def filter_irrelevant_matches(matches, requested_dimensions): """Only return dimensions the user configured""" if requested_dimensions: return [match for match in matches if match["dim"] in requested_dimensions] else: return matches
e436ccffc0931bf7f6582b879d37dd804bdf1787
656,791
import re def email_search(content): """Runs an email search using regex on the passed string""" # Regex searches for standard email format, including "mailto:" if present emails = re.findall(r"(?:mailto:)?\w*[.-]?\w+@\w+[.-]?\w*\.?\w+\.?\w+", content) mailto = [x for x in emails if "mailto:" in x] ...
635c37f82b3ab88ae9223e983fbc7e2aa8a23ec6
656,793
def char_from_number(number): """ Converts number to string by rendering it in base 26 using capital letters as digits """ base = 26 rval = "" if number == 0: rval = 'A' while number != 0: remainder = number % base new_char = chr(ord('A') + remainder) rval = n...
570093a691439d2eed141eeaea982abf8f40b4f9
656,795