content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def as_choice(as_list): """ Creates a dropdown list of authorization servers """ element = "<select name=\"authzsrv\">" for name in as_list: element += "<option value=\"%s\">%s</option>" % (name, name) element += "</select>" return element
c4e644019449e9342efac2b888067753ff4fb526
668,892
def to_day_count(d): """ date > n days """ return (d - type(d).min).days
35a2932f039867526b65d8d160899996a4617250
668,893
def mean(num_list): """ Calculates the mean of a list of numbers Parameters ---------- num_list: list (int or float) Returns ------- ret: int or float The mean of the list Examples -------- >>> mean([1, 2, 3, 4, 5]) 3.0 """ try: return sum(nu...
2920c76d86572d02c9e4015d16b6cc44d86dd548
668,894
import socket def _get_socket_constants(prefix): """Create a dictionary mapping socket module constants to their names.""" return {getattr(socket, n): n for n in dir(socket) if n.startswith(prefix)}
a468911c1ff743c908d797d650fc4794223ea80b
668,895
def _parse_ports_name(file): """Parse and interpret the option line in the touchstone file Parameters ---------- file : Returns ------- """ portnames=[] line = file.readline() while not line.startswith('! Port'): line = file.readline() while line.startswit...
8f5c04c0e2ae52806b6373ee0dd5ab15c994ec7a
668,896
def desi_target_from_survey(survey): """ Return the survey of DESI_TARGET as a function of survey used (cmx, sv1, sv2, sv3, main).""" if survey == 'special': # to avoid error, return one of the column, SV2_DESI_TARGET should be full of 0. return 'SV2_DESI_TARGET' if survey == 'cmx': ...
5e6a012088f540bf1c7101f3d8948a8662dbbad0
668,897
def getProcessName(pdgGen, requiredNumberOfGeneratedObjects): """ returns a process name (such as 'Zee') which can be used in various places (e.g. module names etc.) """ if pdgGen == 11: # electron paths if requiredNumberOfGeneratedObjects == 1: return "Wenu" elif requ...
1b76b9102b2806bf056b4743171c502d0edac146
668,899
from datetime import datetime def get_date_file_name(extension): """ Format 'now' datetime and create file name with a given extension like this: 'YYYY_MM_DD hh_mm_ss.ext' """ return "{}.{}".format(datetime.now().replace(microsecond=0), extension).replace(":", "_")
a6530230d69ea175d89b262da69666d465b803d2
668,900
def euler(n): """ e(n) = n * (1-1/p1) * ... * (1-1/pn) """ res = n n_ = n # 2 if n_ & 1 == 0: res >>= 1 n_ >>= 1 while n_ & 1 == 0: n_ >>= 1 p = 3 while p <= n_: if n_ % p == 0: res = res * (p-1) / p n_ %= p while ...
60e437edd5e3cc761a2f1cfeb6b1e3fc3a4a12f6
668,901
import subprocess def get_pip_list(version): """ :param version: Python version. :type version: float :return: List of installed packages in python. :rtype: list[str] """ cmd = 'pip{:.1f} list'.format(version) return subprocess.getoutput(cmd).splitlines(True)
0faa41e06ec9636fde4e107ace71df441aebc521
668,903
def fi(n): """斐波拉契数列 1 1 2 3 5 7""" if n <= 2: return 1 return fi(n-1) + fi(n-2) pass
4a3c31cbd5f21ae1ebefa24e4ed63f94c9e1ca28
668,904
import select import errno def eintr_retry_call(func, *args, **kwargs): """ Handle interruptions to an interruptible system call. Run an interruptible system call in a loop and retry if it raises EINTR. The signal calls that may raise EINTR prior to Python 3.5 are listed in PEP 0475. Any calls t...
4186276824fcfda86a798de055c6e2f5b2515b0e
668,905
def unique_fitnesses(population: list) -> int: """ Calculates the number of unique fitnesses in the population Args: population (list): The list of individual candidate solutions Returns: int: The number of unique fitnesses in the population """ fitnesses = [individual.fitness for ...
c0057c4e2874ca6ea586e999922ebcc633efb225
668,907
def G(S, K): """the payoff function of put option. Nothing to do with barrier""" return max(K-S, 0)
709dacc7e066b2b3ec54e36c9374e07ba26eeb75
668,908
import os def extension(path: str) -> str: """ Extension of a file. """ filename, file_extension = os.path.splitext(os.path.basename(path)) return file_extension
9de424d5204558ad05b7a26fe2f4f3d42e7f21e4
668,909
def are_equal_nodes(n1, n2, underspecified=True): """Returns True if nodes n1 and n2 have the same predicate and sortinfo. If underspecified, allow underspecification.""" if underspecified: if n1.is_less_specific(n2) or n2.is_less_specific(n1): return True return n1.pred == n2.pred a...
5c4246d757cd0abaebe85aa210f2889d0239d625
668,911
import argparse def parse_args(): """ Parses arguments from the command line. """ parser = argparse.ArgumentParser(description='Combines features into 1 file for every fasta sequence, stores files in 1 output directory.') # Arguments parser.add_argument('train_biodl_path', help='Path to ...
6a730fb06c838f30b7df4fcd9994b0a047df1205
668,912
def name(): """f.__name__: The short name of the function.""" class _New: class _Message: @staticmethod def _mutted(): pass return _New._Message._mutted.__name__
8aa265c6ea5745a57b1eda61d3aa51e24e4a6416
668,913
def _do_decoding(s, encoding): """A function to decode a bytes string, or return the object as-is.""" try: return s.decode(encoding) except UnicodeError: raise except (AttributeError, TypeError): return s
4bda03779164567078eac6bdfcb750a4cf689205
668,916
import argparse import os import sys def process_args(): """Handles user-passed parameters""" parser = argparse.ArgumentParser(description='Check haveibeenpwned for' ' compromised email addresses.') parser.add_argument('-a', '--apikey', required=True, type=str, ...
8a8fa3c3cb9f6570d46665ed786cc3f319c67b99
668,918
def enum_to_list(enum): """Enum to list.""" return [enum_ele.value for enum_ele in enum]
131ab8f7b623f58008666a942e23b042ebbac898
668,919
def binary_search(list_, value): """This function performs a binary search. """ first = 0 last = len(list_) - 1 while first <= last: middle = first + (last - first) // 2 if value == list_[middle]: return middle elif value < list_[middle]: last = middl...
9c58d47941b7f1870911ede211b74583fb6081aa
668,920
def clean_update_item_string(string): """ Removes "(" and ")" parentheses from a string Args: string(str): entry Returns: str: string with parens removed """ return str(string.replace("(", "").replace(")", ""))
14634fe1232e620837855c2400b40a4dc865f237
668,921
def ascii_distance(first, second): """ returns the positive distance between the ascii values of input characters assume: inputs are valid single letters e.g. inputs ("a", "b") should return 1, inputs ("b", "a") should return 1 too (postive distance) """ return abs(ord(first)-ord(second)...
6c1bd591e13fccf14dd17249f392e03ce59c7126
668,922
def is_client_error_or_unmodified(exception): """ Returns true if the request responded with a client error. """ return (400 <= exception.args[1] < 500) or (exception.args[1] == 304)
9b12eab7b0afd7d74365b197e27b571437360041
668,923
import os def list_hdfs_files(location): """Lists the underlying files at a location Arguments: location {str} -- HDFS location Returns: list -- list of hdfs files """ os.system("hdfs dfs -ls %s > migration_temp_file.txt" % (location)) with open("migration_temp_file....
4291e66c225773b5ef6136279db7f0cb4847b0e1
668,924
import math def circ2lin(vl, vr, isign=1): """Convert 2-vector from circular basis to linear basis. Input order L, R. isign argument chooses sign of imaginary unit in phase convention. (See Hamaker1996_III)""" vx = (vl+vr)/math.sqrt(2) vy = isign*1j*(vl-vr)/math.sqrt(2) return vx, vy
9728121a9890a83e72e086fbcdaf8824bc98b230
668,925
from datetime import datetime def parse_date_fields(fields): """ ??? """ assert len(fields) == 6 date_str = '{}-{}-{} {}:{}:{}'.format(fields[0], fields[1].zfill(2), fields[2].zfill(2), ...
899cb6b8b564dcf79bbee8cb6c43c06ef0215c97
668,926
def GenerateFractionSamples(x, w, frac=0.50): """ Randomly samples fraction of the events from given features and weight. Args: x : panda.DataFrame dataframe that contains the features for training. w : panda.DataFrame dataframe that contains the MC event weight. ...
361db7c66ee6f93445a25d2d26752837dc4c989b
668,927
def labeled_racelist(rcs): """ Return list of Race_clusters that have SOME label """ return [rc for rc in rcs if rc.races.filter(labels__isnull = False).count() > 0]
a52461f51b4f6c40dd7a8cacb78ad84bbccabaaf
668,928
from typing import Dict from typing import List from typing import Optional def get_dict_from_cu_inst_result_file(cu_inst_result_file: str) -> Dict[str, List[Dict[str, Optional[str]]]]: """Parses the information contained in cu_inst_result_file into a dictionary of dictionaries, ordered by dependency type and...
a7352e731c3fb05ad0fa13aa1f63bf5325e8a69a
668,929
def wrap(x, m, M): """Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n For example, m = -180, M = 180 (degrees), x = 360 --> returns 0. Args: x: a scalar m: minimum possible value in range M: max...
eb86baba697a0890ff90e176fffa0e7cd904d0bd
668,931
from typing import List def download_users_list(client, page_limit: int) -> List[dict]: """download Slack Web API users.list response. Returns: [{"id":xx, "name":yy}, {}, ...] """ users = [] next_obj_exists = True next_cursor = None while next_obj_exists is True: sl...
aa2ab441080effd160f520569e8e254d5c5d0318
668,933
def _getMenuIndex(values, current, defaultIndex = 1): """ Retrieves the menu index corresponding to the current value selected amongst values. If the value is invalid, returns the defaultIndex. """ try: # Note: menu index is 1-based. return values.index(current) + 1 except: ...
8c739892b777102c71f8522a224d5a5e5d387100
668,934
import asyncio import os import errno def open_agent(loop, agent_path): """Open a connection to ssh-agent""" if not loop: loop = asyncio.get_event_loop() if not agent_path: agent_path = os.environ.get('SSH_AUTH_SOCK', None) if not agent_path: raise OSError(errno.ENOE...
da038479c3394143c7e7aef9ebea5f1cd634693f
668,935
from zipfile import ZipFile def extract_shp(path): """Return a geopandas-compatible path to the shapefile stored in a zip archive. If multiple shapefiles are included, return only the first one found. Parameters ---------- path : Path Path to zip archive holding shapefile. Returns ...
273fb9917c5d5ecedee142e8e252a2376aac59b0
668,936
import hashlib def sha1_20(data): """Return the first 20 bytes of the given data's SHA-1 hash.""" m = hashlib.sha1() m.update(data) return m.digest()[:20]
af7edbfec599cb2204205d905ae1c843794fb8af
668,937
import sys def increment_count(count: int, count_previous: int) -> int: """Increments count up to ``sys.maxsize``.""" return ( count_previous + count if sys.maxsize - count_previous > count else sys.maxsize )
1a4186616294f9cddcb16dff1a9ec7cf12944ea5
668,938
def get_printable_object_name(obj): """ Get a human-readable object name for our reports. This function tries to balance useful information (such as the `__repr__` of an object) with the shortest display (to make reports visually understandable). Since this text is only read by humans, it can be any for...
ef143a0a133089c3d004c1431e3463bee3c6eb3d
668,939
import re def build_url(url, *argv): """ Builds a url with query Expects format of key=value :param url: :param argv: :return: """ if len(argv) == 0: return url url += '?' # start building http request for arg in argv: if re.fullmatch("^[^=]*=[^=]*$", a...
f9d37a8e13d18054de3376ef0d56489d6dd1b4f4
668,940
def prod(l): """ l: iterable of numbers. returns: product of all numbers in l """ p = 1 for i in l: p *= i return p
0575ddd33f67e416ab96c26d9f010756b607261d
668,941
def apply_filter(results, threshold): """Run one simulation with a given threshold. :param dict results: resource with pathways :param int threshold: necessary genes to enrich a pathway :rtype: dict """ filtered_results = {} for database_name, pathways in results.items(): pathways...
c2233c3655ffdd243b77f035cfba9fdf787d5f65
668,942
def convert_functions_in_dict_to_values(dict_to_convert): """ When passed a dictionary that contains functions as some of its values, it converts them to their responses """ return {key: value() if hasattr(value, '__call__') else value for key, value in dict_to_convert.items()}
b480677a4e537abcd27822d2b6ac6e754b3292d2
668,943
def list_reply(objects): """Construct message used by CtrlServer when replying to list requests. By 'list', we mean 'give me all the callable methods on your systems'. :param objects: Dict of subsystem object names to their callable methods. :type objects: dict :returns: Constructed list_reply dic...
72239c1d5e68720242b7d8f57253dace8d5d519c
668,944
import os def get_files(path, ext=''): """ Get all files in a directory with a extension. """ files = [] for filename in os.listdir(path): if filename.endswith(ext): files.append(os.path.join(path, filename)) return files
c5fef69db70106825b225ab91a0c4891fd86a40b
668,945
def find_subseq_in_seq(seq, subseq): """Return an index of `subseq`uence in the `seq`uence. Or `-1` if `subseq` is not a subsequence of the `seq`. The time complexity of the algorithm is O(n*m), where n, m = len(seq), len(subseq) from https://stackoverflow.com/questions/425604/best-way-to-determ...
8200272668a3d97877ccf0c1731bca5d036681bc
668,946
import lzma import gzip def get_open_function(path): """Choose an open function based on the file's extension.""" if path.endswith('xz'): return lzma.open elif path.endswith('gz'): return gzip.open return open
23dc5bcabc86c67c40b7fb190713eb94deb0175a
668,948
def set_weierstrass_eq(*, a=1, b=1): """Return equation that defines Weierstrass curve. """ def wei_eq(x, y): return y ** 2 == x ** 3 + a * x + b return wei_eq
0035f39da01c1524a9429a0054d005395770c59c
668,949
import os def get_port(): """Get game server port.""" return int(os.getenv("PORT", "7840"))
54a8887f66c24c6b812e1d26eb2910a3f1986855
668,950
def digit_sum(n): """Calculating with integer arithmetic instead of char/int/list method doubles the speed. """ result = 0 while n: result += n % 10 n = n // 10 return result
8887cfcb0e806eaee881fbabf00846307c28a0fd
668,951
def topological_sort(g): """ Returns tuple for a directed graph where: - First element is a boolean that is set to True if graph contains a cycle - Second element is an array of vertices in topological order if graph has no cycles, or None otherwise """ visited = set() removed = set...
aba95b8c4008ebd790ae0b2dcce4ca6e5499b182
668,952
def rescale(im, range): """ mini-max rescales the input image """ im_std = (im - im.min()) / (im.max() - im.min()) im_scaled = im_std * (range[1] - range[0]) + range[0] return im_scaled
5b5d3ab3cb075ca166db94ac3f2f7564784861fa
668,953
def power(a, b): """ calculate the value of 'a' to the power 'b' :param a: :param b: :return: """ return pow(a, b)
0c659d1f555f11b43b2ce5665daa114beb7cdf66
668,954
def addslashes(value): """ Adds slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the ``escapejs`` filter instead. """ return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
99fd02a1a13ad76c6e649638fe64ccb792ec977e
668,955
def cutlabel(s, cuts): """Cuts a string s using a set of (n, label) cuts. Returns a list of (sub, label) pairs. If there was an initial part before the first cut, then it has a label of None. If there are no cuts, returns s as a single element, with label None. """ cuts = sorted(cuts) # no c...
2f81a64d24dc0d31ff6671f2cc8459a38e3af51c
668,956
import re def resolve_schema_args(jfile, ARGS): """ Reads JSON and complete the parameters from ARGS """ arguments = re.findall(r"#ARGS\.(.+?);", jfile) for arg in arguments: replace = '#ARGS.%s;' % (arg) to = str(ARGS.__dict__[arg]) if jfile.find('\"#ARGS.%s;\"' % (arg...
0ad035fe8b682b5f4bc24cc7412716ade381205e
668,957
def normalized_margins_data(df): """融资融券数据""" res = df.drop('last_updated', axis = 1) res = res.rename(columns = {'short_balance_amount':'total_balance'}) return res
383303cfc9f801f9d37eae530fe4d3a504114091
668,958
def issequence(obj): """returns True if obj is non-string iterable (list, tuple, ect)""" return getattr(obj, '__iter__', False)
60f193a0e5230df22dd6ca3348edef37b5942236
668,959
def conv_to_list(obj): """ 將物件轉換為list """ if not isinstance(obj, list): results = [obj] else: results = obj return results
a97205491e0b59ed4ec6cae0dc23f1b26767df01
668,961
import inspect def get_module_path_from_type(py_type) -> str: """ Gets full module path + class name by the given class type Parameters ---------- cls: python type Class you want to get full module path for Returns ------- String representation of full module path like module...
ed9576f56116693c29fcf8caf8b879f45bdd5ef4
668,962
def first(listOrTuple): """Return the first element of a list. >>> first((1, 2, 3)) 1 @type listOrTuple: list or tuple of T @param listOrTuple: the list or tuple @rtype: T @return: the second element of a list """ return listOrTuple[0]
c32f2fd8a411e447df0aaeca0d1743cd6fcc6531
668,963
import os def get_ip(): """ 获取当前服务器IP地址 :return: IP """ try: result = os.popen("hostname -I").readlines() IP = result[0].split(' ')[0].strip() except: IP = '127.0.0.1' return IP
b083668fbdf29cb80ab02003fef455f82b26397d
668,964
def rotate_patches_90deg(patches): """ Rotate patch dictionary as if original image is rotated by 90-degree CCW. """ def rot_pos(i, j): """ Board Coordinates: i 9 ... 1 ------ 1 j | | ... ------ 9 """ return (10 - ...
f488cb151b869d740c47464816329e730a12f3f0
668,965
import math def cibeam(orad, fow, fot, fiw, fit, wlh, wth): """ """ global smac,area,warea,ceni,ceno,fki,fko,crad global _orad, _fow, _fot, _fiw, _fit, _wlh, _wth _orad = float(orad) # outside radious of the ring _fow = float(fow) # flange outside w _fot = float(fot) # flang...
62c66d974912c67681e736ee116e97d7bef8bd5b
668,966
def one_max(phenome): """The bare-bones one-max function.""" return sum(phenome)
3ffbeddb61f4533c462b3ba736acf2d1396a91c2
668,967
from typing import List def parse_multi_command(command: str, commands_out: List[int]) -> dict: """ Given a list of commands separated by semicolons (;), this simply separates the commands into individual ones. This is useful for workflows that require different commands at different steps in a w...
6e0162b7bfcb3f52ef437bd7cb50df1414dbbf09
668,968
def replace_keyvalue(jn, ky, val): """ :param jn: 传入的json :param ky: 想要改变的json键名 :param kv: 改变后的josn键值 :return: 返回改变后的json """ for key in jn.keys(): if key == ky: jn[key] = val else: if type(jn[key]) == dict: for key2 in jn[key].keys()...
0dc3777a312652cb29c9a1ff0ec74d84a3baf27a
668,970
def get_device_mac(run_command_fn, dev_name, netns_name=None): """Find device MAC address""" if netns_name: command_prefix = "ip netns exec %s " % netns_name else: command_prefix = "" (output, _) = run_command_fn("%scat /sys/class/net/%s/address" % (comm...
19f9a745f107ce2f00717d783e20cfcfe25fe19a
668,971
import re def get_relvaldata_id(file): """Returns unique relvaldata ID for a given file.""" run_id = re.search('R\d{9}', file) run = re.search('_RelVal_([\w\d]*)-v\d__', file) if not run: run = re.search('GR_R_\d*_V\d*C?_([\w\d]*)-v\d__', file) if run_id and run: return (run_id.gro...
4c5444ad6c769c49778d572d5d3559c94a2460e5
668,972
def swapbytes(bytes_in): """Swaps a list of bytes to conform with TI's documentation Example: input = [0x0f, 0x00] output = swapbytes(input) print output >>> [0x00, 0x0f] Args: bytes_in (2 element list): a list of bytes to swap Returns: list: The swapped...
3dae8d6ef2d9caed62510cfe0925cb177ca834cb
668,973
def get_columns(X): """ Select columns to work with :param X: imported training data :return: all columns, numerical columns, categorical columns """ numerical_cols = [col for col in X.columns if X[col].dtype in ['int64', 'float64']] categorical_cols = [col for col in X.columns if X[col].dt...
5bc4dd521a811edccb0130c2c069910bdfc1ac02
668,974
import torch def quantile_regression_loss(T_theta, Theta, tau_quantiles): """Compute quantile regression loss. Parameters ---------- T_theta: torch.Tensor Target quantiles of size [batch_size x num_quantiles] Theta: torch.Tensor Current quantiles of size [batch_size x num...
87c91bbb5c45540301a26feef9432b8605b44f5f
668,975
def JoinOptionsList(cmd): """ For spawning processes using os.spawnv() to call Python, the options between double quotes (") must be put into just one element of the list. Turn the 'cmd' string into a list and consolidate all options between double quotes into one element. Currently not used, b...
322635ff761060cefdc74ea346257757119a0afb
668,976
def examine_wrong_examples(propagated_labels, gt_labels, rep_indices, mapping): """ :param propagated_labels: predicted labels :param gt_labels: ground truth labels :param rep_indices: indices from the original array used to choose representative frames :param mapping: indexes that refer to the rep...
2255c51e9a7d3c76348ea3e3759f112d2872e91b
668,978
import ast def parse_annotation(code): """Parse an annotation string. Return an AST Expr node. code: annotation string (excluding '@') """ module = ast.parse(code) assert type(module) is ast.Module, 'internal error #1' assert len(module.body) == 1, 'Annotation contains more than one expres...
1144cfc8be1f68dd03e373a91343ea0f078536a6
668,979
from datetime import datetime def beginning_of_this_month(): """ :return Date for first day of this month. """ return datetime.now().replace(day=1, hour=0, minute=0, second=0)
0a74bd684826cb81988ff129e17e77fd6fa73375
668,980
def welcome(): """List all available api routes.""" return ( f"Welcome to Hawaii Climate<br/> " f"<br/>" f"<br/>" f"Available Routes:<br/>" f"<br/>" f"Precipitation Details:<br/>" f"/api/v1.0/precipitation<br/>" f"<br/>" f"Li...
cdd3c300e8e6bac7dac1c5081400e9f93b0464dd
668,981
def startgame(script, match_mode='autobalance', point_count='1'): """Command for starting a game.""" ctfscript = script.server.scripts.capture_the_flag match_mode = match_mode.lower() if match_mode != 'autobalance' and match_mode != 'choose': return "There is no matchmaking mode named '%s'." % \...
0a715cee891abfabcd56532b40078dd7501e2183
668,983
def formatVectorForNCMAT(name,values): """Utility function for help in python scripts composing .ncmat files, transforming an array of of values into a properly formatted text string, with word-wrapping, usage of <val>r<n> syntax, etc. Returns list of lines (strings) for .ncmat files. """ ...
10c19f32aa6930e04bde7266fcc9136d2bbdbca6
668,984
def custom_shuffle(segs, seed, genome, whitelist=None, blacklist=None, coords_colname='coords'): """ Customized implementation of bedtools shuffle """ def _seed_prefix(x, seed): x.name = '_'.join(['perm' + str(seed), x.name]) return x # Shuffle DEL and DUP separately using +seed fo...
f38139c35d9910eacf65a479589cab9cc101717e
668,985
def _get_grashof(rho, mu, grav, theta_average, char_length, deltaT): """Grashof number. """ # Volume expansion coefficient: alpha = -V'(T)/V(T). # Approximate V'(T). dT = 1.0e-2 vpt = (rho(theta_average + dT) - rho(theta_average - dT)) / (2 * dT) volume_expansion = -vpt / rho(theta_average) ...
2358270803dc9708310b35d50472483b164cbd4f
668,986
def calculate_heading_factor(params): """ Calculate the heading factor """ """ # SUPRESS: This is too experimental while we haven't finished tracks yet closest_waypoints = params['closest_waypoints'] waypoints = params['waypoints'] heading = params['heading'] # Calculate the immediate track angle wp1 =...
327ab7c93cac9fd3077a714b45a6de5d2574a8b6
668,987
def shellquote(text): """Quote a string literal for /bin/sh.""" return "'" + text.replace("'", "'\\''") + "'"
71162a5d2ff3699068317395936167e29d069808
668,988
import argparse def parse_args(): """Collect settings from command line and set defaults.""" parser = argparse.ArgumentParser() parser.add_argument('-m', '--model', help='Model Name') parser.add_argument('-p', '--period', help='weekly/season') parser.add_argument( '-n', '--n_iters', type=i...
1d9ef4e2b1dc4abf9667edb903bf3e4f21573bad
668,989
def checkUniqueness(some_list): """ Verifies that every entry in a list is unique. If it is not, it returns non-unique values. """ unique_list = dict([(x,[]) for x in some_list]).keys() repeated_entries = [u for u in unique_list if len([s for s in some_list if s == u])...
616b79e378353dc5c70abb246fa55060cc3d5fd3
668,990
import sqlite3 def database(): """ This function creates bank database if it does not exist and define it's table >> database() >> True or False """ conn = sqlite3.connect('bank.db') conn.execute('''CREATE TABLE BankAccount (AccountNumber INT PRIMARY KEY NOT NU...
48619e59b706744d3e2c284fdc9fd5005669cc07
668,992
def encode_categorical(df): """ Compresses the size of the dataframe by changing column data type to minimum required size that can accommodate the values. This is done only for categorical columns. If a numeric column is expected to have very few values, change that to categorical first and then us...
52bfb33513bac65c3ec94c72c487080865e7e4c8
668,993
def select_main_basin(pd): """ Function that takes a dataframe from the knickpoint anaysis tool and mask it on the main basin Args: pd = pandas dataframe to mask Returns: The new pandas dataframe sorted/masked Author: Yes """ basins_count = pd.groupby("basin_key")["basin_key"].co...
5d59ada3a9104485c44281c7c4b9c3ddf6c2f760
668,994
def extendShape(shape): """Add dummy dimensions to make ``shape`` 3D. :raises NotImplementedError: If ``shape`` is neither 1, 2 or 3D. :param np.ndarray | list | tuple shape: Shape. :return: 3D shape. :rtype: tuple """ if len(shape) == 1: return shape[0], 1, 1 if len(shape) =...
d294241e958f39ee1b6d6b187354a9e652058585
668,996
def is_on_intersection(intersection, coord): """ Determines if coordinates is within intersection :param intersection: intersection object :param coord: coordinates to test :type intersection: Intersection :type coord: Coordinates :return: True if the coord is within the intersection. Fals...
c60f0515f7033842ace5d0186f76b90abbc75e57
668,998
def correct_rate(head_entity, topK_entity_idx, answers): """ :param head_entity: number index :param topK_entity_idx: topK list[number] :param answers: list[number] :return: """ points = 0 for candid in topK_entity_idx: if candid != head_entity and candid in answers: ...
232cf78e2378d6bd43a62e0ad5ad1c75e3444c1d
668,999
def is_vectorized_oper(dims): """Is a vectorized operator.""" return ( isinstance(dims, list) and isinstance(dims[0], list) )
1437731ee61c0236d1d3c98de73d5877a160431b
669,000
def get_set_bits_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer >>> get_set_bits_count(25) 3 >>> get_set_bits_count(37) 3 >>> get_set_bits_count(21) 3 >>> get_set_bits_count(58) 4 >>> get_set_bits_count(0) 0 >>> get_set_bits_count(256)...
52a93fa843449c363c47259f4e24270a50dad5aa
669,001
import os, json def get_inputdata(path): """ A function to extract the smiles, MP dataset required for unsupervised learning. :param path: full path (str) :return: SMI (list), MP (list) """ json_list = list() for filename in os.listdir(path): if 'json' in filename: ...
461497e51398d8ab1e564c9d31313b6f8f08db24
669,002
def areas_html(): """HTML raw page fixture for Areas dashboard.""" return """<div class="row output-table"> <table class="input-table footable" data-page-size="5"> <thead> <tr> <th class="area-first-column"> <h2 data-areaindex="1" id="hAreaName_3">Home...
78ffd6ce51047ef0e962645bfa0d4053db4a0797
669,003
def get_nth_fibonacci_recursive(n): """ @brief nth number is the sum of the (n - 1)th and (n-2)th numbers. O(2^n) time. Since all computational branches always end in leaves valued in 1. """ assert n >= 0 if (n == 0 or n == 1): return 0 if (n == 2): return 1 retur...
841bef162589d1d390fa4e6cfda97c96536e3620
669,004
def get_img_to_cap_dict(filename): """ Opens the file storing image to caption mappings. Creates a dictionary and adds the mappings as key-value pairs to it. Args: filename: the name of the file storing image to caption mappings Returns: img_to_cap_dict: the dictionary storing image to caption mappings """ ...
f821c3c6cd68e4a420888be99c8877caae1efdc8
669,005
def basic_data(): """Basic (incomplete) data used to initialize NBPExchangeRate objects.""" return { 'currency_code': 'USD', 'date': '2017-01-01', 'source_id': '1/A/NBP/2017', }
dcac1551bc59dd6dc005939e1b8597a23c5d96fa
669,006
import time def get_scope_records(device, daq, scopeModule, num_records=1): """ Obtain scope records from the device using an instance of the Scope Module. """ # Tell the module to be ready to acquire data; reset the module's progress to 0.0. scopeModule.execute() # Enable the scope: Now the...
aaace15ce636f62128b3dde96105f75ff177b64e
669,007
def ratio_features(data_df): """ Take ratio of values of two columns and present it as a new feature :param data_df: full_data :return: modified full_data """ for col1, col2 in [["roomnights", "days_stay"]]: data_df[col1 + "_ratio_" + col2] = data_df[col1] / data_df[col2] return dat...
731d93987b5dd36d729d811e937f20be841ad551
669,008