content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import json def get_service_set(schema_path: str) -> set: """ Get the set of all services present in a schema. Args: schema_path: schema file path Returns: service_set: set of services in file """ service_set = set() with open(schema_path, encoding="UTF-8") as f: sc...
8e0d51f2af7133ba92451c3fa1d4f9cd4cb4a997
609,961
def _read_image_ids(image_ids_path): """ Private function to read image ids from a csv file. Args: image_ids_path (str): Path to a file containing image ids Return: list of image ids """ return list(map(str.strip, open(image_ids_path, "r").readlines()))
8b46aa367d2969c464e888de691404f0239c1901
609,963
def get_namespace_as_kwargs(namespace): """Create keyword arguments using the provided namespace. If it is None, then return empty keywords arguments. Mostly for the case of having namespaced or non-namespaced resources in the same function or method. Args: namespace (str): the given names...
3785911140fd3d3cc9b2616a6cdcca9842594b93
609,964
def tostring(barray): """Convert a byte array to string in utf-8 noop if already a string.""" if isinstance(barray, str): return barray if isinstance(barray, bytes): # return str(barray, 'utf-8', errors='replace') # Python 3 return barray.decode(encoding="utf=8", errors="replace")
91b45a715184653499ae5054d6e9d1e1a8563d85
609,965
import torch def linlogcut_torch(x, a=10, b=100): """ Function which is linear until a, logarithmic until b and then constant. y = x x <= a y = a + log(x-a) a < x < b y = a + log(b-a) b < x """ # cutoff x after b - this should also cutoff infinities x = torch.where(x <...
5cfa432070748f1f0065b5bd899e6213d82247a9
609,967
def file_to_string(sql_path): """Converts a SQL file holding a SQL query to a string. Args: sql_path: String containing a file path Returns: String representation of a file's contents """ with open(sql_path, 'r') as sql_file: return sql_file.read()
f63542f756ac85efdb1ec82ec9ed4f629e548fee
609,970
import re def str_to_list(word, dl=','): """Converts a string to a list for the given delimiter.""" regexp = re.compile(r'['+dl+']') if regexp.search(word): x = word.split(',') x = [i.strip() for i in x if i.strip() ] else: x = [word] return x
dde93dd68bd6c0fda218d588df281456e8d4b62e
609,972
import socket def _can_resolve(host: str) -> bool: """Returns True if the system can resolve host to an address.""" try: socket.getaddrinfo(host, None, socket.AF_UNSPEC) return True except socket.gaierror: return False
a20a5eee9d2a52e686779cb643c86f54a78e2e32
609,974
def eval_files(prec: str = "50") -> list: """Obtain a list of pre-processed dataset file patterns for evaluation. Args: prec (str, optional): The percentage here should match with train_files. Returns: list: The TFRecord file patterns for evaluation during training. """ return ["gs...
8a45dca8c7439e95cb2a024a2784408bec9db4f7
609,977
import re def try_option(line): """Parses the line as an option, returning the key/value pair.""" data = re.split('=>?', line, 1) # should split in two (key/val), but either way use first two elements return data[0].rstrip(), data[1].lstrip()
022c3585f6776b23b1ff183e703a949586a758ab
609,979
def get_gate_colour(op_type: str) -> str: """Get ZX-colour of the gate""" if op_type in {"H"}: return "h" if op_type in { "X", "Rx", "V", "Vdg", "S", "Sdg", "SX", "SXdg", "XXPhase", "PhasedX", "XXPhase3", }: ...
25bb8654b60fd708a1e8ea9b93dfafede7116c6d
609,980
def kBtu_h2MBtu_h(x): """kBtu/h -> MBtu/h""" return 1.e-3*x
7e36739f02db31014b456cfc563fd4fc8ac934a3
609,982
from pathlib import Path import hashlib def hash_file(file: Path) -> str: """Compute the hash (SHA256) of a file in text mode. Args: file: File to be hashed. Returns: Hash. """ with open(file, encoding="utf-8") as f: sha256 = hashlib.sha256(f.read().encode("utf-8")) ...
ef01f8932d21b3fd5672b377b03e0a21ee4185cb
609,984
def _make_isotope_string(element_name, isotope_num): """Form a string label for an isotope.""" if isotope_num == 0: return element_name else: return '%s[%d]' % (element_name, isotope_num)
b1bddb64dd4c2737a994a3144f09aef4fea0b9db
609,985
def kf_2nd_derivative_wrt_density(kf, n): """Computes the second derivative of kf with respect to density It is given by `-2 kf / (9 n**2)` Parameters ---------- kf : array-like The fermi momentum in fm^-1 n : array-like The density in fm^-3 Returns ------- d^2(kf)...
aa3f84904a8f7039a3792d81584e05d037bc987c
609,990
import re def stripped(text): """ Removes all whitespace from a string """ return re.sub(r'\s+', '', text)
7e0fa53b64d6ccfb4deb6e2ac70affa7aea46ae8
609,996
def _print_parameter_name_and_type(p_name, p_type): """ Print parameter name and type following Numpy docstring standard. If `p_name` is an empty string, then return an empty string. Parameters ---------- p_name: str Parameter name p_type: str Parameter type """ s = ...
87498fa026a713f8ee7d062c33d3ed0bf950bab8
609,997
def generateSQLString(columns, format, start): """ Generates an SQL string from two vectors that describe the name of the column and the format. Can be used to assist when generating a string to create a new table. """ start += '(' for a, b in zip(columns, format): start += '%s %s, ' % ...
44125a7e705901df1a3af1465d23c12e16d22bb8
610,002
def extract_content_type_encoding(content_type_string): """ Extract the content type and encoding information. """ charset = "" content_type = "" for part in content_type_string.split(";"): part = part.strip().lower() if part.startswith("charset"): charset = part.spli...
d24c4eb4bc7db3a8d058a12a5bb8df832b6055d5
610,005
def dot_product(a,b): """calculate dot product from two lists""" # optimized for PyPy (much faster than enumerate/map) s = 0 i = 0 for x in a: s += x * b[i] i += 1 return s
077a7e1fc97a344d68fd5509191c989e23f626b2
610,009
def l2_regularization(W, reg_strength): """ Computes L2 regularization loss on weights and its gradient Arguments: W, np array - weights reg_strength - float value Returns: loss, single value - l2 regularization loss gradient, np.array same shape as W - gradient of weight by l2 l...
8d7e168da70a0b4e051e56ce7747980854029a73
610,019
import codecs def read_string_from_file(path, encoding="utf8"): """ Read entire contents of file into a string. """ with codecs.open(path, "rb", encoding=encoding) as f: value = f.read() return value
27be4c91c2efc628e455327f8abb2fa0c65bfc9a
610,020
def filter_devices(ads, func): """Finds the AndroidDevice instances from a list that match certain conditions. Args: ads: A list of AndroidDevice instances. func: A function that takes an AndroidDevice object and returns True if the device satisfies the filter condition. Re...
3ec4b214e3b2f3129c7466de6806a4a778df0321
610,021
import re def number_2int(kv_format, str_value): """ kv_format for number is usually something like this: dddd d,ddd d.ddd So converting to an integer means just remove from string non-numeric characters and cast remaining str to integer. """ if str_value: lin...
f162a45ee4f92243b2dcd84f1364638f9a4c56a0
610,024
from typing import List from typing import Any def flatten(list_: List[Any]) -> List[Any]: """Flattens a nested list of tag predictions.""" result = [] for sub in list_: if sub and isinstance(sub, list) and isinstance(sub[0], list): result.extend(flatten(sub)) elif isinstance(...
109d434bc71499a2ab060a728f9fe2d8599595da
610,026
from typing import Dict from typing import Any def change_dict_keys(new_names_dict: Dict[str, str], output_dict: Dict[str, Any]) -> Dict[str, Any]: """ Takes a dictionary and changes the names of the keys Args: new_names_dict: a dictionary with the old names as keys and their new names as their va...
be7e9d430e75851626703674acf148885545819a
610,031
def shift_pos(pos, label_shift): """shift a pos by (sx, xy) pixels""" shiftx = label_shift[0] shifty = label_shift[1] pos2 = pos.copy() for key, position in pos2.items(): pos2[key] = ( position[0] + shiftx, position[1] + shifty) return pos2
aac523a5efb1bc81df1b4f8e6cf094cf5bdd5221
610,035
def sum_function(values): """Sum the values in a list. Args: values (list): List of numbers Returns: int: Sum of values """ result = 0 for i in values: result += i return result
5efc5f1110b10c8cb8dd446b59c237484806dc61
610,036
import re def tmd_positions_match_fasta(s): """ calculate the tmd start and end positions in the protein sequence, the input tmd sequence will be matched with the full protein sequence. :param s: set the input tm sequence, and the full protein sequence :return: tmd start and end positions in the ful...
15be95f2e1e7e4d45e48cce7168f207314345d0b
610,037
import string import re def cleanup_str_for_k8s(value: str): """ Clean up string so that it is kubernetes-compatible: remove special chars (except "-"), and convert all text to lower-case. Args: value (str): The string to clean up Returns: str: The kubernetes-compatible string ...
44b658ca58803f4e5c0e8af515281ef1b97284bc
610,038
def num_channels(I): """number of channels in the image""" return I.shape[2]
12f485391dff5386225ad13905e6292fc9f0bda1
610,039
def cardinal_direction(b): """ Calculate the cardinal direction for a given bearing. Ex: 0 is 'North Args: b: bearing (in degrees) Returns: A string representing cardinal direction """ dirs = ["North", "North-East", "East", "South-East", "South", "South-West", "West", ...
3b30bde51e0a478b4011ed93cd51c48df2194ce5
610,046
def find_path_to_assignment(test_file_location): """ Takes a testfiles location and calculates the path to the assignment, given that it has .dbwebb has the same structure as the me folder. """ FILE_DIR_LIST = test_file_location.split("/") FILE_DIR_LEN = len(FILE_DIR_LIST) - 1 FOLDERS_TO_BAC...
3498bafb12a60cdc0220fedc1d5bee491731f162
610,047
def factorial(n): """Calculate the factorial of an integer number""" assert n >= 0 and int(n) == n,'Number must be positive integers only' if n in [0,1]: return 1 else: return n * factorial(n-1)
8cbc6b5a420d4485af9ebda42fffbb8a88f3db30
610,049
def pixel_count(image): """ Return the number of pixels in the input image. """ width, height = image.size return width * height
d48daedf58d21f77a5096a40870f5aa47cb861ec
610,059
def get_speakers(items): """Returns a sorted, unique list of speakers in a given dataset.""" speakers = {e[2] for e in items} return sorted(speakers)
451c10463a34f40839bec6cf8b017dfa4018b342
610,064
def pytest_ignore_collect(path): """Hook to ignore symlink files and directories.""" return path.islink()
da9e9643f26b4ff011209b5fa8edc44673860686
610,069
def is_st(stock): """Check whether it is ST.""" return 'ST' in stock.get('name')
45e9e7c6235d4ef2055b3b5cb56a96b7ec03fa9e
610,072
def _beautify_message(msg): """ Function for cleaning the received message. Removes everything not allowed by the specification, adds some required fields and renames some to follow the specification. :param msg: Received message as dictionary :return: Cleaned message. """ msg["type"] = "...
0dfeb2d80308d04e0a4e951db113412298624207
610,073
def _dt_from_unit(unit): """Infers the timestep based on the unit. Arguments: unit {string} -- The unit (yr, kyr, Myr, Gyr) under consideration. Raises: AssertionError -- on malformed input. """ assert unit in ['yr', 'kyr', 'Myr', 'Gyr'] return {'yr': 1e0, 'kyr':...
e85c1bf5e1d6f21a86e669a88f696253513144f0
610,074
def compare_polys(poly_a, poly_b): """Compares two polygons via IoU. Input: poly_a: A Shapely polygon. poly_b: Another Shapely polygon. Returns: The IoU between these two polygons. """ intersection = poly_a.intersection(poly_b).area union = poly_a.union(poly_b).area ...
86e50bee10291b5363838a29bdef86dad6605235
610,077
def get_english_chapter_count(book): """ A helper function to return the number of chapters in a given book in the English version of the Bible. :param book: Name of the book :type book: str :return: Number of chapters in the book. 0 usually means an invalid book or unsupported translation. :rt...
e1ee5cb200550d9d34e1753968fb46c332d2c68d
610,078
def _get_compute_id(local_ips, id_to_node_ips): """ Compute the instance ID of the local machine. Expectation is that our local IPs intersect with one (only) of the remote nodes' sets of IPs. :param set local_ips: The local machine's IPs. :param id_to_node_ips: Mapping from instance IDs to set...
0a4542d0d38baa182dfb33eda59dec91c7f9112f
610,080
import math def _angular_velocity_from_cog( cog_speed: float, length_rear_axle_to_cog: float, beta: float, steering_angle: float ) -> float: """ Computes the angular velocity using the Bicycle kinematic model using COG data. :param cog_speed: [m/s] Magnitude of velocity vector at COG :param length...
bc936e556507bb8422df20c1da8b100a9053824e
610,081
from typing import Dict def read_fasta(fname: str) -> Dict[str, str]: """Read fa file, returning a dict of seq names to seqs""" retval = {} curr_key, curr_seq = "", "" with open(fname) as source: for line in source: line = line.strip() if line.startswith(">"): ...
d92b6ed707b7f4dcbd3e8ecd616a191bf24afd2b
610,082
def text_content(seconds): """ Returns text content containing game stats to be sent to user Parameters: seconds (int): the amount of time played """ content = "Thank you so much for playing Champions are Coming. In total, you have been playing for " + str(seconds) + " seconds. Play again ...
dd59c156f54d295423653b0159d5388d5c5faf91
610,085
def recalc_level(level, exp, exp_change): """ Recalculate level and EXP after exp_change. """ exp += exp_change if exp >= 0: required = 1000 * (level + 1) while exp >= required: level += 1 exp -= required required += 1000 else: while exp < 0 a...
06cd1cb4bd52d5b1aa8abf58b31aecddf4bc3c47
610,089
def changed_keys(a, b): """Compares two dictionaries and returns list of keys where values are different""" # Note! This function disregards keys that don't appear in both dictionaries keys = [] if a is not None and b is not None: for k, _ in b.items(): if k in a and a[k] != b[k]: ...
4cc1b0e244996de482baada9cb29f53c590f99a7
610,093
def and_field_filters(field_name, field_values): """AND filter returns documents that contain fields matching all of the values. Returns a list of "term" filters: one for each of the filter values. """ return [ { "term": { field_name: value, } } ...
60c899fe1c252b47d29067a45d1d548c84556f03
610,094
from datetime import datetime def checkDate(field_name, date_format): """Check if field name is a coorect date string Parameters ---------- field_name : string the name of the field. date_format : string Date format to validate the field_name. """ try: data = dateti...
daeab57026f32d372665a49e77bb1e39949ca81b
610,099
def sum_cells(grid_type, max_level_refinement): """ collect all cells of one type in a list """ sum_cells = [] for i in range(max_level_refinement): sum_cells += grid_type[i] return sum_cells
34865a99cdccc6bb2c435eb1a53a6ddbed0aa67e
610,100
import logging def classify_columns(df): """ helper function to label each of the dataframes columns as categorical or numerical based on the data types input: df: pandas dataframe output: all_cols: list of all the dataframe columns categorical_co...
1d5b0f40e924dad135b812622ddc08f871b77b88
610,102
def pentagonal(i): """Pentagonal number.""" return i * (3 * i - 1) // 2
4f1cac6e4b1544c4a8dd932115ad35200771cb2d
610,103
def collectInfo(check, contents): """ If the contents come from an extension of the congressional record, this function will collect the information of the speech's speaker :param check: int indicating the first spot to check for the speaker in contents :param contents: String containing the speech...
c9efa27afdbb00080cc1a279531a607d0ecd77a3
610,106
def dirs(obj, st='', caseSensitive=False): """ I very often want to do a search on the results of dir(), so do that more cleanly here :param obj: the object to be dir'd :param st: the strig to search :param caseSensitive: If False, compares .lower() for all, else doesn't :return: The results...
35a4ec780cf99396cbdb57c8f21633b8242b3764
610,109
from typing import Dict def compactness(r: Dict[str, float]) -> float: """Check how compact a component is. Higher = less compact.""" aa = 10.0 bb = 1.3 s = r['Component S (Franzen)'] if r['Component S (Franzen)'] != 0.0 else r['Component Sp (Franzen)'] ssp = s / r['Component Sp (Franzen)'] aa...
227dfed4fc4c8bff8feea6780665221c890b8672
610,112
def get_qualified_types(qualifier_types): """We want all qualifiers to point to non qualifier types. There are sometimes e.g. 'const restrict int' types. We want the 'const' type point to 'int', not 'restrict'. Returns dictionary {qualifier_type: modified_non_qualifier_type}. """ non_qualifier_...
ef189eec4d352ac016dc10a883198225ddefa2a9
610,114
def posts_for_request(board): """Get all posts from the board in reverse order""" return list(board.get_all_posts(old=False))[::-1]
1526fd7ff20ff8579a6040d11b8c23d2da2411ef
610,116
def _flag_to_arg(flag: str) -> str: """ Splits a flag that looks like --model-version-id into an argument that looks like model_version_id. Parameters ---------- flag The flag string to split Returns ------- An argument name """ arg = flag.split('--')[1].split('-') ...
1c9db59b3fbe569e13c06fcb73094f69bb9f9243
610,118
def run_import(client, model_name, inventory_index_id, background): """Runs the import against an inventory. Args: client (object): Api client to use. model_name (str): Model name to create. inventory_index_id (int64): Inventory index to source. background (bool): If the import ...
1734973143bf6fcdc02968a1ec024de24dbb24c8
610,119
def identity(value): """Identity transformation. Returns itself Note ---- This function doesn't actually apply any transformation. It is used for arbitrary function calls that apply transformations, and this is called when no transformation is to be applied Parameters ---------- value ...
ff59261d2fc930b876e1be4ef9242ad88a7efde7
610,120
def translate_cat_TLG(cat: dict) -> str: """ Print an abstract representation of a CG category in the ABC Treebank format. Parameters ---------- cat : dict An abstract representation of a CG category. Returns ------- res : str A string representation in the ABC Tree...
5959e63e81dabaf9da6d13018fb61b0330fe2b11
610,124
from typing import List from typing import Optional from typing import Match import re def _get_passing_test_num_from_stdout(stdout: str) -> str: """ Get a passing tests number from the stdout. Parameters ---------- stdout : str Test command stdout. Returns ------- passing_te...
8523d4d5979a9359cb330cb19858a57605ff5ccb
610,126
def get_key(iam, user): """ Return all the access keys of the given user """ keys = [] paginator = iam.get_paginator('list_access_keys') for access_key in paginator.paginate(UserName=user['UserName']): for key in access_key['AccessKeyMetadata']: keys.append(key) return ke...
c79d856582bb7b513e66b0517220b2bd4ea9ec0f
610,129
import re def check_segmentation(prefix, lines, contains): """Check that the output consists of the neat repetition of (contents)""" reg = re.compile(r"^" + prefix + r"\(\d+, \d+\): \[(.*)\]$") allOutput = "" for _, line in enumerate(lines): result = reg.match(line) if result: ...
562847009a3c52ad6dffc377d5b54a2b050bc07e
610,131
def duration(s): """Turn a duration in seconds into a human readable string""" m, s = divmod(s, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) parts = [] if d: parts.append('%dd' % d) if h: parts.append('%dh' % h) if m: parts.append('%dm' % m) if s: pa...
670ca369ebb810a9ded2992dcb7b1a3a8663b05f
610,136
def getTrainingLabels(train): """Slices the SalePrice column from the dataset Parameters: train (pd.Dataset): Training set Returns: train.SalePrice.values (pd.Dataset): Single column SalePrice """ return train.SalePrice.values
50bc83dfbdf253e34bb4a2fe71c3ec85534af6c8
610,155
import gzip def _OpenMaybeGz(path): """Calls `gzip.open()` if |path| ends in ".gz", otherwise calls `open()`.""" if path.endswith('.gz'): return gzip.open(path, 'rb') return open(path, 'rb')
0da80c690a108b7f5c71178b6ad9e37a21f97036
610,156
import requests def UploadImageAsset(client, url): """Uploads the image from the specified url. Args: client: An AdWordsClient instance. url: The image URL. Returns: The ID of the uploaded image. """ # Initialize appropriate service. asset_service = client.GetService('AssetService', version=...
4eb9d27100d56356f57620876563fba00ebef146
610,157
def column_is_primary_key(column): """Returns whether a column object is marked as a primary key.""" primary_key = column["is primary key"] if isinstance(primary_key, str): primary_key = primary_key.lower() if primary_key in {"y", "n", "yes", "no", "-"}: primary_key = primary_key...
0d6a6d175292f80bc32e54fc3a57de972923f34f
610,159
def _hasPackage(release_packages, releaseName, newpkg): """ Determine if a given package has already been added to the packages dictionary for a specified release. """ for pkg in release_packages[releaseName]: if (pkg.port == newpkg.port): return True return False
bf7c2475a61eee4745ce44555dd1aab1c037a3b3
610,163
from typing import Any def parse_bool_field(value: Any, default_value: bool) -> bool: """Convert a bool or string value to a bool. Arguments: value: any -- The value to convert to a bool. deafult_value: bool -- The value to use if the conversation cannot be done. Returns: The val...
41a1bba6a603f0ba326c803bd69a477da75e1e08
610,165
def lazy_set_default(dct, key, lazy_val_func, *args, **kwargs): """ A variant of dict.set_default that requires a function instead of a value. >>> d = dict() >>> lazy_set_default(d, 'a', lambda val: val**2, 5) 25 >>> lazy_set_default(d, 'a', lambda val: val**3, 6) 25 >>> d {'a': 25}...
ddce4dd72c18f588b65065d3784533cca7dad095
610,166
def get_memory_monitor_summary_filename(selector=None): """ Return the name for the memory monitor summary file. :param selector: special conditions flag (boolean). :return: File name (string). """ name = "memory_monitor_summary.json" if selector: name += '_snapshot' return na...
aeb43e1b0516c38ab37c3a5020912dacf0dfba66
610,167
def EscapeMakeVariableExpansion(s): """Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.""" return s.replace('$', '$$')
944be8c613ad533d3d89762a224e8dcc619be166
610,168
def get_lbs_for_center_crop(crop_size, data_shape): """ Fetches the lower bounds for central cropping. Args: crop_size: (height, width) data_shape: (x ,y, c) """ lbs = [] for i in range(len(data_shape)-1): lbs.append((data_shape[i] - crop_size[i]) // 2) return lbs
630fb549bc7d619bd617e891a9e53426e18172a6
610,169
def EuclidianPO(x, k, norm_X): """ Proximal operator for Euclidian norm. It returns: prox_k(x) = (1 - k/max(k, \|X\|_2))x """ if norm_X<=k: out = 0.0 else: out = (1 - k/norm_X) * x return out
90e11e0c91e0e7bcc6dcc8a09e7e04f0c27aacbc
610,171
def check_admin_access(api_client): """ Check and return true if api_client is configured with babylon admin access. Access is determined by whether the user can directly manage AnarchySubjects. """ (data, status, headers) = api_client.call_api( '/apis/authorization.k8s.io/v1/selfsubjectacce...
b7f7a36c321a1811663015af63d67bb0c536e1cf
610,176
def shake_shake_eval(xa, xb): """Shake-shake regularization in testing mode. Args: xa: Input, branch A. xb: Input, branch B. Returns: Mix of input branches. """ # Blend between inputs A and B 50%-50%. return (xa + xb) * 0.5
68eca94d4bf8ea75427297b0324dac9cf7eb10c4
610,177
def email_associated(env, email): """Returns whether an authenticated user account with that email address exists. """ with env.db_query as db: cursor = db.cursor() cursor.execute(""" SELECT value FROM session_attribute WHERE authenticated=1 AND nam...
b3d13d518129b092c6fee2caa3c7813975f9811a
610,180
import csv def get_filters(filepath): """Extract the filters from the file with description of filters in ENA as a dictionary with the key being the filter id and the value a dictionary with related results, type of filter, filter description filepath: path with csv with filter description """ ...
d73e01e3f9c6afa0f5439ac6ff8cd0e5c1316a27
610,183
def calculate_image_size(size, target_size): """ Returns the size of the image after resizing. The same code is used in PIL.Image.thumbnail The results of this function is used by JavaScript in resize effect while changing image. """ x, y = size # if the width is greater than the target ...
c766858852810f3d9dd048264abeeeac5d0fe763
610,184
def atom_total_degree(atom): """The degree of an atom including Hs. See Also -------- atom_degree Returns ------- list List containing one int only. """ return [atom.GetTotalDegree()]
fbff267a8dc80f3e8cc8054b168a4887768596e4
610,187
def has_ret(bb): """ @param bb List of PseudoInstructions of one basic block @return True if ret instruction is part of basic block, False otherwise """ return (lambda bb: True if 'ret_T' in map(lambda inst: inst.inst_type, bb) else False)(bb)
df6d4e8d2e934ffb4308d44d73d0aae26a034b4a
610,190
def get_list(item): """ Return instance as a list. """ return item if isinstance(item, list) else [item]
7897baa032ad0026798e142cfb8f58fbc4425c51
610,191
def on(*keys): """Decorator for connecting a callback to one or several events. Usage: class O: @on("MyMemoryKey") def my_callback(self,value): print "I was called!", value o = O() events = EventsHelper() events.connect_decorators(o) After that, whenever MyMem...
5c0695dc45853bba0c80c93ee496fd76704dcca3
610,193
import hashlib def get_sha256(filename): """ get the sha256 of a file """ sha256_hash = hashlib.sha256() with open(filename,"rb") as f: for byte_block in iter(lambda: f.read(4096),b""): sha256_hash.update(byte_block) return sha256_hash.hexdigest()
af7114586d6c998f702097381eb202c1f3919c42
610,194
from sympy.matrices.expressions.kronecker import matrix_kronecker_product def _sympy_tensor_product(*matrices): """Compute the kronecker product of a sequence of sympy Matrices. """ return matrix_kronecker_product(*matrices)
32169bd78a7fc1a2750cd7d7771e0988c5091325
610,197
def to_list(obj): """ Wraps an object in a list if it's not already one """ if isinstance(obj, list): return obj return [obj]
e2973c6f2132dd7fb270b27c21eea0afab625e36
610,202
from typing import List import random def generateLine() -> List[str]: """Generates a new Line with a random block Returns: List(str): A new line for the game, with a random new block """ tmp = ["","","","",""] randNum = random.randint(0, 4) tmp[randNum] = "B" return tmp
5b4ad3f5d5522ab1b40b3874fb7af801ba2ad34f
610,203
def find_srv6_tunnel(database, key=None, l_grpc_address=None, l_grpc_port=None, r_grpc_address=None, r_grpc_port=None, sidlist_lr=None, sidlist_rl=None, dest_lr=None, dest_rl=None, localseg_lr=None, localseg_rl=None, bsid_addr=None, fwd...
0076c01e24a4b540ec9f4a6333151cf88c59ca5c
610,208
def Counts(dict_of_list): """Given a dictionary whose value are lists, returns a dictionary whose values are the length of the list. This can be used to summarize a dictionary. """ return {k: len(v) for k, v in dict_of_list.iteritems()}
47cb8ae3752cbf2b76079458708346ae2747b758
610,209
def calculate_overlap(dictofsubsets): """Takes in a dictionary of subsets, calculates overlaps between all pairwise combinations of the subsets, and returns dictionary with set pair IDs and overlaps Parameters ---------- dictofsubsets: dict Returns ------- dictofoverlap: dict """ ...
77913464e6e27eb08d5770391fab1578a7571465
610,210
def parse_datetime(dtime: str): """ Parse a datetime or period string from STAC request. :param dtime str: input datetime: A date-time: "2018-02-12T23:20:50Z" A period: "2018-02-12T00:00:00Z/2018-03-18T12:31:12Z" or "2018-02-12T00:00...
2a573e43496b922f92b6f62bccabfe168254b04d
610,211
def _input(msg: str) -> bool: """Get yes/no answer from user in terminal Parameters ---------- msg : str prompt for user Returns ------- bool true if y else False """ reply = str(input(msg + ' (y/n): ')).lower().strip() if len(reply) <= 0: return False ...
08305af45f1395cd79db0dc1648dbbed8d311d41
610,212
def is_sublist(source, target): """Checks if one list is a sublist of another. Arguments: source: the list in which to search for the occurrence of target. target: the list to search for as a sublist of source Returns: true if target is in source; false otherwise """ for index in...
43cad34ad6752ffaf929f0a2b7cc9f625a44cafd
610,216
def adjust_detector_length(requested_detector_length, requested_distance_to_tls, lane_length): """ Adjusts requested detector's length according to the lane length and requested distance to TLS. If requested detector length is negative, the resu...
4c3736996c59918d65335fb76360517059490fc9
610,217
def footnote_anchors(content): """ Return the id of the reference and the id of the definition. """ h = str(hash(content))[:8] return f"fr-{h}", f"fd-{h}"
ea621fb659efeb8e899fe5eaa009cbae962cebc6
610,220
import pickle def pickle_load_dict(fpath): """load the dict Parameters ---------- fpath : str file path Returns ------- type dict """ return pickle.load(open(fpath, "rb"))
b71d2cb1c8a105a1fd3cc7b2329ceb8d6fffd5e5
610,223
def pack_byte_to_hn(val): """ Pack byte to network order unsigned short """ return (val << 8) & 0xffff
a0ab9ca7460c45470570bb0eb8a56a16e613b720
610,224