content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def CommandInGoEnv(input_api, output_api, name, cmd, kwargs): """Returns input_api.Command that wraps |cmd| with invocation to go/env.py. env.py makes golang tools available in PATH. It also bootstraps Golang dev environment if necessary. """ if input_api.is_committing: error_type = output_api.PresubmitError else: error_type = output_api.PresubmitPromptWarning full_cmd = [ 'vpython', input_api.os_path.join(input_api.change.RepositoryRoot(), 'go', 'env.py'), ] full_cmd.extend(cmd) return input_api.Command( name=name, cmd=full_cmd, kwargs=kwargs, message=error_type)
7d71c09f0621cfa25d6a7316a2ba1fcfbbc1fb91
690,782
import math def sigmoid(x, derivative=False): """Sigmoid activation function.""" if derivative: return x * (1 - x) return 1 / (1 + math.e ** (-x))
f650ea7fd214f721c246e51559dfee9341d21be7
690,787
def _osfify_urls(data): """ Formats `data` object with OSF API URL Parameters ---------- data : object If dict with a `url` key, will format OSF_API with relevant values Returns ------- data : object Input data with all `url` dict keys formatted """ OSF_API = "https://files.osf.io/v1/resources/{}/providers/osfstorage/{}" if isinstance(data, str): return data elif 'url' in data: data['url'] = OSF_API.format(*data['url']) try: for key, value in data.items(): data[key] = _osfify_urls(value) except AttributeError: for n, value in enumerate(data): data[n] = _osfify_urls(value) return data
9bacd7e60d7412a4cdcd6acf38b59b9d2de0b25a
690,789
def gcd(x: int, m: int) -> int: """ 最大公約数を求める ユークリッドの互除法 """ if m == 0: return x return gcd(m, x % m)
8d476fe4f59d230a2f0e1481fb06ccba9a43b8d6
690,790
def linear_map( values, new_min=0.0, new_max=1.0 ): """Return a NumPy array of linearly scaled values between new_min and new_max. Equivalent to Matlab's mat2gray, I believe. """ new_values = (((values - values.min()) * (new_max - new_min)) / (values.max() - values.min())) + new_min return new_values # End linear_map() definition
2756997048bfb64a4b4f6e5f52b5bc26bf80aa77
690,795
def inttodate(i, lim=1965, unknown='U', sep='-', order="asc", startsatyear=0): """ transforms an int representing days into a date Args: i: the int lim: the limited year below which we have a mistake unknown: what to return when unknown (date is bellow the limited year) sep: the sep between your date (e.g. /, -, ...) order: if 'asc', do d,m,y else do y,m,d startsatyear: when is the year to start counting for this int Returns: str: the date or unknown """ a = int(i // 365) if a > lim: a = str(a + startsatyear) r = i % 365 m = str(int(r // 32)) if int(r // 32) > 0 else str(1) r = r % 32 d = str(int(r)) if int(r) > 0 else str(1) else: return unknown return d + sep + m + sep + a if order == "asc" else a + sep + m + sep + d
f440e136b1e4707403b3b1d565724af8f212a140
690,797
def parse_ref_words(argstr): # address: (expect, mask) """ All three of thse are equivilent: ./solver.py --bytes 0x31,0xfe,0xff dmg-cpu/rom.txt ./solver.py --bytes 0x00:0x31,0x01:0xfe,0x02:0xff dmg-cpu/rom.txt ./solver.py --bytes 0x00:0x31:0xFF,0x01:0xfe:0xFF,0x02:0xff:0xFF dmg-cpu/rom.txt Which maps to: ref_words = { 0x00: (0x31, 0xFF), 0x01: (0xfe, 0xFF), 0x02: (0xff, 0xFF), } """ ret = {} auto_addr = 0 for constraint in argstr.split(","): parts = constraint.split(":") assert len(parts) <= 3 # One arg: assume offset and just use value if len(parts) == 1: offset = auto_addr value = int(parts[0], 0) # two arg: offset:value else: offset = int(parts[0], 0) value = int(parts[1], 0) mask = 0xFF # three arg: allow masking value if len(parts) >= 3: mask = int(parts[2], 0) ret[offset] = (value, mask) auto_addr += 1 return ret
dc558139a3426f926e76096c977e3242173af793
690,798
def degrees2gradians(value:float)->float: """Convert degrees to gradians. """ return value * 200/180
b509b65aba5ced6cd47db914f9fed6ec52ac51f0
690,803
from typing import Dict from typing import Tuple from typing import List def get_intents_keywords(entities: Dict) -> Tuple[List[str], List[str]]: """Obtains the list of intents and the list of keywords from an Wit.ai entity.""" intents = [] keywords = [] for key, val in entities.items(): if key == "intent": intents.extend([dct.get("value") for dct in val]) else: keywords.append(key) return intents, keywords
fa161ed1f5468d6ed86ab1eccee5943f60c4b173
690,805
def application_case_func(decorator_application_scenario, current_cases): """Returns the case function used behind `decorator_application_scenario`.""" return current_cases["decorator_application_scenario"]["p"].func
5135e01e14e2dd54b8afa3db77438f6241be9497
690,806
def _splits_for_summary_description_openapi_doc(lines): """Splites a list of docstring lines between the summary, description, and other properties for an API route openapi spec. For the openapi spec block, it should start with '````openapi' and close with '```'. Parameters ---------- lines : list[str] Returns ------- tuple summary : str description : str openapi : str """ info = [] openapi = [] in_openapi = False for line in lines: if '```openapi' == line: in_openapi = True continue if in_openapi and '```' == line: in_openapi = False continue if not in_openapi: info.append(line) else: openapi.append(line) return info[0], info[1:], openapi
773f060d2af7cda41fbc4a941e9fa57372b2cede
690,807
def blosxom_sort_list_handler(args): """Sorts the list based on ``_mtime`` attribute such that most recently written entries are at the beginning of the list and oldest entries are at the end. :param args: args dict with ``request`` object and ``entry_list`` list of entries :returns: the sorted ``entry_list`` """ entry_list = args["entry_list"] entry_list = [(e._mtime, e) for e in entry_list] entry_list.sort() entry_list.reverse() entry_list = [e[1] for e in entry_list] return entry_list
573fee0a720529aebfeaad5d51eda472bee16d84
690,818
def notes(feature): """ Get all notes from this feature. If none a present then an empty list is returned. """ return feature.qualifiers.get("note", [])
626d4d81527b6656131bd7a7c4dd3c534bb3e318
690,819
def text2float(txt: str) -> float: """Converts text to float. If text is not number, then returns `0.0` """ try: return float(txt.replace(",", ".")) except: return 0.0
68ea77531810e4ab485a6feace0f455a466ee97c
690,822
def get_atom_indices(labels, atom): """ labels - a list of coordinate labels ("Elements") atom - the atom whose indices in labels are sought Returns a list of all location of [atom] in [labels] """ indices = [] for i in range(len(labels)): if labels[i] == atom: indices.append(i) return indices
a5b36423becc9935e64225a6a029999e24471a65
690,825
def validate_manifest(manifest_data, validator): """Validate provided manifest_data against validator, returning list of all raised exceptions during validation""" return list(validator.iter_errors(manifest_data))
021fba2fe84e4d676af2145a4aa1bdd67e573f48
690,826
def get_prop(obj, *prop_list): """ Get property value if property exists. Works recursively with a list representation of the property hierarchy. E.g. with obj = {'a': 1, 'b': {'c': {'d': 2}}}, calling get_prop(obj, 'b', 'c', 'd') returns 2. :param obj: dictionary :param prop_list: list of the keys :return: the property value or None if the property doesn't exist """ if obj is None: return None if len(prop_list) == 1: if prop_list[0] in obj.keys(): return obj[prop_list[0]] else: return None if prop_list[0] in obj.keys(): return get_prop(obj[prop_list[0]], *prop_list[1:]) else: return None
1a8f2000fdc3809a92158c72dbe7c926473889ad
690,827
def splitOut(aa): """Splits out into x,y,z, Used to simplify code Args: aa - dictionary spit out by Returns: outkx, outky, outkz (numpy arrays) - arrays of the x, y, and values of the points """ outkx = aa['x'][::3] outky = aa['x'][1::3] outkz = aa['x'][2::3] return outkx, outky, outkz
3be9e1938374a823a78aa6f8478c8cd02e4e9c50
690,829
def unwrap_cdata(value): """Remove CDATA wrapping from `value` if present""" if value.startswith("<![CDATA[") and value.endswith("]]>"): return value[9:-3] else: return value
fd5188099659002ea0a21d11f4dc80b60d91f377
690,830
import pkgutil def get_all_modules(package_path): """Load all modules in a package""" return [name for _, name, _ in pkgutil.iter_modules([package_path])]
82bed2a436704a3a843fda6490e21ed7d4859b22
690,833
def GetDeviceNamesFromStatefulPolicy(stateful_policy): """Returns a list of device names from given StatefulPolicy message.""" if not stateful_policy or not stateful_policy.preservedState \ or not stateful_policy.preservedState.disks: return [] return [disk.key for disk in stateful_policy.preservedState.disks.additionalProperties]
9a02740424b8742ea866610dc19515784d4c58eb
690,834
def replace_tabs(string: str, tab_width: int = 4) -> str: """Takes an input string and a desired tab width and replaces each \\t in the string with ' '*tab_width.""" return string.replace('\t', ' '*tab_width)
f5d530afdb0059673dd3324c3671b38156c8d6ef
690,838
def closestsites(struct_blk, struct_def, pos): """ Returns closest site to the input position for both bulk and defect structures Args: struct_blk: Bulk structure struct_def: Defect structure pos: Position Return: (site object, dist, index) """ blk_close_sites = struct_blk.get_sites_in_sphere(pos, 5, include_index=True) blk_close_sites.sort(key=lambda x:x[1]) def_close_sites = struct_def.get_sites_in_sphere(pos, 5, include_index=True) def_close_sites.sort(key=lambda x:x[1]) return blk_close_sites[0], def_close_sites[0]
19f28ed590e1ca229bb3240f5aa84bc35f7a0dc8
690,840
from typing import Any import inspect def compare_attributes(obj1: Any, obj2: Any, *, ignore_simple_underscore: bool = False) -> bool: """Compares all attributes of two objects, except for methods, __dunderattrs__, and, optionally, _private_attrs. Args: obj1 (Any): First object to compare. obj2 (Any): Second object to compare. ignore_simple_underscore (:class:`bool`, optional): If ``True``, attributes starting with a single `_` won't be compared. Defaults to ``False`` (compares attributes starting with a single `_`, but not with two). Returns: :class:`bool`: ``True`` if obj1.X == obj2.X for all X (according to the criteria at the function description); ``False`` otherwise. Examples: .. testsetup:: * from serpcord.utils.model import compare_attributes .. doctest:: >>> class A: ... pass >>> a, b, c = A(), A(), A() >>> a.x = 5; a.y = 6; a.z = 7 >>> b.x = 5; b.y = 7; b.z = 7 >>> c.x = 5; c.y = 6; c.z = 7 >>> compare_attributes(a, b) # they differ in one attribute (y) False >>> compare_attributes(a, c) # all attributes are equal True """ for k1, v1 in inspect.getmembers(obj1): if k1.startswith("__") or (not ignore_simple_underscore and k1.startswith("_")): continue is_v1_method = inspect.ismethod(v1) for k2, v2 in filter(lambda k: k and k[0] == k1, inspect.getmembers(obj2)): if is_v1_method != inspect.ismethod(v2): # one is a method and the other isn't? return False if not is_v1_method and v1 != v2: return False return True
55db996ce48051872f45b1b7f398643f0588d89d
690,841
def _updated_or_published(mf): """ get the updated date or the published date Args: mf: python dictionary of some microformats object Return: string containing the updated date if it exists, or the published date if it exists or None """ props = mf['properties'] # construct updated/published date of mf if 'updated' in props: return props['updated'][0] elif 'published' in props: return props['published'][0] else: return None
e487c381ece11faf40c42c02454907cea5104d31
690,843
from pathlib import Path def is_file(path: Path) -> bool: """ Return true if the given path is a file, false otherwise. :param path: a Path :return: a bool """ return path.is_file()
16a110aed72917683bea00672778aba8676c0790
690,847
def dict2str(d): """Pretty formatter of a dictionary for one-line logging.""" return str(sorted(d.items()))
ba50638cecebc3cd013b5209a954dba4c2bf4555
690,848
def retrieve_min_max_from_path(path): """looks for min and max float in path Args: path (str): folder path Returns: (float, float) retrieved min and max values """ path = path.replace("\\", "") path = path.replace("/", "") return float(path.split("_")[-2]), float(path.split("_")[-1])
a2699cd7cf2b8f562e8afb22b718b1e1c5f25a20
690,852
def type_unpack(type): """ return the struct and the len of a particular type """ type = type.lower() s = None l = None if type == 'short': s = 'h' l = 2 elif type == 'bool': s = 'c' l = 1 elif type == 'ushort': s = 'H' l = 2 elif type == 'int': s = 'i' l = 4 elif type == 'uint': s = 'I' l = 4 elif type == 'long': s = 'l' l = 4 elif type == 'ulong': s = 'L' l = 4 elif type == 'float': s = 'f' l = 4 elif type == 'double': s = 'd' l = 8 else: raise TypeError('Unknown type %s' % type) return ('<' + s, l)
1753c1b62944188d3265f33d1c8fce63cc5e0f60
690,853
def get_unicode_code_points(string): """Returns a string of comma-delimited unicode code points corresponding to the characters in the input string. """ return ', '.join(['U+%04X' % ord(c) for c in string])
dada87ad2fef1948fd899fc39bd1abe7c105ac6c
690,854
def as_markdown(args): """ Return args configs as markdown format """ text = "|name|value| \n|-|-| \n" for attr, value in sorted(vars(args).items()): text += "|{}|{}| \n".format(attr, value) return text
0d1cf326f33f63ff71afe3befc20f1d3cc7a1adb
690,858
def ndbi(swir, red, nir, blue): """ Converts the swir, red, nir and blue band of Landsat scene to a normalized difference bareness index. Source: Zao and Chen, "Use of Normalized Difference Bareness Index in Quickly Mapping Bare from TM/ETM+", IEEE Conference Paper, 2005 DOI: 10.1109/IGARSS.2005.1526319 :param swir: numpy.array, shortwave infrared band :param red: numpy.array, red band :param nir: numpy.array, near infrared band :param blue: numpy.array, blue band :return: normal difference bareness index """ # bareness index components x = (swir + red) - (nir + blue) y = (swir + red) + (nir + blue) # prevent division by zero error y[y == 0.0] = 1.0 # bareness index img = x / y img[y == 1.0] = 0.0 # clip range to normal difference img[img < -1.0] = -1.0 img[img > 1.0] = 1.0 return img
5a79e2af482e56429cfe76d3ab12ae9e487573af
690,863
import torch def reg_binary_entropy_loss(out): """ Mean binary entropy loss to drive values toward 0 and 1. Args: out (torch.float): Values for the binary entropy loss. The values have to be within (0, 1). Return: torch.float for the loss value. """ return torch.mean(-out * torch.log(out) - (1 - out) * torch.log(1 - out))
7babb3cef8e0ac6185861f9470b121fde654796a
690,865
def get_hyperion_unique_id(server_id: str, instance: int, name: str) -> str: """Get a unique_id for a Hyperion instance.""" return f"{server_id}_{instance}_{name}"
38c830ca9a319a2d0795b4c2eeb3c1e6c97f0560
690,866
def getModel(tsinput): """ This is the wrapper function for all profile models implemented in the runInput package. Parameters ---------- tsinput : :class:`.tsinput` A TurbSim input object. Returns ------- profModel : A subclass of :class:`.profModelBase` The appropriately initialized 'profile model' object specified in `tsinput`. """ # This executes the sub-wrapper function (defined below) specified # in the tsinput-object (input file WINDPROFILETYPE line) return eval('_' + tsinput['WindProfileType'].lower() + '(tsinput)')
9bd0bcb323f7dd287e3e254af042d2bd9c64c118
690,869
from typing import Union from typing import Collection from typing import Set def split_csp_str(val: Union[Collection[str], str]) -> Set[str]: """Split comma separated string into unique values, keeping their order.""" if isinstance(val, str): val = val.strip().split(",") return set(x for x in val if x)
ad1d57df14469d83dd025b0f951720247eb886bf
690,874
def identity(*args): """ Always returns the same value that was used as its argument. Example: >>> identity(1) 1 >>> identity(1, 2) (1, 2) """ if len(args) == 1: return args[0] return args
f2f0e80b690c54090b260c615823b020639f097c
690,875
import pathlib from typing import Optional def latest_checkpoint_update(target: pathlib.Path, link_name: str) -> Optional[pathlib.Path]: """ This function finds the file that the symlink currently points to, sets it to the new target, and returns the previous target if it exists. :param target: A path to a file that we want the symlink to point to. :param link_name: This is the name of the symlink that we want to update. :return: - current_last: This is the previous target of the symlink, before it is updated in this function. If the symlink did not exist before or did not have a target, None is returned instead. """ link = pathlib.Path(link_name) if link.is_symlink(): current_last = link.resolve() link.unlink() link.symlink_to(target) return current_last link.symlink_to(target) return None
da7654fec781a6b174ce9dedfb7de3efedaac52e
690,879
def isTIFF(filename: str) -> bool: """Check if file name signifies a TIFF image.""" if filename is not None: if(filename.casefold().endswith('.tif') or filename.casefold().endswith('.tiff')): return True return False
33efcce2f2a4c21fd979fd13390a63aa28c50a4f
690,880
from typing import Dict def dataset_is_authoritative(dataset: Dict) -> bool: """Check if dataset is tagged as authoritative.""" is_authoritative = dataset.get("isAuthoritative") if is_authoritative: return is_authoritative["value"] == "true" return False
44f2554d046f356093281f35530a60cc55c4846f
690,881
def max_farmers(collection): # pragma: no cover """Returns the maximum number of farmers recorded in the collection""" max_farmers = 0 for doc in collection.find({}).sort([('total_farmers',-1)]).limit(1): max_farmers = doc['total_farmers'] return max_farmers
9f91774d0fe36fc4299db938e11db45d080ed5c1
690,882
import hashlib import pathlib def calculate_file_hash(file_path): """ Calculate the hash of a file on disk. We store a hash of the file in the database, so that we can keep track of files if they are ever moved to new drives. :param file_path: :return: """ block_size = 65536 hasher = hashlib.sha1() p = pathlib.Path(file_path) if p.exists(): with p.open('rb') as f: buf = f.read(block_size) while len(buf) > 0: hasher.update(buf) buf = f.read(block_size) return hasher.hexdigest() else: return None
59713e788cd61386d52e36eef185fed21175b4f3
690,883
def word_fits_in_line(pagewidth, x_pos, wordsize_w): """ Return True if a word can fit into a line. """ return (pagewidth - x_pos - wordsize_w) > 0
531be505e71e829f208263d5cede0a8774ef4c35
690,886
from typing import Dict from typing import Any def create_gyre_prefix(gyre_comb: Dict[str, Any]) -> str: """ Creates a GYRE run prefix to use for the given combination of GYRE parameter values. These prefixes should be unique within one MESA run, but can be repeated across multiple, separate, MESA runs. This also needs to be deterministic, reguardless of the fact that the dict passed in is unordered. >>> create_gyre_prefix({"a": 2, "c": 3, "b": "hi"}) 'gyre_a_2__b_hi__c_3__' """ name = "gyre_" for key in sorted(gyre_comb.keys()): name += key + "_" + str(gyre_comb[key]) + "__" return name
1f26978f16bb43e33934374f858477b0d2430908
690,896
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
import typing def is_same_classmethod( cls1: typing.Type, cls2: typing.Type, name: str, ) -> bool: """Check if two class methods are not the same instance.""" clsmeth1 = getattr(cls1, name) clsmeth2 = getattr(cls2, name) return clsmeth1.__func__ is clsmeth2.__func__
da2144380b6811a5843ded2f90d855d3c14d52a5
690,898
import socket import pickle def send_packet(sock, pack): """ Send a packet to remote socket. We first send the size of packet in bytes followed by the actual packet. Packet is serialized using cPickle module. Arguments --------- sock : Destination socket pack : Instance of class Packet. """ if pack is None or (sock is None or type(sock) != socket.socket): return # Nothing to send pack_raw_bytes = pickle.dumps(pack) dsize = len(pack_raw_bytes) sock.sendall(dsize.to_bytes(4, byteorder="big")) sock.sendall(pack_raw_bytes) return True
6056663868b7dbc6ad1aa7408ad7044819339308
690,899
import torch def get_all_indcs(batch_size, n_possible_points): """ Return all possible indices. """ return torch.arange(n_possible_points).expand(batch_size, n_possible_points)
0bcf5f26635f70155cbab8ff226bf3169b1e6337
690,903
def N_STS_from_N_SS(N_SS, STBC): """ Number of space-time streams (N_{STS}) from number of spatial streams (N_{SS}), and the space-time block coding (STBC) used. The standard gives this a table (20-12), but it's just addition! """ return N_SS + STBC
b7d4172ae2b0b5ec15607dcb6d6e4f41798c7fc8
690,905
def num_grid_points(d, mu): """ Checks the number of grid points for a given d, mu combination. Parameters ---------- d, mu : int The parameters d and mu that specify the grid Returns ------- num : int The number of points that would be in a grid with params d, mu Notes ----- This function is only defined for mu = 1, 2, or 3 """ if mu == 1: return 2*d + 1 if mu == 2: return 1 + 4*d + 4*d*(d-1)/2. if mu == 3: return 1 + 8*d + 12*d*(d-1)/2. + 8*d*(d-1)*(d-2)/6.
8ebbf251b367ac4375425560e4b80e10e22e36b9
690,908
from datetime import datetime import time def get_end_date_of_schedule(schedule): """Return the end date of the provided schedule in ISO 8601 format""" currenttime = datetime.today() endtime = datetime( currenttime.year, currenttime.month, currenttime.day, schedule['end-hour'], schedule['end-minute']) # manually create ISO8601 string because of tz issues with Python2 ts = time.time() utc_offset = ((datetime.fromtimestamp( ts) - datetime.utcfromtimestamp(ts)).total_seconds()) / 3600 offset = str(int(abs(utc_offset * 100))).zfill(4) sign = "+" if utc_offset >= 0 else "-" return endtime.strftime("%Y-%m-%dT%H:%M:%S{sign}{offset}".format(sign=sign, offset=offset))
bf17c699455a4c7c57abd7751888ba12cd539170
690,910
def get_uncert_dict(res): """ Gets the row and column of missing values as a dict Args: res(np.array): missing mask Returns: uncertain_dict (dict): dictionary with row and col of missingness """ uncertain_dict = {} for mytuple in res: row = mytuple[0] col = mytuple[1] if uncertain_dict.get(row): uncertain_dict[row].append(col) else: uncertain_dict[row] = [col] return uncertain_dict
336eebcd2fc64294ffe70a03988906eb29fca78c
690,911
def _and(*args): """Helper function to return its parameters and-ed together and bracketed, ready for a SQL statement. eg, _and("x=1", "y=2") => "(x=1 AND y=2)" """ return " AND ".join(args)
c917fdaac6296fe01bae57bb359ac62c884a452c
690,917
from typing import Dict def load_lookup_from_csv(csv_source: str, count: int) -> Dict[str, int]: """ From Dino, feature extraction utils Load a lookup dictionary, mapping string to rank, from a CSV file. Assumes the CSV to be pre-sorted. :param csv_source: Source data filepath :param count: number of strings to load :return: dictionary mapping strings to rank """ lookup_dict: Dict[str, int] = dict() rank: int = 0 with open(csv_source, 'r') as fd: line = next(fd) try: while rank < count: if line.startswith("#"): line = next(fd) continue lookup_dict[line.strip().split(',')[-1]] = rank rank += 1 line = next(fd) except StopIteration: raise RuntimeError(f"Not enough entries in file. Expected at least {count}, max is {rank}.") return lookup_dict
91386a17af033369e2813b2abae805a00d709680
690,919
def get_edges(mapping): """ Returns the sorted edge list for topology. :param mapping: Process-to-node mapping :return: Topology edge list """ proc_map = mapping.mapping edges = mapping.process_graph.edges(data=True) return sorted([(min(proc_map[u], proc_map[v]), max(proc_map[u], proc_map[v]), data['weight']) for u, v, data in edges])
d3a1633e338167651be7ef6a74b64646319be354
690,922
import random import string def get_shipping_details_response(order_id, address_id): """ Creates a json response for a shipping details request. :param order_id: ID for the transaction. :param address_id: Address ID received from Vipps. :return: A json response for a shipping details request. """ shipping_details = { "addressId": address_id, "orderId": order_id, "shippingDetails": [ { "isDefault": "N", "priority": 1, "shippingCost": 30.0, "shippingMethod": "postNord", "shippingMethodId": "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) }, { "isDefault": "Y", "priority": 2, "shippingCost": 30.0, "shippingMethod": "Posten", "shippingMethodId": "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) } ] } return shipping_details
09d28d84d55e5b8ea8a808155bbac7466523adc7
690,923
def fillgaps_time(ds, method='cubic', max_gap=None): """ Fill gaps (nan values) across time using the specified method Parameters ---------- ds : xarray.Dataset The adcp dataset to clean method : string Interpolation method to use max_gap : numeric Max number of consective NaN's to interpolate across Returns ------- ds : xarray.Dataset The adcp dataset with gaps in velocity interpolated across time See Also -------- xarray.DataArray.interpolate_na() """ ds['vel'] = ds.vel.interpolate_na(dim='time', method=method, use_coordinate=True, max_gap=max_gap) if hasattr(ds, 'vel_b5'): ds['vel_b5'] = ds.vel.interpolate_na(dim='time', method=method, use_coordinate=True, max_gap=max_gap) return ds
03af3115bdc021cda1afcf763e57c8ebb764ebeb
690,926
def predict1(payload): """ Define a hosted function that echos out the input. When creating a predict image, this is the function that is hosted on the invocations endpoint. Arguments: payload (dict[str, object]): This is the payload that will eventually be sent to the server using a POST request. Returns: payload (dict[str, object]): The output of the function is expected to be either a dictionary (like the function input) or a JSON string. """ print('Predict 1!') return payload
8ef0318845080fc280068aebb633ca19d7b5f659
690,927
def signtest_data(RNG,n,trend=0): """ Creates a dataset of `n` pairs of normally distributed numbers with a trend towards the first half of a pair containing smaller values. If `trend` is zero, this conforms with the null hypothesis. """ return [( RNG.normal(size=size)-trend, RNG.normal(size=size) ) for size in RNG.randint(15,21,size=n) ]
58a7595b43a2d34c4b9c62f3593f449c65f08a6e
690,929
import re def finditer_with_line_numbers(pattern, input_string, flags=0): """ A version of 're.finditer' that returns '(match, line_number)' pairs. """ matches = list(re.finditer(pattern, input_string, flags)) if not matches: return [] end = matches[-1].start() # -1 so a failed 'rfind' maps to the first line. newline_table = {-1: 0} for i, m in enumerate(re.finditer(r'\n', input_string), 1): # don't find newlines past our last match offset = m.start() if offset > end: break newline_table[offset] = i # Failing to find the newline is OK, -1 maps to 0. for m in matches: newline_offset = input_string.rfind('\n', 0, m.start()) line_number = newline_table[newline_offset] yield m, line_number
3734a31153efa1d821ac7821acd41b5ba1bf8899
690,932
import csv def read_employees(csv_file_location): """ Convert csv file to dictionary. Receives a CSV file as a parameter and returns a list of dictionaries from that file. """ csv.register_dialect("empDialect", skipinitialspace=True, strict=True) employee_file = csv.DictReader( open(csv_file_location), dialect="empDialect") employee_list = [] for data in employee_file: employee_list.append(data) return employee_list
a48e51f2ad9a0a2f6cd3d8dfd187c5c170ed9260
690,934
def drop_irrelevant_practices(df, practice_col): """Drops irrelevant practices from the given measure table. An irrelevant practice has zero events during the study period. Args: df: A measure table. practice_col: column name of practice column Returns: A copy of the given measure table with irrelevant practices dropped. """ is_relevant = df.groupby(practice_col).value.any() return df[df[practice_col].isin(is_relevant[is_relevant == True].index)]
a0ed74aeabf8cfafbbd146cd74ed0bfe5895cc2f
690,937
import codecs def encode_endian(text, encoding, errors="strict", le=True): """Like text.encode(encoding) but always returns little endian/big endian BOMs instead of the system one. Args: text (text) encoding (str) errors (str) le (boolean): if little endian Returns: bytes Raises: UnicodeEncodeError LookupError """ encoding = codecs.lookup(encoding).name if encoding == "utf-16": if le: return codecs.BOM_UTF16_LE + text.encode("utf-16-le", errors) else: return codecs.BOM_UTF16_BE + text.encode("utf-16-be", errors) elif encoding == "utf-32": if le: return codecs.BOM_UTF32_LE + text.encode("utf-32-le", errors) else: return codecs.BOM_UTF32_BE + text.encode("utf-32-be", errors) else: return text.encode(encoding, errors)
1d15ffe8d330ade301f2e46ec3297e20017134dd
690,938
def features_axis_is_np(is_np, is_seq=False): """ B - batch S - sequence F - features :param d: torch.Tensor or np.ndarray of shape specified below :param is_seq: True if d has sequence dim :return: axis of features """ if is_np: # in case of sequence (is_seq == True): (S, F) # in case of sample: (F) return 0 + is_seq else: # in case of sequence: (B, S, F) # in case of sample: (B, F) return 1 + is_seq
88c555eaee9a9ce03c8ad874cd75f958a81b9096
690,940
def parse_args(args): """Parses and validates command line arguments Args: args (argparse.Namespace): Pre-paresed command line arguments Returns: bool: verbose flag, indicates whether tag frequency dictionary should be printed bool: sandbox flag, indicates whether Evernote API calls should be made against the production or sandbox environment str: name of the file the tag cloud image should be saved to int: width of the tag cloud image int: height of the tag cloud image file: mask file to use when generating the tag cloud str: font file to use when generating the tag cloud int: maximum number of tags to include in the tag cloud int: ratio of horizontal tags in the tag cloud int: the impact of tag frequency (as opposed to tag ranking) on tag size str: the name of a matplotlib colormap to use for tag colors (see https://matplotlib.org/examples/color/colormaps_reference.html for available colormaps) str: the Evernote API authentication token Raises: ValueError: if numeric parameters have an invalid value """ image_width_height = args.imageSize.split("x") if len(image_width_height) != 2: raise ValueError("invalid imageSize [%s] format, expected format is <width>x<height>", args.imageSize) image_width, image_height = int(image_width_height[0]), int(image_width_height[1]) if image_width not in range(10, 10000): raise ValueError("invalid imageSize.width [%d], imageSize.width must be between 10 and 9999", image_width) if image_height not in range(10, 10000): raise ValueError("invalid imageSize.height [%d], imageSize.height must be between 10 and 9999", image_height) if args.maxTags not in range(1, 1000): raise ValueError("invalid maxTags [%d], maxTags must be between 1 and 999", args.maxTags) if args.horizontalTags < 0 or args.horizontalTags > 1 : raise ValueError("invalid horizontalTags [%f], horizontalTags must be between 0 and 1", args.horizontalTags) if args.tagScaling < 0 or args.tagScaling > 1: raise ValueError("invalid tagScaling [%f], tagScaling must be between 0 and 1", args.horizontalTags) font_file = None if args.fontFile == None else args.fontFile.name return args.verbose, args.sandbox, args.imageFile.name, image_width, image_height, args.maskFile, font_file, args.maxTags, args.horizontalTags, args.tagScaling, args.tagColorScheme, args.evernoteAuthToken
e0070eae06c0f4df64d0818c9bfc352014383a29
690,941
def _extract_prop_set(line): """ Extract the (key, value)-tuple from a string like: >>> 'set foo = "bar"' :param line: :return: tuple (key, value) """ token = ' = "' line = line[4:] pos = line.find(token) return line[:pos], line[pos + 4:-1]
2bdb491c14308ca1b634e7d840893af3c698fa60
690,946
import torch def depth_map_to_locations(depth, invK, invRt): """ Create a point cloud from a depth map Inputs: depth HxW torch.tensor with the depth values invK 3x4 torch.tensor with the inverse intrinsics matrix invRt 3x4 torch.tensor with the inverse extrinsics matrix Outputs: points HxWx3 torch.tensor with the 3D points """ H,W = depth.shape[:2] depth = depth.view(H,W,1) xs = torch.arange(0, W).float().reshape(1,W,1).to(depth.device).expand(H,W,1) ys = torch.arange(0, H).float().reshape(H,1,1).to(depth.device).expand(H,W,1) zs = torch.ones(1,1,1).to(depth.device).expand(H,W,1) world_coords = depth * (torch.cat((xs, ys, zs), dim=2) @ invK.T[None]) @ invRt[:3,:3].T[None] + invRt[:3,3:].T[None] return world_coords
7091666c1e14afb8c48d062f676fc79a0290d344
690,947
def list_to_quoted_delimited(input_list: list, delimiter: str = ',') -> str: """ Returns a string which is quoted + delimited from a list :param input_list: eg: ['a', 'b', 'c'] :param delimiter: '|' :return: eg: 'a'|'b'|'c' """ return f'{delimiter} '.join("'{0}'".format(str_item) for str_item in input_list)
73c8c73b6e6716edad0f17ccb55e460d5356f800
690,948
def plugin(plugin_without_server): """ Construct mock plugin with NotebookClient with server registered. Use `plugin.client` to access the client. """ server_info = {'notebook_dir': '/path/notebooks', 'url': 'fake_url', 'token': 'fake_token'} plugin_without_server.client.register(server_info) return plugin_without_server
2cc59e2fd8de66ce7dbd68114ae5805bc13527fb
690,950
import typing import pathlib import glob def _get_paths(patterns: typing.Set[pathlib.Path]) -> typing.Set[pathlib.Path]: """Convert a set of file/directory patterns into a list of matching files.""" raw = [ pathlib.Path(item) for pattern in patterns for item in glob.iglob(str(pattern), recursive=True) ] files = [p for p in raw if not p.is_dir()] output = files + [ child for p in raw for item in glob.iglob(f"{p}/**/*", recursive=True) if p.is_dir() and not (child := pathlib.Path(item)).is_dir() ] return set(output)
5373f00f18326f4b18fbd5e9d6c7631a67ad7d16
690,955
def _attr2obj(element, attribute, convert): """ Reads text from attribute in element :param element: etree element :param attribute: name of attribute to be read :param convert: intrinsic function (e.g. int, str, float) """ try: if element.get(attribute) is None: return None elif element.get(attribute) == '': return None return convert(element.get(attribute)) except Exception: None
42391ace71e954ced70ec905deb979fa7bcdb47f
690,958
def create_cercauniversita(conn, cercauni): """ Create a new person into the cercauniversita table :param conn: :param cercauni: :return: cercauni id """ sql = ''' INSERT INTO cercauniversita(id,authorId,anno,settore,ssd,fascia,orcid,cognome,nome,genere,ateneo,facolta,strutturaAfferenza) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, cercauni) return cur.lastrowid
f54a9c18bec3f0947d96de8559ac27eb2e7218fe
690,962
def get_item_from_user(message, lst): """ Gets a valid index from a user to get an item from lst. The user is shown `message` and the range of valid indices, in the form of "Valid indices inclusive between 0 and max_index". The user is asked until a valid item was chosen. Args: message: The message to show the user before asking for index lst: the list to choose from Returns: The chosen index """ idx = -1 while idx == -1: try: # get an input from the user print(message) val = input(f"Valid indices inclusive between 0 and {len(lst) - 1}\n") # try to parse it as an int idx = int(val) # try to extract the action, this will throw if out of bounds item = lst[idx] # if it was no int or is out of bounds, remind the user what is to do # and reset idx except (ValueError, IndexError): idx = -1 print( "Please enter an integer value between inclusive " f"0 and {len(lst) - 1}" ) return idx
edfe6a9906318d7a44af4768234a06427d0d185b
690,963
def cauchy_cooling_sequence(initial_t, it): """ Calculates the new temperature per iteration using a cauchy progression. Parameters ---------- initial_t : float initial temperature it: int actual iteration Returns -------- tt: float new temperature """ tt = initial_t/(1+it) return tt
fd275244d184eadac62512ec4972fb1856174108
690,964
def is_end(word, separator): """Return true if the subword can appear at the end of a word (i.e., the subword does not end with separator). Return false otherwise.""" return not word.endswith(separator)
b2bc94dce0f628ce8738c434d2824871f64a653e
690,965
def _reconstruct_path(target_candidate, scanned): """ Reconstruct a path from the scanned table, and return the path sequence. """ path = [] candidate = target_candidate while candidate is not None: path.append(candidate) candidate = scanned[candidate.id] return path
18ca897a367eab0d5868a5d933c7f2fa96d661ff
690,968
import string def query_to_url(query, search_type, size): """convert query to usuable url Args: query (str): search query by user search_type (str): Search type (choice) size (int): number of items to query Returns: (str) the url for search """ # remove bad string & convert txt -> search keys query = query.translate(str.maketrans('', '', string.punctuation)) query = query.replace(" ", "+") # get the correct mapping mapping = {"All Fields": "", "Title": "title", "Abstract": "abstract"} search_type = mapping[search_type] #return the url return f"https://arxiv.org/search/?query={query}&searchtype={search_type}&abstracts=show&order=&size={size}"
5ef32179f8c876fe9751fc87561259fbff8d41ef
690,969
from pathlib import Path def read_polymer(filename: Path) -> tuple[dict, str]: """Read polymer structure information from a file The polymer is represented by a dict of rules and a polymer structer. Args: filename (Path): path to the input file. Returns: dict: rules str: initial polymer structure Examples: >>> read_polymer(Path("test_data/day_14.data"))[0]['CH'] 'B' >>> read_polymer(Path("test_data/day_14.data"))[1] 'NNCB' """ with filename.open("r") as file: poly_template, rules_raw = file.read().split("\n\n") rules = {} for line in rules_raw.strip().split("\n"): start, end = line.strip().split(" -> ") rules[start] = end return rules, poly_template
c326f14e1904361928e032ac2c9b1cfc14225cd1
690,971
def query_phantoms(view, pids): """Query phantoms.""" return view.query_phantoms(pids)
62148567a0b678bc56c0c92d802d5f47f757d85f
690,980
def get_positive_passages(positive_pids, doc_scores, passage_map): """ Get positive passages for a given grounding using BM25 scores from the positive passage pool Parameters: positive_pids: list Positive passage indices doc_scores: list BM25 scores against the query's grounding for all passages passage_map: dict All passages mapped with their ids Returns: positive_passage_pool """ scores = [(i, score) for (i, score) in doc_scores if i in positive_pids] top_scores = sorted(scores, key=lambda x: x[1], reverse=True) top_n_passages = [ {"psg_id": ix, "score": score, "title": passage_map[ix]["title"], "text": passage_map[ix]["text"]} for ix, score in top_scores ] return top_n_passages
0623dcd3a2bc93b59d8ef6f0fc2a790762292d9a
690,983
def lire_mots(nom_fichier): """fonction qui récupère la liste des mots dans un fichier paramètre - nom_fichier, de type chaine de caractère : nom du fichier contenant les mots (un par ligne) retour : liste de chaine de caractères """ liste_mots = [] # le tableau qui contiendra les lignes with open(nom_fichier, encoding="UTF-8") as f: # on ouvre le fichier ligne = f.readline() # une variable temporaire pour récupérer la ligne courante dans le fichier f while ligne != "": liste_mots.append(ligne.strip()) # on rajoute la ligne courante dans le tableau ligne = f.readline() # on récupère la ligne suivante return liste_mots
0c0ac636ef6bfbffcfa102f5bd26716564f73367
690,989
from typing import List def _hyphens_exists_next_line( line_splitted_list: List[str], next_line_idx: int) -> bool: """ Get the boolean value of whether there are multiple hyphen characters on the next line. Parameters ---------- line_splitted_list : list of str A list containing line-by-line strings. next_line_idx : int Next line index. Returns ------- result_bool : bool If exists, True will be set. """ if len(line_splitted_list) < next_line_idx + 1: return False next_line_str: str = line_splitted_list[next_line_idx] is_in: bool = '----' in next_line_str if is_in: return True return False
fedc408dab1176d43be6aecec59c871dda1821d6
690,993
def get_data(dataset): """Get features and targets from a specific dataset. Parameters ---------- dataset : Dataset object dataset that can provide features and targets Returns ------- features : arrary features in the dataset targets : array 1-d targets in the dataset """ handle = dataset.open() data = dataset.get_data(handle, slice(0, dataset.num_examples)) features = data[0] targets = data[1] dataset.close(handle) return features, targets
aeda21744b23ebb74304d4d9f58a99570f5a4321
690,995
def _gen_perm_Numpy(order, mode): """ Generate the specified permutation by the given mode. Parameters ---------- order : int the length of permutation mode : int the mode of specific permutation Returns ------- list the axis order, according to Kolda's unfold """ tmp = list(range(order - 1, -1, -1)) tmp.remove(mode) perm = [mode] + tmp return perm
df2511a8b9278c3018808a259f202e42c8a5462f
690,996
def contains_duplicate(nums: list[int]) -> bool: """Returns True if any value appears at least twice in the array, otherwise False Complexity: n = len(nums) Time: O(n) Space: O(n) Args: nums: array of possibly non-distinct values Examples: >>> contains_duplicate([1,2,3,1]) True >>> contains_duplicate([1,2,3,4]) False >>> contains_duplicate([1,1,1,3,3,4,3,2,4,2]) True """ """ALGORITHM""" ## INITIALIZE VARS ## # DS's/res nums_set = set() for num in nums: if num not in nums_set: nums_set.add(num) else: return True else: return False
397c5f03cd7025eec1fda6041e1a344e7e61f4bc
691,000
def depth_bonacci_rule(depth): """rule for generating tribonacci or other arbitrary depth words Args: depth (int): number of consecutive previous words to concatenate Returns: lambda w: w[-1] + w[-2] + ... + w[-(depth+1)] For example, if depth is 3, you get the tribonacci words. (there is already a tribonacci and quadbonacci words method) """ return lambda w: "".join(w[-1:-depth-1:-1])
db0d9f51475c9e4dd60acee36ffa651e577c4be2
691,003
import re def compile_patterns(patterns): """Compile a list of patterns into one big option regex. Note that all of them will match whole words only.""" # pad intent patterns with \b (word boundary), unless they contain '^'/'$' (start/end) return re.compile('|'.join([((r'\b' if not pat.startswith('^') else '') + pat + (r'\b' if not pat.endswith('$') else '')) for pat in patterns]), re.I | re.UNICODE)
80fdca22145a3f37c1c7c5035051d2b14b121ca6
691,004
def cli(ctx): """Get the list of all data tables. Output: A list of dicts with details on individual data tables. For example:: [{"model_class": "TabularToolDataTable", "name": "fasta_indexes"}, {"model_class": "TabularToolDataTable", "name": "bwa_indexes"}] """ return ctx.gi.tool_data.get_data_tables()
f718231f7a1a852f52d3d77dea8325e8e9ae5af4
691,006
def _function_iterator(graph): """Iterate over the functions in a graph. :rtype: iter[str] """ return ( node.function for node in graph )
aaff945176f3d5754a4381cb74ad5a660a298556
691,013
def ms_energy_stat(microstates): """ Given a list of microstates, find the lowest energy, average energy, and highest energy """ ms = next(iter(microstates)) lowerst_E = highest_E = ms.E N_ms = 0 total_E = 0.0 for ms in microstates: if lowerst_E > ms.E: lowerst_E = ms.E elif highest_E < ms.E: highest_E = ms.E N_ms += ms.count total_E += ms.E*ms.count average_E = total_E/N_ms return lowerst_E, average_E, highest_E
87a276c554750048b9c7c3826f49cce162094c35
691,020
import json def check_role_in_retrieved_nym(retrieved_nym, role): """ Check if the role in the GET NYM response is what we want. :param retrieved_nym: :param role: the role we want to check. :return: True if the role is what we want. False if the role is not what we want. """ if retrieved_nym is None: return False nym_dict = json.loads(retrieved_nym) if "data" in nym_dict["result"]: temp_dict = json.loads(nym_dict["result"]["data"]) if "role" in temp_dict: if not temp_dict["role"] == role: return False else: return True return False
d1e95415ebe2b049eecd8c002ee381ae43e7ed5b
691,024
def _do_get_features_list(featurestore_metadata): """ Gets a list of all features in a featurestore Args: :featurestore_metadata: metadata of the featurestore Returns: A list of names of the features in this featurestore """ features = [] for fg in featurestore_metadata.featuregroups.values(): features.extend(fg.features) features = list(map(lambda f: f.name, features)) return features
d5d1b99aa77067dc22473d12fb8fec6312d75b53
691,030
def vector_dot(xyz, vector): """ Take a dot product between an array of vectors, xyz and a vector [x, y, z] **Required** :param numpy.ndarray xyz: grid (npoints x 3) :param numpy.ndarray vector: vector (1 x 3) **Returns** :returns: dot product between the grid and the (1 x 3) vector, returns an (npoints x 1) array :rtype: numpy.ndarray """ if len(vector) != 3: raise Exception( "vector should be length 3, the provided length is {}".format( len(vector) ) ) return vector[0]*xyz[:, 0] + vector[1]*xyz[:, 1] + vector[2]*xyz[:, 2]
bb793fdf51ec83fd9dc98693030e5d3bfbfbdb6c
691,037
def filter_leetify(a, **kw): """Leetify text ('a' becomes '4', 'e' becomes '3', etc.)""" return a.replace('a','4').replace('e','3').replace('i','1').replace('o','0').replace('u','^')
768116ee67e7f089c9dfd73e8463b2386c48aa15
691,038
import ast def eval_string(string): """automatically evaluate string to corresponding types. For example: not a string -> return the original input '0' -> 0 '0.2' -> 0.2 '[0, 1, 2]' -> [0,1,2] 'eval(1+2)' -> 3 'eval(range(5))' -> [0,1,2,3,4] Args: value : string. Returns: the corresponding type """ if not isinstance(string, str): return string if len(string) > 1 and string[0] == '[' and string[-1] == ']': return eval(string) if string[0:5] == 'eval(': return eval(string[5:-1]) try: v = ast.literal_eval(string) except: v = string return v
eb61fe3949c401318ac219195969fbf3c07048e1
691,039
def convolution(image, kernel, row, column): """ Apply convolution to given image with the kernel and indices. :param image: image that will be convolved. :param kernel: kernel that will be used with convolution. :param row: row index of the central pixel. :param column: row index of the central pixel. :return: the convolved pixel value. """ value = 0 for i in range(2, -1, -1): for j in range(2, -1, -1): row_index = row - (i - 1) col_index = column - (j - 1) value += image[row_index][col_index] * kernel[i][j] if value < 0: value = 0 elif value > 255: value = 255 return int(value)
f7bd8f16f70fec06da0647a0d8eaf79790d4173d
691,041
def token_to_char_position(tokens, start_token, end_token): """Converts a token positions to char positions within the tokens.""" start_char = 0 end_char = 0 for i in range(end_token): tok = tokens[i] end_char += len(tok) + 1 if i == start_token: start_char = end_char return start_char, end_char
3ebb9fc59bb6040a55305c6e930df41dc4dc726e
691,042
def flatten_image(image): """ Flat the input 2D image into an 1D image while preserve the channels of the input image with shape==[height x width, channels] :param image: Input 2D image (either multi-channel color image or greyscale image) :type image: numpy.ndarray :return: The flatten 1D image. shape==(height x width, channels) :rtype: numpy.ndarry """ assert len(image.shape) >= 2, "The input image must be a 2 Dimensional image" if len(image.shape) == 3: image = image.reshape((-1, image.shape[2])) elif len(image.shape) == 2: image = image.reshape((-1, 1)) return image
6733b30adc9131fea237ab11afd3853bec0c2c44
691,043
def split_fqdn(fqdn): """ Unpack fully qualified domain name parts. """ if not fqdn: return [None] * 3 parts = fqdn.split(".") return [None] * (3 - len(parts)) + parts[0:3]
6615456641d09e8e1f2d4f38517204b3db1e1d7c
691,045
from typing import Union from pathlib import Path import json def read_json(path: Union[str, Path]): """ Read a json file from a string path """ with open(path) as f: return json.load(f)
86498196f4c5c01bcd4cadbaa9a095d0fb71c0a1
691,046