content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def check_paragraph(index: int, line: str, lines: list) -> bool: """Return True if line specified is a paragraph """ if index == 0: return bool(line != "") elif line != "" and lines[index - 1] == "": return True return False
b5737a905b32b07c0a53263255d3c581a8593dfa
24,221
import logging def mask(node2sequence, edge2overlap, masking: str = "none"): """If any of the soft mask or hard mask are activated, mask :param dict exon_dict: Dict of the shape exon_id: sequence. :param dict overlap_dict: Dict of the shape (exon1, exon2): overlap between them. :param str masking: Ty...
5f10491773b4b60a844813c06a6ac9e810162daa
24,224
def extract_el_from_group(group, el): """Extract an element group from a group. :param group: list :param el: element to be extracted :return: group without the extracted element, the extracted element """ extracted_group = [x for x in group if x != el] return [extracted_group] + [[el]]
ed6598fd0d7dcb01b35a5c2d58c78d8c2a2397f5
24,226
def example_function_with_shape(a, b): """ Example function for unit checks """ result = a * b return result
33403e6f67d4d6b18c92b56996e5e6ed21f6b3ad
24,227
from typing import Mapping from typing import Any def fields( builder: DataclassBuilder, *, required: bool = True, optional: bool = True ) -> "Mapping[str, Field[Any]]": """Get a dictionary of the given :class:`DataclassBuilder`'s fields. .. note:: This is not a method of :class:`DataclassBuilde...
47b3bd86076ac14f9cca2f24fedf665370c5668f
24,228
from typing import Dict from typing import List def gemm(node: NodeWrapper, params: Dict[str, np.ndarray], xmap: Dict[str, XLayer]) -> List[XLayer]: """ ONNX Gemm to XLayer Dense (+ Scale) (+ BiasAdd) conversion function Compute Y = alpha * A' * B' + beta * C See https://github.com/...
dbc257c98fa4e4a9fdb14f27e97132d77978f0c2
24,229
from datetime import datetime def check_response(game_id, response): """Check for correct response""" if response["result"]["@c"] == "ultshared.rpc.UltSwitchServerException": game = Game.query.filter(Game.game_id == game_id).first() if "newHostName" in response["result"]: print("n...
a5de41170d13022393c15d30816cc3c51f813f36
24,230
def get_signal_handler(): """Get the singleton signal handler""" if not len(_signal_handler_): construct_signal_handler() return _signal_handler_[-1]
bd74ddb1df0c316d4e62e21259e80c0213177aeb
24,232
def post_rule(team_id): """Add a new rule. .. :quickref: POST; Add a new rule. **Example request**: .. sourcecode:: http POST /v1/teams/66859c4a-3e0a-4968-a5a4-4c3b8662acb7/rules HTTP/1.1 Host: example.com Accept: application/json { "name": "Servers", "descri...
687873cb4398877afb6ed444263f4990039a9f6d
24,233
def intents(interface): """ Method to get an object that implements interface by just returning intents for each method call. :param interface: The interface for which to create a provider. :returns: A class with method names equal to the method names of the interface. Each method on this ...
4e514424721ba2fc2cf4261cc856f6984d3781de
24,234
def model(X, Y, learning_rate=0.3, num_iterations=30000, print_cost=True, is_plot=True, lambd=0, keep_prob=1): """ 实现一个三层的神经网络:LINEAR ->RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID 参数: X - 输入的数据,维度为(2, 要训练/测试的数量) Y - 标签,【0(蓝色) | 1(红色)】,维度为(1,对应的是输入的数据的标签) learning_rate - 学习速率 ...
39130fffd282a8f23f29a8967fe0e15386817ed1
24,235
from collections import OrderedDict from urllib.request import urlretrieve from urllib import urlretrieve import scipy.ndimage as nd def load_phoenix_stars(logg_list=PHOENIX_LOGG, teff_list=PHOENIX_TEFF, zmet_list=PHOENIX_ZMET, add_carbon_star=True, file='bt-settl_t400-7000_g4.5.fits'): """ Load Phoenix stell...
39807e591acf1a7338a7e36f5cd50ffffa1ff66b
24,236
def write_ini(locStr_ini_file_path, locStr_ini): """ .. _write_ini : Write the given string into the given INI file path. Parameters ---------- locStr_ini_file_path : str The file full path of the INI file. If the extension ".ini" is not included, it would be adde...
1376f50fa9d91c797cbaccc4066c379e0c085aea
24,237
def create_form(data, form_idx=0): """ Creates PDB structure forms. form_idx = 0 is apo; 1 - holo1; and 2 - holo2 Note: Only works for homodimers. """ # Make a deep copy of BioPandas object to make changes data_out = deepcopy(data) # If form_idx == 2 that's holo2 already if ...
45058e1770519a51677c47a7b78d1b1c2ca2c554
24,238
from typing import Dict import logging def get_verbosity(parsed_arguments: Dict) -> int: """ Gets the verbosity level from parsed arguments. Assumes parameter is being parsed similarly to: ``` parser.add_argument(f"-{verbosity_parser_configuration[VERBOSE_PARAMETER_KEY]}", action="count", def...
b0bf38c8883335f76000a29dcdefe46eccc5040a
24,239
def update_versions_in_library_versions_kt(group_id, artifact_id, old_version): """Updates the versions in the LibrarVersions.kt file. This will take the old_version and increment it to find the appropriate new version. Args: group_id: group_id of the existing library artifact_id: arti...
0f579f10c6e675330f332b1fe0d790e25448d23f
24,240
def GetIdpCertificateAuthorityDataFlag(): """Anthos auth token idp-certificate-authority-data flag, specifies the PEM-encoded certificate authority certificate for OIDC provider.""" return base.Argument( '--idp-certificate-authority-data', required=False, help='PEM-encoded certificate authority ce...
99fa02a0998a1c5e58baa8b334561d715ca4421a
24,241
def MapBasinKeysToJunctions(DataDirectory,FilenamePrefix): """ Function to write a dict of basin keys vs junctions Args: DataDirectory (str): the data directory fname_prefix (str): the name of the DEM Returns: A dictionary with the basin key as the key and the junction as the v...
adb206e711373c07ac28e477cf8dbf842af33d91
24,242
def password_renew(_name: str, old_password: str, new_password: str): """パスワード変更""" old_dat = old_password new_dat = new_password new_hs = sha256(new_dat.encode()).hexdigest() # sha256で暗号化 old_hs = sha256(old_dat.encode()).hexdigest() # sha256で暗号化 if User.select().where(User.name != _name): ...
c8ecc0d905b190535e3770838eeec37159dea95b
24,243
from typing import Callable from typing import List from typing import Tuple from typing import Dict import requests def fetch_abs(compare_res_fn: Callable[[res_arg_dict], List[BadResult]], paper_id: str) -> Tuple[Dict, List[BadResult]]: """Fetch an abs page.""" ng_url = ng_abs_base_url + paper_id legacy_...
a7e239b06213684cda34935956bf1ad1ec29ea6e
24,244
def is_happy(number:int) -> bool: """Returns a bool that states wether a number is happy or not""" results = [] result = thing(number) results.append(result) while results.count(result) < 2: # Checking if a number has shown up in the list of previous results again as that is result = ...
80a96325c28c346b2b23b5c6fb67c9cc62d0477c
24,245
def self_play(n_iterations=10, ben_steps=1000, training_steps=int(1e4), n_eval_episodes=100, **kwargs): """ Returns an agent that learns from playing against himself from random to optimal play. """ agents = [RLAgent(**kwargs), RandomAgent()] for _ in range(n_iterations): benchmark(agents[...
b38d593c53ecc528a3932fe8eba2091fdcd68067
24,246
import json import base64 import time def auth(event, context): """ Return the plain text session key used to encrypt the CAN Data File event dictionary input elements: - CAN Conditioner Serial Number - Encrypted data Prerequisites: The CAN Conditioner must be provisioned with a se...
a040fa68b0c1a65c5f0ca25ac4a58326796598ce
24,247
def xpro_aws_settings(aws_settings): """Default xPRO test settings""" aws_settings.XPRO_LEARNING_COURSE_BUCKET_NAME = ( "test-xpro-bucket" ) # impossible bucket name return aws_settings
72a7bd4a6ba40b19a6fda530db2bf67b0e4e5fc2
24,248
def function_check(arg, result): """arg ↝ result : return""" if result == TypeBuiltin(): return TypeBuiltin() if arg == KindBuiltin() and result == KindBuiltin(): return KindBuiltin() if arg == SortBuiltin() and result in (KindBuiltin(), SortBuiltin()): return SortBuiltin() r...
23840d8c2fba48803d7acc9b32b68ab0903d1d57
24,249
def test_parameter_1_1(): """ Feature: Check the names of parameters and the names of inputs of construct. Description: If the name of the input of construct is same as the parameters, add suffix to the name of the input. Expectation: No exception. """ class ParamNet(Cell): def __init__(...
f5d5be6f1403884192c303f2a8060b95fd3e9fca
24,250
def frule_edit(request, frule_id): """ FM模块编辑应用包下载规则 """ try: frule = FRule.objects.filter(id=frule_id).first() if not frule: response = '<script>alert("Rule id not exist!");' response += 'location.href=document.referrer;</script>' return HttpResponse(response...
1d5d83aaeff5483905e28f428719a6ce0b7833bc
24,251
from typing import Tuple def load_preprocess_data(days_for_validation: int, lag_variables: list, random_validation: bool = False, seed: int = None, lag: int = 8, reload: bool = True, ...
7238841e8f5e32be5ecb15ab5811720b41e8ad63
24,252
def extract_sha256_hash(hash): """Extrach SHA256 hash or return None """ prefix = 'sha256:' if hash and hash.startswith(prefix): return hash.replace(prefix, '') return None
11e9f352f3783657d52772c4b69387151d13f3d2
24,253
def logout(): """User logout""" global bandwidth_object, qos_object bandwidth_object = {} qos_object = {} success_login_form = None return redirect(url_for('base_blueprint.login'))
d3ec08fe6e8e0ca70f2f81b11878750efa101781
24,254
from typing import OrderedDict def draft_intro(): """ Controller for presenting draft versions of document introductions. """ response.files.append(URL('static/js/codemirror/lib', 'codemirror.js')) response.files.append(URL('static/js/codemirror/lib', 'codemirror.css')) response.files.append(U...
1ae932af2a9b89a35efbe0b1da91e26fe66f6403
24,255
import pathlib def collect_shape_data(gtfs_dir): """Calculate the number of times a shape (line on a map) is travelled. Appends some additional information about the route that the shape belongs to. Args: gtfs_dir: the directory where the GTFS file is extracted Returns: pandas.DataFr...
0fa16cc889696f01b25b4eb60ded423968b6aa20
24,256
def lick(): """ Returns a string when a user says 'lick' (This is a joke command) :return: A string """ return "*licks ice cream cone*"
a4e92d7371abe078c48196b0f7d7e899b1b0e19e
24,257
def from_dict(obj, node_name='root'): """Converts a simple dictionary into an XML document. Example: .. code-block:: python data = { 'test': { 'nodes': { 'node': [ 'Testing', 'Another node' ...
3308fb85baea5c145f4acd22fb49a70458f4cc51
24,258
def parse_ascii(state: str, size: int) -> str: """ Args: state: an ascii picture of a cube size: the size of the cube Returns: a string of the cube state in ULFRBD order """ U = [] L = [] F = [] R = [] B = [] D = [] lines = [] for line in state.s...
7ec24a22c3052a76c820dcca54c913c2d5229e5d
24,259
def _get_build_failure_reasons(build): # type: (Build) -> List[str] """Return the names of all the FailureReasons associated with a build. Args: build (Build): The build to return reasons for. Returns: list: A sorted list of the distinct FailureReason.reason values associated with ...
7f446ff96f93443a59293e36f4d071d79218f24d
24,260
import re def parse_line(line: str): """ Parses single record from a log according to log_pattern. If error occurs in parsing request_time, the log line is considered broken and function returns None. If error occurs in parsing URL, while request_time is present, the URL is marked as 'parse_fa...
1d747d22b28019f030c982455bfc89ea03e8631f
24,261
def for_all_arglocs(*args): """ for_all_arglocs(vv, vloc, size, off=0) -> int Compress larger argloc types and initiate the aloc visitor. @param vv (C++: aloc_visitor_t &) @param vloc (C++: argloc_t &) @param size (C++: int) @param off (C++: int) """ return _ida_typeinf.for_all_arglocs(*args...
9cc568f16d64f8a1bb206a08a73cdb4c3b6adcc4
24,262
def fetch_project_check_perm(id, user, perm): """Fetches a project by id and check the permission. Fetches a project by id and check whether the user has certain permission. Args: project_id: The id of the project. user: A User instance. perm: ...
dcf7271ebe171f77748eebdc61b2c74039da0690
24,263
def toRoman(n): """ Convert an integer to Roman numeral.""" if not (0 < n < 5000): raise OutOfRangeError("number out of range (must be 1..4999)") if int(n) != n: raise NotIntegerError("decimals can not be converted") result = "" for numeral, integer in romanNumeralMap: while...
275cd966e6dda8adfbde16ffc9ba0f6a4928ad3e
24,264
import multiprocessing def simulate_one(ticket: Ticket, strategy: Strategy, trials: int) -> float: """ :param ticket: :return: """ diagnostics = False workers = multiprocessing.cpu_count() things = [(strategy, ticket) for x in range(0, trials)] chunksize = int(len(things) / workers) ...
cba86eaabc1b25681cf8b4e9d4c3134c186d5d43
24,266
def download_prostate(): """Download prostate dataset.""" return _download_and_read('prostate.img')
a65174dd85491d259c94b9df31c739b62a9e50be
24,267
import json import random import hashlib def decBIPKey(encrypted_privK, passphrase, currency): """ Decrypt an encrypted Private key Show the corresponding public address """ #using the currencies.json file, get the currency data with open('currencies.json', 'r') as dataFile: currencies = json.load(dataFile) ...
743a87753463ca269ff6a120024813a5e61445ac
24,268
def plot_data(coordinate, box=[], plt_inst=None, **kwargs): """ Plot the coordinate with the "std box" around the curve Args: coordinate (float[]): 1D array of the coordinate to plot box (float[]): 1D array of the box around the curve plt_inst (pyplot): pyplot in...
4c549425f076217cb8b0302a49137bc8e85b661a
24,269
def param_curve(t, R, r, d): """Coordinates of a hypotrochoid for parameters t, R, r and d""" x = (R - r)*cos(t) + d*cos((R - r)/r*t) y = (R - r)*sin(t) - d*sin((R - r)/r*t) z = 3*sin(t) return x, y, z
dd60c3aada02e589d50566910bbc63b6b67c40d8
24,271
def calculate_average_crossing_per_month_and_measure(num_of_months, list_with_agg_values): """Calculates the average crossings per month and per measure. Args: num_of_months: the number of months based on the frequency of each measure, saved as a dict or a ...
750d1b944a4f8723a4f39fc2f92b42f1011ea9c7
24,275
from typing import List from typing import Optional from typing import Dict def predict_with_inferer( images: Tensor, network, keys: List[str], inferer: Optional[SlidingWindowInferer] = None ) -> Dict[str, List[Tensor]]: """ Predict network dict output with an inferer. Compared with directly output networ...
2184c5f681bcf13787b59a036d0f4572a391a852
24,277
import re def split_data(line): """ method splits varibles on line """ data = list() arr = np.array([string for string in line.split(", ")], dtype=str) for _, item in enumerate(arr): word_parse = re.compile(r''' ((?<=:.)-*[0-9]+\.*[0-9]*)''', re.X) parts = word_parse.findall(...
8fcab989a6220ddccf653552b5e9eaf98bd83277
24,278
def show_outcome_group_global(request_ctx, id, **request_kwargs): """ :param request_ctx: The request context :type request_ctx: :class:RequestContext :param id: (required) ID :type id: string :return: Show an outcome group :rtype: requests.Response (with OutcomeGrou...
0e8d8c9411e3bc6d7cdbdede38cca65878dccb65
24,279
import hashlib def md5sum(file: str) -> str: """ Create a strings with the md5 of a given file :param file: filename of the file whose md5 is computed for :return: md5 string """ md5_hash = hashlib.md5() with open(file, "rb") as file: content = file.read() md5_hash.update(con...
0ec81688aa298e73a064034760cdd1687b2561a4
24,280
def read_data(filetype, filename, prn): """Calls the appropriate position reader function based on the filetype.""" func_name = filetype + '_data' possibles = globals().copy() possibles.update(locals()) func = possibles.get(func_name) if func is None: raise NotImplementedError(func + ' i...
91949a7cc1573a44ebb504b3a5542ff289b2100a
24,281
def simulate_games(num_games, switch, num_doors=3): """ Simulate a multiple game of the Monty Hall problem. Parameters: - num_games: Integer, the number of games you want to simulate. - switch: Boolean, whether or not your strategy is to switch doors after the reveal. ...
0296375eb5f57f1b5e9580086f08150774a30956
24,283
from typing import Iterable import functools import operator def prod(iterable:Iterable) -> Iterable: """math.prod support for Python versions < v3.8""" return functools.reduce(operator.mul, iterable, 1)
be811e39b7dd70669fbfc84db5492b4c7383d68f
24,284
def trim_resource(resource): """ trim_resource """ return resource.strip(" \t\n\r/")
5a9d9bbf6da72cf967eee1e9198d109f096e3e41
24,286
import requests def wikipedia_request_page_from_geocoding(flatitude, flongitude): """ Get list of wikipedia page identifiers related to the specified geocode """ places_list = [] loc = "{}|{}".format(flatitude, flongitude) print(loc) parameters = { "action": "query", "list": "ge...
b61ea747c40f132d312e03c6d3b649e35f53430c
24,287
def globalBinarise(logger, img, thresh, maxval): """ This function takes in a numpy array image and returns a corresponding mask that is a global binarisation on it based on a given threshold and maxval. Any elements in the array that is greater than or equals to the given threshold will be...
d16bcc8a78a62b5ec945c6e0ff245a10402d22f1
24,288
def times_by_stencil(results): """Collects times of multiple results by stencils. Args: results: List of `Result` objects. Returns: A tuple of lists (stencils, times). """ stencils = results[0].stencils if any(stencils != r.stencils for r in results): raise ValueError('...
a304924f6f82e6611c9469a21f92592f67d7c84d
24,290
def get_bulk_and_slab(bulk, miller=[1,1,1], layers=4, vacuum=16): """Create a slab and conventional bulk cell from a bulk cell input Parameters ---------- bulk : pymatgen structure pymatgen structure of the bulk material miller : list list of miller indices layers : int ...
4a914dfba1ee4efea747464036b868a07311cb9d
24,291
def gogogo_figure(ipympl, figsize, ax=None): """ gogogo the greatest function name of all """ if ax is None: if ipympl: with ioff: fig = figure(figsize=figsize) ax = fig.gca() else: fig = figure(figsize=figsize) ax = fig...
750b75b669f233b833cd575cbf450de44b0ad910
24,292
from re import L def unzip6(xs): """ unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f]) The unzip6 function takes a list of six-tuples and returns six lists, analogous to unzip. """ a = L[(i[0] for i in xs)] b = L[(i[1] for i in xs)] c = L[(i[2] for i in xs)] d = L[(...
04ac4aae355b82f1709479296239e4d197224975
24,293
import re def grep(lines=None,expr=None,index=False): """ Similar to the standard unit "grep" but run on a list of strings. Returns a list of the matching lines unless index=True is set, then it returns the indices. Parameters ---------- lines : list The list of string lines to ...
aefbf15ba94e8ac2ceced3ed3958abb7e4a70163
24,294
from bs4 import BeautifulSoup from typing import Dict def get_table_map_from_text(sp: BeautifulSoup, keep_table_contents=True) -> Dict: """ Generate table dict only :param sp: :param keep_table_contents: :return: """ table_map = dict() for flt in sp.find_all('float'): try: ...
686cad1a219e53a4d5548bf55e5696da94bd7170
24,295
def grainfromVertices(R=None,fname='shape.txt',mixed=False,eqv_rad=10.,rot=0.,radians=True,min_res=4): """ This function generates a mesh0 from a text file containing a list of its vertices in normalised coordinates over a square grid of dimensions 1 x 1. Centre = (0,0) coordinates must be of the form: ...
12333a4be631dc8fe8646677d8830646b8563624
24,297
def get_block(blockidx, blocksz, obj): """ Given obj, a list, return the intersection of obj[blockidx*blocksz:(blockidx+1)*blocksz] and obj Ex: get_block(2, 100, range(250) returns [200, 201, ..., 249] """ if blockidx*blocksz > len(obj): return [] elif (blockidx+1)*blocksz > len(obj...
8666cc30be23619a49f899beec17d3ba1f0fb357
24,298
import warnings def RDS(net,waves,coupons,p,size,seeds,posseed,poswave): """Conducts respondent-driven sampling Input: net: network, networkx graph waves: maximum number of waves, integer (use 0 with poswave=True for contract tracing) coupons: number of coupons per respon...
5480a85e9f160f988cff384306a90913a6eac905
24,299
import platform def get_dataset_mrnet_args(parser, args=[]): """ Get all relevant parameters to handle the dataset -> here: MRNET """ # determine path if platform.system() == "Linux": path = "/home/biomech/Documents/OsteoData/MRNet-v1.0/" else: path = "C:/Users/Niko/Docume...
466cb843fca4a09f52a72603dcd2c4379ea1e54d
24,300
import base64 def convertImageToBase64(image): """ Convert image to base64 for transmission Args: image (obj): opencv image object Returns: (str): image encoded as base64 """ # im_arr: image in Numpy one-dim array format. _, im_arr = cv2.imencode('.jpg', image) im_bytes = im_arr.tobytes() ...
25f4ce7e9dce20ebb50fc55d31c52c77b0b7aa4b
24,301
def anchor_inside_flags(flat_anchors, valid_flags, tsize, allowed_border=0): """Check whether the anchors are inside the border. Args: flat_anchors (torch.Tensor): Flatten anchors, shape (n, 2). valid_flags (torch.Tensor): An existing valid flags of anchors. tsize (int): Temporal size o...
d7840ebb4e5fcb7735e27454c0367eb14cec6ff0
24,302
def args2command(*args): """ to convert positional arguments to string list """ try: assert None not in args assert "" not in args except: print("args:", args) raise(ValueError("None values not allowed in args!")) return [str(_).strip() for _ in args]
688fed2c2146583f05deb75a5c832aac6c971cbd
24,303
from typing import Tuple from typing import Optional from typing import List def parse_one(line: str) -> Tuple[Optional[str], List[str]]: """ Returns (first corruption char, remaining stack) """ stack = [] for c in line: if c in BRACKET_MAP.keys(): stack.append(c) c...
85c4479b743c5ff3de041bca23a01fec1294a6bd
24,304
def load_callable_dotted_path(dotted_path, raise_=True, reload=False): """ Like load_dotted_path but verifies the loaded object is a callable """ loaded_object = load_dotted_path(dotted_path=dotted_path, raise_=raise_, reload=relo...
e76cf024cfbc4700d224881a9929951a3b23e246
24,305
def get_engine(): """Helper method to grab engine.""" facade = _create_facade_lazily() return facade.get_engine()
1d430d2fbe7b79d6c6cb69a0a11fb811ade92b24
24,306
def generate_diagonals(): """ Cоздает словарь диагоналей на которые модет встать конь и массив с возможным количеством вариантов дойти в кажду точку этой диагонали :return: словарь - где ключ это число диагонали а значения, это список из возможных способов добраться до точек на этой диагонали ""...
cf5945a565197194c7844e8f59ff4a137cab1abf
24,307
from typing import Union def physical_rad_to_pix(im_prod: Union[Image, RateMap, ExpMap], physical_rad: Quantity, coord: Quantity, z: Union[float, int] = None, cosmo=None) -> Quantity: """ Another convenience function, this time to convert physical radii to pixels. It can deal with both...
4a26079610c882e40a31c7ba2ca64f7a0ccdd901
24,308
from functools import reduce def conversation_type_frequency_distribution(convo): """ Returns the type frequency (unigram) distribution for the convo. Parameters ---------- convo : Conversation Returns ------- collections.Counter """ return reduce(lambda x, y: x + y, map(post...
66da6bfea0f6a1df0657fba2c881f373acc7d69e
24,309
import json def _err_to_json(key, *args): """Translate an error key to the full JSON error response""" assert (key in errors) code = errors[key][0] title = errors[key][1] detail = errors[key][2].format(*args) return json.dumps({ 'message': title, 'errors': [{ ...
00be9d9603f5a5e36bb0197dd60886afb4f1f989
24,311
def multiref_represent(opts, tablename, represent_string = "%(name)s"): """ Represent a list of references @param opt: the current value or list of values @param tablename: the referenced table @param represent_string: format string to represent the records """ if not opts:...
86cb90e04073ddb4ec5676de3d9c87417bed5740
24,312
def selected_cells(self): """Get the selected cells. Synchronous, so returns a list. Returns: A list of Cells. """ cells = [] generator = self.selected_cells_async() for chunk in generator: for value in chunk.cells: cells.append(value) return cells
523e77757acf8755b32ac0d283fd8864d6784ff1
24,313
import warnings def calc_annual_capital_addts_ferc1(steam_df, window=3): """ Calculate annual capital additions for FERC1 steam records. Convert the capex_total column into annual capital additons the `capex_total` column is the cumulative capital poured into the plant over time. This function ta...
3d1c07182f590f39f394a2e6ef78105b9ad2b745
24,314
import time import json async def async_upload_file(serialUID, filepath, upload_blockinfo): """异步上传文件""" ts = int(time.time() * 1000) # 计算分片CRC32 data, crc32 = get_block_crc32(filepath, upload_blockinfo["startOffset"], upload_blockinfo["endOffset"]) upload_blockinfo['dataCRC32'] = crc32 # 数据加...
08da476e3ce4b680b60124777972332a807137ce
24,315
def create_cv_split(file_train, file_test, col_label='label', col_group=None, n_folds=5, splitter='skf', random_state=33): """ Parameters: splitter : str "kf", "skf", "gkf" Example: train_df, test_df = create_cv_split(os.path.join(args.data_dir, 'Train.csv'), ...
95a0ceb9c63c68a2cf322ccd72050cdf2708a59c
24,317
def get_scanner(hass, config): """Validate the configuration and return a Bbox scanner.""" scanner = BboxDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None
2ce6e0e9e4b11885a2c3d9090ed31c0a3da9070d
24,318
def _trim_name(image): """Remove the slash at the end of the filename.""" return image[:-1] if image[-1] == '/' else image
823dd63920673352a18d73f83190853d5a234483
24,319
from typing import Callable def sines_sum(parameters: ndarray) -> Callable: """ Construct a sum of sines for given parameters. Parameters ---------- parameters : ndarray y0, amplitude1, frequency1, phase1, amplitude2, frequency2, phase2, ... Returns ------- function f...
43cff5790ec098debc638a2cd66d3ac929a67ef6
24,322
def _divide_and_conquer_convex_hull(points): """ Notes: O(n * log(n)) Args: points: Returns: """ count = len(points) if count < 6: return Hull(_jarvis_convex_hull(points)) midpoint = count // 2 min_cloud, max_cloud = points[:midpoint], points[midpoint:] ...
46fc256c0efc08f978fe1049935d068a9a6b23de
24,323
from typing import Union def _parsed_method_to_method( parsed: Union[parse.UnderstoodMethod, parse.ImplementationSpecificMethod] ) -> Union[UnderstoodMethod, ImplementationSpecificMethod]: """Translate the parsed method into an intermediate representation.""" if isinstance(parsed, parse.ImplementationSpec...
061df4c074cd3fe5f0c5b8570bdefe8605527d46
24,324
def NS(namespace, tag): """ Generate a namespaced tag for use in creation of an XML file """ return '{' + XML_NS[namespace] + '}' + tag
32a6f1e8e351ca15f84391632f6773ee4c538dfd
24,325
def non_contradiction_instance_2(person_list, place_list, n, vi_function=vi, not_vi_function=not_vi, Everyone_str="Everyone", ...
068655c85b9bb5a4979a94a9c58b4297222db32e
24,327
def load_w2v_model(w2v_path): """ Loads pretrained w2v model :param w2v_path: :return: """ return gensim.models.Word2Vec.load(w2v_path)
f9e44290ae8d2e7069ed724b68c405f275d6b95b
24,328
import hmac def derive_keys(token, secret, strategy): """Derives keys for MAC and ENCRYPTION from the user-provided secret. The resulting keys should be passed to the protect and unprotect functions. As suggested by NIST Special Publication 800-108, this uses the first 128 bits from the sha384 KD...
1b7e53957f746f91df4b5e7545ac1a079a96ac94
24,329
from typing import Optional def bitinfo_holding_ts( track_addr: Optional[str] = None, track_coin: Optional[str] = None, timeframe: Optional[str] = "4h", sma: Optional[int] = 20, ): """Scrap the data from bitinfo and calculate the balance based on the resample frequency. track_addr (str): The a...
bf29a9f91c695a4424436522fd76b467e9e573e0
24,330
import logging def sharpe(p): """Sharpe ratio of the returns""" try: return p.mean()/p.std()*np.sqrt(252) except ZeroDivisionError: logging.error("Zero volatility, divide by zero in Sharpe ratio.") return np.inf
e2700f9dfdc5b1d405892bc7ee460a2930b860d4
24,331
from ase.lattice.cubic import FaceCenteredCubic from ase.lattice.cubic import BodyCenteredCubic import six def create_manual_slab_ase(lattice='fcc', miller=None, host_symbol='Fe', latticeconstant=4.0, size=(1, 1, 5), replacements=None, decimals=10, pop_last_layers...
47447a6f34b48865ab0bc4824f05c98e976b92be
24,332
def telephone(): """Generates random 10 digit phone numbers and returns them as a dictionary entry""" num = "" # for i in range(1, 11): num += str(rand.randint(0, 9)) if(i < 7 and i % 3 == 0): num += "-" return {"telephone":num}
436c6a04fbdff8162de39433ddd250a610333173
24,333
from datetime import datetime from typing import List import warnings import time def get_kline(symbol: str, end_date: [datetime, str], freq: str, start_date: [datetime, str] = None, count=None, fq: bool = False) -> List[RawBar]: """获取K线数据 :param symbol: 币安期货的交易对 BTCUSDT/ETHUSDT :param start...
5f6d9cdd82adf1a79dc9ed054de139170249ac13
24,334
def get_terms(properties, out_log, classname): """ Gets energy terms """ terms = properties.get('terms', dict()) if not terms or not isinstance(terms, list): fu.log(classname + ': No terms provided or incorrect format, exiting', out_log) raise SystemExit(classname + ': No terms provided or incorrect format') if...
b25c596fd65a68c4c3f7b99268ddbf39675ad592
24,335
import struct def _decomp_MAMFile(srcfile, destfile=''): """ Superfetch file이나 Prefetch file의 MAM 포맷의 압축을 푼다. """ f = open(srcfile, 'rb') data = f.read() f.close() # 압축된 파일인지 확인한다. """ MAX\x84 : Windows 8 이상 수퍼패치 파일 MAX\x04 : Windows 10 프리패치 파일 """ id = data[0:3].decode('utf8') ...
fd2687854a2918f5692d619b83bd8ca73d6c87aa
24,337
def cg(A, b, x=None, tol=1e-10, verbose=0, f=10, max_steps=None): """ Parameters ---------- A: A matrix, or a function capable of carrying out matrix-vector products. """ n = b.size b = b.reshape(n) if x is None: x = np.zeros(n) else: x = x.reshape(n) if isinstan...
8d2b6e332eee6ce21296a9f66621b1629cd56c33
24,338
def from_string(spec): """Construct a Device from a string. Args: spec: a string of the form /job:<name>/replica:<id>/task:<id>/device:CPU:<id> or /job:<name>/replica:<id>/task:<id>/device:GPU:<id> as cpu and gpu are mutually exclusive. All entries are optional. Returns: A Device. ...
c223ead53ee1677e5bbfd863aeaffb8aefc5e81f
24,339
from typing import OrderedDict def load_HDFS_data_timestamp_approach(input_path, time_delta_sec, timestamp_format, cached_workflow_path='data_df.csv', sep=',', encoding ='utf-8', cache_workflow=True): """ Downloads cached workflow data from csv file Args: input_path: path to cached wo...
b3e7dff820a666ee0060dc3349e91eb990a5c9ab
24,340