content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def conference_title(): """Get conference title from environ variable""" return os.environ.get('CONFERENCE_TITLE', None)
adb13a2565f31af8d273690be10d5d39bcb709d4
9,844
def apply_bounds(grid, lVec): """ Assumes periodicity and restricts grid positions to a box in x- and y-direction. """ dx = lVec[1,0]-lVec[0,0] grid[0][grid[0] >= lVec[1,0]] -= dx grid[0][grid[0] < lVec[0,0]] += dx dy = lVec[2,1]-lVec[0,1] grid[1][grid[1] >= lVec[2,1]] -= dy gri...
34411b7cc1062ade4d45c922225a3364a6c84180
9,845
def _check(edges): """Check consistency""" res = True for src, dsts in edges.items(): for dst in dsts: if dst not in edges: print('Warning: edges[%d] contains %d, which is not in edges[]' % (src, dst)) res = False return res
e97a72e31fc99fdf35e3302ab7a6216d7cab924d
9,846
def matches_filter(graph, props): """ Returns True if a given graph matches all the given props. Returns False if not. """ for prop in props: if prop != 'all' and not prop in graph['properties']: return False return True
8d53f198b7ad1af759203909a05cd28916512708
9,847
from typing import List from typing import Any from typing import Union import re def human_sort_key(key: str) -> List[Any]: """ Function that can be used for natural sorting, where "PB2" comes before "PB10" and after "PA3". """ def _convert(text: str) -> Union[int, str]: return int(text) ...
31c163250f5b040b18f3f2374825191ce3f61ff4
9,848
def get_class(class_string): """ Returns class object specified by a string. Arguments: class_string -- The string representing a class. Raises: ValueError if module part of the class is not specified. """ module_name, _, class_name = class_string.rpartition('.') ...
a25573ac9cb6115e0b8ad1d28a286f86628d8235
9,849
import hashlib def flip_bloom_filter(string: str, bf_len: int, num_hash_funct: int): """ Hash string and return indices of bits that have been flipped correspondingly. :param string: string: to be hashed and to flip bloom filter :param bf_len: int: length of bloom filter :param num_hash_funct: in...
c245637b86cc16b68d069bf2359b1e5c7483a8fc
9,850
def largest_product(product_list): """Find the largest product from a given list.""" largest = 1 for products in product_list: if largest < max(products): largest = max(products) return largest
7f9f2b151afc7d0e35203a5dda665ef100279c65
9,852
import os import stat def is_executable(path): """Tests if the specified path corresponds to an executable file. This is, it is a file and also has the appropriate executable bit set. :param path: Path to the file to test. :return: True if the file exists and is executable, False otherwise. :rtyp...
0926b6118688892db7446dadafa19c300ff29212
9,853
def add_api_component(logger, name, event_dict): """ Adds the component to the entry if the entry is not from structlog. This only applies to the API since it is handled by external WSGI servers. """ event_dict["component"] = "API" return event_dict
d510d8eb563ffd3b819abd3ec970790ed9d30083
9,854
import random def shuffle_string(s: str) -> str: """ Mixes all the letters in the given string Parameters: s(str): the string to shuffle Returns: str: string with randomly reordered letters Examples: >>> shuffle_string('abc') 'cba' >>>...
9c68b276f539d6385e5393cb92fa971fbb6059d4
9,855
import os import errno import functools import signal def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): """ This decorator raise an TimeoutError exception if the function takes more than 'seconds' seconds to terminate From: https://stackoverflow.com/questions/2281850/ """ def d...
f46280146f0ee309f71100614bbc6d1afd38799d
9,857
def onnx2str(model_onnx, nrows=15): """ Displays the beginning of an ONNX graph. See :ref:`onnxsklearnconsortiumrst`. """ lines = str(model_onnx).split('\n') if len(lines) > nrows: lines = lines[:nrows] + ['...'] return "\n".join(lines)
0bca645ab2882cde59788517cc9c8c02d208de2e
9,858
def diff_lists(old, new): """Returns sorted lists of added and removed items.""" old = set(old or []) new = set(new or []) return sorted(new - old), sorted(old - new)
1359a2c89c20993445491ff2a986a392eaee2aed
9,862
def get_gw_bytes_encoding(): """ get gateway encoding method :return: string """ return "utf-8"
44e23564f5feb086334d7d9c00a8f4283ae5273d
9,864
import os import errno def get_cloudinit_instance(): """Return the current CloudInit instance ID.""" try: target = os.readlink('/var/lib/cloud/instance') except OSError as e: if e.errno != errno.ENOENT: raise return path, instance = os.path.split(target) return ...
3eff85599300c0d3a4ae18bc10f7501c3c9c2d25
9,866
def open_file(filename: str): """ >>> open_file("hello.txt") No such file or directory: hello.txt >>> import os >>> if os.path.exists("../LICENSE"): ... f = open_file("../LICENSE") ... _ = f is not None ... _ = f.readline().strip() == "Apache License" ... _ = f.readl...
fdc9f5746f61573014c4cb7b3631c2ce0ad10d4e
9,867
import torch def add_gaussian(p, g_std): """add gaussian noise :param p: input tensor :param g_std: standard deviation of Gaussian :returns: tensor with added noise :rtype: tensor """ if g_std > 0: size = p.size() p += torch.normal(0, g_std, size=size) return p
025bfffca50463589619051f58b5d8e95341c0bd
9,869
def chain(_input, funcs): """Execute recursive function chain on input and return it. Side Effects: Mutates input, funcs. Args: _input: Input of any data type to be passed into functions. funcs: Ordered list of funcs to be applied to input. Returns: Recusive call if any functi...
3f2d1490044f0eb35656bd7601d1569fb6f8a553
9,870
def get_resolution_HRF(): """Returns RIM_ONE_v2 resolution after post-processing.""" return (3504, 3504)
4d50b1a08a469f5790a7e59207fcde3956c4fa2d
9,871
def overlaps_bool(pred_roi, bbox): """ :param rois: regions of interest in format (y1, x1, y2, x2) :return: Boolean Example: [[ 99,325,135,363], [ 54,229,88,264], [ 53,230,94,266], [ 93,321,132,361]] -> [1, 2, 2, 1] """ l_1_y1 = pred_roi[0] l_1_x1 = pred_roi[1] r_1_y2 = pre...
c186026967b7016aba7ce21cd9d710b51af74d91
9,873
import re def underline_to_hump(underline_str): """ Transfer underline to hump Args: underline_str(string): underline code string """ sub = re.sub(r'(_\w)', lambda x: x.group(1)[1].upper(), underline_str) return sub
dbc59ced8306088f08b6997c305c468370b4631d
9,874
def successor(node): """ 4.6 Successor: Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent. """ def get_min(node): if node.left != None: return get_min(node.left) ...
448342a8adcdf73ba73a5e6b4319cd299d1bc9a8
9,875
def build_zooma_query(trait_name: str, filters: dict, zooma_host: str) -> str: """ Given a trait name, filters and hostname, create a url with which to query Zooma. Return this url. :param trait_name: A string containing a trait name from a ClinVar record. :param filters: A dictionary containing fi...
0fb22b1f44319c2fa8e87d8e720de248dd1a7eba
9,876
import os import pickle def pickle_load(cwd,file_Name): """ Load pickled data from current working directory. INPUT: cwd - Current working directory. file_name - Name of pickled data to be loaded. OUTPUT: filePickle - Loaded pickle data. """ print('\nLoading data...\n') os.ch...
63ded4f9511e066d23aa8c99603c3a54f085b5e4
9,877
from typing import Any def ret(d: dict, key: str) -> Any: """ Unwrap nested dictionaries in a recursive way. Parameters ---------- d: dict Python dictionary key: str or Any Key or chain of keys. See example below to access nested levels. Returns ---------- out...
86d07ba6dbe2610ceabb0bcee3099b5734c770ae
9,879
def to_minutes(hour, minute): """ converts hours to minutes and adds extra minutes in the time... returns the sum """ return (hour * 60) + minute
05cc1cada49c7a2c84b3fa32cd9fb7bf805be751
9,882
def is_identity(u): """Checks if the unit is equivalent to 1""" return u.unitSI == 1 and u.unitDimension == (0,0,0,0,0,0,0)
afc9029eeb44739a38869f06f84ba36b2a19da6f
9,883
def m_seq_inx_to_int(seq, args=0): """ 将列表中单个列表中元素转成int,返回新的列表 :param seq: 列表形成的列表 :param args: 列表的次序 :return: 转换后的列表 example: :seq [['30', 0], ['5', 1]] :args 0 :return [[30, 0], [5, 1]] """ for i in seq: ...
f6ba3c4060edffd704c53752df88b4dcfbdbef68
9,884
import os def get_dzi_path(filepath): """ Get a path for the DZI relative to a rendered output file. """ return "%s/dzi/%s.dzi" % (os.path.dirname(filepath), os.path.splitext(os.path.basename(filepath))[0])
f78a88e37130f444e1398c603bfdeda3d30845bd
9,885
import pathlib def get_tree(tree_type, cfg, section, option): """Load a tree from file or parse a string. If the provided value is the name of an existing file, read the contents and treat it as a Newick tree specification. Otherwise, assume the provided value is a Newick tree specification. Trees c...
077ff497e32a9695ae146c381a29361187511bc6
9,886
def common(first_list, second_list): """Receives two lists, returns True if they have any common objects and false otherwise. Note that this implementation should theoretically work with any container-like object for which the in operator doesn't have a different meaning.""" # iterate over the elements ...
da48a3a559bc26a79bc5aa06ca6efa15053e1cd4
9,887
import logging def receive(conn): """Receive a message conn has to be the socket which receive the message A message has to end with the bytestring b'\xDE\xAD\xE1\x1D' """ ip, port = conn.getpeername() logging.info('Receiving a message from '+ip+':'+str(port)) data = b'' while...
0b6f4e9c6fd3a38a33f625fe6b736020a044ca61
9,889
def calc_linear_crossing(m, left_v, right_v): """ Computes the intersection between two line segments, defined by two common x points, and the values of both segments at both x points Parameters ---------- m : list or np.array, length 2 The two common x coordinates. m[0] < m[1] is assum...
3f5eeab9fa906b6858e249f97c7e175e427cb2d7
9,890
def validate_input(input_string): """ :param str input_string: A string input to the program for validation that it will work wiht the diamond_challenge program. :return: *True* if the string can be used to create a diamond. *False* if cannot be used. """ if not isinstance(input_string, st...
cf18344ddd336d878837bc5654a3ea3b98eec729
9,891
from sys import version_info def _open_csv_file(filename): """Opens a file for writing to CSV, choosing the correct method for the current version of Python """ if version_info.major < 3: out_file = open(filename, 'wb') else: out_file = open(filename, 'w', newline='') return ou...
527b7d216d6ecd2d30ac716e993edee6a95766bc
9,892
def octave_to_frequency(octave: float) -> float: """Converts an octave to its corresponding frequency value (in Hz). By convention, the 0th octave is 125Hz. Parameters ---------- octave : float The octave to put on a frequency scale. Returns ------- float The frequency value c...
d50fe69e0dd267b5418834ca2999867213b5f306
9,893
def _complete_choices(msg, choice_range, prompt, all=False, back=True): """Return the complete message and choice list.""" choice_list = [str(i) for i in choice_range] if all: choice_list += ['a'] msg += '\n- a - All of the above.' if back: choice_list += ['b'] msg...
0e5052643cd027d760b08b22bc5f14608845fcb2
9,897
def is_bitcode_file(path): """ Returns True if path contains a LLVM bitcode file, False if not. """ with open(path, 'rb') as f: return f.read(4) == b'BC\xc0\xde'
acfd17eee949f42994b2bc76499ee58c710eb388
9,898
from typing import List def get_file_pattern() -> List[str]: """ Returns a list with all possible file patterns """ return ["*.pb", "*.data", "*.index"]
8c4f471dea29dfe5c79cf3ea353cb1a335a5cf45
9,899
import copy import itertools def _make_inner_dense(sparse_nested_table, outer_inner_cards, default_value): """ Convert n sparse nested table dictionary's implicit default values in the innetables to real entries so that all possible assignments are present in the inner sub tables. :param sparse_neste...
372861e9a38016e0426ff29b62eb47fd82ff9631
9,900
import torch def extract_tensor_batch(t, batch_size): """ batch extraction from tensor """ # extracs batch from first dimension (only works for 2D tensors) idx = torch.randperm(t.nelement()) return t.view(-1)[idx][:batch_size].view(batch_size,1)
291ee82385dad8ad6a60ced0759900a8fb71e0c5
9,901
def charPresent(s, chars): """charpresent(s, chars) - returns 1 if ANY of the characters present in the string chars is found in the string s. If none are found, 0 is returned.""" for c in chars: if str.find(s, c) != -1: return True return False
cac51d18788ae4556609f5f289eb8dbb0741fc79
9,902
def err_ratio(cases): """calculate error ratio Args: cases: ([case,]) all cases in all parts Return: float """ return 1 - len(list(filter(lambda x: x['valid'], cases))) / len(cases)
421905b46c594d99b091e4d6ad094092c4483faa
9,905
def get_param_cols(columns): """ Get the columns that were provided in the file and return that list so we don't try to query non-existent cols Args: columns: The columns in the header of the provided file Returns: A dict containing all the FPDS query columns that the provi...
8a0030c745d2de5bd2baf93af79efce4dcb4c696
9,906
import re def depluralize(word): """Return the depluralized version of the word, along with a status flag. Parameters ---------- word : str The word which is to be depluralized. Returns ------- str The original word, if it is detected to be non-plural, or the dep...
9d879a320da566bceb6e5db6cbfe2e7f23f9bb73
9,907
import ipaddress def _get_network_address(ip, mask=24): """ Return address of the IPv4 network for single IPv4 address with given mask. """ ip = ipaddress.ip_address(ip) return ipaddress.ip_network( '{}/{}'.format( ipaddress.ip_address(int(ip) & (2**32 - 1) << (32 - mask)), ...
bb706209cc7295ab1d0b4bf88e11d3efba10d526
9,909
def get_admin_ids(bot, chat_id): """ Returns a list of admin IDs for a given chat. Results are cached for 1 hour. Private chats and groups with all_members_are_administrator flag are handled as empty admin list """ chat = bot.getChat(chat_id) if chat.type == "private" or chat.all_members_are_adm...
6bd89e1d6b7333d97cbc60fd2617a86d1b69fb2f
9,910
import os def dirname(path): """ Returns the directory in which a shapefile exists. """ # GitPython can't handle paths starting with "./". if path.startswith('./'): path = path[2:] if os.path.isdir(path): return path else: return os.path.dirname(path)
c4c8dcfb511f27984386ee97f8d1ea414561603a
9,911
import math def num_tiles_not_in_position(state): """ Calculates and returns the number of tiles which are not in their final positions. """ n = len(state) total = 0 for row in state: for tile in row: try: y = int(math.floor(float(tile)/n - (float(1)/n))...
102d2eb616f8b459fc31e68788f355440bac97e0
9,912
import random def make_babies(parents, size=10000): """Create a new population by randomly selecting two parents and randomly selecting the character from a parent for each position.""" children = [] for i in range(size): p1, p2 = random.sample(parents, 2) children.append(''.join([p1[i...
74ac5106259eb504ce70a00fccf610137238bbbe
9,913
def plus(cell1, cell2, back_val): """Moves forward between two cells. Requires a third cell, though truly only requires the value of that the form takes at the cell. """ (x1, y1), val1 = cell1 (x2, y2), val2 = cell2 # back_val, val1 + val2, val form an arithmetic progression val = 2 * (...
ecf20c2a46f6ae834e0625f5a54fd30f46af2a7a
9,914
def get_bool_symbols(a_boolean): """ :param a_boolean: Any boolean representation :return: Symbols corresponding the to the True or False value of some boolean representation Motivation: this is reused on multiple occasions """ if a_boolean: return "✅" return "❌"
b95a4fc5ca29e07a89c63c97ba88d256a24a7431
9,915
def returner(x): """ Create a function that takes any arguments and always returns x. """ def func(*args, **kwargs): return x return func
43476f89cae80cd2b61d64771a3dfac5e4297b5a
9,916
from typing import Counter def get_unique_characters(rows, min_count=2): """Given a bunch of text rows, get all unique chars that occur in it.""" def char_iterator(): for row in rows.values: for char in row: yield str(char).lower() return [ c for c, count ...
ecba44e44222bb63c2f794e7ee9e87eb3754f695
9,917
def build_data_type_name(sources, properties, statistic, subtype=None): """ Parameters ---------- sources: str or list[str] type(s) of astrophysical sources to which this applies properties: str or list[str] feature(s)/characterisic(s) of those sources/fields to which the st...
103a7440dfe3b8f6ccce0fdf6cdca86202e27ac5
9,918
def machineCostPerH(fixed, operating): """ fixed = fixed costs operating = operating costs """ return {'Machine cost per H': [fixed + operating]}
d6fd47e14402504dc277375d87a786b7c54cea98
9,919
import re def expand_symbols(text): """ expand symbols in text """ text = re.sub("\;", ",", text) text = re.sub("\:", ",", text) text = re.sub("\-", " ", text) text = re.sub("\&", "and", text) return text
9f212718745ef0f2964490b692cab491ad74430c
9,920
def priter(self, **kwargs): """Prints solution summary data. APDL Command: PRITER Notes ----- Prints solution summary data (such as time step size, number of equilibrium iterations, convergence values, etc.) from a static or full transient analysis. All other analyses print zeros for the d...
aae2dd4c8103d0244887fc7010ca95814f1b853f
9,921
def is_valid_id(id_: str) -> bool: """If it is not nullptr. Parameters ---------- id_ : str Notes ----- Not actually does anything else than id is not 0x00000 Returns ------- bool """ return not id_.endswith("0x0000000000000000")
6520900966475771e2a0d1fcdfd2b60d3ea2ee9b
9,922
def async_is_zwave_js_migrated(hass): """Return True if migration to Z-Wave JS is done.""" zwave_js_config_entries = hass.config_entries.async_entries("zwave_js") if not zwave_js_config_entries: return False migrated = any( config_entry.data.get("migrated") for config_entry in zwave_js_...
ca6a5397ec8329557e8be523f4fa416175347c84
9,923
def get_limit_from_tag(tag_parts): """Get the key and value from a notebook limit tag. Args: tag_parts: annotation or label notebook tag Returns (tuple): key (limit name), values """ return tag_parts.pop(0), tag_parts.pop(0)
e7d4858b166b2a62ec497952853d95b81a608e85
9,924
def Percent(numerator, denominator): """Convert two integers into a display friendly percentage string. Percent(5, 10) -> ' 50%' Percent(5, 5) -> '100%' Percent(1, 100) -> ' 1%' Percent(1, 1000) -> ' 0%' Args: numerator: Integer. denominator: Integer. Returns: string formatted result. "...
a0081a387a737b44268fd71ab9746c7edd72221f
9,925
def link_filtered_DLC_predictions(nwb_file,video_dir): # add the DLC files (need code/write code) """ Function to link filtered DLC predictions to a NWB file""" return nwb_file
d51980fe2bc7099e13d784eb9fc6e324c547c38d
9,930
import json def read_data(f_name): """ Given an input file name f_name, reads the JSON data inside returns as Python data object. """ f = open(f_name, 'r') json_data = json.loads(f.read()) f.close() return json_data
629ab7e9a8bd7d5b311022af4c9900d5942e7a23
9,931
def reverse_string_recursive(s): """ Returns the reverse of the input string Time complexity: O(n^2) = O(n) slice * O(n) recursive call stack Space complexity: O(n) """ if len(s) < 2: return s # String slicing is O(n) operation return reverse_string_recursive(s[1:]) + s[0]
a8d22e88b1506c56693aa1a8cd346695e2b160b2
9,932
def checkIsHours(value): """ checkIsHours tries to distinguish if the value describes hours or degrees :param value: string :return: """ if not isinstance(value, str): return False if '*' in value: return False elif '+' in value: return False elif '-' in va...
4d28996de6087b802757508313e15543b9dd9272
9,933
def gnome_sort(a): """ Sorts the list 'a' using gnome sort >>> from pydsa import gnome_sort >>> a = [5, 6, 1, 9, 3] >>> gnome_sort(a) [1, 3, 5, 6, 9] """ i = 0 while i < len(a): if i != 0 and a[i] < a[i-1]: a[i], a[i-1] = a[i-1], a[i] i -= 1 el...
05aca54513c6d441836aa7a60147b06b85b4e34d
9,934
def fmod(x, y): """Return fmod(x, y), as defined by the platform C library. :type x: numbers.Real :type y: numbers.Real :rtype: float """ return 0.0
cd580ca8efe1e9bd3e5511613ccdcc59ebe55119
9,937
def get_closest_multiple_of_16(num): """ Compute the nearest multiple of 16. Needed because pulse enabled devices require durations which are multiples of 16 samples. """ return int(num) - (int(num) % 16)
333cbed27abbcb576541d5fb0b44bf85b78c9e78
9,939
from typing import List from typing import Tuple def max_subarray(arr: List[int]) -> Tuple[int, int]: """ :time: O(n) :space: O(n) """ max_val = max(x for x in arr) if max_val < 0: return max_val, max_val max_subsequence_sum = sum(x for x in arr if x > 0) max_subarray_sum = 0 ...
056b4c83191f57a36f0fdeb7474b2de2f6e8bb28
9,940
def split_container(path): """Split path container & path >>> split_container('/bigdata/path/to/file') ['bigdata', 'path/to/file'] """ path = str(path) # Might be pathlib.Path if not path: raise ValueError('empty path') if path == '/': return '', '' if path[0] == '/': ...
53b0d1164ecc245146e811a97017f66bb1f032a7
9,941
def parse_sph_header( fh ): """Read the file-format header for an sph file The SPH header-file is exactly 1024 bytes at the head of the file, there is a simple textual format which AFAIK is always ASCII, but we allow here for latin1 encoding. The format has a type declaration for each field a...
d0055b3dc276facd9acb361dfde167d8c123b662
9,942
import numpy def acosine(a,b,weights): """Distance between two points based on the pearson correlation coefficient. By treating each data point as half of a list of ordered pairs it is possible to caluclate the pearson correlation coefficent for the list. Since the pearson correlation coefficen...
19ffa98cb12c1d4e8026e0763c76062d2c4b19c8
9,943
def column(matrix, i): """ Returning all the values in a specific columns Parameters: X: the input matrix i: the column Return value: an array with desired column """ return [row[i] for row in matrix]
2a88c40d11e7fe7f28970acd4d995a8428126a4d
9,944
def cubicinout(x): """Return the value at x of the 'cubic in out' easing function between 0 and 1.""" if x < 0.5: return 4 * x**3 else: return 1/2 * ((2*x - 2)**3 + 2)
505f0c5b8dc7b9499450474dbb1991eec068b553
9,945
def remove_duplicates(string: str) -> str: """ Remove duplicate characters in a string :param string: :return: """ without_duplicates = "" for letter in string: if letter not in without_duplicates: without_duplicates += letter return without_duplicates
2caafc6b38cf2b920324bd976acb3caf90660c25
9,946
import argparse def parse_args(): """ Parses command line args Returns: The argparse namespace """ parser = argparse.ArgumentParser(description="Copies packer artifacts from the packer manifest output to terraform input variables.") parser.add_argument('--enterprise', dest='enterprise...
2b0dddb18edc3dfdf527ff31168f428dfb30dd03
9,948
import glob import os def csvLayerNames(layer_path): """ Get names of layers stored as csv files. """ layer_names = glob.glob(os.path.join(layer_path, "*.csv")) xx = [os.path.basename(i) for i in layer_names] return xx
682bf78f5d0a93f55277acf022d98d8c414a1161
9,949
import sys def module_property(func): """Decorator to turn module functions into proerties. Function names must be prefixed with an underscore""" module = sys.modules[func.__module__] def base_getattr(name): raise AttributeError( f"module '{module.__name__}' has no attribute '{nam...
919e83e8c4027b6d541d1348bba2c1c4c3436952
9,950
import json def dumps(dict_): """ Converts dictionaries to indented JSON for readability. Args: dict_ (dict): The dictionary to be JSON encoded. Returns: str: JSON encoded dictionary. """ string = json.dumps(dict_, indent=4, sort_keys=True) return string
c2f3eabe0b473def6233476018d8c3a3918beb70
9,952
def jpeg_linqual(quality): """ See int jpeg_quality_scaling(int quality) in libjpeg-turbo source (file ijg/jcparam.c). Convert quality rating to percentage scaling factor used to scale the quantization table. """ quality = max(quality, 1) quality = min(quality, 100) if quality < 50: ...
a35157416fd4d95dddfe6cf8408a99e6247703ba
9,953
def pytest_funcarg__content(request): """ The content for the test document as string. By default, the content is taken from the argument of the ``with_content`` marker. If no such marker exists, the content is build from the id returned by the ``issue_id`` funcargby prepending a dash before the i...
e357042566ce22557ba5c8f83b14f56cb8025dca
9,954
def split_s3_path(s3_path): """ Splits the complete s3 path to a bucket name and a key name, this is useful in cases where and api requires two seperate entries (bucket and key) Arguments: s3_path {string} -- An S3 uri path Returns: bucket {string} - The bucket name key {...
81efc5fc125c62d4dcde577b3424029acb4a536f
9,955
import zipfile def createZip(zip_name, src): """ parameter:- zip file name , folder path This will create zip file """ zipf = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) for file in src: zipf.write(file) zipf.close() print("--------zip file created --------") ...
325f8a6b63f4a8c2d46b8d07bfc3b3e938d50836
9,957
def dash(*txts): """Join non-empty txts by a dash.""" return " -- ".join([t for t in txts if t != ""])
53566f49991f8d7930a63f7d2d22c125d9d25073
9,958
import asyncio import functools def call_later(delay, fn, *args, **kwargs) -> asyncio.Handle: """ Call a function after a delay (in seconds). """ loop = asyncio.get_event_loop() callback = functools.partial(fn, *args, **kwargs) handle = loop.call_later(delay, callback) return handle
86d157ed0f5f8dc7f806af9871a71057dc36222c
9,959
from typing import Tuple def build_blacklist_status(blacklist_status: str) -> Tuple[str, str, str]: """Build the blacklist_status @type blacklist_status: str @param blacklist_status: The blacklist status from command line @returns Tuple[str, str, str]: The builded blacklist status """ blackli...
10f0c3a77169a0e9b9136d454e6d17efdd4760f6
9,960
import spwd import grp def isuser(username, domain, password=None): """Check if user exists and if he is a member of the group 'domain'.""" try: spwd.getspnam(username) return username in grp.getgrnam(domain)[3] except KeyError: return False except PermissionError: prin...
70e920c0fe3212c3e2588bc429c745fe134653e7
9,961
def _check_substituted_domains(patchset, search_regex): """Returns True if the patchset contains substituted domains; False otherwise""" for patchedfile in patchset: for hunk in patchedfile: if not search_regex.search(str(hunk)) is None: return True return False
e3fdeaa1ede7f041bb6080d4647c8d969b41f73d
9,962
import re def prepareReposToJson(json_repos): """ Convert information about repo to proper format :param json_repos: :return: dictionary """ columns = ["created_on", "description", "fork_policy", "full_name", "has_issues", "has_wiki", "is_private", "language", "links", "mainbran...
40eaa03779b0161f78250a174e19b77041d511e8
9,963
def delete_segment(seq, start, end): """Return the sequence with deleted segment from ``start`` to ``end``.""" return seq[:start] + seq[end:]
1eba39d373ac2ab28ea1ea414f708a508bdf48d2
9,966
import math def triangleSum(n): """ Finding the sum of 1+2+...+n :param n: the last interger to be added :return: the sum """ n = math.floor(n) if n > 1 : return n+triangleSum(n-1) return 1
4bffb8d8d758730b161a572fad447e5420c30490
9,967
import re def detect_arxiv(txt): """ Extract an arXiv ID from text data """ regex = r'arXiv:[0-9]{4,4}\.[0-9]{5,5}(v[0-9]+)?' m = re.search(regex, txt) if m is not None: return m.group(0) else: return None
a855497b6eb1f027085a301096735e860e76fbe7
9,968
def cut_sentences(text): """ 将文本切成句子 :param text: 待切分文本 :return: 句子列表 """ text = text.translate(str.maketrans('!?!?\r\n', '。。。。 ')) return [sen for sen in text.split('。') if len(sen.strip()) > 1]
06e8b503c2c6e3ea73901bb19f2b4fba2f443e19
9,971
def to_literal(typ, always_tuple=False): """Convert a typestruct item to a simplified form for ease of use.""" def expand(params): return (to_literal(x) for x in params) def union(params): ret = tuple(sorted(expand(params), key=str)) if len(ret) == 1 and not always_tuple: ret, = ret # pylint:...
a628676073a09042689f64ab1aa4d12a2a87c463
9,973
def powmod(a, b, m): """ Returns the power a**b % m """ # a^(2b) = (a^b)^2 # a^(2b+1) = a * (a^b)^2 if b==0: return 1 return ((a if b%2==1 else 1) * powmod(a, b//2, m)**2) % m
33b4cadc1d23423f32e147718e3f08b04bd2fd17
9,974
import numpy as np def str_to_array(s): """ Simplistic converter of strings from repr to float NumPy arrays. If the repr representation has ellipsis in it, then this will fail. Parameters ---------- s : str The repr version of a NumPy array. Examples -------- >>> s = "ar...
858491f8c7279630951b1244a3ea630d932eb7c6
9,975
import functools def generate_decorator(exception): """Ddecorator generator""" def expected_error(test): @functools.wraps(test) def inner(*args, **kwargs): try: test(*args, **kwargs) except exception: assert True else: ...
7089aabfb4ad9ce51b08ec43ada1c27d6fe529f0
9,976
def _update_dict(d, **kwargs): """little helper to modify and return a dict in one line""" d.update(kwargs) return d
0a28c5f82d439ceb65aa3afc39d30a29b589004e
9,977