content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import six def _prompt(message, result_type=str): """ Non-public function that prompts the user for input by logging 'message', converting the input to 'result_type', and returning the value to the caller. """ return result_type(six.moves.input(message))
333da5d331a011d0f2e5505276bc1c415360c510
608,149
import csv def read_crubadan_language_model(pairs, config, gram_type): """ Read a Crubadan language model for a (language name, ISO code) pair. Args: pairs: a list of (name, code) pairs to construct models for config: model parameters gram_type: what type of gram to use - 'character' or 'word' Returns: list of tuples of ngrams, or None if no language model exists for the given name-ISO pairing """ if gram_type != 'character' and gram_type != 'word': raise ValueError("argument 'gram_type' not 'character' or 'word'") base_path = config['locations']['crubadan-language-model'] table = open(config['locations']['crubadan-directory-index'], encoding='utf8') reader = csv.reader(table) header = next(reader) # discard header row dir_map = {} for row in reader: name = row[0] iso = row[1] directory = row[2].strip() dir_map[(name, iso)] = directory table.close() if gram_type == 'character': file_basename = { 3: "-chartrigrams.txt" }.get(int(config['parameters']['crubadan-char-size'])) else: file_basename = { 1: "-words.txt", 2: "-wordbigrams.txt" }.get(int(config['parameters']['crubadan-word-size'])) all_lms = {} for lang_name, iso_code in pairs: try: this_dir = dir_map[(lang_name, iso_code)] crubadan_code = this_dir.split("_")[1] with open("{}/{}/{}{}".format(base_path, this_dir, crubadan_code, file_basename), encoding='utf8') as f: lines = f.readlines() except (FileNotFoundError, KeyError, IndexError): continue lm = set() for line in lines: if line.strip() == '': continue line = line.split()[:-1] feature = tuple(line[0]) if gram_type == 'character' else tuple(line) lm.add(feature) all_lms[(lang_name, iso_code)] = lm return all_lms
8d3ce5829830f1900b6c54b54bb0584934e43986
284,651
import random def _order_alternatives(alts): """ Pop don't know alts, randomize and append "don't know" alt last """ new_alts = [] no_answer = [] for alt in alts: if alt['no_answer']: no_answer.append(alt) else: new_alts.append(alt) random.shuffle(new_alts) return new_alts + no_answer
757f37194567f6c7432660137e7b9efbd97efe70
518,062
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 Returns ------- tuple DASSH Assembly object One of the two input DASSH Assembly objects with the finer meshing in its pin bundle region int Number of gap edge subchannels per side """ if neighbor is None: # Use active asm parameters on this hex side sc_per_side = 0 if asm.has_rodded: sc_per_side = asm.rodded.n_ring - 1 return asm, sc_per_side else: # Need to compare them # If one asm is rodded and the other isn't, use the rodded asm if asm.has_rodded and not neighbor.has_rodded: return asm, asm.rodded.n_ring - 1 elif not asm.has_rodded and neighbor.has_rodded: return neighbor, neighbor.rodded.n_ring - 1 # If both unrodded, trivial elif not asm.has_rodded and not neighbor.has_rodded: return asm, 0 # If both rodded, need to compare else: sc_per_side = asm.rodded.n_ring - 1 sc_per_side_adj = neighbor.rodded.n_ring - 1 # If both assemblies have same number of sc_per_side: # Choose the spacing with the smaller pin pitch if sc_per_side == sc_per_side_adj: if asm.rodded.pin_pitch < neighbor.rodded.pin_pitch: return asm, sc_per_side else: return neighbor, sc_per_side_adj # Otherwise, choose the meshing with more edge subchannels elif sc_per_side < sc_per_side_adj: return neighbor, sc_per_side_adj else: return asm, sc_per_side
10465f9272abe37cb3a1d448a4ffacd08eed0dc5
614,819
import re def normalize_name(name, dns_1035=False): """ Normalize name :param name: name to normalize :type name: str :param dns_1035: (Optional) use DNS-1035 format, by default False :type dns_1035: bool :return: str -- normalized name """ invalid_delimiters = ' ', '_', '+' invalid_chars = r'[^a-zA-Z0-9\-\.]' if dns_1035: invalid_chars = r'[^a-zA-Z0-9\-]' invalid_delimiters = ' ', '_', '+', '.' for char in invalid_delimiters: name = name.replace(char, '-') return re.sub(invalid_chars, '', name)
d9f8219d3bb9f73e6e294eab0e1d86f0206a9934
492,644
def get_folders(values_dict): """Returns a dict of all the folders in the given value_dict.""" return dict( (item, configs) for (item, configs) in values_dict.iteritems() if item.endswith('/') )
f383e21fedb4ee3510d1360a442fb0bfd32a9fd7
619,965
def str2bool(value): """Parse a string into a boolean value""" return value.lower() in ("yes", "y", "true", "t", "1")
76b078822bac4f706cc6e6b1e730128e0f656185
578,335
def convert_to_bytes(mem_str): """Convert a memory specification, potentially with M or G, into bytes. """ if str(mem_str)[-1].upper().endswith("G"): return int(round(float(mem_str[:-1]) * 1024 * 1024)) elif str(mem_str)[-1].upper().endswith("M"): return int(round(float(mem_str[:-1]) * 1024)) else: return int(round(float(mem_str)))
ae0e80565778d7c6308cb07be30cf3a293fd9733
194,273
def moreThan3Chars(value): """String must contain at least 3 characters.""" if len(value) >= 3: return True return False
a50a923e70a6ed89a094ac2040ac27f0f0273aa5
591,593
def get_thresholds(points=100, power=3) -> list: """Run a function with a series of thresholds between 0 and 1""" return [(i / (points + 1)) ** power for i in range(1, points + 1)]
5238a5d6ecf3f5ef05b4128a047f63e93b20cbfd
232,048
def margin_fee(self, **kwargs): """Query Cross Margin Fee Data (USER_DATA) Get cross margin fee data collection with any vip level or user's current specific data as https://www.binance.com/en/margin-fee GET /sapi/v1/margin/crossMarginData https://binance-docs.github.io/apidocs/spot/en/#query-cross-margin-fee-data-user_data Keyword Args: vipLevel (int, optional): User's current specific margin data will be returned if vipLevel is omitted coin (str, optional) recvWindow (int, optional): The value cannot be greater than 60000 """ return self.sign_request("GET", "/sapi/v1/margin/crossMarginData", kwargs)
f2ca69c13b77fffadf6aa319f1847004ed5615da
23,958
def learn_routem_configs(device, output_config=False): """ Gets the current running config on device Args: output_config ('bool'): Specifies whether the config or path of the config is outputted Raise: None Returns: Config ('dict'): {pid: config} ex.) Config = {'123': 'config'} """ output = device.parse("ps -ef | grep routem")['pid'] configs = {} for pid, info in output.items(): config_data = info['cmd'].split() if len(config_data) == 4: config_data = config_data[2] else: continue if output_config: try: config_data = device.execute("cat {}".format(config_data)) except: raise ValueError("The config file at {} does not exist.".format(config_data)) configs.setdefault(pid, config_data) return configs
7cbc98a273025c8b71a85046abd37b1612f7da76
156,380
def make_param_dict(param_val_dict): """Makes dictionary for VI RandomVariable and parameters. :param param_val_dict: (dict of list) A dictionary with key being parameter names, and values being a list of [RandomVariable, mean_vi_param, scale_vi_param] :return: model_param: (dict of RandomVariable) Keys are variable names, Values are RandomVariable output from VI families. vi_param: (dict) Keys are variable names, Values are dict of loc and scale VI parameters. """ model_param = dict() vi_param = dict() for key, value in param_val_dict.items(): model_param[key] = value[0] vi_param[key] = {"loc": value[1], "scale": value[2]} return model_param, vi_param
887d211c47440094450b3fc1b20451281fb7a2b2
361,539
def _ct_specification_type_to_python_type(specification_type: str) -> str: """ Convert a custom specification type into its python equivalent. :param specification_type: a protocol specification data type :return: The equivalent data type in Python """ python_type = specification_type[3:] return python_type
4a63283b0c888fe31e0d87b18b42d1948633b962
596,987
def qn(namespace, tag_name): """Return the qualified name for a given namespace and tag name This is the ElementTree representation of a qualified name """ return "{%s}%s" % (namespace, tag_name)
1d2d6a5455980f65e615e4dd3f3a2e8323623ea2
375,401
import uuid def CreateShoppingCampaign(client, budget_id, merchant_id): """Creates a shopping campaign with the given budget and merchant IDs. Args: client: an AdWordsClient instance. budget_id: the str ID of the budget to be associated with the shopping campaign. merchant_id: the str ID of the merchant account to be associated with the shopping campaign. Returns: The created Shopping Campaign as a sudsobject. """ campaign_service = client.GetService('CampaignService', 'v201809') campaign = { 'name': 'Shopping campaign #%s' % uuid.uuid4(), # The advertisingChannelType is what makes this a shopping campaign 'advertisingChannelType': 'SHOPPING', # Recommendation: Set the campaign to PAUSED when creating it to stop the # ads from immediately serving. Set to ENABLED once you've added targeting # and the ads are ready to serve. 'status': 'PAUSED', # Set portfolio budget (required) 'budget': { 'budgetId': budget_id }, 'biddingStrategyConfiguration': { 'biddingStrategyType': 'MANUAL_CPC' }, 'settings': [ # All shopping campaigns need a ShoppingSetting { 'xsi_type': 'ShoppingSetting', 'salesCountry': 'US', 'campaignPriority': '0', 'merchantId': merchant_id, # Set to "True" to enable Local Inventory Ads in your campaign. 'enableLocal': True } ] } campaign_operations = [{ 'operator': 'ADD', 'operand': campaign }] campaign = campaign_service.mutate(campaign_operations)['value'][0] print ('Campaign with name "%s" and ID "%s" was added.' % (campaign['name'], campaign['id'])) return campaign
208b2ad37d2fda5ee5b85827029597ed8bc6801b
36,057
def skip_label(what): """Generate a "skip" label name.""" return f"skip {what}"
60c32ec2636cb3c14216b604dfa1987381f52dd5
107,035
def vector_orientation (x, y): """Assigns an orientation to a 2D vector according to the Spanish CTE compass rose.""" if x <= 0.3826 and x >= -0.3826 and y <= 1 and y >= 0.9238: return "North" elif x < 0.8660 and x > 0.3826 and y < 0.9238 and y > 0.5000: return "Northeast" elif x <= 1 and x >= 0.8660 and y <= 0.5000 and y >= -0.3583: return "East" elif x < 0.9335 and x > 0.3090 and y < -0.3583 and y > -0.9510: return "Southeast" elif x <= 0.3090 and x >= -0.3090 and y <= -0.9510 and y >= -1: return "South" elif x < -0.3090 and x > -0.9335 and y < -0.3583 and y > -0.9510: return "Southwest" elif x <= -0.8660 and x >= -1 and y <= 0.5000 and y >= -0.3583: return "West" elif x < -0.3826 and x > -0.8660 and y < 0.9238 and y > 0.5000: return "Northwest" else: return "No orientation"
d23030e759dcb697cd4ed9d1ad8a50ac51204ac7
98,907
def not_implemented(*args, **kwargs) -> dict: """ Default response if pair is good, but no action is taken :return: OpenC2 response message - dict """ return dict( status=501, status_text="command good, no action taken" )
02d0f6e6e4915dd14bbb65b1a29c3ae61798d64d
327,140
def _calculate_precision(value: str) -> int: """Calculate the precision of given value as a string.""" no_decimal_point = value.replace(".", "") no_leading_or_trailing_zeros = no_decimal_point.strip("0") return len(no_leading_or_trailing_zeros)
be97a9ab0484e052d80033d0d26cd1259a9f6237
86,051
def get_cache_key_counter(bound_method, *args, **kwargs): """ Return the cache, key and stat counter for the given call. """ model = bound_method.__self__ ormcache = bound_method.clear_cache.__self__ cache, key0, counter = ormcache.lru(model) key = key0 + ormcache.key(model, *args, **kwargs) return cache, key, counter
241b13b29b3dce0888f2eeb40361dfa03d5f8389
12,964
def _parse_ipv4_number(input_): """Parses a single IPv4 number""" r = 10 try: if len(input_) >= 2: if input_[:2].lower() == "0x": r = 16 input_ = input_[2:] elif input_.startswith("0"): r = 8 input_ = input_[1:] if input_ == "": return 0, False return int(input_, r), r != 10 except ValueError: return None, False
bb2ddbe23a17dfb9ff39c5c4a2a2a60092b1f51a
250,352
def degree_of_item(train): """Calculates degree of items from user-item pairs.""" item_to_deg = {} for pair in train: _, item = pair if item in item_to_deg: item_to_deg[item] += 1 else: item_to_deg[item] = 1 return item_to_deg
9f44848b446ffded46c0ceb2aff7e2540cf9f346
318,592
def hashdigit(cpf, position): # type: (str, int) -> int """ Will compute the given `position` checksum digit for the `cpf` input. The input needs to contain all elements previous to `position` else computation will yield the wrong result. """ val = sum(int(digit) * weight for digit, weight in zip(cpf, range(position, 1, -1))) % 11 return 0 if val < 2 else 11 - val
f6984e209b2061c1c7af41da3704ddee77e04d45
186,198
def get_ip_label(ip): """ Format ip address of the node and convert into label The label will consist of hexadecimal values of the ip. Each octet will be converted into it's corresponding hex value and the whole label will be saved as an 8 character string. For example, 10.255.0.192 would have a label of 0AFF00C0 """ ip_label = "" for octet in ip.split("."): hex_val = hex(int(octet))[2:] if len(hex_val) == 1: hex_val = "0" + hex_val ip_label += hex_val return ip_label
ee39aa2d5ba20011efe971e2da31a9dd57560e52
219,090
import itertools def group_on_delimiter(iterable, delimiter): """Group elements separated by delimiter into chunks. group(['a', 'b', '', 'c', 'd', '', 'e'], '') => [['a', 'b'], ['c', 'd'], ['e']] """ return [list(g) for is_delimiter, g in itertools.groupby(iterable, lambda el: el == delimiter) if not is_delimiter]
1d4c89b33c8e6ff7b682acddbd05218a44323de1
605,099
import string def subfig(fig,xloc=0,yloc=1,fontsize=16,**plt_kwargs): """ Add subfigure labels to axes in figure using axes coordinates Parameters: fig: Figure on which to apply labels xloc: X location for label, in axes coordinates (0-1) yloc: Y location for label, in axes coordinates (0-1) fontsize: Font size for axes labels Returns: fig: Figure with labels applied """ axes = fig.get_axes() # Get all axes in figure letters = list(string.ascii_lowercase) for x in range(len(axes)): axes[x].text(xloc, yloc,'('+letters[x]+')',transform=axes[x].transAxes, fontsize=fontsize,va='top',**plt_kwargs) return(fig)
fc0d45fab52ebd250bf1590333655c8543ffbb77
362,458
def point_str(point) -> str: """ Convert a point to a string """ # some string conversion functions (since looking up strings in a dict is pretty fast performance-wise) return str(point[0]) + ";" + str(point[1])
39ea3fbd51fa179941fd36598b508feae4e5a57a
234,914
import torch def log1p_safe(x): """The same as torch.log1p(x), but clamps the input to prevent NaNs.""" x = torch.as_tensor(x) return torch.log1p(torch.min(x, torch.tensor(33e37).to(x)))
5f1f4ce93dd2192bc6722b183ddec276788c8070
129,615
from typing import Counter def count_pileups(bam, contig, start, end): """Returns the number of piled-up bases between the given start and end positions in the given contig.""" raw_counts = Counter({x.pos: x.n for x in bam.pileup(contig, start, end) if start <= x.pos <= end}) return [{"pos": pos, "count": raw_counts[pos]} for pos in range(start, end)]
7fe2335f6fbd37d0eb31ddff0ef1f6a0dc17b622
458,177
def actions(self): """ Returns all the action objects whether enabled or disabled. """ return self.__actions
9eec5e6df3788259230cceb63f9baa0faa868cc8
108,208
def list_output_tensors(node): """ Since Tensorflow 1.14, sometimes the node.output_tensors may not be a list, though the output_tensors is plural. """ return [node.output_tensors] if hasattr(node.output_tensors, 'dtype') else node.output_tensors
f1e0a5fe304c25eec25936b9a200c8797ace389f
183,467
def get_gradient_values(gradient_img, multiplier=1): """ Given the image gradient returns gradient_alpha_rgb_mul and one_minus_gradient_alpha. These pre-calculated numbers are used to apply the gradient on the camera image Arguments: gradient_img (Image): Gradient image that has to applied on the camera image multiplier (float): This decides what percentage of gradient images alpha has to be applied. This is useful in fading feature. Returns: (tuple): gradient_alpha_rgb_mul (Numpy.Array) gradient_img * gradient_alpha value one_minus_gradient_alpha (Numpy.Array) (1 - gradient_alpha) """ (height, width, _) = gradient_img.shape gradient_alpha = (gradient_img[:, :, 3] / 255.0 * multiplier).reshape(height, width, 1) gradient_alpha_rgb_mul = gradient_img * gradient_alpha one_minus_gradient_alpha = (1 - gradient_alpha).reshape(height, width) return gradient_alpha_rgb_mul, one_minus_gradient_alpha
507ea8e1f6b03bc42f77453835ea55ee9a525bca
273,672
def get_search_url(search, page): """ Create the search URL according to search params and page number. """ url = (f"https://hub.docker.com/api/content/v1/products/" + f"search?architecture=arm,arm64,386,amd64&operating_system=linux" + f"&page={page}&page_size=100&q={search}&type=image") return url
f482170f3cbfaa9d9738411394702c45ed587350
154,436
def json_encode_datetime(d): """Encoder for datetimes (from module datetime).""" return {"datetime" : d.strftime("%Y-%m-%d %H:%M:%S.%f"), "tzinfo" : d.tzinfo}
c800ab344601a26f69bcebc7a7bd8ca40acadaa8
561,750
def get_page_image_url(page_ann, vol_meta): """Return image url of the page Args: page_ann (dict): page annotation vol_meta (dict): volume meta data Returns: str: image url of page """ cur_image_grp_id = "" cur_image_grp_id = vol_meta["image_group_id"] image_ref = page_ann["reference"] image_url = f"https://iiif.bdrc.io/bdr:{cur_image_grp_id}::{image_ref}/full/max/0/default.jpg" return image_url
becabcbdf613e0cc0bffe6c340e6dfa71d204927
189,806
def _common_length_of(l1, l2=None, l3=None): """ The arguments are containers or ``None``. The function applies ``len()`` to each element, and returns the common length. If the length differs, ``ValueError`` is raised. Used to check arguments. OUTPUT: A tuple (number of entries, common length of the entries) EXAMPLES:: sage: import sage.geometry.polyhedron.misc as P sage: P._common_length_of([[1,2,3],[1,3,34]]) (2, 3) """ args = []; if l1 is not None: args.append(l1) if l2 is not None: args.append(l2) if l3 is not None: args.append(l3) length = None num = 0 for l in args: for i in l: num += 1 length_i = len(i) if length is not None and length_i != length: raise ValueError("Argument lengths differ!") length = length_i return num, length
3a3f2ecfb541691d2ca833b14f9c8761f92584af
640,761
import json def jsonDecode(jsonString): """Takes a json String and converts it into a Python object such as a list or a dict. If the input is not valid json, a string is returned. Args: jsonString (str): The JSON string to decode into a Python object. Returns: dict: The decoded Python object. """ return json.loads(jsonString)
ab5fbd22089a80dc13e413986df0ec6de4c85b82
478,818
def getBlockNumbersForRegionFromBinPosition(regionIndices, blockBinCount, blockColumnCount, intra): """ Gets the block numbers we will need for a specific region; used when the range to extract is sent in as a parameter Args: regionIndices (array): Array of ints giving range blockBinCount (int): The block bin count of the matrix blockColumnCount (int): The block column count of the matrix intra: Flag indicating if this is an intrachromosomal matrix Returns: blockSet (set): A set of blocks to print """ col1 = int(regionIndices[0] / blockBinCount) col2 = int((regionIndices[1] + 1) / blockBinCount) row1 = int(regionIndices[2] / blockBinCount) row2 = int((regionIndices[3] + 1) / blockBinCount) blocksSet = set() # print(str(col1)+"\t"+str(col2)+"\t"+str(row1)+"\t"+str(row2)) for r in range(row1, row2+1): for c in range(col1, col2+1): blockNumber = r * blockColumnCount + c blocksSet.add(blockNumber) if intra: for r in range(col1, col2+1): for c in range(row1, row2+1): blockNumber = r * blockColumnCount + c blocksSet.add(blockNumber) # print(str(blocksSet)) return blocksSet
065630ade7cf5b5ffc86b05fd80bcd890a0eed76
621,802
import json def output_fn(predictions, content_type): """Post-process and serialize model output to API response""" print('result:', predictions) res = predictions.cpu().numpy().tolist() return json.dumps(res)
f0c22dcd7e5a447b38afd141d6de7d16028fc670
623,646
from typing import List from typing import Optional def determine_root_gpu_device(gpus: List[int]) -> Optional[int]: """ Args: gpus: non-empty list of ints representing which gpus to use Returns: designated root GPU device id """ if gpus is None: return None assert isinstance(gpus, list), "gpus should be a list" assert len(gpus) > 0, "gpus should be a non empty list" # set root gpu root_gpu = gpus[0] return root_gpu
c988e01573b242ab106ef4ef406f0ba88f7533c1
601,277
def posteriors(likelihoods, priors): """Calculate posterior probabilities given priors and likelihoods. Usage: probabilities = posteriors(likelihoods, priors) likelihoods is a list of numbers. priors is a list of probabilities. Returns a list of probabilities (0-1). """ # Check that there is a prior for each likelihood if len(likelihoods) != len(priors): raise ValueError("Lists not equal lengths.") # Posterior probability is defined as prior * likelihood return [l * p for l, p in zip(likelihoods, priors)]
fc47c102d27f9d45dc1b38d58704255251961b6d
214,622
def filter_unmodified_overrides(pkg_info, overrides): """ Given a list of overrides from a particular package, return a copy of the list that's filtered so that any overrides that have not been changed from the underlying file are removed. """ for override in overrides: result = pkg_info.override_diff(override, 1) if result.is_empty: overrides.remove(override) return overrides
bbb4076af863ed2594696714c4ad5ad9a5c1233b
508,071
def toContigScafMap(scaffToContigListDict): """ Transforms the input dictionary (key -> list of items) into the inverse dictionary (item -> key). To each item (contig) only one key (scaffold) exists. @param scaffToContigListDict: map: scaffold -> list of contigs @return: map: contig name -> scaffold name """ contigToScaffDict = dict() for scaff in scaffToContigListDict: for contig in scaffToContigListDict[scaff]: assert contig not in contigToScaffDict, str('Contig: ' + contig + ' is not allowed to be twice in the directory!') contigToScaffDict[contig] = scaff return contigToScaffDict
257baef5bd783cd693465c6a9ee11161667ac0ee
280,423
def get_mask(source, source_lengths): """ Args: source: [B, C, T] source_lengths: [B] Returns: mask: [B, 1, T] """ B, _, T = source.size() mask = source.new_ones((B, 1, T)) for i in range(B): mask[i, :, source_lengths[i]:] = 0 return mask
8466ff5113ca22488b4218f86c43bfea248197d1
24,855
def datt3(b3, b5, b8a): """ Vegetation Index proposed by Datt 3 (Datt, 1998). .. math:: DATT3 = b8a / (b3 * b5) :param b3: Green. :type b3: numpy.ndarray or float :param b5: Red-edge 1. :type b5: numpy.ndarray or float :param b8a: NIR narrow. :type b8a: numpy.ndarray or float :returns DATT3: Index value .. Tip:: Datt, B. 1998. Remote sensing of chlorophyll a, chlorophyll b, \ chlorophyll a + b, and total carotenoid content in eucalyptus leaves. \ Remote Sensing of Environment, 66, 111-121. \ doi:10.1016/S0034-4257(98)00046-7. """ DATT3 = b8a / (b3 * b5) return DATT3
41bdcf06b049a36e5673f884762b488f42213f5b
462,215
def isInside(point, leftTop, rightBottom): """ return True if point is in the rectangle define by leftTop and rightBottom """ if not (leftTop[0] < point[0] < rightBottom[0]): return False if not (leftTop[1] < point[1] < rightBottom[1]): return False return True
f9727e5ac11011ea45d05d5db1a439848c882481
650,229
def dicts_equal(dictionary_one, dictionary_two): """ Return True if all keys and values are the same between two dictionaries. """ return all( k in dictionary_two and dictionary_one[k] == dictionary_two[k] for k in dictionary_one ) and all( k in dictionary_one and dictionary_one[k] == dictionary_two[k] for k in dictionary_two )
abd7d1d89c034c8f57b34b3994f2f8a32b63987e
123,080
def defaultargs(options): """Produce a dictionary of default arguments from a list of options tuples Parameter tuple[] - (flag, default, docstring) tuples describing each flag Return dict - {flag: default} for each option in input """ config = {} for longname, default, doc in options: config[longname] = default return config
fe6a6c11aad99a95491507910a8dccb63139a785
283,666
import collections def picard_idxstats(picard, align_bam): """Retrieve alignment stats from picard using BamIndexStats. """ opts = [("INPUT", align_bam)] stdout = picard.run("BamIndexStats", opts, get_stdout=True) out = [] AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"]) for line in stdout.split("\n"): if line: parts = line.split() if len(parts) == 2: _, unaligned = parts out.append(AlignInfo("nocontig", 0, 0, int(unaligned))) elif len(parts) == 7: contig, _, length, _, aligned, _, unaligned = parts out.append(AlignInfo(contig, int(length), int(aligned), int(unaligned))) else: raise ValueError("Unexpected output from BamIndexStats: %s" % line) return out
6ee5d38b272e4ae05a3df5d02230509bb427133b
64,923
import json def lerArquivoJSON(caminho_arquivo): """ Retorna conteúdo de um arquivo JSON de comandos SQL, delegando tratamento para bloco de função reservado :param caminho_arquivo: :return: data (JSON) """ with open(caminho_arquivo, "r") as read_file: data = json.load(read_file) if caminho_arquivo is not None: return data else: return None
2cfdd872295a244fb2a83f6b287a954e806da829
651,251
def _slugify(doi): """Generate a name from DOI using the same approach as SciHub.""" return doi.replace('/', '@')
f41552f5810ef13995db4edff90120400c7ed052
473,169
def _ceildiv(x, y): """Rounds `x/y` to next largest integer.""" return -int(-x // y)
7430a8148424c170cee225571eeb3574c9a9c237
293,409
from pathlib import Path import json def template_json(keyboard): """Returns a `keymap.json` template for a keyboard. If a template exists in `keyboards/<keyboard>/templates/keymap.json` that text will be used instead of an empty dictionary. Args: keyboard The keyboard to return a template for. """ template_file = Path('keyboards/%s/templates/keymap.json' % keyboard) template = {'keyboard': keyboard} if template_file.exists(): template.update(json.load(template_file.open(encoding='utf-8'))) return template
7949c78a164abfb04ef1b46caaf0897acac88bfc
61,846
def b_to_s(b: bytes) -> str: """convert bytes to string :param b: input bytes :type b: bytes :return: output string :rtype: str """ s = b.decode('utf8') return s
98c4abf3d78e86f5e1b00459135e65d4ec94e030
336,825
def filter_data(data: dict, keys: list) -> dict: """Returns a dictionary with only key/value pairs where the key is in the keys list""" return {k: data[k] for k in keys if k in data}
78dc222b3f6af7d252a01f6d9b5457f14656a477
428,932
def my_kinetic_energy(vel, mass): """ Calculate total kinetic energy. Args: vel (np.array): particle velocities, shape (natom, ndim) mass (float): particle mass Return: float: total kinetic energy """ k = 0.0 for i in vel: k += sum(0.5 * mass * i ** 2) return k
75917ef0fa698539db6207c2b297ad02acea1026
222,565
def get_metric_scores(ground_truth, simulation, measurement, metric, measurement_kwargs={}, metric_kwargs={}): """ Function to combine measurement and metric computations :param ground_truth: pandas dataframe of ground truth :param simulation: pandas dataframe of simulation :param measurement: measurement function :param metric: metric function :return: metric computation for measurements calculated from gold and simulation """ print("Calculating {} for {}".format(metric.__name__, measurement.__name__)) measurement_on_gt = measurement(ground_truth, **measurement_kwargs) measurement_on_sim = measurement(simulation, **measurement_kwargs) return measurement_on_gt, measurement_on_sim, metric(measurement_on_gt, measurement_on_sim, **metric_kwargs)
4087e60ce0578d11756f449e776e01ee81b6e4ac
696,025
def duration(first, last): """Evaluate duration Parameters ---------- first : int First timestamp last : int Last timestamp Returns ------- str Formatted string """ ret = '' diff = last - first if diff <= 0: return '' mm = divmod(diff, 60)[0] if mm == 0: # don't bother unless we have some minutes return '' hh, mm = divmod(mm, 60) if hh > 24: dd, hh = divmod(hh, 24) ret = "%2dd %02dh" % (dd, hh) elif hh > 0: ret = "%2dh %02dm" % (hh, mm) else: ret = "%02dm" % (mm) return ret
d368f18cb574dadab3794e3816410c9d8dcb07ee
636,643
def _legendre(a, p): """ Returns the legendre symbol of a and p assuming that p is a prime i.e. 1 if a is a quadratic residue mod p -1 if a is not a quadratic residue mod p 0 if a is divisible by p Parameters ========== a : int The number to test. p : prime The prime to test ``a`` against. Returns ======= int Legendre symbol (a / p). """ sig = pow(a, (p - 1)//2, p) if sig == 1: return 1 elif sig == 0: return 0 else: return -1
3349f3154fdb6618a4366acf1fffd4179bced25a
136,488
def parse_dir(save_dir): """Parses the save directory to get only the directory (without the file name) to save the pictures to :param save_dir: save directory string :return: save directory string without the file name """ dir_list = save_dir.split('/') dir = '' if len(dir_list) == 1: dir_list = dir_list[0].split('\\') if not(len(dir_list) == 1): for elem in dir_list[:-1]: dir += elem + '/' return dir
d40ff6ff03859654210bce5ed67d33f25e07a467
660,502
def difference(actual, expected): """ Returns strings describing the differences between actual and expected sets. Example:: >>> difference({1, 2, 3}, {3, 4, 5}) ('; added {1, 2}', '; removed {4, 5}') >>> difference({1}, {1}) ('', '') :param set actual: the actual set :param set expected: the expected set """ added = actual - expected if added: added = f'; added {added}' else: added = '' removed = expected - actual if removed: removed = f'; removed {removed}' else: removed = '' return added, removed
cd0d20645effe52df995c6bb6d04eecd6be06e12
404,202
def lambda_handler(event, context): """Sample pure Lambda function Parameters ---------- event: dict, required Choice output { "JobName": "your_job_name", "JobRunId": "jr_uuid", "JobRunState": "SUCCEEDED", "StartedOn": "2021-09-20T20:30:55.389000+00:00", "CompletedOn": "2021-09-20T20:32:51.443000+00:00", "ExecutionTime": 106 } context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ Final status of the execution """ output = { "message": "successful glue job execution" } return output
50b61531dc1d28965148429128d4f1b840d2cc00
379,632
def _times_to_steps(ts, num_trotter_slices): """ Based on the requested times `ts`, calculate Trotter step numbers at which (subsystems of) evolved states need to be saved. .. doctest:: >>> _times_to_steps([10, 25, 30], 100) ([33, 83, 100], 0.3) >>> _times_to_steps([8, 26, 19], 80) ([25, 80, 58], 0.325) Args: ts (list[float]): The times for which the evolution should be computed and the state of the full system or a subsystem returned (i.e. it's reduced density matrix (for now only works with method='mpo'. If the method is not mpo, omit subsystems)). The algorithm will calculate the evolution using the given number of Trotter steps for the largest number in ts. On the way there it will store the evolved states for smaller times. NB: Beware of memory overload since len(t) mpnum.MPArrays will be stored num_trotter_slices (int): Number of Trotter slices to be used for the largest t in ts. Returns: tuple[list[int], float]: step numbers, tau = maximal t / num_trotter_slices """ tau = max(ts) / num_trotter_slices step_numbers = [int(round(t / tau)) for t in ts] return step_numbers, tau
f18e0ef0ecbcbbfa28a1f8ea663f8161c05a0f6c
233,328
import codecs def _int_to_bytes(i): """ Converts the given int to the big-endian bytes """ h = hex(i) if len(h) > 1 and h[0:2] == "0x": h = h[2:] # need to strip L in python 2.x h = h.strip("L") if len(h) % 2: h = "0" + h return codecs.decode(h, "hex")
5fdfdeac50d13e26385277c9cef12b4ed393a08b
56,506
def bonus_letter(puzzle: str, view: str, letter: str) -> bool: """Return True iff the letter is a consonant that appears in the puzzle but not view. >>> bonus_letter('apple', 'a^^le', 'p') True >>> bonus_letter('banana', 'ba^a^a', 'b') False >>> bonus_letter('apple', '^pp^e', 'a') False """ if letter in puzzle and letter not in view: if letter not in ('a', 'e', 'i', 'o', 'u'): return True return False
6255fc1d39055f7d28b4027ca697bb0ca6a4e174
458,203
def arithmetic_mean(samples): """Computes the arithmetic mean of a set of samples. """ return float(sum(samples)) / float(len(samples))
d71cd1782a1c30e0bd6579079a3a56e5c47da764
345,100
def level_list(root): """Get full level order traversal of binary tree nodes. Example: >>> from leetcode_trees import binarytree >>> tree = binarytree.tree_from_list([5,1,4,None,None,3,6]) >>> binarytree.print_tree(tree) ___5___ 1 _4_ 3 6 >>> print(binarytree.level_representation(tree)) [[5], [1, 4], [None, None, 3, 6]] The list of lists contain TreeNode objects. """ curr_level = [root] levels = [curr_level] next_level = [] while True: for node in curr_level: if node is not None: next_level.append(node.left) next_level.append(node.right) else: next_level.append(None) next_level.append(None) if not all(n is None for n in next_level): levels.append(next_level) curr_level = next_level next_level = [] else: break return levels
f53c14c5b195a6d0b5364c5258bd2576f1fabe66
640,564
def fibonacci(n): """Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, ... """ if n <= 1: return n a = 0 b = 1 c = 1 for i in range(2, n): a = b b = c c = a + b return c
275e6594e8662df9d1a5661344ffa3c1e28a7889
261,778
def load_model(plugin, model, weights, device): """ Load OpenVino IR Models Input: Plugin = Hardware Accelerator IE Core Model = model_xml file Weights = model_bin file Output: execution network (exec_net) """ # Read in Graph file (IR) to create network net = plugin.read_network(model, weights) # Load the Network using Plugin Device exec_net = plugin.load_network(network=net, device_name=device) return net, exec_net
f9fa99f2e111d5aa4a1b9f24774f049e55138d73
209,081
def energy_overlap(sp1, sp2): """ Calculate the overlap energy range of two spectra, i.e. lower bound is the maximum of two spectra's minimum energy. Upper bound is the minimum of two spectra's maximum energy Args: sp1: Spectrum object 1 sp2: Spectrum object 2 Returns: Overlap energy range """ overlap_range = [max(sp1.x.min(), sp2.x.min()), min(sp1.x.max(), sp2.x.max())] return overlap_range
4e0f08f3be1e7c8fc39805bc9d16319c1f61f3a4
113,435
def GetFC(FCFCS): """ Return the FC of the FCFCS """ return FCFCS[0]
8329ada301193b9acc69d52acfcd7801df439b5b
433,899
def strip_suffix(s: str, suffix: str) -> str: """Strip the given suffix, if present, and return the resulting string.""" return s[: -len(suffix)] if s.endswith(suffix) else s
ea9f31e5fd15b222f01be767db8a64d008d00812
327,535
def make_list_template_element(title, subtitle=None, image=None, resource_id=None, action=None, i18n_titles=None, i18n_subtitles=None, i18n_images=None, i18n_resource_ids=None): """ create carousel list template a Row. reference - `Common Message Property <https://developers.worksmobile.com/jp/document/100500805?lang=en>`_ """ content = { "title": title } if subtitle is not None: content["subtitle"] = subtitle if image is not None: content["image"] = image if resource_id is not None: content["resourceId"] = resource_id if action is not None: content["action"] = action if i18n_titles is not None: content["i18nTitles"] = i18n_titles if i18n_subtitles is not None: content["i18nSubtitles"] = i18n_subtitles if i18n_images is not None: content["i18nImages"] = i18n_images if i18n_resource_ids is not None: content["resourceIds"] = i18n_resource_ids return content
46665f7c91a9fc4525899279da3318494e0991a9
459,253
def get_brand_tweets(dataframe, brand): """ Filters out all tweets that dont belong to a specific brand :param dataframe: dataframe from kaggle with all the tweets. :param brand: brand that we want to keep. """ return dataframe[dataframe["author_id"] == brand]
2d28351ce61b574582c812f8dbad29511ba34897
537,787
def z_function(text): """ Z Algorithm in O(n) :param text: text string to process :return: the z_array, where z_array[i] = length of the longest common prefix of text[i:] and text """ n = len(text) z_array = [0] * n l = r = 0 for i in range(1, n): z = z_array[i - l] if i + z >= r: z = max(r - i, 0) while i + z < n and text[z] == text[i + z]: z += 1 l, r = i, i + z z_array[i] = z z_array[0] = n return z_array
ed0552ca771865644b2df59c80bc3b785578fab5
604,940
async def pause_(self, ctx): """Pause the currently playing song.""" vc = ctx.voice_client if not vc or not vc.is_playing(): return await ctx.send('I am not currently playing anything!', delete_after=20) elif vc.is_paused(): return vc.pause() await ctx.send(f'**`{ctx.author}`**: Paused the song!')
47271577c1aec1176f33ec56b8285787e1609b0b
602,849
def element_name(element_path): """ Gives the last element in an xpath :param element_path: An xpath with at least one '/' """ return element_path[element_path.rfind('/') + 1:]
975b99d9fc30141e630c31a2ec310f827685b383
286,726
def cli_method(func): """Decorator to register method as available to the CLI.""" func.is_cli_method = True #setattr(func, 'is_cli_method', True) return func
0eb80215e37b7b9290732dc1a8a2a33bbfb647ed
59,565
def findAllInfectedRelationships(tx): """ Method that finds all INFECTED relationships in the data base :param tx: is the transaction :return: a list of relationships """ query = ( "MATCH (n1:Person)-[r:COVID_EXPOSURE]->(n2:Person) " "RETURN ID(n1) , r , r.date , r.name , ID(n2);" ) results = tx.run(query).data() return results
0b5e35d98ae8a91973e60c68b772e159294db751
690,897
def combine_two_lists_no_duplicate(list_1, list_2): """ Method to combine two lists, drop one copy of the elements present in both and return a list comprised of the elements present in either list - but with only one copy of each. Args: list_1: First list list_2: Second list Returns: The combined list, as described above """ additional_unique_elements_list_2 = [i for i in list_2 if i not in list_1] return list_1 + additional_unique_elements_list_2
4caa2d3494eeef61d502bc898433d04362e81f39
690,327
def _make_credentials_property(name): """Helper method which generates properties. Used to access and set values on credentials property as if they were native attributes on the current object. Args: name: A string corresponding to the attribute being accessed on the credentials attribute of the object which will own the property. Returns: An instance of `property` which is a proxy for the `name` attribute on the credentials attribute of the object. """ def get_credentials_value(self): return getattr(self.credentials, name) def set_credentials_value(self, value): setattr(self.credentials, name, value) return property(get_credentials_value, set_credentials_value)
17692cb4cf0ea072d4345d60106bb04c0ad030bd
651,517
def extract_text(element): """ Return *text* attribute of an implied element if available. """ if element is not None: return element.text else: return None
b17c43e1d816a56f43ba27af5bc4a626f8b66181
557,293
import re def valid_url(url): """Return `True` if URL is valid.""" return re.match(r'https?://\S+', url) is not None
05afb03fc96679dd361e799f86d85d8a343cdf18
196,251
def _gcd(a, b): """Computes the greatest common divisor of two numbers using Euclid's Algorithm. Example: >>> _gcd(30, 18) 6 Args: a (int): The first parameter. b (int): The second parameter. Returns: int: The greatest common divisor of a and b. """ while b: a, b = b, a % b return a
0e3ea9b27e22651875c48ae3660ab681117d9dc5
477,896
def _getControllerWalkNodes(tag): """Get the node conneted to a controllers tag as a controller object Arguments: tag (controller list): Maya's controller tag Returns: dagNode: The list of controller objects """ nodes = [] if not isinstance(tag, list): tag = [tag] for t in tag: cnx = t.controllerObject.connections() if cnx: nodes.append(cnx[0]) return nodes
c1e79c8d323931959de3ea7f1882d856ed41eb81
314,267
def group_by_key(param_list, key): """ Return a dictionary of the form {key_value: [param_list]} where the list of param sets is broken up according to common key values >>> param_list = [{'a':0, 'b':1, 'c':2, 'd':3, 'name':'counter'}, {'a':0, 'b':1, 'c':3, 'name':'jumper'}, {'a':0, 'b':'beta', 'name':'greek'}] >>> g = group_by_key(param_list, 'a') >>> for k in get_sorted_keys(g): print(k, len(g[k])) 0 3 None 0 >>> g = group_by_key(param_list, 'b') >>> for k in get_sorted_keys(g): print(k, len(g[k])) 1 2 None 0 beta 1 >>> g = group_by_key(param_list, 'd') >>> for k in get_sorted_keys(g): print(k, len(g[k])) 3 1 None 2 >>> g = group_by_key(param_list, 'name') >>> for k in get_sorted_keys(g): print(k, len(g[k])) None 0 counter 1 greek 1 jumper 1 """ group = {'None':[]} for p in param_list: if key in p: val = str(p[key]) if val in group: group[val].append(p) else: group[val]=[p] else: group['None'].append(p) return group
90fb9857385b19d72bd723eb5207f0a577b99434
397,274
import math def trunc_gaussmf(x, parameters): """ Gaussian Truncated fuzzy membership function :param x: data point :param parameters: a list with 2 real values (mean and variance) and 2 limits :return: the membership value of x given the parameters """ mean = parameters[0] var = parameters[1] lower_bound = parameters[2] upper_bound = parameters[3] coordinate_index = parameters[4] value = x[coordinate_index] if (value >= lower_bound) & (value <= upper_bound) : return math.exp((-(value - mean)**2)/(2 * var**2)) else: return 0
a8160968379f626378774137d59662af5527110c
344,199
import json def LoadJSON(json_string): """Loads json object from string, or None. Args: json_string: A string to get object from. Returns: JSON object if the string represents a JSON object, None otherwise. """ try: data = json.loads(json_string) except ValueError: data = None return data
598c9b4d5e358a7a4672b25541c9db7743fcd587
709,634
def get_domain_id_field(domain_table): """ A helper function to create the id field :param domain_table: the cdm domain table :return: the id field """ return domain_table + '_id'
5805da82b4e57d14d4105d92a62cf4b5cc4bc3f2
5,711
def get_form_field_chart_url(url, field): """Append 'field_name' to a given url""" return u'%s?field_name=%s' % (url, field)
239147fdac8d2f953aba3152b1e709b0057207d5
216,978
import time def timef(fun): """ decorator to record execution time of a function """ def wrapper(*args,**kwargs): start = time.time() res = fun(*args,**kwargs) end = time.time() print(f'Function {fun.__name__} took {end-start}s\n') return res return wrapper
17e2ce5caf7e32b74306c57a8f8d03afb4a92272
281,106
import string def hex_escape(bin_str): """ Hex encode a binary string """ printable = string.ascii_letters + string.digits + string.punctuation + ' ' return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)
f934aa66f3821272f89aafdf12e1343b297b3370
191,584
from typing import List def attributes_to_list(attributes: str) -> List[str]: """Transform a string with potentially multiple attributes to a list of the attributes. Args: attributes: Attributes as a single string. Returns: List of attributes. """ attributes_list = attributes.split(",") attributes_list = [venue.strip(" ") for venue in attributes_list] return attributes_list
011a9cdeaba4830ea931e5cc67040111d4abb557
196,032
def filter_images_by_tags(annotations_df, include=None, exclude=None): """Filter images on tags :param annotations_df: pandas DataFrame of project annotations :type annotations_df: pandas.DataFrame :param include: include images with given tags :type include: list of strs :param exclude: exclude images with given tags :type exclude: list of strs :return: filtered image names :rtype: list of strs """ df = annotations_df[annotations_df["type"] == "tag"] images = set(df["imageName"].dropna().unique()) if include: include_images = set( df[df["tag"].isin(include)]["imageName"].dropna().unique() ) images = images.intersection(include_images) if exclude: exclude_images = set( df[df["tag"].isin(exclude)]["imageName"].dropna().unique() ) images = images.difference(exclude_images) return list(images)
9164b1452dd66145ecd3b1ef4089123330ef04d5
590,218
def truncate(text, max_len, fill="..."): """ Truncate given text to a given maximum length. Parameters ---------- text : str The text to truncate. max_len : int The maximum allowed length for `text`. If `text` is longer than `max_len` it will be shortened, otherwise it will remain unchanged. fill : str, optional The string that should be displayed at the end of the truncated text to indicate truncation. If `max_len` is too short, the fill may be omitted or changed. Defaults to `...`. Returns ------- str The truncated (or unchanged) text, of length no greater than `max_len` (including any filling added at the end). """ if max_len <= 0: return "" if max_len < len(fill): fill = "~" if len(text) > max_len: end_len = max(0, max_len - len(fill)) text = text[:end_len] + fill try: assert len(text) <= max_len except AssertionError: raise AssertionError("{text} {max_len}".format(**locals())) return text
8bc0a033b720bba3391fd14eb043c67efc4d7afa
432,641
def is_subsequence(short_seq, long_seq): """Is short_seq a subsequence of long_seq.""" if not short_seq: return True pos = 0 for x in long_seq: if pos == len(short_seq): return True if short_seq[pos] == x: pos += 1 if pos == len(short_seq): return True return False
cd72675cd423b5ae60f6286575ee3e319bf9c72e
170,023
def add_vec(pos, vec, dt): """add a vector to a position""" px, py, pz = pos dx, dy, dz = vec px += dx * dt py += dy * dt pz += dz * dt p = (px, py, pz) return p
891bd5a1535fdad58957083369661eff68ab6c25
378,729
import requests import json def get_stock(symbol): """ Fetches stock information from the IEX API. :param symbol: The trading symbol or ticker, e.g. "AAPL" for Apple Inc. """ url = 'https://api.iextrading.com/1.0/stock/' + symbol + '/batch' print(url) params = { 'types': 'quote' } try: req = requests.get(url, params=params) print(req.text) stock = req.json() stock_quote = {'quote': stock['quote']} return stock_quote except requests.exceptions.RequestException as re: print('%s (%s)' % (re.strerror, type(re))) except json.decoder.JSONDecodeError as jde: print('%s (%s)' % (jde.msg, type(jde)))
2c7a8a858851dab42c2dac318777a4125aa0be4d
194,108
def format_seconds(total_seconds: int) -> str: """Format a count of seconds to get a [H:]M:SS string.""" prefix = '-' if total_seconds < 0 else '' hours, rem = divmod(abs(round(total_seconds)), 3600) minutes, seconds = divmod(rem, 60) chunks = [] if hours: chunks.append(str(hours)) min_format = '{:02}' else: min_format = '{}' chunks.append(min_format.format(minutes)) chunks.append('{:02}'.format(seconds)) return prefix + ':'.join(chunks)
c0f79b7f45c32589537b5dbf51a95b4811c50417
12,570