content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def negative_log_likelihood(y_true, predicted_distributions): """Calculates the negative log likelihood of the predicted distribution ``predicted_distribution`` and the true label value ``y_true`` # Arguments y_true: Numpy array of shape [num_samples, 1]. predicted_distribution: TensorFlow p...
cb212b478a087cf995be84549dea1ad0869838f5
654,867
def _count(bs) -> int: """Given a sequence of bools, count the Trues""" return sum(1 for b in bs if b)
58a030c42f369407f61c8f9234950d3c0bbc31b5
496,895
from typing import List from typing import Dict from typing import Any def parse_unknown_options(args: List[str]) -> Dict[str, Any]: """Parse unknown options from the CLI. Args: args: A list of strings from the CLI. Returns: Dict of parsed args. """ warning_message = ( "Ple...
e356703c36e71ab15601d64cc9187e2a91cedff4
455,302
def parse_flag(value): """ Convert string to boolean (True or false) :param value: string value :return: True if the value is equal to "true" (case insensitive), otherwise False """ return value.lower() == "true"
4555e655ecd39f362d11065718e10b144ecf2b85
633,919
def user_name_to_file_name(user_name): """ Provides a standard way of going from a user_name to something that will be unique (should be ...) for files NOTE: NO extensions are added See Also: utils.get_save_root """ # Create a valid save name from the user_name (email) # ---------...
d1e45e47f2da4f23c8b97081438aa2d732c56bb1
239,479
import yaml def load_config(path): """Load yaml collection configuration.""" with open(path, 'r') as stream: return yaml.load(stream, Loader=yaml.SafeLoader)
4beb9fff0d471bb23e06b55e18f4d286263fbd4e
644,258
def check_end_condition(grid): """The end condition: There are no more hidden characters. :param grid: The grid. :return: Returns False if there still are hidden characters, otherwise returns True. """ char_locs = grid[2] for x in char_locs: if char_locs[x][3] == 'H' or char_locs[x...
93e25b0dcc8e6ed5fd8552b45e46be7081e6aa9a
248,216
import types def _get_object_config(obj): """Return the object's config depending on string, function, or others.""" if isinstance(obj, str): # Use the content of the string as the config for string. return obj elif isinstance(obj, types.FunctionType): # Keep track of the function's module and name ...
ea95c5131e10400dd773a218cb93879849964027
469,100
from functools import reduce def excel_col_letter_to_index(x): """ Convert a 'AH','C', etc. style Excel column reference to its integer equivalent. @param x (str) The letter style Excel column reference. @return (int) The integer version of the column reference. """ return reduce(lambda...
800f650118c1216727be18722aa4b435ec34b56f
692,397
def delete_models(client, model=None, drawing=None, delete_views=None): """Delete one or more models from a drawing. Args: client (obj): creopyson Client model (str, optional): Model name (wildcard allowed: True). Defaults: all models will be deleted from the...
213da46fcb9af55c340bc687010a2d44661e5e57
497,273
def apply_ratio(o_w, o_h, t_w, t_h): """Calculate width or height to keep aspect ratio. o_w, o_h -- origin width and height t_w, t_h -- target width or height, the dimension to be calculated must be set to 0. Returns: (w, h) -- the new dimensions """ new_w = t_h * o_w / o_h...
f3143e5a5ad8aeafbb913e73aab40e8e8990ddd6
16,045
def convert_to_list(xml_value): """ An expected list of references is None for zero values, a dict for one value, and a list for two or more values. Use this function to standardize to a list. If individual items contain an "@ref" field, use that in the returned list, otherwise return the whole item...
17bb8e21e4247a14a37bb98643cfe9f847168c4c
83,420
def get_attr(obj, attr, default=None): """Recursive get object's attribute. May use dot notation. >>> class C(object): pass >>> a = C() >>> a.b = C() >>> a.b.c = 4 >>> get_attr(a, 'b.c') 4 >>> get_attr(a, 'b.c.y', None) >>> get_attr(a, 'b.c.y', 1) 1 """ if '.' not in a...
a14b821ed3d5ea61abc9b66cb80df4391519055d
464,170
def get_im_physical_coords(array, grid, image_data, direction): """ Converts one dimension of "pixel" image (row or column) coordinates to "physical" image (range or azimuth in meters) coordinates, for use in the various two-variable sicd polynomials. Parameters ---------- array : numpy.arr...
18db75e08404004f0515233b4e759d4d69b92598
571,170
def contact_sequence(data, pIDs): """ Given a pd.DataFrame with variables ['gID', 'pID', 'begin', 'end'], generate a contact sequence of events (j, i, t) where j is the group member being interrupted, i is the group member doing the interrupting, and t is the start time of the interruptive speech. Ignores non-i...
bb36b4bddefc094f036a32319a5cdf47b146005d
645,057
def matrix_mult(a, b): """ Function that multiplies two matrices a and b Parameters ---------- a,b : matrices Returns ------- new_array : matrix The matrix product of the inputs """ new_array = [] for i in range(len(a)): new_a...
5e0f27f29b6977ea38987fa243f08bb1748d4567
708,359
def emulator_uses_kvm(emulator): """Determines if the emulator can use kvm.""" return emulator["uses_kvm"]
654ec1207180e0ac90af71d9333acf3ef431add6
67,164
def expand_features_and_labels(x_feat, y_labels): """ Take features and labels and expand them into labelled examples for the model. """ x_expanded = [] y_expanded = [] for x, y in zip(x_feat, y_labels): for segment in x: x_expanded.append(segment) y_expanded....
5cd5dbe18285fdcbc633809cd95dde17e32dd82b
47,651
import math def calc_rms(data, channel, num_channels, num_samples_per_channel): """ Calculate RMS of a data buffer """ value = 0.0 for i in range(num_samples_per_channel): index = (i * num_channels) + channel value += (data[index] * data[index]) / num_samples_per_channel return math.s...
cd6bf82aeda1e54f692060befcfbd1dc47cedf86
171,620
def get_number_rows(pi_settings, ship_height, alien_height): """Determine the number of rows of aliens that fit on the screen.""" available_space_y = (pi_settings.screen_height - (3 * alien_height) - ship_height) number_rows = int(available_space_y / (alien_height)) return number_rows
3f0cb2282405e543aee93600dfdecda6a7870f79
537,110
def format_multitask_preds(preds): """ Input format: list of dicts (one per task, named with task_name), each having a 'predictions' list containing dictionaries that represent predictions for each sample. Prediction score is represented by the field {task_name}_score in each of those dicts. ...
470b23f6a5cc6b8e48ce0becfafd62104e016de8
12,041
def rivers_with_stations(stations): """This returns a list of all the rivers which have monitoring stations on them""" rivers = [] for s in stations: if s.river not in rivers: rivers.append(s.river) return rivers
4fb7490a0613b2aded3ac42dccb225fef4a147ac
325,490
def calcStraightLine(x0, y0, x1, y1): """ calculates the slope and the axis intercept of a straight line using to points in an x, y grid :Parameters: x0, y0, x1, y1: float 2 points in an x, y grid :Returns: m, b: float the slope and the axis intercept...
43ca4c5072ecb25d4cda334f1b51337cf8e4bc0d
562,728
def normalize_node_id(nid): """Returns a suitable DOT node id for `nid`.""" return '"%s"' % nid
ec40c11895ca6976792ba37eec10e6ef0d61bfde
319,282
def add_header(response): """Add header to response.""" response.cache_control.max_age = 300 response.cache_control.no_cache = True response.cache_control.must_revalidate = True response.cache_control.proxy_revalidate = True return response
b2ae7e23bd1b419c7c2664ee45dad4f0598617d4
464,802
def getReward(state, marker): """Given the state (a board) determine the reward.""" if ( state.gameWon() ): return marker * 10 else: return 0
b4532c64ae1229c15c4c4c391b07d4fb1fd0eba4
367,005
import torch def pow_p_norm(signal): """Compute 2 Norm""" return torch.pow(torch.norm(signal, p=2, dim=-1, keepdim=True), 2)
2f4a1cce69ce765b1768ed2548c2749f856b5c75
176,361
def recursive_multiply(a: int, b: int, _sum: int = 0) -> int: """Multiplies a with b, returns product Args: a (int): factor of product b (int): factor of product _sum (int): private, shouldn't be used Returns: int: product of a * b """ if b != 0: if b > 0: ...
f8d13c02e96b5c90db3f1c3a4f00031c65066622
177,393
def filter_dictionary_starts_with(dictionary, prefix): """Filters a dictionary from a key prefix.""" return {key: dictionary[key] for key in dictionary if key.startswith(prefix)}
49fc5d9701c7f0c2856c10154508654a739f49c3
208,789
import socket import struct def ip2d(ip): """IP to decimal""" packed = socket.inet_aton(ip) return struct.unpack("!L", packed)[0]
0dbbac8438da0ce705633573c701033ee72763bb
467,122
def _dehydrate_token(token): """ Convert the request token into a dict suitable for storing in the session. """ session_token = {} session_token["key"] = token.key session_token["secret"] = token.secret return session_token
5b2b27e0e4f7de776d1ef35e16be1bec1328ef3b
204,959
def get_closer(a, b, test_val): """Returns which ever of a or b is closer to test_val""" diff_a = abs(a - test_val) diff_b = abs(b - test_val) if diff_a < diff_b: return a else: return b
42452b2b03314f96ca8793802e1cd7e5ec7a8b1b
117,000
def create_constant_learning_rate_fn(base_learning_rate): """Create a constant learning rate function. Args: base_learning_rate: learning rate that will always be returned Returns: function of the form f(step) -> learning_rate """ def step_fn(step): ## pylint: disable=unused-argument return bas...
1ba81be7545080ec8be6ec550fe91500cee552ee
282,884
def strip_math(s): """remove latex formatting from mathtext""" remove = (r'\mathdefault', r'\rm', r'\cal', r'\tt', r'\it', '\\', '{', '}') s = s[1:-1] for r in remove: s = s.replace(r, '') return s
ef1231185b1344b6dbf8897198057a11b1ecc652
503,509
from importlib import import_module def load_app(module_name, objects=None): """Simply loads and returns an app module for you.\n Params: - module_name - module name of your app. - objects (str) - if provided, returns a certain part of the module instead of the whole thing. Example: `load_app(...
0bc98ba83a27302d1047c58ca7125f5ceecc419a
510,853
from typing import List def nine_to_no_fix(alts: List[str]) -> List[str]: """ Google ASR specific GASR gives 9 when the person says no or not. Therefore if both of them are present at the start of the sentence, convert all 9 to no """ count_9 = 0 count_no = 0 if len(alts) < 2: ...
0811e71f5128796f1dfc7d385465bdf8264b6b72
288,328
from datetime import datetime def minutes_to_datetime(minutes: int): """ Convert minutes to datetime :param minutes: int :return: datetime """ days, remainder = divmod(minutes, 24 * 60) hours, minutes = divmod(remainder, 60) return datetime(1900, 1, 1+days, hours, minutes)
4f4cae1cdd7cd8c30dfdd3318808bc6a688a9d04
281,275
def calc_step(epoch: int, n_batches: int, batch_index: int) -> int: """Calculates current step. Args: epoch (int): Current epoch. n_batches (int): Number of batches in dataloader. batch_index (int): Current batch index. Returns: int: Current step. """ return (epoch ...
333ccb043213bc007d77c8e087c4523613605d8e
320,613
def get_feature(tablerow): """Extract the feature of a tablerow. Parameters: tablerow (bs4.BeautifulSoup): A tablerow from the wikipedia infobox in html Returns: feature (str): Feature of the tablerow Raises: None """ tableheader = tablerow.find('th') if tableheade...
767f422aad2ff82fd86f10cbce9b6208fff6bef2
301,376
def _adjust_component(component: int) -> int: """Return the midpoint of the quadrant of the range 0-255 that the given component belongs to. Each quadrant spans 63 integers, and the midpoints are: 31, 95, 159, 223. >>> _adjust_component(25) 31 >>> _adjust_component(115) 95 """ if c...
444baac61f20dc32d05c60900f6fe7dbf7374d51
670,731
def get_centroid(M): """ Returns the centroid using the inputted image moments. Centroid is computed as being the first moment in x and y divided by the zeroth moment. Parameters ---------- M : list List of image moments. Returns ------- tuple Centroid of t...
7da4f9ef80e7daee6d95c121088e136a4c93756c
491,835
def sorted_dict(d, key=None, reverse=False): """ Return dictionary sorted using key. If no key provided sorted by dict keys. """ if key is None: return dict(sorted(d.items(), key=lambda e: e[0], reverse=reverse)) return dict(sorted(d.items(), key=key, reverse=reverse))
97b08901c1cd39a2fb17ae6db0cfd088e8366e70
83,022
import fnmatch def select_signals(signal_list, signal_spec): """ Selects signals from a signal list following signal specifications. signal_list: List of strings of possible signal names signal_spec: List of strings with signal specifications including wildcards Normal Unix file nam...
9d39ef92641e851395f02c81117d046d907d229f
224,542
def crop_scores(player): """Select specific only parts of the full score object Args: player (dict): player object from which to read the score Returns: score (dict): filtered scores from the game data """ score = {} # if there is no active username, nobody finished, but the ...
5466cf39b59ce4b49b7da3ff2c355b2d7b46455c
35,959
def percent_delta(old_score, new_score): """Calculates the percent change between two scores. """ return float(new_score - old_score) / float(old_score)
ceaf4e0eecb436818c12a52c32fb1db7f88ca102
582,044
def accession_entry_map(klass): """Creates a `dict` mapping from accessions to the owning instance. for all instances in the database represented by `klass`. Parameters ---------- klass : :class:`Pubmed` or :class:`Psimi` A class having the accession attribute. Returns ------- ...
d3ca955ccea5ee45e1eb938f89c6fdd61ff42390
322,982
def difference(li1, li2): """Difference of two lists.""" return list(list(set(li1)-set(li2)) + list(set(li2)-set(li1)))
c2e9b30c5eeed330f7a10531c4269c6aa43e3ab7
65,856
def calcGeometricMean (theList): """Calculates the geometric mean of a list of values. :param theList: The list of which the geometric mean :type theList: list :return: The geometric mean of the values of theList :rtype: float """ product = 1 root = 0 for value in theList: p...
923ca02c2bb39e65fd7f25eaf0becaae03bdeb18
106,231
def equal_zip(*args): """ Zip which also verifies that all input lists are of the same length """ # make sure that all lists are of the same length assert len(set(map(len, args))) == 1, "lists are of different lengths {}".format(args) return zip(*args)
f50ad8586d24516ba641e1bbef5d62879a0f3d6b
23,922
def limit_vector(vector, bottom_limit, upper_limit): """ This function cut the a vector to keep only the values between the bottom_limit and the upper_limit. Parameters ---------- vector : list The vector that will be cut upper_limit : float The maximum value of the vector. ...
5c520f09e6caac08461cd6add911ea69a12afa72
47,293
def dict_get(d, *args): """Get the values corresponding to the given keys in the provided dict.""" return [d[arg] for arg in args]
0202cbed5cc2b81b1d8b74986630e3c797596837
595,111
def construct_resolver(model_name, resolver_type): """Constructs a resolve_[cable_peer|connected_endpoint]_<endpoint> function for a given model type. Args: model_name (str): Name of the model to construct a resolver function for (e.g. CircuitTermination). resolver_type (str): One of ['connecte...
e7c16fec9e68d875725692349742380dfb1e0e2c
198,973
def Predict_Var(vcf, snp_mdl, ind_mdl): """Predicts the truth value of a variant Parameters ---------- vcf : DataFrame vcf file with variants of interest snp_mdl : XGBClassifier classifier object, trained on SNPs ind_mdl : XGBClassifier classifier object, trained on InDe...
1544785f95b02016f249f5b5e390a1b075c1325b
439,617
def slice_list(list_a: list, start: int, end: int): """Problem 18: Extract a slice from list. Parameters ---------- list_a : list The input list start : int The start of the slice end : int The end of the slice Returns ------- list A slice of the ini...
853088bb218666771e6024953e9956524b139443
665,452
def rk4_step(force, state, time, dt): """Compute one step of the rk4 approximation. Parameters ---------- force : callable Vector field that is being integrated. state : array-like, shape=[2, dim] State at time t, corresponds to position and velocity variables at time t. ...
9d2eb400d608d1c15b73e1e78fcd3bebaff868bd
363,471
import time def fade_to_black(connection): """Transition from the current brightness to zero in a smooth fade""" command = "X03FE" # Lowers by 2 points # Loop until the number is 0 i = 0 while i < 128: connection.write(bytes(command, 'UTF-8')) i += 1 time.sleep(0.03) ...
1de93280291d873c8928140a6ff6410fce70bde1
405,390
import torch def _default_collate_mbatches_fn(mbatches): """Combines multiple mini-batches together. Concatenates each tensor in the mini-batches along dimension 0 (usually this is the batch size). :param mbatches: sequence of mini-batches. :return: a single mini-batch """ batch = [] ...
e3855ff27ec82e723008b9ad6ad6af94fda27b23
323,775
import pytz def add_timezone(time_record): """ Add a default America/New_York timezone info to a datetime object. Args: time_record: Datetime object. Returns: Datetime object with a timezone if time_record did not have tzinfo, otherwise return time_record itse...
e3e16fbb87f9d5ff3a3bd5c7f24b3bd880700a00
127,352
import pickle def compare_pickles(filename_1, filename_2): """Read in both pickles, and see if they match, and return both of them. Inputs: filename_1: string filename_2: string Outputs: pickle_equal: boolean - True iff the pickles have identical contents ...
83af39a6b2416d15bbe97a3c29d7a3e6a8c43bd1
345,705
def clean_name(name): """Replace dashes and spaces with underscores""" return '_'.join(name.split()).replace('-', '_')
5de49ec064b3e6b4359d29d822fd732d080f8a43
641,612
from typing import Any import json def to_json(path: str, output: Any) -> None: """ Writes output to json file Args: path (str): Output path output (Any): Content to output """ with open(path, "w") as stream: return json.dump(output, stream)
9957f8678f94fb9c440cfc0d3387ae8f281e054b
512,454
from typing import List from typing import Any from typing import Dict import torch def my_data_collator(features: List[Any]) -> Dict[str, torch.Tensor]: """ A nearly identical version of the default_data_collator from the HuggingFace transformers library. """ first = features[0] batch = {} ...
80e8e92fee033716ee1e5b22231e6127d2c6349e
595,991
import re def tokenize(text): """ First splits on r',|\.|and', strips the result, and removes empty tokens :param text: the text to tokenize :return: list of string tokens """ tokens = re.split(r',|\.(?![0-9])|and', text) tokens = [t.strip() for t in tokens] tokens = [t for t in tokens...
38cb91abc8c3cfdc87bf4aa3728184bb157daaf4
251,500
def convert_coord_to_axis(coord): """ Converts coordinate type to its single character axis identifier (tzyx). :param coord: (str) The coordinate to convert. :return: (str) The single character axis identifier of the coordinate (tzyx). """ axis_dict = {"time": "t", "longitude": "x", "latitude"...
bc32c5837f7a4fb5a515ee4c3b50d67cf244da6a
261,953
def get_executors(tech): """From a loaded technique, get all executors.""" return tech['atomic_tests']
b5a8d6ed974c22f1c73b6671961b009828d1e87c
600,930
import random def generate_random(choicelist): """ This function generates a random choice of the items in the given list. """ random_choice = random.choice(choicelist) return random_choice
46129c987a78b11d8a12f43625cfd6b825efb0c9
440,138
import re def regex_compile(search_string): """ Used to compile regex search string to object. ------------Parameters---------- search_string : str : a regex pattern string to be used to search for ------------Yields-------------- A compiled regex object that can be used in regex matching comm...
da9e64de7ba35ad3e58289827f973d127d3fc4ca
359,254
import json def get_json(data): """ Attempts to load json from data. @param data - String containing json @return - Dictionary|None """ try: return json.loads(data) except ValueError: return None
85ce81316904d5b52a21fa5c45365401ff9f3d85
311,467
import uuid def generate_molecule_object_dict(source, format, values): """Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Opti...
4a917521a2fd5d4f5f5180aa7d5da60aec2cd00a
81,712
def is_viable_non_dupe(text: str, comparison) -> bool: """text must be longer than 2 ('""'), not 'NULL' and not in comparison. :param text: String to be tested. :param comparison: Dictionary or set to search for text in. :return: bool """ return 2 < len(text) and text != 'NULL' and text not in ...
da575dffde2f13e849949350aabe73f40802f14a
697,200
def get_info(sets, **totals): """ Gets use input and adds values to the totals dictionary. Loops through the items in the totals dictionary and asks for user input for each amount and adds replaces that item's amount in the dictionary. Parameters: - sets (int): Number of sets for the curr...
1d9b43c2fc10a05b23c60a8bd6230e3fac5141dc
544,376
def is_opening_ext_app(text): """ Checks if user wants to open an app. Parameters: text (string): user's speech Returns: (bool) """ state = False keyword = [ "open", "launch", "start" ] for word in keyword: if ((text.lower()).find(word.lower()) != -...
7a78306753cb53b3e5ff1bd2aee356c2a0a33fb6
461,601
def get_test_case_and_alg(basename): """ Extracts the changefile name and algorithm name from the basename of the file, e.g. changefile100Lazy Floyd-Warshall.out yields the output (changefile100, Lazy Floyd-Warshall) """ # Skip "changefile" in the search of an integer i = 10 while True: try: # Check if we...
43e25512d534a2672b4a426f8670e92c6b07d79b
570,495
import re def check_date_format(date: str): """Parses a string for a date. Returns true if date is any of the following formats: MM/DD/YYYY MM/DD DD Arguments: date -- the date string """ return re.match('([0-9]){1,2}((\/)([0-9]){1,2}){0,1}((\/)([0-9]){4}){0,1}', date)
06287a64cc8e48367a8bab875e7165bd11fe6b23
296,863
def search_workspace(results, params, meta): """ Return result data from es_client.query and convert into a format conforming to the schema found in rpc-methods.yaml/definitions/methods/search_workspace/result """ return { "search_time": results["search_time"], "count": results["...
5a102b964d2ecacc4e8ae590a9afd5ed4d1dba23
446,882
import re def parse_timestep_str_from_path(path: str) -> str: """ Get the model timestep timestamp from a given path Args: path: A file or directory path that includes a timestep to extract Returns: The extrancted timestep string """ extracted_time = re.search(r"(\d\d\d\d\d\...
fad83119e54fb7110e6f414d213cfa58c5b72db8
451,754
from typing import Any from typing import Optional from typing import Sequence def is_allowed_types(value: Any, allowed_types: Optional[Sequence[Any]], required: Optional[bool] = None) -> bool: """ Check whether the type of value is in the allowed types. :param value: the value to check the type of :...
2fd9dee9d83cd5b59b3486ab918ecd290552b6e6
118,934
def str2list(src: str) -> list: """Separate a string to a list by \n and ignore blank line at the end automatically.""" ret = src.split("\n") while ret[-1] == "\n" or ret[-1] == "": ret.pop() return ret
db14b8646db070563a7ad3cbb7a915588e9560d1
285,408
def pe6a(n=100): """ sum >>> pe6a() 25164150 """ s1 = sum(x for x in range(1, n + 1)) s2 = sum(x * x for x in range(1, n + 1)) return(s1 * s1 - s2)
8552ca60e9b734a7d3aa46ae416ee78ce7860aea
160,818
import requests import re def CTDrequest(chemName, association, outputPath): """ Function requests CTD database. Search all genes which interact with the chemical given in input. Could be several chemicals names. Analysis will be done like if it's only one chemical. If hierarchicalAssociations is...
2fc172e9de82568f84c386c791d0f44a966a65ce
464,380
import json from datetime import datetime import time def iso_to_unix_secs(s): """ convert an json str like {'time': '2022-02-05T15:20:09.429963Z'} to microsecs since unix epoch as a json str {'usecs': 1644927167429963} """ dt_str = json.loads(s)["time"] dt = datetime.strptime(dt_str, "%Y-%m-%...
7421e6b1781b712ebc3b8bafd1d96f49c5f1d10c
35,587
import cmath import math def line_details(Z1_polar=True, Z1=[] , Z0_polar=True, Z0=[] , length=1 , CT=[1,1], VT=[1,1] , Prim=True): """This function returns the line details for a MiCOM P543 relay Inputs: Z1_polar: Set True if the inp...
154720abeef715745ee2616e858c5f610bf2cccc
605,381
def issafe(arg): """Returns False if arg contains ';' or '|'.""" return arg.find(';') == -1 and arg.find('|') == -1
f6746d5290e21eb84d7343792d277bce4c1871ff
21,804
def get_email_name(email_from): """parse email from header and return the name part First Last <ab@cd.com> -> First Last ab@cd.com -> "" """ if "<" in email_from: return email_from[: email_from.find("<")].strip() return ""
f8b9fad0a6ceff486a71b24995576845a521a83f
537,979
def remove_repeated_first_names(names): """ Question 14.4: Remove duplicate first names from input array """ seen = set() output = [] for name in names: if name[0] not in seen: output.append(name) seen.add(name[0]) return output
4b433d248bfde2075ca57d7cee6e6d6b7c224170
285,628
def get_location(response): """ Returns location of a transaction as returned in the header of a response object. :param response: response object succeeding a successful post request. :type response: requests.models.Response :return: str """ resource_location = response.headers('location') ...
82bc9fb272d47fd8e9d245cb15d4581455c690a8
595,157
def _standardize_sample_or_class_weights(x_weight, output_names, weight_type): """Maps `sample_weight` or `class_weight` to model outputs. # Arguments x_weight: User-provided `sample_weight` or `class_weight` argument. output_names: List of output names (strings) in the model. weight_ty...
f0997b61a2759f35ee3aabddc8b57e3424843562
330,632
def traverse_enum(type_context, enum_proto, visitor): """Traverse an enum definition. Args: type_context: type_context.TypeContext for enum type. enum_proto: EnumDescriptorProto for enum. visitor: visitor.Visitor defining the business logic of the plugin. Returns: Plugin sp...
b83864f19eb9891b4cc6877a137949857343e18f
215,381
def remove_synthetic(entries): """ Filter the given entries by removing those that are synthetic. Args: entries: An iterable of Entry nodes Yields: An iterable of Entry nodes """ return (e for e in entries if not e.synthetic)
bbbd5f79d245520d26a804f4a3a7387c10975018
282,767
from typing import MutableMapping from typing import Any def basic_params_override(dtype: str = 'float32') -> MutableMapping[str, Any]: """Returns a basic parameter configuration for testing.""" return { 'train_dataset': { 'builder': 'synthetic', 'use_per_replica_batch_size': True, ...
341e8e3df6b0ec99d148ea43909aa28404939c15
368,834
def predict_large_image(model, input_image): """Predict on an image larger than the one it was trained on All networks with U-net like architecture in this repo, use downsampling of 2, which is only conducive for images with shapes in powers of 2. If different, please crop / resize accordingly to avoid...
f762c997c953487df32e111babfb25059a2d344d
683,060
def buildIdtoLoc(geoDict, idNameDict): """ Build a dictionary mapping from user id to country for all classes Takes as input a dictionary mapping usernames to countries (as build by builddict, above) and a dictionary that maps from ids to names (as is built by globalUserList.readId2Name) and re...
2ace83855d81adf7dc6d804d3452c3c4b4a5037e
333,852
import re def getMessageError(response): """ Extracts the error message from an ERDDAP error output. """ emessageSearch = re.search(r'message="(.*)"', response) if emessageSearch: return emessageSearch.group(1) else: return ""
020a597e8b3a93a190536dd83b7dfe12d651ed07
694,226
def round_to_full_hour(time_step: int, base=3600) -> int: """Returns given `time_step` and rounds it to nearest full hour""" return base * round(time_step / base)
38b6d78b46e1c2d026a31c0906f0f5f149eddf02
443,570
def check_emptiness(param): """ Function that checks a canvas to see if is empty or not Args: param : str The string we want to check if is empty or not Returns: Bool True if empty, False if not. """ if param not in ['\n', '\r\n']: return True else: ...
a4a5a5a31836558931a6beee9f2bca9cb5b4f7dd
337,328
def vect_mult(_V, _a): """ Multiplies vector _V (in place) by number _a """ for i in range(len(_V)): _V[i] *= _a return _V
8035b8634dc88c98f03c1531d577a05f97215ae9
342,504
def multiplex_user_input(data, cube): """ Get input from the user and ensure it's a multi-dataset dict. Parameters ---------- data: Union[pandas.DataFrame, Dict[str, pandas.DataFrame]] User input. cube: kartothek.core.cube.cube.Cube Cube specification. Returns ------- ...
27841b3e0e22cf8259ed73db9d2289903cd88b1d
222,334
def _create_product(product_name): """Given a product name, prompt for the price and quantity Return a new product record { "name": (str), "price": (float), "quantity": (int) } """ while True: try: product_price = float(input('What is the price for the item? ')) break...
6dbe3fd064a80e261018d4094e458c1bc22e6bf3
94,345
import json def load_json_file(file_path): """Return the contents of a json file in the file path.""" if not file_path: return {} try: with open(file_path, "r", encoding="uts-8") as read_file: data = json.load(read_file) return data except FileNotFoundError as e...
5ac25e98a476cf778aa291be5e84765d5babc9e9
304,481
import csv def read_csv(file_path): """ Reads all lines from csv file into a list representing the header and a seperate list holding all data. Args: file_path (str): Path to file Returns: tuple[list[str], list[list[str]]]: Header, other rows """ with open(file_path, "r"...
46b2dbc57c00cb4e4da83741d4c777495cdf021b
424,744