content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def linear_cell_to_tuple(c1, repeat_units): """ Convert a linear index into a tuple assuming lexicographic indexing. :arg c1: (int) Linear index. :arg repeat_units: (3 int indexable) Dimensions of grid. """ c1 = int(c1) c1x = c1 % repeat_units[0] c1y = ((c1 - c1x) // repeat_units[0]) %...
1ccddb72907fdbdc18e19e79c6146b437dae5f8e
614,783
def contained_point(point, mask): """Checks to see if a point is contained within the coordinates of a mask""" if point[0] < mask.x2 and point[0] > mask.x1 and point[1] < mask.y2 and point[1] > mask.y1: return True return False
426a1ae8953867e98ad94b07070fbd9992098df7
614,787
from typing import Dict from typing import List def get_block_dict(signatures : Dict[str, dict]) -> Dict[str, List[str]]: """ Given dict of signatures, return the dict of blocks containing block name : list of siagnatures in this block """ block_dict = {} for item in signatures.values(): ...
380656fa794a528744007c97d7a76be1609a7723
614,790
def int_shape(x): """Returns the shape of a Keras tensor or a Keras variable as a tuple of integers or None entries. Arguments --------- x: Tensor or variable. Returns ------- A tuple of integers (or None entries). """ shape = x.get_shape() return tuple([i.__int__() for i in shape])
f3ad11f9cf7a3648c93a1d67f1f98269c0e18a12
614,791
def mu(b, I, mu0, mu1): """ Recovery rate. Parameters: ----------- b hospital beds per 10,000 persons I number of infected mu0 Minimum recovery rate mu1 Maximum recovery rate """ # recovery rate, depends on mu0, mu1, b mu = mu0 + (mu1 - mu0) * ...
55345c882a223d5eb1a0cc6a3f8314838cc9b000
614,793
def markables_overlap(mark1, mark2, lex=None): """ Helper function to check if two markables cover some of the same tokens. Note that if the lex argument is specified, it is used to recognize possessives, which behave exceptionally. Possessive pronouns beginning after a main markable has started are tolerated in ca...
1ff321949cb4c589dc6a4b22990802d77763af95
614,798
import logging def ByteStreamCopyToString(byte_stream, codepage='utf-8'): """Copies a UTF-8 encoded byte stream into a Unicode string. Args: byte_stream: A byte stream containing an UTF-8 encoded string. codepage: The codepage of the byte stream. Returns: A Unicode string. """ try: string ...
c26eab65ded39ae27530fa427ee538d0a4db0db7
614,799
def GetVoltWindow(voltage,windowSize,windowCtr): """ This function takes the voltage time series and retrieves a particular window based on the windowCtr parameter Parameters --------- voltage: numpy array of float (measurements,customers) time ...
5cd1cee82df567d0c113216ffb09db8801ad6676
614,803
from typing import List def NumberToBase(number: int, base: int = 10) -> List[int]: """Convert a int into it digits representation into a base Args: number (int): integer value to convert base (int, optional): base to convert. Defaults to 10. Returns: List[int]: List of digits ...
fb6ffa0192f36308658dbe9c37348c7825993f67
614,805
from typing import List def create_binary_list_from_int(number: int) -> List[int]: """Creates a list of the binary representation of a positive integer Args: number: An integer Returns: The binary representation of the provided positive integer number as a list. """ if number < 0...
b795b5edc1dd502aad7896ed7c489654f673dad3
614,814
def _which_asm_has_finer_mesh(asm, neighbor=None): """Determine which assembly has finer meshing Parameters ---------- asm1 : DASSH Assembly object Active assembly around which we are creating mesh asm2 (optional) : DASSH Assembly object Neighboring assembly across active hex side ...
10465f9272abe37cb3a1d448a4ffacd08eed0dc5
614,819
def crop(vol, mins, maxs): """ Crops the input volume. Parameters ---------- vol : ndarray Volume to crop. mins : array Array containg minimum index of each dimension. maxs : array Array containg maximum index of each dimension. Returns ------- vol : ndarray...
4f64d9756e21774b79ea6c0dd66d1b1e47af717b
614,820
def get_gc(seq_str): """ Return GC content from a sequence string. """ return float(seq_str.count('G') + seq_str.count('C')) / len(seq_str)
1cd0c8073306c43d946f81e76ffda3c61d5f776f
614,821
def transpose_imat(nrows, ncols, nnz, imat): """Transpose an index matrix iterator""" def data(): for i, j, v in imat: yield j, i, v return ncols, nrows, nnz, data()
e71e9c2d2d1940148bf9f2e5d978389a9da3e93b
614,823
def get_objs(content, vimtype): """ Get all the vsphere objects associated with a given type """ obj = {} container = content.viewManager.CreateContainerView( content.rootFolder, vimtype, True) for c in container.view: obj.update({c.name: c}) return obj
256733545b82c8c3c7d8e2039262c40b22514410
614,825
def get_value_by_name(en, name): """ Returns value by name from enums """ for n in en: if n.name == name: return n.value
af60b02599845f5e09fd454dc1d8cf7e3044cd9a
614,826
import random def noiseFilter(move, noise): """Turns 'move' into its opposite with the probability noise.""" if random.random() < noise: if move == 1: return 0 else: return 1 else: return move
2b96ac1b52e11de37e4aba81a3de5e81bc818d0c
614,829
def detach_var(var): """Detaches a var from torch Args: var (torch var): Torch variable that requires grad Returns: TYPE: numpy array """ return var.cpu().detach().numpy()
d1a29eb9902d28a765169c54e5cc088ba6ec8e62
614,830
from typing import Callable from typing import Tuple from typing import Any import time def retry_call(callabl: Callable, args=None, kwargs=None, exceptions: Tuple[Any, ...] = (), retries: int = 10, wait: float = 0.1) -> Any: """ Make ...
29d2852065a6e475723441b6df78991d23077c7e
614,832
def identity(frame): """ Identity function to return an input frame. """ return frame
f7da49e87b03eeba1a8c2ce783c95f2e3ec62c05
614,835
def takeBlock(aList, row_l,row_r,col_l,col_r): """ Take sublist given from row row_l to row_r and column col_l to col_r from a double list. The convention for the index of the rows and columns are the same as in slicing. """ result = [] for aRow in aList[row_l:row_r]: result.append(aRow[col_l:col_r]) re...
4caadcdc74d065f63809f53dc6c3f489b1634edd
614,837
import re def parse_event_fields(lines, idx, event_dict): """ Parses lines from a proto file that contain an event definition and stores it in event_dict """ fields = [] end_of_event = False # record all fields in event definition. # note: we don't check if there's a leading brace. ...
f7c229d4a0315e3e8a7d0adbf5b91a4105f36592
614,839
def _predict_fn(input_data, model): """Apply model to the incoming request. :param input_data: The request data in a Pandas Dataframe format. :param model: The loaded model for prediction. :return: Predicted results. """ return model.predict(input_data).values[:]
711a201e3ce5910084c0787d9e3bddef04c9b3af
614,841
def fv(rate_ : float, nper : int, pmt : float, pv_ : float = 0, type_ : int = 0) -> float: """ Calculates the future value of a loan based on a constant interest rate. Parameters ---------- rate_ : float The interest rate per period. nper : int The total number of payment period...
5f91fd390b7f8f8aeda3b37472ab8f72a9b325dd
614,842
from pathlib import Path def temporary_frameworks( tmp_path, test_input_request_template: str, test_input_aqa: str, ) -> Path: """Create a temporary frameworks folder with sub-folders, and files.""" # Create a temporary folder dir_example = tmp_path.joinpath("example") # Create a tempora...
2baad8ec627a0542988d951e76c46c210623998d
614,846
import array def get_hex(code_seq): """Return a hex representation of a string. This function does not remove the delimiter code. Parameters ---------- code_seq : bytearray A sequence of character codes. Returns ------- dump : str E.g. "26 24 12 24 DC 0E AC". """...
68eb58283f3f54bff14723f204b01b78f93a1d31
614,847
def parse_value_bitmask(bitstring): """Parse a ternary string specifying a bitmask. The bitmask is given as a string of 36 bits, written with the most significant bit on the left and the least significant bit on the right. A 0 or 1 overwrites the corresponding bit in the value, while an X leaves the bi...
4a1c1802ea83b25feb861722937b638890cd472b
614,848
def _maybe_append_seq(n, prefix): """Append a sequence value to a prefix if non-zero""" if not n: return prefix return f"{prefix} {n}"
e31511435c62839409ad973175a0ce8a951d4757
614,852
def create_data_model(distance_matrix, pickup_delivery_pair, num_drivers: int, depot: int): """Stores the data for the problem.""" data = {} data['distance_matrix'] = distance_matrix data['pickups_deliveries'] = pickup_delivery_pair data['num_vehicles'] = num_drivers data['depot'] = depot re...
b167cf357d0a0a0d9f93818536b6627417555ab7
614,853
def get_h5_attributes(stack): """Get attributes from a stack.""" element_size_um = axislabels = None if 'element_size_um' in stack.attrs.keys(): element_size_um = stack.attrs['element_size_um'] if 'DIMENSION_LABELS' in stack.attrs.keys(): axislabels = stack.attrs['DIMENSION_LABELS'] ...
4fca6c56424d523fd38cd76d0ffd68425ac2a7b1
614,854
def capacity_cost_rule(mod, prj, prd): """ The capacity cost of projects of the *fuel_spec* capacity type is a pre-specified number with the following costs: * fuel production capacity x fuel production fixed cost; * fuel release capacity x fuel release fixed cost; * fuel storage capacity x fuel...
c3c41b4e120c9a53812e1f5ba10bcb3f5325852b
614,855
def reaction_needs_internal_standard(message): """Whether any analysis uses an internal standard.""" for outcome in message.outcomes: for analysis in outcome.analyses.values(): if analysis.uses_internal_standard: return True return False
aebd66188eddb5b0afd05ef7929afd57bcf67321
614,856
import re def valid_sql_in_clause_str(input_str): """Validates if input is comma separated, single quoted strings. Returns: True: valid False: Invalid For example: True: "'1', '2345'" "'1'" False: "1, 2345" "'abc', 'xy...
7bd78f56b7d3f5c0ec96a5683f4d324f809018ac
614,859
def media_ponderada(valores, pesos): """ Encontra a média ponderada de 'valores'. Parâmetros: listas de floats. Retorna: a média ponderada de 'valores'. """ soma_media = 0 soma_peso = 0 for i in range(len(valores)): soma_media += valores[i]*pesos[i] soma_peso += pesos[...
ddac7d59045ab44688d484c15aeda8ecf829ef68
614,860
def chessboard_3DPoints(board_size, square_size): """ - board_size: a tuple (rows,columns) representing the number of rows and columns of the board. - square_size: the size of a square (cell) on the board in mm """ corners = [] for col in range(0, board_size[1]): for row in range(0,...
73951650cd94498a1c0f5e4f3a30ec8c022f052e
614,863
def get_is_tors_list(mode_dict): """ A list contains the boolean values of each mode to determine if the normal mode is internal rotation or not. """ is_tors_list = [] for mode in sorted(mode_dict.keys()): is_tors = True if mode_dict[mode]['mode'] == 'tors' else False is_tors_li...
cfbf984c78800c4ce3b789a65ffedff822753156
614,864
def parse_gpkgb_header_size(gpkg_wkb): """ Parse header of geopackage wkb and return its size """ # some constants no_envelope_header_size = 8 flag_byte_pos = 3 envelope_size_mask = 14 try: flag_byte = gpkg_wkb[flag_byte_pos] except IndexError: return -1 # probably some inv...
b67abe9674ee8d06a847b23b78084993df1a9954
614,865
def get_midpoint(bounding_box): """ Get middle points of given frame Arguments: ---------- bounding_box : (width,height) or (x, y, w, h) """ if(len(bounding_box) == 2): width, height = bounding_box y = float(height) / float(2) x = float(width) / float(2) return (i...
6f605117b9972dd4d6fad0a83cdcb35e26b85a1c
614,866
def safe_short_path(file_): """Like `File.short_path` but safe for use with files from external repositories. """ # Note: "F" is "File", "FO": is "File.owner". (Lifted from genpkg.bzl.) # | File type | Repo | `F.path` | `F.root.path` | ...
603e01a006d15da21a7a7d3139496c2e26c8be96
614,870
def _transform_hostname_to_http_endpoint(hostnames): """Convert hostnames to status page endpoint. Args: hostnames: List of server names Returns a list of urls in the format "http://<hostname>/status" """ return ["http://{}/status".format(server) for server in hostnames]
e0921161f25b98c62199bb7e0da33d07ee3da9c1
614,878
def akm(m: int, n: int) -> int: """ Ackmann 函数 Args: m (int):m >= 0 n (int):n >= 0 Returns: int """ assert m >= 0 and n >= 0, 'm, n must greater than 0' if m == 0: return n + 1 elif n == 0: return akm(m - 1, 1) else: # n > 0 return akm(...
cea7cc95da099f886366509a13eeb173de2847c7
614,879
def dollarsToEuros(dollar): """ Convert dollar to euros (valid in 21/06/2021) The input format is '$1,200.35' """ return round(0.84*float(dollar[1::].replace(',','')))
0ccd64200625459a6d068a0fb999108920546320
614,880
def convert_bool_to_char(value=False): """Convert boolean to SIP2 char representation.""" return 'Y' if value else 'N'
e861197ab00435e959004925a0ed77d336314739
614,887
import time def to_mmss(time_input): """ Converts a time based integer (in seconds) to MM:SS format. """ return time.strftime("%M:%S", time.gmtime(time_input))
1755b02ef08f30258d72cf6354534ef7e4cc6291
614,890
def get_len(in_string, max_len): """Calculate string length, return as a string with trailing 0s. Keyword argument(s): in_string -- input string max_len -- length of returned string """ tmp_str = str(len(in_string)) len_to_return = tmp_str for _ in range(max_len - len(tmp_str)): ...
eed8cd51f39ec3c8b71f53b2fccd8903b7417caf
614,897
def _extra_urls(entry): """Returns a dict of URL types to URLs, e.g. { 'nytimes': 'http://nytimes.com/story/about/research.html', ... } """ urls = {} for k, v in entry.fields.items(): k = k.lower() if not k.endswith('_url'): continue k = k[:-4] ...
baab9f8584d363a26019b5111b4250cac4439c46
614,908
def age_ceiling(age: float, max_age=85) -> float: """ Given an *age*, returns the same *age* unless it exceeds the *max_age*, in which case the *max_age* is returned. """ return min(age, max_age)
134871277164094d592307fab2117855151ddeb1
614,911
import torch def inference_single_frame(model, data, return_heatmap=False, beautify_results=True): """ Does inference for model of a given a single data object. Arguments: model MMDataParallel/nn.Module in eval mode data dict( img torch.Tensor ...
80ba74b7db69d47f02787e8cfd0b21fb102a9ae6
614,913
def find_histogram_range(histogram): """ Find the min and max index where histogram value is larger than zero. :param histogram: A histogram, e.g. an output of cv.calcHist(). :returns: The min and max index with larger-than-zero value """ size = len(histogram) min_i = 0 while min_i < si...
e4b1450438406ba25cea670ccee86ae042f4a95f
614,919
def is_sublist(l1, l2, pos=False): """ Check if l1 is a sublist of l2 (it contains all elements from l1 in the same order). if pos is True, return position where sublist starts, not a boolean value """ if l1 == []: return 0 if pos else True elif l1 == l2: return 0 if pos else Tr...
8be3d2253d6381e61ee58369bdf0c939e11d017d
614,920
def _get_token_ids(token_word_ids, span_word_id, offset=1): """Retrieve token ids based on word ids. Args: token_word_ids: the list of word ids for token. span_word_id: int. the word id in the original string. offset: int. if the tokenized sequence is prepended with special token, this o...
f68c207f909ed8a5902f7194d0b93325acf2df80
614,926
def ndk(name): """ Return the NDK version of given name, which replace the leading "android" to "acamera" Args: name: name string of an entry Returns: A NDK version name string of the input name """ name_list = name.split(".") if name_list[0] == "android": name_list[0] = "acamera" return...
e2e51bd28ca1b8a2104ca5594eb86fc622ea68f2
614,930
import socket def ip_str_to_bytes(ip): """Convert an IP string to a four-byte bytes. :param ip: IP address string, e.g. '127.0.0.1' :return 4-byte representation of ip, e.g. b'\x7F\x00\x00\x01' :rtype bytes :raises ValueError if ip is not a legal IP address. """ try: return sock...
110efc870ceae945703aaa6a237d1cb0c3301c23
614,932
from pathlib import Path def date_subdir(name): """ define function to construct date sub-directories from FTS product-name """ return Path(name[9:13], name[13:15], name[15:17], name)
e1cfb80638905b3fe533cb89d7de33026187747e
614,938
def exif_resolution_unit(value): """ ResolutionUnit可读化 :param value: int :return: description """ dict_desc = {'1': 'cm', '2': 'Inch', '3': 'km'} return dict_desc.get(str(value) if isinstance(value, int) else value, '')
c9a4b78d358db3b0906db1bc57caa181bc2ce125
614,939
def weight_to_duro(weight, boardside=True): """ Takes a weight in KG and returns an appropriate duro bushing. """ bushings = [78, 81, 85, 87, 90, 93, 95, 97] if not boardside: weight -= 5 weight -= 40 if weight < 0: weight = 0 approx_duro = ((weight) ** 0.66 ) + 79 duro = min(bushings, k...
c10d97683fbe6151e99400ebe292e05439ff7c38
614,941
def lorentz_berthelot_rule(sig_A, sig_B, eps_A, eps_B): """ Lorentz-Berthelot rules for combining LJ paramters. Parameters ----------- sig_A: float sig_B: float input sigma values eps_A: float eps_B: float input epsilon values Returns -------- float ...
178782078d11681ad610271ed572ce6691b2497f
614,942
def new_ccf(rw, purity): """ Compute CCF with estimate of purity :param rw: row (variant) :param purity: purity :return: CCF of each variant """ vaf = rw['t_alt_reads']/(rw['t_ref_reads']+rw['t_alt_reads']) # definition of CCF rw['ccf'] = vaf*(purity*rw['cnv_facets'] + (1-purity)*2...
2b664f2c5bbc4227ba25e99800d362dac0aaa27a
614,948
def find_array_start_position(big_array, small_array): """ Find the starting index of a sub_array inside of a larger array Returns -1 if the small_array is not contrained within the larger array Arguments: big_array (arr) : the larger array to search through small...
43839c990c05bf7aa04367c6e577b3cbefaf7f28
614,951
def isWinner(board, player): """Return True if player is a winner on this TTTBoard.""" b, p = board, player # Shorter names as "syntactic sugar". # Check for 3 marks across the 3 rows, 3 columns, and 2 diagonals. return ((b['1'] == b['2'] == b['3'] == p) or # Across the top (b['4'] == b['5']...
f1c116211a53ef685031c9dab44e85c2de3d9110
614,952
def first_or_default(items, default=None): """ Helper method to fetch first element of list (if exists) """ for item in items: return item return default
5761bc330652cd1597507c60658045e6af55c2d6
614,953
def has_same_digits(num1: int, num2: int) -> bool: """ Return True if num1 and num2 have the same frequency of every digit, False otherwise. digits[] is a frequency table where the index represents the digit from 0-9, and the element stores the number of appearances. Increment the respective in...
6f9cf387ba5e67d98c9147323f2b37abb2eb3b4e
614,954
def strip_node_name(node_name): """Strips off ports and other decorations to get the underlying node name.""" if node_name.startswith("^"): node_name = node_name[1:] return node_name.split(':')[0]
8a0e3f863e4026f9f996493b839463e6d3772238
614,958
def _ComputeDeltas(old_items, new_items): """Finds the added and removed items in a new set compared to an old one. Args: old_items: A collection of existing items. Could be a list or set. new_items: Another collection of items. Returns: A pair of sets (added, removed). """ old, new = set(old_it...
c38561349ec04f5f9f88bdf41fbd0ce1ae289886
614,960
def _string_left(self, nchars): """ Return left-most up to N characters from each string. Convenience use of substr. Returns ------- substrings : type of caller """ return self.substr(0, length=nchars)
c2dadcce7f3d9530550eabcd6477636342ffe806
614,961
def rescale(range1, range2): """Return a function that resizes values from range1 to values in range2 This is useful for interpolating values from one range to another """ min1, max1, min2, max2 = min(range1), max(range1), min(range2), max(range2) def resize(value): return (((value - mi...
eec46072e8205a67550152f695970101e151a7b9
614,965
def _autoconvert(value): """Convert to int or float if possible, otherwise return string""" try: return int(value) except ValueError: pass try: return float(value) except ValueError: return value
8c8620170c9e7c601cac2d4c3a65713b85239107
614,969
def all_transitions(transition_lists): """ Given a list of transition lists, combine them all into a list of unique transitions. """ transitions = set() for trans_list in transition_lists: for trans in trans_list: transitions.add(trans) return sorted(transitions)
f29b0d341f4c994f7bca90cd290bbc60093fc45d
614,972
def check_site_id(args, json_payload): """Return True if site_id matches one of configured site_ids""" if args.site_id: site_id = json_payload.get("site_id", "default") return site_id in args.site_id return True
ec91e9ca10eae4330a3d062bb492ae27cedba15b
614,976
def _check_for_unknown_fields(cls, data): """ Checks for keys in a dictionary that don't exist as fields on a model. :param cls: The ``Model`` class to validate ``data`` against. :param data: A dict with keys to validate. :returns: Errors of the fields that were not presen...
d8c49b8618d64805670b0fd8f4120e30f664dc43
614,979
def cin(prompt=">> ", default="q", raw=False): """ A general prompt for operator input. Kind of simulates a terminal. Will display whatever prompt is (with no newlines, unless they are explicitly in prompt) and accept input from the operator. If the user enteres nothing or whitespaces only, then the prompt wi...
cb5878b0880c62bca993ebd5e0174be7ef677dd3
614,980
def filter_match_kwargs(kwargs, children=False): """ Filters out kwargs for Match construction :param kwargs: :type kwargs: dict :param children: :type children: Flag to filter children matches :return: A filtered dict :rtype: dict """ kwargs = kwargs.copy() for key in ('pat...
445ddda5bd7d76ad3f93e1e6a3c2016bc767c97f
614,981
def Gain_22(RS, TS, URU, tdiffuse): """ Two sphere gain in T sphere for light starting in T sphere. Similarly, when the light starts in the second sphere, the gain for light on the detector in the second sphere $G_{22}$ is found by switching all primed variables to unprimed. Thus $G_{21}(r_s,t_s)$...
a93ef5d679af6c8943e11a832f1d2306d08b69c1
614,982
import operator def transcript_exons_to_bed12(exons_list, transcript_id): """ Convert a list of exon Genomic Intervals from a transcripts (from HTseq) to bed12 line """ blockSizes = [] blockStarts = [] sorted_exons = sorted(exons_list, key=operator.attrgetter("iv.start")) chrom = sorted_e...
9b88916e7e1c4a59165b6dedfe5ba7cb74631f47
614,983
def merge(dict1, dict2): """ Recursive merge dictionaries. :param dict1: Base dictionary to merge. :param dict2: Dictionary to merge on top of base dictionary. :return: Merged dictionary """ for key, val in dict1.items(): if isinstance(val, dict): dict2_node = dict2.setd...
4aff30c006e605b4f302f7c58e57c38a5199fe77
614,991
import re def title_sortkey(s): """Transform a document title into a key useful for sorting and partitioning documents. >>> title_sortkey("The 'viewstate' property") == 'viewstateproperty' True """ s = s.lower() if s.startswith("the "): s = s[4:] # filter away all non-word charac...
0d3a2806c1dea61050e6f13eeb0c9c595f54e02d
614,994
def is_publication(record): """Check if a given record is a published record. Returns: bool: True if the record is a published record, else False. """ return record.json['$schema'].endswith('#/json_schema')
eb44d45f51c8ec04218f0ca750b31c6b4995659c
615,001
def _maybe_expand_batchnorm_weights(model_dict, state_dict, num_splits): """Expands the weights of the BatchNorm2d to the size of SplitBatchNorm. """ running_mean = 'running_mean' running_var = 'running_var' for key, item in model_dict.items(): # not batchnorm -> continue if not ru...
1a0f87bfe019006965656b0c47fd825e00d8b92a
615,003
from pathlib import Path import pickle def read_pickle_dict(filename, folder='C:/Users/Avram/Dropbox (MIT)/MIT' '/Research/Thesis/Sections/mod_studies/'): """Read ptrac data dictionary from pickle file.""" if folder == '': folder = Path.cwd() # set folder ='' to use current dir...
dcf38d34d596a19d9b69a32e48d0f8f1ca10eda4
615,005
def ge(a, b): """Is a >= b?""" if a[0] > b[0]: return True if a[0] < b[0]: return False return a[1] >= b[1]
f54dcc075f305fdb1cf941e7da11dbd4d81bc421
615,010
def active_queues(state): """List the task queues a worker is currently consuming from.""" if state.consumer.task_consumer: return [dict(queue.as_dict(recurse=True)) for queue in state.consumer.task_consumer.queues] return []
f699478913b8b259ebc881bd728a8f0cbd2bf458
615,011
def clean(df): """ Clean the input datframe with a specific strategy. Input df :[pandas.DataFrame] with the raw data Output df :[pandas.DataFrame] with the rows containing na removed """ return df.dropna(axis=0)
8fc0ed6cf3b5fe7026450abf78850548fb891671
615,014
def get_stat( dance, player, stat ): """ Accepts a bin representing the player and a string representing the stat and returns the stat's value. """ return dance[ str(player) ][ str(stat) ]
fb31c3e8930d5d66a237516494aa70eae3bd6c8b
615,015
import pickle def load_keypoints_boxes(vid_path, i): """ Given a video path, with .pkl file included, load the keypoints & boxes """ keypoints = pickle.load(open(vid_path + "keypoints_vid"+str(i)+".pkl", "rb")) keypoints[:, 0, :] = keypoints[:, 0, :]*1.40625 + 280 keypoints[:, 1, :] = keypoints[:, 1, :]*1...
7a3de4d529541ea2bc66801f6b3ad261de146132
615,017
def xyxy2xywh(bbox): """ change bbox to coco format :param bbox: [x1, y1, x2, y2] :return: [x, y, w, h] """ return [ bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1], ]
dd4987b517781f395d42684154445377a791e9ae
615,022
def differentiate(coefficients): """ Calculates the derivative of a polynomial and returns the corresponding coefficients. """ new_cos = [] for deg, prev_co in enumerate(coefficients[1:]): new_cos.append((deg+1) * prev_co) return new_cos
b79d25e5cacc0f11ed5b3250ca80824f3ed02152
615,024
from typing import Iterator def limit( dictset: Iterator[dict], limit: int): """ Returns up to 'limit' number of records """ counter = limit for record in dictset: if counter == 0: return None counter -= 1 yield record
99b4e3437d9daf2bf429a14250db03f3683c03ea
615,030
import re def is_valid_relation(line: str) -> bool: """Check if the line is a valid binary relation annotation.""" regex = r'^R\d+\t\w+ \w+:T\d+ \w+:T\d+$' return re.fullmatch(regex, line) is not None
96ce8d69a18b1ce114acace70d2f5669bf717cd1
615,031
def format_walk_time(walk_time): """ takes argument: float walkTime in seconds returns argument: string time "xx minutes xx seconds" """ if walk_time > 0.0: return str(int(walk_time / 60.0)) + " minutes " + str(int(round(walk_time % 60))) + " seconds" else: return "Walk time is ...
71eada58dc0c047310f599aed5e90f2264ea62ee
615,033
def bitwise_and_2lists(list1, list2): """ Takes two bit patterns of equal length and performs the logical inclusive AND operation on each pair of corresponding bits """ list_len = len(list2) return_list = [None] * list_len for i in range(list_len): return_list[i] = list1[i] & list2[i...
832b9a745eb157d2ae97c620994337c6f44b734e
615,037
import json def json_output(response: dict) -> str: """ Output API response in prettified JSON format Parameters ---------- response : dict Returns ------- str """ return json.dumps(response, indent=2, sort_keys=True)
ee54ed718193be8a788a7141b052736e7e4615a9
615,049
def read_file(file): """ Reads a file. Parameters: file: Path to the file. Returns: The content of the file. """ with open(file, 'r') as f: return f.read()
f5768a704b5568ff9c492ae7a313bf28cd71161c
615,050
def mode_dict(lst): # It returns a dict that contains frequencies of the input. """ >>> mode_dict([3,3,4,4,5,5,6]) {3: 2, 4: 2, 5: 2, 6: 1} >>> mode_dict(["x","y","x"]) {'x': 2, 'y': 1} """ unique_values = {i: 0 for i in list(set(lst))} for i in lst: if i in unique_values.keys():...
6b198476c5f32b7487e314d40ec6782aef44bcd5
615,057
import re def path_contain_regex(path, path_reg=None): """ test if a path string contains regular expression """ if path_reg is None: return True return bool(re.search(path_reg, path))
cd7494904ccdb0154955b92521cdea7c2827de0b
615,061
def get_all_subclasses(klass): """Return all subclasses of a class Use Python introspection to list all subclasses of the given class. This function do not stop to the direct children, but walk the whole inheritance tree. :param klass: the root class to use for introspection :type klass: T ...
056f1cd12255bfb6fff38d25a29923c6be43cc0f
615,063
def asint(val, minimum=None, maximum=None): """Converts a value into an integer :param val: value to convert :param minimum: if specified, this determines the lower boundary for the returned value, defaults to None :param maximum: if specified, this determines the upper boundary for the...
2674f3185f24723cae1c9d55808317df2f286e1e
615,066
import six def check_iterable(value): """Check if a value is iterable (list), but not a string. The checking process is done by trying the `iter` method of Python and matching if the value is a string or not. Parametes --------- value: any Value to be checked if it is iterable. ...
5ea261a32e05b4d1387d15547456b4a52cd28a56
615,075
def amtszeit_ende_isnull(value): """ Template-Filter, der prüft, ob der übergebene Wert None ist. :param value: Der Wert, der überprüft werden soll :type value: any :return: True, wenn der Wert None ist, sonst False. :rtype: bool """ if value is None: return True re...
7ec30ab8d8c9c19b519e8c6e831c3008b93edcfd
615,076
import posixpath import ntpath def as_winpath(location): """ Return a Windows-like path using Windows path separators (backslash or "\") for a `location` path. """ return location.replace(posixpath.sep, ntpath.sep)
abd95002d211d558a3f6cf629d579ecff272f6c9
615,080
def _GenerateDeviceHVInfoStr(hvinfo): """Construct the -device option string for hvinfo dict PV disk: virtio-blk-pci,id=disk-1234,bus=pci.0,addr=0x9 PV NIC: virtio-net-pci,id=nic-1234,bus=pci.0,addr=0x9 SG disk: scsi-generic,id=disk-1234,bus=scsi.0,channel=0,scsi-id=1,lun=0 @type hvinfo: dict @param hvin...
5b7fadf42ee8db8cbae4e782e41230b7a20a8e1d
615,083