content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import hashlib def get_sign(data_dict, key): """ 签名函数 :param data_dict: 需要签名的参数,格式为字典 :param key: 密钥 ,即上面的API_KEY :return: 字符串 """ params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False) # 参数字典倒排序为列表 params_str = "&".join(u"{}={}".format(k, v) for k, v in params_lis...
ea7ee65cd3ae72e19293dc851255bc0f3ad4b321
29,100
def string(): """String representation.""" return "{:s}".format('something')
d13ae4fe229f767c515b0f0d6439ac61c6bfdbe8
29,101
def find_films_in_location(films: pd.DataFrame) -> pd.DataFrame: """finds films filmed in certain location Args: films (pd.DataFrame): films with their locations Returns: pd.DataFrame: films which were filmed in certain location """ films.dropna(inplace=True) # change for more ...
91801357aab19e2a263951907fe74f114b833f68
29,102
from typing import Any import yaml import os def get_saved_schemas() -> Any: """Lists file and display names of all saved schemas. File extensions are stripped, and the names are sorted. Returns: A JSON response. """ schema_paths = sorted(p for p in SCHEMA_DIR.glob("*.yaml")) display...
f7fe9dbac9975bc7d8223dc9fade317c4e17005c
29,103
def _if_installed(pname): """Run if the given program name is installed. """ def argcatcher(func): def decorator(*args, **kwargs): envs = [x for x in args if hasattr(x, "system_install")] env = envs[0] if envs else None if shared.which(pname, env): ...
63eb3a0a3c2b2b6c7370ee4db449e6e3e1d2c84e
29,104
def check_gym_environments(env: gym.Env) -> None: """Checking for common errors in gym environments. Args: env: Environment to be checked. Warning: If env has no attribute spec with a sub attribute, max_episode_steps. Raises: AttributeError: If env has no observati...
95d3a3b7804981cb8308269580359111b257eefe
29,105
def WI(bands: dict) -> xr.DataArray: """ Water Index (2015): Fisher et al. (2016) Args: bands (dict): Bands as {band_name: xr.DataArray} Returns: xr.DataArray: Computed index """ return ( 1.7204 + 171 * bands[obn.GREEN] + 3 * bands[obn.RED] - 70 ...
400c7277d5d7cca07df7953b0db957f3d4fdfd0a
29,106
import io def readZipData(filePath): """ Opening the zip file in READ mode and transform scalars.csv to data frame :param filePath: path to zip-file :return: data frame with scalars.csv content """ with ZipFile(filePath.as_posix(), 'r') as zip: scalars = None for i in zip.namel...
2efd90426366754454f13a8c5e9e61ed2a1c150d
29,107
def calc_relative_scale(skeleton, ref_bone_lengths, joint_tree) -> (float, float): """Calculate the factor by which the reference is larger than the query skeleton. Args: skeleton (torch.DoubleTensor): The query skeleton. ref_bone_lengths (torch.DoubleTensor): The reference skeleton bone length...
cf1bbf2692666e393eb50eeb4ae9d0724af78c7f
29,108
def vertical_move(t, v_speed=2/320): """Probe moves vertically at v_speed [cm/s]""" return 0.*t, 0*t, v_speed*t
eb6a066bf6b6659728647c78dd7673a3d45b250d
29,109
def get_favored_peaks(rama_key): """ returns exact favored peaks with their score value """ assert rama_key in range(6) if rama_key == RAMA_GENERAL: return [((-115.0, 131.0), 0.57068), ((-63.0, -43.0), 1.0), ((53.0, 43.0), 0.323004), ((53.0, -127.0), 0.0246619)] if r...
79bf814becbbf36796e229f69d0a99cd8ef1716e
29,110
def get_all_tablespace_acls(conn): """ Returns: List of :class:`~.types.RelationInfo` objects. """ return [RelationInfo(**row) for row in conn.execute(_pg_tablespace_stmt)]
561514b7986d374ba1dc7a4addf4d0588b53e59b
29,111
import regex def chunk_pars(content): """Given the context contained between `\\beginnumbering` and `\\endnumbering`, return list of paragraphs. This is able to handle paragraphs demarcated by `\\pstart` and `\\pend` as well as when `\\autopar` is used (see §5.2.2 of the reledmac documentation). ...
958890791c67c90a9ed3264e82caca9bfebb5885
29,112
def bound(): """ Generate boundary for testing""" bound = data.Boundary() bound.degree = 3 bound.start = np.array([0.0, 0.0, 0.0]) bound.end = np.array([1.0, 0.0, 0.0]) bound.num_ctrlpts = 5 return bound
210636e3e0618ff8b5ffd48b48f4aa035a38e928
29,113
from typing import Union def to_tensor(pic: Union[Image, np.ndarray]) -> Tensor: """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.""" if not (F_pil._is_pil_image(pic) or _is_numpy(pic)): raise TypeError(f"input pic should be PIL image or numpy.ndarray, Got {type(pic)}") if _is_numpy(pic) ...
26040d594cee200200945d7561bc9e6bcda95f01
29,114
import numpy def dummy_image(): """Create a dummy image""" x = numpy.linspace(-1.5, 1.5, 1024) xv, yv = numpy.meshgrid(x, x) signal = numpy.exp(- (xv ** 2 / 0.15 ** 2 + yv ** 2 / 0.25 ** 2)) # add noise signal += 0.3 * numpy.random.random(size=signal.shape) return signal
8cbf5f31cde69b8ac775114277cee8f88d6dd932
29,115
import os def GetPicList(basedir): """ base_dir -> batch1 -> we -> want -> these -> images -> batch2 """ filename = '' for name in os.listdir(basedir): if not name.startswith('.'): filename = name bre...
de671e7f336e59999f89dd8f3ead2d4bfb059907
29,116
def text_coloured_errors(tree, gold=None, depth=0, single_line=False, missing=None, extra=None, compressed=True, POS=True): """Pretty print, with errors marked using colour. 'missing' should contain tuples (or be None): (start, end, label, crossing-T/F) """ # TODO: Add the ability to compress the s...
4eb7555ade29b478c2d526be0d84a5a68047a1ee
29,117
def update_user(uid, **kwargs): """Updates an existing user account with the specified properties. Args: uid: A user ID string. kwargs: A series of keyword arguments (optional). Keyword Args: display_name: The user's display name (optional). Can be removed by explicitly passing ...
0b52b7e42f286861b43e6e2e25a9547b1cd354d7
29,118
def add_center_dist(nusc: NuScenes, eval_boxes: EvalBoxes): """ Adds the cylindrical (xy) center distance from ego vehicle to each box. :param nusc: The NuScenes instance. :param eval_boxes: A set of boxes, either GT or predictions. :return: eval_boxes augmented with center dista...
5a0c09f9de689efe294a6ce500ba4dbf09885149
29,119
def check_address(btc_addr, network='test'): """ Checks if a given string is a Bitcoin address for a given network (or at least if it is formatted as if it is). :param btc_addr: Bitcoin address to be checked. :rtype: hex str :param network: Network to be checked (either mainnet or testnet). :type n...
9f236f5d6ccf2f28944c577e2ce8fbfb2c2a58b8
29,120
import time def format_time(record): """Format time to ISO 8601. https://en.wikipedia.org/wiki/ISO_8601 """ utc_time = time.gmtime(record.created) time_string = time.strftime('%Y-%m-%d %H:%M:%S', utc_time) return '%s.%03dZ' % (time_string, record.msecs)
ea07736965711a214a738f5443f68cf02e20fcb2
29,121
def _cb_decode(s, maxsize=8192): """Decode a list of IDs from storage in a cookie. ``s`` is text as encoded by ``_cb_encode``. ``maxsize`` is the maximum size of uncompressed data. ``0`` means no limit. Return a list of text IDs. """ dec = decompressobj() squashed = unquote(s).encode('lati...
bf1239cf33bf83b1163d96641a20e4adc3e83221
29,122
def validate_model(df, fix=False): """ Validates the form of a model dataframe. A model dataframe must look something like this: pos val_A val_C val_G val_T 3 1.1 4.3 -6.19 5.2 4 0.01 3.40 -10.5 5.3 5 0 1.4 10.9 231.0 A 'po...
81c8663934c2ae33318635dd68939cff5652912b
29,123
def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng): """Create `TrainingInstance`s from raw text.""" all_documents = [[]] # Input file format: # (1) One sente...
0274db246e701ac1da78564707c851c9e295a21e
29,124
def cdgmm(A, B, inplace=False): """Complex pointwise multiplication. Complex pointwise multiplication between (batched) tensor A and tensor B. Parameters ---------- A : tensor A is a complex tensor of size (B, C, M, N, 2). B : tensor B is a compl...
c3a65ec03339edd0defe723fc860ff9f54495eda
29,125
def InvocationStartEncKeyVector(builder, numElems): """This method is deprecated. Please switch to Start.""" return StartEncKeyVector(builder, numElems)
c00609da890986ff4cf5c30f246459342b9d60bd
29,126
from functools import reduce def dynamic_partial_sum_product( sum_op, prod_op, factors, eliminate=frozenset(), plate_to_step=dict() ): """ Generalization of the tensor variable elimination algorithm of :func:`funsor.sum_product.partial_sum_product` to handle higer-order markov dimensions in additi...
a08298f1440c212310cc3298629e27743325c9ca
29,127
def range_to_number(interval_str): """Converts "X-Y" -> "X".""" if not '-' in interval_str: return int(interval_str) # If first character is -, X is a negative number if interval_str.startswith('-'): number = '-' + interval_str.split('-')[1] else: number = interval_str.split...
562031503241cc37b1b6df5dd657f2f2d90b79a3
29,128
import warnings def load_wav_file_with_wavio( file_path, sample_rate, mono=True, resample_type="kaiser_best" ): """Load a 24-bit wav audio file as a floating point time series. Significantly faster than load_sound_file.""" wavio_obj = wavio.read(str(file_path)) samples = wavio_obj.data actual...
a1b7896e8ac4b9b5833c3ca25776295deb56839e
29,129
import types def make_proxy_cls( remote_cls: netref.BaseNetref, origin_cls: type, override: type, cls_name: str = None, ): """ Makes a new class type which inherits from <origin_cls> (for isinstance() and issubtype()), takes methods from <override> as-is and proxy all requests for other me...
fa48a656ed4fee4a4d1d44b7b97aad32139e644e
29,130
def as_cidr(cr: CidrRepr) -> Cidr: """ Returns a strict network address expressed as in CIDR form: either a string, expressing the network address as ``"<network number><zeros>/<mask bits>"``, or as a ``Cidr`` object, which is returned unaltered. """ if isinstance(cr, _BaseNetwork): return c...
7d6d40c7269619f6189ea1cee940ed4d33eadb1f
29,131
from vivofoundation import get_triples def get_authorship(authorship_uri): """ Given a URI, return an object that contains the authorship it represents """ authorship = {'authorship_uri':authorship_uri} triples = get_triples(authorship_uri) try: count = len(triples["results"]["bindings...
83a1d6a763e16d43c7c83f65f7f3ad11afd5506e
29,132
def Init(): """ Инициализации важных переменных """ # Получаем список листов, их Id и название spreadsheet = service.spreadsheets().get(spreadsheetId = spreadsheet_id).execute() sheetList = spreadsheet.get('sheets') sheetUsers = sheetList[0]['properties']['sheetId'] sheetSW = sheetList[1]['p...
917f2ec6f5d39260ed89c546695e7cd2839bc7b6
29,133
def Nlam_to_Flam(wave, zeropoint, zp_min=5.0, zp_max=30.0): """ The factor that when multiplied into N_lam converts to F_lam, i.e. S_lam where S_lam \equiv F_lam/N_lam Parameters ---------- wave (`numpy.ndarray`_): Wavelength vector for zeropoint zeropoint (`numpy.ndarray`_): zero...
843560dde9e4ec6d2781e4179ca047d00c5e3abc
29,134
def base64_values_validate(name, description, color_set): """Ensures the string wasn't maliciously fabricated to feed corrupted data into the app, even if the b64 code itself successfully decoded into a valid string.""" if custom_palette_name_validate(name) or custom_palette_description_validate(description...
878a5cdf20bcc380a8e81afc47e40592eb4db030
29,135
def isIndepFromTarget(df, attr, x): """ Determiner si un attr est independant de target :df: dataframe choisit :attr: l'argument choisit a etudier :x: seuil :retourner true si n attr est independant de target """ obs=[[], []] ref=[] for t in df.itertuples(): dic=t._asdict...
7bad7b227f3c7af5413ad9778870c44c7844bf6a
29,136
def read_docs_md(filename, root=None): """ Retrieves an apidoc markdown file to be implemented in swagger_auto_schema :param(str) root: root base dir, settings.BASE_DIR as default :param(str) filename: the filename to be retrieved without the .md file type :return: the content of the md file, None i...
e888e1df91b4154fb9d67f6268da76ab2028f780
29,137
def unrotate(points, posor): """Rotate the matrix of column vectors points according to posor, i.e., from absolute coordinates to camera coordinates""" rot_matrix = calc_rot_matrix(posor) return rot_matrix.I * points
58066c958da982d035792997eaff00bfc573d2d1
29,138
def exp_tail(d, x): """Tail of the exponential series starting at d. Needed in the set sampler. Parameters ---------- d: int x: float Returns ------- float """ result = exp(x) # Subtract the _first _d terms. for i in range(d): result -= (pow(x, i) / factorial(i...
48ac3da79e293451d42c5d55196863e27ed3b3e1
29,139
def check_projects_scores(request, hackathon_id): """ When a judge submits the score, check if all projects in the Hackathon were scored by all the judges in all the categories by comparing the number of objects in HackProjectScore for each projects to the required number of objects. If all project...
edfb52db396a984e10a437a1b6561a3e493d9e0e
29,140
import os def remove_and_create_dir(path): """ System call to rm -rf and then re-create a dir """ dir = os.path.dirname(path) print('attempting to delete ', dir, ' path ', path) if os.path.exists(path): os.system("rm -rf " + path) os.system("mkdir -p " + path) return path
5921e55e799580fdb0a3bfea91b0589f60bdbafc
29,141
import pytz from datetime import datetime def _get_week_comfortband(building, zone, date, interval): """ Gets the whole comfortband from the zone configuration file. Correctly Resamples the data according to interval :param date: The date for which we want to start the week. Timezone aware. :param int...
d94542446f61c5dc5b08f1efbff47fccd81dfee4
29,142
import time import os import shutil def setup_testrun_dir(): """ Sets up a testrun_* directory in the cwd and returns the path to it """ test_run = "testrun_{}".format(int(time.time())) os.mkdir(test_run) this_files_dir = os.path.dirname(os.path.realpath(__file__)) config_templates = os.pa...
f71ca502677ececfa1cec9f97b4a13d9426dce23
29,143
def get_path(obj, path, default=None): """Get the value at any depth of a nested object based on the path described by `path`. If path doesn't exist, `default` is returned. Args: obj (list|dict): Object to process. path (str|list): List or ``.`` delimited string of path describing ...
c72cd428979a3f39214c57346aa345087a0248c7
29,144
def get_label_set_args(): """ Add arguments specific to the "Label Set" experiment. Return ArgParser object. """ cmd = get_general_args() cmd = get_explainer_args(cmd) cmd.add('--in_dir', type=str, default='output/influence_set/') cmd.add('--out_dir', type=str, default='output/label_set...
d08e59452ba7afdd8a478f589366e9ba219abb18
29,145
def literal_label(lit): """ Invent a nice label name for the given literal """ return '{}_{}'.format(lit.function.name, lit.name)
14a22d989ee9f07e00e66d1340b946d385d677fd
29,146
from typing import Optional def key(element: DOMElement) -> Optional[str]: """ Retrieve the key of a particular :class:`.DOMElement` in its parent element, if it can be referred to by a key (i.e. if it its parent element is a :class:`collections.abc.Mapping`). :param element: A DOM element :retur...
f7ac059faa2023f88bad386a3d28e44a44c4259d
29,147
def absolute_reverse(view_name, query_kwargs=None, args=None, kwargs=None): """Like django's `reverse`, except returns an absolute URL. Also add query parameters.""" relative_url = reverse(view_name, kwargs=kwargs) url = website_util.api_v2_url(relative_url, params=query_kwargs) return url
11fc1bdc7be40fbbd462570f70f9fe77a5b4777f
29,148
def convert(chinese): """converts Chinese numbers to int in: string out: string """ numbers = {'零':0, '一':1, '二':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '壹':1, '贰':2, '叁':3, '肆':4, '伍':5, '陆':6, '柒':7, '捌':8, '玖':9, '两':2, '廿':20, '卅':30, '卌':40, '虚':50, '圆':60, '近':70, '枯':80, '无':90} ...
c08b9e01f0981afd09d2d9537ec1e98f2af46c06
29,149
def method_not_raises(UnexpectedException): """A decorator that ensures that the underlying function does not raise the UnexpectedException""" @Decorators.decorator def method_not_raises(target, *args, **kwargs): return not_raises(UnexpectedException, target, *args, **kwargs) return method_not_r...
f5267acedcd7bebec7d0cae998635c03c95e2eb8
29,150
def create_random_data(n_randoms, stomp_map): """Function for creating randomly positioned unknown objects on the considerd geomometry. These is used for normalizing the output PDF and properly estimating the "zero point" of the correlation amplitude. The code returns a spatially searchable quad tree of...
c3c73e358d767e46064400d9b48e99a79b7bcfea
29,151
def _rotate_flag(flag, rotation): """Rotates the square flag by the given number of degrees. Preserves size.""" original_size = flag.size offset = int(((flag.size[0] * (2**0.5)) - flag.size[0]) / 2) flag = flag.resize((int(flag.size[0]*(2**0.5)) + 1,)*2, resample=Image.BICUBIC) flag = flag.rotate(ro...
169a0542ce056eaf8368f81e421bb21a97a4d117
29,152
def mobilenetv1(): """Handler da página inicial do modelo de Mobilenet V1 :return: """ return render_template("mobilenetv1.html")
edf8cb04c715c4ce0d3c70883813fb11d0640a19
29,153
def move(board): """Queries the user to move. Returns false if the user puts in an invalid input or move, returns true if the move was successful""" start_input = input("MOVE WHICH PIECE? ") if not start_input.isdigit(): return False start = int(start_input) if start not in board or board...
3377b4f349c9519eff4ede707d10e08038e9d7fc
29,154
import re def _read_reaction_kinetic_law_from_sbml(reaction, mass_reaction, f_replace, **kwargs): """Read the SBML reaction kinetic law and return it. Warnings -------- This method is intended for internal use only. """ mass_rid = mass_reaction.id sbml_species = ( list(reaction.g...
ea800e5b7ccde7dbc87c11066176f963e0367256
29,155
def _total_probe_count_without_interp(params, probe_counts): """Calculate a total probe count without interpolation. This assumes that params are keys in the datasets of probe_counts. The result of ic._make_total_probe_count_across_datasets_fn should give the same count as this function (if params are...
0973e667dbf1fc3bdf476791cbf709549230f94b
29,156
import os import argparse def existing_file(path): """Checks if a file exists. Returns: str: The path to the file. Raises: argparse.ArgumentTypeError: If a path argument does not exist. """ if not os.path.isfile(path): raise argparse.ArgumentTypeError( 'No su...
64ae432231d71ec98132b7a32be149f9f5a192dd
29,157
from typing import Any import math def make_divisible(x: Any, divisor: int): """Returns x evenly divisible by divisor.""" return math.ceil(x / divisor) * divisor
bfbcfb334777a6c7214f16aa0fadd56906e2b7bc
29,158
import csv import os import tarfile import tempfile import glob import shutil import html import uuid def run(tarfolder,outfolder,typeformat="sbml",choice="2",selenzyme_table="N",filenames=''): """Main function that runs the tool""" print(typeformat) #Initialization scores={} #scores (thermod...
38c036a4acc086d783fc3a1c33bc394fd585c05c
29,159
def one_vehicle_xml(): """Emulates a XML response for 1 vehicle trajectory""" STREAM = b'<INST nbVeh="1" val="2.00"><CREATIONS><CREATION entree="Ext_In" id="1" sortie="Ext_Out" type="VL"/></CREATIONS><SORTIES/><TRAJS><TRAJ abs="25.00" acc="0.00" dst="25.00" id="0" ord="0.00" tron="Zone_001" type="VL" vit="25.00...
792cfb5895fd033c40a4cdbf6e79083c865d0093
29,160
def select_data(all_tetrode_data, index): """ Select tetrode data by trial indices. :param all_tetrode_data: (list of 4d numpy arrays) each of format [trial, 1, neuron + tetrode, time] :param index: (1d numpy array) trial indices :return: (list of 4d numpy arrays) selected subset of tetrode data ...
5a883771ef499e0b82e0d3ac5b86550180760e13
29,161
from datetime import datetime def normalize(ds_train, ds_cv, ds_test): """ Normalization of datasets Parameters ---------- ds_train: Dataset Training set ds_cv: Dataset Cross-validation set ds_test: Dataset Test set Returns ------- norm_train: Dataset ...
ad6731096e1081f3ff764ec055d4d3035a40ecbe
29,162
def generate_sequential(num_users=100, num_items=1000, num_interactions=10000, concentration_parameter=0.1, order=3, random_state=None): """ Generate a dataset of user-item interactions where ...
1a9a23fda9c17d5b7085d860986aab78368a4408
29,163
def expand(fluid, pfinal, eta): """Adiabatically expand a fluid to pressure pfinal, using a turbine with isentropic efficiency eta.""" h0 = fluid.enthalpy_mass() s0 = fluid.entropy_mass() fluid.set(S = s0, P = pfinal) h1s = fluid.enthalpy_mass() isentropic_work = h0 - h1s actual_work = i...
acf8cd63684ccf3c41c38cc631d66b4bc143c5c6
29,164
def ADOSC( frame, fast=3, slow=10, high_col="high", low_col="low", close_col="close", vol_col="Volume", ): """Chaikin A/D oscillator""" return _frame_to_series( frame, [high_col, low_col, close_col, vol_col], talib.ADOSC, fast, slow )
61b4959407d68fce2023a135253e02aa7e3428fc
29,165
def op_scr( gep: pd.DataFrame, gross_tp: pd.DataFrame, ul_exp: float, bscr: float ): """ SCR Op Risk module Inputs: - Gross EP last 12m and 12m prior - Gross TP: BEL should be positive - BSCR """ op_premiums = 0.04 * (gep.at['life_all', 'gep_last12m'] - ...
fc1455e5ad7d4da92068b18b80a0ce929b5a9a50
29,166
def parse_voyager_sclk(sclk, planet=None): """Convert a Voyager clock string (FDS) to a numeric value. Typically, a partition number is not specified for FDS counts. However, if it is, it must be compatible with the planetary flyby. The partition number is 2 for Jupiter and Saturn, 3 for Uranus, and 4 ...
237695d43fe17af4f1d7fb704c01ab925099e663
29,167
def format_url(url): """ Formats url by adding 'http://' if necessary and deleting 'www.' :param url: ulr to article or domain :return: formatted url e.g. the following urls: 'http://www.google.pl/', 'google.pl/', 'google.pl/', 'www.google.pl/', 'http://google.pl/...
a9d99b3ad73efb2d79931e9f0d75b1ea557fc6f4
29,168
def append(arr, values, axis=None): """Append to the end of an array along axis (ravel first if None) """ arr = asanyarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axi...
9654f761bd7437840e355abc7b881e3dbe6dd260
29,169
def volo_d4_448(pretrained=False, **kwargs): """ VOLO-D4 model, Params: 193M """ model_args = dict(layers=(8, 8, 16, 4), embed_dims=(384, 768, 768, 768), num_heads=(12, 16, 16, 16), **kwargs) model = _create_volo('volo_d4_448', pretrained=pretrained, **model_args) return model
c7e51cf1af050d79d5c31ef1b7aa107d6eac9c27
29,170
from functools import reduce def rec_hasattr(obj, attr): """ Recursive hasattr. :param obj: The top-level object to check for attributes on :param attr: Dot delimited attribute name Example:: rec_hasattr(obj, 'a.b.c') """ try: ...
b1a9b12f54abb93202a5b41c950f761986307170
29,171
def find_svos(tokens): """ Extracts all the subject-verb objects in a list of tokens. :param tokens: the parsed list. :return: a list of the subject verb objects. """ svos = [] verbs = [tok for tok in tokens if tok.pos_ == "VERB" and tok.dep_ != "aux"] for verb in verbs: subs, ve...
1ece330f828dcf54d1a010127b583327b24aa682
29,172
def def_axiom(arg1): """ def-axiom rule prove propositional tautologies axioms. for reason that prove need propositional logic decision procedure, currently use proofterm.sorry """ # Ts = analyze_type(arg1) # if IntType in Ts: # pt = refl(arg1).on_rhs( # top_conv(rewr_con...
ccf2b1a4ca57a96a09772d1f17c11ba345e62a31
29,173
def not_shiptoast_check(self, message): """Checks whether the message object is not in a shiptoast chat.""" if (message.channel.id in self.settings["shiptoast"]) or (message.channel.name in self.settings["shiptoast"]): return False else: return True
b951ee6be9d9173065f340eda08e997b83964fe4
29,174
def jaccard_distance_loss(y_true, y_pred, smooth=100): """ Jaccard = (|X & Y|)/ (|X|+ |Y| - |X & Y|) = sum(|A*B|)/(sum(|A|)+sum(|B|)-sum(|A*B|)) """ intersection = tf.reduce_sum(tf.math.abs(y_true * y_pred), axis=-1) sum_ = tf.reduce_sum(tf.math.abs(y_true) + tf.math.abs(y_pred), axis=-1...
3ed1236856bc911210f19882a03c107f82450996
29,175
def DiscoverConnect(sources, target_attributes, allowed_links, chain_attribute, chain_filters, link_type, max_length, connect_function = None, debug = None): """ sources - ModelList of elements to start from target_attributes - list of attributes (pairs) to detect target attributes allowed_links - list of attribute...
24f73e65852349e32253b6cb73b26fe1c8efeea8
29,176
def unshare_document(token, docid, userid): """ Unshares a document from another user. :param token: The user JWT token. :type token: str :param docid: The DocID of the document. :type docid: str :param userid: The UserID of the user to be unshared fr...
c79479d93ee687dece0d60137d8837a17c306fca
29,177
import copy import torch def AlterNChannels(layer2alter_id, new_n_channels, old_model): """ Function to increase number of channels Args: layer2alter_id: layer to change new_n_channels: number of channels for the altered layer old_model: model before mutation Returns: ...
a6e02739eddd5c1de572f303b580bcd9c72a272a
29,178
def generate_bins(bins, values=None): """Compute bin edges for numpy.histogram based on values and a requested bin parameters Unlike `range`, the largest value is included within the range of the last, largest value, so generate_bins(N) with produce a sequence with length N+1 Arguments: bins (...
2d448746658193b8dd6c3ac3ef27418b37116a93
29,179
def makeRollAnswerStr( roll_res, mention_str ): """Formats an answer string depending on the roll result. If provided with an invalid roll result, returns 'None'.""" answer = None if roll_res == None: answer = "Invalid dice expression !" elif len(roll_res)==2: #either threshold or success ro...
940f43b5592ff0da6d941bcb13b100c8fb2a590e
29,180
import math def ECSPower(min, max, size): """ on modélise l'eau du réseau comme une fonction sinusoidale de période annuelle cette fonction est complètement calée sur un fichier météo qui commence au 1er janvier mais qui peut être pluriannuel min : température minimale d'injection de l'eau d...
c8f2422bfc066fc2e87caa3d2d87b07d0f1e4335
29,181
from typing import Dict from typing import Any def __create_notification(title: str, content: str) -> Dict[str, Any]: """ Creates a notification "object" from the given title and content. :params title: The title of the notification. :params content: The content of the notification. :returns A di...
484abcc2afcb8f726811e36516572bc5c302a415
29,182
def readme(): """Read and patch README.""" readme_text = read('README.rst') # PyPI does not accept :class: references. return readme_text.replace(':class:`base64io.Base64IO`', '``base64io.Base64IO``')
bad97b377022ec15e0dc0c0c3bcb984924dce216
29,183
def generator_dcgan(noise_dim, img_source_dim,img_dest_dim, bn_mode,deterministic,pureGAN,inject_noise,wd, model_name="generator_dcgan"): """DCGAN generator based on Upsampling and Conv2D Args: noise_dim: Dimension of the noise input img_dim: dimension of the image output bn_mode: keras...
9d8d481fc9688b30fd3b9ffdb5914a61291b56b7
29,184
import sys def get_ironic_client(): """Get Ironic client instance.""" kwargs = {'os_password': CONF.ironic.os_password, 'os_username': CONF.ironic.os_username, 'os_tenant_name': CONF.ironic.os_tenant_name, 'os_auth_url': CONF.ironic.os_auth_url, 'os_endp...
061a47b9c2b3d13d8e874b6d905784120c36ac1f
29,185
def emg21(peak_index, x_pos, amp, init_pars=pars_dict, vary_shape_pars=True, index_first_peak=None): """ Hyper-EMG(2,1) lmfit model (single-peak fit model with two exponential tails on the left and one exponential tail on the right) Parameters ---------- peak_index : int Inde...
9e35deb35806aa1da1c70080a0eb0e5af022fe53
29,186
def _wait_and_retry(provider, job_id, poll_interval, retries, job_descriptor, summary): """Wait for job and retry any tasks that fail. Stops retrying an individual task when: it succeeds, is canceled, or has been retried "retries" times. This function exits when there are no tasks running ...
fc0f78d1ceb9d4d26dbf7b92fedc2de33a4ac4e9
29,187
def summarize_2_dual_3(package_list): """ Given list of packages, return counts of (py3-only, dual-support, py2-only) """ py3 = 0 dual = 0 py2 = 0 for pkg in package_list: if pkg['status'] == 'py3-only': py3 += 1 elif pkg['status'] in PY2_STATUSES: dua...
6a863b456a71fd51e1ac2744424a42495413778f
29,188
import os import json def get_invalid_resumes(): """ Loads invalid json resumes for unit tests, returning a list of TestSchemaFile """ folder = os.path.join(RESUME_DIR, 'invalid') return [ TestSchemaFile( invalid_resume_filename, json.load( open(os.path.join...
15cd771b9dade7e9fc723ca5d36afa2b1c9fbb05
29,189
import os import shutil def get_exppath(tag, name=None, override=False, prompt=False, root='~'): """ Specific path for experiments results Parameters ---------- tag: string specific tag for the task you are working on name: string name of the folder contains all the results (NOTE: the nam...
e2c995f855a5d7e776f1b87015ff18ed9e725a5b
29,190
def isPTSF(p, T=[]): """ >>> from common.production import Production >>> p = Production(['A'], [['\\"a\\"', '\\"b\\"'],['\\"cde\\"']]) >>> isPTSF(p) True >>> p = Production(['A'], [['\\"a\\"', '\\"b\\"'],['\\"cde\\"']]) >>> isPTSF(p, ['a', 'b', 'c', 'd', 'e']) True >>> p = Product...
13f1ed36bb93035490fde33dad3840fe8b98c263
29,191
def new_getvalue( state, name, p): """ Called every time a node value is used in an expression. It will override the value for the current step only. Returns random values for the node states """ global TARGETS value = util.default_get_value( state, name, p ) if name in TARGETS: ...
30b6abacaf478936663b94c45fc2bb3951706299
29,192
import os import csv def csv_find(filein, data): """Finds and returns the row number of the element given, in a CSV file.""" if not os.path.isfile(filein): return(-1) with open(filein, 'rt') as fi: reader = csv.reader(fi, delimiter=',') for row in reader: hashout = row[...
524e006720ebe3043fbfe539c45e42d19b77250b
29,193
def informe_ministerios(): """ Listado de personas """ check_edit_or_admin() roles = db.session.query(Rol).filter(Rol.tipo_rol == 'M')\ .join(relacion_miembros_roles, relacion_miembros_roles.c.id_rol == ...
3dddb4756a092faaa8b6f191f93e22787fb7e38d
29,194
def merge_regions_and_departments(regions, departments): """Merge regions and departments in one DataFrame. The columns in the final DataFrame should be: ['code_reg', 'name_reg', 'code_dep', 'name_dep'] """ return pd.merge(left=regions[["code", "name"]], right=departments[['regi...
0852df4d8ace31a74397ad88140336dbdf9488d2
29,195
import json def updateResourceJsons(swagger,examplesDict,dirName): """ Update the Resource JSON file to include examples in other folder """ try: # Iterate through all resources in the output folder for id in range(len(swagger['tags'])): resourceName = swagger['tags'][id]['...
3d9a7a31e3875bb7c56d8dfbd26ca5b73039101b
29,196
def sign(x): """Sign function. :return -1 if x < 0, else return 1 """ if x < 0: return -1 else: return 1
aae4fcf8fcfafca63593e908c264c08107640ec6
29,197
def set_default_dataseg(*args): """ set_default_dataseg(ds_sel) Set default value of DS register for all segments. @param ds_sel (C++: sel_t) """ return _ida_segregs.set_default_dataseg(*args)
e1f988537cb9eb0518fe5467d07d5487f3f8c440
29,198
def get_sms_history(key: str): """ Get SMS history. :param str key: Authentication key. :return: List of SMSHistoryItems. """ session = get_session(key) url = f"{SITE_BASE_URL}/index.php?page=10&lang=en" response = session.get(url) pages = bs(response.text, "html.parser").find_all...
ed6f4a4a63d90fc91e25baa92179c220783f78b2
29,199