content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def is_specific_url(url): """ This api has a tendency to give you the url for the general list of things if there are no entries. this separates "people/" from "people/123456" """ return url[-1] != '/'
0d4842f4e4264d38350738d92060e0d2de0575c1
693,765
def conj(x): """Return conjugate of x.""" return x.conjugate()
d710ca7536775d26176d6a759cb072532ff9428d
693,768
def fv_annuity(n,c,r): """ Objective: estimate future value of an annuity n : number of payments c : payment amount r : discount formula : c/r*((1+r)**n-1) e.g., >>>fv_annuity(2,100,0.1) 210.0000000000002 """ return c/r*((1+r)**n-1)
312d4d5a8760d86dfb310c7527e02ae611500369
693,771
from typing import Iterable from typing import Any def _iterable_choices_metavar(iterable: Iterable[Any]) -> str: """Generates a string metavar from iterable choices. Args: iterable (Iterable[Any]): Iterable object to generate metavar for. Returns: str: Generated metavar """ # Ge...
e556b62205904cb4c6ffb565f7dfe3c02f02a87d
693,773
from datetime import datetime def get_datetime(utc_time): """ Convert date string to datetime object """ utc = datetime.strptime(utc_time, '%Y-%m-%dT%H:%M:%S.%fZ') return utc
a3626e9eef59a4c8d26944c4776dd6e6c30b21d8
693,779
def unique(v): """Generates a list from a sequence where each value appears only once, and the order is preserved.""" try: sequence = list(v) except: return [] seen = set() seen_add = seen.add return [item for item in sequence if not (item in seen or seen_add(item))]
3c314afeade3ef813ba4869d5017f395184508cb
693,780
def get_audio_route(log, ad): """Gets the audio route for the active call Args: log: logger object ad: android_device object Returns: Audio route string ["BLUETOOTH", "EARPIECE", "SPEAKER", "WIRED_HEADSET" "WIRED_OR_EARPIECE"] """ audio_state = ad.droid.telecom...
2c6353a4f46523d947c949da36782316f8925ff1
693,782
import re def FormatWikiLinks(html): """Given an html file, convert [[WikiLinks]] into *WikiLinks* just to ease readability.""" wikilink = re.compile(r'\[\[(?:[^|\]]*\|)?([^\]]+)\]\]') return wikilink.sub(r'*\1*', html)
e33203875579d1dccb9e09370205da63ff9b3b2c
693,787
def increment_char(c): """ Increment an uppercase character, returning 'A' if 'Z' is given """ return chr(ord(c) + 1) if c != 'Z' else 'A'
89c30f136acc05b289e61e0125ffe4ae3fcc213e
693,796
def RGB(red, green, blue): """ Given integer values of Red, Green, Blue, return a color string "#RRGGBB" :param red: (int) Red portion from 0 to 255 :param green: (int) Green portion from 0 to 255 :param blue: (int) Blue portion from 0 to 255 :return: (str) A single RGB String in the format "#R...
cf2776f29e6b189de3ef8d18f025a40b47e505d0
693,797
import json def get_data(file_name: str) -> dict: """ Simply getting data from specified json file name and returning them in the form of a python dictionary """ with open(file_name, "r") as json_file: content = json.load(json_file) return content
d501d5162c58d2c24a1250e1623947d5f5c6d4bc
693,799
from typing import Optional def _get_bool(val) -> Optional[bool]: """ Converts val to bool if can be done with certainty. If we cannot infer intention we return None. """ if isinstance(val, bool): return val elif isinstance(val, str): if val.strip().lower() == 'true': ...
da2562baeedd83454912745f1b436e1ae18562a4
693,803
def qw_not_found(arg1, arg2, path=None, headers=None, payload=None): """This function is used when a not found resource should be returned. According arg2 argument, if "not_found" is detected as a string then payload is returned directly or as part of "data" dictionnary. """ payload = {'errors': [{ ...
243648edcada2d35baafeeedee80e7319bd8c115
693,807
def determine_spec_version(obj): """Given a STIX 2.x object, determine its spec version.""" missing = ("created", "modified") if all(x not in obj for x in missing): # Special case: only SCOs are 2.1 objects and they don't have a spec_version # For now the only way to identify one is checking...
7c3df55c7e80a6823571aa1af8d77cfd9c67710f
693,808
import re def exemplar_unicodes_convert(text): """Convert \u1234 strings inside the exemplar text to real unicode characters Args: text (str): Raw exemplar string. Eg: "a b c \\u0041" Returns: [type]: Converted exemplar string: Eg: "a b c A" """ uni_chars = re.findall(r"\\u([0-9A...
47d0f1435839a8b47c199fa6f5a687694427860e
693,809
import math def luv_to_hcl(ell: float, u: float, v: float) -> tuple[float, float, float]: """Convert the color from CIELUV coordinates to HCL coordinates.""" h = math.atan2(v, u) c = math.hypot(v, u) h = h + math.tau if h < 0 else h return h, c, ell
569b51e1cf0155e06c34d6f1655e76cd2966243f
693,811
def WebError(message=None, data=None): """ Unsuccessful web request wrapper. """ return { "status": 0, "message": message, "data": data }
022d150fba82bbc1bd7ed425eb34c657d4c7c673
693,819
def generate_rearranged_graph(graph, fbonds, bbonds): """Generate a rearranged graph by breaking bonds (edge) and forming others (edge) Arguments: graph (nx.Graph): reactant graph fbonds (list(tuple)): list of bonds to be made bbonds (list(tuple)): list of bonds to be broken Re...
33f842cee6759f7a012c9806c67fdcee6797bd6c
693,823
def create_html_url_href(url: str) -> str: """ HTML version of a URL :param url: the URL :return: URL for use in an HTML document """ return f'<a href="{url}">{url}</a>' if url else ""
5c41f5035a2b549e9c969eccbcc960a100600e7e
693,824
def tet_vector(i, num_tet): """ Gives the tet equation for the i^th tetrahedron. """ out = [] for j in range(num_tet): if i == j: out.extend([1]*3) else: out.extend([0]*3) return out
5470ee3873e76514c6c747a2066744669df837c0
693,825
from typing import Counter from typing import Tuple def _counter_key_vals(counts: Counter, null_sort_key="ø") -> Tuple[Tuple, Tuple]: """ Split counter into a keys sequence and a values sequence. (Both sorted by key) >>> tuple(_counter_key_vals(Counter(['a', 'a', 'b']))) (('a', 'b'), (2, 1)) ...
0965c7c7e5717c4daa48d3b9a188ad70283b41c7
693,827
def disable_event(library, session, event_type, mechanism): """Disables notification of the specified event type(s) via the specified mechanism(s). Corresponds to viDisableEvent function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier ...
9bbaf57350e46dd3a6035b9f73c2c286821cb346
693,828
def autocast_value(value): """Cast string to string, float, bool or None. """ if value is None: return value_lcase = value.lower() if value_lcase == "null": return if value_lcase == "false": return False if value_lcase == "true": return True try: retur...
0ed4ebcd64f2f9b2fd200d296d4e216a8eca73ac
693,829
def fixture_sample_tag_name() -> str: """Return a tag named 'sample'""" return "sample"
1a5efe0fd71234333ceb778e05bec31315947b52
693,833
def version_is_available(request): """Return a boolean, whether we have the version they asked for. """ path = request.line.uri.path version = request.website.version return path['version'] == version if 'version' in path else True
4c6e67153733b7d547423babc878ea4c71ab50f8
693,835
def is_tag_list(tag_name, conf): """ Return true if a XMP tag accepts list or not """ return tag_name in conf["list"]
0dfcf08abcea9979129515b1a0dec22fae1ec46d
693,836
import hashlib def filehash(filepath): """ Compute sha256 from a given file. Parameters ---------- filepath : str File path. Returns ------- sha256 : str Sha256 of a given file. """ BUF_SIZE = 65536 sha256 = hashlib.sha256() with open(filepath, "rb")...
7e0af85ef132b19a18c4ba7956f58e46256d6445
693,838
from typing import List def split_text(text: str) -> List[str]: """Split arbitrary text into words (str).""" return text.split()
4c48a604b1e76bd7d712cbbc670d9c8d3439e6e0
693,839
def get_uid_search_xpath(uid): # type: (str) -> str """Method to get the XPath expression for a UID that might contain quote characters. Parameters ---------- uid : str Original UID string with XPath expression. Returns ------- str Processed XPath expres...
f3626595b13a9a9cae44d7f5cb9729602e902db9
693,842
import math def round_half_up(x): """ Return x rounded to the nearest integer, with halves rounded up to match SLiM's behaviour. Python's round() function rounds halves to the nearest even number. """ floor_x = math.floor(x) if x - floor_x < 0.5: return floor_x else: re...
e670457f89a46fd560a08f3cbcb956a2a1f10d72
693,843
def DEFAULT_NULLVALUE(test): """ Returns a null value for each of various kinds of test values. **Parameters** **test** : bool, int, float or string Value to test. **Returns** **null** : element in `[False, 0, 0.0, '']` Null value c...
ce9e4df2fc9b3b492bc3a4b3a98c96aa71eca3d0
693,847
import hashlib def sha256_string(content: str) -> str: """ Hash a string using SHA256. Cache results for repeated use. """ h = hashlib.sha256() h.update(content.encode("utf-8")) return h.hexdigest()
a6cf8dfe6becc7ffb7d3e71c6bb50b6092f2480d
693,851
import math def get_bearing(origin_point, destination_point): """ Calculate the bearing between two lat-lng points. Each argument tuple should represent (lat, lng) as decimal degrees. Bearing represents angle in degrees (clockwise) between north and the direction from the origin point to the dest...
cfba6ccd27e0b2e2b8fa34f71611b061692f6dbf
693,852
def parseRating(line): """ Parses a rating record in MovieLens format userId::movieId::rating::count . """ fields = line.strip().split("::") return int(fields[3]), (int(fields[0]), int(fields[1]), float(fields[2]))
de5ee9c8bfc810aae08c27de650a003a9d69a790
693,856
import math def get_MCC(mx): """ Gets the Matthews Correlation Coefficient (MCC)""" [tp, fp], [fn, tn] = mx return (tp * tn - fp * fn) / math.sqrt( (tp + fp) * (tp + fn) * (tn + fp) * (tn + fn) )
59de25c96f75d02e8bf4283bfeeb909d2e9646a9
693,857
def format_list(resources): """ Format comma-separated list of IDs from Django queryset. """ return ', '.join(map(str, sorted(resources.values_list('id', flat=True))))
96b13f3fce990a0c6ec1dd8d75a0cddb8f4b3fa4
693,865
def to(act: bool, models): """Convert Uvicore Model or List[Model] to JSON""" # Uvicore models already have a pydantic .json() method # But if its a List of models, we must handle manually if not act: return models if not models: return '{}' if type(models) == list: results = [] ...
766477a17aa6e0456c650d9dc6f1ad3545953f5b
693,869
def getPath(keyword, topicNames, topicPaths, topicIDs): """ Function to get the path of a particular keyword in ACM Tree. Parameters: keyword (string) - the keyword for which we want the path. topicNames (dictionary) - the name of the topic as the key and the topic ID number as value. ...
22dd07a92290c4a7b9e1baf70ef0cc98960b4520
693,871
def ort_categories(reisende): """Returns all unique location tuples in reisende""" ort = reisende[["Linie", "Richtung", "Haltestelle"]].itertuples( index=False, name=None ) ort = list(set(ort)) return ort
e4637e36485632333d6b48fd415be155e300e1cb
693,872
def get(name, default=None): """ Get the value of a variable in the settings module scope. """ return globals().get(name, default)
15cb84209896fb39785f3e6014861fa9f74374a1
693,874
import json def _get_group_code_names(fob_file_path): """Extract code names from first run in fobs file.""" with open(fob_file_path) as f: data = json.load(f)[0] return [r['name'] for r in data['runs']]
82529c133a1a55092d0b629d01522487fcc8bdaf
693,875
def process_index(index, intensity, interaction_symbol): """ Process index to get edge tuple. Disregard edge weight. Args: index (str): index of the edge list dataframe. intensity (float): intensity of the edge. interaction_symbol (str): symbol used to separate node labels. Ret...
923602fd8be1281b0d28769ccd38e95c03d645b1
693,877
def _profile_strings(base, tails): """Creates a list of profile strings by concatenating base with all permutations of tails""" return [base + level + tail[1] for tail in tails for level in tail[0]]
9a6175d23a7ce89ca3f943a91749859137eb1a6f
693,878
def get_tracks_in_frame(frame_ind, track_list): """ Return list of all tracks present in frame ind. """ tracks_in_frame = [] for track in track_list: if (track['last_frame'] >= frame_ind and track['first_frame'] <= frame_ind): tracks_in_frame.append(track) retur...
dd0c76b3729d7ac427ff64be6121c9947af253c8
693,879
def callables(potential_callables): """Ensure that the callables are in fact a sequence.""" if callable(potential_callables): return [potential_callables] return potential_callables
9ce117902deda63a5ed2c6546c418cbd700104c4
693,882
def get_new_board(dimension): """ Return a multidimensional list that represents an empty board (i.e. string with a space at every position). :param: dimension: integer representing the nxn dimension of your board. For example, if dimension is 3, you should return a 3x3 board :return: For ex...
28e65a0d5eef00d9c27f1d915d41f9e16c3d9026
693,886
def jobs_with_duration(jobs_df): """Return the list of jobs that have a duration""" return jobs_df[jobs_df.duration_m.notnull()]
1900ec9f9ac61bc4313055f2d71bef20794bec08
693,887
from typing import List from typing import Tuple from typing import Union import random import math def sampling( same_name_different_cluster: List[Tuple[str, str, Union[int, float]]], different_name_same_cluster: List[Tuple[str, str, Union[int, float]]], same_name_same_cluster: List[Tuple[str, str, Union...
8a5bef90b76b3d29f63fd7d8d510930671c78b7f
693,890
def compare( data_a: list, data_b: list ): """ Compares two sets of evaluated data with the same Args: data_a (list): data set A data_b (list): data set B Returns: A String "Correct/Total Answers" and the percentage """ ...
6bb1ad3ab8a77c10a89174267e29e80bbc5f9ccd
693,891
def minimus(*args): """Find the smallest number""" print(min(*args)) return min(*args)
c94c4879abdd8d5bd5b252e72575efea4e5afff4
693,898
def _labels_to_state(scan_label, compscan_label): """Use scan and compscan labels to derive basic state of antenna.""" if not scan_label or scan_label == 'slew': return 'slew' if scan_label == 'cal': return 'track' return 'track' if compscan_label == 'track' else 'scan'
a5a6429fa7c7d108fff469b0efe0848e4eb02fcb
693,902
from functools import reduce def Sum(iterable): """Return the concatenation of the instances in the iterable Can't use the built-in sum() on non-integers""" it = [ item for item in iterable ] if it: return reduce(lambda x,y:x+y, it) else: return ''
2a70a282771f5707a545a12c674f4602cd2f6d7c
693,903
def read_def_file(def_file): """Read variables defined in def file.""" ret = {} f = open(def_file, 'r') for line_ in f: if line_.startswith("#"): continue line = line_.rstrip() if len(line) == 0: continue if "=" not in line: continue ...
3999378bca9ad4cdccaa480a50635ad567473c66
693,905
from pathlib import Path def compute_custom_vars(job_dict, dirs): """ DO NOT CHANGE THE NAME OR ARGS OF THIS FUNCTION!!!!!! This function will receive as input a dictionary representing all the run parameters for a given job, enhanced with all the keys provided as global run parameters in your sp...
17c010bb7d4871211707dac04e6b2d312b3aa233
693,906
def filter_issues_on_state(issues, value): """Filter issues based on the value of their state. Parameters ---------- issues : list Issue data. value : str Value required for the state, e.g. "open". Returns ------- filtered_issues : list Filtered issues. """ ...
3bbff601afb621a4b6cfe5caf89bd04aa6c85063
693,912
from pathlib import Path def data_path(path): """Return a path inside the `data` folder""" return Path(__file__).parent.parent.parent / 'tests' / 'data' / path
37af3bde0869bd9746d9743d237b03b09373a408
693,915
def select_bin(bin_list, values): """ Select a bin from a list of bins based on an array of values. Args: bin_list (arr): List of Bin objects values (arr): Array of parameters. Not that the parameters need to be in the same order that the bins were generated from. Returns: ...
5ec77d2cddcf596e786467d96ce79ed3687515fc
693,917
def slice_bounds(seq, slice_obj, allow_step=False): """Calculate the effective (start, stop) bounds of a slice. Takes into account ``None`` indices and negative indices. :returns: tuple ``(start, stop, 1)``, s.t. ``0 <= start <= stop <= len(seq)`` :raises ValueError: if slice_obj.step is not None. :param allow_s...
1005ce9eccaa078d057dfa1a07be5fbdba3611a7
693,918
def get_quota(trans, id): """Get a Quota from the database by id.""" # Load user from database id = trans.security.decode_id(id) quota = trans.sa_session.query(trans.model.Quota).get(id) return quota
3c989923e77a837541f414a3e54a7be8911e1faf
693,920
import re def REGEXMATCH(text, regular_expression): """ Returns whether a piece of text matches a regular expression. >>> REGEXMATCH("Google Doc 101", "[0-9]+") True >>> REGEXMATCH("Google Doc", "[0-9]+") False >>> REGEXMATCH("The price today is $826.25", "[0-9]*\\.[0-9]+[0-9]+") True >>> REGEXMATC...
d5625e9cd06bf3f05569892d09fe22c781f59c00
693,921
import json def is_jsonable(obj): """ Checks if obj is JSONable (can be converted to JSON object). Parameters ---------- obj : any The object/data-type we want to know if it is JSONable. Returns ----- boolean True if obj is JSONable, or False if it is not. """ ...
50a568b898c9609206993372983d40add0be4603
693,922
def get_el_config(charge): """ Returns the electronic shell structure associated with a nuclear charge """ # Electronic shells: 1s, 2s, 2p, 3s, 3p, 4s, 3d, 4p, 5s, 4d, 5p, 6s, 4f, 5d, 6p, 7s, 5f, 6d, 7p el_shell = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # Maximum number of electrons ...
db8a06ab5e277ce5468b0e6d43670d92d9a57580
693,923
from typing import List import collections def preprocess(tokens: List[str], fs=False): """Return text length, vocabulary size and optionally the frequency spectrum. :param fs: additionally calculate and return the frequency spectrum """ txt_len = len(tokens) vocab_size = len(...
03a20358116b3a44791fff32641abe9508e7c233
693,927
from pathlib import Path def get_run_number(run_path: Path) -> int: """Get the "run number" of a specific run. Parameters ---------- run_path : Path Path to the run directory Returns ------- int "run number" """ run_info = run_path.name.split("_")[3] run_num_s...
08946b69bd2b4be818b2fbce2136c04f004bcf05
693,928
def find_winner_line(line): """Return the winner of the line if one exists. Otherwise return None. A line is a row, a column or a diagonal. """ if len(line) != 3: raise ValueError('invalid line') symbols = set(line) if len(symbols) == 1: # All equal. return line[0] ...
c83bd89a601eacf0ef1d9cfc40ec895b39f18f40
693,929
def unique(o, idfun=repr): """Reduce a list down to its unique elements.""" seen = {} return [seen.setdefault(idfun(e),e) for e in o if idfun(e) not in seen]
9cc1d629e7b084acc838b4672dafd0af4df25298
693,933
import random def random_text(size): """Randomly generate text""" alphabet_and_numbers = 'abcdefghijklmnopqrstuvwqyz1234567890' return(''.join(random.choice(alphabet_and_numbers) for _ in range(size)))
fe72e51479756da32456a57c671d51ccee067d72
693,935
import torch def get_device(is_gpu=True): """Return the correct device""" return torch.device( 'cuda' if torch.cuda.is_available() and is_gpu else 'cpu')
30a3389fb165d4dfb6719a50432d4576885461ba
693,937
def isnumeric(x): """Test whether the value can be represented as a number""" try: float(x) return True except: return False
d98817a855e31ea90a9c26e71f60327217c3323d
693,938
def dict_equal(first, second): """ This is a utility function used in testing to determine if two dictionaries are, in a nested sense, equal (ie they have the same keys and values at all levels). :param dict first: The first dictionary to compare. :param dict second: The second dictionary to compare. ...
269ae3059462155e812ff1a5337f59845cfa86d2
693,944
import math def ln(input): """Logaritmo natural Devuelve el logaritmo base e de un número. Args: input(Number): valor real Returns: Number """ return math.log(input,math.e)
aca994104608bca957cd0ab4edfc9e7d42c0800b
693,947
def merge(left_array, right_array): """ 1. Compare first element of both arrays and append the smaller element 2. Increment the index for the array whose element has been pushed to merged array 3. Follow steps 1 and 2 till either of two array is completely merged 4. Whichever array has remaining ele...
f4997c3e7a4d67b3dd8f2f0c86335b28e29d9450
693,952
def get_dat_id(datnum, datname): """Returns unique dat_id within one experiment.""" name = f'Dat{datnum}' if datname != 'base': name += f'[{datname}]' return name
4505b1932e89c6e76073605011aa6260563daa84
693,956
import ctypes def _IsStructType(t): """Tests if a type is a structure.""" return type(t) is type(ctypes.Structure)
7815d9fc840d3fbd29625404b96fa60eb209dd85
693,957
def asini_c(pb, mf): """ asini_c(pb, mf): Return the orbital projected semi-major axis (lt-sec) given: 'pb' is the binary period in sec. 'mf' is the mass function of the orbit. """ return (mf * pb * pb / 8015123.37129)**(1.0 / 3.0)
1dd86e3619f2334d6d11c14bc2a7b28c9edb9dcb
693,961
async def root(): """ Useful for health checks :return: a simple static JSON object """ return {"status": "ok"}
c49c7b99ce096692f3fe5f97e198697fc61c4ccb
693,962
def argkvpair(val): """Splitting key value pair""" k, v = val.split("=", 1) return k, v
9da942bbc32b402217cebcbc1a39d637c15f835b
693,967
from typing import Any from typing import List from typing import Dict def check_is_list_of_dicts(x: Any) -> List[Dict[Any, Any]]: """Return `x` if it is `List[Dict[Any, Any]]`, raise `ValueError`.""" if not isinstance(x, list): raise ValueError() for element in x: if not isinstance(elemen...
b9c0c09607543e52f29ab678a4a27198e2f8642e
693,969
def php_str_repeat(_input, _multiplier): """ >>> php_str_repeat('*', 10) '**********' >>> php_str_repeat('xyz', 3) 'xyzxyzxyz' >>> php_str_repeat('xyz', 0) '' """ return _input * _multiplier
f083f3041c324001caa4791e0fda61aaedb9aa50
693,970
def header_translate_inverse(header_name): """Translate parameter names back from headers.""" name_dict = {'XCENREF': 'xcen_ref', 'YCENREF': 'ycen_ref', 'ZENDIR': 'zenith_direction', 'ZENDIST': 'zenith_distance', 'FLUX': 'flux', ...
ffd333d190530a70aca014438cb3b49eab032e42
693,972
def tsne_kwargs(n_dims, initial_dims, perplexity=25.0, n_epochs=1000): """Argument options for t-SNE. Args: n_dims (int): Number of dimensions to reduce the data down to. initial_dims (int): Initial number of dimensions of the input data. perplexity (float): Related to number of nearest...
4899997827237b383efb60eb6a2b2b230b879170
693,976
def restriction(d, keys): """Return the dictionary that is the subdictionary of d over the specified keys""" return {key: d.get(key) for key in keys}
9fdb2d2e5bea0d96380e592ffc6d7720b32ade30
693,979
import re def is_valid_phone(phone_number: str): """Return if the phone_number is valid or not.""" if phone_number: phone_number = phone_number.replace(' ', '').replace('(', '').replace(')', '') return re.match( r'[\+\d]?(\d{2,3}[-\.\s]??\d{2,3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\...
d9837f9a53a59fdbf92f2c16325a6c4a7c61e1c6
693,980
def binary_to_int(value): """Convert binary number to an integer.""" return int(value, 2)
792b9a01883dc460fb23d10f8415fa6656918c56
693,984
def mul_with_none(v1,v2): """ Standard mul treating None with zero """ if v1 is None: return None elif v2 is None: return None else: return v1 * v2
7065344b6b0efa29cbca14a7ddf85a3ade245fa1
693,988
def root_node(tree, level): """ :param tree: a tree node :param level: level of the subtree (0 for the tree root) :return: subtree root at level """ root = tree while root.level > level: root = root.parent return root
ae41c019e6e2c395343aa64d32ac6a700e451a24
693,989
def StringsContainSubstrings(strings, substrings): """Returns true if every substring is contained in at least one string. Looks for any of the substrings in each string. Only requires each substring be found once. Args: strings: List of strings to search for substrings in. substrings: List of strings...
52c4bf8b4b57a9ebb619c71276881668b6b2a1d8
693,993
def normalize_url(url): """If passed url doesn't include schema return it with default one - http.""" if not url.lower().startswith('http'): return 'http://%s' % url return url
b957056e8ca32f6294c85466b6e52c56bb1dba84
693,995
def singleGridIndexToGridIndex(i, nx, ny, nz): """ Convert a single into a grid index (3 indices): :param i: (int) single grid index :param nx, ny, nz: (int) number of grid cells in each direction :return: ix, iy, iz: (3-tuple) grid index in x-, y-, z-axis direct...
12b3b69318437d66007fd5295ae209f8186f8b36
693,997
import inspect def _get_not_annotated(func, annotations=None): """Return non-optional parameters that are not annotated.""" argspec = inspect.getfullargspec(func) args = argspec.args if argspec.defaults is not None: args = args[:-len(argspec.defaults)] if inspect.isclass(func) or inspect.i...
b16e9a2f1e7b71a1b9e4df303a01e67b7eea5482
693,998
def keysplit(strng): """Split an activity key joined into a single string using the magic sequence `⊡|⊡`""" return tuple(strng.split("⊡|⊡"))
eb1b965843b602410010337f23ea8d0053f2f4b6
693,999
def flatten_list(list_): """ Turn list of lists into list of sublists' elements. Args: list_ (list): List to flatten. Returns: Flattened list. """ return [item for sublist in list_ for item in sublist]
d42e5ef6e2333cbce13e6c4294f8b6b2c8a8ca70
694,001
def get_close_descriptions(get_close, initial_state, current_state): """ Get all 'close' descriptions from the current state (if any). Parameters ---------- get_close: function Function that gets the drawer or the door which is closed. initial_state: nd.array Initial state of the...
54181292066c58968d00e4d8e3d98ec584338e18
694,003
import torch def l1_penalty(model, l1_coef): """Compute L1 penalty. For implementation details, see: https://discuss.pytorch.org/t/simple-l2-regularization/139 """ reg_loss = 0 for param in model.pcca.parameters_('y2'): reg_loss += torch.norm(param, 1) return l1_coef * reg_loss
3a2ddc8bd1eeb64e9ba94ce009e2e621677242e2
694,007
def list_parameters_from_groups(parameter_groups, groups): """Return a list of all the parameters in a list of groups """ return [ p for group in groups for p in parameter_groups[group].values() ]
2ea08013616fd978a49f8d2d5fa2c233a17fabfc
694,008
def unhex(s): """unhex(s) -> str Hex-decodes a string. Example: >>> unhex("74657374") 'test' """ return s.decode('hex')
dcf2d6cd9c317b5eafd77e969272fcf753556403
694,014
import json def get_features(geojson_file, nl=False): """ Get a list of features from something resembling geojson. Note that if the `nl` option is True, this will return a generator that yields a single feature from each line in the source file. """ if nl: return (json.loads(line) fo...
4c3b5bb6011968d3361b44b358a846b51d4fe404
694,016
def _find_test_plugins(paths_file): """ One plugin path per line in a file Lines starting with a # are considered comments and ignored :type paths_file: str :return: List[str] """ with open(paths_file) as f: path = f.read().strip() lines = path.split('\n') lines = [x.strip(...
85b62e7ab41ea02f8d123379c7b0ed2b96c46566
694,019
def sort_population(population): """ Sorts the population based on fitness values :param population: population to be sorted :return: sorted population """ return sorted(population, key=lambda tup: float(tup[1]), reverse=True)
b368bcec27cb4162a464260895bfa463729b4df1
694,020
import hashlib def block_compute_raw_hash(header): """ Compute the raw SHA256 double hash of a block header. Arguments: header (bytes): block header Returns: bytes: block hash """ return hashlib.sha256(hashlib.sha256(header).digest()).digest()[::-1]
4d6a13316aeda0ec42ca1904ba91170ca0220aae
694,021