content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def is_xml_response(req): """Returns True when the request wants an XML response, False otherwise""" return "Accept" in req.headers and "application/xml" in req.accept
643e42ab57fe612de4f7e7121477b4574971992b
406,372
def build_pubmed_url(pubmed_id) -> str: """ Generates a Pubmed URL from a Pubmed ID :param pubmed_id: Pubmed ID to concatenate to Pubmed URL :return: Pubmed URL """ return "https://pubmed.ncbi.nlm.nih.gov/" + str(pubmed_id)
5794fbec75de0451547d6f0570bb89964026c394
5,081
import requests def image_exists_on_dockerhub(image_name: str, image_tag: str) -> bool: """ Given an image name and image_tag, check if it is publicly-accessible on DockerHub. Based on the code from this blog post: * htttps://ops.tips/blog/inspecting-docker-image-without-pull/ :param image_n...
989214d56a2a4635759c1bc6fc821e63a2e28718
90,734
def calculate_cbar_dims(img_width, img_figsize, img_height): """ Helper for plot_topomap_3d_brain when plotting multiple views and using the matplotlib backend. Calculates the colorbar width and height to be placed correctly. Parameters: img_width: matplotlib.figure.Figure Numbe...
60f8c668f7e3ae04d6943e1a2ecd974dbba0bb07
159,906
def fibonacci2(number: int) -> int: """ Generate the fibonacci number for n Utilizes caching to mimic literal memoization, has lower recursive limit... 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :return: Fibonacci number """ ...
ba32daf9b9b56faecda305f50d9e8f5cb7e4c1cb
635,802
import math def get_learning_rate(lr_schedule, tot_epoch, cur_epoch): """ Compuate learning rate based on the initialized learning schedule, e.g., cosine, 1.5e-4,90,6e-5,150,0 -> ('cosine', [1.5e-4,90,6e-5,150,0]). Args: lr_schedule: the learning schedu...
a6ee1d202d846094243baa120f1486e33016a174
636,900
import string def populate_cypher_query_template_with_values_in_dict(cypher_query_template, dictionary): """Populates and Returns a user provided Cypher query with values plucked from a `dictionary`. Args: cypher_query_template (:obj:`string.Template`): string.Template to populate with values. ...
bcb2e11350e15e9da39df88259b38800855f3e57
499,244
def imap(imap, vmin=None, vmax=None, cmap='YlGnBu_r', length_unit='cm'): """ Convenience base function to plot any IntensityMap2D instance Parameters ---------- ratemap : IntensityMap2D Intensity map to plot cmap : Colormap or registered colormap name, optional Colormap to use f...
fbc19e21f7740bb2965f99398090eb24929b4e52
646,498
import json def load_from_json(filepath): """ Load json file from filepath into a dictionary :param filepath: :return: python dictionary """ data = dict() with open(filepath) as data_file: data = json.load(data_file) return data
4943a9719feac01f42000ea3f4b2f2240ad8acaa
602,921
import torch def collate_fn(task_list): """Custom collate function to batch tasks together into single tensors. Args: task_list: a list of tasks, where each task is a dictionary as returned by the __getitem__ method of the dataset object Returns: batch: a dictionary with keys 'co...
2cae401001145e5d7b8489f7499a7b781be35a90
344,929
def compare_acl(acl1, acl2): """ Compares two ACLs by comparing the role, action and allow setting for every ACE. :param acl1: First ACL :type acl1: dict with role, action as key and allow as value :param acl2: Second ACL :type acl2: dict with role, action as key and allow as value :return:...
4e38bb1a0dabe58401898a804bc5d3054861df97
663,923
def check_now_deleted(page): """Returns true if the page is deleted""" # simple check for any content, does catch blanked pages though return not page.text
9e48fbca1a8b08f26deb2651d979c13c9d09dadf
509,876
import re def check_element_symbol(name, symbol): """ Checks if symbol is valid for the element :param name: Element name :param symbol: Validated symbol :return: True if symbol is valid, False otherwise """ # valid symbol has exactly 2 chars if not len(symbol) == 2 or not symbol.istit...
3fe6d9405bc72ad1280b6a59a52edbd9f3eadfed
275,085
import requests def __create_auth_github_session(cfg, session=None): """Create and return GitHub session authorized with token in configuration object""" session = session or requests.Session() token = cfg["github"]["token"] def token_auth(req): req.headers["Authorization"] = f"token {token}"...
2708543b99c013b31558838df3e4861288888b6c
91,966
def intersection_count_to_boundary_weight(intersection_count: int) -> int: """ Get actual weight factor for boundary intersection count. >>> intersection_count_to_boundary_weight(2) 0 >>> intersection_count_to_boundary_weight(0) 1 >>> intersection_count_to_boundary_weight(1) 2 """ ...
34303e1200db250236c950ec1c21d0dd7b27800d
167,679
def formatUintHex64(value): """ Format an 64 bits unsigned integer. """ return u"0x%016x" % value
af82b7b6dd138333f09cf93e9d7990be286333fd
688,266
def listFromFile(fileName): """Read in a file; return a list of its lines. Ignore blank lines.""" lines = [] with open(fileName, 'r') as inF: line = inF.readline() while (line): line = line.rstrip() if (len(line)): lines.append(line) line ...
63ba94bd18b6401d2f3b0aee7e06a543fc530105
491,326
import json def validate_file(file_name): """File validation. Create/Open File, return list of dicts """ try: with open(file_name,'r'): print('-- Opening file... \'' + file_name + '\'!!') with open(file_name,'r') as fread: all_events = json.load(fread) ...
2da8ea3148ee63ef8689b270eb5645b1257baabc
372,746
from typing import FrozenSet from typing import List def get_profit(solution: FrozenSet[int], profit: List[float]): """ Calculates and returns total profit of given knapsack solution :param solution: Knapsack solution consisting of packed items :param profit: profit of items :return: Total profit ...
c7c359582446908535964d8c6d4b45dac6b0f6af
271,472
import re def space_in_tables(filestr): """ Add spaces around | in tables such that substitutions $...$ and `...` get right. """ pattern = r'^\s*\|.+\| *$' # table lines table_lines = re.findall(pattern, filestr, re.MULTILINE) horizontal_rule = r'^\s*\|[-lrc]+\|\s*$' inserted_space_ar...
c45dd26dd329e587e92e6df494ab04e8fddaf3c9
368,311
def str_to_bool(text): """ Parses a boolean value from the given text """ return text and text.lower() in ["true", "y", "yes", "1"]
af7a303de0a923f3a171898204c2b2a656d094f2
280,767
def _as_inline_code(text): """Apply inline code markdown to text Wrap text in backticks, escaping any embedded backticks first. E.g: >>> print(_as_inline_code("foo [`']* bar")) `foo [\\`']* bar` """ escaped = text.replace("`", r"\`") return f"`{escaped}`"
52b01b0e6eeb30ea7845c19006375d6c04748770
100,710
def top_level_files(project): """ Given a project, return only the top-level files - useful for generating table-of-contents, etc """ return project.files.filter(parent__isnull=True)
d9a9d45a59d4dcad91c0c1b354ea5784e3ad27aa
335,290
def VerboseCompleter(unused_self, event_object): """Completer function that suggests simple verbose settings.""" if '-v' in event_object.line: return [] else: return ['-v']
e536e221f8f3465f72071d969b11b6623359cf58
7,342
from typing import Callable import math def _geometric_binary_search( func: Callable[[float], float], target: float, iterations: int = 24, reverse: bool = False ) -> float: """Perform a binary search using geometric centers. Do a binary search to find the value ``n`` that make...
fa61dd9f1129474d43915f47344005a7eda0aa96
33,147
def ticket_matuation_to_dict(mutation: str, meta_data: dict): """ Used in run_mutations to create a dict from. In order to Takes one mutation line of an IPFS batch Returns structured dictionary. -> INDEX of dataframe / database 'statehash_tx': -> hash / receipt of state or mutation(n) ...
7df04b269c5b18c93cfb2281f099afb44ccdfaf0
163,707
def make_title(title): """Create a underlined title with the correct number of =.""" return "\n".join([title, len(title)*"="])
9e2b9cc2816563d1ca1ede04db479c806d76ae52
509,056
import ntpath def path_leaf(path): """ Extract the file name from a path. If the file ends with a slash, the basename will be empty, so the function to deal with it Parameters ---------- path : str Path of the file Returns ------- output : str The name of the ...
58930f081c2366b9084bb279d1b8b267e5f93c96
705,086
import typing def build_issue_doc(org:str, repo:str, title:str, text:typing.List[str]): """Build a document string out of various github features. Args: org: The organization the issue belongs in repo: The repository. title: Issue title text: List of contents of the comments on the issue Returns: ...
56bebe316a7a8787c954eb5e74cc1b0e79f26714
104,074
def cipher(text, shift, encrypt=True): """ Function to encipher or decipher the string by using different shift number. Parameters ---------- text : string A string that you wish to encipher or decipher. shift : integer An integer that you wish to shift. encrypt : boolea...
be24472672cb8ac4f9e582ea367f639f9709fb93
616,022
def filter_by_total_count(feature_table_df, sum_axis=1): """ Remove samples that have total counts <= 5 (R complains if total count <= 5) Inputs - feature_table_df: feature table in pandas DataFrame - sum_axis: axis to sum over. Do axis=0 if sample as columns, taxa/ASV as rows (index) Do axis=1 if sample ...
d8d7f0ada2f5b09eb509060ddc0b1d69f215db8b
511,845
import time def retry(predicate_task, timeout_sec=30, every=0.05, msg='Timed out retrying'): """ Repeat task every `interval` until it returns a truthy value or times out. """ begin = time.monotonic() threshold = begin + timeout_sec while True: res = predicate_task() if res: ...
b31479765cadd35d69c5c69c55bd791a29c49c5d
507,979
def checksum(number): """Calculate the checksum. A valid number should have a checksum of 1.""" check = 0 for n in number: check = (2 * check + int(10 if n == 'X' else n)) % 11 return check
8ada40ca46bc62bbe8f96d69528f2cd88021ad6a
707,437
def row_describes_data(row): """ Returns True if this appears to be a row describing data, otherwise False. Meant to be used in conjunction with filter to prune out those rows that don't actually describe data, such as empty strings or decorations that delimit headers from actual data (i.e. '+----|...
fa30057cc4098c0d51ec528c1032ef62d7b6fa5a
457,512
def compute_resolution(time_grid): """ Compute the resolution given the time grid at which measurements are made. :param time_grid: The time grid on which the sample is taken. :return delta: the resolution """ count = len(time_grid) delta = 0 for i in range(len(time_grid) - 1): ...
d63ac2b2a5c33b8c0b2cf7490554392f35b1b4c4
543,481
def gcd(x: int, y: int) -> int: """ Euclidean GCD algorithm (Greatest Common Divisor) >>> gcd(0, 0) 0 >>> gcd(23, 42) 1 >>> gcd(15, 33) 3 >>> gcd(12345, 67890) 15 """ return x if y == 0 else gcd(y, x % y)
8e8f51f703085aabf2bd22bccc6b00f0ded4e9ca
673,381
def parse_arguments(parser): """Read user arguments""" parser.add_argument('--path_model', type=str, default='Model/weights.01.hdf5', help='Path to the model to evaluate') parser.add_argument('--path_data', type=str, default='data/data_test.pkl', ...
2a313a9db899231a4138512967b36b3f1f5027ee
250,819
def validate_padding(value): """Validates and format padding value Args: value: `str` padding value to validate. Returns: formatted value. Raises: ValueError: if is not valid. """ padding = value.upper() if padding not in ['SAME', 'VALID']: raise ValueError...
b80ff3728c9f63f0729391033c05d1ebfa0198d9
152,754
import re def solve_status_str(hdrlbl, fmtmap=None, fwdth0=4, fwdthdlt=6, fprec=2): """Construct header and format details for status display of an iterative solver. Parameters ---------- hdrlbl : tuple of strings Tuple of field header strings fmtmap : dict or None,...
89d322be134e11bc7d47f3efecbc888ffc7472f5
255,983
def join_all(domain, *parts): """ Join all url components. Example:: >>> join_all("https://www.apple.com", "iphone") https://www.apple.com/iphone :param domain: Domain parts, example: https://www.python.org :param parts: Other parts, example: "/doc", "/py27" :return: url ""...
e2c308c615802ae119ab409b1b73d94c0f29e793
121,139
def format_raw(results): """Mate a formatted string for logging/printing from results of analyze_raw_batch""" msg = "" msg += "AbsError: {:0.5E} +- {:0.5E}\n".format(*(results[0])) msg += "EhfError: {:0.5E} +- {:0.5E}\n".format(*(results[1])) msg += "IdemEror: {:0.5E} +- {:0.5E}\n".format(*(re...
67f7738968fa1f387ae85ea73fbb8020ccc2de2c
207,781
import time def gen_id() -> str: """generate a fresh reminder id""" # id is set according to the current unix time return f'cli-reminder-{time.time()}'
17a5f6928093ed93f0ff958aaecac41cce443569
360,195
def json_get(obj, member, typ, default=None): """Tries to get the passed member from the passed JSON object obj and makes sure it is instance of the passed typ. If the passed member is not found the default is returned instead. If the typ is not matched the exception ValueError is raised. ...
f56f45b4922253d44672ca5e0c2903ef81f78fc9
206,873
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ #return None if there is less or equal to one element in the given array if len(ints) <= 1: return None #initialize th...
5afe2bc788c9a571e31c53a547c12106b4c64861
256,524
import binascii def to_bin(x): """hex to bin""" return binascii.unhexlify(x)
54d448648cc8f3067d72568884332d1a537f67f7
481,321
def force_array(val): """Returns val if it is an array, otherwise a one element array containing val""" return val if isinstance(val, list) else [val]
f26535484658d5c4832ba03e6a65cbef8143505a
299,820
def some(seq, func): """ Description ---------- Return True if some value in the sequence satisfies the predicate function.\n Returns False otherwise. Parameters ---------- seq : (list or tuple or set or dict) - sequence to iterate\n func : callable - predicate function to apply eac...
1390864f74cb36015c924e4e137bdfe2002f579b
480,278
import string def isPunct (s): """Determine if a character is punctuation. Params: s (string) a single character (len(s) == 1) Returns: (bool) is this a punctuation character? """ if s in string.punctuation: return True else : return False
aecee86fe23b43333664e5ac4790d74d9c828a62
345,863
def strip_api(server_url): """ Strips "api/" from the end of ``server_url``, if present >>> strip_api('https://play.dhis2.org/demo/api/') 'https://play.dhis2.org/demo/' """ if server_url.rstrip('/').endswith('api'): i = len(server_url.rstrip('/')) - 3 return server_url[:i] ...
0dd7b93b70209d3b0b6e6b5294eb5e2fdcbc3c95
144,801
def calc_specifity(df): """df contains the confusion_matrix as pandas DataFrame """ fp = df.loc["yes", "no"] tn = df.loc["no", "no"] return tn / (tn + fp)
dcca603f0a761088e772233bc71720ce9e5f47e6
147,616
def is_attr_true( element, name ): """Read a name value from an element's attributes. The value read from the attribute list must be either 'true' or 'false'. If the value is 'false', zero will be returned. If the value is 'true', non-zero will be returned. An exception will be raised for any other value.""" ...
db9cd0f23c6283bbb5f9317acb584f62f54c8119
531,585
def coerce_enum(value, cls): """Attempt to coerce a given string or int value into an Enum instance.""" if isinstance(value, int): value = cls(value) elif isinstance(value, str): value = cls[value] return value
4eaf7f7a2624d940002c2946cb36d8f92d968ed9
81,727
def FindClientNode(mothership): """Search the mothership for the client node.""" nodes = mothership.Nodes() for n in nodes: if n.IsAppNode(): return n return None
e54ae3ce093d2b8547e505de3ee97b50cddcd3f5
508,933
import ast def str2dict(d_s): """Convert string to dictionary :d_s: Dictionary string :returns: Evaluated dictionary """ return ast.literal_eval(d_s)
959da3c3197b5f8338cc33a7d9998303c50dd424
30,260
def _julian_day(date): """ Calculate the Julian day from an input datetime. Parameters ---------- date A UTC datetime object. Note ---- Algorithm implemented following equations from Chapter 3 (Algorithm 14): Vallado, David 'Fundamentals of Astrodynamics and Applications', ...
b94c70e6c9bb9db8348c9f744c3b499e6e4e5be2
409,725
def scaleto255(value): """Scale the input value from 0-100 to 0-255.""" return max(0, min(255, ((value * 255.0) / 100.0)))
fdf0ba0717df4c85fc055c1b8bc2590a22c4bd09
688,538
def get_enum_of_value(enum, val): """ checks, if a value is in an enum, and if true, returns value :param enum: enum to search in :param val: key or value to search for :return: boolean if found, enum_of_val """ if val in enum._value2member_map_: return True, enum(val) elif val i...
aba96d12ad30d7fa377bf757e138c0a2c4dee148
430,746
import ast def _mcpyrate_attr(dotted_name, *, force_import=False): """Create an AST that, when compiled and run, looks up an attribute of `mcpyrate`. `dotted_name` is an `str`. Examples:: _mcpyrate_attr("dump") # -> mcpyrate.dump _mcpyrate_attr("quotes.lookup_value") # -> mcpyrate.quotes.l...
16ab9893075caccf5808a1ce7926bc266394a979
74,687
def inventory_report(products): """ Takes a list of Acme products and prints a summary Summary will incldue: * Number of unique product names * Average price * Average weight * Average flammability """ def most_common(lst): """ Returns most common it...
5a0668567ff28531e25d52238c9bd130293f5d7c
167,759
def first_line(s): """Returns the first line of a multi-line string""" return s.splitlines()[0]
4c56d40e5f310a77ea3b193b740e578b0597fc00
548,857
import six def str_to_intfloat(s): """Convert str to int or float. Args: s (:obj:`str`): String to convert to float if it has a period or int if not. Returns: :obj:`int` or :obj:`float` """ if isinstance(s, six.string_types): if "." in s and s.replace(".", ""...
969506d86dd6454906ab208bb531ca8d5e0f7a52
351,525
def round_to_base (value, base=1): """ This method expects an integer or float value, and will round it to any given integer base. For example: 1.5, 2 -> 2 3.5, 2 -> 4 4.5, 2 -> 4 11.5, 20 -> 20 23.5, 20 -> 20 34.5, 20 -> 40 The default base is '1'. """ r...
c34bfb7e73624ce7f8652aed146218f0b6a86489
611,509
def divide_chunks(a_list, n): """Divide a list into chunks of size n. :param a_list: an entry list. :param n: size of each chunk. :return: chunks in a list object. """ return [a_list[i:i + n] for i in range(0, len(a_list), n)]
a5ad354d4d7b2b974b4b3eace6b9c78edc1c4dfb
619,523
def has_table(table_name, db_engine): """ Checks if a table with table_name is in the database :param table_name: Name of the table that needs to be checked :param db_engine: Specifies the connection to the database :return: True if table with table_name is in the database, False otherwise """ ...
c42056e5a94cca5f088630beba6c3b89f8ff54d8
493,034
def dict_to_fun(dictionary): """ Wraps a function around a dictionary. Parameters ---------- dictionary: a dict Returns ------- f: a function f(a,b,c,...) == X if and only if dictionary[(a,b,c,...)] == X """ if callable(dictionary): return dictionary else: ...
6c4afe1d781f16a16820058330fe647ac91ad702
56,765
def merge_rows(list_1, list_2, key): """ Merges two lists of dicts based on key in dicts Args: list_1(list[dict(),]): A list of dictionaries list_2(list[dict(),]): A list of dictionaries key(string): key using which lists would be merged Returns: List of dictionaries update...
3cf813988a5b4bb0dc0cf933e56fe35e3e1f0c2f
271,925
import itertools def ndgrid_inds(sz): """ Return a sequnce of tuples of indices as if generated by nested comprehensions. Example: ndgrid_inds((ni,nj)) Returns the same sequence as [(i,j) for i in range(ni) for j in range(nj)] The iterates are always tuples so ndgrid_inds(...
c62cd2450ebb52bb4ed9ce359335dc367542bb33
90,904
import functools import warnings def deprecated(reason): """ This is a decorator which can be used to mark function as deprecated. It will result in a warning being emitted when the function is used. :param reason: a reason as a string :return: decorated function """ def deprecated_decora...
1b1644fbfad94561bce78c47e8fc2f294f99335f
581,977
def _fill_deque_by_initial_value( deque_obj, initial_value, buffer_size): """ Fill the deque object with the initial value. Parameters ---------- deque_obj : collections.deque The deque object to add to. initial_value : int or float Initial value to be referenced. bu...
fef8fb44412fe0b56999ffa1d9e73c1848e58ee8
615,416
def to_iso_format( date_time): """ Return a string representing the date and time in ISO 8601 format, YYYY-MM-DD HH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DD HH:MM:SS If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and mi...
41fcc983707874da2bac3407f5f3bfdb8e9807b8
690,287
from typing import List from pathlib import Path def get_filenames(mockname: str) -> List[str]: """ scans all headers in test/mocks/{mockname}, return corresponding file names Args: mockname: string, mock directory name Returns: List of file name for the headers in test/mock/{mocksna...
4c47b1a3364cac702bc2d3b86b2a027754dd19a5
383,791
import re def get_certificate_and_private_key(pem_file_path): # noqa: D205,D400 """Return a dictionary containing the certificate and private key extracted from the given pem file. """ lines = open(pem_file_path, 'rt').read() certificate = re.findall( re.compile("(-*BEGIN CERTIFICATE-*\n(...
d9967f8405928aff2c579af0614987d395dd8b55
458,297
def C2F(C): """Convert Celcius to Fahrenheit""" return 1.8 * C + 32
e09f7415a2c509d8cb2d07d4c0d8e667f94e3c7d
643,725
def expand_indent(line): """ Return the amount of indentation. Tabs are expanded to the next multiple of 8. >>> expand_indent(' ') 4 >>> expand_indent('\\t') 8 >>> expand_indent(' \\t') 8 >>> expand_indent(' \\t') 8 >>> expand_indent(' \\t') 16 ...
79addc10c91b58d1f83e373971ee62b691c56c15
578,903
def list_daily_cases(list_of_cumulative_cases): """ Given a list of cumulative cases, this function makes and returns a list of daily cases. """ daily_list = [0] for i in range(1, len(list_of_cumulative_cases)): N_daily_case = list_of_cumulative_cases[i] - list_of_cumulative_cases[i - 1...
287d01b2c7a2a8764289c1f5f2e65372fedc35b5
629,710
import collections def DictFilter(alist, bits): """Translates bits from EDID into a list of strings. Args: alist: A list of tuples, with the first being a number and second a string. bits: The bits from EDID that indicate whether each string is supported by this EDID or not. Returns: A dic...
d314fdb4c1fd34ae9974f63d64495b8cafefbef5
46,630
import math def KeplerSolve(M: float, e: float) -> float: """Solves Kepler's equation inverse problem for elliptical orbits. Args: M (float): mean anomaly e (float): eccentricity Returns: float: eccentric anomaly """ if not 0 < e < 1: raise ValueError("Eccentricit...
45dca9264039ce0db3da2a755ff1e933edc3250d
526,748
def factorial(number): """ This method calculates the factorial of the number """ result = 1 for index in range(1,number+1): result *= index return result
a182f4fe68e76182bf17e5f9d7701e9004593ecb
303,537
import json def open_locale_file(fname): """Opens a locale file""" with open(fname) as json_file: return json.load(json_file)
903414bddf5335d5a1d1b51e835d59cc5df0b06b
641,121
def no_date_x_days_before_date_to_check(date_to_check, datelist, min_gap): """ Returns true if datelist contains a date less than or equal to min_gap days before date_to_check. Checked. Ignores dates that are greater than or equal to date_to_check. """ for previous_date in datelist: if pre...
9abf0a2ffaa0ea9b9a098981f3eba521325cc7b2
532,176
def filter_on_cdr3_length(df, max_len): """ Only take sequences that have a CDR3 of at most `max_len` length. """ return df[df['amino_acid'].apply(len) <= max_len]
abe853dd0a5baeb3a178c41de9b15b04912e2033
35,494
def divup(x: int, y: int) -> int: """Divide x by y and round the result upwards.""" return (x + y - 1) // y
5fa0ede218aa30bb58eadaedf32da0fd853664f7
689,473
import json def convert_array_in_json(array): """ Converter Return an array in a json """ # Return array in json lists = array.tolist() return json.dumps(lists)
cc4272f5b026010f3ba1ea2eaf0f277efe85be7b
496,894
import sqlite3 def get_connection(DB_FILENAME): """ Opens the connection to the database file at DB_FILENAME. Args: DB_FILENAME (str): path to the database file Returns: CONNECTION (object): """ CONNECTION = sqlite3.connect(DB_FILENAME) return CONNECTION
900abca088500256ac93502975c065c8b08dc4da
313,338
import re def is_pep440_canonical_version(version): """ Determine if the string describes a valid PEP440 canonical version specifier. This implementation comes directly from PEP440 itself. :returns: True if the version string is valid; false otherwise. """ return re.match( ( ...
29518b9a3289d7c1552d675d297e263d9e5255e6
394,385
def image_size(size): """ Determine the image size of the images to be displayed in GUI The original width to height ratio will be preserved. Max width/height is set to be 300, and the other dimension will be adjusted accordingly. Args: size (list): Original image size Returns: ...
37a20efbfdcf1dca52a3b5b49fedc8b019db0fe6
222,268
def is_iterable(obj): """ Test if an object is iterable. :param obj: The object to test. :return: True if the object is iterable, False otherwise. """ # noinspection PyBroadException try: _ = iter(obj) return True except: return False
9427fe56b8a354f12c9b0773a4ba434578265bae
114,447
def file_lines(f): """Read lines from a file (f) into a list.""" try: f = open(f) except TypeError: # probably already a file. pass with f: lines = f.readlines() lines = [line.strip() for line in lines] return lines
f7077f0be665abb1d636c25ef58a68f05ffd0a16
328,526
def get_contents_lektor_file(filepath): """Returns contents of contents Lektor file as string""" with open(filepath, "r") as file: contents = file.readlines() return "".join(contents)
f265525cccbbc602bdef1a89ff0bca558edccb10
596,551
def find_index(x, value): """ 並不限定 x 的單調性與重複性,因為它僅僅是找這個元素的指標。 因此,可能有多個元素,也可能沒有元素。 :param x: [3,5,1,2,3,5,1,20,2,38] :param value: 5 :return: [1, 5] """ temp = [] # 給接下來多個元素位址的暫存空間 for i in range(len(x)): if x[i] == value: temp.append(i) return temp
2effc0767075b21c21daf0ddaa0eaddc02a4b8b7
504,554
def t_iso(M): """ Isolation disruption timescale (2-body evaporation)""" return 17. * (M / 2E5)
92c7978643e2c2c1f4b3f6b1a1f85f8912d35ced
529,604
def precision_at_k(vanilla_topk, fair_topk): """ calculate precision @ K :param vanilla_topk: top K nodes in vanilla mining result :param fair_topk: top K nodes in debiased mining result :return: precision @ K """ topk = set(fair_topk) groundtruth = set(vanilla_topk) return len(topk....
073abf75d0a66d492541d13c799b67c1b09662f8
10,478
def data_context_config_dict_with_datasources(data_context_config_with_datasources): """Wrapper fixture to transform `data_context_config_with_datasources` to a json dict""" return data_context_config_with_datasources.to_json_dict()
4c8166e5711d6d444b465758dc91e10e42ad45cb
337,000
def valid1(s, c, low, high): """ Returns True or False depending on whether the number of occurences of the character `c` in the string `s` is between the integers `low` and `high` inclusive """ return low <= s.count(c) <= high
744f2486ea8fe1340f82f9e35994368f307235ba
598,027
def update_pos(pos1,pos2): """ Get the coordinate of the bounding box containing two parts :param pos1: Coordinate of the first part. :param pos2: Coordinate of the second part. :return: Coordinate of the bounding box containing the two parts """ x1 = min(pos1[0],pos2[0]) y1 = min(pos1[1...
db671fb75640436852e96e86b3af96985e52e605
633,889
def get_terminal_subgraph(g): """ Return the subgraph induced by terminal nodes in g :param g: :return: """ terminals = {node for node, d in g.nodes(data=True) if 'nt' not in d} return g.subgraph(terminals).copy()
dfef760209436efdea0b219dd6d452f153b8d5a7
579,177
def _contains_sample(pairs_list, sample): """Returns pairs_list that contains the sample""" pairs_list_f = [x for x in pairs_list if sample in [x[0][0], x[1][0]]] return pairs_list_f
5731e15326596a824f1e35f31244a35dde371dc5
551,586
import itertools def knapsack_without_repetition(capacity, values, weights=None): """ Find the optimal set of items with values and weights, to fill a knapsack to maximal capacity. The knapsack has a capacity which limits our choice of items in such a way that the sum of the items' weights c...
b468386d8bd80c6c25f30dcec3f5feded3e38c7d
422,664
def f10(x): """ Desc: 定义激活函数 f Args: x —— 输入向量 Returns: (实现阶跃函数)大于 0 返回 1,否则返回 0 """ if x>0: return 1 else: return 0
16843ba1940b5542a0d052938c8314bd28da51a9
444,639
def getint(string): """Try to parse an int (port number) from a string.""" try: ret = int(string) except ValueError: ret = 0 return ret
93ad70e59aa3d264b3215892cf3178d9ab3d8065
97,112