content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def get_experience_for_next_level(level: int) -> int: """Gets the amount of experience needed to advance from the specified level to the next one. :param level: The current level. :return: The experience needed to advance to the next level. """ return 50 * level * level - 150 * level + 200
d21b6e4bacccd9f9d79c5f7e71997027c306d545
587,020
def _m2m_rev_field_name(model1, model2): """Gets the name of the reverse m2m accessor from `model1` to `model2` For example, if User has a ManyToManyField connected to Group, `_m2m_rev_field_name(Group, User)` retrieves the name of the field on Group that lists a group's Users. (By default, this field ...
30f8b5d95b8e8741c227eeb8b0ffac6aea09c750
526,926
import math def mag_of(vals): """ Returns the magnitude of a list of vals by taking the square root of the sum of the square of the components. """ assert(type(vals) is list) return math.sqrt(sum([x*x for x in vals]))
cb4cf804241fe20edeaa0b8c8f4f02b381e04757
238,475
def per_capita(place_vals, place_pop, factor=1): """Calculate per capital stats for each place. Args: place_vals: a dictionary mapping each place to an observed value. place_pop: a dictionary mapping each place to its population for some year. factor: number of people in the per capita denominator. Def...
1bb6fdb23e8305c8f961100812e4fb9c212b0061
541,901
import logging import pkgutil import importlib def page_loader(roots: list) -> dict: """ Reads page modules from subdirectories specified in the `roots` list, and returns them in a dictionary keyed by module.ROUTE. """ page_dict = {} for root in roots: for importer, package_name, _ in pkgutil...
ddc992b67ae5b94510fc1c895f68ac6d7a61792d
429,300
def sat(Bars, Children): """ Arguments: Bars -- chocolate bars array Children-- children array Return: f -- flag. f=1 if the problem is satifiable, 0 Otherwise. S -- message satisfiable/not satisfiable Cp-- if there is an excess amount, create a "ghost" children to take up the excess...
e4369c300a2b9dbee78df5a02ebaea6b09cce0f5
503,129
def add_boundary_ummg(ummg: dict, boundary_points: list): """ Add boundary points list to UMMG in correct format Args: ummg: existing UMMG to augment boundary_points: list of lists, each major list entry is a pair of (lon, lat) coordinates Returns: dictionary representation of u...
6274e3e04a73bbc42f33e89b46688c7f70c1ca26
659,443
from typing import Tuple from typing import Dict import re def _handle_compatibility(doc) -> Tuple[str, Dict[str, str]]: """Parse and remove compatibility blocks from the main docstring. Args: doc: The docstring that contains compatibility notes. Returns: A tuple of the modified doc string and a hash ...
24fe3a59e6df83dbb419eb3db199fc23341443ea
499,809
import random def random_choice(seq): """wrapper around random.choice that returns None if the sequence is empty""" return None if not seq else random.choice(seq)
40894aa9c7f03712756fecaaa32e09f0803d9da1
597,108
def page_not_found(e): """Return a custom 404 error.""" return '<h1>Sorry, nothing at this URL.<h1>', 404
f40fafec4a9df8a073d0efaf2fb2411531b1977a
634,146
def get_indexed_attestation_participants(spec, indexed_att): """ Wrapper around index-attestation to return the list of participant indices, regardless of spec phase. """ if spec.fork == "phase1": return list(spec.get_indices_from_committee( indexed_att.committee, indexed...
97f58350429209c803cfd32b4165de246900a9bf
167,806
def get_row_column(play, board): """ prompt for user input until its correct catch any letters or incomplete values in user input :param play - string, user command: :param board - object, board: :return row, column - int, locations on board in 2-D: """ # loop until there is valid user i...
b6905eb5ad89ef83f3841378d309f49b72e48b7e
637,098
from typing import Match def gen_ruby_plain_text(match: Match) -> str: """Convert matched ruby tex code into plain text for bbs usage \ruby{A}{B} -> A(B) Also support | split ruby \ruby{椎名|真昼}{しいな|まひる} -> 椎名(しいな)真昼(まひる) """ return ''.join('{}({})'.format(*pair) for pair in ...
480423c92d3a49d3e5b6d580e2771e6fa95482f4
446,925
def quacks_like_list(object): """Check if object is list-like""" return hasattr(object, '__iter__') and hasattr(object, 'append')
2bcef3b4265f439717452920a6cbe7af1916b05e
508,498
def mk_scan_mapper(condition_map, dflt=None): """Make function implementing an if/elif/.../else logic from a {bool_func: x, ...} map""" def scan_mapping(x): for condition, then in condition_map.items(): if condition(x): return then return dflt return scan_mappin...
8787cf7783b124029ce28f908c5a49c25ef5de33
57,173
import torch from typing import OrderedDict def load_model_state_from_checkpoint(checkpoint_path, net=None, prefix='model.'): """ Load model weights from Pytorch Lightning trainer checkpoint. Parameters ---------- net: nn.Module Instance of the PyTorch model to load weights to checkpo...
60f45a8d3231eb828ab7886ee66339fefdac8873
83,107
def count_lines_in_file(file, ignore_header=True): """ Counts number of records in a file. This assumes each record is defined in a single line. Similar but not limited to CSV files. By default, consider and ignores the header row (First row) from the count. Args: file - Path to file ...
6e915f3475862c61d7df92085ba410b19758f6c9
370,510
def is_parent(t, s): """Whether t is s's parent.""" return t is s.parent
4bab879707814f537c71a84e40b6dbeb94fd0c4a
114,294
def again_prompt() -> str: """Return the prompt request user character input.""" return f'\nTry again? (y/n): '
4bf7a9b5eb566129d2537e5a4d2d1dce04e4b5c9
188,966
from typing import Callable from typing import Iterable import threading def start_deamon(function: Callable, args: Iterable = ()) -> threading.Thread: """Start a deamon with the given function and arguments.""" thread = threading.Thread(target = function, args = args) thread.daemon = True thread.star...
518b48c52b824b5a1277d1d893353d7bdaf4fe08
489,896
import hashlib def StrSha1(strIn): """Compute and return (as a string, hexdigest) the sha1 of the given input""" sha1 = hashlib.sha1() sha1.update(strIn) return sha1.hexdigest()
e8a5665341c385d067822c9e2b336f1f39a13148
215,098
def collectCleanedFields(form): """Collects all cleaned fields and returns them with the key_name. Args: form: The form from which the cleaned fields should be collected Returns: All the fields that are in the form's cleaned_data property are returned. If there is a key_name field, it is not inclu...
b7f9f0e9315271063207f85a6338e776d2400c01
569,464
def psri(b3, b4, b6): """ Plant Senescence Reflectance Index (Merzlyak et al., 1999). .. math:: PSRI = (b4 - b3)/b6 :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b6: Red-edge 2. :type b6: numpy.ndarray or float :retu...
3be121d6e0852a6a83d307773ffacf8fddec9f9d
698,122
def aggregate_current(sim): """ Calculate the time series of aggregate current of all EVSEs within a simulation. Args: sim (Simulator): A Simulator object which has been run. Returns: np.Array: A numpy ndarray of the aggregate current at each time. [A] """ return sim.charging_rates...
aefd05c071257fd9d7c1978cda18ee0ca8b72df3
159,211
def bankbase(bankindex, numbanks, prgbanksize, fix8000): """Calculate the base address of a PRG bank. bankindex -- the index of a bank (0=first) numbanks -- the total number of banks in the ROM prgbanksize -- the size in 1024 byte units of a bank, usually 8, 16, or 32 fix8000 -- if false, treat the first windo...
20a1816e1b00e78b43b94c283a7407a65b2ad76c
123,346
import math def get_tile_size(num_pixels, tile_size=400): """ num_pixels is the number of pixels in a dimension of the image. tile_size is the desired tile-size. """ # How many times can we repeat a tile of the desired size. num_tiles = int(round(num_pixels / tile_size)) # Ensure tha...
a139fdb8f4548dd2f8576f116943473475294bae
686,613
import json def build_n1ql_request_body(query: str, *args, **kwargs) -> dict: """Build request body for N1QL REST API. Request body consists of ``statement`` key, ``args`` key (if using positional parameters), and any key prefixed with ``$`` (if using named parameters). See https://docs.couchbas...
7fd3cd856c15af07ad3493184fe7d5e15ea01a6f
506,591
def norm(X, n=2): """Return the n-norm of vector X""" return sum([x**n for x in X])**(1/n)
101941824728e5eb28ce40d9ddae7a0f5c6acc5d
662,599
def multiset(target, key, value): """ Set keys multiple layers deep in a target dict. Parameters ------------- target : dict Location to set new keys into key : str Key to set, in the form 'a/b/c' will be available as target[a][b][c] = value value : any Will be added...
33f9049b7a55156de253f51f63a1873b2228b78c
506,413
import requests def http_test_client(application_settings): """ Returns an HTTP client that can send requests to local server.""" class HTTPClient(): def post(self, path, data=None): return requests.post( 'http://localhost:%s%s' % (application_settings['APP_PORT'], path), ...
336b08252e97b66a0ad46224d24779d648d5440a
594,433
def bits_table_q() -> dict[int, int]: """The table of the maximum amount of information (bits) for the version Q. Returns: dict[int, int]: Dictionary of the form {version: number of bits} """ table = { 1: 104, 2: 176, 3: 272, 4: 384, 5: 496, 6: 608, 7: 704, 8: 880, 9: 1056, 10: ...
f05afb73e21b83ac4ade35cde8b5d7d19c215672
541,232
def purity(rho): """ Calculate the purity of a quantum state Parameters --------- rho : quti.Qobj Quantum density matrix Returns --------- purity_rho : float The purity of rho(=1 if pure, <1 if not pure) """ purity_rho=(rho*rho).tr() return purity_r...
36f37f67a09fb4d3cbd223fca38580674d9400f3
262,087
def make_error_response(errors: list) -> dict: """Return a JSONAPI compliant error response.""" return {'errors': [dict(error) for error in errors]}
1abb9363cebed93ba9f10287bcbf632d4ef188d4
134,928
def _get_suggestions_index(name): """Returns suggestions index name for a regular index name.""" return f'df_suggestions_{name}'
4cd2294e89f05dfbefe65ff4604c43818880d6c9
10,580
def trim_from_start(s, substring): """Trims a substring from the target string (if it exists) returning the trimmed string. Otherwise returns original target string.""" if s.startswith(substring): s = s[len(substring) :] return s
a4d68169a50672159af939855734fabff1fd8426
46,373
def doubleclick(x, y, bombs, cal, flags): """ Shortcut for double click :param x: horizontal position of the click :param y: vertical position of the click :param bombs: list of bomb positions :param cal: number of the position :param flags: list of flags :return: status after the double...
cf5fdc76b7af9d27a3b99fee53a454f59c5ff643
351,664
def self_affine_psd(q, pref, hurst, onedim=False): """Ideal self-affine power spectrum, dependent only on prefactor and Hurst exponent.""" exp = -2 * (hurst + 1) if onedim: exp = -1 - 2 * hurst return pref * q**exp
c8208ca4510085fab0c10eac5a63e885c5f1834a
77,314
def _deep_update(main_dict, update_dict): """Update input dictionary with a second (update) dictionary https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth Parameters ---------- main_dict: dict Input dictionary update_dict: d...
864fb0c9bf970438284e9c539de166d7086b4499
192,356
def _CurrentRolesForAccount(project_iam_policy, account): """Returns a set containing the roles for `account`. Args: project_iam_policy: The response from GetIamPolicy. account: A string with the identifier of an account. """ return set(binding.role for binding in project_iam_policy.bindin...
64bb0a51600778580016e3545fe7230949b46d63
39,627
def is_email_link(href=None): """Utility function to determine whether the supplied href attribute is an email link.""" print("email_link()") return href and 'mailto:' in href
44d785cd43cfb8ff7160baa78fab3597c1032f35
296,032
def fib_table_for(n): """ Returns: fibonacci list [a0, a1, ..., an] Parameter n: the position in the fibonacci sequence Precondition: n >= 0 is an int """ if n == 0: return [1] # if for n==1 is unnecessary fib = [1,1] for k in range(2,n): fib.append(fib[-1] ...
8414d4894fff10e78130252ba74bc716cf4b1755
616,905
import math def rotation_matrix_to_euler_angle(R): """ Converts a rotation matrix to [yaw, pitch, roll] """ yaw = math.atan2(R[1, 0], R[0, 0]) pitch = math.atan2(-R[2, 0], math.sqrt(R[2, 1] ** 2 + R[2, 2] ** 2)) roll = math.atan2(R[2, 1], R[2, 2]) return yaw, pitch, roll
8e1f7c77496fabbb0478454940c6cb336d19a0ce
636,994
from string import Template def substitute(template, context): """ Performs string substitution. Args: template (str): The string to perform the substitution on. context (dict): A mapping of keys to values for substitution. Returns: str: The substituted string. """ t...
387ea6a6e4ac5064eebe1afe7f73568a5096cb48
286,117
def truncate(content, length=100, suffix="..."): """ Smart string truncation """ if len(content) <= length: return content else: return content[:length].rsplit(" ", 1)[0] + suffix
1b4129390e3da4c1f6667e069fd0bad520eb393d
353,931
import math def circleconvert(amount, currentformat, newformat): """ Convert a circle measurement. :type amount: number :param amount: The number to convert. :type currentformat: string :param currentformat: The format of the provided value. :type newformat: string :para...
4d31db1094588a157e829d08fa8cee4f7ea73355
530,185
def acc_score(y_true, y_pred): """ Calculate accuracy for the given predictions vector """ cnt_matches = 0 if len(y_true) == 0: return cnt_matches for true, pred in zip(y_true, y_pred): if true == pred: cnt_matches += 1 return cnt_matches / len(y_true)
c42d20722d15492b9da19466ce3374ac072a5943
247,376
def _get_time_units(ds): """Determine time units of dataset""" try: return ds.time.encoding["units"] except Exception: return ds.time.units return None
b7639bf4578728954a0a8d952eacf50e8f8ae72b
243,802
import unicodedata def remove_accents(text): """ Remove accents from a string """ try: text = text.decode("utf-8") except (UnicodeEncodeError, AttributeError): pass text = text.replace("’", "'") # accent used as apostrophe text = unicodedata.normalize("NFKD", text).encode(...
c45e5f3864cf91bcc56608f37bdb9e31fc9a0074
99,029
def list_to_string(lst): """Takes a list of items (strings) and returns a string of items separated by semicolons. e.g. list_to_string(['John', 'Alice']) #=> 'John; Alice' """ return "; ".join(lst)
05bace68ad7eee85aa599eaa5c589b8e9fc44a99
487,466
import torch def barycenter(P, T=None, dim=0): """ Returns the barycenters of the n-gons if a topology is provided, the barycenter of the input point set along the specified dimension otherwise Parameters ---------- P : Tensor the point set tensor T : LongTensor (optional) ...
d3e9a4230b5d2bf18d826cda8b77071ee4094590
608,766
def read_cube_name_from_mdx(mdx): """ Read the cubename from a valid MDX Query :param mdx: The MDX Query as String :return: String, name of a cube """ mdx_trimed = ''.join(mdx.split()).upper() post_start = mdx_trimed.rfind("FROM[") + len("FROM[") pos_end = mdx_trimed.find("]WHERE", post_st...
cdd4511d6904383d1475432944b5c129177afc9e
404,216
import re def _is_private_name(name): """ Return true if the given variable name is considered private. Parameters ---------- name : str Variable name to check """ # e.g. __name__ is considered public. is_reserved_public_name = re.match(r"__[a-zA-Z0-9_]+__$", name) is not None ...
1232f6a52ffc9d07d7ed286771c3c75bc80db8b7
16,280
def get_dict_keys_from_val(d, val): """Get keys whose value in a dictionary match a given value. Args: d (dict): Dictionary from which to get keys. val (Any): Value whose matching keys will be extracted. Returns: List[Any]: List of keys whose values match ``val`` in ``d``. ...
86628d098e4f8f2ac93c49419d73dfb163576c78
192,803
import struct def ntohl(integer): """ntohl(integer) -> integer Convert a 32-bit integer from network to host byte order.""" return struct.unpack("=I", struct.pack("!I", integer))[0]
2db027d2a39c62e9d78eafa9125681f3f460db2f
288,096
def range_cmp(lhs, rhs): """ A range compare function. :param lhs: The left hand side of the comparison. :type lhs: Rangeable :param rhs: The right hand side of the comparison. :type rhs: Rangeable :return: -1 if lhs is before rhs, 1 when after and 0 on overlap. :rtype: int The com...
4b0f438aca6aec3afc4683b19a1045a41f0b5005
452,882
def lag_autocov(v, lag): """ Compute lag autocovariance of a vector """ tmp = 0 N = len(v)-lag for j in range(N): tmp += v[j]*v[j+lag] return tmp/N
4804216db765713cb549b3b537d2d42a09554bab
574,809
def get_data_array_extent(dataarray): """ Get the coordinate of the lower left corner and the coordinate of the upper right corner in map units. Parameters ---------- dataarray : xarray.DataArray The input datasource. Returns ------- extent : tuple of integers A tup...
39800ea9cd24dfa0f027d4046b74e5336ebcfb6b
283,888
from pathlib import Path def setup_data_path(base_path): """ Ensure filesystem path for the data exists.""" _dpath = Path.joinpath(Path(base_path), "data") _dpath.mkdir(parents=True, exist_ok=True) return _dpath
fdf9afb5f740b0112bcc46f03d2e47cdd96fd7d7
257,040
import time def cutoff_test(depth, max_depth, max_time, time_start): """ Returns True if reached maximum depth or finished time False if search is to be continued """ if depth >= max_depth or time.time()-time_start >= max_time: return True return False
a6a04340010258ee16e8fa61d007644aebedfc37
235,047
def tile_is_solid(tid): """ Return whether a tile is solid or not based on its ID. Arguments: tid: the tile ID Returns: whether the tile is solid """ return tid in (2, 3, 5)
d72e526e9f40b0267fb6bdf5becb6e4a660b7c92
258,771
from bs4 import BeautifulSoup def html_extraction(text): """ Remove from the text html tags found on stack overflow data. :param text: string containing textual data mixed with specific html tags found on stack overflow data :return: a string in which specific html tags and it's content are remov...
88e2f5d771e012f1f6320b00078af2d9d4b2a66c
103,912
def ConvertIndexListToSet(index_list): """Creates a set containing the indices of all '1' entries in the index list """ return set(i + 1 for i, j in enumerate(index_list) if j == 1)
78d0769de4b22aabd0d0ea2f906958a929da5299
10,452
import getpass def get_opal_password(opal_password, password_file): """ Retrieve the OPAL password form the user, either from the command line arguments, the file they specified or by asking them to input it :param opal_password: The actual password, if provided via the command line :param passw...
e6c13644c120beab3a629634c433343a43c92f00
54,704
def test_function_docs(arg): """ A function to test docs. :param arg: An argument. :return: A return value. """ return f"test_function_docs: {arg}"
26fb8c907a308e50dd41c0421abe8718c01132f2
589,786
def hours_to_minutes(hours: str) -> int: """Converts hours to minutes""" return int(hours) * 60
84057d6ed73fc20f06fb69741eb2c8bca9628548
607,256
def remove_junk_from_filestream( lines, banner="-----oOo-----", comment_chars=["#", "!", "*"] ): """ Removes comments, headers, and whitespace from a list of strings, parsed from a lagrit.out file. """ newlines = [] in_banner = False for line in lines: stripped = line.strip() ...
0dbbf081b3b473f31ae8becd5b3ecbb1d1bf0198
156,180
def progress_string(i, n): """ Helper to build progress string Parameters ---------- i : int current number n : int maximal number Returns ------- progress_str : str """ width = len(str(n)) string = "({0:{width}d}/{1:d})".format(i, n, width=width) retur...
0c600d944bba960a8c4822180c3de3ae5f31e35a
484,606
def getopts(argument_list): """ Parses command line arguments from argv. :param argument_list: The command line input from the terminal, separated as a list. :return: Dictionary of argument name to value. """ opts = {} while argument_list: if argument_list[0][0] == '-': ...
f08d17c71c90755a05edb92d8201cc591567d9e7
211,132
def clock_to_seconds_remaining(clock_str): """Translates a clock string to a number of seconds remaining""" minutes, seconds = clock_str.split(":") return float(minutes) * 60 + float(seconds)
4f0e616f6d079d772eb0562a0a55c7119ff2e9e9
181,571
from typing import List def is_subseries(first: List[int], second: List[int]) -> bool: """ returns True if second is subseries of first Args: first (List[int]): source of subseries second (List[int]): series that will be checked against first series Returns: bool: True if sec...
e66925002f982a2c4a2a391991bb500899d17755
444,007
def stepsDictToTimeList(stepsDict): """stepsDictToTimeList() takes a dict of steps [stepsDict] and returns a list of all the runtimes of completed steps in seconds. """ cycleTimes = [] for c in stepsDict: if stepsDict[c].complete: cycleTimes.append(stepsDict[c].elapsedTime) r...
8fffa64ff09340c7b5e1ff0459e4b0a1597fed69
426,636
def is_letter(char_code): """Return True if char_code is a letter character code from the ASCII table. Otherwise return False. """ if isinstance(char_code, str) or isinstance(char_code, bytes): char_code = ord(char_code) if char_code >= 65 and char_code <= 90: # uppercase letters ...
26ddd52a7904346a0c487b776a77ac26eb8b50f8
76,561
import random def two_random_partitions(indices, p=0.5): """given a list of indices (indicating word positions) partition into two sets p is probability of entering set1 """ set1, set2 = set(), set() for idx in indices: if random.random() > (1.0 - p): set1.add(idx) ...
972bed2f37174d5b900edaccf0f37fcded972600
129,892
import pytz def toEpoch(timestamp): """Takes a datetime object and returns nanoseconds since epoch (UTC) """ return int(pytz.UTC.localize(timestamp).timestamp()*10**9)
6ad70a0f30c4ab076e002b517b0c02b9d640c65f
310,508
def read_all_words_from_file(source_file): """ Function for read all words from source file. :param source_file: str File with words. :return: List of words. """ if not isinstance(source_file, str): raise TypeError with open(source_file, 'rb') as f_in: word...
8ad8e679f1c1d1efe7797d3a0374a706f2d5327c
573,721
def make_space(space_padding=0): """ Return string with x number of spaces. Defaults to 0. """ space = '' for i in range(space_padding): space += ' ' return space
db846fdb426bc04526744daac8487e2a90320200
688,157
def comma_split(text: str): """ Returns a list of strings after splitting original string by commas Applied to KEYWORDS, CLASSIFIERS, and REQUIREMENTS """ return [x.strip() for x in text.split(",")]
bb9f34a0ffbdd1be0db184fc026de0abddabedf6
488,828
import codecs import csv def count_rows_in_delimited_file(filename, has_header=True, safe=True, delimiter=","): """ Simple and efficient utility function to provide the rows in a valid delimited file If a header is not present, set head_header parameter to False Added "safe" mode which will handle an...
5a5c7a1e4f2e530beae717bcae489f89d68a0cf8
314,879
def simContinue(state, timeLimit = None) : """Test if simulation should continue to next state: If time based: if simulation is after time limit If HP based: if enemy has HP left """ if timeLimit is not None : return state['timeline']['timestamp'] <= timeLimit else : return state...
5a5cb8a9724d1a06839a819c72c186a0ed47e3dc
53,190
from typing import Counter def flush_finder(hand): """ Takes a 5-card hand, concats, returns the most frequent symbol. If we get 5 matching suits, we have a flush, return list: [8, high card rank, 2nd rank, 3rd rank, 4th rank, 5th rank] """ suits = ''.join(hand) if Counter(suits).most_common(1)[0][1] == 5: c...
07e089db41f83f83c88449abd9e5fa2cd1ac7254
152,297
from bs4 import BeautifulSoup def cur_game_status(doc): """ Return the game status :param doc: Html text :return: String -> one of ['Final', 'Intermission', 'Progress'] """ soup = BeautifulSoup(doc, "lxml") tables = soup.find_all('table', {'id': "GameInfo"}) tds = tables[0].find_all(...
74a60e969157e32e964e556513693f065410161e
265,966
def min_max(game_spec, board_state, side, max_depth, evaluation_func=None): """Runs the min_max_algorithm on a given board_sate for a given side, to a given depth in order to find the best move Args: game_spec (BaseGameSpec): The specification for the game we are evaluating evaluation_func ...
8a626126b8255960d1c667ab6cc19e7f0a23d86b
545,630
import math def calc_distance(ij_start, ij_end, R): """" Calculate distance from start to end point Args: ij_start: The coordinate of origin point with (0,0) in the upper-left corner ij_end: The coordinate of destination point with (0,0) in the upper-left corner R: Map resolution ...
4242d8fe01f3d286f69aac2a9432726280271530
660,314
def dm2skin_normalizeWeightsConstraint(x): """Constraint used in optimization that ensures the weights in the solution sum to 1""" return sum(x) - 1.0
79024cb70fd6cbc3c31b0821baa1bcfb29317043
2,884
import dataclasses def has_default_factory(field) -> bool: """ Test if the field has default factory. >>> from typing import Dict >>> @dataclasses.dataclass ... class C: ... a: int ... d: Dict = dataclasses.field(default_factory=dict) >>> has_default_factory(fields(C)[0]) ...
8458c059e401f66151bdee9b96dd4f1c844fa630
558,955
def get_child_entry(parent, key, default=None): """ Helper method for accessing an element in a dictionary that optionally inserts missing elements :param parent: The dictionary to search :param key: The lookup key :param default: A default value if key is missing on parent, if default is None missi...
b960ccf1ada3e93c60ea0abaffd0669de9b9f97b
276,026
def exec_fn(func): """Executes given function, returns {error,result} dict""" try: return {'result': func()} except Exception as error: # pylint: disable=broad-except return {'error': str(error)}
21a122f634833855413767013bbab03167f3ee86
615,470
def is_primitive(v): """ Checks if v is of primitive type. """ return isinstance(v, (int, float, bool, str))
d22607c0e2b93b82b1da6beb50de68668624dd71
3,687
def filterMonth(string, month): """ Filter month. """ if month in string: return True else: return False
25852ed839ce78b80661116ab1338aed7ada6bbf
306,900
import binascii def parse_object_id(value: str) -> bytes: """ Parse an object ID as a 40-byte hexadecimal string, and return a 20-byte binary value. """ try: binary = binascii.unhexlify(value) if len(binary) != 20: raise ValueError() except ValueError: raise...
503b0cd21c445d1ce851dbdc8f47b493bc17b1f8
33,125
def should_deploy(branch_name, day_of_week, hour_of_day): """ Returns true if the code can be deployed. :param branch_name: the name of the remote git branch :param day_of_week: the day of the week as an integer :param hour_of_day: the current hour :return: true if the deployment should continue...
8d8ba7657e9393d588c7019839acc859c56e63f9
62,210
def int2list(num,listlen=0,base=2): """Return a list of the digits of num, zero padding to produce a list of length at least listlen, to the given base (default binary)""" digits = []; temp = num while temp>0: digits.append(temp % base) temp = temp // base digits.extend((listlen-len(digits))*[0]...
9f10135736aaaea2bf655774ea0a5453766e633f
674,873
def _is_ref(schema): """ Given a JSON Schema compatible dict, returns True when the schema implements `$ref` NOTE: `$ref` OVERRIDES all other keys present in a schema :param schema: :return: Boolean """ return '$ref' in schema
1f805929a6b28cf4fbe16714d300f3beffeb6e73
21,015
def get_userhandles(tokens): """ Extract userhandles from a set of tokens """ userhandles = [x for x in tokens if x.startswith("@")] return userhandles
c7be5b9de5a6186bf1d32c02eef32dd565d7ce4d
232,174
def _find_duplicates(iterable): """Returns a list of duplicate entries found in `iterable`.""" duplicates = [] seen = set() for item in iterable: if item in seen: duplicates.append(item) else: seen.add(item) return duplicates
f922cbbaf33d17d4647b5edced6cf057c366fdf1
225,446
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string int) returns: integer """ # TO DO... <-- Remove this comment when you code this function handLen = 0 for val in hand.values(): handLen = handLen + val return ...
788917829149eca65f2c141eac051d1a4895c8ae
425,426
def temporal_plot_features(ax): """Set the temporal plot features""" ax.legend(loc=2) ax.set_xlabel('year') ax.set_ylabel('interhemispheric ocean\ntemperature difference (K)') ax.tick_params(top='off') ax.text(0.92, 0.08, '(a)', transform=ax.transAxes, fontsize=24, va='top') ax.axhline(y=0...
b079cd124fb361591a7097079bd187f6ef9d8950
258,052
def sbi_addition(sbi_code): """Creates link to SBI-code explanation.""" base = "https://sbi.cbs.nl/cbs.typeermodule.typeerservicewebapi/content/angular/app/#/code?sbicode=" link = base+str(sbi_code) return link
76368f8ffb8090773101706c790d58a778cc1e68
610,439
import random def random_point_triangle(p0,p1,p2): """ Uniformally Picks a point in a triangle args: p0,p1,p2 (float,float) : absolute position of triangle vertex return: pr (float,float) : absolute position inside triangle """ # Unwraping Points x0,y0 = p0 x1,y1 = p1 x2,y2 = p2 # Pickin...
af0fef3aa8bf5225e0e814503538acacf3b70969
216,890
def add_gctx_to_out_name(out_file_name): """ If there isn't a '.gctx' suffix to specified out_file_name, it adds one. Input: - out_file_name (str): the file name to write gctx-formatted output to. (Can end with ".gctx" or not) Output: - out_file_name (str): the file name to write gctx-formatted output t...
0cb90a0b6203a6162d8cdfb2c39daf8190a41a40
99,166