content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def _split_key_val(option): """Split extra command line data into key-value pairs.""" key_val = option.split(':', 1) assert len(key_val) == 2, "Bad option %s" % option return key_val
85991e20b7384b7e3a7c966d2e6b52e573befb64
458,359
def get_utm_zone(pos_longlat): """ Return the UTM zone number corresponding to the supplied position Arguments: pos_longlat: position as tuple (This in (long, lat) Returns: The UTM zone number (+ve for North, -ve for South) """ lon, lat = pos_longlat z = int(lon/6) + 31 if lat < 0: z = -z return z
4f3ff0dac79928b9d0be3980527388c9f5051ed3
450,332
def create_dataset(dataset=None, labels=None): """ 构造贷款数据集 :return: 返回数据集和是否放贷(二类) """ if not dataset: dataset = [[0, 0, 0, 0, 'no'], [0, 0, 0, 1, 'no'], [0, 1, 0, 1, 'yes'], [0, 1, 1, 0, 'yes'], [0, 0, 0, 0, 'no'], [1, 0, 0, 0, 'no'], [1, 0, 0, 1, 'no'], [1, 1, 1, 1, 'yes'], [1, 0, 1, 2, 'yes'], [1, 0, 1, 2, 'yes'], [2, 0, 1, 2, 'yes'], [2, 0, 1, 1, 'yes'], [2, 1, 0, 1, 'yes'], [2, 1, 0, 2, 'yes'], [2, 0, 0, 0, 'no']] if not labels: labels = ['不放贷', '放贷'] # labels = ['年龄', '有工作', '有自己的房子', '信贷情况'] return dataset, labels
5a363c71f6ff85ed6a765c39defa3fdac97b2aa3
419,310
import hashlib def compute_hash(filename): """Returns the MD5 hash of the specified file""" with open(filename, 'r') as f: contents = f.read().encode('utf-8') return hashlib.md5(contents).digest()
f73983580eace66d9fe82156ac6cddb1576da58d
657,397
from pathlib import Path from typing import Optional def find_in_parents(name: str, path: Path) -> Optional[Path]: """Searches parent directories of the path for a file or directory.""" path = path.resolve() while not path.joinpath(name).exists(): path = path.parent if path.samefile(path.parent): return None return path.joinpath(name)
252a1d8c985f1a572495401f79759dea35bc56e6
164,647
import turtle def create_turtle(c, s): """ Creates a turtle :param c: turtle's color :param s: turtle's size :return: returns the turtle object fully created """ t = turtle.Turtle() t.pencolor(c) t.pensize(s) return t
3d9d35133a0c8a9c29f9a6a0fa6ff8b101930a08
32,937
def quote_str(value): """ Return a string in double quotes. Parameters ---------- value : str Some string Returns ------- quoted_value : str The original value in quote marks Example ------- >>> quote_str('some value') '"some value"' """ return f'"{value}"'
beaa09c517b6c2a92363652f2d53ae7fd6becabe
622,499
def parse_info_papers(_bibtexs:str, **kwargs) -> list: """ Parse the bibtex string and return a list of lists with the information It is anticipated that _bitexs has the format %l;%Y;%j;%J;%V;%p;%q;%K;%pp;%pc;%R;%S;%T;%u\n according to the documentation (https://ui.adsabs.harvard.edu/help/actions/export) """ # Split per paper _result = _bibtexs.split('\n\n') # Split information _result = [pp.split(';') for pp in _result] return _result[:-1]
7b0df544f6935a423d3dc8a875d7004d1eddd175
377,027
def c_not(condition): """The intrinsic conditional function Fn::Not Returns true for a condition that evaluates to false or returns false for a condition that evaluates to true. Fn::Not acts as a NOT operator. """ return {'Fn::Not': [condition]}
1d98bfbd83c3ba9994018179647caf622041522b
392,480
import re def get_vocabs_from_string(string): """ Search in the string to find BODC vocabularies (P01, P06 etc. Returns a dict where: key = vocabulary value = code """ result = re.findall('SDN:[A-Z0-9]*::[A-Z0-9]*', string) vocabs = {} for item in result: split_item = item.split(':') vocabs[split_item[1]] = split_item[3] return vocabs
5bc5a2fa472f703291907b4c7322415128ebce9a
655,841
def format_route_name(name: str) -> str: """Used to format route name. Parameters ---------- name : str Returns ------- str """ return name.replace("Route", "").lower()
073f1407af0045289fe3dd5fa0554345d0b1c582
487,825
def modify_color(hsbk, **kwargs): """ Helper function to make new colors from an existing color by modifying it. :param hsbk: The base color :param hue: The new Hue value (optional) :param saturation: The new Saturation value (optional) :param brightness: The new Brightness value (optional) :param kelvin: The new Kelvin value (optional) """ return hsbk._replace(**kwargs)
ecc5118873aaf0e4f63bad512ea61d2eae0f7ead
708,258
import torch def batch_first2time_first(inputs): """ Convert input from batch_first to time_first: [B * T * D] -> [T * B * D] :param inputs: :return: """ return torch.transpose(inputs, 0, 1)
1e806761c6ab09dc9f601100cd2e5d4187fc1630
445,810
import math def roundup(n: float, m: int = 10) -> int: """ Round up a number n to the nearest multiple of M. Args: n: Number m: Multiple of which number to roundup to Returns: Rounded integer number """ return int(math.ceil(n / m)) * m
818a683d666b1f868453a11a8755eabb7f46881a
250,668
def get_byte(byte_str): """ Get a byte from byte string :param byte_str: byte string :return: byte string, byte """ byte = byte_str[0] byte_str = byte_str[1:] return byte_str, byte
2a00e82e10b4ed367ebcb41240d5393477f3b234
62,748
def form_save_instance(self, commit=True, **kwargs): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: raise ValueError( "The %s could not be %s because the data didn't validate." % ( self.instance._meta.object_name, 'created' if self.instance._state.adding else 'changed', ) ) if commit: # If committing, save the instance and the m2m data immediately. self.instance.save( **kwargs) self._save_m2m() else: # If not committing, add a method to the form to allow deferred # saving of m2m data. self.save_m2m = self._save_m2m return self.instance
5bfb3c30ae0f1447706c90fa9b39b3bf2575ca22
464,686
def convert_tuple_to_8_int(tuple_date): """ Converts a date tuple (Y,M,D) to 8-digit integer date (e.g. 20161231). """ return int('{0}{1:02}{2:02}'.format(*tuple_date))
8584bb9ade995e95d12c9d09c4a6d52f7df44f5d
8,208
def validate_HR_data(in_data): # test """Validates input to add_heart_rate for correct fields Args: in_data: dictionary received from POST request Returns: boolean: if in_data contains the correct fields """ expected_keys = {"patient_id", "heart_rate"} for key in in_data.keys(): if key not in expected_keys: return False return True
ee5393145f92c5c5e844e3c2577a04be35d27f5f
362,664
def _format_group(g): """Format a restclient deployment group for display""" return { 'id': g['id'], 'description': g['description'], 'default_blueprint_id': g['default_blueprint_id'], 'deployments': str(len(g['deployment_ids'])) }
905ddf119009c89967f642ca92e6d3323ff523f6
301,517
def is_hermitian(matrix): """Check, if a matrix is Hermitian. `matrix` can be a numpy array, a scipy sparse matrix, or a `qutip.Qobj` instance. Args: matrix (list, numpy.ndarray, qutip.Qobj): Input array. Returns: bool: Returns `True` if matrix is Hermitian, `False` otherwise. Examples: >>> m = np.array([[0, 1j], [-1j, 1]]) >>> is_hermitian(m) True >>> m = np.array([[0, 1j], [-1j, 1j]]) >>> is_hermitian(m) False >>> m = np.array([[0, -1j], [-1j, 1]]) >>> is_hermitian(m) False >>> from scipy.sparse import coo_matrix >>> m = coo_matrix(np.array([[0, 1j], [-1j, 0]])) >>> is_hermitian(m) True """ if hasattr(matrix, 'isherm'): # qutip.Qobj return matrix.isherm else: # any numpy matrix/array or scipy sparse matrix) # pylint: disable=simplifiable-if-statement if (abs(matrix - matrix.conjugate().transpose())).max() < 1e-14: # If we were to "simplify the if statement" and return the above # expression directly, we might get an instance of numpy.bool_ # instead of the builtin bool that we want. return True else: return False
eae341b5fcf1c0a22f8b3f33ee432f67d077bb8d
398,345
def cli(ctx, workflow_id, invocation_id, step_id): """See the details of a particular workflow invocation step. Output: The workflow invocation step. For example:: {'action': None, 'id': '63cd3858d057a6d1', 'job_id': None, 'model_class': 'WorkflowInvocationStep', 'order_index': 2, 'state': None, 'update_time': '2015-10-31T22:11:14', 'workflow_step_id': '52e496b945151ee8', 'workflow_step_label': None, 'workflow_step_uuid': '4060554c-1dd5-4287-9040-8b4f281cf9dc'} """ return ctx.gi.workflows.show_invocation_step(workflow_id, invocation_id, step_id)
8892a9afa419ca270beb920e7b0390513a297054
190,063
def format(format_string, cast=lambda x: x): """ A pre-called helper to supply a modern string format (the kind with {} instead of %s), so that it can apply to each value in the column as it is rendered. This can be useful for string padding like leading zeroes, or rounding floating point numbers to a certain number of decimal places, etc. If given, the ``cast`` argument should be a mapping function that coerces the input to whatever type is required for the string formatting to work. Trying to push string data into a float format will raise an exception, for example, so the ``float`` type itself could be given as the ``cast`` function. Examples:: # Perform some 0 padding item_number = columns.FloatColumn("Item No.", sources=['number'], processor=format("{:03d})) # Force a string column value to coerce to float and round to 2 decimal places rating = columns.TextColumn("Rating", sources=['avg_rating'], processor=format("{:.2f}", cast=float)) """ def helper(instance, *args, **kwargs): value = kwargs.get('default_value') if value is None: value = instance value = cast(value) return format_string.format(value, obj=instance) return helper
fb485665d4dae0d8f4aaf256f48a49972c9f3120
170,412
def parse_header( line ): """Parses a header line into a (key, value) tuple, trimming whitespace off ends. Introductory 'From ' header not treated.""" colon = line.find( ':' ) space = line.find( ' ' ) # If starts with something with no whitespace then a colon, # that's the ID. if colon > -1 and ( space == -1 or space > colon ): id = line[ 0: colon + 1 ] value = line[ colon + 1:] if value: value = value.strip() return ( id, value ) return ( None, None )
854fb76adf49fdc6743ae5ee167ea93bf1ad711e
61,681
def _rangelen(begin, end): """Returns length of the range specified by begin and end. As this is typically used to calculate the length of a buffer, it always returns a result >= 0. See functions like `_safeDoubleArray` and `safeLongArray`. """ # We allow arguments like begin=0, end=-1 on purpose. This represents # an empty range; the callable library should do nothing in this case # (see RTC-31484). result = end - begin + 1 if result < 0: return 0 return result
8e010b08ef91b5ce011b348832ca1cdb829e519a
572,882
def form_message(sublines, message_divider): """Form the message portion of speech bubble. Param: sublines(list): a list of the chars to go on each line in message Return: bubble(str): formaatted to fit inside of a bubble """ bubble = "" bubble += message_divider bubble += "".join(sublines) bubble += message_divider return bubble
c3ca1c2a684d25b439a594cfc5ade187f272a2c1
30,123
def get_extra_libraries(experiment_md): """get the extra_libraries field, or empty if not specified""" return experiment_md.get("extra_libraries", ())
5605625929fd60d71294a92f6c0c1000374c8870
515,711
def dms_to_string(d, m, s, decimals=2): """Converts degrees, minutes and decimal seconds to well formated coordinate string. Example: (41, 24, 12.2)-> 41°24'12.2" :param int d: degrees :param int m: minutes :param float s: decimal seconds :param int decimals: second's decimals :rtype: str """ return "{d:d}°{m:02d}'{s:0{z}.{c}f}\"".format(d=d, m=m, s=s, z=decimals + 3 if decimals > 0 else 2, c=decimals)
e97d904123b2534b40ed38645af61835c7dfaf12
178,351
def indent(input_string): """Put 4 extra spaces in front of every line.""" return '\n '.join(input_string.split('\n'))
645f8f7e793e99aec9453327c5e07a429aeab439
579,335
def frequency_temporal_evolution(Q_12,Q_23): """ convolve displacement estimates in the frequency domain Parameters ---------- Q_12 : np.array, size=(m,n), ndim={2,3} cross-power spectrum of first interval. Q_23 : np.array, size=(m,n), ndim={2,3} cross-power spectrum of second interval. Returns ------- Q_13 : np.array, size=(m,n), ndim={2,3} cross-power spectrum of total interval. See Also -------- spatial_temporal_evolution Notes ----- The matching equations are as follows: .. math:: \mathbf{S}_1, \mathbf{S}_2 = \mathcal{F}[\mathbf{I}_1], \mathcal{F}[\mathbf{I}_2] .. math:: \mathbf{Q}_{12} = \mathbf{S}_1 \odot \mathbf{S}_{2}^{\star} .. math:: \mathbf{Q}_{13} = \mathbf{Q}_{12} \odot \mathbf{Q}_{23} See also Equation 17 in [1]. .. [1] Altena & Kääb. "Elevation change and improved velocity retrieval using orthorectified optical satellite data from different orbits" Remote sensing vol.9(3) pp.300 2017. """ # -------D13--------- # | | # | | # +---D12---+---D23---+ # ------------------------------> time Q_13 = Q_12*Q_23 return Q_13
73750df2b5af844a37ce5ee879ad3767a3ff5c5f
504,978
def noise(nx, ny, gen): """ Generate noise value at (nx, ny) using generator gen, tweaked to return a value from (0, 1) """ return gen.noise2d(nx, ny) / 2.0 + 0.5
de57ed5bd7e864b7464f3771fc01a2ad2338bd62
261,106
def recon_rule_preview_payload(passed_keywords: dict) -> dict: """Create a properly formatted payload for retrieving a rule preview from recon. { "filter": "string", "topic": "string" } """ returned_payload = {} if passed_keywords.get("filter", None): returned_payload["filter"] = passed_keywords.get("filter", None) if passed_keywords.get("topic", None): returned_payload["topic"] = passed_keywords.get("topic", None) return returned_payload
dc18c7db03ca133666ac9c8d7f46ae6d4c55c19d
91,214
def alpha_rate(iteration): """ alpha learning rate :param iteration: the count of iteration :return: alpha """ return 150/(300 + iteration)
a62499dcc211827d7edaecf8cba047e4439c6c57
231,195
def cost(graph,e): """ Return the cost of an edge on a graph. Parameters ---------- G = A networkx graph. e = An edge on graph. Returns ------- The weight of an edge 'e' on a graph 'graph'. """ return graph.edges[e]['weight']
af41eb667d2ea586b523fd31c72d4e377ffbfa04
69,384
def cli(ctx, invocation_id): """Get a detailed summary of an invocation, listing all jobs with their job IDs and current states. Output: The invocation step jobs summary. For example:: [{'id': 'e85a3be143d5905b', 'model': 'Job', 'populated_state': 'ok', 'states': {'ok': 1}}, {'id': 'c9468fdb6dc5c5f1', 'model': 'Job', 'populated_state': 'ok', 'states': {'running': 1}}, {'id': '2a56795cad3c7db3', 'model': 'Job', 'populated_state': 'ok', 'states': {'new': 1}}] """ return ctx.gi.invocations.get_invocation_step_jobs_summary(invocation_id)
d5e83ecdc061e8161a5f7ca7ac9bcda864293b7d
52,567
def render_User_detailed(self, h, comp, *args): """Render user detailed view""" h << h.h3(self.data.fullname) h << h.div(comp.render(h, model='avatar')) return h.root
eb1d692f828e219d5dc398fcfbac686bf2df7636
537,064
def stripped(text): """Remove invisible characters Remove all characters not between the ascii 32 and 127 and not an ascii 10 (line feed) """ def whitelist(c: int) -> bool: if 31 < c < 127 or c == 10: return True return False return "".join(filter(lambda c: whitelist(ord(c)), text))
caf4d1afa1d90dbab8d42f5535eedc3d314d48cd
220,543
def content(title, headers, items, style, **context): """ A table. :param title: Table's title. :param headers: List of headers [..., {"id": "<header_id>", "title": "<header_title>"}, ...] :param items: List of content (dicts). Each header will take <header_id> part. :param style: Style of the form (if applicable): primary|danger|info|warning|success :return: """ return { "class": "content", "title": title, "headers": headers, "items": items, "style": style, "context": context }
0f6fe5aeeb594f66620475ca488221044a888a7d
157,624
def get_game_url(season, game): """ Gets the url for a page containing information for specified game from NHL API. :param season: int, the season :param game: int, the game :return: str, https://statsapi.web.nhl.com/api/v1/game/[season]0[game]/feed/live """ return 'https://statsapi.web.nhl.com/api/v1/game/{0:d}0{1:d}/feed/live'.format(season, game)
a404609e565b7b423226bba056f93574d2d21366
448,366
def test_lessthan(value, other): """Check if value is less than other.""" return value < other
199d674e58b55a6c5ceb49136e35ace0067c5289
159,961
from typing import List def convert_sample_names_to_indices( names: List[str], samples: List[str] ) -> List[int]: """Maps samples to their integer indices in a given set of names. Used to map sample string names to the their integer positions in the index of the original character matrix for efficient indexing operations. Args: names: A list of sample names, represented by their string names in the original character matrix samples: A list of sample names representing the subset to be mapped to integer indices Returns: A list of samples mapped to integer indices """ name_to_index = dict(zip(names, range(len(names)))) return list(map(lambda x: name_to_index[x], samples))
3e4bf00fbcebb446757dcf1a09d6dbb1382c8ea1
178,591
import re def remove_spaces(text): """ Remove all the tabs, spaces, and line breaks from the raw text Args: text(str) -- raw text Returns: text(str) -- text clean from tabs, and spaces """ # remove \t, \n, \r text = text.replace("\t", "").replace("\r", "").replace("\n", "") # remove 2 or more than 2 spaces text = re.sub('\s{2,}', '', text) return text
64e0da2b0a6c274476ed1a560fd814479608908b
626,628
def format_theta(theta_topic_row, limit=10): """ Convert full theta row (topic) into compact form The result will be sorted by probability (high to low). """ topics = theta_topic_row; topics = [(i, val) for i, val in enumerate(topics)]; topics = sorted(topics, key=lambda x: x[1], reverse=True); topics = topics[:limit]; return topics;
05c30a16c40d1c474aabb4e054ff8d9cba6e1cd5
88,050
def remove_numbers(s): """Remove any number in a string Args: s (str): A string that need to remove number Returns: A formatted string with no number """ return ''.join([i for i in s if not i.isdigit()])
0777995b98e1c312d6f5276a85cf8eecd7978a51
404,285
from typing import List from typing import Union def list_sum_normalize(num_list: List[Union[int, float]]) -> List[float]: """Normalize with sum. Args: num_list(list): List of number to normalize. Returns: list: List of normalized number. """ t = sum(num_list) # avoid dive zero exception return num_list if t == 0 else [d / t for d in num_list]
4439a382ba8ba02ed26f645c847e93c4e56b51bc
251,055
import re def get_tensor_names(string_obj): """ Get tensor names from the given string. :param obj: a string representing an object from gc.get_objects() :return: the name of the tensor variable >>> names = get_tensor_names(log2) >>> assert len(names) == 3 >>> assert names[0] == "tensor1" >>> assert ['tensor1', 'tensor2', 'tensor3'] == names >>> names = get_tensor_names(log1) >>> assert len(names) == 1 >>> assert ["tensor1"] == names """ # There can be more than a single tensor name in the string. # This pattern does not overlap in the object from gc. pattern = "'(\w+)': tensor\(" # pos = string_obj.find(pattern) return re.findall(pattern, string_obj)
d7b036aa2545cf16d088c29a724f4d1cebab56b1
89,297
def normal_group(group): """ Returns true if group name can be normalized, false otherwise :param group: str :return: bool """ return False if group.startswith('_product_admin_') else True
503441c5657fa5aa277ad2867aad28a5047f11b8
356,160
def calc_average(total, count): """ Function that will return the average of a set of numbers """ return float(total / count)
65c72c81e054f13e0467a1e7aef559c977b115c2
227,069
def JNumber(state_list): """Calculate the angular momentum from the number of sub-states in the list. Parameters: state_list (list): List of sub-states of a single angular momentum state. Returns int: The total angular momentum of the state. """ return int((len(state_list)-1)/2)
b82b5dc60e5d567ea9033bc0f91ae0b26b1509cd
365,532
def maximum(a, b): """ Finds the maximum of two numbers. >>> maximum(3, 2) 3 >>> maximum(2, 3) 3 >>> maximum(3, 3) 3 :param a: first number :param b: second number :return: maximum """ return a if a >= b else b
bcdf0a116af1f7b921a390525e8ff5b0fa7c81fb
340,006
def transform_input_kernel(kernel): """Transforms weights of a single CuDNN input kernel into the regular Keras format.""" return kernel.T.reshape(kernel.shape, order='F')
fc2b69664c364e6989566c8f9538109c7a7833b5
103,686
def diff_lists(lists): """Diff the last list with the other lists and return a list of elements that are in the last list but not in the any of the previous lists. Arguments: lists -- The last list (-1) in this list of lists will be diffed with the other lists. Returns: A list of elements that exist in the last list but do not exist in any of the other lists. If the last list is None, returns []. If the previous lists don't exist then returns the last list (in this case, the only list). If any of the previous lists are a false value (None or []), they are ignored. """ lists_reversed = reversed(lists) new_elements = next(lists_reversed, []) or [] for previous_list in lists_reversed: # This can be done faster using set difference but that doesn't work if the elements of the list are # dictionaries. previous_list = previous_list or [] new_elements = [element for element in new_elements if element not in previous_list] return list(new_elements)
918655ba48e9d278e29d369b5880077d9f5494a9
164,740
from typing import List def quantile(xs: List[float], p: float) -> float: """Returns the pth-percentile value in x""" p_index = int(p * len(xs)) return sorted(xs)[p_index]
35dbf0ca4fc6929786cf08908806a8092be6fe1c
617,893
import random def rand_cord(width : int, height : int): """Pass width and heeight of the window Returns one random coordinate within given window space Steps by 20s """ cord = [] x = random.randrange(0,width - 19,20) y = random.randrange(0,height - 19,20) cord.append(x) cord.append(y) return cord
c81b6a85aa44a46953db82b73f4382557f49d4fd
427,867
def expand(v): """Split a 24 bit integer into 3 bytes >>> expand(0xff2001) (255, 32, 1) """ return ( ((v)>>16 & 0xFF), ((v)>>8 & 0xFF), ((v)>>0 & 0xFF) )
d63a441e8bb9d33c0ff92ceceb412932b0fea84c
330,835
def bind_method(value, instance): # good with this """ Return a bound method if value is callable, or value otherwise """ if callable(value): def method(*args): return value(instance, *args) return method else: return value
33ced528e79e30da1709dae12adb5254f41470d2
513,677
def find_list_string(name, str_list, case_sensitive=True, as_prefix=False, first_matched=False): """ Find `name` in the string list. Comparison parameters are defined in :func:`string_equal`. If ``first_matched==True``, stop at the first match; otherwise if multiple occurrences happen, raise :exc:`ValueError`. Returns: tuple ``(index, value)``. """ if not case_sensitive: lookup_name=name.lower() else: lookup_name=name found_name=None for i,s in enumerate(str_list): if not case_sensitive: lookup_s=s.lower() else: lookup_s=s if as_prefix: sat=lookup_s.startswith(lookup_name) else: sat=(lookup_s==lookup_name) if sat: if found_name is None: found_name=(i,s) if first_matched: break else: raise ValueError("{0} and {1} both satisfy name {2}".format(found_name[1],s,name)) if found_name is None: raise KeyError("can't find name in the container: {0}".format(name)) return found_name
f485ae3cdebcee9e4cfe85378c38f7f27d737b96
37,236
def read(metafile): """ Return the contents of the given meta data file assuming UTF-8 encoding. """ with open(str(metafile), encoding="utf-8") as f: return f.read()
82135a6b680803c01cb9263e9c17b4c3d91d4516
688,557
from typing import Dict from typing import Any def format(content: str, substitutions: Dict[str, Any]) -> str: """Formats the given content by performing the requested substitutions""" for currentKey in substitutions: content = content.replace( "%" + currentKey + "%", str(substitutions[currentKey])) return content
9762afe81a6783900e730f7c3037fefe82e0383f
526,917
def get_num_classes(dataset: str): """Return the number of classes in the dataset. """ if dataset == "imagenet": return 1000 elif dataset == "cifar10": return 10 elif dataset == "mnist": return 10
e3d6a0fe4d40629cec58d93cf8bb9d4f95ea6e29
566,242
import random def choose_from(*args): """Choose a random item from a variable number of lists.""" num_words = sum([len(x) for x in args]) # Take the ith item from the lists i = random.randint(0, num_words - 1) for (j, x) in enumerate(args): if i < len(x): return x[i] i -= len(x)
5dc283d6356205cca95dd886431390910f4f9a25
525,343
import math def area(r: float) -> float: """ Calculate the area of a circle based on the radius. :param r: The radius of the circle: Float :return: The area of the circle: Float """ return math.pi * (r ** 2)
4b0fea9198ce289b7712f732249458a86038a237
191,872
def generalized_entropy_index(distribution, alpha): """Genralized Entropy Index Args: distribution (list): wealth distribution of the population alpha (float): inequality weight, for large alpha the index is especially sensitive to the existence of large incomes, whereas for small alpha the index is especially sensitive to the existence of small incomes Returns: (float): Generalized Entropy Index (GE), inequality of wealth distribution with inequality weight alpha 0 <= GE(aplha) < +inf, GE(alpha) = 0, perfect equality """ n = len(distribution) mean_amount = sum(distribution) / n epsilon = 0 for amount in distribution: epsilon += (amount / mean_amount) ** alpha - 1 return epsilon / (n * alpha * (alpha - 1))
56746b50450d8b17bbb9aa840b561cded8d3a830
468,385
def _get_local_explanation_row(explainer, evaluation_examples, i, batch_size): """Return the local explanation for the sliced evaluation_examples. :param explainer: The explainer used to create local explanations. :type explainer: BaseExplainer :param evaluation_examples: The evaluation examples. :type evaluation_examples: DatasetWrapper :param i: The index to slice from. :type i: int :param batch_size: If include_local is True, specifies the batch size for aggregating local explanations to global. :type batch_size: int :return: The local explanation for the slice of rows. :rtype DynamicLocalExplanation """ rows = evaluation_examples.dataset[i:i + batch_size] return explainer.explain_local(rows)
b17f88b7f03d0ff40772102a88afc4449fee8035
663,142
def addSeqTokensArgs(parser): """ Add arguments defining DNN processing sequences of tokens Parameters: - parser -- argument parser as an object of ArgumentParser to add arguments Returns: constructed argument parser """ parser.add_argument('--seq_len', default=None, type=int, help='maximum lengths of token sequence') parser.add_argument("--coding", type=str, default="categorical", choices=["categorical", "trainable", "one_hot"], help="dnn input data coding: " + "either one-hot or categorical or trainable") parser.add_argument("--embed", default=None, type=int, help="size of embedding vectors; " + "number of tokens if it is not defined" ) parser.add_argument("--kernels", required=True, type=int, nargs='+', help="width of convolution kernels") parser.add_argument("--filters", required=True, type=int, nargs='+', help="number of convolution filters") parser.add_argument("--strides", default = None, type=int, nargs='+', help="strides of convolutions") parser.add_argument("--conv_act", type=str, default= None, choices=["relu", "sigmoid", "tanh"], help="activation of convolutional layers") parser.add_argument("--pool", type=str, default="max", choices=["max", "aver"], help="operation of pooling layer") parser.add_argument("--dropout", default=0, type=float, help="rate of dropout") return parser
15bb822b8f96f58c7e8f30af1789a36bc2471f15
595,786
def _weights(vgg_layers, layer, expected_layer_name): """ Return the weights and biases already trained by VGG """ W = vgg_layers[0][layer][0][0][2][0][0] b = vgg_layers[0][layer][0][0][2][0][1] layer_name = vgg_layers[0][layer][0][0][0][0] assert layer_name == expected_layer_name return W, b.reshape(b.size)
eca1cba51cc4736aef3460666d390cab306ce063
367,318
import gzip import json def import_compressed_json(file_name): """Import gzip compressed JSON. :param file_name: Name of file to be read e.g. dict.json.gz :returns: JSON as a dictionary. """ with gzip.open(file_name, mode="rt") as f: return json.load(f)
c9c4bca3c04a9a36cb33d5b172b6836ec044d5d5
589,856
def check_ALL_DS(DS_ES_X_Map): """ ES used with ALL as DS can not be used with any other DS. This function checks if this is true. """ ES_with_ALL = [row[1] for row in DS_ES_X_Map if row[0] == "ALL"] ES_without_ALL = [ES for ES in ES_with_ALL for row in DS_ES_X_Map if row[0] != "ALL"] return len(ES_without_ALL) == 0
58b2f2fd4a4a1f20bba74aa6150d91169a4a9695
40,252
def _IsBoundary(i, n, cont, assigned): """Is path i a boundary, given current assignment? Args: i: int - index of a path to test for boundary possiblity n: int - total number of paths cont: dict - maps path pairs (i,j) to _Contains(i,j,...) result assigned: set of int - which paths are already assigned Returns: bool - True if there is no unassigned j, j!=i, such that path j contains path i """ for j in range(0, n): if j == i or j in assigned: continue if (j, i) in cont: return False return True
2ea312e2d497980a3bdfd45ac5005e6857869543
231,964
def _get_class(value, max): """Get the CSS class for the value and max such that higher values are better""" if value < (max * 0.33): return "bad" if value > (max * 0.67): return "good" return "okay"
88b0cf6359155f504a6bdbd26e6e3b88941e83c6
524,090
def make_pairs(args, pair_len=2): """Divide input list args into groups of length pair_len (default 2).""" assert len(args) % pair_len == 0 return [tuple(args[pair_len * i: pair_len * (i + 1)]) for i in range(len(args) // pair_len)]
b93526b84784f422676f32d12ff82dc8ae839003
565,878
def infer_angular_variance_spherical(var_r, phi_c, var_q_min): """Calculate angular variance given properties of a beam with quadratic phase corrected by a lens. The lens which removes the spherical component has focal length f = -k*var_r/(2*phi_c). This means that -phi_c is the phase of the quadratic component at r = var_r**0.5. The formula is (19) of Siegman IEEE J. Quantum Electronics, vol. 27 1991, with k = 2*pi/lambda. For consistency with the rest of the program, I use slightly different definitions. The derivation is on p120 of Dane's Fathom notebook 2. It is valid for any refractive index. Args: var_r (scalar): real space variance. phi_c (scalar): real-space curvature - see above. var_q_min (scalar): angular variance of the beam after its curvature has been removed. Returns: var_q (scalar): angular variance of the beam after the lens. """ var_q = var_q_min + 4*phi_c**2/var_r return var_q
b8c3fcfff84530bb6fd2a9cee2e52dcb6fa4baa7
289,571
def _PlatformEventHandler(data): """Decorator for platform event handlers. Apply giving the platform-specific data needed by the window to associate the method with an event. See platform-specific subclasses of this decorator for examples. The following attributes are set on the function, which is returned otherwise unchanged: _platform_event True _platform_event_data List of data applied to the function (permitting multiple decorators on the same method). """ def _event_wrapper(f): f._platform_event = True if not hasattr(f, '_platform_event_data'): f._platform_event_data = [] f._platform_event_data.append(data) return f return _event_wrapper
db2a5194772eb1df26e9cd66402cba60bcf42e32
474,868
def increment(number: int) -> int: """Increment a number. Args: number (int): The number to increment. Returns: int: The incremented number. """ return number + 1
27f4becd9afb747b22de991ab4cf030b14d3dac5
702,917
def makeaxisstep(start=0, step=1.00, length=1000, adjust=False, rounded=-1): """ Creates an axis, or vector, from 'start' with bins of length 'step' for a distance of 'length'. :type start: float :param start: first value of the axis. Default is 0. :type step: float :param step: Step size for the axis. Default is 1.00. :type length: int :param length: LEngth of axis. Default is 1000. :type adjust: boolean :param adjust: If True, rounds (adjusts) the deimals points to the same as the step has. Default is False. :type rounded: int :param rounded: Number of decimals to consider. If -1 then no rounding is performed. :returns: Axis with the set parameters. :rtype: list[float] """ if adjust: d = str(step)[::-1].find('.') axis = [round(start+step*i,d) for i in range(length)] else: if rounded >= 0: axis = [round(start+step*i,rounded) for i in range(length)] else: axis = [start+step*i for i in range(length)] return axis
2c6066f1ae76816bf34135507e180e08f98d12f5
321,931
def dict_from_file(filename, key_type=str): """Load a text file and parse the content as a dict. Each line of the text file will be two or more columns splited by whitespaces or tabs. The first column will be parsed as dict keys, and the following columns will be parsed as dict values. Args: filename(str): Filename. key_type(type): Type of the dict's keys. str is user by default and type conversion will be performed if specified. Returns: dict: The parsed contents. """ mapping = {} with open(filename, 'r') as f: for line in f: items = line.rstrip('\n').split() assert len(items) >= 2 key = key_type(items[0]) val = items[1:] if len(items) > 2 else items[1] mapping[key] = val return mapping
8d12620ca12c65c9cc8769262eba253d26581a72
617,877
def mangle(cls, name): """Applies Python name mangling using the provided class and name.""" return "_" + cls.__name__ + "__" + name
348f9d1b1819c6283f81c8e7bf3a07a1e7c25b7f
99,954
def get_url(query, page): """ Generate URL from query and page number. The input query will be split into token or list of word, e.g 'luka parah' will be ['luka', 'parah'] and 'kdrt' will be ['kdrt'] For input query with more than 1 word, the url will be `..q={token1}+{token2}&..`, e.g `..q=luka+parah&..` """ queryLength = len(query.split()) if queryLength == 1: url = 'https://www.lapor.go.id/search?q={}&page={}'.format(query, page) else: query = query.split() param = '+'.join(query) url = 'https://www.lapor.go.id/search?q={}&page={}'.format(param, page) return url
365e5408f1d429bc63bb5a512164069a149c1c26
122,169
def increment_count(val): """ Increments the value by 1. """ return val + 1
107dc447d5e749daae5b1d0f578a213088d5ba84
678,294
def error_response(message): """ Construct error response for API containing given error message. Return a dictionary. """ return {"error": message}
677912817c91725c7079b538bfdf915eb21f3fa0
689,262
def construct_SN_default_rows(timestamps, ants, nif, gain=1.0): """ Construct list of ants dicts for each timestamp with REAL, IMAG, WEIGHT = gains """ default_nif = [gain] * nif rows = [] for ts in timestamps: rows += [{'TIME': [ts], 'TIME INTERVAL': [0.1], 'ANTENNA NO.': [antn], 'REAL1': default_nif, 'REAL2': default_nif, 'IMAG1': default_nif, 'IMAG2': default_nif, 'WEIGHT 1': default_nif, 'WEIGHT 2': default_nif} for antn in ants] return rows
b81e45d2d5299042b3332a2386a0fd4d2d6d59d7
1,517
import pickle def load_objects(loadpath): """Load (unpickle) saved (pickled) objects from specified loadpath. Parameters ---------- loadpath : absolute path and file name to the file to be loaded Returns ------- objects : list of saved objects """ try: with open(loadpath, 'rb') as buff: return pickle.load(buff) except IOError: raise Exception('File %s does not exist! Data already imported?' % loadpath)
3cd6a212d43a1b8c8c91f58cd332d725398d4dc6
425,226
def box(points): """Obtain a tight fitting axis-aligned box around point set""" xmin = min(points, key=lambda x: x[0])[0] ymin = min(points, key=lambda x: x[1])[1] xmax = max(points, key=lambda x: x[0])[0] ymax = max(points, key=lambda x: x[1])[1] return (xmin, ymin), (xmax, ymax)
8efb486150aa6d9f74f011c37302b57cf78d46f2
255,219
def get_clade_point(arg, node_name, time, pos): """Return a point along a branch in the ARG in terms of a clade and time""" if node_name in arg: tree = arg.get_marginal_tree(pos - .5) if (time > tree.root.age or (time == tree.root.age and node_name not in tree)): return (list(tree.leaf_names()), time) return (list(tree.leaf_names(tree[node_name])), time) else: return ([node_name], time)
b62822600c0cd192769d2813b90358d8b1b66d50
375,132
from typing import Any from typing import Iterable from typing import Optional from typing import Dict def obj_to_dict_helper( obj: Any, attribute_names: Iterable[str], namespace: Optional[str] = None ) -> Dict[str, Any]: """Construct a dictionary containing attributes from obj This is useful as a helper function in objects implementing the SupportsJSON protocol, particularly in the _json_dict_ method. In addition to keys and values specified by `attribute_names`, the returned dictionary has an additional key "cirq_type" whose value is the string name of the type of `obj`. Args: obj: A python object with attributes to be placed in the dictionary. attribute_names: The names of attributes to serve as keys in the resultant dictionary. The values will be the attribute values. namespace: An optional prefix to the value associated with the key "cirq_type". The namespace name will be joined with the class name via a dot (.) """ if namespace is not None: prefix = f'{namespace}.' else: prefix = '' d = {'cirq_type': prefix + obj.__class__.__name__} for attr_name in attribute_names: d[attr_name] = getattr(obj, attr_name) return d
c1c4d95f65f8b5d575629fcb23258f52b871b30b
284,352
from typing import Dict def success_of_action_dict(**messages) -> Dict: """Parses the overall success of a dictionary of actions, where the key is an action name and the value is a dictionarised Misty2pyResponse. `overall_success` is only true if all actions were successful. Returns: Dict: The dictionary of the keys `"overall_success"` (bool) and action names that contain the dictionarised Misty2pyResponses. """ status_dict = {} overall_success = True for name, message in messages.items(): status_dict[name] = message if not message.get("overall_success"): overall_success = False status_dict["overall_success"] = overall_success return status_dict
542725d492df7758e9b90edf8d18a935c824e18a
676,795
def _clean(sensor, fetch_resp): """ Clean data by deleting streams with zero values. Parameters ---------- sensor : sensor name type to evaluate e.g. Zone_Air_Temperature fetch_resp : Mortar FetchResponse object Returns ------- sensor_df : dataframe of nonzero sensor measurements setpoint_df : dataframe of setpoint values equipment : equipment related to the sensor measurement """ # get all the equipment we will run the analysis for. Equipment relates sensors and setpoints equipment = [r[0] for r in fetch_resp.query("select distinct equip from {}_sensors".format(sensor))] # find sensor measurements that aren't just all zeros valid_sensor_cols = (fetch_resp['sensors'] > 0).any().where(lambda x: x).dropna().index sensor_df = fetch_resp['sensors'][valid_sensor_cols] setpoint_df = fetch_resp['setpoints'] return sensor_df, setpoint_df, equipment
3c8404dd6b4a9d9bc7237f16201d91e829d1e113
156,441
def get_text(index_name, es, text_id): """ Return a text in ElasticSearch with the param id :param index_name: ElasticSearch index file :param es: ElasticSearch object :param text_id: Text id :return: str """ res = es.get(index=index_name, id=text_id) return res['_source']['text']
b57ef476c8a1e74614846f7a231cf81b05833fda
296,324
from typing import List def getValuesInInterval(dataTupleList: List, start: float, end: float) -> List: """ Gets the values that exist within an interval The function assumes that the data is formated as [(t1, v1a, v1b, ...), (t2, v2a, v2b, ...)] """ intervalDataList = [] for dataTuple in dataTupleList: time = dataTuple[0] if start <= time and end >= time: intervalDataList.append(dataTuple) return intervalDataList
42dd008ff3dfadc5e7ac4d7b34f30626a6dadf73
148,796
import datetime as dt def createDatetime(yr, mo, dy, hr): """ Same thing as above function but converts to datetime format instead of decimal year """ datetime = [] for i in range(len(yr)): time = dt.datetime(yr[i], mo[i], dy[i], hr[i]) datetime.append(time) return datetime
087b6672dbd7d3a0a81e3fd6c8fc808667563074
167,256
def area_of_rectangle(height, width = None): """ Returns the area of a rectangle. Parameters ---------- height : int or float The height of the rectangle. width : int or float The width of the rectangle. If `None` width is assumed to be equal to the height. Returns ------- int or float The area of the rectangle Examples -------- >>> area_of_rectangle(7) 49 >>> area_of_rectangle (7, 2) 14 """ area = height * width return area
6867148be08d474f41e928d59d248041236911e8
188,717
def other(si, ti): """ Retrieves the "other" index that is not equal to the stack index or target stack index. Parameters ---------- si : int The stack index that would be removed from. ti : int The target stack index that would be added to. Returns ------- int The "other" index in the list [0, 1, 2] that equates to the stack index that is unused (not stack index or target stack index). """ other = [0, 1, 2] del other[other.index(ti)] del other[other.index(si)] return other[0]
357e51f22f4dd9b40af4bbf66da2363df9fd2a7b
553,957
def set_is_singles(slots): """Check whether a set is in the singles or doubles format based on its slots""" if slots is None: return False for slot in slots: entrant = slot['entrant'] try: participants = entrant['participants'] if len(participants) > 1: return False else: return True except KeyError: return True
89e919d9205076e84103f563b0ce364eb947fef4
340,890
def none_has_no_cards(player_cards,players_number): """checks if every player has cards on their hands >>> p1_cards=[('A', '♥', 11),('K', '♣', 10), ('5', '♥', 5), ('7', '♣', 7), ('8', '♣', 8), ('5', '♦', 5),('J', '♠', 10)] >>> p2_cards=[('A', '♥', 11),('4', '♦', 4), ('2', '♠', 2), ('3', '♣', 3), ('9', '♣', 9), ('5', '♦', 5),('A', '♠', 11)] >>> p3_cards=[] >>> player_cards=[p1_cards,p2_cards,p3_cards] >>> none_has_no_cards(player_cards,3) False """ for i in range(players_number): if len(player_cards[i])==0: return False return True
1eb1ac44df3fbf5e2a824057813b7ea710a2610a
317,796
def q_learn(old_state_action_q_value, new_state_max_q_value, reward, learn_rate=0.01, discount_factor=0.9): """ Returns updated state-action Q_value. :param old_state_action_q_value: Q_value of the chosen action in the previous state. :param new_state_max_q_value: maximum Q_value of new state. :param reward: received reward as result of taken action. :param learn_rate: learning rate. :param discount_factor: discount factor. :return: Updated Q-value of previous state-action pair. """ error = (reward + (discount_factor * new_state_max_q_value)) - old_state_action_q_value return old_state_action_q_value + (learn_rate * error)
cfe2f70823dff79b43a426b2f9e0996ac5e507c1
643,016
def portfolio_return(weights, returns): """ Computes the return on a portfolio from constituent returns and weights weights are a numpy array or Nx1 matrix and returns are a numpy array or Nx1 matrix """ return weights.T @ returns
9e6ac36b97c1fbcd74c209ab04493ff12a8ca713
421,941
def pxe_mac(mac): """ Create a MAC address file for pxe builds. Add O1 to the beginning, replace colons with hyphens and downcase """ return "01-" + mac.replace(":", "-").lower()
483ccf559b5cb014070be3cc9e0237ac5d1a0b34
670,281
def get_kqshift(ngkpt, kshift, qshift): """Add an absolute qshift to a relative kshift.""" kqshiftk = [ kshift[i] + qshift[i] * ngkpt[i] for i in range(3) ] return kqshiftk
0fe469cbeea3265705e1eb89bad8c00cb59374a7
624,208
def _repeated_proto3_field_to_list(field): """Convert a proto3 repeated field to list. Repeated fields are represented as an object that acts like a Python sequence. It cannot be assigned to a list type variable. Therefore, doing the conversion manually. """ result = [] for item in field: result.append(item) return result
424ef2a64d2878a2dce547bcb22c6f265d417aea
83,573
def getDistance(sensor): """Return the distance of an obstacle for a sensor.""" # Special case, when the sensor doesn't detect anything, we use an # infinite distance. if sensor.getValue() == 0: return float("inf") return 5.0 * (1.0 - sensor.getValue() / 1024.0)
68ff9e0c8c4dd7687e328d3b9c4634677cfe25cd
702,978
def load_reports_file(path): """ Loads radiology reports from a file. Radiology reports must be separated by the following string: '----------------------------------------------' Inputs: path str path to the file containing the reports Output: reportlist list a list with a report for each element """ reportlist = [""] x = 0 with open(path, "r") as reportsfile: for line in reportsfile: if "----------------------------------------------" in line: x = x+1 reportlist.append("") else: reportlist[x] = reportlist[x] + line return reportlist
4a941c75c725f73134007112a74920954465494d
106,855