content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import OrderedDict def load_status_info(sfile, fudge=None): """ Parse the output of pb_run_status.py, either from a file or more likely from a BASH <() construct - we don't care. It's quasi-YAML format but I'll not use the YAML parser. Also I want to preserve the order. """...
13e6b546d93847b0321da2cb659150345b6a8b20
3,617,754
def calculateSimilarity(img1, img2, similarityType="l2"): """ This method calculates the similarity of two images given the type of similarity function (such as l2 distance). :param img1: np.array :param img2: np.array :param similarityType: str default: "l2" :return: float - distance between th...
7431f6a15e7d4af649efca55f4a99fb057f5dabb
3,617,755
def _is_false(x): """Evaluates false for bool(False) and str("false")/str("False"). The function is vectorized over numpy arrays or pandas Series. Everything that is NA as defined in `is_na()` evaluates to False. but also works for single values.""" x = np.array(x).astype(object) return _is_f...
d5fec5506da6fca9eeb1736dc6b42e5689a7cd3f
3,617,756
def badDebts(_trader: str = None, _start: int = None, _end: int = None) -> []: """ Get bad debts """ with utils.dbInterface() as client: db = client['perp'] criteria = {} if _trader: criteria['trader'] = _trader if _start or _end: criteria['timestamp'] = {} i...
a9d275770acfc1cb6fdb4c06bcfcda37e5fa3be1
3,617,757
from benchbuild.utils import schema def create_run_group(prj): """ Create a new 'run_group' in the database. This creates a new transaction in the database and creates a new run_group within this transaction. Afterwards we return both the transaction as well as the run_group itself. The user is r...
9112e921038df2544c56daf8aa698511bc509555
3,617,758
def get_tags_from_message(message): """ Given a message string, extracts hashtags and returns a comma-separated list :param message: a Hipchat message body """ tags = {word.strip('#') for word in message.split() if word.startswith('#')} return ','.join(tags)
528f7702f43f8f81adf942c79b292f508773d205
3,617,759
def tf_read_img(tf, filename): """Loads a image file as float32 HxWx3 array; tested to work on png and jpg images.""" string = tf.read_file(filename) image = tf.image.decode_image(string, channels=3) image = tf.cast(image, tf.float32) image /= 255 return image
662fc1c9840e67fb0ff3fae4b12da5179e286e25
3,617,762
def remove_outliers(X): """Function to replace "bad" measurements to zero. Inputs: H: Measurement applied field [float, SI units] Hr: Reversal field [float, SI units] M: Measured magnetization [float, SI units] Fk: Index of measured FORC (int) Fj: Index of given measurement within ...
6e759a35de66655eb93d01da71b80a30316b7f2d
3,617,763
def mumps_eigsh(matrix, k, sigma, **kwargs): """Call sla.eigsh with mumps support. Please see scipy.sparse.linalg.eigsh for documentation. """ class LuInv(sla.LinearOperator): def __init__(self, matrix): instance = kwant.linalg.mumps.MUMPSContext() instance.analyze(matr...
bde217f73ba97510eb8d544ba70fbd13f47f78e8
3,617,764
def collect_server_info(host, port): """ Collect general information of server. """ info = {} with pymongo.MongoClient(host, port, connect=True, serverSelectionTimeoutMS=3000) as mc: info['version'] = mc.server_info()['version'] return info
f8dca0057eb9f358a946b53a93098c39b5c8e799
3,617,765
def mean(array): """Return the mean value of the valid elements of an array. Parameters ---------- array : `numpy.ndarray` array of values Returns ------- `float` mean value """ non_nan = e.isfinite(array) return array[non_nan].mean()
baf91db62bc92887ce8055a1c4401ac874cd2014
3,617,766
def _get_boot_list_for_boot_device(node, device, controller_version): """Get the boot list for a given boot device. The DCIM_BootConfigSetting resource represents each boot list (eg. IPL/BIOS, BCV, UEFI, vFlash Partition, One Time Boot). The DCIM_BootSourceSetting resource represents each of the boot l...
a0713051126a6187e8e4e4c30b2331ff3873dd16
3,617,767
def putseconds(secs): """ Create a datestring for format 'dd HH:MM:SS' """ days = int(secs / SECSPERDAY) secs = int(secs - days * SECSPERDAY) hours = int(secs / SECSPERHOUR) secs = int(secs - hours * SECSPERHOUR) minutes = int(secs / SECSPERMINUTE) secs = int(secs - minutes * SECSPERMINU...
28ed6fe7a6fb00b14e9a89a0609819a5947f2f5f
3,617,768
def get_dataloaders(datasets, batch_size, data_type, preprocessor=None, name=None, label_transformer=None, **kwargs): """ Prepare, define and retrieve appropiate data loaders for the dataset partitions. Args: datasets: dict, {key:partition, val:dict of X, y lists} batch_size: int, batch size data_type: st...
d695a0caf9b86cbfa88ec726374019aa00efb1e0
3,617,769
def Gillespie_FRM4X(generics_func, func_param): """ FUNCTION: Gillespie_FRM4X(a{}, b str) a: dictionary containing function's generic values b: XML string file name - Function generic's handler for "Gillespie_FRM4X". """ # Python's variable...
20b40610607b2923877c65fe5fdbbc846a28adf7
3,617,770
def test_1_subject(sess,MR_image,CT_GT,MR_patch_sz,CT_patch_sz,step): """ receives an MR image and returns an estimated CT image of the same size """ matFA=MR_image matSeg=CT_GT dFA=MR_patch_sz dSeg=CT_patch_sz eps=1e-5 [row,col,leng]=matFA.shape margin1=int((dFA[0]-dSeg[0])/2) margin2=int((dFA[1]-dSeg[...
918877392d3d4a69c626a8cc175739d0750c0d46
3,617,771
def jpeg_cmyk_to_rgb(image_bytes, quality=100): """Converts JPEG CMYK image (bytes) to RGB JPEG (bytes).""" runner = _get_runner() image = runner.run(tf.image.decode_jpeg, image_bytes) fn = lambda img: tf.image.encode_jpeg(img, format="rgb", quality=quality) return runner.run(fn, image)
dc09430d20d09bd44d82672ac779b557ee369346
3,617,773
def indices_for_pixel(pix_x, pix_y, x, y): """ Return the indices of the sources for which the coordinates lie in the x, y pixel """ (indxs,) = np.where( np.logical_and.reduce([pix_x > x, pix_x <= x + 1, pix_y > y, pix_y <= y + 1]) ) return indxs
0f8427927bea388e8bb23e0cc615b02ac1821fda
3,617,774
def is_valid_config_entry(opp, logger, origin, destination, region): """Return whether the config entry data is valid.""" origin = resolve_location(opp, logger, origin) destination = resolve_location(opp, logger, destination) try: WazeRouteCalculator(origin, destination, region).calc_all_routes_...
a052e508931cb1538b042c60ec205e54324d068b
3,617,775
import numpy as np # noqa def is_numpy_array(obj: Any) -> bool: # type: ignore """ Checks if the given object is a numpy array Args: obj (Any): The object to check Returns: bool: True if the object is a numpy array otherwise False """ try: except Exception: retu...
f32644e4dd9dfbb2513dc50a85fa3ee79973dfef
3,617,776
from pathlib import Path def construct_storage_path() -> Path: """Construct a Path to draw the standard "storage" flowchart shape.""" # NOTE: After a MOVETO, we need to put the pen down for CLOSEPOLY to # complete a filled shape. _path_data = [ # main shape (Path.MOVETO, [-1.000, -0.80...
5b4c263c9412071b93ef9db395392a8a8db8193d
3,617,778
def create_pb_from_mathtext(text, align='center', weight='heavy', color='b', style='normal'): """ Create a Gdk.Pixbuf from a mathtext string """ global pbmt_cache global dpi if not text in pbmt_cache: parts, fontsize = _handle_customs(text) pbs = [] width = 0 ...
a368e7a2ab1ac543ad511fcea0a7c00a1b70b047
3,617,779
def compare_rrs_types(exp_val, got_val, skip_rrsigs): """sets of RR types in both sections must match""" def rr_ordering_key(rrset): if rrset.covers: return rrset.covers, 1 # RRSIGs go to the end of RRtype list else: return rrset.rdtype, 0 def key_to_text(rrtype, rr...
85bd9f3cffaccaf70ccbb1020ad611fd450dc709
3,617,780
def __do_config_section(parser): """Populate the config section""" # Purge section before adding. parser.remove_section(dtfglobals.CONFIG_SECTION_CONFIG) parser.add_section(dtfglobals.CONFIG_SECTION_CONFIG) # Color is enabled by default parser.set(dtfglobals.CONFIG_SECTION_CONFIG, 'use_color...
90d6d07aefb8057f5c05ab8e8ca61deb0e4febce
3,617,781
def act_gsymbol_reference(context, nodes): """Repetition operators (`*`, `+`, `?`) will create additional productions in the grammar with name generated from original symbol name and suffixes: - `_0` - for `*` - `_1` - for `+` - `_opt` - for `?` Zero or more produces `one or more` productions a...
07ca0e0454b7b6e9b9c127d29afea6faf0f500e5
3,617,782
def is_higher_permission(level1, level2): """ Return True if the level1 is higher than level2 """ return (is_publish_permission(level1) and not is_publish_permission(level2) or (is_edit_permission(level1) and not is_publish_permission(level2) and not is_...
2ec9ee12804c37aeaa64d2fcad9842f05d434760
3,617,783
def vectorize_array(y, steps=1, return_type='df'): """ Take in an array like sequence of values. Vectorize the array and add steps from further in the series to each item. The values in the input array must be of shape [n, 1]. Rows with nan values in the result array will be dropped. If return_...
60be622200aa5000d936d13f3da8a4f7445dfe70
3,617,784
from typing import List from typing import Dict from typing import Callable from typing import Tuple import copy def do_upper_envelope_step( policy: List[np.ndarray], value: List[np.ndarray], *, expected_value: np.ndarray, params: pd.DataFrame, options: Dict[str, int], compute_utility: Cal...
9a9051751bb43211421012ca662c7fe8ef6248e2
3,617,786
def normalize_yaml(path): """Normalize a YAML file, and return whether the file changed.""" data = read_yaml(path) changed = write_yaml(data, path) return changed
f74c1b9a5a59bd728ac86c1aa92a70e182be2809
3,617,787
def rotateQuaternionByRPYInUnrotatedFrame(roll, pitch, yaw, in_quat): """ Apply RPY rotation in the reference frame of the quaternion. Input: geometry_msgs.msg.Quaternion Output: geometry_msgs.msg.Quaternion rotated by roll, pitch, yaw in its frame """ q_in = [in_quat.x, in_quat.y, in_quat.z, i...
55e2f10e9a2af76c590a5a580c898fcfbdb66422
3,617,789
def log_mat(U): """Matrix logarithm, only use for normal matrices, i.e., square matrices U with U * U^T = U^T * UU""" vals, vecs = la.eig(U) vals = np.log(vals) return np.real(np.einsum('...ij,...j,...kj', vecs, vals, vecs))
e73c610e5584a379e7b4eb40ad8085e943a30511
3,617,790
from typing import Optional def date_str_to_datetime(date_str: Optional[str]) -> timezone.datetime: """ Converts a date string to a datetime object. :param date_str: Date string (iso8601) :return: A datetime object. """ if date_str is None: return None return parse_datetime(date_...
70e8fa578a7a713d014f9d2e927abf8b3196c912
3,617,792
def add_field(radar_dest, radar_orig): """ adds the fields from orig radar into dest radar. If they are not in the same grid, interpolates them to dest grid Parameters ---------- radar_dest : radar object the destination radar radar_orig : radar object the radar object conta...
df6e62f2e5fb5bbddad77e037f196e0dbc3c5c97
3,617,793
def _convert_str_to_html(string): """Helper function to insert <br> at line endings etc.""" if not string: return "" lines = string.splitlines() for index, line in enumerate(lines): for char in line: if char == '\t': lines[index] = line.replace(char, "&nbsp;&nbsp;&nbs...
b357d04f28a08f6b65d98ee381dcaef8969f6ff0
3,617,795
def build_icd(cp, instruction): """ Build the integer representation of the input channels to dequeue. :param cp: CoreParameters instance for the target architecture :param instruction: Instruction instance :return: integer representation of icd """ # OR in the literal array of bits. i...
99c1a7799a51ec53136cd7fee4104093921e3f61
3,617,796
def _parseLinks(response, rel): """ Parses an HTTP response's ``Link`` headers of a given relation, according to the Corelight API specification. response (requests.Response): The response to parse the ``Link`` headers out of. rel (str): The link relation type to parse; all other relations are...
73a4f2a7e981b335aa511e5e311ef7290a7695e3
3,617,798
def compute_crop_box(bound_box: dict): """Computes the coordinates to crop an image based on the provided bound_box and the SCALE variable. The input only describes a box around the mask (or area where the mask would be), and the width and height could could be different. The output box will be a square...
66bee6c87b5cb21ed1091f62bab1b9dd940e43d9
3,617,799
def find_min_max(data): """Solution to exercise C-4.9. Write a short recursive Python function that finds the minimum and maximum values in a sequence without using any loops. """ n = len(data) min_val = data[0] max_val = data[0] def recurse_minmax(idx): nonlocal min_val, max_v...
b8f50d1dafa0f66ab61db8d4974c8d201cd4dc3c
3,617,800
def generate_T3_uvh5(name, pt_dec, tstart, ntint, nfint, filelist, params=T3PARAMS, start_offset=None, end_offset=None): """Generates a measurement set from the T3 correlations. Parameters ---------- name : str The name of the measurement set. pt_dec : quantity The pointing declinat...
c0714aa0ec61c8c5762424f8a5d3f3434237c978
3,617,801
import torch from functools import reduce def mask_with_tokens(t, token_ids): """ 用记号遮掩 """ init_no_mask = torch.full_like(t, False, dtype=torch.bool) mask = reduce(lambda acc, el: acc | (t == el), token_ids, init_no_mask) # print("mask",mask) return mask
f233f2e2111e02919ff3795820f024b0e5b850a1
3,617,802
def isStandard(descriptorType): """ >>> isStandard(0x0a) True >>> isStandard(0x22) False >>> isStandard(0x61) False >>> isStandard(0x1a) True """ # See USB Common Class Specification s. 3.11 for this field's structure # Bit 7: reserved # Bits 6..5: descriptor type ...
a4e002e58c07638cb14d1a13a27ac7232af140cf
3,617,803
def split_test(df, test_method='fo', test_size=.2): """ method of splitting data into training data and test data Parameters ---------- df : pd.DataFrame raw data waiting for test set splitting test_method : str, way to split test set 'fo': split by ratio ...
8256a16f3f73f42e06c7b28f34295a39dc8e2091
3,617,804
def store_bot_config(host, content): """Stores a new version of bot_config.py. Returns the ndb.Key of the new stored entity. """ if not _validate_python(content): raise ValueError('Invalid python') # The memcache entry will be cleared out automatically after 60s. Try a best # effort. signature = _get...
2930b24b764e9b931f0c36fa921d6c4c2d1a3772
3,617,805
def equals(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when t...
9a9951ee08251cebfda90d52e4e1e04bb2510a5b
3,617,806
def binary_close(fig, size=5): """ Joins unconnected pixel by dilation and erosion""" selem = disk(size) img = pad(fig.img, size, mode='constant') img = binary_closing(img, selem) img = crop_skimage(img, size) return Figure(img, raw_img=fig.raw_img)
98a4c5393a7010eef7ff7e6f94a08fe359600d08
3,617,807
def build_delete_item(obj): """Build div tag for delete details""" parent = "None" if obj.parent is not None: parent = obj.parent.name return ( "<ul><li>Serial: %s</li><li>Subject: %s</li><li>Parent: %s</li><li>Description: %s</li>" "<li>x509 Extension: %s</li><li>Created: %s</...
f1bb11f2bec57035abea6667a05127d856086b61
3,617,808
def get_user_token(user, purpose, minutes_valid): """Return login token info for given user.""" token = ''.join( dumps([ user.get_username(), get_auth_hash(user, purpose), ]).encode('base64').split('\n') ) return { 'id': get_meteor_id(user), 'token...
a2706da9fe38b10c85815c8a6d2a821e27004b3d
3,617,809
def cell_content_to_str(v): """ Convert the value of a cell to string :param v: Value of a cell :return: """ if v: if isinstance(v, float) or isinstance(v, int): return str(int(v)) else: return str(v).strip() else: return None
b73746d735ed155d387512704b91fc92c0c93560
3,617,811
def create_haar_state(num_qubits: int): """Create a random Haar quantum state Args: num_qubits (int): number of qubits Returns: qiskit.QuantumCircuit """ psi = 2*np.random.rand(2**num_qubits)-1 psi = psi / np.linalg.norm(psi) qc = qiskit.QuantumCircuit(num_qubits, num_qubit...
aa9be2e086f20daaf6597bf726e148fecbf4b9ae
3,617,812
def partition_layers(layers, split=2): """ partitions the each layer of a list according to the layer # and number of elements """ layers_partitioned = [] for i in range(len(layers)): num_parts = split ** i layer_partitioned = partition_list(layers[i], num_parts) layers_partitioned....
be76def26a41488203540b257e1ded0d279bbdb8
3,617,813
def __hamming_distance_with_hash(dhash1, dhash2): """ *Private method* 根据dHash值计算hamming distance :param dhash1: str :param dhash2: str :return: 汉明距离(int) """ difference = (int(dhash1, 16)) ^ (int(dhash2, 16)) return bin(difference).count("1")
c8a28a3f20a037fe9e96bfe82cb522caf6600337
3,617,815
def _van_es_entropy(X, m): """Compute the van Es estimator as described in [6].""" # No equation number, but referred to as HVE_mn. # Typo: there should be a log within the summation. n = X.shape[-1] difference = X[..., m:] - X[..., :-m] term1 = 1/(n-m) * np.sum(np.log((n+1)/m * difference), axi...
90143d9395bf3851a848ac6f0e0349a5131349fb
3,617,816
def insert_coke(message): """Function to add ingested coke. Parameters ---------- message : telebot.types.Message The message object. Returns ------- msg : success or failure message - to be displayed at Telegram's chat. """ message_text = message.text.lower().split(' ') ...
95e97edd600351a1f1e828d01bad17b37cd94263
3,617,817
async def async_browse_media( hass: HomeAssistant, media_content_type: str, media_content_id: str, cast_type: str, ) -> BrowseMedia | None: """Browse media.""" if media_content_type != DOMAIN: return None try: get_url(hass, require_ssl=True, prefer_external=True) except ...
333ee495d5a0be9f3ce1957473aa0f6e5ded09ad
3,617,819
def is_internal_ip(ip): """ 判断是否为内网ip :param ip: :return: """ if ip in ('127.0.0.1', '0.0.0.0', 'localhost'): return True ip = ip_into_int(ip) net_a = ip_into_int('10.255.255.255') >> 24 net_b = ip_into_int('172.31.255.255') >> 20 net_c = ip_into_int('192.168.255.255') >>...
f68ccf10d7aff3f6b0bb853077ddc90489d48420
3,617,820
def part_3b_output_equilb_NVT_started(job): """Check to see if the equilb_NVT (set temperature) gomc simulation is started.""" return gomc_simulation_started(job, equilb_NVT_control_file_name_str)
e86a95a13438c9da4a4214e4e82ee90e22b79dc9
3,617,821
def readAllSopv(sopvFilepath, logger = None): """Return information of all registered scanposes in VOCS.""" sopvs = [] first_line = True with open(sopvFilepath, 'r') as f: for line in f: if first_line: first_line = False continue sopvs.appe...
531e14ad2684b9c4a7afe9164090fe6e3a09c0b1
3,617,822
def _min_to_sec(minutes): """converts minutes to seconds, assuming that input is a number representing minutes""" return minutes*60
dff3330038c7e8cd1abda2c8a0a4433979fedf58
3,617,823
def get_ip(request) -> str: """ 获取当前请求的ip地址 :param request: :return: """ if request.META.get('HTTP_X_FORWARDED_FOR', None): ip = request.META['HTTP_X_FORWARDED_FOR'] else: ip = request.META['REMOTE_ADDR'] return ip
eb084135920231aa176e6099d70ed3954b407070
3,617,824
def aggregate_argmax(z_mean, z_logvar, new_mean, new_log_var, labels, kl_per_point): """Argmax aggregation with adaptive k. The bottom k dimensions in terms of distance are not averaged. K is estimated adaptively by binning the distance into two bins of equal width. Args: z_mean: Mean...
6c262a3b6356ad4a6f5493b1174db3d120f828dd
3,617,825
def get_file_data_old(archivo): """ Separa del nombre del archivo y extrae nombre de Centroide (ctrd) y cultivo (clt) """ diccionario = {} listado = archivo.split('-') diccionario['ctrd'] = listado[0] condicion = 'TS(S2)' in listado[1] or\ 'TS(TC)' in listado[1] or\ ...
4d02b5b77aaf0abfc768c898534493d3723ef54e
3,617,826
def mask_rcnn_loss(mask_outputs, mask_targets, select_class_targets, params): """Computes the mask loss of Mask-RCNN. This function implements the mask loss of Mask-RCNN. As the `mask_outputs` produces `num_classes` masks for each RoI, the reference model expands `mask_targets` to match the shape of `ma...
7cbf78de040fba38d66e0e669ab8fecfea06e3ae
3,617,827
from typing import Optional def get_error_handler( request: web.Request, config: Optional[Config] ) -> Optional[_Handler]: """Find error handler matching current request path if any.""" if not config: return None path = request.rel_url.path for item, handler in config.items(): if ...
a49351ab5479b653f45eff3bc6b069b354615154
3,617,828
def subject_stats_comparison(combined_df): """ Calculates the percentage of subjects with an exclusion and the rate of exclusions per patient. Parameters: combined_df: A DataFrame in the format provided by prepare_for_comparison Returns: A DataFrame with run names as the index and the colu...
ebf3ec1771861565130d926af1b59405ca74e1f9
3,617,829
def flip_randomly_left_right_image_with_annotation(image_tensor, annotation_tensor): """Accepts image tensor and annotation tensor and returns randomly flipped tensors of both. The function performs random flip of image and annotation tensors with probability of 1/2 The flip is performed or not performed fo...
bfad843de51500fb83dd453680983cbc983af8f1
3,617,830
from typing import Dict def dict_squares(n: int) -> Dict[int, int]: """Generates a dictionary with numbers from 0 to n as keys which are mapped to their squares using dictionary comprehension. doctests: >>> dict_squares(2) {0: 0, 1: 1, 2: 4} >>> dict_squares(5) {0: 0, 1: 1, 2: 4, 3: 9,...
4101d0256069c07da6c3d5a8d1e40783a4b26eea
3,617,831
def factor_cartesian(table): """Factor a cartesian products of lists The function unrolls a cartesian product of lists. The table argument is a list of sequences and the output is a tuple of lists Example: >>> factor_cartesian([('a1','b1'),('a1','b2'),('a2','b1'),('a2','b2')])...
8b283944644d89c863e2bc7f5dc3824fa26ca27e
3,617,834
def _palettize_seq(seq): """" seq must be a sequence of 3-d numpy arrays with dtype np.uint8, all with the same depth (i.e. the same length of the third dimension). """ # Call np.unique for each array in seq. Each array is viewed as a # 2-d structured array of colors. depth = seq[0].shape[-...
491831139adf23a13403e68a30ea0b33ec636e21
3,617,836
import mimetypes def _fetch_bundle_contents_blob(uuid, path=''): """ API to download the contents of a bundle or a subpath within a bundle. For directories, this method always returns a tarred and gzipped archive of the directory. For files, if the request has an Accept-Encoding header containin...
d709378344a9a7916bbdb96f2102ddc02f430293
3,617,837
def get_parents(model): """ Return the list of instances refered as "parents" of a given model instance. """ result = list() options = getattr(model, 'RoleOptions', None) if options: parents_list = getattr(options, 'permission_parents', None) if parents_list: for ...
cd8fd84bfc9fc87e9a7374d505b14fb3c1ff6034
3,617,838
import socket def _setDNSCache(): """ DNS缓存 """ def _getaddrinfo(*args, **kwargs): if args in _dnscache: # print str(args) + " in cache" return _dnscache[args] else: # print str(args) + " not in cache" _dnscache[args] = socket._getaddrinfo(*args...
b4d46a204e66113e81bc4ade3768a35edf6d4bba
3,617,839
def create_word2vec(all_questions, embeddings_dim, window, workers, min_count): """ Create the word2vec model""" model = gensim.models.Word2Vec(sentences=all_questions, size=embeddings_dim, window=window, workers= workers, min_count=min_count) # vocab size words = list(model.wv.vocab) print("vocab...
808c42339bb4596427fa4c784cd58d7b89d1a171
3,617,840
import math def velocity_line_trajectory(start, end, velocity, sampling_rate=0.01): """ start and end being n dimentional points, velocity a float value (meter per seconds) and the sampling rate between two points, returns a list of instance of States corresponding to a point going from start...
dabe203380cbcdc4ce3ff82ca7372b99caf4c68e
3,617,841
from .Equal import Equal def isEqual(*, value): """ Check that a numeric value is equal to {value} """ return Equal(value)
fa7c9c26c092a8a2cae1d2ad6a5e4255d93abdaf
3,617,842
def wrap_coro(coro, unpack, *args, **kwargs): """ building a coroutine receiving one argument and call it curried with *args and **kwargs and unpack it (if unpack is set) """ if unpack: async def _coro(value): return await coro(*args, *value, **kwargs) else: async def _co...
2e1916f5f34be5878a3af64ea28b5ffb56f6b350
3,617,843
def rasterizeSourcePositionList(shape, led_pattern, illumination_source_position_list_na=[], objective_numerical_aperture=0.25, objective_magnification=10, syst...
ddde89a347f32d9e3aa3ee1530f041e0bf639e71
3,617,844
from typing import List def list_to_dict(list: List, name_key: str = "name", value_key: str = "value"): """ Returns a key-value pair dictionary with given list of dictionary having `name` and `value` keys or custom keys. """ if not is_list(list): raise AttributeError( "Argument...
81c4b0597b8012b51f9d6cb619948d6afe972c6e
3,617,845
from typing import Tuple def _one_grid_to_points( axes: GridPointsLike, *, dim_domain: int, ) -> Tuple[np.ndarray, Tuple[int, ...]]: """ Convert a list of ndarrays, one per domain dimension, in the points. Returns also the shape containing the information of how each point is formed. ...
ac830c070ff2f456f75ac7f079e7d19987942bc8
3,617,846
def mAP(results, k=200, AP=True): """ Arguments : results = related images list for sorted file list k = mAP@k AP = whether return AP list for each images return : mAP value """ aps = [] for truth, result in enumerate(results): result = result[:k] ...
17da5fc85fdee24e24771e785298dfc71e2948a5
3,617,847
from typing import Any import typing def hint_is_specialized(hint: Any, target: Any) -> bool: """Checks if a type hint is a specialized version of target. E.g., hint_is_specialized(ClassVar[int], ClassVar) is True. isinstance will invoke type-checking, which this methods sidesteps. Behavior is undef...
b651fc05290de82ab5a5833d10ca68d6a96f2d7a
3,617,848
from typing import Dict from typing import Union def compute_selection_criteria( blast: Dict[str, Union[int, float]] ) -> Dict[str, Union[int, float]]: """Calculate a series of parameters used to discriminate which entries should be kept to search for a core genome from a series of blast files (*....
cc12be84aad55de090b0e6ba26eaeb5c77706073
3,617,849
def build_spc_queue(rxn_lst): """ Build spc queue from the reaction lst for the drivers :return spc_queue: all the species and corresponding models in rxn :rtype: list[(species, model),...] """ if 'all' in rxn_lst: # First check if rxn_lst is a bunch of species spc_queue = r...
0dbe4e2bc3db16dc5dc83a55f0f802d4dfae853f
3,617,851
def patch_telomeres(bands_by_chr): """Account for special case with Drosophila melanogaster """ for chr in bands_by_chr: first_band = bands_by_chr[chr][0] start = first_band[1] if start != '1': stop = str(int(start) - 1) pter_band = ['pter', '1', stop, '1', st...
23057227c526bb3837fd0c02233ddac4671c6956
3,617,852
import scipy.cluster as spcluster def cluster_sites(mol, tol, give_only_index=False): """ Cluster sites based on distance and species type. Args: mol (Molecule): Molecule **with origin at center of mass**. tol (float): Tolerance to use. Returns: (origin_site, clustered_sites)...
37c913a484c29420fefb72c41cf9f71b2bd8cbb3
3,617,853
def get_comment_notification_targets(comment): """ Gets a list of comments that should get a notification about this new comment :param PostComment|AnswerComment comment: :param set user_ids: set of user_ids to exclude :return: returns a tuple, first item is comments to notify, sec...
d2b0ff99705117b7642366d7080a3a29c48dc22a
3,617,854
def build_model(params: dict, build_options: dict = None) -> CompartmentalModel: """ Build the compartmental model from the provided parameters. """ params = Parameters(**params) # Get country/region details country = params.country pop = params.population # Create the model object ...
7738f8e31536822a50856186ffff38c70d807ca6
3,617,855
import six def gen_spewer_method(name, args): """Generates spewer code for a single opcode.""" method_name = "spew" + name # Generate code like this: # # void spewGuardShape(CacheIRReader& reader) { # spewOp(CacheOp::GuardShape); # spewOperandId("objId", reader.objOperandId()); ...
a8e546df4a9cfd0562611d8f456f8e109c331062
3,617,856
from typing import Optional def cir_LRsRQRQ(w, Rs, L, R1: Optional[float] = None, Q1: Optional[float] = None, n1: Optional[float] = None, fs1: Optional[float] = None, R2: Optional[float] = None, Q2: Optional[float] = None, n2: Optional[float] = N...
596951396a68140347cf06844041fcdf87a46974
3,617,857
from typing import List def smallest_positive_integer_not_in_array(arr: List[int]) -> int: """ [1..N] can cover everything from 1 to (N * (N+1) / 2) """ res = 1 for num in arr: if num > res: return res else: res += num return res
9d01e051c278beab40aefa6618a4a5f4934e451a
3,617,858
def module_enclosing_func(offset): """ Test function to see if module-level enclosures are detected """ def module_closure_func(self): """ Actual closure function, should be reported as: putil.tests.my_module.module_enclosing_func.module_closure_func """ self._exobj.add_e...
399212d5cc04479639cdb5cacb50b167327f2445
3,617,859
def out_of_bounds_replace(llhs, params, out_of_bounds): """ replace out of bounds llh evals with large, valid values""" llhs[out_of_bounds(params)] = NAN_REPLACE_VAL return llhs
d774ba545cdd8ac99932966495f581a2436c8aab
3,617,860
import numpy def fourier_sum ( func , N , xmin , xmax , fejer = False ) : """Make a function/histiogram representation in terms of Fourier series >>> func = lambda x : x * x >>> fsum = fourier_sum ( func , 4 , -1 , 1 ) >>> print fsum >>> x = ... >>> print 'FUN(%s) = %s ' % ( x , fsum ( x ) ) ...
566a1640fa1d3bc4c69658bce7e5847fe1103edf
3,617,861
def get_retrieval_model(params): """ This method returns the Retrieval class requested in the parameter dict. Args: params(dict): A dict of parameters. In this method, the parameters 'logger' and 'query_generation', and 'search_engine' are required. Based on the requested retrievel model, so...
f90596d7bd280a6a000e59b6fe05d05afbdc957c
3,617,862
def trigrams(docs): """create trigrams""" return [trigram_model[bigram_model[doc]] for doc in docs]
c5ecd514e233858abc875fc3a8026a1b0494fd9f
3,617,863
import nilearn.image as niimg def concat_imgs(in_files, out_file=None): """ Use nilearn.image.concat_imgs to concat images of up to 4 dimensions. Returns ------- out_file: str The absolute path to the output file. """ return niimg.concat_imgs(in_files)
04b5e376b3d20623ed66e08ffe704875568cebbc
3,617,864
def conv_2d(in_nodes, nb_filter, filter_size, strides=1, padding='same', activation='relu', bias=True, weights_init='truncated_normal', bias_init='truncated_normal', regularizer=None, weight_decay=0.001, trainable=True, restore=True, reuse=False, name="conv_2d"): """ ...
73b8e104cf398e0d34b77c36c1d53a083c2b52df
3,617,865
def tensor_repr(fra_data, dtype=None): """Creates a tensor representation of the FRA.""" dtype = dtype or tf.float64 res = dict() res["fixing_date"] = tf.convert_to_tensor( fra_data["fixing_date"], dtype=tf.int32) res["fixed_rate"] = tf.convert_to_tensor( fra_data["fixed_rate"], dtype=dtype) con...
415c6b40e17015d074a0cdb387184468b26a2143
3,617,867
def find_section_clamping_values(zlevel, lowerfract, upperfract): """Find int8 values that correspond to lowerfract & upperfract of zlevel histogram From igneous (https://github.com/seung-lab/igneous/blob/master/igneous/tasks/tasks.py#L547) """ filtered = np.copy(zlevel) # remove pure black fr...
fc0ebcbca1f10d2028d2ddd829092532544c44d9
3,617,868
def get_levels(content, language=None): """ Returns a list of integers whose value is for the content of the same index. :param content: Either a list of strings, or a list of dictionaries that contain 'content' and 'language' keys. :param language: Optional, only needed if only passing in a list of str...
f38acf80394c95ca395a1fd1dc755b1338275ad0
3,617,869
import logging def losses(args): """Set up ``losses`` dict which stores model losses per epoch as well as evaluation metrics""" losses = {} keys = ["D", "Dr", "Df", "G"] if args.gp: keys.append("gp") eval_keys = ["w1p", "w1m", "w1efp", "fpnd", "coverage", "mmd"] if not args.fpnd: ...
b4da1c280968c510b59d598d699c331194196100
3,617,870