content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def label_developer_portrait(user, user_profile): """ Generating user profile of issue/pr label. :param user: issue user_login of open source community :param user_profile: issue user_profile data of open source community :return: [user_activity, user_habit] """ # user_portrait_classifier ...
ec84c6b888e3814fcc961ca5c4ee7b162fd27163
624,315
def get_reverse_sorted_dict(dict): """ Sorts the dictionary in reverse order according to the keys of the original dictionary. :param dict: Dictionary to sort. :return: The sorted dictionary in reverse order. """ reverse_sorted_dict = {} for key in sorted(dict, reverse=True): re...
417933dcfb646ad155b5939ec46b1ef568894708
624,316
from typing import Callable import inspect async def nested_apply(target: dict, func: Callable): """ Applies `func` recursively to all non dict types in `target` """ for key, val in target.items(): if isinstance(val, dict): target[key] = await nested_apply(val, func) else: ...
e3bc14f70defd29ce81853b46afbe34411678a91
624,317
def shorten_duplicate_content_url(url): """Remove anchor part and trailing index.html from URL.""" if '#' in url: url = url.split('#', 1)[0] if url.endswith('index.html'): return url[:-10] if url.endswith('index.htm'): return url[:-9] return url
86c351d857d9e3b140af2f81ab67959f5697e33b
624,318
import random def generate(model, n, seed, max_iterations): """Generates a list of tokens from information in model, using n as the length of n-grams in the model. Starts the generation with the n-gram given as seed. If more than max_iteration iterations are reached, the process is stopped. (This is to prevent...
16412c50a7082bed5668fd78213bb30f2d6c089b
624,319
def get_edge_label(layer): """Define edge label based on layer type. """ if layer.type == 'Data': edge_label = 'Batch ' + str(layer.data_param.batch_size) elif layer.type == 'Convolution' or layer.type == 'Deconvolution': edge_label = str(layer.convolution_param.num_output) elif lay...
729cafaa01b9f47ac6d4a27f397fef7a18dc9766
624,320
def _setup_sockets(monkeypatch): """Helper function to create fake socket connection responses corresponding to Sonos speakers on specific IP address / port combinations only.""" def mock_socket_connect_ex_return(_, address_port): if address_port in [("192.168.0.1", 1400), ("192.168.0.2", 1400)]: ...
08337fb7a9bfabf6714dca91c50853c6d5490043
624,321
def pip_cross(point, pgon): """ Input pgon: a list of points as the vertices for a polygon The polygon needs to be closed. Otherwise an error is raised. point: the point Ouput Returns a boolean value of True or False and the number of times the half line crosses the...
d681601f9ba98f2c22c3c68aabe9da7dafc492a1
624,322
def convert_hhmmss(hhmmss): """Convert hh:mm:ss to seconds.""" fields = hhmmss.split(":") if len(fields) != 3: raise ValueError("Received invalid HH:MM:SS data: {}".format(hhmmss)) fields = [int(x) for x in fields] hours, minutes, seconds = fields return (hours * 3600) + (minutes * 60) +...
bcbf0911eda403b38ca31a4efc9ef0ca98cb8f82
624,324
def _get_trids(db, id_val, id_type): """Return text ref IDs corresponding to any ID type and value.""" # Get the text ref id(s) if id_type in ['trid']: trid_list = [int(id_val)] else: id_types = ['pmid', 'pmcid', 'doi', 'pii', 'url', 'manuscript_id'] if id_type not in id_types: ...
4f4c0bf412bd608efd6623b4681d653c94a8b05d
624,325
def country_dict_geofabrik(): """ Create a dictionary to convert ISO2 codes to Geofabrik country names. Returns: *dictionary* -- lookup between ISO2 codes and Geofabrik country names. """ countries = ['LU','CZ','CH','EE','LV','LT','PT','ES','AT','BE','DK','IE','NL','NO','SE','UK','...
b89cd6b2f0599c4e7cb3bdd1864d1712f771c988
624,326
def groupby(function, sequence): """ Example: >>> from m2py import functional as f >>> f.groupby(len, ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']) {3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']} >>> >>> >>> f.groupby(f.is_even, [1, 2, 3, 4, 5, 6, 7]) {F...
857bbc415cf2c664370b7b36f1b23469f1769fd2
624,327
def load_brackets(file_path): """Load from brackets file""" bracket_file_path = file_path.replace('ann.xml', 'txt.brackets') edges = [] with open(bracket_file_path) as f: for line in f: line_p = line.strip().replace('(', '').replace(')', '') line_p = line_p.replace("'", ...
56e5db6dc4e7f27f82a0f772a1e1b8c7f1007c18
624,328
from typing import Optional async def read_user_item(user_id: int, item_id: str, q: Optional[str] = None, short: bool = False): """Multiple path and query parameters""" item = {"item_id": item_id, "owner_id": user_id} if q: item.update({"q": q}) if not short: item.update( {...
003cf2cfb45cc59d1fea3c26c1da0f6341f27fff
624,329
def title_from_label_and_target(label, correct_label): """Returns "OK" ofr "NO" for a label and a prediction Args: label (string) correct_label (string) Returns: string """ CLASSES = [0, 1] if correct_label is None: return CLASSES[label], True correct = (lab...
f7a7ff242560038ab63b7286bc7cb7fff94dda3a
624,330
def is_leaf(dmrs, nodeid): """ Check if a node has no outgoing links """ return not any(dmrs.get_out(nodeid, itr=True))
b8ecd4056b6488341abd40e5fe4b8053fd1e3454
624,331
def get_active(user_id): # noqa: E501 """Get active packages # noqa: E501 :param user_id: The id of the user :type user_id: int :rtype: InsurancePolicies """ return 'do some magic!'
afef3483f2f1c46721f829044f2d6ad30218f810
624,332
def comparator_eval(comparator_params): """Gets BUFF score for interaction between two AMPAL objects """ top1, top2, params1, params2, seq1, seq2, movements = comparator_params xrot, yrot, zrot, xtrans, ytrans, ztrans = movements obj1 = top1(*params1) obj2 = top2(*params2) obj2.rotate(xrot, ...
bfd2892b44b14d9561c26778f062b0ca7ab34bcd
624,333
import re def count_sentences(string: str) -> int: """ Counts quantity of sentences in given text. """ sentence_endings = re.compile("[.!?]+") return len(sentence_endings.findall(string))
e1e1d2bdfedcd71fb35397e307b036192ab36104
624,334
import random import requests def shimo(content): """提交数据到石墨文档表单收集器 """ # 石墨文档提交数据格式 data = { "duration" : 55, #时间 "formRev" : 1, "responseContent" : [ { "guid" : "xxxxx", #石墨文档的guid "text" : { "content" : "xxxxxxxx" }, ...
344d758ee5e36781cabb920e49f6828512185f0d
624,335
def hotdist(dist, name, beta_temp, *args, **kwargs): """ Instantiate a "hot" distribution. The "hot" distribution takes the value returned by the logp method of `dist` and returns beta * logp. Parameters ---------- dist : PyMC3 distribution The name of a distribution you want to make ho...
d2f595a2d19eb78b769a7198ae5d582d6a3c712e
624,336
from pkg_resources import get_distribution, DistributionNotFound def get_version() -> str: """Get the version of the code from egg_info. Returns: the package version number """ try: # pylint: disable=no-member version = get_distribution(__name__.split('.')[0]).version excep...
d0b72f8a3bf9726aeba60ce00e97de3d5d75d860
624,337
def points(): """ Fixture to create polynomial values """ return [2, 3, 4]
fb89b97aa3b99e0d67c6d35b7862303d5347c770
624,338
def bytes_to_unicode(): """ Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.(예측할 수 없음) When you're at something like a 10B token datas...
546e9debb3f612ae0e0446a989f223c40dfdcfc3
624,339
def normalize_ssc(name): """ Convert a name in SCREAMING_SNAKE_CASE to regular notation, e.g. "Screaming snake case". Args: name: Name to convert. Returns: str: Converted name. """ if not name: return return " ".join(part for part in name.split("_")).capitalize...
42f4c66aff0ffe9ede73d2700814935a38eb9f4e
624,340
def trim_for_encoding(wav_data, sample_length, hop_length=512): """Make sure audio is a even multiple of hop_size. Args: wav_data: 1-D or 2-D array of floats. sample_length: Max length of audio data. hop_length: Pooling size of WaveNet autoencoder. Returns: wav_data: Trimmed array. sample_le...
31d51d9242c53b6012948ff33c59b002b0acf927
624,341
from typing import Dict from typing import Any def comic_to_str(comic: Dict[str, Any]) -> str: """ Convert a comic info dict to a markdown-formatted message string. """ msg = f"Comic #{comic['num']} (Posted {comic['year']}-{comic['month'].zfill(2)}-{comic['day'].zfill(2)}):\n\n# {comic['title']}\n" ...
7c602094643ae0888689248a86fe2b9575d0b7a8
624,342
def epoch_log(epoch_loss, measure): """logging the metrics at the end of an epoch""" dices = measure.get_metrics() dice = dices print("Loss: %0.4f |dice: %0.4f" % (epoch_loss, dice)) return dice
3e848e9c2091e386972db9ab2ebc3a5774344b9f
624,343
import re def alpha_only(s): """ Strip any non-alpha characters from s, and convert to lowercase """ return re.sub(r'[^A-Za-z]+', '', s.lower())
71f69ebe8e3d0819ff6b4336bfeac7a0e907364c
624,344
def grab_file_list(apk) : """ @param apk : an APK instance @rtype : the file list inside the AP """ return apk.get_files()
ecef8108984889c6a54d6cc59a4a32e27e627994
624,345
def swift_library_output_map(name, module_link_name): """Returns the dictionary of implicit outputs for a `swift_library`. This function is used to specify the `outputs` of the `swift_library` rule; as such, its arguments must be named exactly the same as the attributes to which they refer. Args: name: ...
629a8199142cf584497b188c51d05ad55c457b8f
624,346
def get_dep_json(res_json): """get json for dependency browser and dependency graph""" CLIENT_PROTOCOL_SERVICES = ("LocateProtocol", "OpenProtocol") dep_json = list() for module_info in res_json: for protocol in module_info["protocols"]: if ( protocol["service"] == "...
879049ec2b82966a1f5275dfab5e873731903b20
624,347
import os import subprocess def exec_node_command(node_dir, *args): """ This function runs an indigo-node command from the provided directory. """ os.chdir(node_dir) return subprocess.check_output(["indigo-node"] + list(args))
334233f3a55c91c472e7fe9cd190ec1db88a7082
624,348
def gen_custom_item_windows_group(description, info, value_type, members, group_name): """ Generates a custom item stanza for a windows group membership audit Args: description: string, a description of the audit info: string, info about the audit value_type: string, "POLICY_TEXT" -- inclu...
c840c9510e863a7c06bb20d13f75a8d2c5a74272
624,349
def convert_string_to_list_float(string): """ Convert the string of a list to the actual floating point list. """ return [float(l) for l in string[1:-1].split(", ")]
77db3e9fa59d27c47a5a0d63185d467293527b2c
624,350
from pathlib import Path import os def expand_path(path: Path, config_directory: Path) -> Path: """ Return an absolute path from a (possibly) relative path. Relative paths are relative to $ASTRALITY_CONFIG_HOME, and ~ is expanded to the home directory of $USER. """ # Expand environment variab...
dfddf1def92ea7fe6357b308b7e971966bbe2373
624,351
import timeit def upload(ftpsession, remote_filename, local_filename_read, remote_directory_upload, timestamp): """ upload local speedtest file """ start = timeit.default_timer() ftpsession.cwd(remote_directory_upload) ftpsession.storbinary('STOR ' + remote_filename + str(timestamp), local_filename_re...
d3167ebbdda80c95141ffdb7b547a7e6ec2469d3
624,352
import subprocess import sys def list_executables(dir): """Return a list of the executable files under `dir`.""" output = subprocess.check_output( ['find', dir, '-executable', '-type', 'f']) r = set() for line in output.splitlines(): r.add(line.decode(sys.getfilesystemencoding())) ...
aec3295bd50b7e747d20e7b5f67578018ec5ad35
624,353
import os import sys def _is_image_data_provided(args): """Return True if some image data has probably been provided by the user""" # NOTE(kragniz): Check stdin works, then check is there is any data # on stdin or a filename has been provided with --file try: os.fstat(0) except OSError: ...
f61c2f69c64c5e19895d6c848674edb3941c0719
624,354
def revpad(s): """ This function is to remove padding. parameters: s:str string to be reverse padded """ k=ord(s[-1]) temp=0 #temporary variable to check padding for i in range (1,k): #for loop to check padding if(s[-i]!=s[...
9c6145f56655a9bea0e1fd4b3e962175f436a4fa
624,355
import sys import os def getOutputPaths(lldbRootDirectory): """ Returns typical build output paths for the lldb executable lldbDirectory - path to the root of the lldb svn/git repo """ result = [] if sys.platform == 'darwin': result.extend(getXcodeOutputPaths(lldbRootDirectory)) ...
5a3edc5cb244507a9262ac317d5cdd0139cb3cd9
624,356
def find_aircraft_id(key, config): """ find_aircraft_id The aircraft identifier can be given either as a dictionary key in the yaml file or under the fields 'identifier' or 'id' in the aircraft configuration item. This function test in the parsed yaml to find the aircraft id. """ if 'ident...
e3988096a4a3ebf70681efb0595a8a1ad8abaa96
624,357
def call_reply(msg, call_return): """Construct message used by CtrlServer when replying to API calls. :param msg: Description of API call. :type msg: string :param call_return: Return value of API call. :type call_return: string :returns: Constructed call_reply dict, ready to be sent over the w...
eadbaf02bf182af228e0c4a1a31603ca5bfa0eb2
624,358
import torch def flatten(params): """ Turns a module's parameters (or gradients) into a flat numpy array params: the module's parameters (or gradients) """ with torch.no_grad(): return torch.cat([p.data.view(-1) for p in params])
1e278028f1878aa1cadc730fe03007cb6062f4c3
624,359
def pk_same_public_key(key1, key2): """Return true iff key1 and key2 are the same key.""" return key1.encode_key(1) == key2.encode_key(1)
084818c7af42ac52573c14c1e103f91ee882e9a5
624,361
import string def list_candidates(hits, blows, misses): """List candidates according to the clues given. 1. skip words with different length 2. skip if blows are missing 3. skip if hits don't hit 4. skip if misses are included 5. what's left are the candidates """ length = len(hi...
47c7d052226e9a3c00cc7ece472f9cddca385d22
624,362
def safe_mathis_label(tput_true, tput_mathis): """ Returns the Mathis model label based on the true throughput and Mathis model fair throughput. If either component value is -1 (unknown), then the resulting label is -1 (unknown). """ return ( -1 if tput_true == -1 or tput_mathis == -1 el...
26108c82db9e5e5f3deb3affa37326ff2a28f2f0
624,363
import itertools import operator def multi_split(string, *seps): """split a list of separators""" split = [string] for sep in seps: split = itertools.chain.from_iterable(map(operator.methodcaller('split', sep), split)) return split
8b0a362a5be414c7b04c828cb0e70ca53ace031d
624,365
def setup_with_context_manager(testcase, cm): """Use a contextmanager to setUp a test case.""" val = cm.__enter__() testcase.addCleanup(cm.__exit__, None, None, None) return val
ef60ebfe6ce00ea2a4784a61241dc22dd292b81d
624,366
from typing import Union from typing import List def parse_to_string_list(values: Union[None, str, List[str]]) -> List[str]: """Parse to string list.""" if isinstance(values, str): return [values] if isinstance(values, list): return values return []
ae6ae28c757f5f7ef2b065fd5d9a635cf7961377
624,367
import os import requests def fetch_screenshot(screenshot: dict): """Fetches screenshot data. Retuns None if screenshot has no asset.""" attr = screenshot["attributes"] file_ext = os.path.splitext(attr["fileName"])[1] if attr["imageAsset"] is None: return None width = attr["imageAsset"]["...
e9fb216fedd9fa95e717175b2aba4ca9ce36a234
624,368
def get_item(iterable_or_dict, index, default=None): """Return iterable[index] or default if IndexError is raised.""" try: return iterable_or_dict[index] except (IndexError, KeyError): return default
9fb8bcaf2dcc30396cdce6e61610c5d1a51c40ff
624,369
def getDimensions(name): """Gets the rows and columns of a matrix from a text file Args: name (string): filename for matrix Returns: tuple: a tuple of the rows and columns """ file = open(name, 'r') size = file.readline().split() #split at a tab rows = size[0] cols = s...
339fda5cd34ed20b3c2aa1cd5908d642e3ca0d2e
624,370
def _rho3(basis_states): """State ρ₃ from the "3states" functional""" d = len(basis_states) # dimension of logical subspace return (1.0 / d) * sum([psi * psi.dag() for psi in basis_states])
1f91bf8db224d2ac0e515f33d88bbae150cdfb71
624,371
def cli(ctx, group_id): """Get the list of users associated to the given group. Output: List of group users' info """ return ctx.gi.groups.get_group_users(group_id)
d2a63ecbf454afe66a0f74a564bd2f4862257264
624,372
import os def getSiteName(): """ Return the site or laboratory name """ return os.environ['SITENAME']
042310ce54117ac5972e6c442fc003109eb6f1ee
624,373
def plain_text_to_html(string): """Convert plain text to HTML markup.""" string = string.replace("&", "&") return string
8dfaf9287ec8f765d77c241e2161c1729cb8c422
624,374
def _getMapExprStrings(): """Return patterns for parsing map file paths from expression The attribute value of mapped texture has format like: $x=map('${DESC}/paintmaps/mask'); $a=map('${DESC}/${HAHA}/mask');#3dpaint,5.0 $b=map('${DESC}/paintmaps/regionMask/pSphere2.ptx');#3dpaint,5.0a...
48f5e09b519e1805bd38ca60e7ec610ca3e2007f
624,375
import yaml def read_yaml(crds_loc): """ Read yaml file :param crds_loc: (string) location of yaml file :return config: (?) read file """ ## Configuration parameter config = None ## Safe loading file try: with open(crds_loc, "r") as file: config = yaml.safe_l...
3d9f1955e2d5973eb463ecb381ede07022a958f1
624,376
import os import shutil def _find_make(): """Returns the correct make command for this environment. """ make_cmd = os.environ.get('MAKE') if not make_cmd: make_cmd = 'gmake' if shutil.which('gmake') else 'make' return make_cmd
ba5066701c5865008ec322d187e832408c16460f
624,378
def _realign_region_in_hap(haplotypes): """ Find all the variant region in haplotypes Args: `haplotypes`: It's a list of `Haplotype` """ boundary = 1 regions = set() for h in haplotypes: # Loop all the haplotypes in this block if h.variants: for v in h.variant...
1d4938b12fcf58af2919fff56578ad729e6f941d
624,379
def slice_doubles(doubles): """Get the heads and relations from a matrix of doubles.""" return ( doubles[:, 0:1], # heads doubles[:, 1:2], # relations )
35ffcc48382f78c9c547eb49fcde19413d2a9f5b
624,380
import copy def tuple_to_string(tuptup): """ Converts a tuple to its string representation. Uses different separators (';', '/', '|') for different depths of the representation. Parameters ---------- tuptup : list Tuple to convert to its string representation. Returns ------- ...
a11fa135e5e001b57c6c4c0255de6e3896e97048
624,381
import torch from typing import Dict def update_lr(lr_scheduler: torch.optim.lr_scheduler._LRScheduler) -> Dict[str, float]: """ Update lr scheduler and returns the current learning rate as a summary - Parameters: - lr_scheduler: A `torch.optim.lr_scheduler._LRScheduler` to update - Returns: ...
1b8bae8f88a9f4b1044485251b87661bfef6bfb9
624,382
import random def roll(times=0,sides=0): """simulate a die roll with arguments times,sides and return a list with roll results""" try: if times <= 100 and sides <= 100_000: result_list = [] for i in range(times): result_list.append(random.randint(1,sides)) ...
6554e505184e516a93643e181476e20652c084a6
624,383
def get_positions(peptide, proteins, proteins_dic): """ Get a string of peptide positions. Parameters: peptide: str, peptide proteins: str,proteins sep by ; proteins_dic: dict, <protein>:<sequence> """ return ";".join( [str(proteins_dic[protein_i].index(peptide) + 1) for protein...
14ec480798cd77125c4e9f26e34723acd6a4a7c0
624,385
import json def format(data): """ Converts a dict to a string of space-delimited key=val pairs """ return json.dumps(data, separators=(',', ':'))
00c3d1654bd16cbda33ba5e0b547bda6aac1a5c8
624,386
from typing import List import torch def _pad(tokenized: List[torch.Tensor], value: int) -> torch.Tensor: """Utility function that pads batches to the same length.""" batch_size = len(tokenized) max_len = max(len(t) for t in tokenized) output = torch.zeros((batch_size, max_len), dtype=tokenized[0].dty...
9f495cd5bd779f24521081b0ad7fa67557eb82a0
624,387
def extractIniParam(iniparams, inStr): """ if inStr starts with $ then we return matching param from the ini params, otherwise return taskval Params: iniparams - the map of parameters derived from the ini file inStr - input string """ taskval = inStr if inStr.startswith('...
8d615b9312c27fb38f8fd3280c404377f6cb55eb
624,388
def compose_submit_url(contest: str, contest_no: int) -> str: """ 与えられたコンテスト名、コンテスト番号から 提出先のURLを生成する Parameters ---------- contest : str コンテスト名. ABC, ARC or AGC contest_no : int コンテスト番号 Returns ---------- url : str 対応する提出先のURL """ host = 'https:/...
00389ba253aa4094cb4995adc58b9c3b0f40250f
624,389
def cap_at_n(lines, n=2000): """ Takes in a list of strings and joins them with `\n`, but no more than n characters. The Discord message character limit is 2000. """ text = "" for line in lines: if len(text) + len(line) + 1 < n - 3: text += line + "\n" else: text += "..."...
0203fc5acff6da3be6a8ee5ac7b0a3d7c2d02e0d
624,390
def simplification(postfixExpr, operand): """ 对输入表达式判断以及分类 :param postfixExpr:输入的表达式 :param operand:生成的操作数列表 :param operateSymbol:操作符列表 :return:处理后的表达式列表 """ tokenLists = [] operateSymbol_list = ['+', '-', '*', '/', '(', ')'] for i in list(postfixExpr): if i in operand or...
a94d072108ce0b007df913eeb4c6651b9cfe4564
624,391
import random def improved_evaluation_function(game_state, agent, **context): """ This simple evaluation functions improves the basic one by adding some randomness when choosing among non final states. In some cases this evaluation function behaves better than the basic one since it can block oppo...
a5f1b8007a018fcbe83c10a126c42d4d4fabb74e
624,392
def str_to_bool(value): """ Convert a human readable string into a boolean. """ valuestr = str(value).lower() if valuestr in ['1', 'yes', 'enable', 'true']: return True elif valuestr in ['0', 'no', 'disable', 'false']: return False else: raise Exception("Unable to con...
d5de50a562aee6fbfc02a852b9642010598e05a9
624,393
import uuid def generate_uuid(class_name: str, identifier: str, test: str = 'teststrong') -> str: """ Generate a uuid based on an identifier :param identifier: characters used to generate the uuid :type identifier: str, required :param class_name: classname of the object to create a...
223b9b80fcd3579db2846c6d3c79394aef7d5612
624,394
from typing import Type def isnestedclass(cls: Type, scope: Type) -> bool: """Returns true, if the given class ``cls`` is a member on an outer class ``scope``.""" for mroClass in scope.mro(): for memberName in mroClass.__dict__: member = getattr(mroClass, memberName) if isinstance(member, Type): if cls ...
0233013f446e7e16b751947b7ab57d5b1e7e0254
624,395
import re def get_coll_size(s, fname, username): """ Determines a size of downloadable collection. Needed for progress bar. """ chk_size_url = 'https://infoproducts.alcatel-lucent.com/aces/cgi-bin/chk_col_done.pl' params = {'remote_user': username, 'col_name': fname} resp = s...
60a49a176cf540c395a6e151f9887655575e7e7f
624,396
def midPoint(pointA,pointB): """ Input : two points A,B. Output : Midpoint of these two points """ X = int(pointA.x+pointB.x)/2 Y = int(pointA.y+pointB.y)/2 return (X,Y)
402fbd8fe95e4ff42f2aacd57ed8a9ed41c1be8d
624,397
def _throw_exception(exception: Exception): """Returns a function pointer for a function throwing an arbitrary exception""" def _throw(*args, **kwargs): raise exception return _throw
53ce9c1edb2d6101fe2fa99fad9963eca576c086
624,398
def sphere_pad(image, pad=(0, 0, 0, 0)): """ Pad equirectangular projected spherical image for 2D convolution """ assert 0 <= pad[0] <= image.size(3) and 0 <= pad[1] <= image.size(3) and 0 <= pad[2] <= image.size(2) and 0 <= pad[3] <= image.size(2) size = list(image.size()) size[3] = size[3] + p...
a9b175fd4aaae16d3341225aa36b4f63486c122a
624,399
def summation(lower, upper): """returns the sum of the numbers from lower through upper""" #!base case if lower > upper: return 0 #!recursive case return lower + summation(lower + 1, upper)
54ff82089e8f422ade4fa7e384c50cce37ab635b
624,400
def disappear_round_brackets(text): """ :param text: :return: >>> disappear_round_brackets("trib(unus) mil(itum) leg(ionis) III") 'tribunus militum legionis III' """ text = text.replace("(", "") return text.replace(")", "")
a1ce14bfb3d5434c12dd06915efeac3d063d29be
624,401
import numpy as np def tensor_scalar_product(sc, g1): """ :param sc: scalar :param g1: 3 * 3 tensor :return: product between the tensor and the scalar """ # we define the scalar and the tensor as complex sc = np.array(sc, dtype=np.complex128) g1 = np.array(g1, dtype=np.complex128) ...
36832cadc1cda2dba4e4dc3eef14d9e75c923552
624,402
def get_recommended_modification(simple_order, impact): """ Generate a recommendation string from an operator and the type of impact :param simple_order: simplified operator :param impact: whether the change has positive or negative impact :return: formatted recommendation string """ bigger_...
4f23de8adfdae94a1bb609e7b6eb5dcf81388bd0
624,403
def blah3(): """ silly method 2 .. versionadded:: 0.17 Returns ---------- ding: int """ ding =0 return ding
aa8aa0bb3da291049e146c0171b38b8f214f97f3
624,405
def grb_rate_wp(z, z_inhom=0.): """Returns the rate of Gamma-Ray Burst, per comoving volume, evaluated at the specified redshift. Ref: Wanderman, Piran: Mon.Not.Roy.Astron.Soc.406:1944-1958,2010 Args: z (float): redshift z_inhom (float): redshift where the universe becomes inhomogenous...
cd6b809953448cde9596c1cf3a695216a316b2b5
624,406
import subprocess def make_png_thumbnail_for_instance(filepath, max_dimension): """Abstract function for making a thumbnail for a PDF See helper functions below for how to use this in a simple way. :param filepath: The attr where the PDF is located on the item :param max_dimension: The longest you w...
2b807ff7f80181a43f23cb406c9f8727e7733d0d
624,407
def remove_invalid_char(obj): """去除字符串中无效字符 input: str out: str """ vaild_char = [char for char in obj if char.isidentifier()] return ''.join(vaild_char)
295a09f0ff59b3fcf4686b6da2d3c9c6da923aa9
624,408
import functools def rgetattr(obj, attr, *args): """Get attr that handles dots in attr name.""" def _getattr(obj, attr): return getattr(obj, attr, *args) return functools.reduce(_getattr, [obj] + attr.split('.'))
44d098ed472c1b5884dd11bad5f94c9b459be351
624,409
def _dn2partition_id(dn): # pylint: disable=invalid-name """Converts cell partition dn to full id.""" parts = dn.split(',') partition = parts.pop(0).split('=')[1] cell = parts.pop(0).split('=')[1] return (cell, partition)
ef69f396ef5fd9bb57bc79a881b9f311b666b152
624,410
import os def getOFMDsFromFile(fileName): """ Takes in a raw MVC/H264 file, collects the OFMDs from it to a list. """ blockSize = (1024 * 1024) * 1 OFMDs = [] with open(fileName, 'rb') as f: while True: keepgoing = True piece = f.read(blockSize) ...
143bec4c80d7e2c70f96e0b30898afb45923f9b1
624,411
import sys def chooseKeyAndGetInfo(possibleKey, dic): """ Return all possible hintInfo and chosen key """ if not possibleKey: print(" **** This key does not exist **** ") sys.exit(0) if len(possibleKey) == 1: return (dic[possibleKey[0]], possibleKey[0]) else: ch...
323c5fd50521e04045eaf40858e58529318f78a4
624,412
import hmac def calculate_message_signature(key: str, msg: str): """ calculate a message signature using a SHA1 HMAC :param key: the secret token :param msg: the message :return: the calculated HMAC """ return hmac.new(key.encode(), msg=msg.encode(), digestmod='sha1').hexdigest()
d38ca1d4c219cc3e3e47b87c0ad71e4921f63e93
624,413
from typing import List def calculate_pages(page_range_string) -> List[int]: """ Calculate a list of pages from the ranges given as CLI parameter page-range. :param page_range_string: CLI parameter page-range :return: list of pages in given range """ page_ranges = page_range_string.split(',')...
7dcc0c297ce065efe5caa689cf4b8eb9b17d55c7
624,414
def has_permission(user): """Check permission for Inline Editing """ return user.is_staff and user.is_active
af9a47c9440aa04bc1a3a4aeb87e465ca858156e
624,415
from typing import List def _median_even(xs: List[float]) -> float: """returns the mean of the two middle elements""" sorted_xs = sorted(xs) upper_middle = len(xs) // 2 return (sorted_xs[upper_middle - 1] + sorted_xs[upper_middle]) / 2
232a9bf17aec55178356d7d1956bedd87791d5e7
624,416
def render_response_v1(response, version=2): """ Renders a response into version 1 compatible format response: a dict to convert version: the version of the response """ if version == 2: status = response.get("status") data = response.get("message...
b8d74e7fecdb25ec3e1f2ebe6051b0fe07107051
624,417
def stringXor(a, b): """ Calculates the bitwise xor for every value of the arrays. The arrays need to be equally long :param a: The first array :param b: The second array :return: The calculated result """ if len(a) != len(b): raise Exception("stringXor: the two arrays must have...
a5d86a8821b6143e02a0d64d7d269e04c5c3069d
624,418
def strip_trailing_nl(s): """If s ends with a newline, drop it; else return s intact""" return s[:-1] if s.endswith('\n') else s
c408b7fd409d5706e22aceb1072792224245e280
624,419
import functools def validate_context(func): """Validate context in the preprocessor.""" @functools.wraps(func) def transform_wrapper(self, *args, **kwargs): if not self.context: raise ValueError('Please call `fit` before calling `transform`.') return func(self, *args, **kwarg...
d5599eb8abedb770b3780e6ecfb1225b42311062
624,420