content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import torch def ls_discriminator_loss(scores_real, scores_fake): """ Compute the Least-Squares GAN metrics for the discriminator. Inputs: - scores_real: PyTorch Variable of shape (N,) giving scores for the real data. - scores_fake: PyTorch Variable of shape (N,) giving scores for the fake data. ...
dfbbfead7e4d64bda2d8b863338016d6722b8c4e
163,348
def has_obj_value(data_obj, attr): """Return weather dict has the given key or object has the given attribute.""" if isinstance(data_obj, dict): return attr in data_obj.keys() return hasattr(data_obj, attr)
c23c00c7fd6cc7a1823dc12744b9eb10e12fe528
239,758
def listify(x): """Puts non-list objects into a list. Parameters ---------- x: Object to ensure is list Returns ---------- :obj:`list` If ``x`` is already a list, this is returned. Otherwise, a list\ containing ``x`` is returned. """ if isinstance(x, list): ...
5251c6e70cce9a6b134e321c89a674915ac389b0
461,702
import re def normalize_hostname_to_rfc(mystr): """ Given a hostname, normalize to Nextdoor hostname standard Args: mystr (str): hostname to normalize Returns: normalized hostname Details: * lower everthing * delete anything which is not alphanumeric * compress mul...
ce6d6fd07ba12ac28f0d96bb4ee3dc0345e7bcd4
101,340
def get_auth_token( http_requests, url="https://danielvaughan.eu.auth0.com/oauth/token", client_id="Zdsog4nDAnhQ99yiKwMQWAPc2qUDlR99", client_secret="t-OAE-GQk_nZZtWn-QQezJxDsLXmU7VSzlAh9cKW5vb87i90qlXGTvVNAjfT9weF", audience="http://localhost:8080", grant_type="client_credentials", ): """Re...
a1dfc8a1b873138967e7e7c7ed497fda8d22f16c
554,139
import itertools def flatten(gen): """Flatten a sequence, but only one level deep.""" return itertools.chain.from_iterable(gen)
a15b84d9741962a4e4588253a41bb8b538635bfa
567,374
import statistics def get_partition_agreement_score(partitionA, partitionB): """ Compute the partition agreement score for two partitions. """ scores = [] for i, prtB in enumerate(partitionB): score = 0 for j, prtA in enumerate(partitionA): if prtB.issubset(prtA): ...
0a80b858ea768c08c368d97406f181a0b9c75b1c
60,673
def get_filter_par(filter_group, filter_ids, key): """ Given a pandas groupby object 'filter_group' that group the filters by filter_number (giving a filter set) and a key, get the first value for that key in each group. """ return [filter_group[i][0][key] for i in filter_ids]
bd5f9a08c20152956443d8f39a0ebe4ed36f14f6
90,773
def minmax_element(iterable, first=0, last=None, key=None): """ Find and return the minimum and maximum element in an iterable range. Parameters ---------- iterable: an iterable object with __get_item__ first: first element to check last: one past last element to check. None will check unti...
a5176ac552ff720fdd304c12b64a1ec9a9b9a09b
638,555
def migrate(engine): """Replace 'backend' with 'store' in meta_data column of image_locations""" sql_query = ("UPDATE image_locations SET meta_data = REPLACE(meta_data, " "'\"backend\":', '\"store\":') where INSTR(meta_data, " " '\"backend\":') > 0") # NOTE(abhishekk): INS...
6d7fa2beed8cf38cb7debe556663950a820af1c2
654,084
def morph_word(word: str) -> str: """Apply simple morphing of the word to improve robustness for checking similarity. A derived token is created by concatenating the word and the sorted version of the word. Args: word: Word to be morphed. Returns: The morphed word. ""...
8b0502d643d71bf2e493d3b903c3f7280f727807
310,891
def _isRunMaskDuplicate(run, lumis, runLumis): """ Test whether run and lumi is a subset of one of the runLumi pairs in runLumis :param run: integer run number :param lumi: set of lumis :param runLumis: list of dictionaries containing run and lumis """ for runLumi in runLumis: if...
4b17001087175db9325efaa7f7420bc75a6f1e61
655,933
def extract(d, *args, default=None): """Return a tuple of results extracted from the dictionary using strings of paths to the values E.g. extract(d, 'a', 'b.c') is will return (d.get(a), d.get(b).get(c) """ assert isinstance(d, dict) results = [] for key in args: key = key.split('.') ...
7ce7bb4c28d96430388bff4a29e9875c6774716d
243,819
def append_cluster(cluster_a, cluster_b): """ Appends cluster_b to cluster_a :param cluster_a: array of shape [n_points, n_dimensions] :param cluster_b: array of shape [n_points, n_dimensions] """ for point in cluster_b: cluster_a.append(point) return cluster_a
cc5e6fc6d3162fdd8a0f87071039afc80ab582fc
290,868
def is_extrapackages_checked(active_packages, package_name): """ Checks if the given package_name is under the already activate packages """ if package_name in active_packages: return True else: return False
a705c041347f1147bf2e66945983f59a884a19bd
541,965
def parse_secret_from_authentication_url(url): """ This helper will parse the secret part of a totp url like otpauth://totp/alice%07c%40apothekia.de?secret=M3FAFWGD2QA5JJPCPWEOKALPBROHXOL3&algorithm=SHA1&digits=6&period=30 """ return url.split("secret")[1][1:33]
207ed2c0633af4b5eb0c29992dc6c4cb8cc5e40c
312,289
def fixIncorrectDateEncoding(Date): """ Fix date string to make it conform to ISO standard. """ if 'T00:00:00Z' in Date: return Date return Date + "T00:00:00Z"
57b0bed00c214794d3d1e25c313ce3e3cbe61526
648,767
def heart_color(color='red'): """Set the color of the hearts on the player's HUD. Keyword Arguments: color {str} -- The heart color. Options are 'red', 'blue', 'green', and 'yellow' (default: {'red'}) Returns: list -- a list of dictionaries indicating which ROM address offsets to write an...
1d5e8f9511ad49fe33e1d167f3e5b9ce5c2f3bfb
506,317
def normalize(array): """ This function normalizes a numpy array to sum up to 1 (L1 norm) """ return array/array.cumsum()[-1]
a3ec4e9f867b7548c1fefca3807fa846508a20bc
603,411
import hashlib def hash_sha3_512(password): """ Hashes a password using SHA3-512. Arguments: password <str>: The password to be hashed. """ return hashlib.sha3_512(password.encode('utf-8')).hexdigest()
6357d195e5420855e474f73a17acff55a9d43f78
273,843
import json from typing import OrderedDict def loads(f): """ Load a json stream into an OrderedDict """ return json.JSONDecoder(object_pairs_hook=OrderedDict).decode(f)
9b99189239fc9977375e6a5f650f70ec1ea7f020
359,278
def create_speed_command2(packer, speed3, lsmcdecel, actlbrknocs, actlbrknocnt, actlbrkqf): """Creates a CAN message for the Ford Speed Command.""" values = { "Veh_V_ActlBrk": speed3, "LsmcBrkDecel_D_Stat": lsmcdecel, "VehVActlBrk_No_Cs": actlbrknocs, "VehVActlBrk_No_Cnt": actlbrknocnt, "VehVAct...
89695360160e03945177eeab451eb3f0dd262389
409,570
def show_price(price: float) -> str: """ >>> show_price(1000) '$ 1,000.00' >>> show_price(1_250.75) '$ 1,250.75' """ return "$ {0:,.2f}".format(price)
3c3c9a7532e1a84ddcf5b58d348dda778fdf5e59
681,211
def get_data_meta_path(either_file_path: str) -> tuple: """get either a meta o rr binary file path and return both as a tuple Arguments: either_file_path {str} -- path of a meta/binary file Returns: [type] -- (binary_path, meta_path) """ file_stripped = '.'.join(either_file_path....
0456186cd99d5899e2433ac9e44ba0424077bcc0
707,218
import six def make_hashable(thing): """ Creates a representation of some input data with immutable collections, so the output is hashable. :param thing: The data to create a hashable representation of. """ if isinstance(thing, list): return tuple(make_hashable(elem) for elem in thing...
42f60d3a0886f7cc8a339ffe0f0c8d5bd2da2873
121,416
from typing import Union def read_field(dictionary: dict, key: str) -> Union[str, None]: """ Read field value from dictionary. If there is no `key` in `dictionary` or value is equal to `N/A` return `None` :param dictionary: container to read from :param key: key to look up :return: value or N...
a2a03c65d6cf9acb423e9fff20367ba9d6642873
613,175
import re def _replace_ampersands(html): """Replace ampersand symbols in html""" html = re.sub('&amp;', '&', html, flags=re.DOTALL) html = re.sub('&quot;', '"', html, flags=re.DOTALL) # html = re.sub('&amp;', ' ', html, flags=re.DOTALL) # html = re.sub('&quot;', ' ', html, flags=re.DOTALL) htm...
355785a2971a56a9dc73174a019314077f1a12b9
550,781
from typing import Optional from typing import Any from warnings import warn def migrate_deprecated_argument( new_arg: Optional[Any], new_arg_name: str, old_arg: Optional[Any], old_arg_name: str ) -> Any: """ Facilitates the migration of an argument's name. This method han...
5007ef28f027978743f1b83dc688592c5742989d
453,371
def partition(inp_list, n): """ Paritions a given list into chunks of size n Parameters ---------- inp_list: List to be splittted n: Number of equal partitions needed Returns ------- Splits inp_list into n equal chunks """ division = len(inp_list) / float(n) return [ inp_list[int(round(divisi...
d1f4c126c10be18e2c93519113beb76b39a3ac4d
204,419
def ppm_to_pa(ppm, pres): """ Convert ppm (umol mol^-1) to a partial pressure Args: ppm (float) : ppm of gas [umol mol^-1] pres (float) : atmospheric pressure [Pa] Returns: pa (float) : partial pressure of gas [Pa] """ pa = ppm * 1e-6 * pres return pa
3dff62717f30ba5c086a6dfb2c9c7fe9c1cde429
570,221
def extract_values(json_array, key): """ Obtain all values for a key in the JSON (dict) array """ return [item[key] for item in json_array]
18b62abcc25f60ef25a9ec9b312726c541f597a0
342,424
def hamming_distance(x, y): """Return the Hamming distance between `x` and `y`.""" assert len(x) == len(y) return sum(xi != yi for xi, yi in zip(x, y))
c48f4986adbc522f4cbc06743f3aed2034aea598
259,649
from typing import OrderedDict def get_any_value(x): """ Returns a value of a dict, list, or tuple. # Arguments x: object. The object to grab a value for. # Return value If `x` is a dictionary (including an OrderedDict), returns a value from it. If `x` is a list or tuple, returns an element ...
ea9f4e35235d8b80722e365d03aef9c0309b907b
150,877
def to_bazelname(filename: str, mockname: str) -> str: """ maps divided mock class file name to bazel target name e.g. map "test/mocks/server/admin_stream.h" to "//test/mocks/server:admin_stream_mocks" Args: filename: string, mock class header file name (might be the whole path instead of the b...
a6d0507deae0ebdf2c8f3bfe155364e24110617f
272,710
import re def htmldoc(text): """ Format docstring in html for a nice display in IPython. Parameters ---------- text : str The string to convert to html. Returns ------- out : str The html string. """ p = re.compile("^(?P<name>.*:)(.*)", re.MULTILINE) # To get...
f2385b2dbeaa294270aa9481f85d26eabd5f169a
507,939
import binascii def compute_crc(buf, crc_so_far=0): """ :param buf: bytes to compute CRC over. :param crc_so_far: value of CRC of bytes seen so far. To compute the CRC over multiple buffers, pass the previous buffer's CRC as *crc_so_far*. Use 0 (default) for the first time. :returns: CRC v...
ab1a066cae8cd85e6d3a57419c46fcd587676507
538,516
def generate_fiscal_month(date): """ Generate fiscal period based on the date provided """ if date.month in [10, 11, 12, "10", "11", "12"]: return date.month - 9 return date.month + 3
6fe0e8945efa22f11835a618b9b234082b45b757
428,420
from typing import Union from typing import List def format_keywords(keywords: Union[str, List]) -> str: """ Format keywords fromm YAML file into the comma string list expected by boto3. Possible inputs are: a) A comma string list, e.g. 'foo, bar, baz, qux' b) A list of strings, e.g. ['foo', ...
336600193a94a3d3431583e71f18b245d26c4241
340,509
def rect_sum(rect: list[list[int]], x1: int, y1: int, x2: int, y2: int) -> int: """Calculates sum of pixels of a rectangle within given borders Args: rect (list[list[int]]): matrix of integers x1 (int): top left border X coordinate y1 (int): top left border Y coordinate x2 (int):...
0ee770a2ce72c44b137416ea7dbec140dfb1bd2b
572,113
def get_supporting_points(exponent_bits, linear_bits): """ Get supporting points that have a coarse exponential segments and fine linear segments in the range of 0 to 0.5. The number of segments are given as bits. This kind of support structure is optimal for icdf and hardware implementations. ...
b02976a08cada8627e3ca481737a7812b464bf71
523,974
def version_no_valid(version: str) -> bool: """ Determine if string version is valid for getting specific PyPi package version :param version: version string :return: True if valid, False otherwise """ try: x = [int(v) for v in version.split('.')] return 2 <= len(x) <=3 exce...
6fa23fe8c3b65e164094218462d7c02206408074
179,538
from pathlib import Path from typing import Tuple from typing import List from typing import Dict def get_category(label_def_file: Path) -> Tuple[List[Dict], Dict]: """ Returns the list of categories, and a lookup table that for each category/sub_category/value in {label_def_file}, contains that assigned ...
4be53c663726c66c0fe54a7d944641128aee2b48
485,750
def coerce_result(result): """ Coerces return value to a tuple if it returned only a single value. """ if isinstance(result, tuple): return result else: return (result,)
4b750d563edd712fd1c4d0f260fa795b1f404e1e
473,090
def strip_surrounding_spaces(string): """Strip leading and trailing space | str --> str""" if string == '': return string if string[0] == ' ': string = string[1:] if string[-1] == ' ': string = string[:-1] return string
4ea16c545df9c1233425bfafcdfee16e08968229
278,288
def ReplaceParams(text, replace_params): """Replace keys with values in the given text.""" for (key, value) in replace_params.iteritems(): text = text.replace(key, value) return text
4daa374ed6ff084e168f6511dd7d192e2a337002
207,112
import tarfile from pathlib import Path def _list_files(path): """Return files in a .tar.gz file, ignoring hidden files """ with tarfile.open(path) as tar: return set(f for f in tar.getnames() if not Path(f).name.startswith('.'))
c338f5d2a5923e52aed8d0aa8ca2b290299bb39f
465,362
def _next_power_of_2(x): """ Calculate the closest power of 2, greater than the given x. :param x: positive integer :return: int - the closest power of 2, greater than the given x. """ return 1 if x == 0 else 2**(x - 1).bit_length()
616c01f6aacb7442ce1b2afbcac35b26c8f79701
12,191
def is_at_end(word1, word2): """checks if word1 is at the end of word2""" return word1 != word2 and word1 == word2[-len(word1):]
5c894542272aeb4ac08bff13dd562d228a6e638a
386,603
def _bit_str_pad(base_str: str, req_len: int, pad_type: str='0') -> str: """ Pads the left side of a string with pad_type Args: base_str: The string to add padding to req_len: The total required length of the string pad_type: What to pad the string with Returns: A left padde...
8e6361ddc8249d213768ca2938ed281196088a52
390,397
def srnirnarrowre1(b5, b8a): """ Simple NIR and Red-edge 1 Ratio (Datt, 1999b). .. math:: SRNIRnarrowRE1 = b8a/b5 :param b5: Red-edge 1. :type b5: numpy.ndarray or float :param b8a: NIR narrow. :type b8a: numpy.ndarray or float :returns SRNIRnarrowRE1: Index value .. Tip:: ...
d1b8517df55f66f28bcb3afc997f7ada9c98d027
401,644
import torch def embeddings_to_cosine_similarity_matrix(z): """Converts a a tensor of n embeddings to an (n, n) tensor of similarities. """ cosine_similarity = torch.matmul(z, z.t()) embedding_norms = torch.norm(z, p=2, dim=1) embedding_norms_mat = embedding_norms.unsqueeze(0)*embedding_norms.unsq...
f68dcdcceb4eea59d4525650111f3b2720ea878f
103,732
def normalize_index(index, length): """ Normalizes an index per sequence indexing. >>> normalize_index(0, 10) 0 >>> normalize_index(9, 10) 9 >>> normalize_index(-2, 10) 8 """ index = int(index) if 0 <= index < length: return index elif -length <= ind...
bc9be3a3ef554ca95217f93d2d698934c2f1096f
31,570
def guess_type(filename): """ Guess the particle type from the filename Parameters ---------- filename: str Returns ------- str: 'gamma', 'proton', 'electron' or 'unknown' """ particles = ['gamma', 'proton', 'electron'] for p in particles: if p in filename: ...
1dac0dcca3444244d3a4072a87963822f88724de
372,080
def balance_into_sublists(test_counts, total_shards): """Augment the result of otool into balanced sublists Args: test_counts: (collections.Counter) dict of test_case to test case numbers total_shards: (int) total number of shards this was divided into Returns: list of list of test classes """ ...
070efe511682f07b9486279794c63b1d1457bb70
273,791
def get_values(df, rows, column): """Get the desired column value from a list of dataframe iloc indexes.""" return [df.iloc[row][column] for row in rows]
2013275ba248ddcd6170f3bb71a31a468585b739
592,723
def get_expected_validation_developer_message(preference_key, preference_value): """ Returns the expected dict of validation messages for the specified key. """ return "Value '{preference_value}' not valid for preference '{preference_key}': {error}".format( preference_key=preference_key, ...
bbfbc9d3c81aa80572096f2ded75d5dafb2c8fc3
160,925
def square_area(side): """Returns the area of a square""" return side*side
6308af2538493b8a24cd456522dbf55ce82b05ca
171,931
def maxstep_terminal_condition(env, max_step=500): """A terminal condition based on the time step. Args: env: An instance of MinitaurGymEnv max_step: The maximum time step allowed for the environment Returns: A boolean indicating if the env.step exceeds the given limit """ return env.env_step_co...
d3f56346e51984a37cde67225f36497e4da6ca6a
543,121
def certificate_size(rf, mode): """returns the certificate dimension w.r.t. a given mode and RF :param rf: the RF :type rf: model.ReachabilityForm :param mode: either 'min' or 'max' :type mode: str :return: certificate dimension :rtype: int """ assert mode in ["min", "max"] C, N...
5499c0fcebaf7fb829623bc4525dce3a6cd3c1f2
294,281
def read_file_precision(file,precision): """ Read in the file converting floats to the given precision """ file_data=[] with open(file) as file_handle: for line in file_handle: formatted_data=[] for data in line.rstrip().split("\t"): try: d...
8d1901b7651f0eae04424121a885c48519f05e8d
203,465
def parse_curl_error(proc_stderr): """Report curl failure. Args: proc_stderr (str): Stderr returned from curl command. Returns: str: Reason for curl failure. """ curl_err = "" if isinstance(proc_stderr, bytes): proc_stderr = proc_stderr.decode("utf-8") try: ...
ed7fba8424b00e98a96b898160207047390c3baf
92,421
from pathlib import Path import json def return_event(file_name): """Return a Lambda event object.""" with Path(__file__).parent.joinpath(file_name).open() as json_file: test_event = json.load(json_file) return test_event
ca06628be9f42b2476b0633b9dc36b1ebae43018
550,310
def bangbang_compressor(bangbang_protocol ): """Compresses the bang bang protocol. Merges chunks of contiguous bangbang chunks into a Tuple of duration (in number of chunks) and which Hamiltonian to apply. Args: bangbang_protocol: List of HamiltonianType values, determines which ...
7e3b6e0e5678e705c54c39e31561a908900d9b08
697,976
def good_suffix_match(small_l_prime): """ Given a full match of P to T, return amount to shift as determined by good suffix rule. """ return len(small_l_prime) - small_l_prime[1]
5812985a95c439512f8422e2858d94bb3ece2b20
195,669
def strip_specific_magics(source, magic): """ Given the source of a cell, filter out specific cell and line magics. """ filtered=[] for line in source.splitlines(): if line.startswith(f'%{magic}'): filtered.append(line.lstrip(f'%{magic}').strip(' ')) if line.startswith(f'...
3c2722b86b6fc8e40c8dd51edd06d7edb28e2945
20,452
def bprop_scalar_uadd(x, out, dout): """Backpropagator for `scalar_uadd`.""" return (dout,)
c6258cf655b4a22737b6addd861d4320aaf4901f
593,795
def Pdiff(rho, Pset, T, xi, eos): """ Calculate difference between set point pressure and computed pressure for a given density. Parameters ---------- rho : float Density of system [mol/:math:`m^3`] Pset : float Guess in pressure of the system [Pa] T : float Temp...
971625d109c3e2d984c656e6a4ef8230f5ab2ddb
344,948
def _HasOneSimplePort(ports): """Check if this list of ports only contains a single simple port. Args: ports: JSON-serializable representation of address ports. Returns: True if ports is length 1 and the only attribute is just a port number with no protocol. """ if len(ports) == 1: protocol ...
e3ebf274c368455383ba1900b554c9bfdbe83ebc
288,975
def capitalized(s: str) -> str: """Returned the string, where first letter is capitalized. Id est: >>> capitalized("Two Words") -> "Two Words" >>> capitalized("another examplE") -> "Another examplE" And so on. Str is empty => return it. """ if not s: return s c, *s_ = s re...
ce05bc057df83898c8956fb74e5b6cb1bded2efd
542,064
def denormalize(img, mean, std): """ Denormalize the image with mean and standard deviation. This inverts the normalization. Parameters ---------- img : array(float) The image to denormalize. mean : float The mean which was used for normalization. std : float ...
b2fd8315ef4d282409f648ceb3e6a35652bea6e4
622,201
from typing import Iterable def ensure_iterable(value): """ensure that the results of a command are always iterable""" if isinstance(value, Iterable): return value return tuple((value,))
32ce448b9cc6003abf93f3448c948d32790d14ad
591,060
from typing import Any def is_byte_data(data: Any): """ Checks if the given data is of type byte :param data: The data to check :return: Whether the data is of type bytes or not """ return type(data) is bytes
3b04758f812220b97f21c15cacc4773c92b5bb30
44,312
def format_guesses(past_guesses): """Returns a string of the past_guesses. For example, format_guesses(['x', 'y', 'z']) should return the str 'x y z' Args: past_guesses: a list of strings Returns: A string: of past_guesses """ return " ".join(past_guesses)
5d86dcfc1b68239a908a7d2be4edc27ecb2029b5
252,454
from datetime import datetime def timestamp_to_date(timestamp: float) -> datetime: """convert different timestamp precision to python format Python2.7: https://docs.python.org/2.7/library/datetime.html#datetime.datetime Python3+ :https://docs.python.org/3.7/library/datetime.html#datetime.datetime ...
64d3fe3da8041c6e48199cebc1b847d5294e62f9
571,614
def fixture_cram_path(fixtures_dir): """Return the path to a cram file""" _file_path = fixtures_dir / "bam" / "test.cram" return _file_path
9d2636c5a9a0698332a362fcfa83875e2ea492fc
227,127
def simple_lang(pressure, n_total, k_const): """A simple Langmuir equation returning loading at a pressure.""" return (n_total * k_const * pressure / (1 + k_const * pressure))
46d4143c2dd1267c4f8199d6bbfc73b427a5b62b
294,612
import tempfile def new_temp_handle(**kwargs): """A new temporary handle ready to be written to.""" handle = tempfile.NamedTemporaryFile(delete=False, **kwargs) return handle
1fca94026f15e41d30ef9fac5b09b1fa533f78f4
513,099
from datetime import datetime def parse_time(time): """convert time string to datatime object :param str time: time representation :return: datetime.datetime :rtype: int """ ''' "Fri Aug 29 12:23:59 +0000 2014" ''' return datetime.strptime(time, '%a %b %d %X %z %Y')
27cc16659a40eaf8ef6abc11bef634669668de99
552,197
def Imu_I0c1c2c3c4(mu, c): """ I(mu, c) where c = (I0, c1, c2, c3, c4) """ return c[0]*(1-c[1]*(1-mu**0.5)-c[2]*(1-mu)-c[3]*(1-mu**1.5)-c[4]*(1-mu**2.))
6553deaff09f4a3e00364b271095b5e80472b3a1
12,789
def dec2bin(ndec): """ Convert a decimal number into a string representing the same value in binary format. """ if ndec < 1: return "0" binary = [] while ndec != 0: binary.append(ndec%2) ndec = ndec/2 strbin = "" binary.reverse() for i in binary: s...
83251f38dd1c42d28829802ee9e3e5838cef94dc
357,210
import re def _make_url_friendly(title): """Given a title that will be used as flavor text in a URL, returns a string that will look less like garbage in an address bar. """ # RFC 3986 section 2.3 says: letters, numbers, and -_.~ are unreserved return re.sub('[^-_.~a-zA-Z0-9]', '-', title)
d95b158b9d46227935e7035ad54af767d4268a84
178,145
def lookup_name(frame, name): """Get the value of the named variable, as seen by the given frame. The name is first looked for in f_locals, then f_globals, and finally f_builtins. If it's not defined in any of these scopes, NameError is raised. """ try: return frame.f_locals[name] ...
1dab10055941c27e2744ee16738f9746039339a2
254,516
def _get_last_doc_ref(path, doc): """Mutate a document top-down using a path. :param pathlib.Path path: The path. :param dict doc: The document. :rtype: dict """ for part in path.parts: if part not in doc: doc[part] = {} doc = doc[part] return doc
316c2579897e1ce5834a2bf34fc7c5929c7868c9
39,501
def remove_trailing_prefs(proposal_record, preferences): """ Function trims each preference list by eliminating possibilities indexed after accepted proposal Takes in two dictionaries: proposal_record and preference_lists Returns updated preference_lists For example: Inputs ...
67dfd38a370691d786624991f9d98915b189a957
387,027
def page_element_conf0(element): """Get confidence (as float value) of the first text result.""" if element.get_TextEquiv(): # generateDS does not convert simpleType for attributes (yet?) return float(element.get_TextEquiv()[0].conf or "1.0") return 1.0
312a7974e02ca06b36e7553c46cc8cec29ae5362
487,809
import re def parse_losses_from_log_file(file_name: str): """ Read a log file produced by VISSL and extract the losses produced at each iteration """ iterations = [] losses = [] regex = re.compile(r"iter: (.*?); lr: (?:.*?); loss: (.*?);") with open(file_name, "r") as file: for...
1eedcc7f4439100609a85aceb8bf72a7615b6090
570,869
from typing import Dict from typing import List def nest_fields(data: Dict, nest: str, eggs: List[str]): """Make sure specified fields are nested under "nest" key.""" for egg_field in eggs: if egg_field in data: if not data.get(nest): data[nest] = {} data[nest][...
986c66c5ce55e6086f07a77c990a18459b44bbfa
320,596
import pickle def load_pickle(byte_file): """Loads a pickled object""" with open(byte_file, "rb") as f: return pickle.load(f)
932f376bcd3a79398c600056fd327d5b54951e43
677,683
def best_ss_to_expand_greedy(new_set, supersets, ruleWeights, max_mask): """ Returns index of the best superset to expand, given the rule weights and the maximum allowed mask size. -1 if none possible. """ bestSuperset = None bestCost = float('inf') new_set = set(new_set) for superset...
e03a5d9d752f24b7b5188ae9babae277642bacf2
186,572
def get_percent_alloc(values): """ Determines a portfolio's allocations. Parameters ---------- values : pd.DataFrame Contains position values or amounts. Returns ------- allocations : pd.DataFrame Positions and their allocations. """ return values.divide( ...
7f4ec48b2adbdb812292930e7fda50038b6d5e96
8,906
def get_template_source(jinja2_env, template): """Returns the source text of the given `template`.""" template_source, _, _ = jinja2_env.loader.get_source(jinja2_env, template) return template_source
26c4ee57f5734059d7099fa9b4420fdbfcabbc9b
252,811
import math def is_polygonal_number(m, n): """ Checks whether a given number m is a polygonal number for some n, i.e. whether it is an n-gonal number for some n > 2. If so, it returns the index of the number in the sequence, otherwise it returns null. """ if m == 1: return ...
5e14b7bb99c3e532ac7af1ffbf03f8a6103d37a6
274,812
def get(amt): """ Creates a quadratic easing interpolator. The amount of easing (curvature of the function) is controlled by ``amt``. -1 gives a *in* type interpolator, 1 gives a *out* type interpolator, 0 just returns the :func:`linear` interpolator. Other values returns something in between. :par...
c151990f3d5cfd8adf06549ff61fcc1671f510bf
115,246
import json def get_class_names(path, parent_path=None, subset_path=None): """ Read json file with entries {classname: index} and return an array of class names in order. If parent_path is provided, load and map all children to their ids. Args: path (str): path to class ids json file. ...
65b461a9fa3d573e18ab48d858b6d558050f0a96
148,653
def get_intermittent_node_injections(generators, nodes, dispatch): """Intermittent generator node injections Parameters ---------- generators : pandas DataFrame Generator information nodes : pandas DataFrame Node information dispatch : pandas DataFrame Disp...
7de11b6d5aecfc3f5dd9ced3f08b30cdf652f16e
550,970
import re def filter_url(text): """ Remove URLs from a given string :param text: string of text :return: string of text without URLs """ return re.sub(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", '', text)
3b12ca8ecb2d1072e2e91776b01583e3833f2037
602,579
def _StrConvert(value): """Converts value to str if it is not.""" # This file is imported by c extension and some methods like ClearField # requires string for the field name. py2/py3 has different text # type and may use unicode. if not isinstance(value, str): return value.encode('utf-8') return value
1bba85cd0f6d93abf5a08e1b4b735b8c12578ad1
330,821
def img2windows(img, h_split, w_split): """Convert input tensor into split stripes Args: img: tensor, image tensor with shape [B, C, H, W] h_split: int, splits width in height direction w_split: int, splits width in width direction Returns: out: tensor, splitted image ""...
1580c818bf4ba2d0a13d0c039f4d4028dc113061
643,273
from sympy.printing.fortran import FCodePrinter def fcode(expr, assign_to=None, **settings): """Converts an expr to a string of fortran code Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of ...
8f504707ecc5c7a4951529fa2c45f118be6814db
101,271
def convert_to_crlf(string): """Unconditionally convert LF to CRLF.""" return string.replace('\n', '\r\n')
5715bfa5849cafdb9ad80eb63ab7f5bf6a0cd75a
406,579