content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def individual_margin_diversity(i, ensemble_proba, target, alpha = 0.2): """ Computes the individual diversity of the classifier wrt. to the ensemble and its contribution to the margin. alpha controls the trade-off between both values. The original paper uses :math:`\\alpha = 0.2` in all experiments and reports...
3d1e2976a383a77c698941883935dc7f89301fa3
66,000
def qr_for_geolocation(**kwargs): """Accepts a *'coordinates'* keyword argument or a triplet *'latitude'*, *'longitude'*, and *'altitude'*.""" return _make_geolocation_qr_code(embedded=True, **kwargs)
712d94b13deec9c6020057c97507f2e24fc7e577
66,001
import requests def update_host(token, current_ip, domain, subdomain='@'): """ Formulate and Execute an Update request on EntryDNS API for a given access token / IP Args: token: (string) Access Token for an EntryDNS Domain current_ip: (string) IP to point EasyDNS Domain to domain:...
ad9b97be6643ecb3662275aeb3dcda14ed08baf6
66,002
def nick_that_sent_message(tags, prefix): """Returns a nick that sent the message based on the given data passed to the callback. """ # 'tags' is a comma-separated list of tags that WeeChat passed to the # callback. It should contain a tag of the following form: nick_XYZ, where # XYZ is the nick...
973121bdf85d4a1c3df8f388f3564c8df5b4fb07
66,003
def Code_encoding(pred): """ Returns 2-D numpy array with codes corresponding to it's type in predict vector 0 column is peninsula cnt 1 column is bay cnt pred: numpy 1-D array with types of puzzles """ code = np.ones((pred.shape[0], 2), dtype=int) for i, typ in enumerate(pred): ...
b7d4e8a0df91363be493881ceb42a27871debcc1
66,004
from typing import Union import pathlib def pathlibify(item: Union[str, pathlib.Path]) -> pathlib.Path: """Converts string 'path' to pathlib.Path object. Args: item (Union[str, pathlib.Path]): either a string summary of a path or a pathlib.Path object. Returns: pathlib.Path o...
cca9d213d47bb5033157887c5e19994020684331
66,005
import torch def get_topk_logits_selector(logits, k=3): """ takes logits[batch, nout, voc_size] and returns a mask with ones at k largest logits """ topk_logit_indices = torch.topk(logits, k=k).indices.cpu() # indices = torch.stack([ # (torch.range(start=0, end=logits.shape[0] * logits.shape[1] * ...
d9b2b83da1856c5d355c22257b3acc4c445f5960
66,006
async def upload_tracks(csv_file: UploadFile = File(...)): """Upload a utf-8 encoded CSV file containing columns (with headings): - `provider` - `license` - `title` - `artist` - `external_url` - `mp3` (as url of audio file in format ffmpeg can read) - `internal_preview_uri` (optional) ...
aa7d9768e97d2b3d5f5566ad1e41d482cebddb66
66,007
def and_(left: ds.Expression, right: ds.Expression) -> ds.Expression: """ Given a left and right expression combined them using the `AND` logical operator Parameters ---------- left : pyarrow._dataset.Expression A Dataset `Expression` to logically `AND` right : pyarrow._dataset.Expressi...
e9ace739045a2c9421ed3bc65b0058ceb83c9225
66,008
from re import T def interp(times, values, fill=0, name=None, **kw): """ Generic interpolation function of t given `times` and `values` Imterpolator such that: f(times[i]) = values[i] if t < times[0] or t > times[-1]: f(t) = fill See ``scipy.interpolate.interp1d`` for details of interp...
e288400d30613ebe66492a4e7751418a7cb66130
66,009
def rename_target(blend_shape, target, new_name): """ Rename the given blendshape target :param blend_shape: str, name of blendshape to rename target from :param target: str, blenshape target to rename :param new_name: str, new name for the blendshpae target :return: str """ check_blend...
c44ad137fe54ad2c88826045985104a685c34982
66,010
from scipy.stats import ks_2samp def p_value_inflation_test(p_values): """ Test for p-value inflation using the Kolmogorov-Smirnov test. However there are no assumptions to fail for this test. :param p_values: array of p-values :return: p-value (significant is bad) """ h_null = np.random....
57ad6124b56e799f1dcd2505392a089e52e1cdcb
66,011
from typing import Dict def templated_supplier(supplier_map: Dict[str, ValueSupplierInterface], engine: RecordProcessor) -> ValueSupplierInterface: """ Creates a supplier that populates the template string from the supplier map Args: supplier_map: map of field name -> value...
9a05242c309a8405b3ca5590609cf45f86fe06da
66,012
def fp_mask_to_list(fp_mask): """Parse a fp_mask, eg 1-4,2,3 or 0x202 Returns fp cpus based on given mask """ if '0x' in fp_mask: fp_cpus = [i for i in range(0, 64) if (1 << i) & int(fp_mask, 16)] else: fp_cpus = [] for rule in fp_mask.split(','): if '-' in rule...
6819495ac608d9e94845581da7567f56aebe51c9
66,013
def get_sub_objects(obj): """Get all the children of an object that were extracted and are BioPaxObjects that need to be registered in the model.""" sub_objs = [] for attr in [a for a in dir(obj) if not a.startswith('__')]: val = getattr(obj, attr) if isinstance(val, BioPaxObject): ...
e76b0dd856e6e9e0abdac7e22adce5ad651ddf3e
66,014
def color_check(origin_color: list, target_color: list) -> bool: """ Function that check if it is the color we're looking for in C.I. Set C.I. properly for handling between accuracy and robustness. """ CI = 20 # Confidential Interval if target_color[0]-CI <= origin_color[0] <= target_color[0]+CI\ and target_col...
4a9e72f10779174eaa409ffb1aa2fe657382ba4a
66,015
def get_obesity_label_bmi(pct, bmi, age, gender): """ Returns the obesity label as underweight, normal, overweight, obese, class I or class II severe obesity """ if 0 <= pct < 0.05: return 'underweight' elif 0.05 <= pct < 0.85: return 'normal' elif 0.85 <= pct < 0.95: ret...
e04ea231b880ac3b20e6dc281d2b5ee0f0bf6d93
66,016
def make_bin_mtx(num_mtx, aa_table): """ Convert a numeric matrix into a binary matrix. Each column of the alignment occupies a submatrix that has as many columns as there are letters in the amino acid alphabet. If we consider an amino acid alphabet of 21 letters (all standard 20 amino acids pl...
e59d0fc187e2a15b646a298594e327f6ceed116b
66,017
import gzip import pickle def read_pickle(filename): """ Helper to read pickle file which may be zipped or not. Args: filename (str): A valid string path. Returns: The file object. """ try: with gzip.open(filename, "rb") as f: loaded_object = pickle.load(f...
3ea50f95713570075f14977591e17bad68ef9d24
66,018
def y0(si): """The initial conditions for y :param si: the simulation info object :type si: SimInfo """ i = 0 end_pg = 1 + si.n_pg end_dg = 1 + si.n_pg + si.n_dg f = np.zeros(shape=(si.n_entries(),), dtype=float) f[i] = 1.0 # power is normalized is 1 for j in range(0, si.n_pg):...
464d90692b405ec388e9a211637d4cc92924e28d
66,019
import os import sys import subprocess def check_environment(): """ Verify the environment contains the top-level tools we need to operate (cmake will check a lot of other things) """ checks_output = [] if not executable_exists(['cmake', '--version']): debug_print_idf_version() ...
56a44469c54350840583577f5e890d04fe4d91a5
66,020
def show_saxs_qmap( img, pargs, width=200, vmin=0.1, vmax=300, logs=True, image_name="", show_colorbar=True, file_name="", show_time=False, save=False, show_pixel=False, aspect=1, save_format="png", cmap="viridis", ): """ Show a SAXS q-map by giving ...
53155ac1b6de4936ce5272ccb7caceed4478e377
66,021
def load_img(path, gs=False): """Load an image and return it as a numpy ndarray""" image = Image.open(path) if gs: #Convert to single-channel greyscale, if desired image = image.convert('LA') width, height = image.size return np.array(image)[0:height, 0:width, 0] return np.array(...
d50869bd3ea7f99f402e7518e8a4907e1d9a4037
66,022
def results(hometeam, awayteam, scores_mat): """ Predict head-to-head score function input: hometeam: name of the home team as string awayteam: name of the away team as string scores_mat: stores the scores output: The result of the game """ #hometeam, awaytea...
364e3731cd79c7c6d820a23ca13427cd1cd12fd6
66,023
def decimate_within_epochs(tsfinname, finname, foutname, dtype, sos, buffer_len=16777216, max_len=None): """Docstring goes here. This is TEMPORARY! Not how Jagular should be used! But we need resultzzz. So, this function takes in a memmapped raw channel (say 15 GB) and an IN...
d7c52ef3d3998b23789ca076c778755c1060228f
66,024
def getManager(libPaths,scriptPath,nodeTypeClassMap={},renderStateFactory=None,viewDebugScriptGraph=False,debugPath=None): """ a utility function to avoid having to make the library and builders for simple cases """ lib=shaderBuilder.Library(libPaths,nodeTypeClassMap) builder=lib.loadScript(scriptPath,viewG...
367c324e7d3374d8783c21e640d1d79e7a337dd1
66,025
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ pw_hash = c['users'].find_one({'username':username}, {'pw_hash':1}) if pw_hash: pw_hash = pw_hash['pw_hash'] if sha512(password).hexdigest() == pw_hash: #TODO salt hashes return True ...
9068f867f8e7bacdb855c969b0bc80ad30e9b29c
66,026
import multiprocessing as mp def gen_new_phiw_div_phib_arr(N_PROCESSES, phiw_div_phib_arr_new, cond_GT, fcn_D, fcn_eta, z_div_L_arr, phiw_div_phib_arr, Pi_div_DLP_arr, weight, gp_arr, gm_arr, yt_arr, phi_yt_arr, ID_yt_arr, Ieta_yt_arr): """ Calculation phi_w/phi_b at the given z using Eq. (D3) in [1] The deta...
304be2f26d1df4414c8cd248fbc2f7d3eaa3217d
66,027
from typing import Counter def getRepeatedList(mapping_argmat, score_mat_size): """ Count the numbers in the mapping dictionary and create lists that contain repeated indices to be used for creating the repeated affinity matrix for fusing the affinity values. """ count_dict = dict(Counter(mapp...
fa2449379bf8bf2051c2492d56de11c2ee0191e4
66,028
def particle_velocity_fields(model, save, space_order): """ Create the particle velocity fields """ if model.grid.dim == 2: x, z = model.space_dimensions stagg_x = x stagg_z = z # Create symbols for forward wavefield, source and receivers vx = TimeFunction(name='v...
c1897347d78423a9c725f7f57f8446ad1a7fbf0d
66,029
import time def _random_fixed_norm_serial(shape, dtype, seed, norm): """ Handles `random_fixed_norm` for `serial=False`. """ if seed is None: seed = int(time.time()) key = jax.random.PRNGKey(seed) matrix = jax.random.normal(key, shape=shape, dtype=dtype) if norm is not None: matrix *= norm / jnp.l...
bf4e6c2dfcef6dc3938c6fc2cb4e8d08a8bbabef
66,030
import torch def model_logprobs(model, collator, input_texts, output_texts, length_penalty=0, batchsize=128): """Computes logprobabilities of input and output texts for a given model Inputs: model: conditional generation model to use collator: collator to process texts input_texts: it...
721ea1b5e7d934d92dbb2ecacef0bc318a25be25
66,031
def extract_arg_list(args: dict, names: list): """Get process argument by list of (legacy/fallback/...) names.""" for name in names: if name in args: return args[name] # TODO: find out process id for proper error message? raise ProcessParameterRequiredException(process='n/a', paramet...
305180a80ab456fcedab8e1f25402b06563a5696
66,032
import os def _read_last_line(filename): """Efficiently read the last line from a file Modified from https://stackoverflow.com/a/54278929 (CC BY-SA 4.0) 24 hours of log at 1 line per sec takes ~1e-3 sec to read """ if not os.path.exists(filename): return None try: with open(fil...
ddfbd541da2329583371ce294f7738d3d828064a
66,033
def no_repeats(n): """Returns number of arrangments with no repeats.""" return sum((-1)**k * comb(n//2, k) * num_pairs(n - 2*k) for k in range(n//2+1))
6af59c4e599cc151b6973eac74611837de93dbb6
66,034
def process(orography, landmask, site_list, metadata_dict=None, all_methods=False, land_constraint=None, minimum_dz=None, search_radius=None, node_limit=None, site_coordinate_system=None, site_x_coordinate=None, site_y_coordinate=None): """Module to create neighbour cubes for ext...
92fd5eb6b5ce7ad7c2facb8bf95c6e0d61a3e38a
66,035
def _get_text_alignment(point1, point2): """Get the horizontal and vertical text alignment keywords for text placed at the end of a line segment from point1 to point2 args: point1 - x,y pair point2 - x,y pair returns: ha - horizontal alignment string va - vertical alignment s...
317860030bf86750207bc891c236ad2618c686b1
66,036
def ldns_rr_list2buffer_str(*args): """LDNS buffer.""" return _ldns.ldns_rr_list2buffer_str(*args)
658912718ede1b21d2238929cfd7e782bf8bf72a
66,037
def param(key, **kwargs): """Decorator for Agent operation functions to assist with checking params prior to actually trying to execute the code. Example:: class MyAgent: ... @param('voltage', type=float) @param('delay', default=0., type=float) @inlineCallbacks de...
910dd83169b86b6f432c24a6c0ad320644aee9f2
66,038
def weights_none(mol): """ Calculates the QED descriptor using unit weights. """ return qed(mol,w=[1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00])
da2cf2f634c13e52a44c804f70d2700f252066eb
66,039
from typing import Set from typing import Tuple def unrecognized_footprints_check(bom_rows: Rows, footprint_index: int) -> str: """Return an error string if unrecognized footprints are detected.""" # Sweep through looking for acceptable vs unacceptable footprints: unrecognized_footprints: Set[str] = set()...
0bd6ae4ba675007f75efefadf75216a52cd94aee
66,040
def sample_on_ellipsoid(numpts, radius=(1.,1.,1.), rot=(0.,0.,0.), trans=(0.,0.,0.)): """Sample points uniformly randomly on the surface of an ellipsoid. Args: - numpts (int): Number of points to sample - radius (tuple, float): radius of each axis (X, Y, Z) of the ellipsoid - rot (np.array): rotation parameter...
58671be659ea646ff3b02859d2a09879de6a27f6
66,041
from typing import Any def avro_mocked_request(data: Any, schema: Any, **kwargs) -> web.Request: """For testng purposes.""" return mocked_request(MinosAvroProtocol.encode(data, schema), content_type="avro/binary", **kwargs)
4cf99dc403c1559968d596804523d0b7fc49b04d
66,042
def MOLT_query(collection): """ Returns a list of the possible MOLT (objects) that contain the collection. Accepts either a list of midi tones, a list of strings, a list of pitch objecs, or a list of note objects. """ # Convert everything to pitch classes. query_collection = set() if all(isinstance(x, int) or i...
ce4040e6701b61f1d468f4274de74986388b3feb
66,043
import json def admin_team_insert(): """ API for inserting a team """ prv_id = None team_id = None prjid = None bgt_id = None teamname = request.form['Name'] div_id = clean_jsgrid_int(request.form['DivisionID']) myids = admindb.AdmIDs(prv_id, team_id, prjid, bgt_id, div_id) retu...
63122cabf8bc6f7d423f70e722ad2ff91aea0ac2
66,044
def wavenumber(f, er=1, ur=1): """Calculate freespace wavenumber of dielectric material (or vacuum). Typically represented by: k Args: f: frequency, in units [Hz] er: relative permittivity ur: relative permeability Returns: np.ndarray: freespace wavenumber, in units [1...
d4fb4d3cf861d6d13308e9d487100465f104c2a1
66,045
import re def getPolyPhen2input(data, filesize=150000): """ Reads data and creates files needed for PolyPhen2 input. Saves and returns file names to be used as input. File size is restricted to 150000. Arguments: data = dataframe containing COSMIC data filesize = int restricting lines ...
811f0290f15e73d28d8a0685a7a360194090a40f
66,046
def load_cell_expression_5platform(ncols=None, scaling='std', add_prefix=True): """Load 5-platform averaged cell line expression data, sub-select columns of gene expression randomly if specificed, scale the selected data and return a pandas dataframe. Parameters ---------- ncols : int o...
fffca39904c1f790de7854631e023e29de667cb3
66,047
def normalize_rectangle(rect): """Normalizes a rectangle so that it is at the origin and 1.0 units long on its longest axis. Input should be of the format (x0, y0, x1, y1). (x0, y0) and (x1, y1) define the lower left and upper right corners of the rectangle, respectively.""" assert len(rect) == 4, '...
b1a011948adb52bb6dea068116ab3a564ab2a1f8
66,048
def flip_joints_3d(joints_3d, width, joint_pairs): """Flip 3d joints. Parameters ---------- joints_3d : numpy.ndarray Joints in shape (num_joints, 3, 2) width : int Image width. joint_pairs : list List of joint pairs. Returns ------- numpy.ndarray Flip...
776057afbd195f1d17375a72cc0225e2e169c1de
66,049
def forward(internal_func, f_x0, params_value, i, h): """Calculate the forward difference. Args: internal_func (func): A function with a 1d numpy array as it's only argument. f_x0 (numpy array): The function value at params_value. params_value (numpy array): The value column of param_df...
6c2270e51904e11553ea3e335225b3308158c29a
66,050
import email def todo_get_mailer(user, task): """A mailer is a (from_address, backend) pair""" task_backend = todo_get_backend(task) if task_backend is None: return (None, mail.get_connection) from_address = getattr(task_backend, "from_address") from_address = email.utils.formataddr((user...
a5f2fe735711826f13815476fb1038e76a228687
66,051
import inspect import warnings def valid_func_args(func, *args): """ Helper function to test that a function's parameters match the desired signature, if not then issue a deprecation warning. """ keys = inspect.signature(func).parameters.keys() if set(args) == set(keys): return True ...
4872817033ea55881442e69711b620b2853407f1
66,052
import pdb def emlines_from_alis_output(alis_file): """ Generate a list of emission lines from a standard ALIS output file Currently loads Parameters ---------- alis_file : str Returns ------- emlines : list List of EmLine objects """ linelist = LineList('Galaxy') ...
971a8267efd7f2acf8f78cde9f119e179be09ecb
66,053
import fileinput import sys import traceback def get_file_stream(encoding): """Get the file stream.""" sys.argv = [] text = [] try: for line in fileinput.input(): text.append(compat.to_unicode(line, encoding)) stream = ''.join(text) except Exception: logger.Log...
1b6200790e803e49dd66bc417ba50d95f453f824
66,054
import re def load_off(filename, verbose=True): """Load 3D model in .off format.""" with open(filename, 'r') as f: obj_file = f.read().splitlines() v = [] # list of vertices f = [] # list of faces e = [] # list of edges num_vertices = None num_faces = None num_edges = None...
df03642b2270e149dc14587dbfa1df0505cad1b5
66,055
def share_get(context, share_id): """Get share by id.""" return IMPL.share_get(context, share_id)
c255a964fbee69c2c2ef402d4e05f4b1e43c9672
66,056
def put_ldap_group_schema_settings( api_client, group_required=None, group_base=None, group_id_attribute=None, group_list_filter=None, group_member_attribute=None, group_member_attr_format=None, group_search_scope=None, **kwargs ): """Put update LDAP group schema settings # noqa...
03b065fe95fa191d35c5904363381fdc3258bb55
66,057
def pp(obj, maxwidth=79): """ Pretty-print the given object. """ ctx = PrettyPrinter(maxwidth=maxwidth) ctx.pp(obj) return str(ctx)
a957f8093be00a04a81c727ee00eb697638b08ac
66,058
from typing import Tuple from typing import Optional import os async def lookup_path(path: str) -> Tuple[str, Optional[os.stat_result]]: """ Get the full path to the requested file and check if it exists :param path: the relative path to the file :return: the absolute path to and stat of the file ...
0b31fe8967df309e5dc966d6d892fa917134534a
66,059
def _get_descriptor(service_name): """Find ServiceDescriptor class by the service name and instanciate it """ service = OTC_SERVICES.get(service_name, None) if service: service_type = service['service_type'] desc_class = _find_service_description_class(service_type) # _logge...
ef27f8d62c2e6ba1c8d20a405dbda9c35f98e864
66,060
def connect(addr, name=None, group=None, blocking=True, header_len=16, cache_size=-1): """ Creates a `HiSockClient` instance. See HiSockClient for more details :param addr: A two-element tuple containing the IP address and the port number of the server. :type addr: tuple :param name: A stri...
8f98cd067a4d70d2ef2c1f292c27f7f4349fbd9c
66,061
def bodypart(actions: Actions) -> Features: """Get the body part used to perform each action. Parameters ---------- actions : Actions The actions of a game. Returns ------- Features The 'bodypart_id' of each action. """ return actions[['bodypart_id']]
bb9e325f608d4ca325d92f7e70973f561657c109
66,062
import shutil def binary_available() -> bool: """Returns True if the GitHub CLI binary (gh) is availabile in $PATH, otherwise returns False. """ return shutil.which("gh") is not None
e959757ccce6d162b225fd6ef986a7e248c606fa
66,063
import copy import six def _config_list(conf_tuples=None, only_net=False, **kwargs): """ Return a list of dicts from the salt level configurations conf_tuples _LXCConfig compatible list of entries which can contain - string line - tuple (lxc config param,value) ...
03a3e472784a132d6d65e480b17ffab77357607a
66,064
def rectify_analysis(notice_xml, dry=False): """ Parses through the analysis section and fixes common problems: - analysisSection with only a title: adds an empty analysisParagraph """ new_xml = deepcopy(notice_xml) notice_analysis = new_xml.find('.//{eregs}analysis') # If there is no noti...
cf9b0f2ce864445126c21e6c6ce1a9785e92c736
66,065
def _get_message(status): """ Given problem status code, return a more detailed message. Parameters ---------- status : int An integer representing the exit status of the optimization:: 0 : Optimization terminated successfully 1 : Iteration limit reached 2 : Prob...
2cf7328fda4cbcabb30c52b0868363e1ad10534a
66,066
import torch def add_k(c, active_k, max_k, gamma): """ replace the cluster indictors of 0 to active_K+1 :param c: a sparse matrix to indicate the cluster membership. :return: a new sparse matrix to indicate the cluster membership. """ indices = c._indices() values = c._values() values...
056acd7fcc7fd050e351a55d98003963bc22d5b5
66,067
def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): """Parse the historical data in file handle fh from yahoo finance. Parameters ---------- adjusted : bool If True (default) replace open, high, low, close prices with their adjusted values. The adjustment is by a scale fact...
1899038f05d486f5af198ae411da11facd94ea8e
66,068
def clean_colnames( df: pd.DataFrame, keep_names=True, attr_name="column_map", ) -> pd.DataFrame: """Dataframe method, that applies :func:`clean_names` dataframe columns.""" return clean_names(df, keep_names=keep_names, attr_name=attr_name)
1a4529239b46d243338762eb675767ab64b3e240
66,069
from typing import Union from typing import Optional from sys import path def _get_map_child( parent: Union[_ProtoChildExpression, _ProtoRootExpression], desc: descriptor.Descriptor, field_name: ProtoFieldName, backing_str_tensor: Optional[tf.Tensor], ) -> Optional[Union[_ProtoLeafExpression, _ProtoCh...
ce697bf1c28c77098642747c4a7f68aaf1a43f66
66,070
def getAllValidSequences(rule): """ Loops over all possible lists of three cards and returns the list of three cards that are accepted by the given rule. Parameters ---------- rule: Tree The rule that we want to find valid cards for Returns ------- goodList: list Li...
0778295231226a44fb802d99ece815b6ffe9fcf7
66,071
def reverse_complement(sequence): """ Return reverse complement of DNA sequence. """ return ''.join(COMPLEMENT[b] for b in sequence[::-1])
4d416804b152c7d538771a8239842cc6acb920cd
66,072
async def async_api_turn_on(hass, config, request, context, entity): """Process a turn on request.""" domain = entity.domain if entity.domain == group.DOMAIN: domain = ha.DOMAIN service = SERVICE_TURN_ON if entity.domain == cover.DOMAIN: service = cover.SERVICE_OPEN_COVER await...
0e33791fde12d7582beed05be2d4adfd0eb004f2
66,073
def ring_float_to_class_int(rings:float, step=0.1): """Ring value rounded to classifier value; rounded to nearest step size""" return round(rings/step)
563f155481592c9924ed61535e07a4d1ff7a1e8e
66,074
def capture(cohesin, occupied, args): """ We are describing CTCF capture here. This function is specific to this particular project, and users are encouraged to write functions like this Note the for-loop over left/right sites below, and using cohesin[side] to get left/right leg. ...
f5d93c05bd0597c4344c4fd6ebc108f5f897d65d
66,075
def vh_u(Xcp,Ycp,Zcp,Gamma,R,h,psih=0,nB=3,bWT=True,method='wrench',bSemi=True,polar_out=True): """ Induced velocity by nB azimuthally dstributed helices INPUTS: - psih : reference azimuthal position of the first helix - bSemi: Semi-infinite helices may be obtained using bSemi=True, but then ...
62a51ed9ef4ac3bc0792b84bac3a974427b13be8
66,076
def action_github(commands, args, repos, data, options=cfg.OPTIONS): """Вывод данных, полученных из функции get_data_for_actions, в файл вашего репозитария на github.com Необходимо заранее сгенерить personal access token (https://github.com/settings/tokens) и прописать его в конфигурационный файл: gith...
1bd781292a664538f58d3c7026d6068440230474
66,077
def submitData(): """ Controller to manage the AJAX import of vulnerability data """ # Get the action to be performed action = request.post_vars.action if action == "vulnerability": return import_vul_ui() elif action == "vulnerability_part1": return import_vul_csv_part1() elif a...
1c8ff6e516d3f2971580bfa188727cb74492cf9d
66,078
async def get_product(product: ProductGinoModel = Depends(get_product)): # noqa: B008 """API for getting a product.""" return product
60ccf32fcb97eb7e0fe0c0b86a6d4204a0584925
66,079
import torch def prep_image(img, img_size=(1088, 608)): """ Prepare image for inputting to the neural network. Returns a Variable """ orig_im = cv2.imread(img) dim = orig_im.shape[1], orig_im.shape[0] img = letterbox_image(orig_im, img_size) img_ = img[:, :, ::-1].transpose((2, 0, 1)...
e65d7f558ac0610133b6f996a118cd40429478fa
66,080
def ifft_flat(ft, tod, nthread=1, axes=[-1], flags=None): """Same workaround as fft_flat but now for the inverse transform.""" shape_tod = tod.shape naxes = np.atleast_1d(axes).size axes_new = list(range(-1, -1 - naxes, -1)) tod = utils.partial_flatten(tod, axes=axes, pos=0) ft = utils.partial_flatten(ft, axes=ax...
b1cc55db92fb818659d816f26b9acf6525c45fee
66,081
def weekday_list_to_hexweek(weekday_list): """ Helper to convert list of integers represending weekdays into speaker's hex representation of weekdays. :param hexweek: List of weekday integers e.g. [0, 1, 2, 3, 4] :returns: Hex string .e.g. 0x3E """ # Mon, Tue, Wed, Thu, Fri, Sat, Sun weekda...
c729dbc134c67c4c71911cbb5c817276583e1503
66,082
def set_markers(board): """ Function creates the lists of the markers to the side of the game board which indicates the number of ship pieces in each row and column. board: list of board tiles returns the 2 lists of markers with number of ship pieces in each row (xmarkers) and column (y...
0302b250a43907db0969d693ac7adbe13c73ca7c
66,083
def makeBdc(bus, branch): """Builds the B matrices and phase shift injections for DC power flow. Returns the B matrices and phase shift injection vectors needed for a DC power flow. The bus real power injections are related to bus voltage angles by:: P = Bbus * Va + PBusinj The real power f...
753daefabe56694b80024648ed7266efcc51c9a0
66,084
def Cx2(c1, c2, q1, q2, kind='std'): """ Helper function to create pulse block for a pair of single-qubit Cliffords """ clifford_fun = clifford_map[kind.upper()] seq1 = clifford_fun(q1, c1) seq2 = clifford_fun(q2, c2) #Create the pulse block return seq1 * seq2
ba39af4789e49e8f545de4c05fe4d952c4a16711
66,085
import sys def value(board, chess_net, depth=0): """ Get the value of the current position denoting likelihood of opposite (-) or current (+) player winning given the current state through the use of an Alpha-Beta pruned tree search with depth = `depth` Parameters ==== :param board: Chess boa...
e05f568a19d8993d72c39711a046b6249b31398c
66,086
def can_create_teams(user, organization): """ Returns a boolean describing whether a user has the ability to create new teams. """ if user.is_superuser: return True if not is_organization_admin(user, organization): return False result = plugins.first('has_perm', user, 'add_...
e4413302714edfeaab3d140790ef6def9680c838
66,087
def article_seen(article_title:str) -> list: """ Description: Function to turn a certain article to seen if the user has clicked the 'x' on a news article. Arguments: article_title {str} : string containing the title of an article the user has pressed 'x' on Returns: article...
822e90707bbe822dc0ad51338c944f9c30c9e6ac
66,088
import hashlib def get_hash(*args) -> str: """ Convert to String all given args Adding SECRET_KEY and hashing it with sha3_256 @param args: Any argument convertible to String @return: String with HEX digest """ hashing_list = [] for arg in args: hashing_list.append(str(arg)) ...
7c9d7f5cff8c3a5e5584653ba31af88b807d5e8d
66,089
from typing import Callable from typing import Iterable from typing import Iterator def map_n(func: Callable[..., _T], /, *iterables: Iterable, max_workers: int | None = None, prefetch: int | None = 2, mp: bool = False, chunksize: int | None = None, ...
a52a3ac0f757fd5c51282586f80e354a53c75c43
66,090
from typing import Set from typing import Type from typing import List def create_approach(name: str, initial_predicates: Set[Predicate], initial_options: Set[ParameterizedOption], types: Set[Type], action_space: Box, train_tasks: List[Task]) -> BaseApproach...
07492255fd5331c0e80dd06793c4644f6c68d1ce
66,091
import torch def validate_adv(val_loader, model, criterion): """ Run evaluation """ losses = AverageMeter() top1 = AverageMeter() # switch to evaluate mode model.eval() for i, (input, target) in enumerate(val_loader): input = input.cuda() target = target.cuda() ...
846a0c7eda2c27d8a22cd0d54f48fadb85fb1fc1
66,092
import torchvision def interpolate( input, size=None, scale_factor=None, mode="nearest", align_corners=None ): """ Equivalent to nn.functional.interpolate, but with support for empty batch sizes. This will eventually be supported natively by PyTorch, and this class can go away. """ return ...
f3b4ed48be73aa4438c2c48ea6e1ffcd9757c3cb
66,093
from typing import Any from typing import Optional def def_sensitivity( *, default: Any = NOTHING, dtype: Optional[Any] = None, description: Optional[str] = None, converter: Optional[callable] = None, validator: Optional[callable] = None, **kwargs, ): """Define a sensitivity attribute ...
4cb92c257913e08022ab6a6b67c2abfa84a958dd
66,094
def is_matched_html(raw): """Return True if all HTML tags are properly match; False otherwise.""" S = ArrayStack() j = raw.find('<') # find first '<' character (if any) while j != -1: k = raw.find('>', j + 1) # find next '>' character if k == -1: ...
ecfe27be92d046097980e36748f26a463a8e1a50
66,095
import warnings def manager_from(*mixins, **kwds): """ Returns a Manager instance with extra methods, also available and chainable on generated querysets. (By George Sakkis, originally posted at http://djangosnippets.org/snippets/2117/) :param mixins: Each ``mixin`` can be either a class or ...
baa145170f073b596769e6bc359a319f209b5ef8
66,096
def create_isolated_mask(pr, gt, label_id, output='fp'): """ Create a mask image by extracting only the isoated objects that are not overlaped by one of the masks. Args: pr ([type]): predicted mask gt ([type]): GT mask output (str, optional): Type of mask to be created. 'fp', 'fn' c...
e015a250f680d5b66e0dd1978b04337f1a0b29a5
66,097
import requests def get_bot_message_by_id(message_id, bot_id): """ This function will get the message content using the {message_id} :param message_id: Webex Teams message_id :param bot_id: the Bot id to validate message :return: message content """ url = WEBEX_TEAMS_URL + '/messages/' + m...
b6ed1e3524983aea43c9b9dac69626f2576a2719
66,098
def extract_indices(idx_to_check, *args): """ Look if a given index j_gt is present in all the other series of indices (_, j) and return the corresponding one for argument idx_check --> gt index to check for correspondences in other method idx_method --> index corresponding to the method idx_gt...
c2de117417689d30d5b9a72f5bae07f12baf72ed
66,099