content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def convert_email(value: str) -> str: """Convert email domain from student to employee or vice versa""" user, domain = value.split('@') if domain.startswith('st.'): return f"{user}@{domain[3:]}" else: return f"{user}@st.{domain}"
b927a521f379698bcc57c125c39de63a5552d9a6
678,568
import os import json def load_config(): """Read config.json""" config_path = os.path.join(os.path.dirname(__file__), "..", "..","..", "config.json") with open(config_path, "r") as config_fh: config = json.load(config_fh) return config
7c8ed07381bc13e1b04c3370cb11eda753cd408d
678,569
def depart_gmt_plot(self, node): # pylint: disable=unused-argument """ Actions to take at the end of a plot directive. """ return None
d82ccf43452d8f9a430a1ed207cc7a2891858d8a
678,570
import six def sudo_support(fn, command): """Removes sudo before calling fn and adds it after.""" if not command.script.startswith('sudo '): return fn(command) result = fn(command.update(script=command.script[5:])) if result and isinstance(result, six.string_types): return u'sudo {}'...
b01dc0f7cf8a92c2bde0bbf4f70febcd33a9db39
678,571
def intersection(r1, r2): """Calculates the intersection rectangle of two regions. Args: r1, r2 (dict): A dictionary containing {x1, y1, x2, y2} arguments. Returns: dict or None: A dictionary in the same fashion of just the intersection or None if the regions do not int...
5c435866d36f4dfffa13c443a04ede9beab6e932
678,572
def formatdevaddr(addr): """ Returns address of a device in usual form e.g. "00:00:00:00:00:00" - addr: address as returned by device.getAddressString() on an IOBluetoothDevice """ # make uppercase cos PyS60 & Linux seem to always return uppercase # addresses # can safely encode to as...
d06220f8115998a77cc4d9111c45960ccac18e9c
678,573
def get_map_attributes(declarations): """ """ property_map = {'map-bgcolor': 'background'} return dict([(property_map[dec.property.name], dec.value.value) for dec in declarations if dec.property.name in property_map])
5cd0b24dc9b64c0da42d2ca5fb2ca348ce7fc96a
678,574
def put(lens, big, small): """ Set a value in `big`. """ return lens.put(big, small)
db007a06c50a9225f3c2844372d18dc388012f23
678,575
def get_label_name_from_dict(labels_dict_list): """ Parses the labels dict and returns just the names of the labels. Args: labels_dict_list (list): list of dictionaries Returns: str: name of each label separated by commas. """ label_names = [a_dict["name"] for a_dict in labels...
3b9f429438ba26f997660bc0731bc6a79a053657
678,576
def _FormatToken(token): """Converts a Pythonic token name into a Java-friendly constant name.""" assert str(token).startswith('Token.'), 'Expected token, found ' + token return str(token)[len('Token.'):].replace('.', '_').upper()
96f8e2a418daa9ea44b2933b35ace88f6d0cc92b
678,577
import networkx def nx_create_graph(graph): """Covert a graph from the simple_graph package into networkx format.""" G = networkx.DiGraph() G.add_nodes_from(range(0, len(graph))) for i, edge_list in enumerate(graph): if len(edge_list) != 0: to_add = [(i, e) for e in edge_list] ...
00b5f4faca2c1c8e3bad7e858a335cea3939c3e2
678,579
def is_fun_upd(t): """Whether t is fun_upd applied to three parameters, that is, whether t is of the form f (a := b). """ return t.is_comb('fun_upd', 3)
04d1eeaaff7a92f2438a51ebdb55ce1e52bdc011
678,580
def JustFileName(fpath): """ Extracts the file name from the path Input: fpath - Full path """ if(fpath.find('/')>-1): rfpath = fpath[::-1] rfname = rfpath[:rfpath.find('/')] fname = rfname[::-1] return fname else: return fpath
75bcca150a1772a7e3ca99982e92dda61c26db3c
678,581
def sort_maf(df): """ Sort chromosome, start positions correctly (1-22, X, Y, etc.) """ df['chromosome'] = df['chromosome'].apply( lambda x: int(x) if x.isdigit() else x) df = df.sort_values(['chromosome', 'start_position']) df['chromosome'] = df['chromosome'].astype(str) df.reset_index(inpl...
9726183db1fc2412c3cf6a4a6a2167f715a33936
678,582
def select_field(features, field): """Select a field from the features Arguments: features {InputFeatures} -- List of features : Instances of InputFeatures with attribute choice_features being a list of dicts. field {str} -- Field to consider. Returns: [list] -- List ...
13912cf5bf9d2920799c30376be5d4b368d6aad9
678,583
import re def purify_app_references(txt: str) -> str: """ Remove references to `/app`. """ txt = re.sub("/app/", "", txt, flags=re.MULTILINE) return txt
3461d9fa4e6e86918919b3b635fa3aa0c8205344
678,584
def is_in(var, obj): """ If the contents of "var" is equivalent to the value in obj.name. :param var: The value to look for. :type var: str :param obj: The object to iterate over. :type obj: dict/class :returns: True, False """ r = False for o in obj: if var == o.name: ...
8a2e6e5248da92772758462f9f0f769cbaf3f49c
678,585
def paths_from_issues(issues): """Extract paths from list of BindConfigIssuesModel.""" return [issue.path for issue in issues]
a1a105058f5682fd6c680ab44701d83161157a4b
678,586
def get_hosts_descriptions(hosts_scans): """ Get the hosts descriptions Args: hosts_scans (list[dict]): hosts scans information. Returns: List[dict]: images descriptions. """ return [ { "Hostname": scan.get("hostname"), "OS Distribution": scan.ge...
2801797123bfb724d918b95fcd88cd5d41204431
678,587
import argparse def parseargs(): """ Parse arguments """ parser = argparse.ArgumentParser(description="ACT Bootstrap data model") parser.add_argument( "--userid", type=int, dest="user_id", required=True, help="User ID") parser.add_argument( "--object-typ...
9f597b01d7d0867d419fc3aac7108fabcdadbaa2
678,588
def ali_je_palindrom(n): """preveri, ali je število n palindrom""" n = str(n) if n == '' or len(n) == 1: return True elif n[0] == n[-1]: return ali_je_palindrom(n[1:-1]) else: return False
e8783f927bd1ead3b64ddc0c7dd9060374dcf800
678,590
def draw_rectangle(image=None, coordinates=None, size=None, color=None): """ Generate a rectangle on a given image canvas at the given coordinates :param image: Pillow/PIL Image Canvas :param coordinates: coordinate pair that will be the center of the rectangle :param size: tuple with the x...
ff492e256594ef562d58a8d9fdce0c1b6b10e99b
678,591
def __dive_to_detect_iteration(SM0, sm0_state, SM1, sm1_state, VisitList=[]): """This function goes along all path of SM0 that lead to an acceptance state AND at the same time are valid inside SM1. The search starts at the states sm0_state and sm1_state. """ sm0_transition_list = sm0_state.t...
fe7f7f6a63d57b3397512bc9cf5009007a646f70
678,592
import argparse def _parse_args(): """ Subroutine to parse command line arguments """ parser = argparse.ArgumentParser( description="Perform an FRI Calculation") parser.add_argument( 'hf_path', type=str, help="Path to the directory that contains the HF output files eris.npy, hcore...
b90331a3dac27b93d5884cfd748198e665139344
678,593
def resource_provider_url(environ, resource_provider): """Produce the URL for a resource provider. If SCRIPT_NAME is present, it is the mount point of the placement WSGI app. """ prefix = environ.get('SCRIPT_NAME', '') return '%s/resource_providers/%s' % (prefix, resource_provider.uuid)
c0fc414c5873f0af2389fc2b220b09031d604e75
678,594
def add_if_not_exists_raw(string, name): """ turn a 'CREATE INDEX' template into a 'CREATE INDEX IF NOT EXISTS' template in PostgreSQL 9.5 it would be return string.replace('CREATE INDEX', 'CREATE INDEX IF NOT EXISTS') but the current implementation does the same thing for 9.4+ """ # ...
125ce96f76b874475d5e12926709b86493bf4c3a
678,595
def JavaMemberString(scope, type_defn): """Gets the representation of a member name in Java. Args: scope: a Definition for the scope in which the expression will be written. type_defn: a Definition for the type. Returns: a string representing the type """ # Silence gpylint scope, type_defn = s...
843c9c1e106e25ddfafa9a1667c417d0c0707345
678,596
import numpy import pandas def bodycomp(mass, tbw, method="reilly", simulate=False, n_rand=1000): """Create dataframe with derived body composition values Args ---- mass: ndarray Mass of the seal (kg) tbw: ndarray Total body water (kg) method: str name of method used t...
54fff1497a25545b67223623bf8f0adc41314c8b
678,597
def _get_real_chan_name(chan): """ Get the real channel name Channels with a light group will have the light group appended to the name """ ch_name = chan.channel_name lgt_grp = chan.light_group.strip() if lgt_grp != '' and lgt_grp not in ch_name: ch_name = '%s_%s' % (ch_name, lgt_gr...
a6e58188599bb17757fb93c5e04d8fc127bca84a
678,598
import subprocess def run_without_error(shell_command: str) -> bool: """ Run the given shell command Print the command ouput (even in Jupyter) and return whether the command ran without error (exit code 0) """ status = subprocess.run(shell_command.split(), capture_output=True) print(statu...
6e2067144b7d741becb5a020def87162b66d9ac7
678,599
import torch def pack_beam(hyps, device): """pack a list of hypothesis to decoder input batches""" token = torch.LongTensor([h.sequence[-1] for h in hyps]) hists = tuple(torch.stack([hyp.hists[i] for hyp in hyps], dim=d) for i, d in enumerate([1, 1, 0])) token = token.to(device) ...
cc877fc9860584f879a79758d1d884923e065919
678,600
def getOutputsNames(net): """Get the output names from the output layer Arguments: net {network} -- Yolo network Returns: list -- List of names """ layersNames = net.getLayerNames() return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]
502c95c0ad37edcce2da454e42aae4d07ec8dc7b
678,601
from typing import List def ds_make(n: int) -> List[int]: """ Make n subsets containing the numbers 0 to n - 1. """ # The value of element i is the parent of that set # If parent is itself then it's the root return [i for i in range(n)]
ea1b0266751cedb85a8fe8ea8be1ce5bc45a68b9
678,602
def error_email_subject_doi(identity, doi): """email subject for an error email""" return u"Error in {identity} JATS post for article {doi}".format( identity=identity, doi=str(doi) )
7c8f04437971b0e0511f2b5d7076fe87129868bb
678,603
import torch def batched_concat_per_row(A, B): """Concat every row in A with every row in B where the first dimension of A and B is the batch dimension""" b, m1, n1 = A.shape _, m2, n2 = B.shape res = torch.zeros(b, m1, m2, n1 + n2) res[:, :, :, :n1] = A[:, :, None, :] res[:, :, :, n1:] ...
76da3c7f344c0ceddf74e65fd4aae749731bb0a4
678,604
def dict_search(lst, search): """リストに入っているdict型の値のうち、searchに一致するものだけを取得する """ searched = [] skey, svalue = search for item in lst: if item[skey] == svalue: searched.append(item) return searched
faf82230fc74e4daebb9d8f1407134e6921103a8
678,605
def process_dataset(dataset, labeler): """Labels all items of the dataset with the specified labeler.""" return {item: labeler.label_object(item, true_description) for item, true_description in dataset.items()}
9e69704555e5129b5a015160e37db6a87a381dd8
678,606
import click import requests from bs4 import BeautifulSoup def search_list(username, search_type): """Search a user's list for a manga or anime and return the matching entry :param username: A string, the username of a MAL user :param search_type: A string, must be either "anime" or "manga" :return: ...
14b2b719b2e249a1c6e2ddfa64703e6c108c5d40
678,607
import re def bpf_parametrize(bpf_text, args): """ A function to change specific parameters in eBPF program code to customize it before compiling and executing in the kernel. """ res = bpf_text if args.unique_interval: print("Unique flows filtering enabled (within %ds interval)" % args...
29d1395c21fc3b29f0e11cdfce4870efa95e3615
678,608
def cleanHtmlBody(htmlBody): """For some reason htmlBody values often have the following tags that really shouldn't be there.""" if htmlBody is None: return "" return (htmlBody.replace("<html>", "") .replace("</html>", "") .replace("<body>", "") ...
efb6e761a1e76ac8684aca7177f517de868c0ef2
678,610
import copy def fill_other_holes(key: str, full_tree: dict, chat: str, chat_tree_inserts: dict) -> dict: """Given a full tree (with holes), node type of swaps and the chat command, fill the holes for nodes that we are not swapping. """ new_tree = copy.deepcopy(full_tree) for k, v in new_tree.items...
ed44c9e134b8cc65d781a0279de4be40c3d6a5db
678,611
def user_info( first_name, last_name, **profile): """Function that builds user information.""" profile['firstname'] = first_name profile['lastname'] = last_name return profile
c7108061000dab067f3cece044486c906aa67e90
678,612
def harmonic_mean(frequencies1, frequencies2): """Finds the harmonic mean of the absolute differences between two frequency profiles, expressed as dictionaries. Assumes every key in frequencies1 is also in frequencies2 >>> harmonic_mean({'a':2, 'b':2, 'c':2}, {'a':1, 'b':1, 'c':1}) 1.0 >>> har...
c8701a5df020bd8f4d1655f406a13ffdf92cf362
678,613
def dnfcode_key(code): """Return a rank/dnf code sorting key.""" # rank [rel] '' dsq hd|otl dnf dns dnfordmap = { u'rel':8000, u'':8500, u'hd':8800,u'otl':8800, u'dnf':9000, u'dns':9500, u'dsq':10000,} ...
fb1be042adb6fd25371c7b382df68f0c7e34d926
678,614
from pathlib import Path import json import pandas def data_loader(file_path): """ opens source file at filepath and reads data into either dictionary object or pandas dataframe object :param file_path: path to file :return: data_frame or dictionary """ extension = Path(file_path).suffix ...
d24429ed66460cb1b7c1472d17027867c1d33d46
678,615
import re def sanitize_for_path(value, replace=' '): """Remove potentially illegal characters from a path.""" sanitized = re.sub(r'[<>\"\?\\\/\*:|]', replace, value) return re.sub(r'[\s.]+$', '', sanitized)
4e8b51742782122402453ffa6a7cc5718deef348
678,616
import itertools def countCombosSumEqual(sm: int, nums: list) -> int: """ Count all possible combos of elements in nums[] such that sum(combo) == sm Args: sm (int): the sum to match. nums (list): list of positive integers. Returns: int: resulting count. If nums[0] == sm,...
6ab5af1a6b26d6043b677f607a56e989d6d45200
678,617
from typing import List from typing import Dict def get_line_index_overlap_count(line_index_frequencies: List[Dict[int, int]]) -> int: """Returns total line index overlap count.""" return sum([*map( lambda d: len([*filter(lambda v: v > 1, d.values())]), line_index_frequencies )])
37b50bac7d61b13a17240a477559ddb9eea19841
678,618
def makeHook(func): """Special method marker decorator""" func.is_hook = True return func
6205a7d28884c730ee6488c89207860ef8144c04
678,619
def areStringParameters(parameters: list) -> bool: """ This method verifies whether or not all values in the list are strings. :param parameters: A list of parameters for which needs to be verified whether or not all values in it are strings. :return: A boolean value indicating whet...
99763758319af2bf6d222cc4c1b62d1650ca81df
678,620
def family_ped(family, family_count): """Determine a family ID and return family info strings in PED format.""" # Determine family id - ideally, sampleID of the first affected child. familyID = family_count if len(family) == 1: familyID = family[0].sampleID else: for sample in fami...
9294d3752c45b36220d8985f5dbaf493e0835d1d
678,621
def SquishHash(s): """ SquishHash() is derived from the hashpjw() function by Peter J. Weinberger of AT&T Bell Labs. https://en.wikipedia.org/wiki/PJW_hash_function """ h = 0 for f in s: h = (h << 4) + ord(f.lower()) g = h & 0xf0000000 if g != 0: h |= g >> ...
f4c7e2cc404871dc99c3da0a4666396c18835e5a
678,622
import re def titleize(name): """ Titleize a course name or instructor, taking into account exceptions such as II. """ name = re.sub(r'I(x|v|i+)', lambda m: 'I' + m.group(1).upper(), name.strip().title()) name = re.sub(r'(\d)(St|Nd|Rd|Th)', lambda m: m.group(1) + m.group(2).lower(), name) name = re.su...
b4eb58ec092d89d23d1e878a8b0de077ec17c551
678,624
def get_prediction_results(data, labels, predict_prob, vocab_dict, label_dict): """ Get the prediction and the true labels with the words in conll format @params : data - unpadded test data @params : labels - unpadded test labels @params : predict_prob - the predicted probabilities @params : voc...
b3b1cb1434fcf778252784d5cdd16e277465eff6
678,625
def get_index_of_user_by_id(id_value, data): """Get index of user in list by id""" for count, item in enumerate(data): if item['id'] == id_value: return count return None
4bdf8001224aa6b96343e0bce0354fc59d6e962b
678,626
def starts_new_warning(line) -> bool: """Return true if the line starts a new warning.""" return "warning:" in line
10e6871d3ae10ec4d856b3dd4b966a5050cf06f7
678,627
def find_path(start, end, parents): """ Constructs a path between two vertices, given the parents of all vertices. Parameters ---------- start : int The first verex in the path end : int The last vertex in the path parents : list[int] The parent of a vertex in its pa...
f38f4f2fb9631476f20372113066ef94dc3d23e0
678,628
def argname(arg): """Format illegal argument names (like 'new').""" name = arg.name if arg.name == 'new' or arg.name == 'old': name += 'path' return name
c5f18b3ea4c311d1610c49cdbaff657e9c4971e7
678,629
def ComptageNil(tree): """Compte le nombre de pointeurs nuls de l'arbre tree.""" if tree is None: return 1 if tree.is_empty(): return 4 number = 0 number += ComptageNil(tree.left) number += ComptageNil(tree.middle) number += ComptageNil(tree.right) return number
47ed85b915b25ab45875b7acf32022920a109161
678,630
def get_class_image_ids(self, class_name=None, class_id=None): """ Retrieves image_ids associated with class_name or class_id """ return self.get_class_info(class_id=class_id, class_name=class_name)['image_ids']
c354cf627ba3fff7f19f54655c9997a55cfa11dc
678,631
import string def cols2num(cols): """ convert column in excel to number for python. Input = ['B','K']; output = 1, 10 * does not work with double chars, e.g. AA and beyond; use openpyxl.utils.column_index_from_string """ nums = [] for col in cols: num = 0 #for c in col: ...
adf4af314a184f1f08551af3032dc4da48e5adb4
678,632
def use_rule(name, rule): """Use one of rules and apply it to identification""" result = name parts = rule.split() for part in parts: if part[0] == '-': shift = len(part[1:]) result = result[:-shift] elif part[0] == '+': result = result + part[1:] ...
832f2ca69ab3d17d2ccefca170735ec3c871fc56
678,633
def showCurPos(length, pos1, marker1="^", pos2=None, marker2="*"): """A helper function to make a string to show the position of the given cursor.""" display = [" "] *length display[pos1] = marker1 if pos2: display[pos2] = marker2 return "".join(display)
dfd4fe2cd37efdbbf98ca246963cee19523b660a
678,634
from typing import Union def _get_vars(symbol: Union[str, int]) -> str: """Get the javascript variable declarations associated with a given symbol. These are adapted from plotly.js -> src/components/drawing/symbol_defs.js Args: symbol: The symbol whose variables should be retrieved. Returns...
487a93b649ce4c35b3cbea59cc931e8f4c68e0b0
678,637
import re def make_consts_consecutive(s): """ The given phenotype will have zero or more occurrences of each const c[0], c[1], etc. But eg it might have c[7], but no c[0]. We need to remap, eg: 7 -> 0 9 -> 1 so that we just have c[0], c[1], etc. :param s: A given phenotype str...
dad03e955efb8f7e78e9e3bfc13a7a3204689691
678,638
import os def on_dev_server(): """ Return true if we are running on dev_appserver""" return os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
7e45bad831c9357bc28b8e9cadf5e153053bfb76
678,639
def chinese_zodiac_traditional(translation): """ Returns the original translation of the Chinese Zodiac in the script of Mandarin Chinese. Parameters ---------- translation: str The input string from the chinese_zodiac_translation which houses all the calculations. traditional: str ...
4cff75cff6101b4608c36b0323593fa694eb7f62
678,640
def normalized_value(xs): """ normalizes a list of numbers :param xs: a list of numbers :return: a normalized list """ minval = min(xs) maxval = max(xs) minmax = (maxval-minval) * 1.0 return [(x - minval) / minmax for x in xs]
8036e8041982ebbb5ad21a8f8468797b1ea3e58c
678,641
import yaml def _yaml_reader(yaml_file): """Import the YAML File for the YOLOv5 data as dict.""" with open(yaml_file) as file: data = yaml.safe_load(file) return data
fdbb318a5e8176dcf7072643d40fdc433de0b6d4
678,642
import os import json def read_(db_path): """Read data from db_path. Args: db_path (PATH): Path to file. Raises: FileNotFoundError: If file is not found. Returns: dict: Associated data. """ exist = os.path.exists(db_path) # Check for existance. if exist == True: ...
d0d88a01fbcac7b4210e3e21101d05ab4d800231
678,643
def valid_for_gettext(value): """Gettext acts weird when empty string is passes, and passing none would be even weirder""" return value not in (None, "")
b338d33b13364410cc9b4af5bf5d4a74cab1bef1
678,644
def convert_indices(direction, x, y): """ Converts indices between Python and Fortran indexing, assuming that Python indexing begins at 0 and Fortran (for x and y) begins at 1. In Tracmass, the vertical indexing does begin at zero so this script does nothing to vertical indexing. Examples: ...
3984174fa435cc2e8694fff0b516ec7d87d489fe
678,645
def get_or_none(model, **kwargs): """ Gets the model you specify or returns none if it doesn't exist. """ try: return model.objects.get(**kwargs) except model.DoesNotExist: return None
590d18d17eb39f8524473f457faebf37f0fb771d
678,646
import torch def get_min(hook, bins_range): """ Compute the percentage of activations around zero from hook's histogram matrix. """ res = torch.stack(hook.stats[2]).t().float() return res[slice(*bins_range)].sum(0) / res.sum(0)
b29a031e8d8a72824ab1f973ae7fd23c32771911
678,647
import os def get_test_name_from_spec_file(full_path): """Generate test name from a spec test file.""" _, filename = os.path.split(full_path) test_name = os.path.splitext(filename)[0].replace('-', '_') return test_name
c51d351870b32418ba6d7f9a1647cea0f644bbc3
678,648
def _copy_remove_keys(dic, keys): """ convenience function returning the copy a dict missing keys """ new_dic = {_k: _v for _k, _v in dic.items() if _k not in keys} return new_dic
20b51c66af44cfd01059bafe775878d52da8d689
678,649
def armijo(fun, xk, xkp1, p, p_gradf, fun_xk, eta=0.5, nu=0.9): """ Determine step size using backtracking f(xk + alpha*p) <= f(xk) + alpha*nu*<p,Df> Args: fun : objective function `f` xk : starting position xkp1 : where new position `xk + alpha*p` is stored p : search ...
0b44b06fe6db1f778dbc22995a2800ebbf6f051a
678,650
import os import subprocess def ontology_file_formatter(loc: str, full_kg: str, owltools: str = os.path.abspath('./pkt_kg/libs/owltools')) -> None: """Reformat an .owl file to be consistent with the formatting used by the OWL API. To do this, an ontology referenced by graph_location is read in and output to t...
a78aa2118794f669f1b100b6ce4439fa93e1f0ed
678,651
import numpy import math def mean_var_skew(data): """return the mean, variance, and skewness of data """ data = numpy.array(data) num = data.shape[0] mean = numpy.add.reduce(data)/float(num) var = numpy.add.reduce((data - mean)**2)/float(num-1) # std = math.sqrt(var) skew = numpy.a...
e34352263e226f0c454f4040364abf4ff669efcf
678,652
def processObjectListWildcards(objectList, suffixList, myId): """Replaces all * wildcards with n copies that each have appended one element from the provided suffixList and replaces %id wildcards with myId ex: objectList = [a, b, c_3, d_*, e_%id], suffixList=['0', '1', '2'], myId=5 => objectList = [a, b, c_3, e...
aaa2a59c36822a94b51d0b08a617b671b8429513
678,653
def get_remote_file_name(url): """Create a file name from the url Args: url: file location Returns: String representing the filename """ array = url.split('/') name = url if len(array) > 0: name = array[-1] return name
5591b5ea17344b08d09b85548c83061bcd4e3162
678,654
def has_nan(dataframe): """ Return true if dataframe has missing values (e.g. NaN) and counts how many missing value each feature has """ is_nan = dataframe.isnull().values.any() no_nan = dataframe.isnull().sum() # is_infinite = np.all(np.isfinite(dataframe)) return is_nan, no_nan
691c7fb8e3934cdf7543805b38f1f4d287421c55
678,655
def GnuHash(name): """Compute the GNU hash of a given input string.""" h = 5381 for c in name: h = (h * 33 + ord(c)) & 0xffffffff return h
49ed421d6b055047e81c63d1f15e3be7dea60f68
678,656
def dp_fib_ls(n: int): """A dynamic programming version of Fibonacci, linear space""" res = [0, 1] for i in range(2, n+1): res.append(res[i-2] + res[i-1]) return res[n]
36959ccfd56c01b52c8b989d9b10672401f5230d
678,657
def get_version(): """Load the version from version.py, without importing it. This function assumes that the last line in the file contains a variable defining the version string with single quotes. """ try: with open('pycydemo/version.py', 'r') as f: return f.read().split('=')...
cc111c79cfa86fa3d602110c875c8d2ae0d392a8
678,659
import re def yapi_swagger_param_template(param_type, description, field): """解析apidoc为yapi或在swagger格式的参数模板 :param param_type: 请求类型 :param description: 描述 :param field: 参数 :return: """ if '[]' in param_type: # 数组类型模板 object_item = { "type": "array", ...
6c9ffc890f92c9b7ed494574846f0134da3124df
678,660
def hex_to_rgb(hex_str: str, normalized=False): """ Returns a list of channel values of a hexadecimal string color :param hex_str: color in hexadecimal string format (ex: '#abcdef') :param normalized: if True, color will be float between 0 and 1 :return: list of all channels """ hex_str = he...
5a6ac8fd0a45264984bee7575011b6886e5ddee4
678,661
import math def adam(opfunc, x, config, state=None): """ An implementation of Adam http://arxiv.org/pdf/1412.6980.pdf ARGS: - 'opfunc' : a function that takes a single input (X), the point of a evaluation, and returns f(X) and df/dX - 'x' : the initial point - 'config` : a t...
7171ad2862e4d96b204eae01383a2e296bbe006b
678,662
import os def dcm2niix_json_fname(info, ser_no, suffix): """ Construct a dcm2niix filename from parse_dcm2niix_fname dictionary Current dcm2niix version: v20200331 :param info: dict series metadata :return: str dcm2niix filename """ if len(suffix) > 0: ser_no = '{}...
97bf8cad8e7f666828a89338062ed86cad73acc2
678,663
def _partition(nums, left, right): """Util method for quicksort_ip() to rearrange nums in place.""" # Use right number as pivot. right_num = nums[right] # Rearrange numbers w.r.t. pivot: # - For left <= k <= i: nums[k] <= pivot, # - For i+1 <= k <= j-1: nums[k] > pivot, # - For k = right: ...
29b23ca1f703428b987d5f2843e9a9bf3ebea81f
678,664
def map_colnames(row, name_map): """Return table row with renamed column names according to `name_map`.""" return { name_map.get(k, k): v for k, v in row.items()}
5a4182996632bade50ef8239229047c91f4cff77
678,665
def get_interquartile_lower_upper(df, target_column): """ Gets the quantiles a variable and returns the interquartile range""" quantile_25 = df[target_column].quantile(0.25) median = df[target_column].quantile(0.5) quantile_75 = df[target_column].quantile(0.75) interquartile_range = [quanti...
d77db7a63918ce9d3ebb205d4dcb99f8e09ff0aa
678,666
def source_lang(arg): """ detects if the arg is a source lang """ if arg.startswith("!") and len(arg) == 3: return arg[1:] raise Exception
c6ad1bd38c09291b9b9d648ee5e8f65d2c4a3c3c
678,667
def get_uniprot(tax, acc): """ get matching uniprot id given taxid """ taxid1 = list(acc['taxid']) taxid2 = list(acc['taxid2']) taxid3 = list(acc['species_taxid']) if int(tax) in taxid1: unip = acc[acc['taxid']==int(tax)]['uniprot'].item() elif int(tax) in taxid2: uni...
cd65c8485ed5a4a589d824cd97a31eec0a192604
678,668
def empty(obj): """* is the object empty? * returns true if the json object is empty """ if not obj: # Assume if it has a length property with a non-zero value # that that property is correct. return True if len(obj) > 0: return False if len(obj) == 0: ret...
227f769199a58489b8d31418db8b7c25526b61d5
678,669
def is_ineq(tm): """check if tm is an ineq term.""" return tm.is_greater() or tm.is_greater_eq() or tm.is_less() or tm.is_less_eq()
759bc062752f288ab83d67f610a6f04136b0ab69
678,670
def show_resource_pool(client, private_cloud, resource_pool, location): """ Returns the details of a resource pool. """ return client.get(location, private_cloud, resource_pool)
fdca38cfc891eebb37b6ec22c78c321c9aa9fe6c
678,671
def limpiar(texto: str) -> str: """El texto que recibe se devuelve limpio, eliminando espacios dobles y los espacios que haya tanto al principio como al final. :param texto: Texto de entrada :type texto: str :return: Texto de entrada limpio (eliminando :rtype: str >>> limpiar("estoy escribi...
f856e4cfca0423fbbee7d4dbfdf2a16da0c4c164
678,672
import sqlite3 def get_sqlite_connexion(): """This function returns the sqlite connection :returns: The connetion with the database """ return sqlite3.connect('holyscrap.db')
af585f0d32619930e1f939b42bb1fb23f94cea7f
678,673
from typing import Dict from typing import Optional def weighted_average( distribution: Dict[str, float], weights: Dict[str, float], rounding: Optional[int] = None, ) -> float: """ Calculate a weighted average from dictionaries with the same keys, representing the values and the weights. Args...
b6c710fc8039b79637c8d45329eb90cc0d1bb264
678,674