content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def file_appender(fname, write_task=False, write_res=True): """A utility to use for on_complete_func. Appends the result to fname""" if not write_task and not write_res: raise ValueError("at least one of write_task and write_res must be truthy") async def append_to_file(task, res): # tr...
d518e2cb8a502e78e3973a70b115ab0a63ef295e
670,148
def display_joke(): """ 003 Write code that will display the joke 'What do you call a bear with no teeth?' and on the next line display the anser 'A gummy bear!'. Try not to create it using only one line of code. """ question = "What do you call a bear with no teeth?\n" answer = "A gummy bea...
a3919b4c30fcff42a2c601d54d69619cb0567edc
670,151
def create_navigator_apt_entry(nav_info, appointment_timestamp): """ This function takes a dictionary popluated with navigator information and an appointment timestamp and creates an dictionary containing appointment information corresponding to the information given. :param nav_info: :param appoin...
461e9ef73c291d7c74ea01aa4fccd764c6e53767
670,152
def color_RGB_and_brightness_to_RGB(brightness: int, rgb=(0, 0, 0)): """Combine RGB and brightness""" rgb = [int((x / 255.0) * brightness) for x in rgb] return tuple(rgb)
c1ecb90f84e72fd8670e7f916ac60da6c1fe7a58
670,153
import re def clean(sentence): """ Clean up a sentence. Remove non alpha number letters. Lower cased. >>> clean('all done.') 'all done' >>> clean('ALL DONE.') 'all done' >>> clean('here we go:') 'here we go' :param sentence: :return: """ return re.sub('[^A-Za-z0-9]', ...
1d45d61b897d49073f6bd5a5e2147b5d6494b2fd
670,154
import struct def bytes_to_integer(bytes_): """Convert bytes to integer""" integer, = struct.unpack("!I", bytes_) return integer
7ab9128a1336f4e642da52766effe89e23f0aaac
670,156
def is_wsl_host(): """ Detects whether the function is run under MS WSL. http://stackoverflow.com/questions/38859145/detect-ubuntu-on-windows-vs-native-ubuntu-from-bash-script """ with open('/proc/sys/kernel/osrelease') as os_release: info = os_release.read() is_wsl = 'Microsoft' in inf...
859332bda26c0972980c65647cb2895ba3af2819
670,157
def to_rpc_byte_order(internal_byte_order): """ Returns a given internal byte order hash (bytes) to the format expected by the RPC client. """ return internal_byte_order[::-1]
0d7f47e3e57175e9a88bad8de2a47d536564e309
670,158
import secrets def token_url() -> str: """Return random and URL safe token.""" return secrets.token_urlsafe()
03e73a6757ccf25854f1e3cd9ae0922c782bf1e0
670,160
import sympy def antal_l_coefficient(index, game_matrix): """ Returns the L_index coefficient, according to Antal et al. (2009), as given by equation 1. L_k = \frac{1}{n} \sum_{i=1}^{n} (a_{kk}+a_{ki}-a_{ik}-a_{ii}) Parameters ---------- index: int game_matrix: sympy.Matrix Return...
39dd5dab87f29db5a85a55e8bbb3d0d98ff4ad3c
670,161
import torch def collate_videos(batch, pad=0): """Batch preparation. Pads the sequences """ transposed = list(zip(*batch)) max_len = max((len(x) for x in transposed[0])) data = torch.zeros( (len(batch), max_len, transposed[0][0].size(-1)), dtype=torch.float ) + pad mas...
1e2549901e512aec4478ba52838ae26f5794e28e
670,162
import requests def copy_job(job_id, key): """Helper function to create a Figure 8 job based on existing job. Args: job_id: ID number of job to copy instructions and settings from when creating new job key: API key to access Figure 8 account Returns: int: ID number of job created...
810fc44c636fa6bdb4e05f023321313036f3807e
670,163
def most_common_bit_for_position(numbers: list[str], position: int) -> int: """calculates the most common bit for a given position (if equal, returns 1)""" sum_for_position = 0 for number in numbers: sum_for_position += int(number[position]) return int(sum_for_position >= len(numbers) / 2)
1e58a5d36a6ab033cc4750dcfacb29cd1eb178be
670,164
import random def prob_handling(var_table, var_tag, d, ph_table): """ A roulette stohastic method of choosing which path to follow. :param var_table: the numpy array representing the discrete values :param var_tag: tag of the variable :param d: number of discrete values per variable :param ph_...
db60a1244d1f053c576d5b164314d875742b6e62
670,165
import os import base64 def load_certs(certs_dir): """ Load all of the certificate, key and PEM files from the given directory. Only files with "crt", "key" and "pem" extentions are loaded. Returns: A dictionary of the file name keys (dots are removed and the names are camel-cased, eg "ca.crt" be...
a6dd8ada5dea7d2d0777644bc1797f8d59434f78
670,167
def getattr_(entity, attribute): """Either unpack the attribute from every item in the entity if the entity is a list, otherwise just return the attribute from the entity. Returns None if the entity is either None or empty.""" if entity in (None, []): return None if isinstance(entity, li...
42dbfb2c0cdb1bd59d627cd6d509e6dc43ba7a2d
670,168
from datetime import datetime import sys def get_route(way, destination, number, time): """ Запросить данные о маршруте. """ way.append( { 'destination': destination, 'number': number, 'time': time, } ) try: datetime.strptime(time, "...
028008955e22c44b005f0041fac527f0bd1ca885
670,169
def lg_wsb(data, weights): """lgwSB = (SB * runSB + CS * runCS) / (1B + BB + HBP – IBB) Used in the calculation of wSB. :param data: DataFrame or Series of league totals :param weights: DataFrame or Series of linear weights :returns: Series of lgwSB values """ x1b = data["h"] - data["x2b"] ...
e0538843e3d309f7d8d026da832d99bf654ae661
670,170
import binascii def HexifyBuffer(string_buffer): """Return a string with the hex representation of a string buffer.""" chars = [] for char in string_buffer: chars.append(binascii.hexlify(char)) return '\\x{0:s}'.format('\\x'.join(chars))
b3091daa7d8b2be3e778ab763619fdd05c8ea051
670,171
def convert_empty_sets_to_none(config_dict): """Convert empty lists to None type objects in configuration dictionary. :param config_dict: dict, CAZy classes and families to be scraped Return dictionary with no empty lists. """ for key in config_dict: if config_dict[key] is not None: ...
075755a2a35baf877be893c6282d9f7390b05a28
670,172
def finished_prediction(status): """ Gets prediction of finished game :param status: :return: 1.0 if white wins, 0.0 if black wins, 0.5 if draw """ finished_dict = {"w": 1.0, "b": 0.0, "d": 0.5} return finished_dict[status]
595f4ef557e78fef482a2780e80a8cddb6b799a3
670,174
import os def getFsiP(): """Fsi parameters""" filePath = os.path.abspath(os.path.dirname(__file__)) p = {} # Solvers and config files p['fluidSolver'] = 'SU2' p['solidSolver'] = 'Modal' p['cfdFile'] = os.path.join(filePath,'staticAgard_fluid.cfg') p['csdFile'] = 'agard_solid' # FSI...
5197d25fb337d595ecbc93514fe3caa50be8e43d
670,175
def lift_iter(f): """ Lift a function to consume an iterator instead of single values. """ def f_iter(iter, *args, **kwargs): return (f(x, *args, **kwargs) for x in iter) return f_iter
b5e11406f3c8222778af3bd0f1a37e065f933186
670,177
def remove_digits(name: str) -> str: """ "O1" -> "O" """ return ''.join([i for i in name if not i.isdigit()])
6d14aa2a0d93f3765b8f3b1e49cff09985f95387
670,178
import json def pp(s): """ Pretty print JSON string. """ return json.dumps(s, indent=4)
2300fead2a6ff63bf5b2e8a4298d74fb44789425
670,179
def has_illegal_grading_method(s): """ s : string with description of grading method returns True if forbidden word contained in s else False """ forbidden = ["出席", "出欠", "欠席", "参加度"] for f in forbidden: if f in s: return True return False
cf94c816cdfff9092656b70d72319b96506691e1
670,180
def token2cwsw(tokens, cw_list, sw_list, cw_token='cw', sw_token='sw', none_token='_', both_token='both'): """ The rule here is very flexible. """ cwsw_list = [] for token in tokens: if token in cw_list: if token in sw_list: cwsw_list.append(both_t...
4d23fd3a1f0d7c6aa0caa74bb8a9b37317a0d941
670,181
import math def add_months(dt, months): """ 添加N个月份 :param dt: 开始时间: :param months: 增加的月份 :return: """ month = dt.month - 1 + months year = dt.year + math.floor(month / 12) month = month % 12 + 1 return dt.replace(year=year, month=month)
a4ee985365e5cd324fb480bcaee3fef17e83b3a4
670,183
def transform_coords(coords, swap, reflect): """ coords - a set of coordinates swap - the swap transformation (i.e. (0, 2, 1) --> (x, z, y)) reflect - the reflection transformation (i.e. (1, -1, 1) --> (x, -y, z)) Returns the transformed coordinates """ new_coords = [] for i in range(le...
0ae4f7f046099d16a0eb7926f4c60946b70a1562
670,184
def ellipsis_or_number(context, paginator, current_page): """ To avoid display a long pagination bar :param context: template context :param paginator: paginator_obj :param current_page: int :return: str or None """ # Checks is it first page chosen_page = int(context['request'].GET...
a0c61abcef6d5eda71f076201449fd50c15707fe
670,185
def scalb(f, scaleFactor): """Return the scale for the factor""" return f * pow(2., scaleFactor)
52001e5fe1fcda8c01bb7df3d1af5193ae9b20f9
670,186
def compute_trapped_rain_water(heights: list[int]) -> int: """ Given n non-negative integers representing an elevation map (height) where the width of each bar is 1, compute how much water it can trap after raining. Notes: if `left_max_height` and `right_max_height` are the maximum heights ...
520060057fc4526927f23ca398d9e0d096b9499e
670,187
from typing import Optional from pathlib import Path def _try_touch_file(target) -> Optional[Path]: """Test to see if we have permissions to create a file at ``target``. If the target already exists, it will not be touched. If it does not exist, this function attempts to create it and delete it (i.e...
7854c1139946a5ff0969e79876b1c0e377030c55
670,188
def ramb18_2x(tile_name, luts, lines, sites): """ RAMB18E1 in both top and bottom site. """ params = {} params['tile'] = tile_name params['Y0_IN_USE'] = True params['Y1_IN_USE'] = True params['FIFO_Y0_IN_USE'] = False params['FIFO_Y1_IN_USE'] = False lines.append( ''' (...
1d1ada3199c5a244f9a2fccfa25e281586361a82
670,189
def read_to_whitespace(fptr, track): """ Read, skipping over white space. Then read all non-whitespace until one character of white space is consumed. Return the non-whitespace that was read. If the end of the file is encountered, return any non-whitespace if available, or an empty bytes string. ...
80d246f578af932830169306816acb5f0d6bfffb
670,190
def reopen_to(fhandle, path, mode): """ close a filehandle and return a new one opened for the specified path and mode. example: sys.stdout = reopen_to(sys.stdout, "/tmp/log.txt", "w") Parameters: fhandle (file): the file handle to close (may be None) path (str): the new path to open ...
17eb5da556899e80962866b9229d3cde478ec7df
670,191
def get_hash(): """ Returns the hash map of options the server can take. EG { 1: name 1, 2: name 2, ... n: name n } """ options = [ "Close the server", "Broadcast a command", "Send a message to all the ...
7267ac7ae92ac4ec58caac5b586447ac84d3cf8c
670,192
import re def parse_package_names(names): """ ### 排除列表中包名的版本号限制符。 例如传入['fastpip>=0.5,<0.8'],返回['fastpip']。 """ package_names = list() pt = re.compile(r"[^\<\>\=\,]+") for n in names: m_obj = pt.match(n) if not m_obj: continue package_names.append(m_obj....
089c52db1597d4023a7e48aa63f4fd7fe5e77b0a
670,193
import re def check_input(new_ver): """ Ensure that user input matches the format X.X.X """ pat = r'\d+.\d+.\d+' if not re.match(pat, new_ver): print("The new version must be in the format X.X.X (ex. '0.6.0')") return True
7e632a45c0e8f4c71ef85c18b316e7f81de908c9
670,194
import math def distance(pose1, pose2): """ Function implementing the distance """ argument = 0 for i in range(len(pose1)): argument += (pose1[i]-pose2[i])**2 return math.sqrt(argument)
6ddf73b5d2cad198f00a646f5a6461943e5f71cf
670,195
import argparse import textwrap def parse_args(): """Process command-line arguments.""" description = """Parse data from flora website.""" arg_parser = argparse.ArgumentParser( description=textwrap.dedent(description), fromfile_prefix_chars='@') arg_parser.add_argument( '--csv...
560e25c2b04d920844d8b2970db6790d534aa8c3
670,196
def get_data_path(): """Returns the default path where the data is stored.""" return '../data_preprocessed/'
26168e5b9bcd2cb51c019d76164063e1f664a9a7
670,197
def euler_maruyama_step(drift_func, diff_coeff): """Construct Euler-Maruyama integrator step function.""" def forward_func(z, x, v, δ): return x + δ * drift_func(x, z) + δ ** 0.5 * diff_coeff(x, z) @ v return forward_func
d454f23ef564edc3f2dfd10741c4fc783160fa17
670,198
def ignore_exception_handler(ex): """ acts as if no exception was raised, equivalent to except: pass""" return None
0e52bac1d9f13b65edbee94c2def8c9eaba422a0
670,199
def modNeg90To90(angle_deg): """Returns a modulo between -90 and 90""" return (angle_deg + 90)%180-90
f79d6bb1cba93b0d4bbbfcf6fd3c581b14da518c
670,200
def shorter_str(s): """Replaces words in a string that are found in the helper dictionaries in pfxdict.py with shorter versions for a more compact description.""" tokens = [ "Increase Inc", "Decrease Dec", "Emergency Emcy", "Oscillate Osc", "Direction Dir", "...
713f4400742777fef729e634234f1952d1d7750f
670,201
def image(title, desc, image_name, group=None, height=None): """ Builds an image element. Image elements are primarily created and then wrapped into an image gallery element. This is not required behavior, however and it's independent usage should be allowed depending on the behavior required. ...
301f7831567e8845ef32ec33da4d5d273e50ac65
670,202
def flatten(l): """Utility function to flatten an iter of iters into an iter.""" return [item for sublist in l for item in sublist]
e9deb14a37676aaff78ba5080f792793f8ff06ce
670,203
from functools import reduce def fold(*funcs): """ Function that composes an arbitrary number of functions """ def f_of_g(f,g): return lambda x:f(g(x)) return reduce(f_of_g,funcs,lambda x:x)
09a8669863385ec133c8de12f2dc38b58fa85995
670,204
def _int_str_to_bit_str(int_str, num_bits, msb_first): """ Convert an integer string to num_bits bits string. Example: int_string_to_bit_str('0x5', 4) -> '0101' int_string_to_bit_str('0x3', 4, msb_first=false) -> '1010' """ data = int(int_str, 0) # use radix 0 to automatically deduc...
237b87ecf578834517b5137ed7ffbb92b284520d
670,205
def w_liq_real_enter_feed(F_mass, d_enter_feed_real, rho_F_20): """ Calculates the real speed of liquid at the tube. Parameters ---------- F_mass : float The mass flow rate of feed [kg/s] rho_F_20 : float The density of feed at 20 degrees, [kg/m**3] d_enter_feed_real : float ...
a4c4c6fdeba1e39bfbd9276cbd47f52f3e1f67db
670,206
def get_padding(kernel, dilations, axis): """ Calculates required padding for given axis Args: kernel: A tuple of kernel height and width dilations: A tuple of dilation height and width axis: 0 - height, 1 width Returns: An array that contains a length of padding at the ...
7c8918c8abcd3590efe3f80b5d4b7e28d183f98b
670,207
import os def get_timestamp(path): """Return a timestamp to give a sense of time between seeds. If you want to maintain timestamps via other means (db, flat file with times, etc), just swap out this function for your implementation.""" return os.path.getmtime(path)
06d7898ad0dcc615ecbd06814b7ef6bf8226df20
670,208
import json def create_test_bank(test_instance): """ helper method to create a test assessment bank """ test_endpoint = '/api/v2/assessment/banks/' test_instance.login() payload = { "name": "a test bank", "description": "for testing" } req = test_instance.client.post(te...
cff4e653435e547bfc10a6b4be3ed971b641321d
670,209
def update_variables(variables, constraints): """Updates all variables with their neighboring variables and constraints.""" for constraint in constraints: scope = constraints[constraint].variables for var in scope: variables[var].add_constraint(constraint) variables[var]....
3a4c9d2b8cf86dc26fe93bafca4e4bf0071ca1cb
670,210
import requests import re def get(share_url) -> dict: """ author, title, audioName, audios, videoName, videos """ data = {} headers = { 'accept': 'application/json', 'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Versi...
18ff790fc46564a5aa08498a7045cb680772b0f0
670,211
import numpy def RV2coeff(dataList): """ This function computes the RV2 coefficients between two matrices at the time. The RV2 coefficient is a modified version of the RV coefficient with values -1 <= RV2 <= 1. RV2 is independent of object and variable size. REF: A.K. Smilde, et al. Bioinform...
d25918646772e344eaf3f69ce3420408bad152de
670,212
def are_elements_oriented(subgraph_elements): """Check wheter all the elements of a subgraph have an orientation value `[+/-]`. """ for id_, orientation in subgraph_elements.items(): if orientation is None: return False return True
a4f730f8b46e13033cba112124b599dd0448d4e6
670,213
def ramp(s, width, annealing_time): """Schedule with a ramp shape. Args: s (float): The mid-point of the ramp, as a fraction of the annealing time. width (float): The width of the ramp, as a fraction of the annealing time. Note that QPUs have a maximum slope...
cbffad367302c75e44279a483b8691f751f2f0a2
670,214
import os def findFiles( path, regexp=None, ext=None, excludeSVN=True ): """ Returns a list with all files in 'path' whoms names match a certain pattern. Pattern can be: * regexp: a precompiled regular expression object * ext: file has a certain extension, e.g. ".c" (mi...
856f0a57b6bbf2412101b444f0f9270d5d631a22
670,215
import os from typing import List def find_path_to_subdirectory(target_dir, search_path=None) -> List[str]: """Find a directory name among subdirs searching for target_dir: 'testdata' from '/home/nate': '/home/nate/testdata' would match '/home/nate/testdata/something' would NOT match '/home/nate/...
94b07ea7158b135b965fba7455e620127039d85e
670,216
def ema_std(data, span=100): """Computes and returns the standard deviation of the exponential moving average. :Input: :data: pandas.DataFrame with stock prices in columns :span: int (defaul: 100), number of days/values over which the average is computed :Output: :ema_std: pand...
5348f6682d690879927838f03c6f90a06b744c22
670,217
import optparse def LoadOptionsFromFlags(argv): """Parse command-line arguments. Args: argv: The program argument vector (excluding the script name) Returns: A dictionary with key-value pairs for each of the options """ usage_string = 'python dsplcheck.py [options] [DSPL XML file or zip archive]' ...
6de6289cb33a8369808d7c295158d839d3dffdc3
670,218
def sort_by_name(name: str): """ function needed to sort signal groups by name """ return len(name), name
75a777b4fda40ac7d37cb3063db006826682caa6
670,219
from typing import Dict def create_result_dict() -> Dict: """ Create the results dictionary """ return {"Title": None, "Issue Type": None, "Severity": None, "CWE": None, "Vulnerable File": None, "Details": []}
6fab9750cac1201e3d8f530f03919e05db668bd8
670,220
def dummy_dict(): """Return a dict of dicts""" return { 1: {1.1: "1.1.1", 1.2: {"1.2.1": {}, "1.2.2": "1.2.2.1"}}, 2: {2.1: "2.1.1", 2.2: {}}, 3: {}, }
2d712db4eb1cdf56debe10584bd43761ddf05992
670,221
import re def fancyIMDBpages(imdbDict, soup): """ Same as bsIMDB to extract data from IMDB page except this is for promotional movies where the html is different. Parameters ---------- imdbDict : dictonary contains current information about this movie soup : beautiful soup object of i...
b76b14d287ad82860afac8961519cfbfd6c1d4cb
670,222
def new_merged_dict(*dicts): """Merges dictionaries into a new dictionary. Necessary for python2 and python34 since neither have PEP448 implemented.""" # Necessary for python2 support output = {} for d in dicts: output.update(d) return output
d431bd1587d05f26caed9181c58315bf309d3d04
670,223
import torch def coord_to_blender(dtype=torch.float32, device="cpu"): """ Standard to Blender coordinate system transform. Standard coordinate system is: x right y up z out (out=screen to face) Blender coordinate system is: x right y in z up :return (4, 4) """ return torch.tensor( ...
c2ae7a28d6f8ce0823b68c9e0a844cb165fafb74
670,224
def get_srcmap_step_id(): """Returns the id for the srcmap step.""" return 'srcmap'
9b773469006012a886e624cb03e4084ff1942fb7
670,225
import six def commalist(value): """ Convert a comma separated string into a list If ``value`` is already a list or tuple it will be returned. """ if isinstance(value, six.string_types): return [v.strip() for v in value.split(',')] if isinstance(value, (set, list)): return ...
3ffa6c9662d15ace3a59812bdf71a7c2394cc969
670,226
import re def replace(string, args): """ Perform a regular expression search and replace. Usage: {{ var|replace:"/search/replace" }} """ search = args.split(args[0])[1] replace = args.split(args[0])[2] return re.sub(search, replace, string)
52aa592f65b83d4c3618989a87df19c661fee8d8
670,227
def neg_poly(p): """Returns a negation of a polynomial""" result = [m.copy() for m in p] for m in result: m.c = -m.c return result
79aeb665e856e3fac2a9794873e07109b3b19e83
670,228
import os def portmap_provision(realm): """ this function provision portmap for the realm passed as arg """ server_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) python_path = os.path.join(server_dir + '/bin/python3') cmd = python_path + ' ' + os.path.join(server_dir,...
db61435040aa4db1b17eff3c0b0032c06c14681f
670,229
def MaskField(**kwargs): """Create a new field for a :py:class:`~.KeyspacesRegion` that will write out a mask value from a keyspace. Parameters ---------- field : string The name of the keyspace field to store the mask for. tag : string The name of the keyspace tag to store the ...
29db1753257d397de50e8d317b10ec057a82f4d6
670,230
def get_file_content_as_string(path): """ Download a single file and make its content available as a string. """ # url = 'https://raw.githubusercontent.com/insert_path_to_repo_here' + path # response = urllib.request.urlopen(url) with open(path, encoding="utf-8", errors="ignore") as f: r...
29fd23752031747884a56a83c12bbc9ad4fab692
670,231
import re def parse_sympy(data, condition=False): """ :param condition: :param data: :return: """ def clean_text(text, rep={" ": ""}): rep = dict((re.escape(k), v) for k, v in rep.iteritems()) pattern = re.compile("|".join(rep.keys())) new_key = pattern.sub(lambda m: r...
1a698e90e5407b756b5937678dd2365216765032
670,232
def chop_duplicate_ends(word): """Remove duplicate letters on either end, if the are adjacent. Args: words (list): The list of words Returns: list: An updated word list with duplicate ends removed for each word. """ if word[0] == word[1]: word = word[1:] if word[-2:-1] ...
ab16766e5ec0cf54f4dbcb1630307ecb202c6ff8
670,233
def compare_feature(old, new): """Check two SeqFeatures agree.""" if old.type != new.type: raise ValueError("Type %r versus %r" % (old.type, new.type)) if ( old.location.nofuzzy_start != new.location.nofuzzy_start or old.location.nofuzzy_end != new.location.nofuzzy_end ): ...
faf41d9e6ab0e387c8c85c73a85de2aec94948eb
670,234
def to_hashable(map): """ Compute a map to a hashbable """ h = "" for e in map: for c in e: h += c return h
16f0b97f91ad09512de4718c2dab453857dafb8c
670,235
def search_linear(xs, target): """ Find and return the index of target in sequence xs """ for (i, v) in enumerate(xs): if v == target: return i return -1
91b719857decfe4818f2843ac1df6e423ea966ef
670,236
import functools import inspect def get_class_that_defined_method(meth): """Get the name of the class for given function.""" if isinstance(meth, functools.partial): return get_class_that_defined_method(meth.func) if inspect.ismethod(meth) or (inspect.isbuiltin(meth) ...
8b2ce062bae70d8abdaea008b72b07d852b248ab
670,237
def check_private_exponent(a, B=512): """ Checks the bit length of the given private exponent. If you've asked for a random number of bit length at least :param:`B`, but are retrieving numbers that are smaller than said size, you might want to check your RNG. >>> B = 8 >>> a = 0b11111111 >...
a1d4e0c6d1345057f4c2648ded655fa9e31585c5
670,238
def is_valid_in_build(pattern): """Is a valid target pattern in BUILD file""" return pattern.startswith('//') or pattern.startswith(':')
9d0e0f402fe3b6d7c36c28cb655728bba8705660
670,239
def _is_removed(tensor_name, removed_op_names): """Determine whether the named tensor is an output of a removed op.""" for removed_op_name in removed_op_names: if tensor_name.split(':')[0] == removed_op_name: return True return False
55915465adeecf5ba33aff8daa3de04a35c28ac1
670,240
def map_title_from_list(number, title_list): """Used during the iterative inserts in fn:write_to_db - if number matches the number within title_list, write title to db. :arg number: string containing RFC number :arg title_list: list of all rfc titles from fn:get_title_list :returns result: string ...
25b6dcafbd9eb56ad8d5068fdb51950c60b90498
670,241
def zeros(m,n): """ Return a zero "matrix" (iterated list) with m rows (1st index) and n columns. """ return map(lambda var: map(lambda var: 0, range(n)), range(m));
9d2e55a99a14bf9eee112f275ded7fc705f63407
670,242
def _get_resize(input_size, img_size): """Copies a resized and properly zero-padded image to a model's input tensor. Args: interpreter: The ``tf.lite.Interpreter`` to update. size (tuple): The original image size as (width, height) tuple. resize: A function that takes a (width, height) tuple, ...
def08cd2cd616afd628e0e0dc3f690d0aa011934
670,244
def find_instance_of_digit(train_labels, digit): """ find_instance_of_digit function Find the first instance of a digit within the given labels and returns its index. Args ---- train_labels : np.array list of labels digit : Number digit to search for Returns ------...
680a8db67f95c42212fcbd02b632a5a79aa8f84a
670,246
import os import glob def augment_file_list(file_list, tag_from, tag_to): """ Replace a tag in the filenames of a list, with another tag, and search for files with the new names. This is useful to add filenames of augmented data. For example, if you start with im_file_1_nan.tif im_file_2_...
b6540c5e01ee8cc327df4da8d64f2e896bfb140b
670,247
def get_string_content(line): """ Get the quoted string content from a line. :param line: a string which contains a quoted substring :return: the string between the quotes """ first_index = line.find('\"') + 1 last_index = line.rfind('\"') content = line[first_index:last_index] conte...
a11bd8721ac9cf5be6a8bdb19ee5e97ab3174983
670,248
def sum_2d(a): """ Sum all the values in a matrix together. :param a: (list) 2D matrix containing values to be summed :return: (int/float) sum value of the matrix. """ # Check if given matrices are of "list" type if type(a) != list: raise TypeError('Error xm01: Incorrect type, m...
a41a2dce6d49e102f2d35e15aef43efc6f49d829
670,249
def number_of_tweets_per_day(df): """ Function will count number of tweets per day Arguments: takes a Pandas DataFrame as input Returns: a new DataFrame grouped by day (new column 'Date') with the number of tweets for that day """ df["D...
86d3d2ec85424ae3fbe17b3ad475d802cab9eb11
670,250
def allowed_to_preview(user): """ Is the user allowed to view the preview? Users are only allowed to view the preview if they are authenticated, active and staff. :param user: A User object instance. :return: Boolean. """ if ( user.is_authenticated and user.is_active and ...
3f628939f79ffcb7f0802b71a9433eaa58c48946
670,251
def filter(nodes, labels=[]): """Filter nodes which matches labels""" labels = set(labels) filterd_nodes = {} for k, spec in nodes.items(): node_labels = set(spec.get('labels', [])) matched_labels = labels & node_labels if matched_labels == labels: filterd_nodes[k] = ...
5b81de38ccdef8b8271b29445328f90d4f7bfd79
670,252
import hashlib def generate_unique_key(master_key_path, url): """ master_key_path: str Path to the 32-byte Master Key (for S3 Encryption) url: str S3 URL (e.g. https://s3-us-west-2.amazonaws.com/bucket/file.txt) Returns: str 32-byte unique key generated for that URL "...
f254a57fa02eafe7363e65859cfc3710e0b97f47
670,253
def _pack_arguments(function): """ generate an equivalent function that takes all of its arguments packed into a sequence """ def _function(args=()): return function(*args) _function.__name__ = function.__name__ return _function
66b2b6b9ab9da6d42ee0d4ce34073371b5addcd6
670,254
from string import digits def remove_numbers(string: str) -> str: """Strips numbers from a string Eg, a1b2c3 -> abc Args: string (str): String to clean Returns: str: Provided string without numbers """ return string.translate(str.maketrans("", "", digits))
621ded81a05412b17f6cfdeb14dd71d393cee8fb
670,255
import re def add_uuid_dashes(uuid): """Convert a plain UUID (i.e. "65ea51744ce54bee...") to a dashed UUID (i.e. 65ea5174-4ce5-4bee-...) """ if uuid is None: return None else: p = re.compile(r"(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})") return p.sub(r"\1-\2-\3-\4-\5", uuid)
14e94716804c8a5f86a1076e62926da1e4d20a5f
670,257
def service(func): """ Service decorator This will add a tag property to a function called 'is_service' so that the function/method can be identified as a service. When writing a Measurement class, any method that is to be offered as a service can be tagged with the @service decorator e.g. ...
acae0b71c5a5bbdb0835c11ffc765aab2f988b4f
670,258